Agent traces preview
Language: typescript Framework packs applied by the engine: cookie-options, dom, electron, express, graphql, http-clients, http-response, jquery, node-core, node-http, react-dom, sanitizers, sql-drivers, template-engines Engine handlers: 119 (protected 0, reaching data 0); service functions 3, authorization gates 3; unverified authorization candidates 0. Handlers by directory: packages/sync-server/src (61), packages/sync-server/src/app-simplefin (22), packages/desktop-electron (15), packages/sync-server/src/app-gocardless (10), packages/sync-server/src/app-pluggyai (8), packages/sync-server/src/util (3) BLIND SPOT: the engine sees data access in only 0 of 119 handlers. If this app reaches its database through a layer the engine does not know, teach it (the sinks), or every unit's ranking and guards will be blind too. Pack format for teach(): [pack] name = "app-conventions" language = "python" # or "javascript" (TypeScript too) description = "what this pack teaches" detect = { imports = ["myapp.db"] } # optional: only files importing one of these # A data access the engine does not know (an ORM wrapper / repository): reads are # "resource_select", writes "resource_modify". `call` is the canonical call id # (module.Class.method, as imported); `*` matches within a segment, `**` across. [[sink]] call = ["myapp.db.Repository.get", "myapp.db.Repository.find_*"] kind = "resource_select" [[sink]] call = ["myapp.db.Repository.save", "myapp.db.Repository.delete"] kind = "resource_modify" # A decorator that authenticates / authorizes the handler it wraps. [[auth_gate]] decorator = ["myapp.auth.require_admin", "myapp.auth.login_required"] # The authenticated caller, as the app exposes it (a module-level proxy). [[identity]] proxies = ["myapp.auth.current_user"] Map the application, teach the engine if it is blind, then finish_profile. 1 message 12 tools APPLICATION PROFILE (from the mapping pass): AUTHENTICATION - Session token from req.body.token or header x-actual-token. validateSession() (packages/sync-server/src/util/validate-user.ts:10) looks it up via getSession() in account-db.js:209 and checks expires_at (-1 = never). Invalid/expired -> 401. - validateSessionMiddleware (packages/sync-server/src/util/middlewares.js:38) sets res.locals = session (so res.locals.user_id is the caller). Handlers never get a req.user; they read res.locals.user_id or session.user_id. - Applied per-router: app.use(validateSessionMiddleware) in app-sync.ts:32, app-secrets.js:15, app-gocardless.js:30; per-route in app-admin.js, app-openid.js. app.ts mounts /sync, /account, /gocardless, /simplefin, /pluggyai, /secret, /cors-proxy, /admin, /openid. Verify each mount has the gate: app-account.js and app-simplefin/pluggyai routes and the /cors-proxy catch-all (app-cors-proxy.js:129, app.use('/')) were NOT confirmed as gated in this pass. - Header/proxy auth: validateAuthHeader() (validate-user.ts:44) trusts peer IP against trustedAuthProxies. ACCESS MODEL - Server roles: users.is admin via isAdmin(userId) (account-db.js:135); hasPermission/getUserPermission at 139/219. - Per-file ownership plus sharing: files have an owner; user_access(file_id,user_id) grants shared access (services/user-service.js:157-258, app-sync/services/files-service.js:125-153). - File gate: requireFileAccess(file, userId) (app-sync.ts:72) = owner OR server admin OR user_access row. Used across /sync routes (app-sync.ts lines 123-492) but not every route was read. ENFORCEMENT HELPERS - validateSession / validateSessionMiddleware, isAdmin, requireFileAccess, UserService.countUserAccess, files-service canSeeAll (admin) branch. DATA ACCESS - Single SQLite account DB: getAccountDb() (account-db.js:12) -> openDatabase() in db.js (WrappedDatabase: all/first/exec/mutate/transaction). Per-file data lives in separate file DBs under app-sync/. - Services: services/user-service.js, app-sync/services/files-service.js. Routes: app-*.js and app-sync.ts. ENGINE STATUS / BLIND SPOT - Teach applied (db.WrappedDatabase / getAccountDb sinks, validateSessionMiddleware gate): no change; still 0/53 handlers reaching data in the scanned files. The engine does not resolve the getAccountDb().all/mutate chain, so data-access facts here come from manual reading, not the engine. Treat engine "protected: 0" as unreliable. PRIORITY AUDIT AREAS - Per-route checks in app-admin.js (granted===0 fallbacks), app-sync.ts file rout UNIT: packages/sync-server/src/app-sync.ts (module-level) HANDLERS (a verdict is required for EACH): - boolToInt (packages/sync-server/src/app-sync.ts:53-55) protected=False reaches_data=False - verifyFileExists (packages/sync-server/src/app-sync.ts:57-70) protected=False reaches_data=False - requireFileAccess (packages/sync-server/src/app-sync.ts:72-82) protected=False reaches_data=False - anonymous_L84 (packages/sync-server/src/app-sync.ts:84-147) protected=False reaches_data=False sinks=[sensitive_log@89] - anonymous_L142 (packages/sync-server/src/app-sync.ts:142-142) protected=False reaches_data=False - anonymous_L149 (packages/sync-server/src/app-sync.ts:149-176) protected=False reaches_data=False - anonymous_L178 (packages/sync-server/src/app-sync.ts:178-205) protected=False reaches_data=False - anonymous_L207 (packages/sync-server/src/app-sync.ts:207-242) protected=False reaches_data=False sinks=[sensitive_log@237] SOURCE: packages/sync-server/src/app-sync.ts (502 lines), lines 50-244: 50: 51: const OK_RESPONSE = { status: 'ok' }; 52: 53: function boolToInt(deleted) { 54: return deleted ? 1 : 0; 55: } 56: 57: const verifyFileExists = (fileId, filesService, res, errorObject) => { 58: try { 59: return filesService.get(fileId); 60: } catch (e) { 61: if (e instanceof FileNotFound) { 62: //FIXME: error code should be 404. Need to make sure frontend is ok with it. 63: //TODO: put this into a middleware that checks if FileNotFound is thrown and returns 404 and same error message 64: // for every FileNotFound error 65: res.status(400).send(errorObject); 66: return; 67: } 68: throw e; 69: } 70: }; 71: 72: function requireFileAccess(file: File, userId: string) { 73: const isOwner = file.owner === userId; 74: const isServerAdmin = isAdmin(userId); 75: if (isOwner || isServerAdmin) { 76: return null; 77: } 78: if (UserService.countUserAccess(file.id, userId) > 0) { 79: return null; 80: } 81: return 'file-access-not-allowed'; 82: } 83: 84: app.post('/sync', async (req, res): Promise<void> => { 85: let requestPb; 86: try { 87: requestPb = SyncProtoBuf.SyncRequest.deserializeBinary(req.body); 88: } catch (e) { 89: console.log('Error parsing sync request', e); 90: res.status(500); 91: res.send({ status: 'error', reason: 'internal-error' }); 92: return; 93: } 94: 95: const fileId = requestPb.getFileid() || null; 96: const groupId = requestPb.getGroupid() || null; 97: const keyId = requestPb.getKeyid() || null; 98: const since = requestPb.getSince() || null; 99: const messages = requestPb.getMessagesList(); 100: 101: if (!since) { 102: res.status(422).send({ 103: details: 'since-required', 104: reason: 'unprocessable-entity', 105: status: 'error', 106: }); 107: return; 108: } 109: 110: const filesService = new FilesService(getAccountDb()); 111: 112: const currentFile = verifyFileExists( 113: fileId, 114: filesService, 115: res, 116: 'file-not-found', 117: ); 118: 119: if (!currentFile) { 120: return; 121: } 122: 123: const fileAccessError = requireFileAccess(currentFile, res.locals.user_id); 124: if (fileAccessError) { 125: res.status(403); 126: res.send(fileAccessError); 127: return; 128: } 129: 130: const errorMessage = validateSyncedFile(groupId, keyId, currentFile); 131: if (errorMessage) { 132: res.status(400); 133: res.send(errorMessage); 134: return; 135: } 136: 137: const { trie, newMessages } = simpleSync.sync(messages, since, groupId); 138: 139: // encode it back... 140: const responsePb = new SyncProtoBuf.SyncResponse(); 141: responsePb.setMerkle(JSON.stringify(trie)); 142: newMessages.forEach(msg => responsePb.addMessages(msg)); 143: 144: res.set('Content-Type', 'application/actual-sync'); 145: res.set('X-ACTUAL-SYNC-METHOD', 'simple'); 146: res.send(Buffer.from(responsePb.serializeBinary())); 147: }); 148: 149: app.post('/user-get-key', (req, res) => { 150: if (!res.locals) return; 151: 152: const { fileId } = req.body || {}; 153: 154: const filesService = new FilesService(getAccountDb()); 155: const file = verifyFileExists(fileId, filesService, res, 'file-not-found'); 156: 157: if (!file) { 158: return; 159: } 160: 161: const fileAccessError = requireFileAccess(file, res.locals.user_id); 162: if (fileAccessError) { 163: res.status(403); 164: res.send(fileAccessError); 165: return; 166: } 167: 168: res.send({ 169: status: 'ok', 170: data: { 171: id: file.encryptKeyId, 172: salt: file.encryptSalt, 173: test: file.encryptTest, 174: }, 175: }); 176: }); 177: 178: app.post('/user-create-key', (req, res) => { 179: const { fileId, keyId, keySalt, testContent } = req.body || {}; 180: 181: const filesService = new FilesService(getAccountDb()); 182: const file = verifyFileExists(fileId, filesService, res, 'file-not-found'); 183: 184: if (!file) { 185: return; 186: } 187: 188: const fileAccessError = requireFileAccess(file, res.locals.user_id); 189: if (fileAccessError) { 190: res.status(403); 191: res.send(fileAccessError); 192: return; 193: } 194: 195: filesService.update( 196: fileId, 197: new FileUpdate({ 198: encryptSalt: keySalt, 199: encryptKeyId: keyId, 200: encryptTest: testContent, 201: }), 202: ); 203: 204: res.send(OK_RESPONSE); 205: }); 206: 207: app.post('/reset-user-file', async (req, res) => { 208: const { fileId } = req.body || {}; 209: 210: const filesService = new FilesService(getAccountDb()); 211: const file = verifyFileExists( 212: fileId, 213: filesService, 214: res, 215: 'User or file not found', 216: ); 217: 218: if (!file) { 219: return; 220: } 221: 222: const fileAccessError = requireFileAccess(file, res.locals.user_id); 223: if (fileAccessError) { 224: res.status(403); 225: res.send(fileAccessError); 226: return; 227: } 228: 229: const groupId = file.groupId; 230: 231: filesService.update(fileId, new FileUpdate({ groupId: null })); 232: 233: if (groupId) { 234: try { 235: await fs.unlink(getPathForGroupFile(groupId)); 236: } catch { 237: console.log(`Unable to delete sync data for group "${groupId}"`); 238: } 239: } 240: 241: res.send(OK_RESPONSE); 242: }); 243: 244: app.post('/upload-user-file', async (req, res) => { [... 258 more lines: read_file(path, start_line=245) to continue] Audit every member, using the engine tools to settle what reading alone cannot. 1 message 27 tools APPLICATION PROFILE (from the mapping pass): AUTHENTICATION - Session token from req.body.token or header x-actual-token. validateSession() (packages/sync-server/src/util/validate-user.ts:10) looks it up via getSession() in account-db.js:209 and checks expires_at (-1 = never). Invalid/expired -> 401. - validateSessionMiddleware (packages/sync-server/src/util/middlewares.js:38) sets res.locals = session (so res.locals.user_id is the caller). Handlers never get a req.user; they read res.locals.user_id or session.user_id. - Applied per-router: app.use(validateSessionMiddleware) in app-sync.ts:32, app-secrets.js:15, app-gocardless.js:30; per-route in app-admin.js, app-openid.js. app.ts mounts /sync, /account, /gocardless, /simplefin, /pluggyai, /secret, /cors-proxy, /admin, /openid. Verify each mount has the gate: app-account.js and app-simplefin/pluggyai routes and the /cors-proxy catch-all (app-cors-proxy.js:129, app.use('/')) were NOT confirmed as gated in this pass. - Header/proxy auth: validateAuthHeader() (validate-user.ts:44) trusts peer IP against trustedAuthProxies. ACCESS MODEL - Server roles: users.is admin via isAdmin(userId) (account-db.js:135); hasPermission/getUserPermission at 139/219. - Per-file ownership plus sharing: files have an owner; user_access(file_id,user_id) grants shared access (services/user-service.js:157-258, app-sync/services/files-service.js:125-153). - File gate: requireFileAccess(file, userId) (app-sync.ts:72) = owner OR server admin OR user_access row. Used across /sync routes (app-sync.ts lines 123-492) but not every route was read. ENFORCEMENT HELPERS - validateSession / validateSessionMiddleware, isAdmin, requireFileAccess, UserService.countUserAccess, files-service canSeeAll (admin) branch. DATA ACCESS - Single SQLite account DB: getAccountDb() (account-db.js:12) -> openDatabase() in db.js (WrappedDatabase: all/first/exec/mutate/transaction). Per-file data lives in separate file DBs under app-sync/. - Services: services/user-service.js, app-sync/services/files-service.js. Routes: app-*.js and app-sync.ts. ENGINE STATUS / BLIND SPOT - Teach applied (db.WrappedDatabase / getAccountDb sinks, validateSessionMiddleware gate): no change; still 0/53 handlers reaching data in the scanned files. The engine does not resolve the getAccountDb().all/mutate chain, so data-access facts here come from manual reading, not the engine. Treat engine "protected: 0" as unreliable. PRIORITY AUDIT AREAS - Per-route checks in app-admin.js (granted===0 fallbacks), app-sync.ts file rout UNIT: packages/sync-server/src/app-sync.ts (module-level) HANDLERS (a verdict is required for EACH): - anonymous_L244 (packages/sync-server/src/app-sync.ts:244-345) protected=False reaches_data=False sinks=[sensitive_log@300] - anonymous_L318 (packages/sync-server/src/app-sync.ts:318-320) protected=False reaches_data=False - anonymous_L347 (packages/sync-server/src/app-sync.ts:347-385) protected=False reaches_data=False - anonymous_L387 (packages/sync-server/src/app-sync.ts:387-406) protected=False reaches_data=False - anonymous_L408 (packages/sync-server/src/app-sync.ts:408-426) protected=False reaches_data=False - anonymous_L413 (packages/sync-server/src/app-sync.ts:413-424) protected=False reaches_data=False - anonymous_L420 (packages/sync-server/src/app-sync.ts:420-423) protected=False reaches_data=False - anonymous_L428 (packages/sync-server/src/app-sync.ts:428-472) protected=False reaches_data=False SOURCE: packages/sync-server/src/app-sync.ts (502 lines), lines 241-474: 241: res.send(OK_RESPONSE); 242: }); 243: 244: app.post('/upload-user-file', async (req, res) => { 245: if (typeof req.headers['x-actual-name'] !== 'string') { 246: // FIXME: Not sure how this cannot be a string when the header is 247: // set. 248: res.status(400).send('single x-actual-name is required'); 249: return; 250: } 251: 252: const name = decodeURIComponent(req.headers['x-actual-name']); 253: const fileId = req.headers['x-actual-file-id']; 254: 255: if (!fileId || typeof fileId !== 'string') { 256: res.status(400).send('fileId is required'); 257: return; 258: } 259: 260: let groupId = req.headers['x-actual-group-id'] || null; 261: const encryptMeta = req.headers['x-actual-encrypt-meta'] || null; 262: const syncFormatVersion = req.headers['x-actual-format'] || null; 263: 264: const keyId = 265: encryptMeta && typeof encryptMeta === 'string' 266: ? JSON.parse(encryptMeta).keyId 267: : null; 268: 269: const filesService = new FilesService(getAccountDb()); 270: let currentFile; 271: 272: try { 273: currentFile = filesService.get(fileId); 274: } catch (e) { 275: if (e instanceof FileNotFound) { 276: currentFile = null; 277: } else { 278: throw e; 279: } 280: } 281: 282: const fileAccessError = currentFile 283: ? requireFileAccess(currentFile, res.locals.user_id) 284: : null; 285: if (fileAccessError) { 286: res.status(403); 287: res.send(fileAccessError); 288: return; 289: } 290: 291: const errorMessage = validateUploadedFile(groupId, keyId, currentFile); 292: if (errorMessage) { 293: res.status(400).send(errorMessage); 294: return; 295: } 296: 297: try { 298: await fs.writeFile(getPathForUserFile(fileId), req.body); 299: } catch (err) { 300: console.log('Error writing file', err); 301: res.status(500).send({ status: 'error' }); 302: return; 303: } 304: 305: if (!currentFile) { 306: // it's new 307: groupId = uuidv4(); 308: 309: filesService.set( 310: new File({ 311: id: fileId, 312: groupId, 313: syncVersion: syncFormatVersion, 314: name, 315: encryptMeta, 316: owner: 317: res.locals.user_id || 318: (() => { 319: throw new Error('User ID is required for file creation'); 320: })(), 321: }), 322: ); 323: 324: res.send({ status: 'ok', groupId }); 325: return; 326: } 327: 328: if (!groupId) { 329: // sync state was reset, create new group 330: groupId = uuidv4(); 331: filesService.update(fileId, new FileUpdate({ groupId })); 332: } 333: 334: // Regardless, update some properties 335: filesService.update( 336: fileId, 337: new FileUpdate({ 338: syncVersion: syncFormatVersion, 339: encryptMeta, 340: name, 341: }), 342: ); 343: 344: res.send({ status: 'ok', groupId }); 345: }); 346: 347: app.get('/download-user-file', async (req, res) => { 348: const fileId = req.headers['x-actual-file-id']; 349: if (typeof fileId !== 'string') { 350: // FIXME: Not sure how this cannot be a string when the header is 351: // set. 352: res.status(400).send('Single file ID is required'); 353: return; 354: } 355: 356: const filesService = new FilesService(getAccountDb()); 357: const file = verifyFileExists( 358: fileId, 359: filesService, 360: res, 361: 'User or file not found', 362: ); 363: 364: if (!file) { 365: return; 366: } 367: 368: const fileAccessError = requireFileAccess(file, res.locals.user_id); 369: if (fileAccessError) { 370: res.status(403); 371: res.send(fileAccessError); 372: return; 373: } 374: 375: const path = getPathForUserFile(fileId); 376: 377: if (!path.startsWith(resolve(config.get('userFiles')))) { 378: //Ensure the user doesn't try to access files outside of the user files directory 379: res.status(403).send('Access denied'); 380: return; 381: } 382: 383: res.setHeader('Content-Disposition', `attachment;filename=${fileId}`); 384: res.sendFile(path, { dotfiles: 'allow' }); 385: }); 386: 387: app.post('/update-user-filename', (req, res) => { 388: const { fileId, name } = req.body || {}; 389: 390: const filesService = new FilesService(getAccountDb()); 391: const file = verifyFileExists(fileId, filesService, res, 'file-not-found'); 392: 393: if (!file) { 394: return; 395: } 396: 397: const fileAccessError = requireFileAccess(file, res.locals.user_id); 398: if (fileAccessError) { 399: res.status(403); 400: res.send(fileAccessError); 401: return; 402: } 403: 404: filesService.update(fileId, new FileUpdate({ name })); 405: res.send(OK_RESPONSE); 406: }); 407: 408: app.get('/list-user-files', (req, res) => { 409: const fileService = new FilesService(getAccountDb()); 410: const rows = fileService.find({ userId: res.locals.user_id }); 411: res.send({ 412: status: 'ok', 413: data: rows.map(row => ({ 414: deleted: boolToInt(row.deleted), 415: fileId: row.id, 416: groupId: row.groupId, 417: name: row.name, 418: encryptKeyId: row.encryptKeyId, 419: owner: row.owner, 420: usersWithAccess: fileService.findUsersWithAccess(row.id).map(access => ({ 421: ...access, 422: owner: access.userId === row.owner, 423: })), 424: })), 425: }); 426: }); 427: 428: app.get('/get-user-file-info', (req, res) => { 429: const fileId = req.headers['x-actual-file-id']; 430: 431: // TODO: Return 422 if fileId is not provided. Need to make sure frontend can handle it 432: // if (!fileId) { 433: // return res.status(422).send({ 434: // details: 'fileId-required', 435: // reason: 'unprocessable-entity', 436: // status: 'error', 437: // }); 438: // } 439: 440: const fileService = new FilesService(getAccountDb()); 441: 442: const file = verifyFileExists(fileId, fileService, res, { 443: status: 'error', 444: reason: 'file-not-found', 445: }); 446: 447: if (!file) { 448: return; 449: } 450: 451: const fileAccessError = requireFileAccess(file, res.locals.user_id); 452: if (fileAccessError) { 453: res.status(403); 454: res.send(fileAccessError); 455: return; 456: } 457: 458: res.send({ 459: status: 'ok', 460: data: { 461: deleted: boolToInt(file.deleted), // FIXME: convert to boolean, make sure it works in the frontend 462: fileId: file.id, 463: groupId: file.groupId, 464: name: file.name, 465: encryptMeta: file.encryptMeta ? JSON.parse(file.encryptMeta) : null, 466: usersWithAccess: fileService.findUsersWithAccess(file.id).map(access => ({ 467: ...access, 468: owner: access.userId === file.owner, 469: })), 470: }, 471: }); 472: }); 473: 474: app.post('/delete-user-file', (req, res) => { [... 28 more lines: read_file(path, start_line=475) to continue] Audit every member, using the engine tools to settle what reading alone cannot. 2 messages 29 tools APPLICATION PROFILE (from the mapping pass): AUTHENTICATION - Session token from req.body.token or header x-actual-token. validateSession() (packages/sync-server/src/util/validate-user.ts:10) looks it up via getSession() in account-db.js:209 and checks expires_at (-1 = never). Invalid/expired -> 401. - validateSessionMiddleware (packages/sync-server/src/util/middlewares.js:38) sets res.locals = session (so res.locals.user_id is the caller). Handlers never get a req.user; they read res.locals.user_id or session.user_id. - Applied per-router: app.use(validateSessionMiddleware) in app-sync.ts:32, app-secrets.js:15, app-gocardless.js:30; per-route in app-admin.js, app-openid.js. app.ts mounts /sync, /account, /gocardless, /simplefin, /pluggyai, /secret, /cors-proxy, /admin, /openid. Verify each mount has the gate: app-account.js and app-simplefin/pluggyai routes and the /cors-proxy catch-all (app-cors-proxy.js:129, app.use('/')) were NOT confirmed as gated in this pass. - Header/proxy auth: validateAuthHeader() (validate-user.ts:44) trusts peer IP against trustedAuthProxies. ACCESS MODEL - Server roles: users.is admin via isAdmin(userId) (account-db.js:135); hasPermission/getUserPermission at 139/219. - Per-file ownership plus sharing: files have an owner; user_access(file_id,user_id) grants shared access (services/user-service.js:157-258, app-sync/services/files-service.js:125-153). - File gate: requireFileAccess(file, userId) (app-sync.ts:72) = owner OR server admin OR user_access row. Used across /sync routes (app-sync.ts lines 123-492) but not every route was read. ENFORCEMENT HELPERS - validateSession / validateSessionMiddleware, isAdmin, requireFileAccess, UserService.countUserAccess, files-service canSeeAll (admin) branch. DATA ACCESS - Single SQLite account DB: getAccountDb() (account-db.js:12) -> openDatabase() in db.js (WrappedDatabase: all/first/exec/mutate/transaction). Per-file data lives in separate file DBs under app-sync/. - Services: services/user-service.js, app-sync/services/files-service.js. Routes: app-*.js and app-sync.ts. ENGINE STATUS / BLIND SPOT - Teach applied (db.WrappedDatabase / getAccountDb sinks, validateSessionMiddleware gate): no change; still 0/53 handlers reaching data in the scanned files. The engine does not resolve the getAccountDb().all/mutate chain, so data-access facts here come from manual reading, not the engine. Treat engine "protected: 0" as unreliable. PRIORITY AUDIT AREAS - Per-route checks in app-admin.js (granted===0 fallbacks), app-sync.ts file rout UNIT: packages/sync-server/src/app-sync.ts (module-level) HANDLERS (a verdict is required for EACH): - anonymous_L466 (packages/sync-server/src/app-sync.ts:466-469) protected=False reaches_data=False - anonymous (packages/sync-server/src/app-sync.ts:474-502) protected=False reaches_data=False SOURCE: packages/sync-server/src/app-sync.ts (502 lines), lines 463-502: 463: groupId: file.groupId, 464: name: file.name, 465: encryptMeta: file.encryptMeta ? JSON.parse(file.encryptMeta) : null, 466: usersWithAccess: fileService.findUsersWithAccess(file.id).map(access => ({ 467: ...access, 468: owner: access.userId === file.owner, 469: })), 470: }, 471: }); 472: }); 473: 474: app.post('/delete-user-file', (req, res) => { 475: const { fileId } = req.body || {}; 476: 477: if (!fileId) { 478: res.status(422).send({ 479: details: 'fileId-required', 480: reason: 'unprocessable-entity', 481: status: 'error', 482: }); 483: return; 484: } 485: 486: const filesService = new FilesService(getAccountDb()); 487: const file = verifyFileExists(fileId, filesService, res, 'file-not-found'); 488: if (!file) { 489: return; 490: } 491: 492: const fileAccessError = requireFileAccess(file, res.locals.user_id); 493: if (fileAccessError) { 494: res.status(403); 495: res.send(fileAccessError); 496: return; 497: } 498: 499: filesService.update(fileId, new FileUpdate({ deleted: true })); 500: 501: res.send(OK_RESPONSE); 502: }); Audit every member, using the engine tools to settle what reading alone cannot. 1 message 13 tools Language: python Framework packs applied by the engine: celery, django-settings, fastapi, http-clients, llm-context, llm-sdks, process-execution, python-builtins, sql-libraries, web-settings Engine handlers: 589 (protected 0, reaching data 0); service functions 0, authorization gates 0; unverified authorization candidates 0. Handlers by directory: libs/aegra-api/tests/integration/test_api (111), libs/aegra-api/tests/unit/test_core (100), libs/aegra-api/tests/unit/test_api (84), libs/aegra-api/src/aegra_api/api (51), libs/aegra-api/tests/integration (45), libs/aegra-api/tests/unit/test_services (42), libs/aegra-api/src/aegra_api/core (38), libs/aegra-api/src/aegra_api/services (23), libs/aegra-api/tests/unit/test_threads (21), libs/aegra-api/tests/unit/test_middleware (18), libs/aegra-api/tests/integration/test_services (16), libs/aegra-api/src/aegra_api (11), libs/aegra-api/tests/unit (9), libs/aegra-api/tests/unit/test_observability (6), libs/aegra-api/src/aegra_api/middleware (5) BLIND SPOT: the engine sees data access in only 0 of 589 handlers. If this app reaches its database through a layer the engine does not know, teach it (the sinks), or every unit's ranking and guards will be blind too. Pack format for teach(): [pack] name = "app-conventions" language = "python" # or "javascript" (TypeScript too) description = "what this pack teaches" detect = { imports = ["myapp.db"] } # optional: only files importing one of these # A data access the engine does not know (an ORM wrapper / repository): reads are # "resource_select", writes "resource_modify". `call` is the canonical call id # (module.Class.method, as imported); `*` matches within a segment, `**` across. [[sink]] call = ["myapp.db.Repository.get", "myapp.db.Repository.find_*"] kind = "resource_select" [[sink]] call = ["myapp.db.Repository.save", "myapp.db.Repository.delete"] kind = "resource_modify" # A decorator that authenticates / authorizes the handler it wraps. [[auth_gate]] decorator = ["myapp.auth.require_admin", "myapp.auth.login_required"] # The authenticated caller, as the app exposes it (a module-level proxy). [[identity]] proxies = ["myapp.auth.current_user"] Map the application, teach the engine if it is blind, then finish_profile. 1 message 10 tools APPLICATION PROFILE (from the mapping pass): AUTHORIZATION PROFILE (aegra-api, Python/FastAPI + SQLAlchemy async) Authentication - Pluggable backend via core/auth_middleware.get_auth_backend(); config from aegra.json/langgraph.json "auth" (config.py load_auth_config). Default AUTH_TYPE "noop" (settings.py:61). - core/auth_deps.py: require_auth(request) (line 58) calls backend.authenticate, 401 on failure, stores user in request.scope, returns User model. get_current_user(request) (line 106) is the handler-facing caller accessor; get_user_id, require_permission(perm) (line 155, checks user.permissions -> 403), require_authenticated also here. - Routers apply auth at registration: api/runs.py:29, assistants.py:30 use dependencies=auth_dependency ([Depends(require_auth)]). main.py _apply_auth_to_routes (line 184) prepends auth to every route when http.enable_custom_route_auth is set (custom routes otherwise unprotected by default). Access model - Ownership, not roles: ORM tables (core/orm.py) carry user_id (Assistant l.46, Thread l.89, Run l.112). Handlers filter by user.identity, e.g. runs.py get_run (l.147-151) filters RunORM.user_id == user.identity; threads.py l.236/266 likewise. Cross-owner thread access returns 404 (runs.py l.57, l.105). - Sharing/teams/tenants: none found in these files. - Fine-grained hook: core/auth_handlers.py handle_event (l.62) runs user-defined @auth.on.* handlers (resource/action, e.g. threads/create_run). It is NON-INTERRUPTIVE by default: no handler, or a handler returning None/True, allows the request; only False or an exception denies. Returned dicts are merged as filters/metadata. So authorization beyond ownership filters depends entirely on the app's auth.py defining handlers. Enforcement helpers - auth_deps.require_auth / get_current_user / require_permission; auth_handlers.handle_event / build_auth_context; per-query user_id predicates in api/*.py. Data access and routes - Data access: SQLAlchemy AsyncSession injected via core/orm.py get_session (l.155) into route handlers (api/runs.py, threads.py, stateless_runs.py, assistants.py). Services in services/ (run_preparation._prepare_run, streaming_service). Engine was blind here; taught via teach() (sinks on AsyncSession.scalar/execute/add/delete/commit; auth gates; identity proxies). Now 18 handlers reach data. - Routes registered in main.py (include routers, l.277-339) and api/*.py. Audit focus / open items 1. Verify every data-touching handler filters by user_id (not only thread_id): check threads.py, stateles UNIT: libs/aegra-api/src/aegra_api/api/runs.py (module-level) Selected because: 7 unverified engine candidate(s); 6 unprotected handler(s) reaching data HANDLERS (a verdict is required for EACH): - create_run (libs/aegra-api/src/aegra_api/api/runs.py:41-82) protected=False reaches_data=True decorators=['router.post'] - create_and_stream_run (libs/aegra-api/src/aegra_api/api/runs.py:86-127) protected=False reaches_data=True decorators=['router.post'] - get_run (libs/aegra-api/src/aegra_api/api/runs.py:131-164) protected=False reaches_data=True decorators=['router.get'] - list_runs (libs/aegra-api/src/aegra_api/api/runs.py:168-199) protected=False reaches_data=True decorators=['router.get'] - update_run (libs/aegra-api/src/aegra_api/api/runs.py:203-249) protected=False reaches_data=True decorators=['router.patch'] - join_run (libs/aegra-api/src/aegra_api/api/runs.py:253-304) protected=False reaches_data=False decorators=['router.get'] - wait_for_run (libs/aegra-api/src/aegra_api/api/runs.py:308-348) protected=False reaches_data=False decorators=['router.post'] - stream_run (libs/aegra-api/src/aegra_api/api/runs.py:352-412) protected=False reaches_data=True decorators=['router.get'] ENGINE CANDIDATES (unverified; confirm with report_finding or refute with mark_safe naming the guard): - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:54 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:102 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:153 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:195 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:216 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:244 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:368 SOURCE: libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 39-84: 39: 40: @router.post("/threads/{thread_id}/runs", response_model=Run, responses={**NOT_FOUND, **CONFLICT}) 41: async def create_run( 42: thread_id: str, 43: request: RunCreate, 44: user: User = Depends(get_current_user), 45: session: AsyncSession = Depends(get_session), 46: ) -> Run: 47: """Create and execute a new run. 48: 49: Starts graph execution asynchronously and returns the run record 50: immediately with status `pending`. Poll the run or use the stream 51: endpoint to follow progress. Provide either `input` or `command` (for 52: human-in-the-loop resumption) but not both. 53: """ 54: existing_thread = await session.scalar( 55: select(ThreadORM).where(ThreadORM.thread_id == thread_id) 56: ) 57: if existing_thread and existing_thread.user_id != user.identity: 58: raise HTTPException(404, f"Thread '{thread_id}' not found") 59: 60: # Authorization check (create_run action on threads resource) 61: ctx = build_auth_context(user, "threads", "create_run") 62: value = {**request.model_dump(), "thread_id": thread_id} 63: filters = await handle_event(ctx, value) 64: 65: # If handler modified config/context, update request 66: if filters: 67: if "config" in filters and isinstance(filters["config"], dict): 68: request.config = {**(request.config or {}), **filters["config"]} 69: if "context" in filters and isinstance(filters["context"], dict): 70: request.context = {**(request.context or {}), **filters["context"]} 71: else: 72: value_config = value.get("config") 73: if isinstance(value_config, dict): 74: request.config = {**(request.config or {}), **value_config} 75: 76: value_context = value.get("context") 77: if isinstance(value_context, dict): 78: request.context = {**(request.context or {}), **value_context} 79: 80: _run_id, run, _job = await _prepare_run(session, thread_id, request, user, initial_status="pending") 81: 82: return run 83: 84: [... 478 more lines: read_file(path, start_line=85) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 84-129: 84: 85: @router.post("/threads/{thread_id}/runs/stream", responses={**SSE_RESPONSE, **NOT_FOUND, **CONFLICT}) 86: async def create_and_stream_run( 87: thread_id: str, 88: request: RunCreate, 89: user: User = Depends(get_current_user), 90: session: AsyncSession = Depends(get_session), 91: ) -> StreamingResponse: 92: """Create a new run and stream its execution via SSE. 93: 94: Returns a `text/event-stream` response with Server-Sent Events. Each 95: event has a `type` field (e.g. `values`, `updates`, `messages`, 96: `metadata`, `end`) and a JSON `data` payload. 97: 98: Set `on_disconnect` to `"continue"` if the run should keep executing 99: after the client disconnects (default is `"cancel"`). Use `stream_mode` 100: to control which event types are emitted. 101: """ 102: existing_thread = await session.scalar( 103: select(ThreadORM).where(ThreadORM.thread_id == thread_id) 104: ) 105: if existing_thread and existing_thread.user_id != user.identity: 106: raise HTTPException(404, f"Thread '{thread_id}' not found") 107: 108: run_id, run, _job = await _prepare_run(session, thread_id, request, user, initial_status="pending") 109: 110: # Default to cancel on disconnect - this matches user expectation that clicking 111: # "Cancel" in the frontend will stop the backend task. Users can explicitly 112: # set on_disconnect="continue" if they want the task to continue. 113: cancel_on_disconnect = (request.on_disconnect or "cancel").lower() == "cancel" 114: 115: return StreamingResponse( 116: streaming_service.stream_run_execution( 117: run, 118: None, 119: cancel_on_disconnect=cancel_on_disconnect, 120: ), 121: media_type="text/event-stream", 122: headers={ 123: **get_sse_headers(), 124: "Location": f"/threads/{thread_id}/runs/{run_id}/stream", 125: "Content-Location": f"/threads/{thread_id}/runs/{run_id}", 126: }, 127: ) 128: 129: [... 433 more lines: read_file(path, start_line=130) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 129-166: 129: 130: @router.get("/threads/{thread_id}/runs/{run_id}", response_model=Run, responses={**NOT_FOUND}) 131: async def get_run( 132: thread_id: str, 133: run_id: str, 134: user: User = Depends(get_current_user), 135: session: AsyncSession = Depends(get_session), 136: ) -> Run: 137: """Get a run by its ID. 138: 139: Returns the current state of the run including its status, input, output, 140: and error information. 141: """ 142: # Authorization check (read action on runs resource) 143: ctx = build_auth_context(user, "runs", "read") 144: value = {"run_id": run_id, "thread_id": thread_id} 145: await handle_event(ctx, value) 146: 147: stmt = select(RunORM).where( 148: RunORM.run_id == str(run_id), 149: RunORM.thread_id == thread_id, 150: RunORM.user_id == user.identity, 151: ) 152: logger.info(f"[get_run] querying DB run_id={run_id} thread_id={thread_id} user={user.identity}") 153: run_orm = await session.scalar(stmt) 154: if not run_orm: 155: raise HTTPException(404, f"Run '{run_id}' not found") 156: 157: # Refresh to ensure we have the latest data (in case background task updated it) 158: await session.refresh(run_orm) 159: 160: logger.info( 161: f"[get_run] found run status={run_orm.status} user={user.identity} thread_id={thread_id} run_id={run_id}" 162: ) 163: # Convert to Pydantic 164: return Run.model_validate(run_orm) 165: 166: [... 396 more lines: read_file(path, start_line=167) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 166-201: 166: 167: @router.get("/threads/{thread_id}/runs", response_model=list[Run]) 168: async def list_runs( 169: thread_id: str, 170: limit: int = Query(10, ge=1, description="Maximum number of runs to return"), 171: offset: int = Query(0, ge=0, description="Number of runs to skip for pagination"), 172: status: str | None = Query( 173: None, description="Filter by run status (e.g. pending, running, success, error, interrupted)" 174: ), 175: user: User = Depends(get_current_user), 176: session: AsyncSession = Depends(get_session), 177: ) -> list[Run]: 178: """List runs for a thread. 179: 180: Returns runs ordered by creation time (newest first). Use `status` to 181: filter and `limit`/`offset` to paginate. 182: """ 183: stmt = ( 184: select(RunORM) 185: .where( 186: RunORM.thread_id == thread_id, 187: RunORM.user_id == user.identity, 188: *([RunORM.status == status] if status else []), 189: ) 190: .limit(limit) 191: .offset(offset) 192: .order_by(RunORM.created_at.desc()) 193: ) 194: logger.info(f"[list_runs] querying DB thread_id={thread_id} user={user.identity}") 195: result = await session.scalars(stmt) 196: rows = result.all() 197: runs = [Run.model_validate(r) for r in rows] 198: logger.info(f"[list_runs] total={len(runs)} user={user.identity} thread_id={thread_id}") 199: return runs 200: 201: [... 361 more lines: read_file(path, start_line=202) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 201-251: 201: 202: @router.patch("/threads/{thread_id}/runs/{run_id}", response_model=Run, responses={**NOT_FOUND}) 203: async def update_run( 204: thread_id: str, 205: run_id: str, 206: request: RunStatus, 207: user: User = Depends(get_current_user), 208: session: AsyncSession = Depends(get_session), 209: ) -> Run: 210: """Update a run's status. 211: 212: Primarily used to interrupt a running execution. Set `status` to 213: `"interrupted"` to cooperatively stop the run. 214: """ 215: logger.info(f"[update_run] fetch for update run_id={run_id} thread_id={thread_id} user={user.identity}") 216: run_orm = await session.scalar( 217: select(RunORM).where( 218: RunORM.run_id == str(run_id), 219: RunORM.thread_id == thread_id, 220: RunORM.user_id == user.identity, 221: ) 222: ) 223: if not run_orm: 224: raise HTTPException(404, f"Run '{run_id}' not found") 225: 226: # Handle interruption/cancellation 227: # Validate status conforms to API specification 228: validated_status = validate_run_status(request.status) 229: 230: if validated_status == "interrupted": 231: logger.info(f"[update_run] cancelling/interrupting run_id={run_id} user={user.identity} thread_id={thread_id}") 232: # Handle interruption - use interrupt_run for cooperative interruption 233: await streaming_service.interrupt_run(run_id) 234: logger.info(f"[update_run] set DB status=interrupted run_id={run_id}") 235: await session.execute( 236: update(RunORM) 237: .where(RunORM.run_id == str(run_id)) 238: .values(status="interrupted", updated_at=datetime.now(UTC)) 239: ) 240: await session.commit() 241: logger.info(f"[update_run] commit done (interrupted) run_id={run_id}") 242: 243: # Return final run state 244: run_orm = await session.scalar(select(RunORM).where(RunORM.run_id == run_id)) 245: if not run_orm: 246: raise HTTPException(404, f"Run '{run_id}' not found") 247: # Refresh to ensure we have the latest data after our own update 248: await session.refresh(run_orm) 249: return Run.model_validate(run_orm) 250: 251: [... 311 more lines: read_file(path, start_line=252) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 251-306: 251: 252: @router.get("/threads/{thread_id}/runs/{run_id}/join", responses={**NOT_FOUND}) 253: async def join_run( 254: thread_id: str, 255: run_id: str, 256: user: User = Depends(get_current_user), 257: ) -> StreamingResponse: 258: """Wait for a run to complete and return its output. 259: 260: Returns a chunked ``application/json`` response. While the run is still 261: executing, the server sends periodic ``\\n`` heartbeat bytes to keep the 262: connection alive through proxies and load balancers (AWS ALB, Cloudflare, 263: etc.). The final chunk is the JSON result. Leading whitespace is ignored 264: by JSON parsers, so clients can parse the concatenated body normally. 265: 266: If the run is already in a terminal state, the output is returned 267: immediately with no heartbeat overhead. 268: 269: Sessions are managed manually (not via ``Depends``) to avoid holding a 270: pool connection during the long wait. 271: """ 272: maker = _get_session_maker() 273: 274: # Short-lived session: validate run exists and check terminal state 275: async with maker() as session: 276: run_orm = await session.scalar( 277: select(RunORM).where( 278: RunORM.run_id == str(run_id), 279: RunORM.thread_id == thread_id, 280: RunORM.user_id == user.identity, 281: ) 282: ) 283: if not run_orm: 284: raise HTTPException(404, f"Run '{run_id}' not found") 285: 286: if run_orm.status in TERMINAL_STATES: 287: return StreamingResponse( 288: iter([encode_output(run_orm.output or {})]), 289: media_type="application/json", 290: ) 291: 292: return StreamingResponse( 293: heartbeat_wait_body( 294: run_id, 295: thread_id, 296: user.identity, 297: timeout=settings.worker.BG_JOB_TIMEOUT_SECS, 298: ), 299: media_type="application/json", 300: headers={ 301: "Location": f"/threads/{thread_id}/runs/{run_id}/join", 302: "Content-Location": f"/threads/{thread_id}/runs/{run_id}", 303: }, 304: ) 305: 306: [... 256 more lines: read_file(path, start_line=307) to continue] libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 306-339: 306: 307: @router.post("/threads/{thread_id}/runs/wait", responses={**NOT_FOUND, **CONFLICT}) 308: async def wait_for_run( 309: thread_id: str, 310: request: RunCreate, 311: user: User = Depends(get_current_user), 312: ) -> StreamingResponse: 313: """Create a run, execute it, and wait for completion. 314: 315: Returns a chunked ``application/json`` response with periodic ``\\n`` 316: heartbeat bytes to keep the connection alive. The final chunk is the 317: JSON result. Uses ``BG_JOB_TIMEOUT_SECS`` (default 1 hour) as the 318: safety-net timeout. 319: 320: Sessions are managed manually (not via ``Depends``) to avoid holding a 321: pool connection during the long wait. 322: """ 323: maker = _get_session_maker() 324: 325: # Session block: all pre-execution DB work (validate, create run, submit) 326: async with maker() as session: 327: existing_thread = await session.scalar( 328: select(ThreadORM).where(ThreadORM.thread_id == thread_id) 329: ) 330: if existing_thread and existing_thread.user_id != user.identity: 331: raise HTTPException(404, f"Thread '{thread_id}' not found") 332: 333: run_id, _run, _job = await _prepare_run(session, thread_id, request, user, initial_status="pending") 334: 335: # No pool connection held from here — safe for long waits 336: return StreamingResponse( 337: heartbeat_wait_body( 338: run_id, 339: thread_id, [... 223 more lines: read_file(path, start_line=340) to continue] Audit every member, using the engine tools to settle what reading alone cannot. 1 message 30 tools APPLICATION PROFILE (from the mapping pass): AUTHORIZATION PROFILE (aegra-api, Python/FastAPI + SQLAlchemy async) Authentication - Pluggable backend via core/auth_middleware.get_auth_backend(); config from aegra.json/langgraph.json "auth" (config.py load_auth_config). Default AUTH_TYPE "noop" (settings.py:61). - core/auth_deps.py: require_auth(request) (line 58) calls backend.authenticate, 401 on failure, stores user in request.scope, returns User model. get_current_user(request) (line 106) is the handler-facing caller accessor; get_user_id, require_permission(perm) (line 155, checks user.permissions -> 403), require_authenticated also here. - Routers apply auth at registration: api/runs.py:29, assistants.py:30 use dependencies=auth_dependency ([Depends(require_auth)]). main.py _apply_auth_to_routes (line 184) prepends auth to every route when http.enable_custom_route_auth is set (custom routes otherwise unprotected by default). Access model - Ownership, not roles: ORM tables (core/orm.py) carry user_id (Assistant l.46, Thread l.89, Run l.112). Handlers filter by user.identity, e.g. runs.py get_run (l.147-151) filters RunORM.user_id == user.identity; threads.py l.236/266 likewise. Cross-owner thread access returns 404 (runs.py l.57, l.105). - Sharing/teams/tenants: none found in these files. - Fine-grained hook: core/auth_handlers.py handle_event (l.62) runs user-defined @auth.on.* handlers (resource/action, e.g. threads/create_run). It is NON-INTERRUPTIVE by default: no handler, or a handler returning None/True, allows the request; only False or an exception denies. Returned dicts are merged as filters/metadata. So authorization beyond ownership filters depends entirely on the app's auth.py defining handlers. Enforcement helpers - auth_deps.require_auth / get_current_user / require_permission; auth_handlers.handle_event / build_auth_context; per-query user_id predicates in api/*.py. Data access and routes - Data access: SQLAlchemy AsyncSession injected via core/orm.py get_session (l.155) into route handlers (api/runs.py, threads.py, stateless_runs.py, assistants.py). Services in services/ (run_preparation._prepare_run, streaming_service). Engine was blind here; taught via teach() (sinks on AsyncSession.scalar/execute/add/delete/commit; auth gates; identity proxies). Now 18 handlers reach data. - Routes registered in main.py (include routers, l.277-339) and api/*.py. Audit focus / open items 1. Verify every data-touching handler filters by user_id (not only thread_id): check threads.py, stateles UNIT: libs/aegra-api/src/aegra_api/api/runs.py (module-level) Selected because: 5 unverified engine candidate(s); 2 unprotected handler(s) reaching data HANDLERS (a verdict is required for EACH): - cancel_run_endpoint (libs/aegra-api/src/aegra_api/api/runs.py:420-493) protected=False reaches_data=True decorators=['router.post'] - delete_run (libs/aegra-api/src/aegra_api/api/runs.py:501-562) protected=False reaches_data=True decorators=['router.delete'] ENGINE CANDIDATES (unverified; confirm with report_finding or refute with mark_safe naming the guard): - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:440 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:479 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:519 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:547 - CWE-639 idor at libs/aegra-api/src/aegra_api/api/runs.py:547 SOURCE: libs/aegra-api/src/aegra_api/api/runs.py (562 lines), lines 417-562: 417: response_model=Run, 418: responses={**NOT_FOUND}, 419: ) 420: async def cancel_run_endpoint( 421: thread_id: str, 422: run_id: str, 423: wait: int = Query(0, ge=0, le=1, description="Set to 1 to wait for the run task to settle before returning."), 424: action: str = Query( 425: "cancel", 426: pattern="^(cancel|interrupt)$", 427: description="Cancellation strategy: 'cancel' for hard cancel, 'interrupt' for cooperative interrupt.", 428: ), 429: user: User = Depends(get_current_user), 430: session: AsyncSession = Depends(get_session), 431: ) -> Run: 432: """Cancel or interrupt a running execution. 433: 434: Use `action=cancel` to hard-cancel the run immediately, or 435: `action=interrupt` to cooperatively interrupt (the graph can handle the 436: interrupt and save partial state). Set `wait=1` to block until the 437: background task has fully settled before returning the updated run. 438: """ 439: logger.info(f"[cancel_run] fetch run run_id={run_id} thread_id={thread_id} user={user.identity}") 440: run_orm = await session.scalar( 441: select(RunORM).where( 442: RunORM.run_id == run_id, 443: RunORM.thread_id == thread_id, 444: RunORM.user_id == user.identity, 445: ) 446: ) 447: if not run_orm: 448: raise HTTPException(404, f"Run '{run_id}' not found") 449: 450: if action == "interrupt": 451: logger.info(f"[cancel_run] interrupt run_id={run_id} user={user.identity} thread_id={thread_id}") 452: await streaming_service.interrupt_run(run_id) 453: # Persist status as interrupted 454: await session.execute( 455: update(RunORM) 456: .where(RunORM.run_id == str(run_id)) 457: .values(status="interrupted", updated_at=datetime.now(UTC)) 458: ) 459: await session.commit() 460: else: 461: logger.info(f"[cancel_run] cancel run_id={run_id} user={user.identity} thread_id={thread_id}") 462: await streaming_service.cancel_run(run_id) 463: # Persist status as interrupted 464: await session.execute( 465: update(RunORM) 466: .where(RunORM.run_id == str(run_id)) 467: .values(status="interrupted", updated_at=datetime.now(UTC)) 468: ) 469: await session.commit() 470: 471: # Optionally wait for the run to settle 472: if wait: 473: # Poll DB until the run reaches a terminal state (or 10s timeout). 474: # This is simpler and more reliable than pub/sub for cancel-with-wait 475: # since the cancel has already been issued and the status update committed. 476: for _ in range(20): 477: await asyncio.sleep(0.5) 478: session.expire_all() # sync method, clears cache 479: fresh = await session.scalar(select(RunORM).where(RunORM.run_id == run_id)) 480: if fresh and fresh.status in TERMINAL_STATES: 481: break 482: 483: # Reload and return updated Run (do NOT delete here; deletion is a separate endpoint) 484: run_orm = await session.scalar( 485: select(RunORM).where( 486: RunORM.run_id == run_id, 487: RunORM.thread_id == thread_id, 488: RunORM.user_id == user.identity, 489: ) 490: ) 491: if not run_orm: 492: raise HTTPException(404, f"Run '{run_id}' not found after cancellation") 493: return Run.model_validate(run_orm) 494: 495: 496: @router.delete( 497: "/threads/{thread_id}/runs/{run_id}", 498: status_code=204, 499: responses={**NOT_FOUND, **CONFLICT}, 500: ) 501: async def delete_run( 502: thread_id: str, 503: run_id: str, 504: force: int = Query(0, ge=0, le=1, description="Set to 1 to cancel an active run before deleting it."), 505: user: User = Depends(get_current_user), 506: session: AsyncSession = Depends(get_session), 507: ) -> None: 508: """Delete a run record. 509: 510: If the run is active (pending or running) and `force=0`, returns 409 511: Conflict. Set `force=1` to cancel the run first (best-effort) and then 512: delete it. Returns 204 No Content on success. 513: """ 514: # Authorization check (delete action on runs resource) 515: ctx = build_auth_context(user, "runs", "delete") 516: value = {"run_id": run_id, "thread_id": thread_id} 517: await handle_event(ctx, value) 518: logger.info(f"[delete_run] fetch run run_id={run_id} thread_id={thread_id} user={user.identity}") 519: run_orm = await session.scalar( 520: select(RunORM).where( 521: RunORM.run_id == str(run_id), 522: RunORM.thread_id == thread_id, 523: RunORM.user_id == user.identity, 524: ) 525: ) 526: if not run_orm: 527: raise HTTPException(404, f"Run '{run_id}' not found") 528: 529: # If active and not forcing, reject deletion 530: if run_orm.status in ["pending", "running"] and not force: 531: raise HTTPException( 532: status_code=409, 533: detail="Run is active. Retry with force=1 to cancel and delete.", 534: ) 535: 536: # If forcing and active, cancel first 537: if force and run_orm.status in ["pending", "running"]: 538: logger.info(f"[delete_run] force-cancelling active run run_id={run_id}") 539: await streaming_service.cancel_run(run_id) 540: # Best-effort: wait for bg task to settle 541: task = active_runs.get(run_id) 542: if task: 543: with contextlib.suppress(asyncio.CancelledError, Exception): 544: await task 545: 546: # Delete the record 547: await session.execute( 548: delete(RunORM).where( 549: RunORM.run_id == str(run_id), 550: RunORM.thread_id == thread_id, 551: RunORM.user_id == user.identity, 552: ) 553: ) 554: await session.commit() 555: 556: # Clean up active task if exists 557: task = active_runs.pop(run_id, None) 558: if task and not task.done(): 559: task.cancel() 560: 561: # 204 No Content 562: return Audit every member, using the engine tools to settle what reading alone cannot. 1 message 13 tools APPLICATION PROFILE (from the mapping pass): AUTHORIZATION PROFILE (aegra-api, Python/FastAPI + SQLAlchemy async) Authentication - Pluggable backend via core/auth_middleware.get_auth_backend(); config from aegra.json/langgraph.json "auth" (config.py load_auth_config). Default AUTH_TYPE "noop" (settings.py:61). - core/auth_deps.py: require_auth(request) (line 58) calls backend.authenticate, 401 on failure, stores user in request.scope, returns User model. get_current_user(request) (line 106) is the handler-facing caller accessor; get_user_id, require_permission(perm) (line 155, checks user.permissions -> 403), require_authenticated also here. - Routers apply auth at registration: api/runs.py:29, assistants.py:30 use dependencies=auth_dependency ([Depends(require_auth)]). main.py _apply_auth_to_routes (line 184) prepends auth to every route when http.enable_custom_route_auth is set (custom routes otherwise unprotected by default). Access model - Ownership, not roles: ORM tables (core/orm.py) carry user_id (Assistant l.46, Thread l.89, Run l.112). Handlers filter by user.identity, e.g. runs.py get_run (l.147-151) filters RunORM.user_id == user.identity; threads.py l.236/266 likewise. Cross-owner thread access returns 404 (runs.py l.57, l.105). - Sharing/teams/tenants: none found in these files. - Fine-grained hook: core/auth_handlers.py handle_event (l.62) runs user-defined @auth.on.* handlers (resource/action, e.g. threads/create_run). It is NON-INTERRUPTIVE by default: no handler, or a handler returning None/True, allows the request; only False or an exception denies. Returned dicts are merged as filters/metadata. So authorization beyond ownership filters depends entirely on the app's auth.py defining handlers. Enforcement helpers - auth_deps.require_auth / get_current_user / require_permission; auth_handlers.handle_event / build_auth_context; per-query user_id predicates in api/*.py. Data access and routes - Data access: SQLAlchemy AsyncSession injected via core/orm.py get_session (l.155) into route handlers (api/runs.py, threads.py, stateless_runs.py, assistants.py). Services in services/ (run_preparation._prepare_run, streaming_service). Engine was blind here; taught via teach() (sinks on AsyncSession.scalar/execute/add/delete/commit; auth gates; identity proxies). Now 18 handlers reach data. - Routes registered in main.py (include routers, l.277-339) and api/*.py. Audit focus / open items 1. Verify every data-touching handler filters by user_id (not only thread_id): check threads.py, stateles UNIT: libs/aegra-api/src/aegra_api/api/stateless_runs.py (module-level) HANDLERS (a verdict is required for EACH): - _delete_thread_by_id (libs/aegra-api/src/aegra_api/api/stateless_runs.py:46-84) protected=False reaches_data=False - _cleanup_after_background_run (libs/aegra-api/src/aegra_api/api/stateless_runs.py:87-103) protected=False reaches_data=False - stateless_wait_for_run (libs/aegra-api/src/aegra_api/api/stateless_runs.py:112-173) protected=False reaches_data=False decorators=['router.post'] - _wrapped_iterator (libs/aegra-api/src/aegra_api/api/stateless_runs.py:144-166) protected=False reaches_data=False - stateless_stream_run (libs/aegra-api/src/aegra_api/api/stateless_runs.py:177-234) protected=False reaches_data=False decorators=['router.post'] - _wrapped_iterator#2 (libs/aegra-api/src/aegra_api/api/stateless_runs.py:212-227) protected=False reaches_data=False - stateless_create_run (libs/aegra-api/src/aegra_api/api/stateless_runs.py:238-272) protected=False reaches_data=False decorators=['router.post'] SOURCE: libs/aegra-api/src/aegra_api/api/stateless_runs.py (272 lines), lines 43-272: 43: # --------------------------------------------------------------------------- 44: 45: 46: async def _delete_thread_by_id(thread_id: str, user_id: str) -> None: 47: """Delete an ephemeral thread and cascade-delete its runs. 48: 49: Opens its own DB session so it can be called after the request session has 50: been closed (e.g. in a ``finally`` block or background task). 51: """ 52: maker = _get_session_maker() 53: async with maker() as session: 54: # Cancel any still-active runs on this thread 55: active_runs_stmt = select(RunORM).where( 56: RunORM.thread_id == thread_id, 57: RunORM.user_id == user_id, 58: RunORM.status.in_(["pending", "running"]), 59: ) 60: active_runs_list = (await session.scalars(active_runs_stmt)).all() 61: 62: for run in active_runs_list: 63: run_id = run.run_id 64: await streaming_service.cancel_run(run_id) 65: task = active_runs.pop(run_id, None) 66: if task and not task.done(): 67: task.cancel() 68: try: 69: await task 70: except asyncio.CancelledError: 71: pass 72: except Exception: 73: logger.exception("Error awaiting cancelled task during thread cleanup", run_id=run_id) 74: 75: # Delete thread (cascade deletes runs via FK) 76: thread = await session.scalar( 77: select(ThreadORM).where( 78: ThreadORM.thread_id == thread_id, 79: ThreadORM.user_id == user_id, 80: ) 81: ) 82: if thread: 83: await session.delete(thread) 84: await session.commit() 85: 86: 87: async def _cleanup_after_background_run(run_id: str, thread_id: str, user_id: str) -> None: 88: """Wait for a background run to finish, then delete the ephemeral thread. 89: 90: Uses executor.wait_for_completion which works both in-process (dev) 91: and cross-instance (prod with Redis workers). 92: """ 93: try: 94: await executor.wait_for_completion(run_id, timeout=3600.0) 95: except (asyncio.CancelledError, TimeoutError): 96: pass 97: except Exception: 98: logger.exception("Error waiting for background run", run_id=run_id) 99: 100: try: 101: await _delete_thread_by_id(thread_id, user_id) 102: except Exception: 103: logger.exception("Failed to delete ephemeral thread", thread_id=thread_id, run_id=run_id) 104: 105: 106: # --------------------------------------------------------------------------- 107: # Endpoints 108: # --------------------------------------------------------------------------- 109: 110: 111: @router.post("/runs/wait", responses={**NOT_FOUND, **CONFLICT}) 112: async def stateless_wait_for_run( 113: request: RunCreate, 114: user: User = Depends(get_current_user), 115: ) -> StreamingResponse: 116: """Create a stateless run and wait for completion. 117: 118: Generates an ephemeral thread, delegates to the threaded ``wait_for_run`` 119: endpoint, and deletes the thread after the response finishes streaming 120: (unless ``on_completion="keep"``). 121: """ 122: thread_id = str(uuid4()) 123: should_delete = request.on_completion != "keep" 124: 125: try: 126: response = await wait_for_run(thread_id, request, user) 127: except Exception: 128: if should_delete: 129: try: 130: await _delete_thread_by_id(thread_id, user.identity) 131: except Exception: 132: logger.exception( 133: "Failed to delete ephemeral thread after wait error", 134: thread_id=thread_id, 135: ) 136: raise 137: 138: if not should_delete: 139: return response 140: 141: # Wrap the body_iterator so cleanup happens after the stream ends 142: original_iterator = response.body_iterator 143: 144: async def _wrapped_iterator() -> AsyncIterator[bytes]: 145: completed = False 146: try: 147: async for chunk in original_iterator: 148: yield chunk 149: completed = True 150: finally: 151: aclose = getattr(original_iterator, "aclose", None) 152: if aclose is not None: 153: await aclose() 154: if completed: 155: try: 156: await _delete_thread_by_id(thread_id, user.identity) 157: except Exception: 158: logger.exception( 159: "Failed to delete ephemeral thread after wait", 160: thread_id=thread_id, 161: ) 162: else: 163: logger.info( 164: "Client disconnected before stream completed, keeping ephemeral thread", 165: thread_id=thread_id, 166: ) 167: 168: return StreamingResponse( 169: _wrapped_iterator(), 170: status_code=response.status_code, 171: media_type=response.media_type, 172: headers=dict(response.headers), 173: ) 174: 175: 176: @router.post("/runs/stream", responses={**SSE_RESPONSE, **NOT_FOUND, **CONFLICT}) 177: async def stateless_stream_run( 178: request: RunCreate, 179: user: User = Depends(get_current_user), 180: session: AsyncSession = Depends(get_session), 181: ) -> StreamingResponse: 182: """Create a stateless run and stream its execution. 183: 184: Generates an ephemeral thread, delegates to the threaded 185: ``create_and_stream_run`` endpoint, and deletes the thread after the 186: stream finishes (unless ``on_completion="keep"``). 187: """ 188: thread_id = str(uuid4()) 189: should_delete = request.on_completion != "keep" 190: 191: try: 192: response = await create_and_stream_run(thread_id, request, user, session) 193: except Exception: 194: # create_and_stream_run may have auto-created the thread via 195: # update_thread_metadata before raising; clean up to avoid orphans. 196: if should_delete: 197: try: 198: await _delete_thread_by_id(thread_id, user.identity) 199: except Exception: 200: logger.exception( 201: "Failed to delete ephemeral thread after stream setup error", 202: thread_id=thread_id, 203: ) 204: raise 205: 206: if not should_delete: 207: return response 208: 209: # Wrap the body_iterator so cleanup happens after the stream ends 210: original_iterator = response.body_iterator 211: 212: async def _wrapped_iterator() -> AsyncIterator[str | bytes]: 213: try: 214: async for chunk in original_iterator: 215: yield chunk 216: finally: 217: # Close the underlying iterator if it supports aclose() 218: aclose = getattr(original_iterator, "aclose", None) 219: if aclose is not None: 220: await aclose() 221: try: 222: await _delete_thread_by_id(thread_id, user.identity) 223: except Exception: 224: logger.exception( 225: "Failed to delete ephemeral thread after stream", 226: thread_id=thread_id, 227: ) 228: 229: return StreamingResponse( 230: _wrapped_iterator(), 231: status_code=response.status_code, 232: media_type=response.media_type, 233: headers=dict(response.headers), 234: ) 235: 236: 237: @router.post("/runs", response_model=Run, responses={**NOT_FOUND, **CONFLICT}) 238: async def stateless_create_run( 239: request: RunCreate, 240: user: User = Depends(get_current_user), 241: session: AsyncSession = Depends(get_session), 242: ) -> Run: 243: """Create a stateless background run. 244: 245: Generates an ephemeral thread, delegates to the threaded ``create_run`` 246: endpoint, and schedules cleanup as a background task (unless 247: ``on_completion="keep"``). 248: """ 249: thread_id = str(uuid4()) 250: should_delete = request.on_completion != "keep" 251: 252: try: 253: result = await create_run(thread_id, request, user, session) 254: except Exception: 255: # create_run may have auto-created the thread via 256: # update_thread_metadata before raising; clean up to avoid orphans. 257: if should_delete: 258: try: 259: await _delete_thread_by_id(thread_id, user.identity) 260: except Exception: 261: logger.exception( 262: "Failed to delete ephemeral thread after create error", 263: thread_id=thread_id, 264: ) 265: raise 266: 267: if should_delete: 268: task = asyncio.create_task(_cleanup_after_background_run(result.run_id, thread_id, user.identity)) 269: _background_cleanup_tasks.add(task) 270: task.add_done_callback(_background_cleanup_tasks.discard) 271: 272: return result Audit every member, using the engine tools to settle what reading alone cannot. 1 message 26 tools APPLICATION PROFILE (from the mapping pass): AUTHORIZATION PROFILE (aegra-api, Python/FastAPI + SQLAlchemy async) Authentication - Pluggable backend via core/auth_middleware.get_auth_backend(); config from aegra.json/langgraph.json "auth" (config.py load_auth_config). Default AUTH_TYPE "noop" (settings.py:61). - core/auth_deps.py: require_auth(request) (line 58) calls backend.authenticate, 401 on failure, stores user in request.scope, returns User model. get_current_user(request) (line 106) is the handler-facing caller accessor; get_user_id, require_permission(perm) (line 155, checks user.permissions -> 403), require_authenticated also here. - Routers apply auth at registration: api/runs.py:29, assistants.py:30 use dependencies=auth_dependency ([Depends(require_auth)]). main.py _apply_auth_to_routes (line 184) prepends auth to every route when http.enable_custom_route_auth is set (custom routes otherwise unprotected by default). Access model - Ownership, not roles: ORM tables (core/orm.py) carry user_id (Assistant l.46, Thread l.89, Run l.112). Handlers filter by user.identity, e.g. runs.py get_run (l.147-151) filters RunORM.user_id == user.identity; threads.py l.236/266 likewise. Cross-owner thread access returns 404 (runs.py l.57, l.105). - Sharing/teams/tenants: none found in these files. - Fine-grained hook: core/auth_handlers.py handle_event (l.62) runs user-defined @auth.on.* handlers (resource/action, e.g. threads/create_run). It is NON-INTERRUPTIVE by default: no handler, or a handler returning None/True, allows the request; only False or an exception denies. Returned dicts are merged as filters/metadata. So authorization beyond ownership filters depends entirely on the app's auth.py defining handlers. Enforcement helpers - auth_deps.require_auth / get_current_user / require_permission; auth_handlers.handle_event / build_auth_context; per-query user_id predicates in api/*.py. Data access and routes - Data access: SQLAlchemy AsyncSession injected via core/orm.py get_session (l.155) into route handlers (api/runs.py, threads.py, stateless_runs.py, assistants.py). Services in services/ (run_preparation._prepare_run, streaming_service). Engine was blind here; taught via teach() (sinks on AsyncSession.scalar/execute/add/delete/commit; auth gates; identity proxies). Now 18 handlers reach data. - Routes registered in main.py (include routers, l.277-339) and api/*.py. Audit focus / open items 1. Verify every data-touching handler filters by user_id (not only thread_id): check threads.py, stateles UNIT: libs/aegra-api/src/aegra_api/core/auth_handlers.py (module-level) HANDLERS (a verdict is required for EACH): - handle_event (libs/aegra-api/src/aegra_api/core/auth_handlers.py:62-158) protected=False reaches_data=False - _get_handler (libs/aegra-api/src/aegra_api/core/auth_handlers.py:161-210) protected=False reaches_data=False - build_auth_context (libs/aegra-api/src/aegra_api/core/auth_handlers.py:213-248) protected=False reaches_data=False SOURCE: libs/aegra-api/src/aegra_api/core/auth_handlers.py (248 lines), lines 59-248: 59: ) 60: 61: 62: async def handle_event( 63: ctx: AuthContextWrapper | None, 64: value: dict[str, Any], 65: ) -> dict[str, Any] | None: 66: """Call the appropriate @auth.on.* handler for authorization. 67: 68: This function resolves the most specific handler for the given resource 69: and action, calls it with the auth context and value, and interprets 70: the result. 71: 72: **Default Behavior (Non-Interruptive):** 73: - If no auth is configured → allows by default (returns None) 74: - If no handlers are defined → allows by default (returns None) 75: - If handler returns None/True → allows (returns None) 76: - If handler returns dict → allows with filters applied (returns dict) 77: - **Only interrupts if handler returns False or raises exception** 78: 79: This ensures that developers using raw Aegra without custom authorization 80: handlers will have a working system out-of-the-box. Handlers are purely 81: additive - they can inject metadata, apply filters, or deny access, but 82: they don't interrupt the flow unless explicitly configured to do so. 83: 84: Handler resolution priority (most specific first): 85: 1. Resource+action specific (e.g., "threads", "create") 86: 2. Resource-specific (e.g., "threads", "*") 87: 3. Action-specific (e.g., "*", "create") 88: 4. Global handler ("*", "*") 89: 90: Args: 91: ctx: Auth context wrapper with user, resource, and action 92: value: The data being authorized (request body, search filters, etc.) 93: This dict may be modified by the handler (e.g., injecting metadata) 94: 95: Returns: 96: None: Request allowed, no filters to apply 97: dict: Filter dict to apply to queries (e.g., {"user_id": "123"}) 98: 99: Raises: 100: HTTPException(403): If handler returns False or raises AssertionError 101: HTTPException(500): If handler raises unexpected exception or returns invalid type 102: """ 103: if ctx is None: 104: # No auth context means no authorization check needed 105: # This allows the request to proceed normally 106: return None 107: 108: auth = get_auth_instance() 109: if auth is None: 110: # No auth configured, allow by default 111: # This ensures raw Aegra works out-of-the-box without interruption 112: return None 113: 114: # Convert to AuthContext 115: auth_ctx = ctx.to_langgraph_context() 116: 117: # Find the most specific handler 118: handler = _get_handler(auth, auth_ctx.resource, auth_ctx.action) 119: if handler is None: 120: # No handler for this resource/action, allow by default 121: # Developers can use Aegra without defining handlers - it won't break 122: return None 123: 124: try: 125: # Call the handler with context and value 126: result = await handler(ctx=auth_ctx, value=value) 127: except Auth.exceptions.HTTPException as e: 128: # Handler raised HTTP exception, convert to FastAPI HTTPException 129: raise HTTPException( 130: status_code=e.status_code, 131: detail=e.detail, 132: headers=dict(e.headers) if hasattr(e, "headers") and e.headers else None, 133: ) from e 134: except AssertionError as e: 135: # Handler used assert for authorization check 136: raise HTTPException(status_code=403, detail=str(e)) from e 137: except Exception as e: 138: # Unexpected error in handler 139: raise HTTPException(status_code=500, detail=f"Authorization error: {str(e)}") from e 140: 141: # Interpret handler result 142: if result in (None, True): 143: # Allow request, no filters 144: return None 145: 146: if result is False: 147: # Deny request 148: raise HTTPException(status_code=403, detail="Forbidden") 149: 150: if isinstance(result, dict): 151: # Return filter dict to apply to queries 152: return result 153: 154: # Invalid return type 155: raise HTTPException( 156: status_code=500, 157: detail=f"Auth handler returned invalid type: {type(result)}. Expected dict, None, True, or False.", 158: ) 159: 160: 161: def _get_handler( 162: auth: Auth, 163: resource: str, 164: action: str, 165: ) -> Any | None: 166: """Find the most specific handler for resource+action. 167: 168: Handler resolution follows this priority order (most specific first): 169: 1. (resource, action) - e.g., ("threads", "create") 170: 2. (resource, "*") - e.g., ("threads", "*") 171: 3. ("*", action) - e.g., ("*", "create") 172: 4. ("*", "*") - global handler 173: 174: Args: 175: auth: Auth instance with registered handlers 176: resource: Resource name (e.g., "threads", "assistants") 177: action: Action name (e.g., "create", "read", "update") 178: 179: Returns: 180: Handler function or None if no handler found 181: """ 182: # Check cache first 183: key = (resource, action) 184: if key in auth._handler_cache: 185: return auth._handler_cache[key] 186: 187: # Priority order (most specific first) 188: keys = [ 189: (resource, action), # Most specific: exact resource+action 190: (resource, "*"), # Resource-specific: all actions on resource 191: ("*", action), # Action-specific: all resources for action 192: ("*", "*"), # Global: all resources and actions 193: ] 194: 195: # Find first matching handler 196: for check_key in keys: 197: if check_key in auth._handlers and auth._handlers[check_key]: 198: # Get the last registered handler (most recent wins) 199: handler = auth._handlers[check_key][-1] 200: # Cache the result 201: auth._handler_cache[key] = handler 202: return handler 203: 204: # Check global handlers (fallback for backward compatibility) 205: if auth._global_handlers: 206: handler = auth._global_handlers[-1] 207: auth._handler_cache[key] = handler 208: return handler 209: 210: return None 211: 212: 213: def build_auth_context( 214: user: User, 215: resource: str, 216: action: str, 217: ) -> AuthContextWrapper: 218: """Build AuthContextWrapper from user and operation info. 219: 220: This is a convenience function to create an AuthContextWrapper with 221: the correct resource and action for a given operation. 222: 223: Args: 224: user: Authenticated user from require_auth dependency 225: resource: Resource being accessed (e.g., "threads", "assistants") 226: action: Action being performed (e.g., "create", "read", "update") 227: 228: Returns: 229: AuthContextWrapper instance ready to pass to handle_event() 230: 231: Example: 232: ```python 233: @router.post("/threads") 234: async def create_thread( 235: request: ThreadCreate, 236: user: User = Depends(require_auth), 237: ): 238: ctx = build_auth_context(user, "threads", "create") 239: value = request.model_dump() 240: filters = await handle_event(ctx, value) 241: # Use filters or modified value... 242: ``` 243: """ 244: return AuthContextWrapper( 245: user=user, 246: resource=resource, 247: action=action, 248: ) Audit every member, using the engine tools to settle what reading alone cannot. 1 message 13 tools APPLICATION PROFILE (from the mapping pass): AUTHORIZATION PROFILE (aegra-api, Python/FastAPI + SQLAlchemy async) Authentication - Pluggable backend via core/auth_middleware.get_auth_backend(); config from aegra.json/langgraph.json "auth" (config.py load_auth_config). Default AUTH_TYPE "noop" (settings.py:61). - core/auth_deps.py: require_auth(request) (line 58) calls backend.authenticate, 401 on failure, stores user in request.scope, returns User model. get_current_user(request) (line 106) is the handler-facing caller accessor; get_user_id, require_permission(perm) (line 155, checks user.permissions -> 403), require_authenticated also here. - Routers apply auth at registration: api/runs.py:29, assistants.py:30 use dependencies=auth_dependency ([Depends(require_auth)]). main.py _apply_auth_to_routes (line 184) prepends auth to every route when http.enable_custom_route_auth is set (custom routes otherwise unprotected by default). Access model - Ownership, not roles: ORM tables (core/orm.py) carry user_id (Assistant l.46, Thread l.89, Run l.112). Handlers filter by user.identity, e.g. runs.py get_run (l.147-151) filters RunORM.user_id == user.identity; threads.py l.236/266 likewise. Cross-owner thread access returns 404 (runs.py l.57, l.105). - Sharing/teams/tenants: none found in these files. - Fine-grained hook: core/auth_handlers.py handle_event (l.62) runs user-defined @auth.on.* handlers (resource/action, e.g. threads/create_run). It is NON-INTERRUPTIVE by default: no handler, or a handler returning None/True, allows the request; only False or an exception denies. Returned dicts are merged as filters/metadata. So authorization beyond ownership filters depends entirely on the app's auth.py defining handlers. Enforcement helpers - auth_deps.require_auth / get_current_user / require_permission; auth_handlers.handle_event / build_auth_context; per-query user_id predicates in api/*.py. Data access and routes - Data access: SQLAlchemy AsyncSession injected via core/orm.py get_session (l.155) into route handlers (api/runs.py, threads.py, stateless_runs.py, assistants.py). Services in services/ (run_preparation._prepare_run, streaming_service). Engine was blind here; taught via teach() (sinks on AsyncSession.scalar/execute/add/delete/commit; auth gates; identity proxies). Now 18 handlers reach data. - Routes registered in main.py (include routers, l.277-339) and api/*.py. Audit focus / open items 1. Verify every data-touching handler filters by user_id (not only thread_id): check threads.py, stateles UNIT: libs/aegra-api/src/aegra_api/services/run_preparation.py (module-level) HANDLERS (a verdict is required for EACH): - _validate_resume_command (libs/aegra-api/src/aegra_api/services/run_preparation.py:31-40) protected=False reaches_data=False - _resolve_content_text (libs/aegra-api/src/aegra_api/services/run_preparation.py:46-63) protected=False reaches_data=False - _extract_thread_name (libs/aegra-api/src/aegra_api/services/run_preparation.py:66-100) protected=False reaches_data=False - update_thread_metadata (libs/aegra-api/src/aegra_api/services/run_preparation.py:103-157) protected=False reaches_data=False - _prepare_run (libs/aegra-api/src/aegra_api/services/run_preparation.py:160-278) protected=False reaches_data=False SOURCE: libs/aegra-api/src/aegra_api/services/run_preparation.py (278 lines), lines 28-278: 28: logger = structlog.getLogger(__name__) 29: 30: 31: async def _validate_resume_command(session: AsyncSession, thread_id: str, command: dict[str, Any] | None) -> None: 32: """Validate resume command requirements.""" 33: if command and command.get("resume") is not None: 34: # Check if thread exists and is in interrupted state 35: thread_stmt = select(ThreadORM).where(ThreadORM.thread_id == thread_id) 36: thread = await session.scalar(thread_stmt) 37: if not thread: 38: raise HTTPException(404, f"Thread '{thread_id}' not found") 39: if thread.status != "interrupted": 40: raise HTTPException(400, "Cannot resume: thread is not in interrupted state") 41: 42: 43: _THREAD_NAME_MAX_LENGTH = 100 44: 45: 46: def _resolve_content_text(content: Any) -> str: 47: """Extract plain text from a message content field. 48: 49: Handles both plain strings and list-of-blocks format used by some SDKs:: 50: 51: [{"type": "text", "text": "Hello world"}] 52: """ 53: if isinstance(content, str): 54: return content 55: if isinstance(content, list): 56: parts: list[str] = [] 57: for block in content: 58: if isinstance(block, dict) and block.get("type") == "text": 59: text = block.get("text", "") 60: if isinstance(text, str): 61: parts.append(text) 62: return " ".join(parts) 63: return "" 64: 65: 66: def _extract_thread_name(input_data: dict[str, Any]) -> str: 67: """Derive a thread name from the first human message in the run input. 68: 69: Supports the common ``{"messages": [{"role": "human", "content": "..."}]}`` 70: shape emitted by agent-chat-ui, LangGraph Studio, and the JS/Python SDKs. 71: Also handles list-of-blocks content from OpenAI-compatible APIs. 72: Returns an empty string when no suitable message is found. 73: """ 74: messages = input_data.get("messages") 75: if not isinstance(messages, list) or not messages: 76: return "" 77: _HUMAN_ROLES = {"human", "user"} 78: for msg in messages: 79: raw_content: Any = None 80: role: str | None = None 81: if isinstance(msg, dict): 82: role_val = msg.get("role") 83: role = role_val if isinstance(role_val, str) else None 84: if role is None: 85: type_val = msg.get("type") 86: role = type_val if isinstance(type_val, str) else None 87: raw_content = msg.get("content") 88: elif hasattr(msg, "content"): 89: raw_content = getattr(msg, "content", None) 90: msg_type = getattr(msg, "type", None) 91: role = msg_type if isinstance(msg_type, str) else None 92: if role not in _HUMAN_ROLES: 93: continue 94: text = _resolve_content_text(raw_content) 95: if text.strip(): 96: name = text.strip() 97: if len(name) > _THREAD_NAME_MAX_LENGTH: 98: return name[:_THREAD_NAME_MAX_LENGTH].rsplit(" ", 1)[0] + "..." 99: return name 100: return "" 101: 102: 103: async def update_thread_metadata( 104: session: AsyncSession, 105: thread_id: str, 106: assistant_id: str, 107: graph_id: str, 108: *, 109: user_id: str | None = None, 110: input_data: dict[str, Any] | None = None, 111: ) -> None: 112: """Update thread metadata with assistant and graph information (dialect agnostic). 113: 114: If thread doesn't exist, auto-creates it. 115: When *input_data* is provided and the thread has no name yet, the first 116: human message content is used as ``thread_name``. 117: Does NOT commit — the caller controls the transaction boundary. 118: """ 119: # Read-modify-write to avoid DB-specific JSON concat operators 120: thread = await session.scalar(select(ThreadORM).where(ThreadORM.thread_id == thread_id)) 121: 122: thread_name = _extract_thread_name(input_data or {}) 123: 124: if not thread: 125: # Auto-create thread if it doesn't exist 126: if not user_id: 127: raise HTTPException(400, "Cannot auto-create thread: user_id is required") 128: 129: metadata = { 130: "owner": user_id, 131: "assistant_id": str(assistant_id), 132: "graph_id": graph_id, 133: "thread_name": thread_name, 134: } 135: 136: thread_orm = ThreadORM( 137: thread_id=thread_id, 138: status="idle", 139: metadata_json=metadata, 140: user_id=user_id, 141: ) 142: session.add(thread_orm) 143: return 144: 145: md = dict(getattr(thread, "metadata_json", {}) or {}) 146: md.update( 147: { 148: "assistant_id": str(assistant_id), 149: "graph_id": graph_id, 150: } 151: ) 152: # Only set thread_name if empty and we have a name from the input 153: if thread_name and not md.get("thread_name"): 154: md["thread_name"] = thread_name 155: await session.execute( 156: update(ThreadORM).where(ThreadORM.thread_id == thread_id).values(metadata_json=md, updated_at=datetime.now(UTC)) 157: ) 158: 159: 160: async def _prepare_run( 161: session: AsyncSession, 162: thread_id: str, 163: request: RunCreate, 164: user: User, 165: *, 166: initial_status: str, 167: ) -> tuple[str, Run, RunJob]: 168: """Shared run-creation logic used by create, stream, and wait endpoints. 169: 170: Validates inputs, resolves the assistant, persists the RunORM record, 171: builds a RunJob, submits it to the executor, and returns the triple 172: ``(run_id, run_model, job)``. 173: """ 174: await _validate_resume_command(session, thread_id, request.command) 175: 176: run_id = str(uuid4()) 177: langgraph_service = get_langgraph_service() 178: logger.info( 179: "Scheduling run", 180: run_id=run_id, 181: thread_id=thread_id, 182: user_id=user.identity, 183: status=initial_status, 184: ) 185: 186: # Resolve assistant / graph 187: requested_id = str(request.assistant_id) 188: available_graphs = langgraph_service.list_graphs() 189: resolved_assistant_id = resolve_assistant_id(requested_id, available_graphs) 190: 191: # Config / context merging 192: config = request.config or {} 193: context = request.context or {} 194: configurable = config.get("configurable", {}) 195: if not isinstance(configurable, dict): 196: raise HTTPException(status_code=422, detail="`config.configurable` must be a mapping") 197: 198: if not context: 199: context = configurable.copy() 200: 201: assistant_stmt = select(AssistantORM).where( 202: AssistantORM.assistant_id == resolved_assistant_id, 203: ) 204: assistant = await session.scalar(assistant_stmt) 205: if not assistant: 206: raise HTTPException(404, f"Assistant '{request.assistant_id}' not found") 207: 208: config = _merge_jsonb(assistant.config, config) 209: context = _merge_jsonb(assistant.context, context) 210: 211: # Validate the assistant's graph exists 212: available_graphs = langgraph_service.list_graphs() 213: if assistant.graph_id not in available_graphs: 214: raise HTTPException(404, f"Graph '{assistant.graph_id}' not found for assistant") 215: 216: # Mark thread as busy and update metadata 217: await update_thread_metadata( 218: session, thread_id, assistant.assistant_id, assistant.graph_id, user_id=user.identity, input_data=request.input 219: ) 220: await set_thread_status(session, thread_id, "busy") 221: 222: # Build the RunJob before persisting so we can store execution_params 223: job = RunJob( 224: identity=RunIdentity(run_id=run_id, thread_id=thread_id, graph_id=assistant.graph_id), 225: user=user, 226: execution=RunExecution( 227: input_data=request.input or {}, 228: config=config, 229: context=context, 230: stream_mode=request.stream_mode, 231: checkpoint=request.checkpoint, 232: command=request.command, 233: ), 234: behavior=RunBehavior( 235: interrupt_before=request.interrupt_before, 236: interrupt_after=request.interrupt_after, 237: multitask_strategy=request.multitask_strategy, 238: subgraphs=request.stream_subgraphs or False, 239: ), 240: ) 241: 242: # Persist run record with trace metadata for worker observability. 243: # The correlation_id from the HTTP request is stored so workers can 244: # link their logs and spans back to the original request. 245: exec_params = job.to_execution_params() 246: exec_params["trace"] = { 247: "correlation_id": correlation_id.get(""), 248: "user_id": user.identity, 249: "thread_id": thread_id, 250: "graph_id": assistant.graph_id, 251: } 252: 253: now = datetime.now(UTC) 254: run_orm = RunORM( 255: run_id=run_id, 256: thread_id=thread_id, 257: assistant_id=resolved_assistant_id, 258: status=initial_status, 259: input=request.input or {}, 260: config=config, 261: context=context, 262: user_id=user.identity, 263: created_at=now, 264: updated_at=now, 265: output=None, 266: error_message=None, 267: execution_params=exec_params, 268: ) 269: session.add(run_orm) 270: await session.commit() 271: 272: run = Run.model_validate(run_orm) 273: 274: # Submit to executor 275: await executor.submit(job) 276: logger.info("Submitted run to executor", run_id=run_id) 277: 278: return run_id, run, job Audit every member, using the engine tools to settle what reading alone cannot. 1 message 18 tools

Frame Agent Traces

Security-audit agent trajectories produced by Frame, the open-source neuro-symbolic security scanner. Each session is one agent of Frame's agentic hunt for authorization and business-logic flaws (IDOR, missing authorization, privilege escalation, unbounded quantities, races, skipped workflow steps, replays, unlimited login attempts) auditing a slice of a real application, with Frame's own analysis engine as a tool. Labels come from the benchmarks' deterministic scorers run against each advisory's ground truth, never from the agent's own verdict.

The dataset is 28,721 agent sessions in HuggingFace Session-Traces format (the agent-traces viewer), the format Frame writes when [hunt] trajectory_dir is set. Each .jsonl file is one session: a header line carrying the labels, then one message per turn with tool calls and results.

How a hunt runs. frame scan --hunt-authz (or --hunt limits,race,workflow,replay,bruteforce) first lets scouts map an area of the repository (routes, data-touching services, authorization helpers) and teach the engine conventions it missed. The engine then plans units (a handler class, a service function, an authorization gate) ranked by engine facts only, and a fresh agent audits each one with read_file, grep and the engine as tools (handler_facts, trace, callers, guards, check, ...). An agent must end every member with a verdict: report_finding (an invariant plus a violating request), mark_safe (the enforcing check) or mark_unresolved (what the repository cannot decide). Coverage units audit files several agents read but none owned.

Sources

source sessions
logicbench 18,046
bacbench 10,099
propagation-seeds 576
  • bacbench: BAC-Bench (ABSENTIA), 30 disclosed broken-access-control advisories in 25 open-source web applications, each on its vulnerable and its fixing commit. Several development runs of the hunt (gen_run), so a case appears more than once.
  • logicbench: Frame's business-logic benchmark (benchmarks/logicbench), 32 disclosed business-logic advisories (limits, race, workflow, replay, bruteforce), keyed from each advisory and its fix before Frame was run on them, on the vulnerable and fixing commits.
  • propagation-seeds: the small Flask and Express seed applications of Coding Agents Propagate Vulnerabilities in Code Bases, each in a secure and an insecure_cweN variant.

Stats

count
sessions 28,721
scouts / profiles 1,436
audit units (incl. coverage) 27,195
single-agent hunts (early runs) 90
benchmark cases (BAC-Bench + logicbench) 62
units auditing the ground-truth code, vulnerable commit 594 (reported 190 · unresolved 7 · safe 397)
units auditing the ground-truth code, fixed commit 598 (reported 135 · unresolved 11 · safe 452)
seed-app units on secure variants that reported a finding (false positives) 55 of 258

Agent verdicts over all sessions: safe 23,960 · reported 2,939 · none 1,504 · unresolved 318. Flaw classes audited: authz 10,337 · limits 8,384 · race 3,076 · workflow 2,121 · replay 2,104 · bruteforce 1,263. Models: claude-haiku-5-5 24,849 · deepseek-v4.1-flash 3,868 · claude-sonnet-5-5 4. Median session: 16 messages, 9 tool calls. Tool mix: read_file (31%), grep (27%), mark_safe (22%), handler_facts (5%), check (4%), callers (3%), list_files (2%), guards (2%). 53.5% of the 3.85B prompt tokens were prompt-cache hits (Frame keeps each agent's transcript append-only with a stable prefix).

Header labels

field meaning
source, gen_run the benchmark and the run that produced the session
case, advisory, cve, repo, commit, language, framework provenance: the advisory and the checkout audited
side vulnerable / fixed commit (benchmarks), insecure-variant vulnerable / secure (seed apps)
flaw_class, expected_cwes, ground_truth_cwe the case's class and its ground-truth CWEs
role scout, profile, unit, coverage, or agent (one agent for the whole repository, early runs)
unit, unit_kind, hunt_class, unit_files what the agent was asked to audit (handlers, service, gate, scouted, coverage, ...) and for which flaw class
session_verdict what the agent concluded: reported beats unresolved beats safe; none for scouts
unit_verdicts, unit_findings, unit_stop the hunt's own record of the unit: a verdict per member, findings kept, how it ended
covers_ground_truth the unit's files hold the advisory's vulnerable code (sink_files / root_files)
case_outcome the deterministic scorer's verdict on the agent tier for the case: paired (found, and gone on the fixed commit), detected, miss, hunt-error
ground_truth_in_map whether the scouts' map of the repository included the ground-truth files
case_detected, case_false_positives seed apps: whether the hunt found the insecure variant's flaw; findings on the secure variant
turns_used, tool_calls, tools, messages, usage effort and cost: per-call prompt / cached / completion / reasoning tokens and USD

Using these

import json, glob

def sessions():
    for path in glob.glob("*/*/*/*.jsonl"):
        lines = [json.loads(l) for l in open(path)]
        yield lines[0], [l["message"] for l in lines[1:]]

# units that audited the vulnerable code and reported it, on a case the scorer counts as found
positives = [(h, m) for h, m in sessions()
             if h.get("covers_ground_truth") and h["side"] == "vulnerable"
             and h["session_verdict"] == "reported" and h.get("case_outcome") in ("detected", "paired")]

# the same code on the fixed commit, judged safe: the negative twin
negatives = [(h, m) for h, m in sessions()
             if h.get("covers_ground_truth") and h["side"] == "fixed" and h["session_verdict"] == "safe"]

The most useful slices are the disagreements: units that audited the ground-truth code on the vulnerable commit and marked it safe (missed flaws), and seed-app units that reported a finding on the secure variant (false positives), for training a verifier of security verdicts.

Contamination. BAC-Bench, logicbench and the seed applications are evaluation sets. Training on these sessions contaminates any score you report on them.

Provenance

Sessions were produced by Frame's hunt (frame/sil/llm_hunt.py) through an OpenAI-compatible endpoint or Anthropic's Messages API, with the models listed above. Applications are cloned at the advisories' pinned commits by benchmarks/bacbench/prepare.py; tool results quote their source code, which stays under each project's own license (the header's repo and commit name it). Each case is labelled by benchmarks/bacbench/score.py, the deterministic matcher both benchmarks use. Sessions are curated by benchmarks/traces/curate.py: units whose endpoint failed mid-run, empty sessions and exact duplicates (units reused from a cache) are left out; local paths, private network addresses and user names are replaced with placeholders, and every session is checked against Frame's provider-credential formats.

Directories: bacbench/h1/fixed, bacbench/h1/vulnerable, bacbench/h2/fixed, bacbench/h2/vulnerable, bacbench/h2_outage/fixed, bacbench/h2_outage/vulnerable, bacbench/h3/fixed, bacbench/h3/vulnerable, bacbench/h4/fixed, bacbench/h4/vulnerable, bacbench/h5/fixed, bacbench/h5/vulnerable, bacbench/sonnet_or/fixed, bacbench/sonnet_or/vulnerable, bacbench/sonnet_smoke2/fixed, bacbench/sonnet_smoke2/vulnerable, bacbench/v1/fixed, bacbench/v1/vulnerable, bacbench/v11/fixed, bacbench/v11/vulnerable, bacbench/v11b/fixed, bacbench/v11b/vulnerable, bacbench/v12smoke/vulnerable, bacbench/v2/fixed, bacbench/v2/vulnerable, bacbench/v3/fixed, bacbench/v3/vulnerable, bacbench/v4/fixed, bacbench/v4/vulnerable, bacbench/v5/fixed, bacbench/v5/vulnerable, bacbench/v6/fixed, bacbench/v6/vulnerable, bacbench/v7/fixed, bacbench/v7/vulnerable, bacbench/v8/fixed, bacbench/v8/vulnerable, bacbench/v9/fixed, bacbench/v9/vulnerable, logicbench/limits-t1/fixed ...

Related

Downloads last month
115

Paper for lambdasec/frame-agent-traces