UX Issue

Users See Each Other's Data: AI Session Mix-Up Nightmare

A copy-pasted auth snippet shared sessions across users; we isolated contexts and sealed the privacy hole.

January 15, 2025 5 min read

The problem

A healthcare portal was showing patients each other's medical records, prescriptions, and test results. Users reported seeing strangers' HIV results, psychiatric evaluations, and social security numbers. The company faced HIPAA violations with fines up to $50,000 per record exposed. 12,000 patient records were compromised. Emergency rooms couldn't trust the system, reverting to paper records.

How AI created this issue

The developer had asked Copilot to implement user authentication. Copilot generated code that stored user data in module-level variables:


// Copilot's authentication implementation
let currentUser = null;
let userSession = {};

// Middleware to load user
app.use(async (req, res, next) => {
  const token = req.headers.authorization;
  if (token) {
    // Copilot stored user in module variable
    currentUser = await getUserFromToken(token);
    userSession = {
      userId: currentUser.id,
      permissions: currentUser.permissions,
      patientData: await loadPatientData(currentUser.id)
    };
  }
  next();
});

// Routes using the global variables
app.get('/api/medical-records', (req, res) => {
  // Returns data from whoever logged in last!
  res.json({
    user: currentUser,
    records: userSession.patientData
  });
});

app.get('/api/prescriptions', (req, res) => {
  // All users see the same person's prescriptions
  const prescriptions = getPrescriptions(userSession.userId);
  res.json(prescriptions);
});

Copilot's code worked perfectly in development with one user. But in production, Node.js runs in a single process - those module-level variables are shared across ALL requests. When User A logged in, currentUser was set to A. When User B logged in milliseconds later, currentUser was overwritten with B. Now User A sees User B's medical records!

The solution

  1. Request-scoped context using AsyncLocalStorage:
    
    // Proper request isolation
    const { AsyncLocalStorage } = require('async_hooks');
    const sessionStorage = new AsyncLocalStorage();
    
    // Middleware creates isolated context per request
    app.use(async (req, res, next) => {
      const token = req.headers.authorization;
      
      if (token) {
        try {
          const user = await getUserFromToken(token);
          
          // Run the rest of the request in isolated context
          sessionStorage.run({
            user,
            requestId: crypto.randomUUID(),
            startTime: Date.now()
          }, () => {
            next();
          });
        } catch (error) {
          return res.status(401).json({ error: 'Invalid token' });
        }
      } else {
        next();
      }
    });
    
    // Safe helper to get current user
    function getCurrentUser() {
      const context = sessionStorage.getStore();
      if (!context || !context.user) {
        throw new Error('No authenticated user in context');
      }
      return context.user;
    }
    
    // Routes now properly isolated
    app.get('/api/medical-records', async (req, res) => {
      try {
        const user = getCurrentUser();
        const records = await getMedicalRecords(user.id);
        
        // Audit log for HIPAA compliance
        await auditLog({
          userId: user.id,
          action: 'VIEW_MEDICAL_RECORDS',
          ip: req.ip,
          timestamp: new Date()
        });
        
        res.json({ records });
      } catch (error) {
        res.status(403).json({ error: 'Access denied' });
      }
    });
  2. Session validation on every request: Never trust client-side data
  3. Comprehensive audit logging: Track every data access for compliance
  4. Penetration testing: Professional security audit of all endpoints
  5. Zero-trust architecture: Verify permissions on every data access

The results

  • Zero data leaks after fix deployment
  • Passed HIPAA security audit with zero findings
  • Avoided $600M in potential fines (12,000 records × $50,000)
  • Trust restored: Hospitals resumed using the system
  • Insurance premium reduced 40% after security improvements
  • 100% request isolation verified through automated testing

The team learned that AI-generated code often uses patterns that work in single-user development but fail catastrophically in multi-user production. They now require security review for all authentication code and use request-scoped storage for all user data. In healthcare, one shared variable can destroy lives.

Ready to fix your codebase?

Let us analyze your application and resolve these issues before they impact your users.

Get Diagnostic Assessment →