diff --git a/server/src/db/working-group-db.ts b/server/src/db/working-group-db.ts index 0f17b1ec531..c095ec07a39 100644 --- a/server/src/db/working-group-db.ts +++ b/server/src/db/working-group-db.ts @@ -560,25 +560,33 @@ export class WorkingGroupDatabase { * a member of. Use this when building aggregated feeds so private subgroup * posts/events don't leak to non-members viewing the public parent. * - * The target group itself is always included — visibility of the target is + * The ordinary target group itself is always included — visibility of the target is * the caller's responsibility (the route guards against viewing private * groups you aren't in). * - * Pass `isAdmin: true` to skip the privacy filter entirely (for admin views). + * Pass `isAdmin: true` to skip ordinary subgroup privacy filters (for admin views). + * The reserved platform group always requires the caller's exact authenticated + * platform decision, including when historical data places it under a parent. */ async getVisibleDescendantIds( groupId: string, userId: string | null, - options: { isAdmin?: boolean } = {}, + options: { isAdmin?: boolean; canViewReservedAdminGroup?: boolean } = {}, ): Promise { - const result = await query<{ id: string; is_private: boolean; parent_id: string | null }>( - `SELECT id, is_private, parent_id FROM working_groups + const result = await query<{ id: string; slug: string; is_private: boolean; parent_id: string | null }>( + `SELECT id, slug, is_private, parent_id FROM working_groups WHERE id = $1 OR parent_id = $1`, [groupId] ); const allowed: string[] = []; for (const row of result.rows) { + // Canonical membership and an incorrect privacy flag cannot expose + // reserved administrator content through an ordinary parent's feed. + if (row.slug === AAO_ADMIN_WORKING_GROUP_SLUG) { + if (options.canViewReservedAdminGroup === true) allowed.push(row.id); + continue; + } // Target group: always include. if (row.id === groupId) { allowed.push(row.id); diff --git a/server/src/http.ts b/server/src/http.ts index 6dba0e333a0..ba99ce7f519 100644 --- a/server/src/http.ts +++ b/server/src/http.ts @@ -106,7 +106,7 @@ import { import { invalidateMembershipCache, findClaimableProspectOrgForDomain } from "./db/org-filters.js"; import * as relationshipDb from "./db/relationship-db.js"; import * as personEvents from "./db/person-events-db.js"; -import { isWebUserAAOAdmin } from "./addie/mcp/admin-tools.js"; +import { isAuthenticatedUserAAOAdmin } from "./addie/admin-status-lookup.js"; import { resolveWebUserAAOAdminAccess } from "./addie/admin-status-lookup.js"; import { isBreakGlassAdminEmail } from "./auth/admin-access.js"; import { createSlackRouter } from "./routes/slack.js"; @@ -3761,7 +3761,7 @@ export class HTTPServer { // Check ownership - user must be creator or admin const isCreator = brand.created_by_user_id && brand.created_by_user_id === req.user?.id; - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isCreator && !isAdmin) { return res.status(403).json({ error: 'Not authorized to update this brand' }); } @@ -3776,6 +3776,7 @@ export class HTTPServer { const updated = await this.brandDb.updateHostedBrand(brand.id, { brand_json }); return res.json(updated); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to update hosted brand'); return res.status(500).json({ error: 'Failed to update brand' }); } @@ -3811,7 +3812,7 @@ export class HTTPServer { // Check ownership - user must be creator or admin const isCreator = brand.created_by_user_id && brand.created_by_user_id === req.user?.id; - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isCreator && !isAdmin) { return res.status(403).json({ error: 'Not authorized to delete this brand' }); } @@ -3819,6 +3820,7 @@ export class HTTPServer { await this.brandDb.deleteHostedBrand(brand.id); return res.json({ success: true }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to delete hosted brand'); return res.status(500).json({ error: 'Failed to delete brand' }); } @@ -3936,7 +3938,7 @@ export class HTTPServer { // access for moderation and support. this.app.post('/api/brands/discovered/:domain/rollback', requireAuth, async (req, res) => { try { - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); await enrichUserWithMembership(req.user as any); if (!isAdmin && !(req.user as any)?.isMember) { return res.status(403).json({ error: 'Membership required to roll back brands' }); @@ -3989,6 +3991,7 @@ export class HTTPServer { return res.json({ brand, revision_number }); } catch (error: any) { + if (respondToAdminAuthorizationError(error, res)) return; if (error.message?.includes('not found')) { logger.warn({ err: error, path: req.path }, 'Brand not found during rollback'); return res.status(404).json({ error: 'Resource not found' }); @@ -4043,7 +4046,7 @@ export class HTTPServer { // GET /api/registry/requests - List unresolved registry requests (admin only) this.app.get('/api/registry/requests', requireAuth, async (req, res) => { try { - const isAdmin = await isWebUserAAOAdmin(req.user!.id); + const isAdmin = await isAuthenticatedUserAAOAdmin(req.user!); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4059,6 +4062,7 @@ export class HTTPServer { const requests = await this.registryRequestsDb.listUnresolved(entityType, { limit, offset }); return res.json({ requests, limit, offset }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to list registry requests'); return res.status(500).json({ error: 'Failed to list registry requests' }); } @@ -4067,7 +4071,7 @@ export class HTTPServer { // GET /api/registry/requests/stats - Registry request statistics (admin only) this.app.get('/api/registry/requests/stats', requireAuth, async (req, res) => { try { - const isAdmin = await isWebUserAAOAdmin(req.user!.id); + const isAdmin = await isAuthenticatedUserAAOAdmin(req.user!); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4080,6 +4084,7 @@ export class HTTPServer { const stats = await this.registryRequestsDb.getStats(entityType); return res.json(stats); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to get registry request stats'); return res.status(500).json({ error: 'Failed to get registry request stats' }); } @@ -4285,7 +4290,7 @@ export class HTTPServer { // Check ownership const isCreator = property.created_by_user_id && property.created_by_user_id === req.user?.id; - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isCreator && !isAdmin) { return res.status(403).json({ error: 'Not authorized to delete this property' }); } @@ -4293,6 +4298,7 @@ export class HTTPServer { await this.propertyDb.deleteHostedProperty(property.id); return res.json({ success: true }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to delete hosted property'); return res.status(500).json({ error: 'Failed to delete property' }); } @@ -4414,7 +4420,7 @@ export class HTTPServer { // POST /api/properties/hosted/:domain/rollback - Rollback property (admin only) this.app.post('/api/properties/hosted/:domain/rollback', requireAuth, async (req, res) => { try { - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4441,6 +4447,7 @@ export class HTTPServer { return res.json({ property, revision_number }); } catch (error: any) { + if (respondToAdminAuthorizationError(error, res)) return; if (error.message?.includes('not found')) { logger.warn({ err: error, path: req.path }, 'Property not found during rollback'); return res.status(404).json({ error: 'Resource not found' }); @@ -4494,7 +4501,7 @@ export class HTTPServer { // POST /api/registry/edit-bans - Create an edit ban this.app.post('/api/registry/edit-bans', requireAuth, async (req, res) => { try { - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4530,6 +4537,7 @@ export class HTTPServer { return res.json(ban); } catch (error: any) { + if (respondToAdminAuthorizationError(error, res)) return; if (error?.constraint) { return res.status(409).json({ error: 'Ban already exists for this user/scope' }); } @@ -4541,7 +4549,7 @@ export class HTTPServer { // GET /api/registry/edit-bans - List active edit bans this.app.get('/api/registry/edit-bans', requireAuth, async (req, res) => { try { - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4557,6 +4565,7 @@ export class HTTPServer { }); return res.json({ bans }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to list edit bans'); return res.status(500).json({ error: 'Failed to list bans' }); } @@ -4565,7 +4574,7 @@ export class HTTPServer { // DELETE /api/registry/edit-bans/:id - Remove an edit ban this.app.delete('/api/registry/edit-bans/:id', requireAuth, async (req, res) => { try { - const isAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isAdmin = req.user && await isAuthenticatedUserAAOAdmin(req.user); if (!isAdmin) { return res.status(403).json({ error: 'Admin access required' }); } @@ -4576,6 +4585,7 @@ export class HTTPServer { } return res.json({ success: true }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to remove edit ban'); return res.status(500).json({ error: 'Failed to remove ban' }); } @@ -4710,7 +4720,7 @@ export class HTTPServer { // Check if user can delete (admin or creator) const devUser = getDevUser(req); const isDevAdmin = devUser?.isAdmin === true; - const isDbAdmin = req.user && await isWebUserAAOAdmin(req.user.id); + const isDbAdmin = !isDevAdmin && req.user && await isAuthenticatedUserAAOAdmin(req.user); const isAdmin = isDevAdmin || isDbAdmin; const isCreator = ref.contributed_by_email === req.user?.email; @@ -4721,6 +4731,7 @@ export class HTTPServer { await manifestRefsDb.deleteReference(ref.id); return res.json({ success: true }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error }, 'Failed to delete manifest ref'); return res.status(500).json({ error: 'Failed to delete reference' }); } @@ -6985,7 +6996,7 @@ export class HTTPServer { const { slug, filename } = req.params; const pool = getPool(); const userId = req.user?.id ?? null; - const userIsAdmin = userId ? await isWebUserAAOAdmin(userId) : false; + const userIsAdmin = req.user ? await isAuthenticatedUserAAOAdmin(req.user) : false; const perspResult = await pool.query( `SELECT p.id, @@ -7028,6 +7039,7 @@ export class HTTPServer { res.setHeader('Content-Length', asset.file_data.length); res.send(asset.file_data); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error, slug: req.params.slug }, 'Serve perspective asset error'); res.status(500).send('Failed to serve asset'); } @@ -8637,7 +8649,7 @@ ${p.category ? `${p.category}\n` : ''}${publishedUrl}< // Match requireAdmin: working-group authority with an explicit, // environment-managed break-glass fallback. - const isAdmin = (await resolveWebUserAAOAdminAccess(user.id, user.email)).isAdmin; + const isAdmin = (await resolveWebUserAAOAdminAccess(user)).isAdmin; // Check Slack sync status, seat type, and read DB names (user may have // set a display name that differs from the WorkOS session values) let isLinkedToSlack = false; @@ -8694,6 +8706,7 @@ ${p.category ? `${p.category}\n` : ''}${publishedUrl}< res.json(response); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get current user error:'); res.status(500).json({ error: 'Failed to get user info', @@ -10381,6 +10394,7 @@ ${p.category ? `${p.category}\n` : ''}${publishedUrl}< // Global error handler - logger.error() automatically captures to PostHog via error hook this.app.use((err: Error & { status?: number; statusCode?: number; type?: string }, req: express.Request, res: express.Response, _next: express.NextFunction) => { + if (respondToAdminAuthorizationError(err, res)) return; const status = err.status || err.statusCode || 500; // Range Not Satisfiable (416) from static file serving is a client error, not a server issue diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index b1e3c756f70..9e005c8e431 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -5,10 +5,10 @@ import { CompanyDatabase } from '../db/company-db.js'; import type { WorkOSUser, Company, CompanyUser, Ban } from '../types.js'; import { createLogger } from '../logger.js'; import { - decideAAOAdminAccess, type AAOAdminAccessMechanism, } from '../auth/admin-access.js'; -import { isWebUserAAOAdmin } from '../addie/mcp/admin-tools.js'; +import { resolveWebUserAAOAdminAccess } from '../addie/admin-status-lookup.js'; +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; import { bansDb } from '../db/bans-db.js'; import { isWorkOSApiKeyFormat } from './api-key-format.js'; import { verifyWorkOSJWT, looksLikeJWT } from '../auth/workos-jwt.js'; @@ -1605,10 +1605,13 @@ export async function requireAdmin(req: Request, res: Response, next: NextFuncti }); } - const decision = decideAAOAdminAccess( - await isWebUserAAOAdmin(req.user.id), - req.user.email, - ); + let decision; + try { + decision = await resolveWebUserAAOAdminAccess(req.user); + } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; + return next(error); + } if (!decision.isAdmin) { logger.warn({ userId: req.user.id, email: req.user.email }, 'Non-admin user attempted to access admin endpoint'); @@ -1744,17 +1747,28 @@ export function createRequireWorkingGroupLeader( // Match the platform-admin authority decision: aao-admin membership is // primary and ADMIN_EMAILS remains a centralized break-glass fallback. - // isWebUserAAOAdmin fails closed to false when its membership lookup fails. - const decision = decideAAOAdminAccess( - await isWebUserAAOAdmin(req.user.id), - req.user.email, - ); + let decision; + try { + decision = await resolveWebUserAAOAdminAccess(req.user); + } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; + return next(error); + } if (decision.isAdmin) { logger.debug({ userId: req.user.id, slug }, 'Admin access granted to working group'); return next(); } + // This reserved group is itself the platform authority. A linked canonical + // member/leader must not re-grant access after the exact credential failed. + if (slug === 'aao-admin') { + return res.status(403).json({ + error: 'Admin access required', + message: 'This working group is restricted to platform administrators', + }); + } + // Look up the working group const workingGroup = await workingGroupDb.getWorkingGroupBySlug(slug); if (!workingGroup) { @@ -1813,17 +1827,28 @@ export function createRequireWorkingGroupMember( // Match the platform-admin authority decision: aao-admin membership is // primary and ADMIN_EMAILS remains a centralized break-glass fallback. - // isWebUserAAOAdmin fails closed to false when its membership lookup fails. - const decision = decideAAOAdminAccess( - await isWebUserAAOAdmin(req.user.id), - req.user.email, - ); + let decision; + try { + decision = await resolveWebUserAAOAdminAccess(req.user); + } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; + return next(error); + } if (decision.isAdmin) { logger.debug({ userId: req.user.id, slug }, 'Admin access granted to working group'); return next(); } + // This reserved group is itself the platform authority. A linked canonical + // member/leader must not re-grant access after the exact credential failed. + if (slug === 'aao-admin') { + return res.status(403).json({ + error: 'Admin access required', + message: 'This working group is restricted to platform administrators', + }); + } + const workingGroup = await workingGroupDb.getWorkingGroupBySlug(slug); if (!workingGroup) { return res.status(404).json({ diff --git a/server/src/middleware/rate-limit.ts b/server/src/middleware/rate-limit.ts index 48cb015f9f9..32bf4bd4211 100644 --- a/server/src/middleware/rate-limit.ts +++ b/server/src/middleware/rate-limit.ts @@ -2,7 +2,6 @@ import rateLimit from 'express-rate-limit'; import type { IncrementResponse, Options, Store } from 'express-rate-limit'; import type { Request, Response } from 'express'; import { createLogger } from '../logger.js'; -import { isBreakGlassAdminEmail } from '../auth/admin-access.js'; import { CachedPostgresStore, PostgresStore, type WeightedIncrementStore } from './pg-rate-limit-store.js'; const logger = createLogger('rate-limit'); @@ -101,20 +100,17 @@ export const agentCardValidationRateLimiter = rateLimit({ * env var for emergency access, matching requireAdmin semantics. */ async function skipForAdmins(req: Request): Promise { - const user = (req as any).user as { id?: string; email?: string; isAdmin?: boolean } | undefined; + const user = (req as any).user as { id?: string; authWorkosUserId?: string; email?: string; isAdmin?: boolean } | undefined; if (!user) return false; - if (user.isAdmin === true) return true; - - if (isBreakGlassAdminEmail(user.email)) { - return true; - } + if ((req as Request & { isStaticAdminApiKey?: boolean }).isStaticAdminApiKey) return true; + if (process.env.NODE_ENV !== 'production' && user.id?.startsWith('user_dev_') && user.isAdmin === true) return true; if (!user.id) return false; try { - const { isWebUserAAOAdmin } = await import('../addie/mcp/admin-tools.js'); - return await isWebUserAAOAdmin(user.id); + const { isAuthenticatedUserAAOAdmin } = await import('../addie/admin-status-lookup.js'); + return await isAuthenticatedUserAAOAdmin({ ...user, id: user.id }); } catch (err) { logger.warn({ err, userId: user.id }, 'admin check failed in rate limiter; applying limit'); return false; diff --git a/server/src/routes/aao-admin.ts b/server/src/routes/aao-admin.ts index b88e410d56c..aed84c34f0b 100644 --- a/server/src/routes/aao-admin.ts +++ b/server/src/routes/aao-admin.ts @@ -64,7 +64,7 @@ export function createAAOAdminRouter(): Router { try { const membership = await workingGroupDb.grantAAOAdminMembership({ targetUserId: input.targetUserId, - actorUserId: req.user!.id, + actorUserId: req.user!.authWorkosUserId ?? req.user!.id, actorAuthorizationMechanism, reason: input.reason, }); @@ -86,7 +86,7 @@ export function createAAOAdminRouter(): Router { try { const revokedUserId = await workingGroupDb.revokeAAOAdminMembership({ targetUserId: input.targetUserId, - actorUserId: req.user!.id, + actorUserId: req.user!.authWorkosUserId ?? req.user!.id, actorAuthorizationMechanism, reason: input.reason, }); diff --git a/server/src/routes/addie-admin.ts b/server/src/routes/addie-admin.ts index bf544b55ed7..edbab990d8e 100644 --- a/server/src/routes/addie-admin.ts +++ b/server/src/routes/addie-admin.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Addie Admin routes module * @@ -1640,7 +1641,10 @@ Be specific and actionable. Focus on patterns that could help improve Addie's be } targetUserId = workosUserId; - content = await getWebHomeContent(workosUserId); + // This admin-only preview simulates the explicitly selected WorkOS + // credential, including its own email; no canonical identity lookup. + const previewCredential = await workos.userManagement.getUser(workosUserId); + content = await getWebHomeContent({ id: workosUserId, email: previewCredential.email }); } // Return based on format @@ -1659,6 +1663,7 @@ Be specific and actionable. Focus on patterns that could help improve Addie's be }); } } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, "Error previewing Addie Home"); res.status(500).json({ error: "Internal server error", diff --git a/server/src/routes/committees.ts b/server/src/routes/committees.ts index f0ad906d732..62243c10cd1 100644 --- a/server/src/routes/committees.ts +++ b/server/src/routes/committees.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Committee routes module * @@ -20,7 +21,8 @@ import { import { WorkingGroupDatabase } from "../db/working-group-db.js"; import { eventsDb } from "../db/events-db.js"; import { invalidateMemberContextCache } from "../addie/index.js"; -import { invalidateWebAdminStatusCache, isWebUserAAOAdmin } from "../addie/mcp/admin-tools.js"; +import { invalidateWebAdminStatusCache } from "../addie/admin-status-cache.js"; +import { isAuthenticatedUserAAOAdmin } from "../addie/admin-status-lookup.js"; import { syncWorkingGroupMembersFromSlack, syncAllWorkingGroupMembersFromSlack } from "../slack/sync.js"; import { notifyPublishedPost } from "../notifications/slack.js"; import { notifyUser } from "../notifications/notification-service.js"; @@ -243,13 +245,18 @@ export function createCommitteeRouters(): { * working group itself. As with the private group detail and posts routes, * private content is visible only to direct members; leadership, parent- * group membership, and site-admin status do not bypass that boundary. + * The reserved platform authority group instead requires the exact + * authenticated administrator credential, including independent break-glass. * Callers outside it receive the same 404 as they would for a missing group * so private group existence is not disclosed. */ const canViewWorkingGroupContent = async (req: Request, group: WorkingGroup): Promise => { + const user = req.user; + if (group.slug === 'aao-admin') { + return !!user?.id && await isAuthenticatedUserAAOAdmin(user); + } if (!group.is_private) return true; - const user = req.user; if (!user?.id) return false; return workingGroupDb.isMember(group.id, user.id); @@ -1007,30 +1014,24 @@ export function createCommitteeRouters(): { }); } - if (group.is_private) { - if (!user?.id) { - return res.status(404).json({ - error: 'Working group not found', - message: `No working group found with slug: ${slug}`, - }); - } - - const isMember = await workingGroupDb.isMember(group.id, user.id); - if (!isMember) { - return res.status(404).json({ - error: 'Working group not found', - message: `No working group found with slug: ${slug}`, - }); - } + if (!(await canViewWorkingGroupContent(req, group))) { + return res.status(404).json({ + error: 'Working group not found', + message: `No working group found with slug: ${slug}`, + }); } + const membershipUserId = group.slug === 'aao-admin' + ? user?.authWorkosUserId ?? user?.id + : user?.id; + const memberships = await workingGroupDb.getMembershipsByWorkingGroup(group.id); let isMember = false; let isFamilyMember = false; - if (user?.id) { - isMember = await workingGroupDb.isMember(group.id, user.id); - isFamilyMember = isMember || await workingGroupDb.isFamilyMember(group.id, user.id); + if (membershipUserId) { + isMember = await workingGroupDb.isMember(group.id, membershipUserId); + isFamilyMember = isMember || await workingGroupDb.isFamilyMember(group.id, membershipUserId); } // Hierarchy context: parent summary (if any) and list of direct subgroups @@ -1042,11 +1043,15 @@ export function createCommitteeRouters(): { // Private subgroups show up only for people who are direct members of // that subgroup, or for AAO admins. Parent membership alone does not // unlock private subgroup visibility. - const isAAOAdmin = user?.id ? await isWebUserAAOAdmin(user.id) : false; + const isAAOAdmin = user?.id ? await isAuthenticatedUserAAOAdmin(user) : false; const allSubgroups = await workingGroupDb.listSubgroups(group.id); const visibleSubgroups: typeof allSubgroups = []; for (const sg of allSubgroups) { if (sg.status !== 'active') continue; + if (sg.slug === 'aao-admin') { + if (isAAOAdmin) visibleSubgroups.push(sg); + continue; + } if (!sg.is_private || isAAOAdmin) { visibleSubgroups.push(sg); continue; @@ -1087,6 +1092,7 @@ export function createCommitteeRouters(): { is_family_member: isFamilyMember, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get working group error'); res.status(500).json({ error: 'Failed to get working group', @@ -1110,26 +1116,29 @@ export function createCommitteeRouters(): { }); } - let isMember = false; - if (user?.id) { - isMember = await workingGroupDb.isMember(group.id, user.id); + if (!(await canViewWorkingGroupContent(req, group))) { + return res.status(404).json({ + error: 'Working group not found', + message: `No working group found with slug: ${slug}`, + }); } - if (group.is_private) { - if (!user?.id || !isMember) { - return res.status(404).json({ - error: 'Working group not found', - message: `No working group found with slug: ${slug}`, - }); - } - } + const membershipUserId = group.slug === 'aao-admin' + ? user?.authWorkosUserId ?? user?.id + : user?.id; + const isMember = membershipUserId + ? await workingGroupDb.isMember(group.id, membershipUserId) + : false; // Aggregate from the group plus its subgroups the caller may see. // Private subgroups the caller isn't a member of are filtered out. const includeSubgroups = req.query.include_subgroups !== 'false'; - const isAAOAdmin = user?.id ? await isWebUserAAOAdmin(user.id) : false; + const isAAOAdmin = user?.id ? await isAuthenticatedUserAAOAdmin(user) : false; const targetIds = includeSubgroups - ? await workingGroupDb.getVisibleDescendantIds(group.id, user?.id ?? null, { isAdmin: isAAOAdmin }) + ? await workingGroupDb.getVisibleDescendantIds(group.id, membershipUserId ?? null, { + isAdmin: isAAOAdmin, + canViewReservedAdminGroup: isAAOAdmin, + }) : [group.id]; const result = await pool.query( @@ -1143,7 +1152,7 @@ export function createCommitteeRouters(): { WHERE p.working_group_id = ANY($1::uuid[]) AND p.status = 'published' AND (p.is_members_only = false OR $2 = true) ORDER BY p.published_at DESC NULLS LAST`, - [targetIds, isMember] + [targetIds, isMember || (group.slug === 'aao-admin' && isAAOAdmin)] ); const posts = result.rows.map(row => ({ @@ -1172,6 +1181,7 @@ export function createCommitteeRouters(): { res.json({ posts }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get working group posts error'); res.status(500).json({ error: 'Failed to get posts', @@ -1181,9 +1191,13 @@ export function createCommitteeRouters(): { // GET /api/working-groups/:slug/events - Get events for a committee publicApiRouter.get('/:slug/events', optionalAuth, async (req: Request, res: Response) => { + const user = req.user ? Object.freeze({ + id: req.user.id, + authWorkosUserId: req.user.authWorkosUserId, + email: req.user.email, + }) : null; try { const { slug } = req.params; - const user = req.user; const group = await workingGroupDb.getWorkingGroupBySlug(slug); @@ -1194,15 +1208,31 @@ export function createCommitteeRouters(): { }); } + // Resolve exact authority independently of include_subgroups. That + // query may select the response shape, never whether authorization runs. + const isAAOAdmin = user ? await isAuthenticatedUserAAOAdmin(user) : false; + if (group.slug === 'aao-admin' && !isAAOAdmin) { + return res.status(404).json({ + error: 'Working group not found', + message: `No working group found with slug: ${slug}`, + }); + } + + const membershipUserId = group.slug === 'aao-admin' + ? user?.authWorkosUserId ?? user?.id + : user?.id; const includeSubgroups = req.query.include_subgroups !== 'false'; const targetIds = includeSubgroups - ? await workingGroupDb.getVisibleDescendantIds(group.id, user?.id ?? null) + ? await workingGroupDb.getVisibleDescendantIds(group.id, membershipUserId ?? null, { + canViewReservedAdminGroup: isAAOAdmin, + }) : [group.id]; const events = await eventsDb.getEventsByCommittee(targetIds, { includeUnpublished: false }); res.json(events); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get committee events error'); res.status(500).json({ error: 'Failed to get events', @@ -1739,7 +1769,10 @@ export function createCommitteeRouters(): { // Don't expose internal content to non-leaders const user = req.user; - const isLeader = user && await workingGroupDb.isLeader(group.id, user.id); + const leadershipUserId = group.slug === 'aao-admin' + ? user?.authWorkosUserId ?? user?.id + : user?.id; + const isLeader = leadershipUserId && await workingGroupDb.isLeader(group.id, leadershipUserId); const publicDocuments = documents.map(doc => ({ id: doc.id, @@ -1763,6 +1796,7 @@ export function createCommitteeRouters(): { res.json({ documents: publicDocuments }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get committee documents error'); res.status(500).json({ error: 'Failed to get documents', @@ -1781,6 +1815,7 @@ export function createCommitteeRouters(): { const activity = await workingGroupDb.getRecentActivity(group.id); res.json({ activity }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get committee activity error'); res.status(500).json({ error: 'Failed to get activity', @@ -1811,6 +1846,7 @@ export function createCommitteeRouters(): { res.json({ summary }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Get committee summary error'); res.status(500).json({ error: 'Failed to get summary', @@ -2012,6 +2048,7 @@ export function createCommitteeRouters(): { res.setHeader('Content-Length', fileData.file_data.length); res.send(fileData.file_data); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Serve committee document file error'); res.status(500).json({ error: 'Failed to serve file' }); } @@ -2202,10 +2239,11 @@ export function createCommitteeRouters(): { 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'", 'Content-Disposition': 'inline', - 'Cache-Control': group.is_private ? 'private, no-cache' : 'public, max-age=86400', + 'Cache-Control': group.slug === 'aao-admin' || group.is_private ? 'private, no-cache' : 'public, max-age=86400', }); return res.send(asset.asset_data); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error, assetId: req.params.assetId }, 'Failed to serve document asset'); res.status(500).send('Internal error'); } @@ -2235,6 +2273,7 @@ export function createCommitteeRouters(): { url: `/api/working-groups/assets/${a.id}`, }))); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Failed to list document assets'); res.status(500).json({ error: 'Failed to list assets' }); } diff --git a/server/src/routes/community-mirrors.ts b/server/src/routes/community-mirrors.ts index 28604698804..b442c2d1751 100644 --- a/server/src/routes/community-mirrors.ts +++ b/server/src/routes/community-mirrors.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Community-mirror catalog lifecycle API (#2176). * @@ -17,7 +18,7 @@ */ import { Router } from 'express'; -import type { Request, RequestHandler, Response } from 'express'; +import type { Request, RequestHandler, Response, NextFunction } from 'express'; import type { PoolClient } from 'pg'; import { createHash } from 'node:crypto'; import { z } from 'zod'; @@ -27,7 +28,7 @@ import { PublisherDatabase } from '../db/publisher-db.js'; import type { CatalogEventsDatabase } from '../db/catalog-events-db.js'; import { getClient } from '../db/client.js'; import { isRegistryModerator } from '../services/brand-logo-auth.js'; -import { isWebUserAAOAdmin } from '../addie/admin-status-lookup.js'; +import { isAuthenticatedUserAAOAdmin, type AAOAdminPrincipal } from '../addie/admin-status-lookup.js'; import { validateAdagentsDocument } from '../services/adagents-schema-validator.js'; import { registryReadRateLimiter, brandCreationRateLimiter } from '../middleware/rate-limit.js'; import { createLogger } from '../logger.js'; @@ -86,18 +87,19 @@ export interface CommunityMirrorRouterConfig { * Organization API keys represent an organization, not a human working-group * member, so they intentionally submit proposals instead of passing this gate. */ -async function canManageMirrors(userId: string): Promise { +async function canManageMirrors(user: AAOAdminPrincipal): Promise { + const userId = user.authWorkosUserId ?? user.id; if (userId === 'admin_api_key') return true; if (userId.startsWith('api_key_')) return false; const [isOrganizationAdmin, isModerator] = await Promise.all([ - isWebUserAAOAdmin(userId), + isAuthenticatedUserAAOAdmin(user), isRegistryModerator(userId), ]); return isOrganizationAdmin || isModerator; } async function resolveManager( - req: { user?: { id?: string } }, + req: { user?: AAOAdminPrincipal }, res: Response ): Promise { const userId = req.user?.id; @@ -105,7 +107,7 @@ async function resolveManager( res.status(401).json({ error: 'Authentication required' }); return null; } - if (!(await canManageMirrors(userId))) { + if (!(await canManageMirrors(req.user!))) { res.status(403).json({ error: 'Only registry moderators or AgenticAdvertising.org administrators can manage community mirrors', }); @@ -205,7 +207,7 @@ export function createCommunityMirrorRouter(config: CommunityMirrorRouterConfig) if (req.query.review_queue !== undefined && !['true', 'false'].includes(String(req.query.review_queue))) { return res.status(400).json({ error: 'Invalid review_queue flag' }); } - const isManager = await canManageMirrors(userId); + const isManager = await canManageMirrors(req.user!); if (reviewQueue && !isManager) { return res.status(403).json({ error: 'Registry moderator access is required for the review queue' }); } @@ -241,7 +243,7 @@ export function createCommunityMirrorRouter(config: CommunityMirrorRouterConfig) try { const proposal = await mirrorDb.getProposalById(proposalId); if (!proposal) return res.status(404).json({ error: 'Community mirror proposal not found' }); - const isManager = await canManageMirrors(userId); + const isManager = await canManageMirrors(req.user!); const organizationId = isManager ? null : await callerOrganizationId(req); const ownsProposal = organizationId ? proposal.proposed_by_organization_id === organizationId @@ -251,6 +253,7 @@ export function createCommunityMirrorRouter(config: CommunityMirrorRouterConfig) } return res.json({ proposal: proposalForResponse(proposal, isManager) }); } catch (err) { + if (respondToAdminAuthorizationError(err, res)) return; logger.error({ err, proposalId }, 'Failed to read community mirror proposal'); return res.status(500).json({ error: 'Failed to read community mirror proposal' }); } @@ -454,7 +457,7 @@ export function createCommunityMirrorRouter(config: CommunityMirrorRouterConfig) const userId = req.user?.id; if (!userId) return res.status(401).json({ error: 'Authentication required' }); - const isManager = await canManageMirrors(userId); + const isManager = await canManageMirrors(req.user!); const organizationId = isManager ? null : await callerOrganizationId(req); if (!isManager && !organizationId) { return res.status(403).json({ error: 'Organization context is required to propose a community mirror' }); @@ -653,5 +656,10 @@ export function createCommunityMirrorRouter(config: CommunityMirrorRouterConfig) } }); + router.use((error: unknown, _req: Request, res: Response, next: NextFunction) => { + if (respondToAdminAuthorizationError(error, res)) return; + next(error); + }); + return router; } diff --git a/server/src/routes/content.ts b/server/src/routes/content.ts index cd3ea6665a7..0e4586abb9d 100644 --- a/server/src/routes/content.ts +++ b/server/src/routes/content.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Content routes module * @@ -16,7 +17,6 @@ import { createLogger } from '../logger.js'; import { requireAuth } from '../middleware/auth.js'; import { contentProposeRateLimiter, contentFetchUrlRateLimiter, contentAssetUploadRateLimiter } from '../middleware/rate-limit.js'; import { getPool } from '../db/client.js'; -import { isWebUserAAOAdmin } from '../addie/mcp/admin-tools.js'; import { isAuthenticatedUserAAOAdmin, type AAOAdminPrincipal } from '../addie/admin-status-lookup.js'; import { sendChannelMessage } from '../slack/client.js'; import type { SlackBlockMessage } from '../slack/types.js'; @@ -352,25 +352,43 @@ async function getUserInfo(userId: string): Promise<{ name: string } | null> { * User context for direct function calls (from Addie or other internal services) */ export interface ContentUser { - id: string; - email?: string; - /** Explicit null means a person-only context with no administrative or committee-leader authority. */ - adminPrincipal?: AAOAdminPrincipal | null; + readonly id: string; + readonly email?: string; + /** Missing/null provenance grants no authenticated credential authority. */ + readonly adminPrincipal?: Readonly | null; +} + +type AuthenticatedContentUser = Readonly & { + readonly adminPrincipal: Readonly; +}; + +/** Capture authenticated authority before asynchronous work can mutate req.user. */ +function captureAuthenticatedContentUser(user: AAOAdminPrincipal): AuthenticatedContentUser { + const principal = Object.freeze({ + id: user.authWorkosUserId ?? user.id, + email: user.email, + }); + return Object.freeze({ + id: user.id, + email: user.email ?? undefined, + adminPrincipal: principal, + }); +} + +/** Only legacy in-process publishers may omit provenance for a system actor. */ +function isSystemContentUser(user: ContentUser): boolean { + return user.adminPrincipal === undefined && user.id.startsWith('system:'); } /** Keep profile attribution separate from credential-scoped review authority. */ function contentAuthorizationUserId(user: ContentUser): string | null { - if (user.adminPrincipal === null) return null; return user.adminPrincipal ? user.adminPrincipal.authWorkosUserId ?? user.adminPrincipal.id - : user.id; // Legacy internal/HTTP callers; migrated web callers supply provenance. + : isSystemContentUser(user) ? user.id : null; } async function isContentUserAAOAdmin(user: ContentUser): Promise { - if (user.adminPrincipal === null) return false; - if (user.adminPrincipal) return isAuthenticatedUserAAOAdmin(user.adminPrincipal); - // Preserve existing HTTP callers until their separate authorization sweep. - return isWebUserAAOAdmin(user.id); + return user.adminPrincipal ? isAuthenticatedUserAAOAdmin(user.adminPrincipal) : false; } /** @@ -427,8 +445,11 @@ export async function proposeContentForUser( // Membership tier gate — Professional+ required for content submission. // System users (system:* prefix) and site admins are exempt, matching the // rate-limiter carve-out and the existing admin bypass pattern below. - if (!user.id.startsWith('system:') && !(await isContentUserAAOAdmin(user))) { - const eligible = await checkContentSubmissionTier(user.id); + const authorizationUserId = contentAuthorizationUserId(user); + if (!isSystemContentUser(user) && !(await isContentUserAAOAdmin(user))) { + const eligible = authorizationUserId !== null + && !authorizationUserId.startsWith('system:') + && await checkContentSubmissionTier(authorizationUserId); if (!eligible) { logger.warn({ userId: user.id }, 'proposeContentForUser blocked — insufficient membership tier'); return { @@ -514,7 +535,7 @@ export async function proposeContentForUser( const membershipResult = await pool.query( `SELECT 1 FROM working_group_memberships WHERE working_group_id = $1 AND workos_user_id = $2 AND status = 'active'`, - [committeeId, user.id] + [committeeId, authorizationUserId] ); if (membershipResult.rows.length === 0) { logger.warn({ committeeSlug, userId: user.id }, 'Content proposal failed: user not a member'); @@ -1170,7 +1191,7 @@ export function createContentRouter(): Router { // GET /api/content/collections - Get available collections for content submission router.get('/collections', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const pool = getPool(); // Get public collections (anyone can submit) @@ -1198,7 +1219,7 @@ export function createContentRouter(): Router { AND wg.accepts_public_submissions = FALSE AND wg.status = 'active' ORDER BY wg.name`, - [user.id] + [contentAuthorizationUserId(user)] ); const collections = [ @@ -1230,9 +1251,9 @@ export function createContentRouter(): Router { // POST /api/content/propose - Submit content to any collection router.post('/propose', requireAuth, contentProposeRateLimiter, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const result = await proposeContentForUser( - { id: user.id, email: user.email }, + user, req.body as ProposeContentRequest ); @@ -1257,6 +1278,7 @@ export function createContentRouter(): Router { message: result.message, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'POST /api/content/propose error'); res.status(500).json({ error: 'Failed to propose content', @@ -1267,14 +1289,15 @@ export function createContentRouter(): Router { // GET /api/content/pending - List pending content user can review router.get('/pending', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const committeeSlug = req.query.committee_slug as string | undefined; const result = await listPendingContentForUser( - { id: user.id, email: user.email }, + user, { committeeSlug } ); res.json(result); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'GET /api/content/pending error'); res.status(500).json({ error: 'Failed to get pending content', @@ -1285,12 +1308,12 @@ export function createContentRouter(): Router { // POST /api/content/:id/approve - Approve pending content router.post('/:id/approve', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const { publish_immediately = true } = req.body; const result = await approveContentForUser( - { id: user.id, email: user.email }, + user, id, { publishImmediately: publish_immediately } ); @@ -1313,6 +1336,7 @@ export function createContentRouter(): Router { message: result.message, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'POST /api/content/:id/approve error'); res.status(500).json({ error: 'Failed to approve content', @@ -1410,12 +1434,12 @@ export function createContentRouter(): Router { // POST /api/content/:id/reject - Reject pending content router.post('/:id/reject', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const { reason } = req.body; const result = await rejectContentForUser( - { id: user.id, email: user.email }, + user, id, reason ); @@ -1439,6 +1463,7 @@ export function createContentRouter(): Router { message: result.message, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'POST /api/content/:id/reject error'); res.status(500).json({ error: 'Failed to reject content', @@ -1449,12 +1474,12 @@ export function createContentRouter(): Router { // POST /api/content/:id/request-revisions - Request revisions (non-terminal) router.post('/:id/request-revisions', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const { notes } = req.body; const result = await requestRevisionsForUser( - { id: user.id, email: user.email }, + user, id, notes ); @@ -1474,6 +1499,7 @@ export function createContentRouter(): Router { res.json({ success: true, status: result.status, message: result.message }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'POST /api/content/:id/request-revisions error'); res.status(500).json({ error: 'Failed to request revisions' }); } @@ -1482,11 +1508,11 @@ export function createContentRouter(): Router { // POST /api/content/:id/resubmit - Author resubmits after revisions router.post('/:id/resubmit', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const result = await resubmitContentForUser( - { id: user.id, email: user.email }, + user, id ); @@ -1550,7 +1576,7 @@ export function createContentRouter(): Router { }, async (req: any, res: any) => { try { const { slug } = req.params; - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const file = req.file; const assetType = req.body.asset_type as string; @@ -1590,7 +1616,7 @@ export function createContentRouter(): Router { const perspectiveId = perspResult.rows[0].id; // Check permission: must be author, proposer, or admin - const userIsAdmin = await isWebUserAAOAdmin(user.id); + const userIsAdmin = await isContentUserAAOAdmin(user); if (!userIsAdmin) { const authorCheck = await pool.query( `SELECT 1 FROM perspectives WHERE id = $1 AND (author_user_id = $2 OR proposer_user_id = $2) @@ -1652,6 +1678,7 @@ export function createContentRouter(): Router { res.status(201).json({ asset: { ...asset, url: assetUrl } }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Upload perspective asset error'); res.status(500).json({ error: 'Failed to upload asset' }); } @@ -1670,13 +1697,14 @@ export function createMyContentRouter(): Router { // GET /api/me/content - Get all content where user has a relationship router.get('/', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const status = req.query.status as string | undefined; const collection = req.query.collection as string | undefined; const relationship = req.query.relationship as string | undefined; const limit = parseInt(req.query.limit as string); const result = await listMyContentService({ userId: user.id, + adminPrincipal: user.adminPrincipal, status, collection, relationship, @@ -1684,6 +1712,7 @@ export function createMyContentRouter(): Router { }); res.json({ items: result.items }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; if (error instanceof MyContentError && error.is('invalid_status')) { return res.status(400).json({ error: 'Invalid status', @@ -1698,7 +1727,7 @@ export function createMyContentRouter(): Router { // PUT /api/me/content/:id - Update content user owns router.put('/:id', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const { title, @@ -1740,9 +1769,9 @@ export function createMyContentRouter(): Router { [id, user.id] ).then(r => r.rows.length > 0); const userIsLead = contentItem.working_group_id - ? await isCommitteeLead(contentItem.working_group_id, user.id) + ? await isCommitteeLead(contentItem.working_group_id, contentAuthorizationUserId(user)) : false; - const userIsAdmin = await isWebUserAAOAdmin(user.id); + const userIsAdmin = await isContentUserAAOAdmin(user); if (!isProposer && !isAuthor && !userIsLead && !userIsAdmin) { return res.status(403).json({ @@ -1956,6 +1985,7 @@ export function createMyContentRouter(): Router { res.json(result.rows[0]); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'PUT /api/me/content/:id error'); res.status(500).json({ error: 'Failed to update content', @@ -1968,7 +1998,7 @@ export function createMyContentRouter(): Router { // pending-review items. Admins can delete anything (including published). router.delete('/:id', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; const pool = getPool(); @@ -1991,9 +2021,9 @@ export function createMyContentRouter(): Router { [id, user.id] ).then(r => r.rows.length > 0); const userIsLead = contentItem.working_group_id - ? await isCommitteeLead(contentItem.working_group_id, user.id) + ? await isCommitteeLead(contentItem.working_group_id, contentAuthorizationUserId(user)) : false; - const userIsAdmin = await isWebUserAAOAdmin(user.id); + const userIsAdmin = await isContentUserAAOAdmin(user); if (!isProposer && !isAuthor && !userIsLead && !userIsAdmin) { return res.status(403).json({ @@ -2015,6 +2045,7 @@ export function createMyContentRouter(): Router { logger.info({ contentId: id, userId: user.id, title: contentItem.title }, 'Content deleted by owner'); res.json({ success: true }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'DELETE /api/me/content/:id error'); res.status(500).json({ error: 'Failed to delete content' }); } @@ -2023,18 +2054,10 @@ export function createMyContentRouter(): Router { // POST /api/me/content/:id/authors - Add co-author to content router.post('/:id/authors', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id } = req.params; - const { user_id, display_name, display_title } = req.body; const pool = getPool(); - if (!user_id || !display_name) { - return res.status(400).json({ - error: 'Missing required fields', - message: 'user_id and display_name are required', - }); - } - // Check ownership const contentResult = await pool.query( `SELECT p.*, wg.slug as committee_slug @@ -2056,9 +2079,9 @@ export function createMyContentRouter(): Router { // Check permission const isProposer = contentItem.proposer_user_id === user.id; const userIsLead = contentItem.working_group_id - ? await isCommitteeLead(contentItem.working_group_id, user.id) + ? await isCommitteeLead(contentItem.working_group_id, contentAuthorizationUserId(user)) : false; - const userIsAdmin = await isWebUserAAOAdmin(user.id); + const userIsAdmin = await isContentUserAAOAdmin(user); if (!isProposer && !userIsLead && !userIsAdmin) { return res.status(403).json({ @@ -2067,6 +2090,17 @@ export function createMyContentRouter(): Router { }); } + // Authorize the authenticated principal against stored content before + // interpreting the requested author. Body fields never control whether + // the ownership, committee, or platform authorization checks run. + const { user_id, display_name, display_title } = req.body; + if (!user_id || !display_name) { + return res.status(400).json({ + error: 'Missing required fields', + message: 'user_id and display_name are required', + }); + } + // Verify the target user exists — prevents FK violation from surfacing as 500 const userCheck = await pool.query( `SELECT 1 FROM users WHERE workos_user_id = $1`, @@ -2102,6 +2136,7 @@ export function createMyContentRouter(): Router { res.status(201).json(result.rows[0]); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'POST /api/me/content/:id/authors error'); res.status(500).json({ error: 'Failed to add author', @@ -2112,7 +2147,7 @@ export function createMyContentRouter(): Router { // DELETE /api/me/content/:id/authors/:authorId - Remove co-author from content router.delete('/:id/authors/:authorId', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = captureAuthenticatedContentUser(req.user!); const { id, authorId } = req.params; const pool = getPool(); @@ -2137,9 +2172,9 @@ export function createMyContentRouter(): Router { // Check permission const isProposer = contentItem.proposer_user_id === user.id; const userIsLead = contentItem.working_group_id - ? await isCommitteeLead(contentItem.working_group_id, user.id) + ? await isCommitteeLead(contentItem.working_group_id, contentAuthorizationUserId(user)) : false; - const userIsAdmin = await isWebUserAAOAdmin(user.id); + const userIsAdmin = await isContentUserAAOAdmin(user); if (!isProposer && !userIsLead && !userIsAdmin) { return res.status(403).json({ @@ -2165,6 +2200,7 @@ export function createMyContentRouter(): Router { res.json({ success: true, deleted: authorId }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'DELETE /api/me/content/:id/authors/:authorId error'); res.status(500).json({ error: 'Failed to remove author', diff --git a/server/src/routes/events.ts b/server/src/routes/events.ts index c382fe39a62..03c6a8527c6 100644 --- a/server/src/routes/events.ts +++ b/server/src/routes/events.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Events routes module * @@ -40,8 +41,7 @@ import { WorkingGroupDatabase } from "../db/working-group-db.js"; import { createChannel, setChannelPurpose, sendDirectMessage } from "../slack/client.js"; import { SlackDatabase } from "../db/slack-db.js"; import { EmailPreferencesDatabase } from "../db/email-preferences-db.js"; -import { isWebUserAAOAdmin } from "../addie/admin-status-lookup.js"; -import { isBreakGlassAdminEmail } from "../auth/admin-access.js"; +import { isAuthenticatedUserAAOAdmin } from "../addie/admin-status-lookup.js"; import { getWorkos } from "../auth/workos-client.js"; import { resolveUserOrgMembership } from "../utils/resolve-user-org-membership.js"; @@ -1741,10 +1741,7 @@ export function createEventsRouter(): { let isDraftPreview = false; if (!["published", "completed"].includes(event.status)) { const user = req.user; - const isAdmin = !!user && ( - isBreakGlassAdminEmail(user.email) || - await isWebUserAAOAdmin(user.id) - ); + const isAdmin = !!user && await isAuthenticatedUserAAOAdmin(user); if (!isAdmin) { return res.status(404).json({ error: "Event not found", @@ -1859,6 +1856,7 @@ export function createEventsRouter(): { draft_preview: isDraftPreview, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, "Error getting event"); res.status(500).json({ error: "Failed to get event", diff --git a/server/src/routes/organizations.ts b/server/src/routes/organizations.ts index ec0c2050dd1..0093a9077d5 100644 --- a/server/src/routes/organizations.ts +++ b/server/src/routes/organizations.ts @@ -1,3 +1,4 @@ +import { respondToAdminAuthorizationError } from '../auth/admin-authorization-response.js'; /** * Organization routes module * @@ -29,7 +30,7 @@ import { getCompanyDomain } from "../utils/email-domain.js"; import { resolveUserRole } from "../utils/resolve-user-role.js"; import { resolveUserOrgMembership } from "../utils/resolve-user-org-membership.js"; import { isValidWorkOSMembershipId } from "../utils/workos-validation.js"; -import { isWebUserAAOAdmin } from "../addie/mcp/admin-tools.js"; +import { AAOAdminLookupUnavailableError, isAuthenticatedUserAAOAdmin } from "../addie/admin-status-lookup.js"; import { createStripeCustomer, createCustomerPortalSession, @@ -1508,17 +1509,17 @@ export function createOrganizationsRouter(): Router { // auto_provision_brand_hierarchy_children) router.patch('/:orgId/settings', requireAuth, async (req, res) => { try { - const user = req.user!; + const user = Object.freeze({ id: req.user!.id }); + const principal = Object.freeze({ + id: req.user!.authWorkosUserId ?? req.user!.id, + email: req.user!.email, + }); + const isStaticAdminApiKey = + (req as Request & { isStaticAdminApiKey?: boolean }).isStaticAdminApiKey === true; const { orgId } = req.params; - const { - company_type, - revenue_tier, - auto_provision_verified_domain, - auto_provision_brand_hierarchy_children, - } = req.body; // Verify user is member of this organization with owner or admin role - const membership = await resolveUserOrgMembership(workos, user.id, orgId); + const membership = await resolveUserOrgMembership(workos, principal.id, orgId); if (!membership) { return res.status(403).json({ error: 'Access denied', @@ -1535,6 +1536,20 @@ export function createOrganizationsRouter(): Router { }); } + // Resolve the privilege-grant capability from trusted authority before + // request fields decide which settings to write. Preserve ordinary + // settings updates when only the separate platform lookup is unavailable. + let canChangeAutoProvision = userRole === 'owner' || isStaticAdminApiKey; + let autoProvisionLookupError: AAOAdminLookupUnavailableError | undefined; + if (!canChangeAutoProvision) { + try { + canChangeAutoProvision = await isAuthenticatedUserAAOAdmin(principal); + } catch (error) { + if (!(error instanceof AAOAdminLookupUnavailableError)) throw error; + autoProvisionLookupError = error; + } + } + // Check if organization is personal (cannot have company type/revenue tier) const org = await orgDb.getOrganization(orgId); if (!org) { @@ -1551,6 +1566,13 @@ export function createOrganizationsRouter(): Router { }); } + const { + company_type, + revenue_tier, + auto_provision_verified_domain, + auto_provision_brand_hierarchy_children, + } = req.body; + // Validate company_type if provided if (company_type !== undefined && company_type !== null && !COMPANY_TYPE_VALUES.includes(company_type)) { return res.status(400).json({ @@ -1591,14 +1613,12 @@ export function createOrganizationsRouter(): Router { // unilaterally (admins can promote auto-joined members to admin under // the role-cap policy). Restrict to owner-only. AAO super-admin (or // the static admin API key for internal tooling) can override. - const isPrivilegeGrant = - auto_provision_verified_domain !== undefined || - auto_provision_brand_hierarchy_children !== undefined; - if (isPrivilegeGrant && userRole !== 'owner') { - const isStaticAdminApiKey = - (req as Request & { isStaticAdminApiKey?: boolean }).isStaticAdminApiKey === true; - const isAAOAdmin = isStaticAdminApiKey || (await isWebUserAAOAdmin(user.id)); - if (!isAAOAdmin) { + if (!canChangeAutoProvision) { + if ( + auto_provision_verified_domain !== undefined + || auto_provision_brand_hierarchy_children !== undefined + ) { + if (autoProvisionLookupError) throw autoProvisionLookupError; return res.status(403).json({ error: 'Insufficient permissions', message: 'Only owners can change auto-provisioning settings', @@ -1668,6 +1688,7 @@ export function createOrganizationsRouter(): Router { : org.auto_provision_brand_hierarchy_children, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error }, 'Update organization settings error'); res.status(500).json({ error: 'Failed to update organization settings', @@ -2897,7 +2918,7 @@ export function createOrganizationsRouter(): Router { : await resolveUserOrgMembership(workos, user.id, orgId); const callerOrgRole = callerMembership?.role ?? null; const isAAOAdmin = - isStaticAdminApiKey || (await isWebUserAAOAdmin(user.id)); + isStaticAdminApiKey || (await isAuthenticatedUserAAOAdmin(user)); const isOrgAdminOrOwner = callerOrgRole === 'admin' || callerOrgRole === 'owner'; const isOrgOwner = callerOrgRole === 'owner'; @@ -3229,6 +3250,7 @@ export function createOrganizationsRouter(): Router { previous_role: rawCurrentRole, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; const errorMessage = error instanceof Error ? error.message : 'Unknown error'; logger.error( { err: error, errorMessage, orgId, email: normalizedEmail, role }, diff --git a/server/src/routes/registry-api.ts b/server/src/routes/registry-api.ts index 7753120a56f..d565954f73a 100644 --- a/server/src/routes/registry-api.ts +++ b/server/src/routes/registry-api.ts @@ -189,9 +189,8 @@ import { sdkSafeFetch, withSdkSafeTransport } from "../utils/sdk-safe-fetch.js"; import { getRequestLog, getRequestCount, logOutboundRequest } from "../db/outbound-log-db.js"; import { enrichUserWithMembership } from "../utils/html-config.js"; import { classifyProbeError } from "../utils/probe-error.js"; -import { isWebUserAAOAdmin } from "../addie/admin-status-lookup.js"; -import { isBreakGlassAdminEmail } from "../auth/admin-access.js"; -import { getDevUser, isDevModeEnabled } from "../middleware/auth.js"; +import { isAuthenticatedUserAAOAdmin, type AAOAdminPrincipal } from "../addie/admin-status-lookup.js"; +import { respondToAdminAuthorizationError } from "../auth/admin-authorization-response.js"; import { OrganizationDatabase, hasApiAccess, resolveMembershipTier } from "../db/organization-db.js"; import { resolveCallerOrgId } from "./helpers/resolve-caller-org.js"; import { canonicalizeAgentUrl, PublisherDatabase } from "../db/publisher-db.js"; @@ -217,6 +216,11 @@ import { } from "../db/compliance-refresh-requests-db.js"; import { ComplianceRefreshQueue } from "../services/compliance-refresh-queue.js"; +const RegistryAdminAuthorizationUnavailableSchema = z.object({ + error: z.literal('admin_authorization_unavailable'), + message: z.string(), +}); + type PublisherBrandSummary = { name?: string; description?: string; @@ -1960,17 +1964,17 @@ registry.registerPath({ }, }, 503: { - description: "Publisher crawl is temporarily busy", + description: "Publisher crawl is temporarily busy, or administrator authorization could not be checked", headers: z.object({ "Retry-After": z.string().openapi({ description: "Seconds to wait before retrying" }), }), content: { "application/json": { - schema: z.object({ + schema: z.union([RegistryAdminAuthorizationUnavailableSchema, z.object({ error: z.string(), code: z.literal("publisher_crawl_busy"), retry_after: z.number().int().openapi({ description: "Seconds to wait before retrying" }), - }), + })]), }, }, }, @@ -2008,6 +2012,11 @@ registry.registerPath({ }, }, 500: { description: "Crawl failed", content: { "application/json": { schema: ErrorSchema } } }, + 503: { + description: "Administrator authorization could not be checked", + headers: z.object({ "Retry-After": z.string() }), + content: { "application/json": { schema: RegistryAdminAuthorizationUnavailableSchema } }, + }, }, }); @@ -3443,17 +3452,17 @@ registry.registerPath({ 401: { description: "Authentication required", content: { "application/json": { schema: ErrorSchema } } }, 404: { description: "Crawl request not found", content: { "application/json": { schema: ErrorSchema } } }, 503: { - description: "Crawl status is temporarily unavailable", + description: "Crawl status or administrator authorization is temporarily unavailable", headers: z.object({ "Retry-After": z.string().openapi({ description: "Seconds to wait before retrying" }), }), content: { "application/json": { - schema: z.object({ + schema: z.union([RegistryAdminAuthorizationUnavailableSchema, z.object({ error: z.string(), code: z.literal("crawl_status_unavailable"), retry_after: z.number().int(), - }), + })]), }, }, }, @@ -4175,7 +4184,7 @@ registry.registerPath({ operationId: "refreshAgent", summary: "Refresh agent snapshot", description: - "Re-probe the agent and update its registry health (online, tools_count, response_time_ms), capability snapshot (inferred type, discovered tools), and compliance verdict (storyboard pass/fail counts). Use after fixing your agent so the registry shows fresh data without waiting for the periodic heartbeat (~1h).\n\n**Compliance re-run:** when the caller owns the agent or is an AAO admin and the capability probe succeeds, the full storyboard suite can run for several minutes on capability-rich agents with a fresh test session, and `agent_storyboard_status` is updated. Owner-triggered runs use `triggered_by: 'owner_test'`; admin-triggered support runs use `triggered_by: 'manual'`. Badge fan-out reissues verification badges off the new run. If the compliance call fails (timeout, OAuth wall, internal error), the capability/health portion still returns successfully — `compliance.ran` is `false` with an `error` string.\n\n**Auth:** owner of the agent, AAO admin, or static `ADMIN_API_KEY`.\n\n**Rate limits:** 60 seconds per agent URL, 30 requests per user per hour.", + "Re-probe the agent and update its registry health (online, tools_count, response_time_ms), capability snapshot (inferred type, discovered tools), and compliance verdict (storyboard pass/fail counts). Use after fixing your agent so the registry shows fresh data without waiting for the periodic heartbeat (~1h).\n\n**Compliance re-run:** when the caller owns the agent or is an AAO admin and the capability probe succeeds, the full storyboard suite can run for several minutes on capability-rich agents with a fresh test session, and `agent_storyboard_status` is updated. Owner-triggered runs use `triggered_by: 'owner_test'`; admin-triggered support runs use `triggered_by: 'manual'`. Badge fan-out reissues verification badges off the new run. If the compliance call fails (timeout, OAuth wall, internal error), the capability/health portion still returns successfully — `compliance.ran` is `false` with an `error` string.\n\n**Auth:** owner of the agent, AAO admin, or static `ADMIN_API_KEY`. Human submissions are temporarily fenced with HTTP 503 until durable authorization provenance is supported; static admin API key submissions remain available.\n\n**Rate limits:** 60 seconds per agent URL, 30 requests per user per hour.", tags: ["Agent Compliance"], security: [{ bearerAuth: [] }, { oauth2: [] }], request: { @@ -4275,7 +4284,14 @@ registry.registerPath({ }, 500: { description: "Refresh failed after durable execution", content: { "application/json": { schema: ErrorSchema } } }, 502: { description: "Probe failed (timeout, DNS, OAuth wall, etc.)", content: { "application/json": { schema: ErrorSchema } } }, - 503: { description: "Durable refresh queue unavailable or at capacity", content: { "application/json": { schema: ErrorSchema } } }, + 503: { + description: "Refresh queue or authorization unavailable. All human submissions are temporarily fenced with refresh_authorization_provenance_required; only static admin API key submissions are supported.", + headers: z.object({ "Retry-After": z.string() }), + content: { "application/json": { schema: z.union([ + RegistryAdminAuthorizationUnavailableSchema, + z.object({ error: z.string(), code: z.string(), retry_after: z.number().int() }), + ]) } }, + }, }, }); @@ -4336,7 +4352,7 @@ registry.registerPath({ }, }, }, - 503: { description: "Refresh status temporarily unavailable", content: { "application/json": { schema: ErrorSchema } } }, + 503: { description: "Refresh status or administrator authorization temporarily unavailable", content: { "application/json": { schema: z.union([RegistryAdminAuthorizationUnavailableSchema, ErrorSchema]) } } }, }, }); @@ -7343,6 +7359,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { "/registry/agents/:encodedUrl/grading-profile", ...(authMiddleware ? [authMiddleware] : []), async (req, res) => { + const principal = captureRegistryPrincipal(req); try { const agentUrl = decodeURIComponent(req.params.encodedUrl); if (!validateExternalUrl(agentUrl)) { @@ -7383,7 +7400,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { } const manager = await canManageAgentForOrg(organizationId, req.user.id, agentUrl); - const registryAdmin = await isRegistryAdminRequest(req); + const registryAdmin = await isRegistryAdminRequest(principal); let actorKind: 'organization' | 'registry_admin' = 'organization'; if (!manager) { if (!registryAdmin || !adminOverrideReason) { @@ -7402,6 +7419,12 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { actorKind = 'registry_admin'; } + if (actorKind === 'registry_admin' && !(await isRegistryAdminRequest(principal))) { + return res.status(403).json({ + error: 'An owner/admin of the selected organization is required; registry admin overrides require a reason', + }); + } + const selection = await selectGradingProfile({ agentUrl, role, @@ -7412,7 +7435,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { acknowledgePublicImpact: body.acknowledge_public_impact === true, idempotencyKey: body.idempotency_key, requestId: String(req.headers['x-request-id'] ?? randomUUID()), - actorUserId: req.user.id, + actorUserId: actorKind === 'registry_admin' ? principal.user!.id : req.user.id, actorOrgId: organizationId, actorKind, adminOverrideReason: actorKind === 'registry_admin' ? adminOverrideReason : null, @@ -7449,6 +7472,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { return res.json({ ...selection, token_refresh: tokenRefresh }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; if (error instanceof GradingProfileConflictError) { logger.warn({ error, path: req.path, reason: error.reason }, 'Grading profile selection conflict'); return res.status(409).json({ @@ -7825,18 +7849,26 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { return (req as Request & { isStaticAdminApiKey?: boolean }).isStaticAdminApiKey === true; } - async function isRegistryAdminRequest(req: Request): Promise { - if (isStaticAdminRequest(req)) return true; - const user = req.user as ({ id?: string; email?: string; isAdmin?: boolean } | undefined); - if (!user) return false; - if (user.isAdmin === true) return true; + type RegistryPrincipal = Readonly<{ + staticAdmin: boolean; + user: Readonly | null; + }>; - const devUser = isDevModeEnabled() ? getDevUser(req) : null; - if (devUser?.isAdmin === true) return true; + // Capture authenticated middleware state before the first await. Neither + // presentation flags nor later mutation of req.user can change authority. + function captureRegistryPrincipal(req: Request): RegistryPrincipal { + return Object.freeze({ + staticAdmin: isStaticAdminRequest(req), + user: req.user ? Object.freeze({ + id: req.user.authWorkosUserId ?? req.user.id, + email: req.user.email, + }) : null, + }); + } - if (isBreakGlassAdminEmail(user.email)) return true; - if (!user.id) return false; - return isWebUserAAOAdmin(user.id); + async function isRegistryAdminRequest(principal: RegistryPrincipal): Promise { + if (principal.staticAdmin) return true; + return principal.user ? isAuthenticatedUserAAOAdmin(principal.user) : false; } router.get( @@ -8251,6 +8283,8 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { function publicRefreshFailure(code: string | null): { code: string; message: string } { switch (code) { + case 'authorization_provenance_missing': + return { code, message: 'Refresh requester authorization provenance is unavailable' }; case 'authorization_revoked': return { code: 'authorization_revoked', message: 'Access changed before the refresh started' }; case 'monitoring_paused': @@ -8291,11 +8325,18 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { request: ClaimedComplianceRefreshRequest, lease: { assertValid(): void }, ): Promise> { + // Legacy rows cannot establish which WorkOS credential authenticated or + // its authorization epoch. Never infer either from canonical attribution, + // even for an owner, a current admin, or an already checkpointed run. + // #7457/591 alone may enable execution with proven durable provenance. + if (request.requester_type === 'user') { + throw refreshFailure('authorization_provenance_missing', + 'Refresh requester authorization provenance is unavailable'); + } const agentUrl = request.agent_url; - // Authorization is checked both when the request is admitted and when a - // worker claims it. This closes the queue-time revocation window before - // saved owner credentials are resolved. + // Preserve the existing additional ownership constraint for any legacy + // static-admin row carrying an owner context. User rows never reach it. if (request.triggered_by === 'owner_test') { if ( !request.owner_org_id @@ -8304,18 +8345,6 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { ) { throw refreshFailure('authorization_revoked', 'Agent ownership changed before the refresh started'); } - } else if (request.requester_type === 'user') { - const isCurrentAdmin = !!request.requested_by_user_id - && ( - await isWebUserAAOAdmin(request.requested_by_user_id) - || ( - isDevModeEnabled() - && process.env.DEV_USER_ID === request.requested_by_user_id - ) - ); - if (!isCurrentAdmin) { - throw refreshFailure('authorization_revoked', 'Administrator access changed before the refresh started'); - } } // A prior attempt may have persisted the canonical run and then died @@ -8690,6 +8719,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { ); router.post("/registry/agents/:encodedUrl/refresh", ...complianceWriteMiddleware, capabilityProbeRateLimiter, async (req, res) => { + const principal = captureRegistryPrincipal(req); const responseDeadline = Date.now() + legacyRefreshWaitMs; try { const rawAgentUrl = decodeURIComponent(req.params.encodedUrl); @@ -8697,7 +8727,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { return res.status(400).json({ error: "Invalid agent URL" }); } const agentUrl = canonicalizeAgentUrl(rawAgentUrl) ?? rawAgentUrl; - if (!req.user) { + if (!principal.user && !principal.staticAdmin) { return res.status(401).json({ error: "Authentication required" }); } @@ -8705,33 +8735,42 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { if (!orgSelection.ok) { return res.status(400).json({ error: "organization_id must be a non-empty organization ID" }); } - const ownerOrgId = await resolveOwnerOrgForUser( - req.user.id, + const ownerOrgId = principal.user && !principal.staticAdmin ? await resolveOwnerOrgForUser( + principal.user.id, agentUrl, orgSelection.organizationId, - ); + ) : null; - // Owner OR AAO admin. Admin escape hatch lets staff fix things for - // any registered agent (mirrors how admin tools work elsewhere). - // Dev-admin fallback is gated behind `isDevModeEnabled()` to match - // `requireAdmin`'s pattern in middleware/auth.ts — in production - // (no DEV_USER_EMAIL/DEV_USER_ID) this branch never fires. - const isStaticAdmin = isStaticAdminRequest(req); + const isStaticAdmin = principal.staticAdmin; const isOwner = ownerOrgId !== null; - const isAaoAdmin = await isWebUserAAOAdmin(req.user.id); - const isDevAdmin = isDevModeEnabled() && getDevUser(req)?.isAdmin === true; - if (!isOwner && !isAaoAdmin && !isDevAdmin && !isStaticAdmin) { + if (!isOwner && !(await isRegistryAdminRequest(principal))) { return res.status(403).json({ error: "You do not have permission to refresh this agent" }); } + + // #7457 owns durable credential + epoch provenance. This schema cannot + // prove any human request, including one currently appearing unlinked. + // Do not enqueue work that the worker must deterministically reject. + // There is deliberately no environment switch to reopen this path. + if (!isStaticAdmin) { + logger.warn({ workosUserId: principal.user?.id, code: 'refresh_authorization_provenance_required' }, + 'Refresh admission fenced until durable authorization provenance is supported'); + res.setHeader('Retry-After', '60'); + res.setHeader('Cache-Control', 'private, no-store'); + return res.status(503).json({ + error: 'Refresh is temporarily unavailable for this credential. Please try again later.', + code: 'refresh_authorization_provenance_required', + retry_after: 60, + }); + } try { const operationId = randomUUID(); const { request, coalesced } = await complianceRefreshQueue.enqueue({ id: operationId, agentUrl, - ownerOrgId, - requesterType: isStaticAdmin ? 'static_admin' : 'user', - requestedByUserId: isStaticAdmin ? null : req.user.id, - triggeredBy: ownerOrgId ? 'owner_test' : 'manual', + ownerOrgId: null, + requesterType: 'static_admin', + requestedByUserId: null, + triggeredBy: 'manual', agentWindowMs: REFRESH_AGENT_RATE_LIMIT_MS, requesterWindowMs: REFRESH_USER_WINDOW_MS, requesterLimit: REFRESH_USER_LIMIT, @@ -8750,7 +8789,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { } if (coalesced && request.status === 'failed') { const failure = publicRefreshFailure(request.last_error_code); - const status = failure.code === 'authorization_revoked' + const status = failure.code === 'authorization_revoked' || failure.code === 'authorization_provenance_missing' ? 403 : failure.code === 'monitoring_paused' ? 409 @@ -8777,7 +8816,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { } if (terminal?.status === 'failed') { const failure = publicRefreshFailure(terminal.last_error_code); - const status = failure.code === 'authorization_revoked' + const status = failure.code === 'authorization_revoked' || failure.code === 'authorization_provenance_missing' ? 403 : failure.code === 'monitoring_paused' ? 409 @@ -8827,6 +8866,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { throw error; } } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error, path: req.path }, "Failed to enqueue agent refresh"); res.setHeader('Retry-After', '5'); res.status(503).json({ @@ -8842,6 +8882,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { ...complianceWriteMiddleware, agentReadRateLimiter, async (req, res) => { + const principal = captureRegistryPrincipal(req); try { const rawAgentUrl = decodeURIComponent(req.params.encodedUrl); if (!validateAgentUrlParam(rawAgentUrl)) { @@ -8851,7 +8892,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { if (!isUuid(req.params.operationId)) { return res.status(400).json({ error: "Invalid refresh operation ID" }); } - if (!req.user) { + if (!principal.user && !principal.staticAdmin) { return res.status(401).json({ error: "Authentication required" }); } @@ -8859,11 +8900,11 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { if (!operation || operation.agent_url !== agentUrl) { return res.status(404).json({ error: "Refresh operation not found" }); } - const ownsCredentialContext = !!operation.owner_org_id - && await isOrgOwnerOfAgent(operation.owner_org_id, req.user.id, agentUrl); - const canRead = isStaticAdminRequest(req) + const ownsCredentialContext = !!operation.owner_org_id && !!principal.user + && await isOrgOwnerOfAgent(operation.owner_org_id, principal.user.id, agentUrl); + const canRead = principal.staticAdmin || ownsCredentialContext - || await isRegistryAdminRequest(req); + || await isRegistryAdminRequest(principal); if (!canRead) { return res.status(404).json({ error: "Refresh operation not found" }); } @@ -8888,6 +8929,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { error: failure, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ err: error, path: req.path }, "Failed to read agent refresh operation"); res.setHeader('Retry-After', '5'); return res.status(503).json({ @@ -12637,6 +12679,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { res: import('express').Response, rateLimitKey: string, domainOverride?: string, + memberIdOverride?: string, ): Promise { const domain = domainOverride ?? req.body?.domain; if (!domain || typeof domain !== 'string') { @@ -12653,7 +12696,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { return null; } - const memberId = req.user?.id || 'anonymous'; + const memberId = memberIdOverride ?? req.user?.id ?? 'anonymous'; // Per-domain rate limit (shared key space for all crawl types on same domain) const lastCrawl = crawlRequestRateLimits.get(rateLimitKey); @@ -12684,9 +12727,9 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { } /** Release the reservation when synchronous crawler admission rejects. */ - function releaseCrawlRateLimit(req: import('express').Request, rateLimitKey: string): void { + function releaseCrawlRateLimit(req: import('express').Request, rateLimitKey: string, memberIdOverride?: string): void { crawlRequestRateLimits.delete(rateLimitKey); - const memberId = req.user?.id || 'anonymous'; + const memberId = memberIdOverride ?? req.user?.id ?? 'anonymous'; const memberState = memberCrawlCounts.get(memberId); if (!memberState) return; if (memberState.count <= 1) { @@ -12699,12 +12742,14 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { if (!authMiddleware) throw new Error('requireAuth middleware is required for crawl-request endpoint'); router.post("/registry/publisher/:domain/adagents/revalidate", authMiddleware, async (req, res) => { - let reservedDomain: string | null = null; + const principal = captureRegistryPrincipal(req); + const rateLimitMemberId = principal.user?.id ?? 'anonymous'; + let reservedRateLimitKey: string | null = null; try { - if (!req.user && !isStaticAdminRequest(req)) { + if (!principal.user && !principal.staticAdmin) { return res.status(401).json({ error: "Authentication required" }); } - if (!(await isRegistryAdminRequest(req))) { + if (!(await isRegistryAdminRequest(principal))) { return res.status(403).json({ error: "Admin access required" }); } @@ -12715,18 +12760,29 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { return res.status(400).json({ error: "Invalid domain" }); } - reservedDomain = await validateAndRateLimitCrawl(req, res, rawDomain, rawDomain); - if (!reservedDomain) return; + const normalizedDomain = await validateAndRateLimitCrawl(req, res, rawDomain, rawDomain, rateLimitMemberId); + if (!normalizedDomain) return; + reservedRateLimitKey = rawDomain; + // DNS validation can suspend the request. Recheck the same credential + // immediately before dispatch, including revocation during that wait. + if (!(await isRegistryAdminRequest(principal))) { + releaseCrawlRateLimit(req, reservedRateLimitKey, rateLimitMemberId); + return res.status(403).json({ error: "Admin access required" }); + } const force = req.query.force === 'true' || req.query.force === '1'; - const result = await crawler.revalidatePublisherAdagents(reservedDomain, { force }); + const result = await crawler.revalidatePublisherAdagents(normalizedDomain, { force }); return res.json(result); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) { + if (reservedRateLimitKey) releaseCrawlRateLimit(req, reservedRateLimitKey, rateLimitMemberId); + return; + } const errorCode = error instanceof Error ? (error as Error & { code?: string }).code : undefined; if (errorCode === 'crawl_deferred' || errorCode === 'crawl_execution_lock_lost') { - if (reservedDomain) releaseCrawlRateLimit(req, reservedDomain); + if (reservedRateLimitKey) releaseCrawlRateLimit(req, reservedRateLimitKey, rateLimitMemberId); res.setHeader('Retry-After', '5'); return res.status(503).json({ error: "Publisher crawl is temporarily busy", @@ -12740,11 +12796,14 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { }); router.post("/registry/brand/:domain/force-crawl", authMiddleware, async (req, res) => { + const principal = captureRegistryPrincipal(req); + const rateLimitMemberId = principal.user?.id ?? 'anonymous'; + let reservedRateLimitKey: string | null = null; try { - if (!req.user && !isStaticAdminRequest(req)) { + if (!principal.user && !principal.staticAdmin) { return res.status(401).json({ error: "Authentication required" }); } - if (!(await isRegistryAdminRequest(req))) { + if (!(await isRegistryAdminRequest(principal))) { return res.status(403).json({ error: "Admin access required" }); } @@ -12760,10 +12819,16 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { res, rawDomain, rawDomain, + rateLimitMemberId, ); if (!normalizedDomain) return; + reservedRateLimitKey = rawDomain; const previous = await brandDb.getDiscoveredBrandByDomain(normalizedDomain); + if (!(await isRegistryAdminRequest(principal))) { + releaseCrawlRateLimit(req, reservedRateLimitKey, rateLimitMemberId); + return res.status(403).json({ error: "Admin access required" }); + } const crawlResult = await crawler.scanBrandForDomain(normalizedDomain); const current = await brandDb.getDiscoveredBrandByDomain(normalizedDomain); @@ -12786,6 +12851,10 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { checked_at: new Date().toISOString(), }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) { + if (reservedRateLimitKey) releaseCrawlRateLimit(req, reservedRateLimitKey, rateLimitMemberId); + return; + } logger.error({ error, path: req.path }, "Failed to force brand.json crawl"); return res.status(500).json({ error: "Failed to force brand.json crawl" }); } @@ -12871,25 +12940,26 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { }); router.get("/registry/crawl-request/:crawlRequestId", authMiddleware, async (req, res) => { + const principal = captureRegistryPrincipal(req); try { const crawlRequestId = req.params.crawlRequestId; if (!isUuid(crawlRequestId)) { return res.status(400).json({ error: "Invalid crawl request ID" }); } - const staticAdmin = isStaticAdminRequest(req); - if (!req.user && !staticAdmin) { + const staticAdmin = principal.staticAdmin; + if (!principal.user && !staticAdmin) { return res.status(401).json({ error: "Authentication required" }); } const crawlRequest = await crawler.getPublisherCrawlRequest(crawlRequestId); - const ownsRequest = !!req.user + const ownsRequest = !!principal.user && crawlRequest?.requester_type === 'user' - && crawlRequest.requested_by_user_id === req.user.id; + && crawlRequest.requested_by_user_id === principal.user.id; if (!crawlRequest) { return res.status(404).json({ error: "Crawl request not found" }); } const canReadAnyRequest = staticAdmin - || (!ownsRequest && await isRegistryAdminRequest(req)); + || (!ownsRequest && await isRegistryAdminRequest(principal)); if (!ownsRequest && !canReadAnyRequest) { return res.status(404).json({ error: "Crawl request not found" }); } @@ -12911,6 +12981,7 @@ export function createRegistryApiRouters(config: RegistryApiConfig): { last_error_code: crawlRequest.last_error_code, }); } catch (error) { + if (respondToAdminAuthorizationError(error, res)) return; logger.error({ error, crawl_request_id: req.params.crawlRequestId }, "Failed to read crawl request"); res.setHeader('Retry-After', '5'); return res.status(503).json({ diff --git a/server/src/services/compliance-refresh-queue.ts b/server/src/services/compliance-refresh-queue.ts index e68c129c16a..2f575170a6e 100644 --- a/server/src/services/compliance-refresh-queue.ts +++ b/server/src/services/compliance-refresh-queue.ts @@ -15,6 +15,8 @@ const RETENTION_MS = 7 * 24 * 60 * 60_000; function stableFailureMessage(code: string): string { switch (code) { + case 'authorization_provenance_missing': + return 'Refresh requester authorization provenance is unavailable'; case 'authorization_revoked': return 'Authorization changed before the refresh started'; case 'monitoring_paused': @@ -30,6 +32,7 @@ function stableFailureMessage(code: string): string { function stableFailureCode(code: unknown): string { return code === 'authorization_revoked' + || code === 'authorization_provenance_missing' || code === 'monitoring_paused' || code === 'probe_failed' || code === 'compliance_failed' diff --git a/server/src/services/my-content-service.ts b/server/src/services/my-content-service.ts index 8b8f5a35b25..1b2e2a4ba66 100644 --- a/server/src/services/my-content-service.ts +++ b/server/src/services/my-content-service.ts @@ -14,7 +14,7 @@ */ import { getPool } from '../db/client.js'; -import { isWebUserAAOAdmin, isAuthenticatedUserAAOAdmin, type AAOAdminPrincipal } from '../addie/admin-status-lookup.js'; +import { isAuthenticatedUserAAOAdmin, type AAOAdminPrincipal } from '../addie/admin-status-lookup.js'; import { fetchPathPageviewCounts } from './posthog-query.js'; export type MyContentStatus = 'draft' | 'pending_review' | 'published' | 'archived' | 'rejected' | 'needs_revisions'; @@ -75,8 +75,8 @@ export class MyContentError e export interface ListMyContentInput { userId: string; - /** Null forbids platform and committee-leader scope; omitted retains legacy compatibility. */ - adminPrincipal?: AAOAdminPrincipal | null; + /** Explicit provenance is required; null grants only the person's author/proposer view. */ + adminPrincipal: Readonly | null; /** One of MyContentStatus, the literal 'all', or undefined (returns all). */ status?: string; /** Committee slug, or 'personal' (no committee), or undefined. */ @@ -99,6 +99,12 @@ export async function listMyContent({ relationship, limit, }: ListMyContentInput): Promise { + // An omitted principal at a legacy/untyped boundary cannot inherit the + // canonical person's leadership. Copy before the first asynchronous read. + const principal = adminPrincipal ? Object.freeze({ + id: adminPrincipal.authWorkosUserId ?? adminPrincipal.id, + email: adminPrincipal.email, + }) : null; if (status !== undefined && status !== 'all' && !VALID_STATUSES.includes(status as MyContentStatus)) { throw new MyContentError('invalid_status', `status must be one of: ${VALID_STATUSES.join(', ')}, or 'all'`, { provided: status, @@ -114,11 +120,7 @@ export async function listMyContent({ // Committees the user leads — feeds the "owner" relationship and the // SQL WHERE clause that surfaces all content for those committees. - const authorizationUserId = adminPrincipal === null - ? null - : adminPrincipal - ? adminPrincipal.authWorkosUserId ?? adminPrincipal.id - : userId; + const authorizationUserId = principal?.id ?? null; const leaderResult = await pool.query<{ working_group_id: string }>( `SELECT working_group_id FROM working_group_leaders WHERE user_id = $1`, [authorizationUserId], @@ -129,11 +131,7 @@ export async function listMyContent({ // pre-existing content with no proposer or content from committees // they don't lead). Relationships are still computed so the UI/chat // can distinguish their own contributions. - const userIsAdmin = adminPrincipal === null - ? false - : adminPrincipal - ? await isAuthenticatedUserAAOAdmin(adminPrincipal) - : await isWebUserAAOAdmin(userId); + const userIsAdmin = principal ? await isAuthenticatedUserAAOAdmin(principal) : false; let queryText = ` SELECT DISTINCT ON (p.id) diff --git a/server/src/utils/html-config.ts b/server/src/utils/html-config.ts index 7d0ad1bd5e2..6118dce3635 100644 --- a/server/src/utils/html-config.ts +++ b/server/src/utils/html-config.ts @@ -37,6 +37,7 @@ const POSTHOG_HOST = process.env.POSTHOG_HOST || 'https://us.i.posthog.com'; interface AppUser { id?: string; + authWorkosUserId?: string; email: string; firstName?: string | null; lastName?: string | null; @@ -167,18 +168,20 @@ export function getPublicFilePath(filename: string): string { /** * Resolve the admin flag for a user using the same rules as the requireAdmin * middleware: site-admin working-group membership, with `ADMIN_EMAILS` as an - * environment-managed break-glass fallback. If the user already has isAdmin - * set (e.g. a dev user), trust it. + * environment-managed break-glass fallback. Only development fixtures may + * retain a preset flag; real credentials perform a fresh credential authority lookup. */ export async function enrichUserWithAdmin(user: AppUser | null | undefined): Promise { if (!user) return user; - if (typeof user.isAdmin === 'boolean') return user; + // Development fixtures have no WorkOS authority. Real sessions must recheck + // their exact credential; a previously enriched flag is presentation only. + if (process.env.NODE_ENV !== 'production' && user.id?.startsWith('user_dev_') && typeof user.isAdmin === 'boolean') return user; if (user.id) { try { - user.isAdmin = (await resolveWebUserAAOAdminAccess(user.id, user.email)).isAdmin; + user.isAdmin = (await resolveWebUserAAOAdminAccess({ ...user, id: user.id })).isAdmin; } catch (error) { - logger.warn({ error, userId: user.id }, 'Failed to resolve isAdmin via working group; defaulting to false'); + logger.warn({ error, userId: user.authWorkosUserId ?? user.id }, 'Administrator visibility unavailable; privileged UI hidden'); user.isAdmin = false; } } else { diff --git a/server/tests/integration/community-mirrors.test.ts b/server/tests/integration/community-mirrors.test.ts index 0248fc2913e..d7793150ff3 100644 --- a/server/tests/integration/community-mirrors.test.ts +++ b/server/tests/integration/community-mirrors.test.ts @@ -53,7 +53,17 @@ vi.mock('../../src/services/brand-logo-auth.js', async () => { }); vi.mock('../../src/addie/admin-status-lookup.js', async () => { const actual = await vi.importActual>('../../src/addie/admin-status-lookup.js'); - return { ...actual, isWebUserAAOAdmin }; + const resolve = async (principal: any) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + const isAdmin = await isWebUserAAOAdmin(id); + return { isAdmin, mechanism: isAdmin ? 'aao_admin_working_group' : null }; + }; + return { + ...actual, + isWebUserAAOAdmin, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; }); vi.mock('../../src/notifications/registry.js', async () => { const actual = await vi.importActual>('../../src/notifications/registry.js'); diff --git a/server/tests/integration/content-credential-authorization.test.ts b/server/tests/integration/content-credential-authorization.test.ts index 97748763beb..902c1d65483 100644 --- a/server/tests/integration/content-credential-authorization.test.ts +++ b/server/tests/integration/content-credential-authorization.test.ts @@ -127,7 +127,7 @@ describe('Content committee authority belongs to the authenticated credential', it('uses only credential leadership for committee owner content', async () => { const result = await listMyContent({ userId: canonical, - adminPrincipal: user.adminPrincipal, + adminPrincipal: user.adminPrincipal ?? null, collection: slug, relationship: 'owner', }); @@ -140,6 +140,13 @@ describe('Content committee authority belongs to the authenticated credential', external_url: 'https://example.com/article', collection: { committee_slug: slug }, status: 'published', }); + if (credential === null) { + expect(result.success).toBe(false); + expect(result.error).toContain('/dashboard/membership'); + const persisted = await pool.query('SELECT id FROM perspectives WHERE proposer_user_id = $1', [canonical]); + expect(persisted.rows).toEqual([]); + return; + } expect(result.success).toBe(true); expect(result.status).toBe(allowed ? 'published' : 'pending_review'); const persisted = await pool.query('SELECT status, proposer_user_id FROM perspectives WHERE id = $1', [result.id]); diff --git a/server/tests/integration/content-my-content.test.ts b/server/tests/integration/content-my-content.test.ts index 857e8de307b..d6f9f7922a7 100644 --- a/server/tests/integration/content-my-content.test.ts +++ b/server/tests/integration/content-my-content.test.ts @@ -17,16 +17,20 @@ vi.mock('../../src/auth/workos-client.js', () => ({ // non-admin. The mock reads this at call time. const authState = { userId: 'user_my_content', + authWorkosUserId: undefined as string | undefined, email: 'mc@example.com', + requestUser: undefined as Record | undefined, }; vi.mock('../../src/middleware/auth.js', () => { const setTestUser = (req: any) => { req.user = { id: authState.userId, + authWorkosUserId: authState.authWorkosUserId, email: authState.email, firstName: 'Mary', }; + authState.requestUser = req.user; }; const passthrough = (_req: any, _res: any, next: any) => next(); const requireAuthMock = (req: any, _res: any, next: any) => { setTestUser(req); next(); }; @@ -65,7 +69,13 @@ vi.mock('../../src/middleware/csrf.js', () => ({ csrfProtection: (_req: any, _res: any, next: any) => next(), })); -const adminState = { isAdmin: false }; +const adminState = { + isAdmin: false, + grantedUserId: undefined as string | undefined, + unavailable: false, + principals: [] as Array<{ id: string; authWorkosUserId?: string; email?: string | null }>, + onLookup: undefined as (() => void) | undefined, +}; // Mock the lookup module directly. `my-content-service.ts` imports // `isWebUserAAOAdmin` from `addie/admin-status-lookup.js` (the thin // module created in PR #3758), so the test must intercept there. @@ -73,9 +83,25 @@ const adminState = { isAdmin: false }; // re-exports are not call-routed through the original module — once // the consumer points at `admin-status-lookup`, that's what gets // resolved. -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ - isWebUserAAOAdmin: vi.fn(async () => adminState.isAdmin), -})); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async (id: string) => { + if (adminState.unavailable) throw new actual.AAOAdminLookupUnavailableError(); + return adminState.grantedUserId ? id === adminState.grantedUserId : adminState.isAdmin; + }); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + if (typeof principal !== 'string') adminState.principals.push(principal); + adminState.onLookup?.(); + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => { const actual = await importOriginal() as Record; return { @@ -115,6 +141,10 @@ describe('My Content — body, admin scope, status, delete', () => { let app: any; let pool: Pool; let wgId: string; + let adminWgId: string; + let privateWgId: string; + const ADMIN_WG_SLUG = 'mc-test-platform-review-wg'; + const PRIVATE_WG_SLUG = 'mc-test-private-wg'; const WG_SLUG = 'mc-test-wg'; const ARCHIVED_WG_SLUG = 'mc-test-archived-wg'; const USER_ID = 'user_my_content'; @@ -168,6 +198,28 @@ describe('My Content — body, admin scope, status, delete', () => { // Ensure users exist await ensureContentSubmissionEligibleUser(USER_ID, 'mc@example.com'); await ensureContentSubmissionEligibleUser(OTHER_USER_ID, 'mc-other@example.com'); + await pool.query( + `INSERT INTO users (workos_user_id, email, first_name, last_name) + VALUES ($1, 'mc-ineligible@example.com', 'Sam', 'Adeyemi') + ON CONFLICT (workos_user_id) DO UPDATE SET primary_organization_id = NULL`, + [INELIGIBLE_USER_ID], + ); + const extraGroups = await pool.query<{ id: string; slug: string }>( + `INSERT INTO working_groups (name, slug, accepts_public_submissions, is_private) + VALUES ('Platform review fixture', $1, true, false), ('Private committee fixture', $2, false, true) + ON CONFLICT (slug) DO UPDATE SET accepts_public_submissions = EXCLUDED.accepts_public_submissions, + is_private = EXCLUDED.is_private, status = 'active' + RETURNING id, slug`, + [ADMIN_WG_SLUG, PRIVATE_WG_SLUG], + ); + adminWgId = extraGroups.rows.find(group => group.slug === ADMIN_WG_SLUG)!.id; + privateWgId = extraGroups.rows.find(group => group.slug === PRIVATE_WG_SLUG)!.id; + await pool.query( + `INSERT INTO working_group_memberships (working_group_id, workos_user_id, status) + VALUES ($1, $2, 'active') + ON CONFLICT (working_group_id, workos_user_id) DO UPDATE SET status = 'active'`, + [privateWgId, OTHER_USER_ID], + ); const wgResult = await pool.query( `INSERT INTO working_groups (name, slug, description, accepts_public_submissions) @@ -200,6 +252,8 @@ describe('My Content — body, admin scope, status, delete', () => { [ARCHIVED_WG_SLUG] ); await pool.query(`DELETE FROM working_groups WHERE slug = $1`, [ARCHIVED_WG_SLUG]); + await pool.query(`DELETE FROM working_group_memberships WHERE working_group_id = $1`, [privateWgId]); + await pool.query(`DELETE FROM working_groups WHERE id = ANY($1)`, [[adminWgId, privateWgId]]); await pool.query(`DELETE FROM working_group_leaders WHERE working_group_id = $1`, [wgId]); await pool.query(`DELETE FROM working_groups WHERE slug = $1`, [WG_SLUG]); // Side tables the propose flow writes into. Clear everything referencing @@ -217,6 +271,12 @@ describe('My Content — body, admin scope, status, delete', () => { beforeEach(async () => { adminState.isAdmin = false; + adminState.grantedUserId = undefined; + adminState.unavailable = false; + adminState.principals = []; + adminState.onLookup = undefined; + authState.requestUser = undefined; + authState.authWorkosUserId = undefined; authState.userId = USER_ID; authState.email = 'mc@example.com'; await pool.query(`DELETE FROM addie_escalations WHERE summary LIKE $1`, [`${ESCALATION_SUMMARY_PREFIX}%`]); @@ -224,6 +284,15 @@ describe('My Content — body, admin scope, status, delete', () => { await pool.query(`DELETE FROM perspectives WHERE slug LIKE 'mc-test-%'`); }); + function expectCapturedAuthority(credential: string) { + expect(adminState.principals.length).toBeGreaterThan(0); + for (const principal of adminState.principals) { + expect(Object.isFrozen(principal)).toBe(true); + expect(principal.authWorkosUserId ?? principal.id).toBe(credential); + expect(principal).not.toBe(authState.requestUser); + } + } + async function insertPerspective(opts: { slug: string; title: string; @@ -285,6 +354,27 @@ describe('My Content — body, admin scope, status, delete', () => { expect(slugs).not.toContain('mc-test-orphan'); }); + it.each([ + ['user_my_content', 'user_my_content_other', true], + ['user_my_content_other', 'user_my_content', false], + ] as const)('uses authenticated %s instead of canonical %s for platform scope', async (authenticated, canonical, allowed) => { + await insertPerspective({ slug: 'mc-test-orphan', title: 'Unrelated official content', proposerUserId: null, workingGroupId: null }); + authState.userId = canonical; + authState.authWorkosUserId = authenticated; + adminState.grantedUserId = USER_ID; + + const response = await request(app).get('/api/me/content').expect(200); + expect(response.body.items.some((item: { slug: string }) => item.slug === 'mc-test-orphan')).toBe(allowed); + }); + + it('reports an unavailable platform lookup separately from an empty personal list', async () => { + adminState.unavailable = true; + const response = await request(app).get('/api/me/content').expect(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(response.headers['cache-control']).toBe('no-store'); + }); + it('admins see every perspective so they can edit anything', async () => { await insertPerspective({ slug: 'mc-test-orphan', @@ -543,7 +633,11 @@ describe('My Content — body, admin scope, status, delete', () => { // directly, bypassing HTTP middleware. Fresh user id so we start // with an empty window. const { proposeContentForUser } = await import('../../src/routes/content.js'); - const testUser = { id: RATE_LIMIT_USER_ID, email: 'ratelimit@test.local' }; + const testUser = { + id: RATE_LIMIT_USER_ID, + email: 'ratelimit@test.local', + adminPrincipal: Object.freeze({ id: RATE_LIMIT_USER_ID, email: 'ratelimit@test.local' }), + }; await ensureContentSubmissionEligibleUser(testUser.id, testUser.email); const results: Array<{ success: boolean; error?: string }> = []; @@ -816,6 +910,258 @@ describe('My Content — body, admin scope, status, delete', () => { }); }); + describe.each([ + { authority: 'leader', authenticated: 'user_my_content', canonical: 'user_my_content_other', allowed: true }, + { authority: 'platform administrator', authenticated: 'user_my_content', canonical: 'user_my_content_other', allowed: true }, + { authority: 'leader', authenticated: 'user_my_content_other', canonical: 'user_my_content', allowed: false }, + { authority: 'platform administrator', authenticated: 'user_my_content_other', canonical: 'user_my_content', allowed: false }, + ])('content $authority credential $authenticated linked to $canonical', ({ authority, authenticated, canonical, allowed }) => { + let authorityGroupId: string; + let authorityGroupSlug: string; + beforeEach(() => { + authState.userId = canonical; + authState.authWorkosUserId = authenticated; + adminState.grantedUserId = authority === 'platform administrator' ? USER_ID : undefined; + authorityGroupId = authority === 'platform administrator' ? adminWgId : wgId; + authorityGroupSlug = authority === 'platform administrator' ? ADMIN_WG_SLUG : WG_SLUG; + }); + + it('passes immutable exact authority through the my-content route', async () => { + const id = await insertPerspective({ + slug: 'mc-test-credential-my-content', title: 'Review-owned content', + status: 'pending_review', proposerUserId: null, workingGroupId: authorityGroupId, + }); + const response = await request(app).get('/api/me/content').query({ collection: authorityGroupSlug }).expect(200); + expectCapturedAuthority(authenticated); + expect(response.body.items.some((item: { id: string }) => item.id === id)).toBe(allowed); + }); + + it('passes the authenticated credential through the proposal route', async () => { + const response = await request(app).post('/api/content/propose').send({ + title: 'mc-test-credential-proposal', + adminPrincipal: { id: USER_ID }, authWorkosUserId: USER_ID, + content: 'Credential-scoped publishing authority', + content_type: 'article', + collection: { slug: authorityGroupSlug }, + status: 'published', + }).expect(201); + + expectCapturedAuthority(authenticated); + const expectedStatus = allowed ? 'published' : 'pending_review'; + expect(response.body.status).toBe(expectedStatus); + const stored = await pool.query( + 'SELECT status, proposer_user_id FROM perspectives WHERE id = $1', [response.body.id], + ); + expect(stored.rows).toEqual([{ status: expectedStatus, proposer_user_id: canonical }]); + }); + + it('passes the authenticated credential through the pending-review route', async () => { + const id = await insertPerspective({ + slug: 'mc-test-credential-pending', title: 'Private pending submission', + status: 'pending_review', proposerUserId: null, workingGroupId: authorityGroupId, + }); + + const response = await request(app).get('/api/content/pending') + .query({ committee_slug: authorityGroupSlug }).expect(200); + expectCapturedAuthority(authenticated); + expect(response.body.items.some((item: { id: string }) => item.id === id)).toBe(allowed); + if (!allowed) expect(response.body.items).toEqual([]); + }); + + it.each([ + { action: 'approve', body: { publish_immediately: false }, nextStatus: 'draft' }, + { action: 'reject', body: { reason: 'Please revise this submission' }, nextStatus: 'rejected' }, + { action: 'request-revisions', body: { notes: 'Please add supporting evidence' }, nextStatus: 'needs_revisions' }, + ])('passes the authenticated credential through the $action route', async ({ action, body, nextStatus }) => { + const id = await insertPerspective({ + slug: `mc-test-credential-${action}`, title: 'Pending submission', + status: 'pending_review', proposerUserId: null, workingGroupId: authorityGroupId, + }); + + const response = await request(app).post(`/api/content/${id}/${action}`).send({ ...body, adminPrincipal: { id: USER_ID }, authWorkosUserId: USER_ID }) + .expect(allowed ? 200 : 403); + expectCapturedAuthority(authenticated); + if (allowed) expect(response.body.status).toBe(nextStatus); + const stored = await pool.query( + 'SELECT status, reviewed_by_user_id, reviewed_at FROM perspectives WHERE id = $1', [id], + ); + expect(stored.rows[0]).toMatchObject({ + status: allowed ? nextStatus : 'pending_review', + reviewed_by_user_id: allowed ? canonical : null, + }); + expect(stored.rows[0].reviewed_at !== null).toBe(allowed); + }); + + it.each(['update', 'delete', 'add-author', 'remove-author'] as const)('uses exact credential for %s authority', async (operation) => { + const id = await insertPerspective({ + slug: `mc-test-credential-${operation}`, title: 'Original title', + status: 'draft', proposerUserId: null, workingGroupId: authorityGroupId, + }); + if (operation === 'remove-author') { + await pool.query( + `INSERT INTO content_authors (perspective_id, user_id, display_name) VALUES ($1, $2, 'Existing author')`, + [id, OTHER_USER_ID], + ); + } + + const path = `/api/me/content/${id}`; + const response = operation === 'update' + ? await request(app).put(path).send({ title: 'Changed title' }) + : operation === 'delete' + ? await request(app).delete(path) + : operation === 'add-author' + ? await request(app).post(`${path}/authors`).send({ user_id: OTHER_USER_ID, display_name: 'New author' }) + : await request(app).delete(`${path}/authors/${OTHER_USER_ID}`); + expectCapturedAuthority(authenticated); + expect(response.status).toBe(allowed ? operation === 'add-author' ? 201 : 200 : 403); + + if (operation === 'update' || operation === 'delete') { + const stored = await pool.query(`SELECT title FROM perspectives WHERE id = $1`, [id]); + expect(stored.rows).toEqual(allowed && operation === 'delete' ? [] : [{ title: allowed ? 'Changed title' : 'Original title' }]); + } else { + const authors = await pool.query(`SELECT user_id FROM content_authors WHERE perspective_id = $1`, [id]); + const expectedCount = operation === 'add-author' ? Number(allowed) : Number(!allowed); + expect(authors.rows).toHaveLength(expectedCount); + } + }); + + it.each([ + { missing: 'user_id', body: { display_name: 'Untrusted author' } }, + { missing: 'display_name', body: { user_id: OTHER_USER_ID } }, + ])('authorizes before validating missing $missing or trusting body authority', async ({ body }) => { + const id = await insertPerspective({ + slug: 'mc-test-credential-author-validation', title: 'Stored author authority', + status: 'draft', proposerUserId: null, workingGroupId: authorityGroupId, + }); + const response = await request(app).post(`/api/me/content/${id}/authors`).send({ + ...body, + adminPrincipal: { id: USER_ID }, authWorkosUserId: USER_ID, + proposer_user_id: canonical, isAdmin: true, + }); + + expect(response.status).toBe(allowed ? 400 : 403); + expectCapturedAuthority(authenticated); + expect((await pool.query('SELECT 1 FROM content_authors WHERE perspective_id = $1', [id])).rows).toEqual([]); + }); + }); + + describe.each([ + { authenticated: OTHER_USER_ID, canonical: INELIGIBLE_USER_ID, allowed: true }, + { authenticated: INELIGIBLE_USER_ID, canonical: OTHER_USER_ID, allowed: false }, + ])('paid submission credential $authenticated linked to $canonical', ({ authenticated, canonical, allowed }) => { + it('uses the exact organization grant for the Professional tier gate and keeps canonical attribution', async () => { + authState.userId = canonical; + authState.authWorkosUserId = authenticated; + const title = 'mc-test-linked-paid-tier'; + const response = await request(app).post('/api/content/propose').send({ + title, content: 'Tier-protected submission', content_type: 'article', + collection: { slug: ADMIN_WG_SLUG }, + adminPrincipal: { id: OTHER_USER_ID }, authWorkosUserId: OTHER_USER_ID, + }).expect(allowed ? 201 : 403); + + expectCapturedAuthority(authenticated); + const stored = await pool.query('SELECT proposer_user_id, status FROM perspectives WHERE title = $1', [title]); + expect(stored.rows).toEqual(allowed ? [{ proposer_user_id: canonical, status: 'pending_review' }] : []); + if (!allowed) expect(response.body.message).toContain('/dashboard/membership'); + }); + }); + + it('does not treat a paid primary organization pointer as an exact credential membership grant', async () => { + authState.userId = OTHER_USER_ID; + authState.authWorkosUserId = INELIGIBLE_USER_ID; + await pool.query('UPDATE users SET primary_organization_id = $1 WHERE workos_user_id = $2', [ELIGIBLE_ORG_ID, INELIGIBLE_USER_ID]); + try { + const response = await request(app).post('/api/content/propose').send({ + title: 'mc-test-stale-paid-pointer', content: 'Must require an exact membership row', + content_type: 'article', collection: { slug: ADMIN_WG_SLUG }, + }).expect(403); + expect(response.body.message).toContain('/dashboard/membership'); + expectCapturedAuthority(INELIGIBLE_USER_ID); + const stored = await pool.query("SELECT id FROM perspectives WHERE title = 'mc-test-stale-paid-pointer'"); + expect(stored.rows).toEqual([]); + } finally { + await pool.query('UPDATE users SET primary_organization_id = NULL WHERE workos_user_id = $1', [INELIGIBLE_USER_ID]); + } + }); + + describe.each([ + { authenticated: OTHER_USER_ID, canonical: USER_ID, allowed: true }, + { authenticated: USER_ID, canonical: OTHER_USER_ID, allowed: false }, + ])('private committee member $authenticated linked to $canonical', ({ authenticated, canonical, allowed }) => { + beforeEach(() => { + authState.userId = canonical; + authState.authWorkosUserId = authenticated; + }); + + it('lists the private collection only through exact credential membership', async () => { + const response = await request(app).get('/api/content/collections').expect(200); + expect(response.body.collections.some((collection: { slug: string }) => collection.slug === PRIVATE_WG_SLUG)).toBe(allowed); + }); + + it('checks exact private committee membership before inserting content', async () => { + const title = 'mc-test-linked-private-committee'; + const response = await request(app).post('/api/content/propose').send({ + title, content: 'Private committee submission', content_type: 'article', + collection: { slug: PRIVATE_WG_SLUG }, + adminPrincipal: { id: OTHER_USER_ID }, authWorkosUserId: OTHER_USER_ID, + }).expect(allowed ? 201 : 403); + + expectCapturedAuthority(authenticated); + const stored = await pool.query('SELECT proposer_user_id, working_group_id FROM perspectives WHERE title = $1', [title]); + expect(stored.rows).toEqual(allowed ? [{ proposer_user_id: canonical, working_group_id: privateWgId }] : []); + if (!allowed) expect(response.body.message).toContain('must be a member of this committee'); + }); + }); + + it.each([ + { authenticated: USER_ID, canonical: OTHER_USER_ID, allowed: true }, + { authenticated: OTHER_USER_ID, canonical: USER_ID, allowed: false }, + ])('captures immutable principal and attribution before an awaited lookup for $authenticated', async ({ authenticated, canonical, allowed }) => { + authState.userId = canonical; + authState.authWorkosUserId = authenticated; + adminState.grantedUserId = USER_ID; + let changed = false; + adminState.onLookup = () => { + if (changed) return; + changed = true; + // Model another middleware/service holding the original req.user object. + // The route must have captured its authority and attribution before I/O. + authState.requestUser!.id = authenticated; + authState.requestUser!.authWorkosUserId = canonical; + authState.requestUser!.email = 'changed@example.com'; + }; + + const response = await request(app).post('/api/content/propose').send({ + title: 'mc-test-immutable-request-principal', content: 'Snapshot principal through asynchronous work', + content_type: 'article', collection: { slug: ADMIN_WG_SLUG }, status: 'published', + adminPrincipal: { id: USER_ID }, authWorkosUserId: USER_ID, + }).expect(201); + + expect(changed).toBe(true); + expectCapturedAuthority(authenticated); + const stored = await pool.query('SELECT proposer_user_id, status FROM perspectives WHERE id = $1', [response.body.id]); + expect(stored.rows).toEqual([{ proposer_user_id: canonical, status: allowed ? 'published' : 'pending_review' }]); + }); + + it.each([null, undefined])('my-content missing principal %s cannot recover canonical leadership or admin scope', async (principal) => { + const { listMyContent } = await import('../../src/services/my-content-service.js'); + const owned = await insertPerspective({ + slug: 'mc-test-principal-omitted-owned', title: 'Canonical attribution remains available', + status: 'draft', proposerUserId: USER_ID, + }); + const reviewOnly = await insertPerspective({ + slug: 'mc-test-principal-omitted-review', title: 'Committee review authority is separate', + status: 'pending_review', proposerUserId: null, workingGroupId: wgId, + }); + adminState.grantedUserId = USER_ID; + // Exercise a runtime legacy caller omitting the now-required field. + const result = await listMyContent({ userId: USER_ID, adminPrincipal: principal as null }); + expect(result.items.map(item => item.id)).toContain(owned); + expect(result.items.map(item => item.id)).not.toContain(reviewOnly); + expect(result.items.every(item => !item.relationships.includes('owner'))).toBe(true); + expect(adminState.principals).toEqual([]); + }); + describe('DELETE /api/admin/content/:id', () => { it('resolves linked open escalations before deleting the perspective', async () => { const id = await insertPerspective({ diff --git a/server/tests/integration/event-speakers.test.ts b/server/tests/integration/event-speakers.test.ts index bee3288fd92..6c9e0d3705c 100644 --- a/server/tests/integration/event-speakers.test.ts +++ b/server/tests/integration/event-speakers.test.ts @@ -65,6 +65,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => { }; }); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async () => true); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/billing/stripe-client.js', () => ({ stripe: null, getSubscriptionInfo: vi.fn().mockResolvedValue(null), diff --git a/server/tests/integration/events-draft-preview.test.ts b/server/tests/integration/events-draft-preview.test.ts index 9a5fbf78034..831c4ab0def 100644 --- a/server/tests/integration/events-draft-preview.test.ts +++ b/server/tests/integration/events-draft-preview.test.ts @@ -61,9 +61,20 @@ vi.mock('../../src/middleware/csrf.js', () => ({ const adminState = { isAdmin: false }; // Draft preview authorization reads the thin membership-status seam directly. // Mock it before HTTPServer is imported so the module graph sees test state. -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ - isWebUserAAOAdmin: vi.fn(async () => adminState.isAdmin), -})); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async () => adminState.isAdmin); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); vi.mock('../../src/billing/stripe-client.js', () => ({ stripe: null, diff --git a/server/tests/integration/member-by-email-policy.test.ts b/server/tests/integration/member-by-email-policy.test.ts index 8f1db7f9150..f035ef4b563 100644 --- a/server/tests/integration/member-by-email-policy.test.ts +++ b/server/tests/integration/member-by-email-policy.test.ts @@ -209,6 +209,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: vi.fn().mockImplementation(() => Promise.resolve(mockState.isCallerAAOAdmin)), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn().mockImplementation(() => Promise.resolve(mockState.isCallerAAOAdmin)); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + import { HTTPServer } from '../../src/http.js'; import request from 'supertest'; import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; diff --git a/server/tests/integration/org-auto-provision-toggles.test.ts b/server/tests/integration/org-auto-provision-toggles.test.ts index 6e8ca965c02..7242f0687ee 100644 --- a/server/tests/integration/org-auto-provision-toggles.test.ts +++ b/server/tests/integration/org-auto-provision-toggles.test.ts @@ -26,11 +26,19 @@ const SUB_DOMAIN_B = 'apt-sub-b.test'; let currentMockUser = OWNER_USER; let currentMockEmail = 'owner@apt-co.test'; +let currentAuthWorkosUserId: string | undefined; +let currentRequestUser: { id: string; email: string; authWorkosUserId?: string } | undefined; +const adminLookupState = { + grantedUserId: undefined as string | undefined, + unavailable: false, + principals: [] as Array<{ id: string; email?: string | null }>, +}; vi.mock('../../src/middleware/auth.js', async (importOriginal) => ({ ...(await importOriginal()), requireAuth: (req: any, _res: any, next: any) => { - req.user = { id: currentMockUser, email: currentMockEmail, is_admin: false }; + req.user = { id: currentMockUser, authWorkosUserId: currentAuthWorkosUserId, email: currentMockEmail, is_admin: false }; + currentRequestUser = req.user; next(); }, })); @@ -59,6 +67,25 @@ vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => ({ isWebUserAAOAdmin: vi.fn().mockResolvedValue(false), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async (id: string) => { + if (adminLookupState.unavailable) throw new actual.AAOAdminLookupUnavailableError(); + return id === adminLookupState.grantedUserId; + }); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + if (typeof principal !== 'string') adminLookupState.principals.push(principal); + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + describe('org auto-provisioning toggles', () => { let server: HTTPServer; let app: any; @@ -83,6 +110,13 @@ describe('org auto-provisioning toggles', () => { beforeEach(async () => { await cleanupTestData(pool); workosMocks.listOrganizationMemberships.mockReset(); + currentMockUser = OWNER_USER; + currentMockEmail = 'owner@apt-co.test'; + currentAuthWorkosUserId = undefined; + currentRequestUser = undefined; + adminLookupState.grantedUserId = undefined; + adminLookupState.unavailable = false; + adminLookupState.principals = []; }); it('owner GET /domains returns both flags and inferred subsidiaries', async () => { @@ -317,6 +351,107 @@ describe('org auto-provisioning toggles', () => { currentMockEmail = 'owner@apt-co.test'; }); + it.each([ + { authenticated: OWNER_USER, canonical: ADMIN_USER, allowed: true }, + { authenticated: ADMIN_USER, canonical: OWNER_USER, allowed: false }, + ])('uses exact $authenticated ownership rather than linked $canonical for both provision flags', async ({ authenticated, canonical, allowed }) => { + await seedTestOrg(pool); + currentMockUser = canonical; + currentAuthWorkosUserId = authenticated; + workosMocks.listOrganizationMemberships.mockImplementation(async ({ userId }) => ({ + data: [{ organizationId: TEST_ORG, role: { slug: userId === OWNER_USER ? 'owner' : 'admin' }, status: 'active' }], + })); + + const res = await request(app).patch(`/api/organizations/${TEST_ORG}/settings`).send({ + auto_provision_verified_domain: false, + auto_provision_brand_hierarchy_children: true, + role: 'owner', userRole: 'owner', isAAOAdmin: true, adminPrincipal: { id: OWNER_USER }, + }); + + expect(res.status).toBe(allowed ? 200 : 403); + expect(workosMocks.listOrganizationMemberships).toHaveBeenCalledWith({ userId: authenticated, organizationId: TEST_ORG }); + const stored = await pool.query( + 'SELECT auto_provision_verified_domain, auto_provision_brand_hierarchy_children FROM organizations WHERE workos_organization_id = $1', [TEST_ORG], + ); + expect(stored.rows[0]).toEqual({ + auto_provision_verified_domain: !allowed, + auto_provision_brand_hierarchy_children: allowed, + }); + }); + + it.each([ + { authenticated: OWNER_USER, canonical: ADMIN_USER, allowed: true }, + { authenticated: ADMIN_USER, canonical: OWNER_USER, allowed: false }, + ])('uses immutable exact platform authority for $authenticated despite linked identity mutation', async ({ authenticated, canonical, allowed }) => { + await seedTestOrg(pool); + currentMockUser = canonical; + currentAuthWorkosUserId = authenticated; + currentMockEmail = `${authenticated}@apt-co.test`; + adminLookupState.grantedUserId = OWNER_USER; + workosMocks.listOrganizationMemberships.mockImplementation(async () => { + await Promise.resolve(); + currentRequestUser!.id = authenticated; + currentRequestUser!.authWorkosUserId = canonical; + currentRequestUser!.email = 'spoofed@apt-co.test'; + return { data: [{ organizationId: TEST_ORG, role: { slug: 'admin' }, status: 'active' }] }; + }); + + const res = await request(app).patch(`/api/organizations/${TEST_ORG}/settings`).send({ + auto_provision_brand_hierarchy_children: true, + isStaticAdminApiKey: true, authWorkosUserId: OWNER_USER, isAdmin: true, + }); + + expect(res.status).toBe(allowed ? 200 : 403); + expect(workosMocks.listOrganizationMemberships).toHaveBeenCalledWith({ userId: authenticated, organizationId: TEST_ORG }); + expect(adminLookupState.principals).toHaveLength(1); + expect(adminLookupState.principals[0]).toEqual({ id: authenticated, email: `${authenticated}@apt-co.test` }); + expect(Object.isFrozen(adminLookupState.principals[0])).toBe(true); + expect((await pool.query( + 'SELECT auto_provision_brand_hierarchy_children FROM organizations WHERE workos_organization_id = $1', [TEST_ORG], + )).rows[0].auto_provision_brand_hierarchy_children).toBe(allowed); + }); + + it.each([ + { field: 'auto_provision_verified_domain', value: false }, + { field: 'auto_provision_brand_hierarchy_children', value: true }, + ])('fails closed with typed unavailable for $field while retaining ordinary admin updates', async ({ field, value }) => { + await seedTestOrg(pool); + currentMockUser = ADMIN_USER; + adminLookupState.unavailable = true; + workosMocks.listOrganizationMemberships.mockResolvedValue({ + data: [{ organizationId: TEST_ORG, role: { slug: 'admin' }, status: 'active' }], + }); + + const denied = await request(app).patch(`/api/organizations/${TEST_ORG}/settings`).send({ [field]: value, isAdmin: true }); + expect(denied.status).toBe(503); + expect(denied.body.error).toBe('admin_authorization_unavailable'); + expect(denied.headers['cache-control']).toBe('no-store'); + expect(denied.headers['retry-after']).toBe('5'); + expect((await pool.query( + 'SELECT auto_provision_verified_domain, auto_provision_brand_hierarchy_children FROM organizations WHERE workos_organization_id = $1', [TEST_ORG], + )).rows[0]).toEqual({ auto_provision_verified_domain: true, auto_provision_brand_hierarchy_children: false }); + + const ordinary = await request(app).patch(`/api/organizations/${TEST_ORG}/settings`).send({ revenue_tier: null }); + expect(ordinary.status).toBe(200); + }); + + it('rejects absent exact membership before malformed settings or spoofed body roles', async () => { + await seedTestOrg(pool); + currentMockUser = OWNER_USER; + currentAuthWorkosUserId = ADMIN_USER; + workosMocks.listOrganizationMemberships.mockResolvedValue({ data: [] }); + + const res = await request(app).patch(`/api/organizations/${TEST_ORG}/settings`).send({ + auto_provision_brand_hierarchy_children: 'yes', role: 'owner', isStaticAdminApiKey: true, + }); + expect(res.status).toBe(403); + expect(adminLookupState.principals).toEqual([]); + expect(workosMocks.listOrganizationMemberships).toHaveBeenCalledWith({ userId: ADMIN_USER, organizationId: TEST_ORG }); + expect((await pool.query( + 'SELECT auto_provision_brand_hierarchy_children FROM organizations WHERE workos_organization_id = $1', [TEST_ORG], + )).rows[0].auto_provision_brand_hierarchy_children).toBe(false); + }); + it('flipping the flag back to false sets disabled_at and preserves enabled_at', async () => { await seedTestOrg(pool, { hierarchyOptIn: true }); workosMocks.listOrganizationMemberships.mockResolvedValue({ diff --git a/server/tests/integration/perspective-assets.test.ts b/server/tests/integration/perspective-assets.test.ts index 21bd39edbc2..1440a855824 100644 --- a/server/tests/integration/perspective-assets.test.ts +++ b/server/tests/integration/perspective-assets.test.ts @@ -76,6 +76,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => { }; }); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn().mockImplementation(async () => adminAccess.enabled); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/billing/stripe-client.js', () => ({ stripe: null, getSubscriptionInfo: vi.fn().mockResolvedValue(null), diff --git a/server/tests/integration/registry-api-agent-refresh.test.ts b/server/tests/integration/registry-api-agent-refresh.test.ts index 271a1ab5e2b..d3bf1c11680 100644 --- a/server/tests/integration/registry-api-agent-refresh.test.ts +++ b/server/tests/integration/registry-api-agent-refresh.test.ts @@ -1,10 +1,9 @@ /** * Integration tests for POST /api/registry/agents/:encodedUrl/refresh. * - * The endpoint lets an agent's owner (or an AAO admin) re-probe the agent - * on demand and write fresh `agent_health_snapshot` / `agent_capabilities_snapshot` - * rows. It replaces the prior pattern of either waiting for the 60-min - * periodic crawl or hitting the (admin-only, full-fan-out) /api/crawler/run. + * Human refresh requests are fenced until durable credential provenance is + * supported. Static-admin refreshes retain the durable probe/compliance lifecycle; + * legacy human queue rows must fail before recovering or publishing evidence. * * Run locally: * DATABASE_URL=postgresql://adcp:localdev@localhost:53198/adcp_test \ @@ -13,6 +12,8 @@ import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; import request from 'supertest'; +import { randomUUID } from 'node:crypto'; +import { AAOAdminLookupUnavailableError } from '../../src/addie/admin-status-lookup.js'; import type { Pool } from 'pg'; import { HTTPServer } from '../../src/http.js'; import { initializeDatabase, closeDatabase } from '../../src/db/client.js'; @@ -21,6 +22,8 @@ import { AAO_UA_COMPLIANCE } from '../../src/config/user-agents.js'; import { HOSTED_FULL_COMPLIANCE_TIMEOUT_MS } from '../../src/services/hosted-compliance-version.js'; import { ComplianceRefreshRequestsDatabase } from '../../src/db/compliance-refresh-requests-db.js'; import { ComplianceDatabase } from '../../src/db/compliance-db.js'; +import { AgentContextDatabase } from '../../src/db/agent-context-db.js'; +import type { ComplianceRefreshQueue } from '../../src/services/compliance-refresh-queue.js'; import { complianceRunProvenance } from '../../src/compliance/run-provenance.js'; import type { ComplianceResult, ComplyOptions } from '@adcp/sdk/testing'; @@ -42,9 +45,21 @@ const SECOND_ORG_ID = `org_test_refresh_second_${RUN_SUFFIX}`; // expects it to succeed. const ownedAgentUrl = (slug: string) => `https://refresh-${slug}-${RUN_SUFFIX}.example.com/mcp`; const OTHER_AGENT_URL = `https://other-agent-${RUN_SUFFIX}.example.com/mcp`; +const LEGACY_USER_CASES = (['manual', 'owner_test'] as const).flatMap(triggeredBy => + (['queued', 'running'] as const).flatMap(status => + [false, true].map(checkpointed => ({ + triggeredBy, status, checkpointed, + slug: `legacy-${triggeredBy}-${status}-${checkpointed ? 'checkpoint' : 'fresh'}`, + })), + ), +); const ALL_OWNED_URLS = [ + ...LEGACY_USER_CASES.map(({ slug }) => ownedAgentUrl(slug)), + ownedAgentUrl('legacy-static-owner'), ownedAgentUrl('owner'), ownedAgentUrl('admin'), + ownedAgentUrl('linked-owner'), + ownedAgentUrl('owner-admin-outage'), ownedAgentUrl('probe-fail'), ownedAgentUrl('paused'), ownedAgentUrl('rate-limit'), @@ -70,12 +85,19 @@ const ALL_OWNED_URLS = [ // Toggle which user the auth middleware stamps onto the request. Tests // flip this between owner / other / admin to exercise the auth branches. let currentUserId: string | null = OWNER_USER_ID; +let currentAuthWorkosUserId: string | undefined; +let currentIsAdmin: boolean | undefined; +let currentRequestUser: { id: string; authWorkosUserId?: string; email: string; isAdmin?: boolean } | undefined; vi.mock('../../src/middleware/auth.js', async () => { const actual = await vi.importActual>('../../src/middleware/auth.js'); const stampUser = (req: { user?: unknown; isStaticAdminApiKey?: boolean }) => { if (currentUserId === null) return; - req.user = { id: currentUserId, email: `${currentUserId}@test.com` }; + currentRequestUser = { + id: currentUserId, authWorkosUserId: currentAuthWorkosUserId, + email: `${currentAuthWorkosUserId ?? currentUserId}@test.com`, isAdmin: currentIsAdmin, + }; + req.user = currentRequestUser; if (currentUserId === STATIC_ADMIN_USER_ID) { req.isStaticAdminApiKey = true; } @@ -116,9 +138,11 @@ vi.mock('../../src/billing/stripe-client.js', () => ({ // Admin lookup used by the /refresh route. Default to non-admin; the // admin test toggles it for one user id. -const isAdminMock = vi.fn(async (userId: string) => userId === ADMIN_USER_ID); -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ - isWebUserAAOAdmin: (userId: string) => isAdminMock(userId), +const isAdminMock = vi.fn(async (principal: { id: string; authWorkosUserId?: string }) => (principal.authWorkosUserId ?? principal.id) === ADMIN_USER_ID); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => ({ + ...(await importOriginal()), + isWebUserAAOAdmin: (userId: string) => isAdminMock({ id: userId }), + isAuthenticatedUserAAOAdmin: (principal: { id: string; authWorkosUserId?: string }) => isAdminMock(principal), })); // Stub the actual probe — the test doesn't need real outbound capability @@ -301,7 +325,11 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { beforeEach(() => { currentUserId = OWNER_USER_ID; - isAdminMock.mockClear(); + currentAuthWorkosUserId = undefined; + currentIsAdmin = undefined; + currentRequestUser = undefined; + isAdminMock.mockReset(); + isAdminMock.mockImplementation(async (principal: { id: string; authWorkosUserId?: string }) => (principal.authWorkosUserId ?? principal.id) === ADMIN_USER_ID); refreshSingleAgentMock.mockReset(); refreshSingleAgentMock.mockResolvedValue({ online: true, @@ -329,6 +357,144 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { const url = (agentUrl: string) => `/api/registry/agents/${encodeURIComponent(agentUrl)}/refresh`; + const stopRefreshWorker = async () => { + const queue = (server as unknown as { complianceRefreshQueue: ComplianceRefreshQueue }).complianceRefreshQueue; + queue.stop(); + await vi.waitFor(() => { + expect((queue as unknown as { processing: boolean }).processing).toBe(false); + }); + return queue; + }; + + it.each(LEGACY_USER_CASES)( + 'terminally rejects legacy user $triggeredBy $status checkpointed=$checkpointed before any domain work', + async ({ triggeredBy, status, checkpointed, slug }) => { + const queue = await stopRefreshWorker(); + const operationId = randomUUID(); + const agentUrl = ownedAgentUrl(slug); + const runId = randomUUID(); + const canonicalUserId = triggeredBy === 'manual' ? ADMIN_USER_ID : OWNER_USER_ID; + const probe = checkpointed ? { + online: true, tools_count: 4, response_time_ms: 120, inferred_type: 'governance', + type_promoted: false, oauth_required: false, checked_at: new Date().toISOString(), + } : null; + const context = await new AgentContextDatabase().create({ + organization_id: TEST_ORG_ID, agent_url: agentUrl, created_by: OWNER_USER_ID, + }); + await new AgentContextDatabase().saveAuthToken(context.id, 'legacy-test-bearer-do-not-use-in-prod', 'bearer'); + await pool.query( + `INSERT INTO agent_compliance_refresh_requests + (id, agent_url, owner_org_id, requester_type, requested_by_user_id, triggered_by, + test_session_id, status, attempts, max_attempts, available_at, + lease_owner, lease_token, lease_expires_at, probe_result_json, auth_available) + VALUES ($1, $2, $3, 'user', $4, $5, $6, $7, $8, 5, NOW(), $9, $10, $11, $12::jsonb, $13)`, + [operationId, agentUrl, triggeredBy === 'owner_test' ? TEST_ORG_ID : null, + canonicalUserId, triggeredBy, `legacy-refresh-${operationId}`, status, + status === 'running' ? 1 : 0, status === 'running' ? 'expired-worker' : null, + status === 'running' ? randomUUID() : null, + status === 'running' ? new Date(Date.now() - 60_000) : null, + probe ? JSON.stringify(probe) : null, checkpointed ? true : null], + ); + if (checkpointed) { + await pool.query( + `INSERT INTO agent_compliance_runs + (id, agent_url, lifecycle_stage, overall_status, triggered_by, dry_run, refresh_operation_id) + VALUES ($1, $2, 'production', 'passing', $3, FALSE, $4)`, + [runId, agentUrl, triggeredBy, operationId], + ); + } + const domainState = () => pool.query( + `SELECT * FROM ( + SELECT 'runs' AS source, to_jsonb(t) AS value FROM agent_compliance_runs t WHERE agent_url = $1 + UNION ALL SELECT 'status', to_jsonb(t) FROM agent_compliance_status t WHERE agent_url = $1 + UNION ALL SELECT 'storyboards', to_jsonb(t) FROM agent_storyboard_status t WHERE agent_url = $1 + UNION ALL SELECT 'diagnostics', to_jsonb(t) FROM agent_compliance_step_diagnostics t WHERE agent_url = $1 + UNION ALL SELECT 'badges', to_jsonb(t) FROM agent_verification_badges t WHERE agent_url = $1 + UNION ALL SELECT 'health', to_jsonb(t) FROM agent_health_snapshot t WHERE agent_url = $1 + UNION ALL SELECT 'capabilities', to_jsonb(t) FROM agent_capabilities_snapshot t WHERE agent_url = $1 + UNION ALL SELECT 'credentials', to_jsonb(t) FROM agent_contexts t WHERE agent_url = $1) AS domain_state + ORDER BY source, value::text`, + [agentUrl], + ); + const before = await domainState(); + const forbiddenCalls = [ + vi.spyOn(ComplianceDatabase.prototype, 'getRunForRefreshOperation'), + vi.spyOn(ComplianceDatabase.prototype, 'resolveOwnerAuth'), + vi.spyOn(ComplianceDatabase.prototype, 'recordComplianceRun'), + vi.spyOn(ComplianceDatabase.prototype, 'upsertBadge'), + vi.spyOn(ComplianceDatabase.prototype, 'revokeBadge'), + vi.spyOn(ComplianceDatabase.prototype, 'revokeAllBadges'), + vi.spyOn(AgentContextDatabase.prototype, 'getByOrgAndUrl'), + vi.spyOn(AgentContextDatabase.prototype, 'getAuthInfoByOrgAndUrl'), + vi.spyOn(AgentContextDatabase.prototype, 'getOAuthTokensByOrgAndUrl'), + vi.spyOn(AgentContextDatabase.prototype, 'getOAuthClientCredentialsByOrgAndUrl'), + vi.spyOn(AgentContextDatabase.prototype, 'findOwnerOrgWithSavedAuth'), + vi.spyOn(ComplianceRefreshRequestsDatabase.prototype, 'recordProbeResult'), + vi.spyOn(ComplianceRefreshRequestsDatabase.prototype, 'markSucceeded'), + vi.spyOn(ComplianceRefreshRequestsDatabase.prototype, 'requeueAfterFailure'), + ]; + try { + expect(await queue.processQueue()).toEqual({ claimed: 1, succeeded: 0, failed: 1, lostLease: 0 }); + const failed = await pool.query('SELECT * FROM agent_compliance_refresh_requests WHERE id = $1', [operationId]); + expect(failed.rows[0]).toMatchObject({ + status: 'failed', attempts: status === 'running' ? 2 : 1, + last_error_code: 'authorization_provenance_missing', + last_error: 'Refresh requester authorization provenance is unavailable', + lease_owner: null, lease_token: null, lease_expires_at: null, + result_json: null, probe_result_json: probe, + }); + expect(failed.rows[0].completed_at).toBeInstanceOf(Date); + expect(await queue.processQueue()).toEqual({ claimed: 0, succeeded: 0, failed: 0, lostLease: 0 }); + expect((await pool.query('SELECT attempts FROM agent_compliance_refresh_requests WHERE id = $1', [operationId])).rows[0].attempts) + .toBe(status === 'running' ? 2 : 1); + for (const spy of forbiddenCalls) expect(spy).not.toHaveBeenCalled(); + expect(isAdminMock).not.toHaveBeenCalled(); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await domainState()).rows).toEqual(before.rows); + + currentUserId = STATIC_ADMIN_USER_ID; + const response = await request(app).get(`${url(agentUrl)}es/${operationId}`).send(); + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ + status: 'failed', + error: { + code: 'authorization_provenance_missing', + message: 'Refresh requester authorization provenance is unavailable', + }, + }); + } finally { + for (const spy of forbiddenCalls) spy.mockRestore(); + await pool.query('DELETE FROM agent_compliance_runs WHERE id = $1', [runId]); + await pool.query('DELETE FROM agent_compliance_refresh_requests WHERE id = $1', [operationId]); + await pool.query('DELETE FROM agent_contexts WHERE id = $1', [context.id]); + queue.start(); + } + }, + ); + + it('preserves rejection of a legacy static-admin row carrying an owner context without a requester', async () => { + const queue = await stopRefreshWorker(); + const operationId = randomUUID(); + const agentUrl = ownedAgentUrl('legacy-static-owner'); + try { + await pool.query( + `INSERT INTO agent_compliance_refresh_requests + (id, agent_url, owner_org_id, requester_type, requested_by_user_id, triggered_by, test_session_id) + VALUES ($1, $2, $3, 'static_admin', NULL, 'owner_test', $4)`, + [operationId, agentUrl, TEST_ORG_ID, `legacy-refresh-${operationId}`], + ); + expect(await queue.processQueue()).toEqual({ claimed: 1, succeeded: 0, failed: 1, lostLease: 0 }); + const failed = await pool.query('SELECT status, last_error_code FROM agent_compliance_refresh_requests WHERE id = $1', [operationId]); + expect(failed.rows[0]).toEqual({ status: 'failed', last_error_code: 'authorization_revoked' }); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + } finally { + await pool.query('DELETE FROM agent_compliance_refresh_requests WHERE id = $1', [operationId]); + queue.start(); + } + }); + it.each(['complete', 'timed_out'] as const)('reports targeted %s runs as audit-only with provenance and no diagnostics', async completeness => { const agentUrl = ownedAgentUrl(`targeted-${completeness}`); complyMock.mockImplementation(async (_url: string, options: ComplyOptions) => { @@ -349,7 +515,8 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { .toBe(res.body.provenance.test_session_id); }); - it('owner can refresh and gets the snapshot back', async () => { + it('static admin can refresh and gets the snapshot back', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('owner'); const res = await request(app).post(url(agentUrl)).send(); expect(res.status).toBe(200); @@ -388,8 +555,8 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { [agentUrl], ); expect(latestRun.rows[0]).toMatchObject({ - triggered_by: 'owner_test', - triggered_org_id: TEST_ORG_ID, + triggered_by: 'manual', + triggered_org_id: null, }); expect(latestRun.rows[0].notices_json).toEqual([{ severity: 'info', @@ -417,6 +584,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }); it('public compliance bounds notice output while retaining the raw private record', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('public-notices'); const refresh = await request(app).post(url(agentUrl)).send(); expect(refresh.status).toBe(200); @@ -487,12 +655,122 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { expect(stored.rows[0].notices_json[0]).toHaveProperty('experimental_context'); }); - it('admin can refresh an agent they do not own', async () => { + it('fences administrator session refresh until durable credential provenance is supported', async () => { currentUserId = ADMIN_USER_ID; const agentUrl = ownedAgentUrl('admin'); const res = await request(app).post(url(agentUrl)).send(); - expect(res.status).toBe(200); - expect(refreshSingleAgentMock).toHaveBeenCalledWith(agentUrl, expect.any(Object)); + expect(res.status).toBe(503); + expect(res.body.code).toBe('refresh_authorization_provenance_required'); + expect(res.headers['retry-after']).toBe('60'); + expect(res.headers['cache-control']).toBe('private, no-store'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + const queued = await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl]); + expect(queued.rows).toEqual([]); + }); + + it.each([ + { authenticated: ADMIN_USER_ID, canonical: OTHER_USER_ID, status: 503 }, + { authenticated: OTHER_USER_ID, canonical: ADMIN_USER_ID, status: 403 }, + ])('uses exact $authenticated admin authorization linked to $canonical before refresh admission', async ({ authenticated, canonical, status }) => { + currentUserId = canonical; + currentAuthWorkosUserId = authenticated; + currentIsAdmin = true; + const response = await request(app).post(url(OTHER_AGENT_URL)).send(); + expect(response.status).toBe(status); + if (status === 503) expect(response.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + const queued = await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [OTHER_AGENT_URL]); + expect(queued.rows).toEqual([]); + // The rate limiter can independently check its optional admin exemption; + // the route must additionally resolve its immutable captured principal. + const principals = isAdminMock.mock.calls.map(([principal]) => principal); + expect(principals.every(principal => (principal.authWorkosUserId ?? principal.id) === authenticated)).toBe(true); + const routePrincipal = principals.find(principal => Object.isFrozen(principal)); + expect(routePrincipal).toMatchObject({ id: authenticated }); + }); + + it('fences linked owner refresh instead of persisting ambiguous credential provenance', async () => { + currentUserId = OTHER_USER_ID; + currentAuthWorkosUserId = OWNER_USER_ID; + const agentUrl = ownedAgentUrl('linked-owner'); + const response = await request(app).post(url(agentUrl)).send(); + expect(response.status).toBe(503); + expect(response.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); + }); + + it('does not inherit canonical organization ownership on refresh', async () => { + currentUserId = OWNER_USER_ID; + currentAuthWorkosUserId = OTHER_USER_ID; + const agentUrl = ownedAgentUrl('linked-owner'); + const response = await request(app).post(url(agentUrl)).send(); + expect(response.status).toBe(403); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); + }); + + it('fences a confirmed unlinked owner without misreporting a separate platform-admin outage', async () => { + isAdminMock.mockRejectedValue(new AAOAdminLookupUnavailableError()); + const agentUrl = ownedAgentUrl('owner-admin-outage'); + const response = await request(app).post(url(agentUrl)).send(); + expect(response.status).toBe(503); + expect(response.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); + expect(isAdminMock.mock.calls.every(([principal]) => (principal.authWorkosUserId ?? principal.id) === OWNER_USER_ID)).toBe(true); + }); + + it('reports non-owner admin lookup unavailability without enqueuing or trusting isAdmin', async () => { + currentUserId = ADMIN_USER_ID; + currentAuthWorkosUserId = OTHER_USER_ID; + currentIsAdmin = true; + isAdminMock.mockRejectedValue(new AAOAdminLookupUnavailableError()); + const response = await request(app).post(url(OTHER_AGENT_URL)).send(); + expect(response.status).toBe(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(response.headers['cache-control']).toBe('no-store'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [OTHER_AGENT_URL])).rows).toEqual([]); + }); + + it.each([ + { authenticated: ADMIN_USER_ID, canonical: OTHER_USER_ID, allowed: true }, + { authenticated: OTHER_USER_ID, canonical: ADMIN_USER_ID, allowed: false }, + ])('authorizes refresh status with exact $authenticated and immutable lookup provenance', async ({ authenticated, canonical, allowed }) => { + const operationId = randomUUID(); + await pool.query( + `INSERT INTO agent_compliance_refresh_requests + (id, agent_url, requester_type, requested_by_user_id, triggered_by, test_session_id, status, result_json, completed_at) + VALUES ($1, $2, 'user', $3, 'manual', $4, 'succeeded', '{"online":true}'::jsonb, NOW())`, + [operationId, OTHER_AGENT_URL, OWNER_USER_ID, `test-status-${operationId}`], + ); + currentUserId = canonical; + currentAuthWorkosUserId = authenticated; + currentIsAdmin = !allowed; + isAdminMock.mockImplementationOnce(async (principal) => { + await Promise.resolve(); + currentRequestUser!.id = authenticated; + currentRequestUser!.authWorkosUserId = canonical; + return principal.id === ADMIN_USER_ID; + }); + try { + const response = await request(app).get(`${url(OTHER_AGENT_URL)}es/${operationId}`).send(); + expect(response.status).toBe(allowed ? 200 : 404); + if (allowed) expect(response.body.result).toEqual({ online: true }); + const principal = isAdminMock.mock.calls[0][0]; + expect(principal.id).toBe(authenticated); + expect(Object.isFrozen(principal)).toBe(true); + } finally { + await pool.query('DELETE FROM agent_compliance_refresh_requests WHERE id = $1', [operationId]); + } }); it('static admin API key can refresh and rerun compliance for an agent it does not own', async () => { @@ -558,6 +836,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }); it('returns 502 when the probe throws', async () => { + currentUserId = STATIC_ADMIN_USER_ID; refreshSingleAgentMock.mockRejectedValue(new Error('Probe timeout')); const res = await request(app).post(url(ownedAgentUrl('probe-fail'))).send(); expect(res.status).toBe(502); @@ -568,6 +847,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }); it('returns 409 when monitoring is paused', async () => { + currentUserId = STATIC_ADMIN_USER_ID; refreshSingleAgentMock.mockRejectedValue(new Error('Monitoring paused for this agent')); const res = await request(app).post(url(ownedAgentUrl('paused'))).send(); expect(res.status).toBe(409); @@ -575,6 +855,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }); it('returns an immediate durable handle and polls a long-running refresh to completion', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('async-refresh'); let resolveCompliance!: (value: ReturnType) => void; const deferredCompliance = new Promise>((resolve) => { @@ -605,7 +886,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { const forbidden = await request(app).get(accepted.body.status_url).send(); expect(forbidden.status).toBe(404); - currentUserId = OWNER_USER_ID; + currentUserId = STATIC_ADMIN_USER_ID; const waitForStatus = async (target: 'running' | 'succeeded') => { const deadline = Date.now() + 12_000; while (Date.now() < deadline) { @@ -632,6 +913,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }, 20_000); it('falls back to 202 at the legacy deadline without Prefer, then completes by polling', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('legacy-timeout'); let resolveCompliance!: (value: ReturnType) => void; const deferredCompliance = new Promise>((resolve) => { @@ -768,6 +1050,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }, 30_000); it('retries failed badge persistence from the saved run without executing a second suite', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('badge-retry'); complyMock.mockResolvedValueOnce(makeComplianceResult({ specialisms: ['sales-broadcast-tv'], @@ -807,6 +1090,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }, 40_000); it('surfaces an allowlisted badge failure after retry exhaustion', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('badge-retry-exhausted'); complyMock.mockResolvedValueOnce(makeComplianceResult({ specialisms: ['sales-broadcast-tv'], @@ -849,6 +1133,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { }, 40_000); it('recovers the same operation handle when a completed response is retried', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('rate-limit'); const first = await request(app).post(url(agentUrl)).send(); expect(first.status).toBe(200); @@ -869,7 +1154,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { // even though evaluate_agent_quality (which resolves saved auth) worked // fine. The route now resolves owner-org auth and threads it to the // crawler so the probe sees the same credentials. - it('threads the org-saved bearer token to the crawler', async () => { + it('fences owner refresh before using an organization-saved bearer token', async () => { const agentUrl = ownedAgentUrl('saved-bearer'); const { AgentContextDatabase } = await import('../../src/db/agent-context-db.js'); const db = new AgentContextDatabase(); @@ -883,20 +1168,17 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { try { const res = await request(app).post(url(agentUrl)).send(); - expect(res.status).toBe(200); - expect(refreshSingleAgentMock).toHaveBeenCalledWith( - agentUrl, - expect.objectContaining({ - auth: { type: 'bearer', token: FAKE_BEARER }, - ownerOrgId: TEST_ORG_ID, - }), - ); + expect(res.status).toBe(503); + expect(res.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); } finally { await pool.query('DELETE FROM agent_contexts WHERE id = $1', [context.id]); } }); - it('canonicalizes the requested URL before owner auth lookup and probe', async () => { + it('fences a canonicalized owner URL before resolving saved auth or probing', async () => { const agentUrl = ownedAgentUrl('canonical-saved-bearer'); const requestedUrl = agentUrl .replace('https://', 'HTTPS://') @@ -913,14 +1195,11 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { try { const res = await request(app).post(url(requestedUrl)).send(); - expect(res.status).toBe(200); - expect(refreshSingleAgentMock).toHaveBeenCalledWith( - agentUrl, - expect.objectContaining({ - auth: { type: 'bearer', token: FAKE_BEARER }, - ownerOrgId: TEST_ORG_ID, - }), - ); + expect(res.status).toBe(503); + expect(res.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); } finally { await pool.query('DELETE FROM agent_contexts WHERE id = $1', [context.id]); } @@ -961,7 +1240,7 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { } }); - it('uses the selected org credentials when a shared agent is refreshed', async () => { + it('fences selected-organization owner refresh before using saved credentials', async () => { const agentUrl = ownedAgentUrl('selected-org-refresh'); const { AgentContextDatabase } = await import('../../src/db/agent-context-db.js'); const db = new AgentContextDatabase(); @@ -978,14 +1257,11 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { .post(url(agentUrl)) .send({ organization_id: SECOND_ORG_ID }); - expect(res.status).toBe(200); - expect(refreshSingleAgentMock).toHaveBeenCalledWith( - agentUrl, - expect.objectContaining({ - auth: { type: 'bearer', token }, - ownerOrgId: SECOND_ORG_ID, - }), - ); + expect(res.status).toBe(503); + expect(res.body.code).toBe('refresh_authorization_provenance_required'); + expect(refreshSingleAgentMock).not.toHaveBeenCalled(); + expect(complyMock).not.toHaveBeenCalled(); + expect((await pool.query('SELECT id FROM agent_compliance_refresh_requests WHERE agent_url = $1', [agentUrl])).rows).toEqual([]); } finally { await pool.query('DELETE FROM agent_contexts WHERE id = $1', [context.id]); } @@ -1021,7 +1297,8 @@ describe('POST /api/registry/agents/:encodedUrl/refresh (integration)', () => { expect(stored.rows).toEqual([{ organization_id: SECOND_ORG_ID }]); }); - it('fans out badge issuance for an owner refresh with a passing specialism', async () => { + it('fans out badge issuance for a static-admin refresh with a passing specialism', async () => { + currentUserId = STATIC_ADMIN_USER_ID; const agentUrl = ownedAgentUrl('badge-fanout'); complyMock.mockResolvedValueOnce(makeComplianceResult({ specialisms: ['sales-broadcast-tv'], diff --git a/server/tests/integration/registry-reader-baseline-public-endpoints.test.ts b/server/tests/integration/registry-reader-baseline-public-endpoints.test.ts index 24687c547bf..a4dcfef4a85 100644 --- a/server/tests/integration/registry-reader-baseline-public-endpoints.test.ts +++ b/server/tests/integration/registry-reader-baseline-public-endpoints.test.ts @@ -360,6 +360,8 @@ describe('Registry reader baseline — public endpoints', () => { }); it('enforces non-enumerating crawl-status ownership and both admin paths', async () => { + const originalAdminEmails = process.env.ADMIN_EMAILS; + delete process.env.ADMIN_EMAILS; const requestId = '22222222-2222-4222-8222-222222222222'; const missingId = '33333333-3333-4333-8333-333333333333'; const now = new Date(); @@ -404,6 +406,13 @@ describe('Registry reader baseline — public endpoints', () => { expect(forbidden.body).toEqual(missing.body); setRequireAuthUser({ id: 'web-admin', email: 'admin@example.com', isAdmin: true }); + const staleAdminFlag = await request(app) + .get(`/api/registry/crawl-request/${requestId}`); + expect(staleAdminFlag.status).toBe(404); + + // A presentation flag is not authority. Supply the credential's + // independently configured break-glass grant for this positive case. + process.env.ADMIN_EMAILS = 'admin@example.com'; const webAdmin = await request(app) .get(`/api/registry/crawl-request/${requestId}`); expect(webAdmin.status).toBe(200); @@ -414,6 +423,8 @@ describe('Registry reader baseline — public endpoints', () => { .set('Authorization', 'Bearer static-admin-test'); expect(staticAdmin.status).toBe(200); } finally { + if (originalAdminEmails === undefined) delete process.env.ADMIN_EMAILS; + else process.env.ADMIN_EMAILS = originalAdminEmails; setRequireAuthUser({ id: DEFAULT_TEST_USER_ID, email: 'registry-baseline@test.com', diff --git a/server/tests/integration/working-group-document-privacy.test.ts b/server/tests/integration/working-group-document-privacy.test.ts index d318292f460..e8bf2f7fb0a 100644 --- a/server/tests/integration/working-group-document-privacy.test.ts +++ b/server/tests/integration/working-group-document-privacy.test.ts @@ -26,6 +26,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ invalidateWebAdminStatusCache: vi.fn(), isWebUserAAOAdmin: vi.fn(async (userId: string) => userId === 'privacy-admin'), })); + +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async (userId: string) => userId === 'privacy-admin'); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); vi.mock('../../src/addie/index.js', () => ({ invalidateMemberContextCache: vi.fn() })); vi.mock('../../src/addie/jobs/committee-document-indexer.js', () => ({ reindexDocument: vi.fn() })); vi.mock('../../src/addie/mcp/docs-indexer.js', () => ({ refreshWorkingGroupDocs: vi.fn() })); diff --git a/server/tests/unit/aao-admin-routes.test.ts b/server/tests/unit/aao-admin-routes.test.ts index 255221e5e10..894568d7971 100644 --- a/server/tests/unit/aao-admin-routes.test.ts +++ b/server/tests/unit/aao-admin-routes.test.ts @@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('../../src/middleware/auth.js', () => ({ requireGlobalAdmin: [ (req: express.Request, _res: express.Response, next: express.NextFunction) => { - req.user = { id: 'admin_1', email: 'admin@example.test' } as never; + req.user = { id: 'admin_1', email: 'admin@example.test', authWorkosUserId: req.get('X-Test-Authenticated-Credential') } as never; if (req.get('X-Test-Omit-Admin-Mechanism') !== 'true') { req.adminAccessMechanism = 'break_glass_admin_email'; } @@ -96,6 +96,14 @@ describe('AAO site-admin mutation routes', () => { expect(mocks.invalidate).toHaveBeenCalledOnce(); }); + it.each(['grant', 'revoke'])('attributes %s to the exact authenticated credential', async (operation) => { + const response = await request(createApp()).post(`/api/admin/aao-admin/${operation}`) + .set('X-Test-Authenticated-Credential', 'user_authenticated_admin') + .send({ workos_user_id: 'user_target', reason: 'Coverage rotation' }); + expect(response.status).toBe(operation === 'grant' ? 201 : 200); + expect(operation === 'grant' ? mocks.grant : mocks.revoke).toHaveBeenCalledWith(expect.objectContaining({ actorUserId: 'user_authenticated_admin' })); + }); + it('does not clear a cache entry when no active membership was revoked', async () => { mocks.revoke.mockResolvedValue(null); const response = await request(createApp()) diff --git a/server/tests/unit/billing-admin-tenant-boundary.test.ts b/server/tests/unit/billing-admin-tenant-boundary.test.ts index 1c35c4e28b5..c5702a9095b 100644 --- a/server/tests/unit/billing-admin-tenant-boundary.test.ts +++ b/server/tests/unit/billing-admin-tenant-boundary.test.ts @@ -26,6 +26,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: (...args: unknown[]) => mocks.isWebUserAAOAdmin(...args), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = (...args: unknown[]) => mocks.isWebUserAAOAdmin(...args); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/middleware/auth.js', async (importOriginal) => { const actual = await importOriginal(); diff --git a/server/tests/unit/compliance-refresh-queue.test.ts b/server/tests/unit/compliance-refresh-queue.test.ts index 402795614c2..54600e91ac9 100644 --- a/server/tests/unit/compliance-refresh-queue.test.ts +++ b/server/tests/unit/compliance-refresh-queue.test.ts @@ -39,6 +39,37 @@ function claimedRequest(): ClaimedComplianceRefreshRequest { } describe('ComplianceRefreshQueue', () => { + it.each(['manual', 'owner_test'] as const)('terminalizes missing provenance for %s without retrying', async (triggeredBy) => { + const request = { ...claimedRequest(), triggered_by: triggeredBy }; + const release = vi.fn().mockResolvedValue(undefined); + const markFailed = vi.fn().mockResolvedValue(true); + const requeueAfterFailure = vi.fn(); + const markSucceeded = vi.fn(); + const db = { + claimDue: vi.fn().mockResolvedValue({ requests: [request], terminalizedExpired: 0 }), + acquireExecutionFence: vi.fn().mockResolvedValue({ isValid: () => true, release }), + heartbeat: vi.fn(), + requeueAfterFailure, + markSucceeded, + markFailed, + deleteTerminalBefore: vi.fn().mockResolvedValue(0), + } as unknown as ComplianceRefreshRequestsDatabase; + const queue = new ComplianceRefreshQueue(async () => { + throw Object.assign(new Error('untrusted upstream diagnostics'), { code: 'authorization_provenance_missing' }); + }, db, 'worker-test'); + + await expect(queue.processQueue()).resolves.toEqual({ claimed: 1, succeeded: 0, failed: 1, lostLease: 0 }); + expect(markFailed).toHaveBeenCalledExactlyOnceWith( + request.id, + request.lease_token, + 'authorization_provenance_missing', + 'Refresh requester authorization provenance is unavailable', + ); + expect(requeueAfterFailure).not.toHaveBeenCalled(); + expect(markSucceeded).not.toHaveBeenCalled(); + expect(release).toHaveBeenCalledOnce(); + }); + it('never persists or logs arbitrary exception codes and messages', async () => { const request = claimedRequest(); const markFailed = vi.fn().mockResolvedValue(true); diff --git a/server/tests/unit/mastermind-council-join-route.test.ts b/server/tests/unit/mastermind-council-join-route.test.ts index fe8969231e0..e398e1adab8 100644 --- a/server/tests/unit/mastermind-council-join-route.test.ts +++ b/server/tests/unit/mastermind-council-join-route.test.ts @@ -33,6 +33,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ invalidateWebAdminStatusCache: vi.fn(), isWebUserAAOAdmin: vi.fn().mockResolvedValue(false), })); + +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn().mockResolvedValue(false); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); vi.mock('../../src/addie/index.js', () => ({ invalidateMemberContextCache: vi.fn() })); vi.mock('../../src/addie/jobs/committee-document-indexer.js', () => ({ reindexDocument: vi.fn() })); vi.mock('../../src/addie/mcp/docs-indexer.js', () => ({ refreshWorkingGroupDocs: vi.fn() })); diff --git a/server/tests/unit/member-profile-admin-global-auth.test.ts b/server/tests/unit/member-profile-admin-global-auth.test.ts index 5edff42ddf3..0f25ecd69a5 100644 --- a/server/tests/unit/member-profile-admin-global-auth.test.ts +++ b/server/tests/unit/member-profile-admin-global-auth.test.ts @@ -42,6 +42,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: vi.fn().mockResolvedValue(false), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn().mockResolvedValue(false); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + const { createAdminMemberProfileRouter } = await import( '../../src/routes/member-profiles.js' ); diff --git a/server/tests/unit/network-health-security.test.ts b/server/tests/unit/network-health-security.test.ts index 94f35fa58c4..f4d82ed4634 100644 --- a/server/tests/unit/network-health-security.test.ts +++ b/server/tests/unit/network-health-security.test.ts @@ -60,6 +60,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: mocks.isWebUserAAOAdmin, })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = mocks.isWebUserAAOAdmin; + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/db/network-health-db.js', () => ({ getNetworkSummaries: mocks.getNetworkSummaries, getLatestReport: mocks.getLatestReport, diff --git a/server/tests/unit/perspective-asset-cache-privacy.test.ts b/server/tests/unit/perspective-asset-cache-privacy.test.ts index a5c1b6a74f7..f97fda36015 100644 --- a/server/tests/unit/perspective-asset-cache-privacy.test.ts +++ b/server/tests/unit/perspective-asset-cache-privacy.test.ts @@ -59,6 +59,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', async (importOriginal) => { }; }); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = (...args: unknown[]) => mocks.isWebUserAAOAdmin(...args); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/middleware/auth.js', async () => { const actual = await vi.importActual( '../../src/middleware/auth.js', diff --git a/server/tests/unit/perspective-external-url-validation.test.ts b/server/tests/unit/perspective-external-url-validation.test.ts index 424516c5876..b123d8530d8 100644 --- a/server/tests/unit/perspective-external-url-validation.test.ts +++ b/server/tests/unit/perspective-external-url-validation.test.ts @@ -28,6 +28,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: (...args: unknown[]) => mocks.isAdmin(...args), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = (...args: unknown[]) => mocks.isAdmin(...args); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + vi.mock('../../src/slack/client.js', () => ({ sendChannelMessage: vi.fn().mockResolvedValue(undefined), })); diff --git a/server/tests/unit/rate-limit-retry-after.test.ts b/server/tests/unit/rate-limit-retry-after.test.ts index 83a8e89830e..302b40bd8d2 100644 --- a/server/tests/unit/rate-limit-retry-after.test.ts +++ b/server/tests/unit/rate-limit-retry-after.test.ts @@ -17,6 +17,24 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: vi.fn().mockResolvedValue(false), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async (id: string) => { + if (id === 'user_lookup_unavailable') throw new actual.AAOAdminLookupUnavailableError(); + return id === 'user_platform_admin'; + }); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); + /** * Tests for the retryAfter fallback field we surface on the 429 body * from `agentReadRateLimiter` (#2804/#2939). Reverse proxies sometimes @@ -102,11 +120,14 @@ describe('capability probe rate limiter', () => { max?: number; responseStatus?: number; isAdmin?: boolean; + principal?: { id: string; authWorkosUserId?: string; email?: string; isAdmin?: boolean }; + isStaticAdminApiKey?: boolean; } = {}) { const app = express(); app.use((req, _res, next) => { - (req as any).user = { - id: 'capability-probe-rate-limit-user', + (req as any).isStaticAdminApiKey = options.isStaticAdminApiKey; + (req as any).user = options.principal ?? { + id: options.isAdmin ? 'user_platform_admin' : 'capability-probe-rate-limit-user', isAdmin: options.isAdmin === true, }; next(); @@ -154,6 +175,29 @@ describe('capability probe rate limiter', () => { expect((await request(app).get('/probe')).status).toBe(429); }); + it.each([ + ['user_platform_admin', 'user_member', false, 200], + ['user_member', 'user_platform_admin', true, 429], + ] as const)('uses authenticated %s instead of canonical %s or cached flags', async (authenticated, canonical, staleFlag, status) => { + const app = buildApp({ max: 1, principal: { + id: canonical, authWorkosUserId: authenticated, isAdmin: staleFlag, + } }); + expect((await request(app).get('/probe')).status).toBe(200); + expect((await request(app).get('/probe')).status).toBe(status); + }); + + it('applies ordinary limits when administrator authority is unavailable', async () => { + const app = buildApp({ max: 1, principal: { id: 'user_lookup_unavailable', isAdmin: true } }); + expect((await request(app).get('/probe')).status).toBe(200); + expect((await request(app).get('/probe')).status).toBe(429); + }); + + it('preserves the explicitly authenticated static administrator key exemption', async () => { + const app = buildApp({ max: 1, principal: { id: 'admin_api_key' }, isStaticAdminApiKey: true }); + expect((await request(app).get('/probe')).status).toBe(200); + expect((await request(app).get('/probe')).status).toBe(200); + }); + it('bypasses the capability budget for platform admins', async () => { const app = buildApp({ max: 1, isAdmin: true }); diff --git a/server/tests/unit/registry-badge-routes.test.ts b/server/tests/unit/registry-badge-routes.test.ts index 864a91c0a19..a2a9130b30e 100644 --- a/server/tests/unit/registry-badge-routes.test.ts +++ b/server/tests/unit/registry-badge-routes.test.ts @@ -40,10 +40,22 @@ const gradingMocks = vi.hoisted(() => ({ completeGradingProfileProjectionJob: vi.fn(), })); const badgeIssuanceMocks = vi.hoisted(() => ({ runBadgeFanOut: vi.fn() })); +const adminStatusMocks = vi.hoisted(() => ({ + isWebUserAAOAdmin: vi.fn(), + isAuthenticatedUserAAOAdmin: vi.fn(), +})); +const databaseMocks = vi.hoisted(() => ({ query: vi.fn() })); vi.mock('../../src/services/agent-ownership.js', () => ownershipMocks); vi.mock('../../src/notifications/compliance.js', () => notificationMocks); -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ isWebUserAAOAdmin: vi.fn().mockResolvedValue(false) })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => ({ + ...await importOriginal(), + ...adminStatusMocks, +})); +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...await importOriginal(), + query: databaseMocks.query, +})); vi.mock('../../src/middleware/rate-limit.js', () => { const pass: import('express').RequestHandler = (_req, _res, next) => next(); @@ -109,12 +121,16 @@ const VALID_ROLES = [ function buildApp( visibility: 'public' | 'members_only' | 'private' = 'public', - authenticated = false, + authenticated: boolean | { id: string; authWorkosUserId?: string; email?: string } = false, ): express.Express { const app = express(); app.use(express.json()); const passAuth: import('express').RequestHandler = (req, _res, next) => { - if (authenticated) req.user = { id: 'user_badge_owner' } as typeof req.user; + if (authenticated) { + req.user = (typeof authenticated === 'boolean' + ? { id: 'user_badge_owner' } + : authenticated) as typeof req.user; + } next(); }; const config: RegistryApiConfig = { @@ -164,6 +180,12 @@ describe('registry badge routes', () => { ownershipMocks.findOwnerOrgForUser.mockResolvedValue('org_badge_owner'); ownershipMocks.findOwnedAgentVisibility.mockResolvedValue('public'); ownershipMocks.canManageAgentForOrg.mockResolvedValue(true); + adminStatusMocks.isWebUserAAOAdmin.mockReset(); + adminStatusMocks.isWebUserAAOAdmin.mockResolvedValue(false); + adminStatusMocks.isAuthenticatedUserAAOAdmin.mockReset(); + adminStatusMocks.isAuthenticatedUserAAOAdmin.mockResolvedValue(false); + databaseMocks.query.mockReset(); + databaseMocks.query.mockResolvedValue({ rowCount: 1, rows: [{}] }); gradingMocks.selectGradingProfile.mockReset(); gradingMocks.completeGradingProfileProjectionJob.mockReset(); gradingMocks.completeGradingProfileProjectionJob.mockResolvedValue(undefined); @@ -509,6 +531,80 @@ describe('registry badge routes', () => { expect(gradingMocks.selectGradingProfile).not.toHaveBeenCalled(); }); + it('does not inherit grading-profile admin authority from a linked canonical profile', async () => { + ownershipMocks.canManageAgentForOrg.mockResolvedValueOnce(false); + adminStatusMocks.isAuthenticatedUserAAOAdmin.mockImplementation(async ({ id }) => id === 'user_badge_owner'); + + const response = await request(buildApp('private', { + id: 'user_badge_owner', + authWorkosUserId: 'credential_non_admin', + email: 'credential@example.test', + })) + .put(`/api/registry/agents/${encodeURIComponent(AGENT_URL)}/grading-profile`) + .send({ + organization_id: 'org_other', role: 'media-buy', adcp_version: '3.1', + selected_profile: 'spec', assessment_id: '11111111-1111-4111-8111-111111111111', + expected_revision: 0, idempotency_key: '22222222-2222-4222-8222-222222222222', + admin_override_reason: 'Support request', + }); + + expect(response.status).toBe(403); + expect(adminStatusMocks.isAuthenticatedUserAAOAdmin).toHaveBeenCalledWith({ + id: 'credential_non_admin', + email: 'credential@example.test', + }); + expect(databaseMocks.query).not.toHaveBeenCalled(); + expect(gradingMocks.selectGradingProfile).not.toHaveBeenCalled(); + }); + + it('rechecks and audits exact credential authority for a registry-admin override', async () => { + ownershipMocks.canManageAgentForOrg.mockResolvedValueOnce(false); + adminStatusMocks.isAuthenticatedUserAAOAdmin.mockResolvedValue(true); + + const response = await request(buildApp('private', { + id: 'user_linked_profile', + authWorkosUserId: 'credential_admin', + email: 'admin-credential@example.test', + })) + .put(`/api/registry/agents/${encodeURIComponent(AGENT_URL)}/grading-profile`) + .send({ + organization_id: 'org_other', role: 'media-buy', adcp_version: '3.1', + selected_profile: 'spec', assessment_id: '11111111-1111-4111-8111-111111111111', + expected_revision: 0, idempotency_key: '22222222-2222-4222-8222-222222222222', + admin_override_reason: 'Support request', + }); + + expect(response.status).toBe(200); + expect(adminStatusMocks.isAuthenticatedUserAAOAdmin).toHaveBeenCalledTimes(2); + expect(gradingMocks.selectGradingProfile).toHaveBeenCalledWith(expect.objectContaining({ + actorUserId: 'credential_admin', + actorKind: 'registry_admin', + adminOverrideReason: 'Support request', + })); + }); + + it('fails closed when exact registry-admin authority is revoked before dispatch', async () => { + ownershipMocks.canManageAgentForOrg.mockResolvedValueOnce(false); + adminStatusMocks.isAuthenticatedUserAAOAdmin + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(false); + + const response = await request(buildApp('private', { + id: 'user_linked_profile', + authWorkosUserId: 'credential_revoked', + })) + .put(`/api/registry/agents/${encodeURIComponent(AGENT_URL)}/grading-profile`) + .send({ + organization_id: 'org_other', role: 'media-buy', adcp_version: '3.1', + selected_profile: 'spec', assessment_id: '11111111-1111-4111-8111-111111111111', + expected_revision: 0, idempotency_key: '22222222-2222-4222-8222-222222222222', + admin_override_reason: 'Support request', + }); + + expect(response.status).toBe(403); + expect(gradingMocks.selectGradingProfile).not.toHaveBeenCalled(); + }); + it('durably schedules convergence when post-commit token refresh fails', async () => { badgeIssuanceMocks.runBadgeFanOut.mockRejectedValueOnce(new Error('signing unavailable')); const response = await request(buildApp('private', true)) diff --git a/server/tests/unit/registry-brand-force-crawl-route.test.ts b/server/tests/unit/registry-brand-force-crawl-route.test.ts index 9abd2743516..6033814008c 100644 --- a/server/tests/unit/registry-brand-force-crawl-route.test.ts +++ b/server/tests/unit/registry-brand-force-crawl-route.test.ts @@ -3,7 +3,7 @@ import express from 'express'; import request from 'supertest'; const validateCrawlDomainMock = vi.fn(); -const isWebUserAAOAdminMock = vi.fn(); +const isAuthenticatedUserAAOAdminMock = vi.fn(); vi.hoisted(() => { process.env.WORKOS_API_KEY = process.env.WORKOS_API_KEY || 'sk_test_registry_brand_force_crawl'; @@ -18,10 +18,12 @@ vi.mock('../../src/utils/url-security.js', async () => { }; }); -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ - isWebUserAAOAdmin: (userId: string) => isWebUserAAOAdminMock(userId), +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => ({ + ...(await importOriginal()), + isAuthenticatedUserAAOAdmin: (principal: { id: string; authWorkosUserId?: string; email?: string | null }) => isAuthenticatedUserAAOAdminMock(principal), })); +import { AAOAdminLookupUnavailableError } from '../../src/addie/admin-status-lookup.js'; import { createRegistryApiRouter, type RegistryApiConfig } from '../../src/routes/registry-api.js'; const ORIGINAL_ADMIN_EMAILS = process.env.ADMIN_EMAILS; @@ -38,7 +40,7 @@ function brand(overrides: Record) { } function buildApp(options: { - user?: { id: string; email: string; isAdmin?: boolean }; + user?: { id: string; authWorkosUserId?: string; email: string; isAdmin?: boolean }; scanBrandForDomain: ReturnType; getDiscoveredBrandByDomain: ReturnType; }) { @@ -74,7 +76,7 @@ describe('POST /api/registry/brand/:domain/force-crawl', () => { vi.clearAllMocks(); delete process.env.ADMIN_EMAILS; validateCrawlDomainMock.mockImplementation(async (domain: string) => domain.toLowerCase().trim()); - isWebUserAAOAdminMock.mockResolvedValue(false); + isAuthenticatedUserAAOAdminMock.mockImplementation(async (principal: { id: string; authWorkosUserId?: string }) => (principal.authWorkosUserId ?? principal.id) === 'admin_user'); }); afterEach(() => { @@ -225,4 +227,77 @@ describe('POST /api/registry/brand/:domain/force-crawl', () => { expect(scanBrandForDomain).not.toHaveBeenCalled(); expect(getDiscoveredBrandByDomain).not.toHaveBeenCalled(); }); + it.each([ + { authenticated: 'admin_user', canonical: 'member_user', allowed: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false }, + ])('uses exact $authenticated authority linked to $canonical, ignoring stale isAdmin', async ({ authenticated, canonical, allowed }) => { + const user = { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com', isAdmin: !allowed }; + const sideEffect = vi.fn().mockResolvedValue({ found: false, valid: false, variant: null, manifestPersisted: false }); + const app = buildApp({ user, scanBrandForDomain: sideEffect, getDiscoveredBrandByDomain: vi.fn().mockResolvedValue(null) }); + const response = await request(app).post('/api/registry/brand/security.example/force-crawl').send(); + expect(response.status).toBe(allowed ? 200 : 403); + expect(sideEffect).toHaveBeenCalledTimes(Number(allowed)); + expect(isAuthenticatedUserAAOAdminMock).toHaveBeenCalledTimes(allowed ? 2 : 1); + const principal = isAuthenticatedUserAAOAdminMock.mock.calls[0][0]; + expect(principal.authWorkosUserId ?? principal.id).toBe(authenticated); + expect(principal.email).toBe('credential@example.com'); + expect(Object.isFrozen(principal)).toBe(true); + expect(principal).not.toBe(user); + for (const [checked] of isAuthenticatedUserAAOAdminMock.mock.calls) expect(checked).toBe(principal); + }); + + it('returns retryable unavailable without trusting a stale admin flag or running the side effect', async () => { + isAuthenticatedUserAAOAdminMock.mockRejectedValueOnce(new AAOAdminLookupUnavailableError()); + const user = { id: 'admin_user', authWorkosUserId: 'revoked_credential', email: 'credential@example.com', isAdmin: true }; + const sideEffect = vi.fn().mockResolvedValue({ found: false, valid: false, variant: null, manifestPersisted: false }); + const app = buildApp({ user, scanBrandForDomain: sideEffect, getDiscoveredBrandByDomain: vi.fn().mockResolvedValue(null) }); + const response = await request(app).post('/api/registry/brand/security.example/force-crawl').send(); + expect(response.status).toBe(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(response.headers['cache-control']).toBe('no-store'); + expect(sideEffect).not.toHaveBeenCalled(); + }); + + it.each([ + { authenticated: 'admin_user', canonical: 'member_user', allowed: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false }, + ])('captures immutable $authenticated provenance before an awaited authorization lookup', async ({ authenticated, canonical, allowed }) => { + const user = { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com', isAdmin: !allowed }; + isAuthenticatedUserAAOAdminMock.mockImplementationOnce(async (principal) => { + await Promise.resolve(); + user.id = authenticated; + user.authWorkosUserId = canonical; + user.email = 'changed@example.com'; + return (principal.authWorkosUserId ?? principal.id) === 'admin_user'; + }); + const sideEffect = vi.fn().mockResolvedValue({ found: false, valid: false, variant: null, manifestPersisted: false }); + const app = buildApp({ user, scanBrandForDomain: sideEffect, getDiscoveredBrandByDomain: vi.fn().mockResolvedValue(null) }); + const response = await request(app).post('/api/registry/brand/security.example/force-crawl').send(); + expect(response.status).toBe(allowed ? 200 : 403); + expect(sideEffect).toHaveBeenCalledTimes(Number(allowed)); + const principal = isAuthenticatedUserAAOAdminMock.mock.calls[0][0]; + expect(Object.isFrozen(principal)).toBe(true); + expect(principal.authWorkosUserId ?? principal.id).toBe(authenticated); + expect(principal.email).toBe('credential@example.com'); + }); + + it.each(['revoked', 'unavailable'] as const)('fails closed when authorization becomes %s during preflight I/O', async (decision) => { + const user = { id: 'member_user', authWorkosUserId: 'admin_user', email: 'credential@example.com', isAdmin: true }; + isAuthenticatedUserAAOAdminMock.mockResolvedValueOnce(true); + if (decision === 'revoked') isAuthenticatedUserAAOAdminMock.mockResolvedValueOnce(false); + else isAuthenticatedUserAAOAdminMock.mockRejectedValueOnce(new AAOAdminLookupUnavailableError()); + const sideEffect = vi.fn().mockResolvedValue({ found: false, valid: false, variant: null, manifestPersisted: false }); + const app = buildApp({ user, scanBrandForDomain: sideEffect, getDiscoveredBrandByDomain: vi.fn().mockResolvedValue(null) }); + const response = await request(app).post('/api/registry/brand/security.example/force-crawl').send(); + expect(response.status).toBe(decision === 'revoked' ? 403 : 503); + expect(sideEffect).not.toHaveBeenCalled(); + if (decision === 'unavailable') expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(isAuthenticatedUserAAOAdminMock).toHaveBeenCalledTimes(2); + // A refusal before the crawler runs must release its per-domain reservation. + const retry = await request(app).post('/api/registry/brand/security.example/force-crawl').send(); + expect(retry.status).toBe(200); + expect(sideEffect).toHaveBeenCalledTimes(1); + }); + }); diff --git a/server/tests/unit/registry-publisher-adagents-revalidate-route.test.ts b/server/tests/unit/registry-publisher-adagents-revalidate-route.test.ts index 1e3f9320e60..9b70ddfa5b8 100644 --- a/server/tests/unit/registry-publisher-adagents-revalidate-route.test.ts +++ b/server/tests/unit/registry-publisher-adagents-revalidate-route.test.ts @@ -3,7 +3,7 @@ import express from 'express'; import request from 'supertest'; const validateCrawlDomainMock = vi.fn(); -const isWebUserAAOAdminMock = vi.fn(); +const isAuthenticatedUserAAOAdminMock = vi.fn(); vi.hoisted(() => { process.env.WORKOS_API_KEY = process.env.WORKOS_API_KEY || 'sk_test_registry_adagents_revalidate'; @@ -18,10 +18,12 @@ vi.mock('../../src/utils/url-security.js', async () => { }; }); -vi.mock('../../src/addie/admin-status-lookup.js', () => ({ - isWebUserAAOAdmin: (userId: string) => isWebUserAAOAdminMock(userId), +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => ({ + ...(await importOriginal()), + isAuthenticatedUserAAOAdmin: (principal: { id: string; authWorkosUserId?: string; email?: string | null }) => isAuthenticatedUserAAOAdminMock(principal), })); +import { AAOAdminLookupUnavailableError } from '../../src/addie/admin-status-lookup.js'; import { createRegistryApiRouter, type RegistryApiConfig } from '../../src/routes/registry-api.js'; const ORIGINAL_ADMIN_EMAILS = process.env.ADMIN_EMAILS; @@ -29,8 +31,9 @@ const ORIGINAL_DEV_USER_EMAIL = process.env.DEV_USER_EMAIL; const ORIGINAL_DEV_USER_ID = process.env.DEV_USER_ID; function buildApp(options: { - user?: { id: string; email: string; isAdmin?: boolean }; - crawler: Pick; + user?: { id: string; authWorkosUserId?: string; email: string; isAdmin?: boolean }; + crawler: Pick + & Partial>; }) { const app = express(); app.use(express.json()); @@ -68,7 +71,7 @@ describe('POST /api/registry/publisher/:domain/adagents/revalidate', () => { delete process.env.DEV_USER_EMAIL; delete process.env.DEV_USER_ID; validateCrawlDomainMock.mockImplementation(async (domain: string) => domain.toLowerCase().trim()); - isWebUserAAOAdminMock.mockResolvedValue(false); + isAuthenticatedUserAAOAdminMock.mockImplementation(async (principal: { id: string; authWorkosUserId?: string }) => (principal.authWorkosUserId ?? principal.id) === 'admin_user'); }); afterEach(() => { @@ -209,7 +212,7 @@ describe('POST /api/registry/publisher/:domain/adagents/revalidate', () => { it('rejects authenticated non-admin callers', async () => { const revalidatePublisherAdagents = vi.fn(); - isWebUserAAOAdminMock.mockResolvedValue(false); + isAuthenticatedUserAAOAdminMock.mockResolvedValue(false); const res = await request(buildApp({ user: { id: 'member_user', email: 'member@example.com', isAdmin: false }, @@ -236,4 +239,158 @@ describe('POST /api/registry/publisher/:domain/adagents/revalidate', () => { expect(res.body).toMatchObject({ error: 'Authentication required' }); expect(revalidatePublisherAdagents).not.toHaveBeenCalled(); }); + it.each([ + { authenticated: 'admin_user', canonical: 'member_user', allowed: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false }, + ])('uses exact $authenticated authority linked to $canonical, ignoring stale isAdmin', async ({ authenticated, canonical, allowed }) => { + const user = { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com', isAdmin: !allowed }; + const sideEffect = vi.fn().mockResolvedValue({ domain: 'security.example', adagents_valid: true }); + const app = buildApp({ user, crawler: { revalidatePublisherAdagents: sideEffect } }); + const response = await request(app).post('/api/registry/publisher/security.example/adagents/revalidate').send(); + expect(response.status).toBe(allowed ? 200 : 403); + expect(sideEffect).toHaveBeenCalledTimes(Number(allowed)); + expect(isAuthenticatedUserAAOAdminMock).toHaveBeenCalledTimes(allowed ? 2 : 1); + const principal = isAuthenticatedUserAAOAdminMock.mock.calls[0][0]; + expect(principal.authWorkosUserId ?? principal.id).toBe(authenticated); + expect(principal.email).toBe('credential@example.com'); + expect(Object.isFrozen(principal)).toBe(true); + expect(principal).not.toBe(user); + for (const [checked] of isAuthenticatedUserAAOAdminMock.mock.calls) expect(checked).toBe(principal); + }); + + it('returns retryable unavailable without trusting a stale admin flag or running the side effect', async () => { + isAuthenticatedUserAAOAdminMock.mockRejectedValueOnce(new AAOAdminLookupUnavailableError()); + const user = { id: 'admin_user', authWorkosUserId: 'revoked_credential', email: 'credential@example.com', isAdmin: true }; + const sideEffect = vi.fn().mockResolvedValue({ domain: 'security.example', adagents_valid: true }); + const app = buildApp({ user, crawler: { revalidatePublisherAdagents: sideEffect } }); + const response = await request(app).post('/api/registry/publisher/security.example/adagents/revalidate').send(); + expect(response.status).toBe(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(response.headers['cache-control']).toBe('no-store'); + expect(sideEffect).not.toHaveBeenCalled(); + }); + + it.each([ + { authenticated: 'admin_user', canonical: 'member_user', allowed: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false }, + ])('captures immutable $authenticated provenance before an awaited authorization lookup', async ({ authenticated, canonical, allowed }) => { + const user = { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com', isAdmin: !allowed }; + isAuthenticatedUserAAOAdminMock.mockImplementationOnce(async (principal) => { + await Promise.resolve(); + user.id = authenticated; + user.authWorkosUserId = canonical; + user.email = 'changed@example.com'; + return (principal.authWorkosUserId ?? principal.id) === 'admin_user'; + }); + const sideEffect = vi.fn().mockResolvedValue({ domain: 'security.example', adagents_valid: true }); + const app = buildApp({ user, crawler: { revalidatePublisherAdagents: sideEffect } }); + const response = await request(app).post('/api/registry/publisher/security.example/adagents/revalidate').send(); + expect(response.status).toBe(allowed ? 200 : 403); + expect(sideEffect).toHaveBeenCalledTimes(Number(allowed)); + const principal = isAuthenticatedUserAAOAdminMock.mock.calls[0][0]; + expect(Object.isFrozen(principal)).toBe(true); + expect(principal.authWorkosUserId ?? principal.id).toBe(authenticated); + expect(principal.email).toBe('credential@example.com'); + }); + + it.each(['revoked', 'unavailable'] as const)('fails closed when authorization becomes %s during preflight I/O', async (decision) => { + const user = { id: 'member_user', authWorkosUserId: 'admin_user', email: 'credential@example.com', isAdmin: true }; + isAuthenticatedUserAAOAdminMock.mockResolvedValueOnce(true); + if (decision === 'revoked') isAuthenticatedUserAAOAdminMock.mockResolvedValueOnce(false); + else isAuthenticatedUserAAOAdminMock.mockRejectedValueOnce(new AAOAdminLookupUnavailableError()); + const sideEffect = vi.fn().mockResolvedValue({ domain: 'security.example', adagents_valid: true }); + const app = buildApp({ user, crawler: { revalidatePublisherAdagents: sideEffect } }); + const response = await request(app).post('/api/registry/publisher/security.example/adagents/revalidate').send(); + expect(response.status).toBe(decision === 'revoked' ? 403 : 503); + expect(sideEffect).not.toHaveBeenCalled(); + if (decision === 'unavailable') expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(isAuthenticatedUserAAOAdminMock).toHaveBeenCalledTimes(2); + // A refusal before the crawler runs must release its per-domain reservation. + const retry = await request(app).post('/api/registry/publisher/security.example/adagents/revalidate').send(); + expect(retry.status).toBe(200); + expect(sideEffect).toHaveBeenCalledTimes(1); + }); + + it.each([ + { authenticated: 'admin_user', canonical: 'member_user', allowed: true, mutate: false }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false, mutate: false }, + { authenticated: 'admin_user', canonical: 'member_user', allowed: true, mutate: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false, mutate: true }, + { authenticated: 'member_user', canonical: 'admin_user', allowed: false, mutate: false, unavailable: true }, + ])('keeps crawl status authority on $authenticated before asynchronous row loading (mutate=$mutate)', async ({ authenticated, canonical, allowed, mutate, unavailable }) => { + if (unavailable) isAuthenticatedUserAAOAdminMock.mockRejectedValueOnce(new AAOAdminLookupUnavailableError()); + const user = { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com', isAdmin: !allowed }; + const id = '11111111-1111-4111-8111-111111111111'; + const getPublisherCrawlRequest = vi.fn(async () => { + await Promise.resolve(); + if (mutate) { + user.id = authenticated; + user.authWorkosUserId = canonical; + user.email = 'changed@example.com'; + } + return { + id, publisher_domain: 'private-request.example', requester_type: 'user', + requested_by_user_id: 'unrelated_requester', status: 'succeeded', attempts: 1, max_attempts: 2, + created_at: new Date(), completed_at: new Date(), available_at: new Date(), + }; + }); + const response = await request(buildApp({ + user, crawler: { revalidatePublisherAdagents: vi.fn(), getPublisherCrawlRequest }, + })).get(`/api/registry/crawl-request/${id}`).send(); + expect(response.status).toBe(unavailable ? 503 : allowed ? 200 : 404); + if (unavailable) { + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(response.headers['cache-control']).toBe('no-store'); + } + if (allowed) expect(response.body.domain).toBe('private-request.example'); + const principal = isAuthenticatedUserAAOAdminMock.mock.calls[0][0]; + expect(principal.id).toBe(authenticated); + expect(principal.email).toBe('credential@example.com'); + expect(Object.isFrozen(principal)).toBe(true); + }); + + it.each([ + { authenticated: 'request_owner', canonical: 'member_user', allowed: true }, + { authenticated: 'member_user', canonical: 'request_owner', allowed: false }, + ])('uses exact $authenticated ownership for crawl status instead of canonical $canonical', async ({ authenticated, canonical, allowed }) => { + if (allowed) isAuthenticatedUserAAOAdminMock.mockRejectedValue(new AAOAdminLookupUnavailableError()); + const id = '22222222-2222-4222-8222-222222222222'; + const getPublisherCrawlRequest = vi.fn().mockResolvedValue({ + id, publisher_domain: 'owned-request.example', requester_type: 'user', + requested_by_user_id: 'request_owner', status: 'succeeded', attempts: 1, max_attempts: 2, + created_at: new Date(), completed_at: new Date(), available_at: new Date(), + }); + const response = await request(buildApp({ + user: { id: canonical, authWorkosUserId: authenticated, email: 'credential@example.com' }, + crawler: { revalidatePublisherAdagents: vi.fn(), getPublisherCrawlRequest }, + })).get(`/api/registry/crawl-request/${id}`).send(); + expect(response.status).toBe(allowed ? 200 : 404); + if (allowed) expect(isAuthenticatedUserAAOAdminMock).not.toHaveBeenCalled(); + }); + + it.each([ + '/api/registry/authorizations?agent_url=https%3A%2F%2Fagent.example&include=raw', + '/api/registry/authorizations/snapshot?include=raw', + ])('keeps raw authorization audit access static-key-only at %s', async (path) => { + const { AuthorizationSnapshotDatabase } = await import('../../src/db/authorization-snapshot-db.js'); + const narrow = vi.spyOn(AuthorizationSnapshotDatabase.prototype, 'getNarrow'); + const snapshot = vi.spyOn(AuthorizationSnapshotDatabase.prototype, 'openSnapshot'); + try { + isAuthenticatedUserAAOAdminMock.mockResolvedValue(true); + const response = await request(buildApp({ + user: { id: 'member_user', authWorkosUserId: 'admin_user', email: 'admin@example.com', isAdmin: true }, + crawler: { revalidatePublisherAdagents: vi.fn() }, + })).get(path).send(); + expect(response.status).toBe(403); + expect(response.body.error).toBe('include=raw requires admin access'); + expect(narrow).not.toHaveBeenCalled(); + expect(snapshot).not.toHaveBeenCalled(); + } finally { + narrow.mockRestore(); + snapshot.mockRestore(); + } + }); + }); diff --git a/server/tests/unit/working-group-descendant-visibility.test.ts b/server/tests/unit/working-group-descendant-visibility.test.ts new file mode 100644 index 00000000000..5f6ab01c94b --- /dev/null +++ b/server/tests/unit/working-group-descendant-visibility.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ query: vi.fn() })); +vi.mock('../../src/db/client.js', () => ({ + query: mocks.query, + getPool: () => ({ query: mocks.query }), +})); + +import { WorkingGroupDatabase } from '../../src/db/working-group-db.js'; + +describe('reserved administrator group descendant visibility', () => { + const parent = { id: 'parent', slug: 'ordinary-parent', parent_id: null, is_private: false }; + const reserved = { id: 'reserved', slug: 'aao-admin', parent_id: parent.id, is_private: true }; + const publicChild = { id: 'public-child', slug: 'public-child', parent_id: parent.id, is_private: false }; + const privateChild = { id: 'private-child', slug: 'private-child', parent_id: parent.id, is_private: true }; + let db: WorkingGroupDatabase; + + beforeEach(() => { + vi.clearAllMocks(); + db = new WorkingGroupDatabase(); + mocks.query.mockResolvedValue({ rows: [parent, reserved, publicChild, privateChild] }); + }); + + it.each([true, false])('requires explicit reserved authority even when canonical membership exists and is_private=%s', async (isPrivate) => { + mocks.query.mockResolvedValue({ rows: [parent, { ...reserved, is_private: isPrivate }, publicChild, privateChild] }); + const member = vi.spyOn(db, 'isMember').mockResolvedValue(true); + + const visible = await db.getVisibleDescendantIds(parent.id, 'canonical-admin', { + canViewReservedAdminGroup: false, + }); + + expect(visible).toEqual([parent.id, publicChild.id, privateChild.id]); + expect(member).not.toHaveBeenCalledWith(reserved.id, expect.anything()); + expect(member).toHaveBeenCalledWith(privateChild.id, 'canonical-admin'); + }); + + it('does not infer reserved authority from an ordinary admin-view flag', async () => { + const member = vi.spyOn(db, 'isMember').mockResolvedValue(true); + expect(await db.getVisibleDescendantIds(parent.id, 'canonical-admin', { isAdmin: true })) + .toEqual([parent.id, publicChild.id, privateChild.id]); + expect(member).not.toHaveBeenCalled(); + }); + + it('keeps anonymous parent feeds public without exposing the reserved child', async () => { + const member = vi.spyOn(db, 'isMember'); + expect(await db.getVisibleDescendantIds(parent.id, null)).toEqual([parent.id, publicChild.id]); + expect(member).not.toHaveBeenCalled(); + }); + + it('permits the reserved child without widening ordinary private event visibility', async () => { + const member = vi.spyOn(db, 'isMember').mockResolvedValue(false); + expect(await db.getVisibleDescendantIds(parent.id, 'canonical-nonadmin', { + canViewReservedAdminGroup: true, + })).toEqual([parent.id, reserved.id, publicChild.id]); + expect(member).not.toHaveBeenCalledWith(reserved.id, expect.anything()); + expect(member).toHaveBeenCalledWith(privateChild.id, 'canonical-nonadmin'); + }); + + it('preserves the explicit ordinary private-group bypass used by admin post views', async () => { + const member = vi.spyOn(db, 'isMember'); + expect(await db.getVisibleDescendantIds(parent.id, 'canonical-nonadmin', { + isAdmin: true, canViewReservedAdminGroup: true, + })).toEqual([parent.id, reserved.id, publicChild.id, privateChild.id]); + expect(member).not.toHaveBeenCalled(); + }); + + it.each([false, true])('requires reserved authority even when the requested target is the reserved group: %s', async (allowed) => { + mocks.query.mockResolvedValue({ rows: [reserved] }); + const member = vi.spyOn(db, 'isMember').mockResolvedValue(true); + expect(await db.getVisibleDescendantIds(reserved.id, 'canonical-admin', { + canViewReservedAdminGroup: allowed, + })).toEqual(allowed ? [reserved.id] : []); + expect(member).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/working-group-document-privacy.test.ts b/server/tests/unit/working-group-document-privacy.test.ts index 96a7dfd35cf..04327f51068 100644 --- a/server/tests/unit/working-group-document-privacy.test.ts +++ b/server/tests/unit/working-group-document-privacy.test.ts @@ -38,6 +38,16 @@ const db = vi.hoisted(() => ({ getDocumentAssetData: vi.fn(), getDocumentById: vi.fn(), getDocumentAssets: vi.fn(), + getMembershipsByWorkingGroup: vi.fn(), + isFamilyMember: vi.fn(), + listSubgroups: vi.fn(), + countFamilyMembers: vi.fn(), + getVisibleDescendantIds: vi.fn(), + query: vi.fn(), + getEventsByCommittee: vi.fn(), + adminPrincipals: vi.fn(), + requestUser: null as Express.Request['user'] | null, + authorityUnavailable: false, })); vi.mock('../../src/db/working-group-db.js', () => ({ @@ -54,8 +64,10 @@ vi.mock('../../src/middleware/auth.js', () => { if (identity) { req.user = { id: identity, - email: `${identity}@example.com`, + authWorkosUserId: req.header('x-test-authenticated-user'), + email: req.header('x-test-email') ?? `${identity}@example.com`, } as Express.Request['user']; + db.requestUser = req.user; } next(); }; @@ -75,6 +87,35 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ isWebUserAAOAdmin: vi.fn(async (userId: string) => userId === 'admin'), })); +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn(async (userId: string) => { + if (db.authorityUnavailable) throw new actual.AAOAdminLookupUnavailableError(); + return userId === 'admin'; + }); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => { + db.adminPrincipals(principal); + return (await resolve(principal)).isAdmin; + }, + }; +}); + +vi.mock('../../src/db/client.js', async (importOriginal) => ({ + ...await importOriginal(), + getPool: () => ({ query: db.query }), +})); +vi.mock('../../src/db/events-db.js', () => ({ + eventsDb: { getEventsByCommittee: db.getEventsByCommittee }, +})); + vi.mock('../../src/addie/index.js', () => ({ invalidateMemberContextCache: vi.fn() })); vi.mock('../../src/addie/jobs/committee-document-indexer.js', () => ({ reindexDocument: vi.fn() })); vi.mock('../../src/addie/mcp/docs-indexer.js', () => ({ refreshWorkingGroupDocs: vi.fn() })); @@ -105,6 +146,8 @@ function createApp() { describe('private working-group document reads', () => { beforeEach(() => { vi.clearAllMocks(); + db.requestUser = null; + db.authorityUnavailable = false; delete process.env.ADMIN_EMAILS; db.getWorkingGroupBySlug.mockImplementation(async (slug: string) => ( @@ -275,4 +318,269 @@ describe('private working-group document reads', () => { .expect(200) .expect('cache-control', 'public, max-age=86400'); }); + + it.each(['/api/working-groups/private-group', '/api/working-groups/private-group/posts'])( + 'preserves ordinary private-group membership behavior at %s', async (path) => { + db.getMembershipsByWorkingGroup.mockResolvedValue([]); + db.isFamilyMember.mockResolvedValue(false); + db.listSubgroups.mockResolvedValue([]); + db.countFamilyMembers.mockResolvedValue(0); + db.getVisibleDescendantIds.mockResolvedValue([privateGroup.id]); + db.query.mockResolvedValue({ rows: [] }); + await request(createApp()).get(path) + .set('x-test-user', 'member') + .set('x-test-authenticated-user', 'outsider') + .expect(200); + await request(createApp()).get(path) + .set('x-test-user', 'outsider') + .set('x-test-authenticated-user', 'admin') + .expect(404); + }, + ); + + describe('reserved platform-authority group reads', () => { + const reservedGroup = { ...privateGroup, slug: 'aao-admin' }; + const paths = [ + '/api/working-groups/aao-admin', + '/api/working-groups/aao-admin/posts', + '/api/working-groups/aao-admin/events', + '/api/working-groups/aao-admin/documents', + '/api/working-groups/aao-admin/activity', + '/api/working-groups/aao-admin/summary', + `/api/working-groups/aao-admin/documents/${ids.document}/file`, + `/api/working-groups/aao-admin/documents/${ids.document}/assets`, + `/api/working-groups/assets/${ids.asset}`, + ]; + + beforeEach(() => { + db.getWorkingGroupBySlug.mockResolvedValue(reservedGroup); + db.getWorkingGroupById.mockResolvedValue(reservedGroup); + db.isMember.mockImplementation(async (_groupId: string, userId: string) => userId === 'admin'); + db.isLeader.mockImplementation(async (_groupId: string, userId: string) => userId === 'admin'); + db.getMembershipsByWorkingGroup.mockResolvedValue([{ workos_user_id: 'admin' }]); + db.isFamilyMember.mockResolvedValue(false); + db.listSubgroups.mockResolvedValue([]); + db.countFamilyMembers.mockResolvedValue(1); + db.getVisibleDescendantIds.mockResolvedValue([reservedGroup.id]); + db.query.mockResolvedValue({ rows: [{ id: 'private-post', content: 'Private post' }] }); + db.getEventsByCommittee.mockResolvedValue([{ id: 'private-event' }]); + }); + + function expectNoPrivateReads() { + expect(db.getMembershipsByWorkingGroup).not.toHaveBeenCalled(); + expect(db.getDocumentsByWorkingGroup).not.toHaveBeenCalled(); + expect(db.getRecentActivity).not.toHaveBeenCalled(); + expect(db.getCurrentSummary).not.toHaveBeenCalled(); + expect(db.getDocumentFileData).not.toHaveBeenCalled(); + expect(db.getDocumentAssets).not.toHaveBeenCalled(); + expect(db.getDocumentAssetData).not.toHaveBeenCalled(); + expect(db.getEventsByCommittee).not.toHaveBeenCalled(); + expect(db.query).not.toHaveBeenCalled(); + expect(db.isMember).not.toHaveBeenCalled(); + expect(db.isLeader).not.toHaveBeenCalled(); + } + + it('never publicly caches reserved asset bytes even if the privacy flag is misconfigured', async () => { + db.getWorkingGroupById.mockResolvedValue({ ...reservedGroup, is_private: false }); + const path = `/api/working-groups/assets/${ids.asset}`; + await request(createApp()).get(path).expect(404); + expectNoPrivateReads(); + await request(createApp()).get(path) + .set('x-test-user', 'member') + .set('x-test-authenticated-user', 'admin') + .expect(200) + .expect('cache-control', 'private, no-cache'); + }); + + it.each(paths)('retains authenticated admin access linked to a non-admin canonical profile at %s', async (path) => { + await request(createApp()).get(path) + .set('x-test-user', 'member') + .set('x-test-authenticated-user', 'admin') + .expect(200); + for (const call of [...db.isMember.mock.calls, ...db.isLeader.mock.calls]) { + expect(call[1]).toBe('admin'); + } + }); + + it.each(paths)('blocks a non-admin linked to an admin canonical profile before private reads at %s', async (path) => { + await request(createApp()).get(path) + .set('x-test-user', 'admin') + .set('x-test-authenticated-user', 'member') + .expect(404); + expectNoPrivateReads(); + }); + + it.each(paths)('distinguishes unavailable authority from forbidden at %s', async (path) => { + db.authorityUnavailable = true; + const response = await request(createApp()).get(path) + .set('x-test-user', 'admin') + .set('x-test-authenticated-user', 'member') + .expect(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expectNoPrivateReads(); + }); + + it.each(paths)('honors the authenticated credential break-glass email at %s', async (path) => { + process.env.ADMIN_EMAILS = 'break-glass@example.test'; + await request(createApp()).get(path) + .set('x-test-user', 'admin') + .set('x-test-authenticated-user', 'member') + .set('x-test-email', 'break-glass@example.test') + .expect(200); + }); + + it.each(paths)('keeps reserved-group reads unavailable to anonymous callers at %s', async (path) => { + await request(createApp()).get(path).expect(404); + expectNoPrivateReads(); + }); + }); + + describe('reserved administrator subgroup behind an ordinary public parent', () => { + const reserved = { ...privateGroup, slug: 'aao-admin', parent_id: publicGroup.id }; + const ordinaryPrivate = { + ...privateGroup, + id: '55555555-5555-4555-8555-555555555555', + slug: 'ordinary-private-child', + parent_id: publicGroup.id, + }; + const paths = [ + '/api/working-groups/public-group', + '/api/working-groups/public-group/posts', + '/api/working-groups/public-group/events', + ]; + + beforeEach(() => { + db.getWorkingGroupBySlug.mockResolvedValue(publicGroup); + db.getWorkingGroupById.mockResolvedValue(publicGroup); + db.isMember.mockImplementation(async (groupId: string, userId: string) => ( + groupId === reserved.id && userId === 'admin' + )); + db.isFamilyMember.mockResolvedValue(false); + db.getMembershipsByWorkingGroup.mockImplementation(async (groupId: string) => ( + groupId === reserved.id ? [{ workos_user_id: 'admin' }] : [] + )); + db.listSubgroups.mockResolvedValue([reserved, ordinaryPrivate]); + db.countFamilyMembers.mockResolvedValue(1); + // This mock checks route-to-helper permission plumbing. The real helper's + // reserved and ordinary privacy policies are tested independently. + db.getVisibleDescendantIds.mockImplementation(async ( + groupId: string, _userId: string | null, + options: { isAdmin?: boolean; canViewReservedAdminGroup?: boolean } = {}, + ) => [ + groupId, + ...(options.canViewReservedAdminGroup ? [reserved.id] : []), + ...(options.isAdmin ? [ordinaryPrivate.id] : []), + ]); + db.query.mockImplementation(async (_sql: string, params: [string[]]) => ({ + rows: params[0].includes(reserved.id) + ? [{ id: 'reserved-post', content: 'Reserved admin content' }] + : [], + })); + db.getEventsByCommittee.mockImplementation(async (groupIds: string[]) => [ + ...(groupIds.includes(reserved.id) ? [{ id: 'reserved-event' }] : []), + ...(groupIds.includes(ordinaryPrivate.id) ? [{ id: 'ordinary-private-event' }] : []), + ]); + }); + + function includesReserved(response: request.Response, path: string): boolean { + if (path.endsWith('/posts')) return response.body.posts.some((post: { id: string }) => post.id === 'reserved-post'); + if (path.endsWith('/events')) return response.body.some((event: { id: string }) => event.id === 'reserved-event'); + return response.body.working_group.subgroups.some((group: { slug: string }) => group.slug === 'aao-admin'); + } + + it.each(['false', 'true', 'admin'])('does not let include_subgroups=%s skip exact event authorization', async (includeSubgroups) => { + db.authorityUnavailable = true; + const response = await request(createApp()).get(paths[2]) + .query({ include_subgroups: includeSubgroups, isAdmin: true, authWorkosUserId: 'admin' }) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member').expect(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(db.adminPrincipals).toHaveBeenCalledWith(expect.objectContaining({ authWorkosUserId: 'member' })); + expect(db.getVisibleDescendantIds).not.toHaveBeenCalled(); + expect(db.getEventsByCommittee).not.toHaveBeenCalled(); + }); + + it.each([ + { exact: 'admin', canonical: 'member', grants: true }, + { exact: 'member', canonical: 'admin', grants: false }, + ])('keeps immutable event authority for $exact linked to $canonical across group lookup', async ({ exact, canonical, grants }) => { + db.getWorkingGroupBySlug.mockImplementationOnce(async () => { + db.requestUser!.id = exact; + db.requestUser!.authWorkosUserId = canonical; + return publicGroup; + }); + const response = await request(createApp()).get(paths[2]) + .set('x-test-user', canonical).set('x-test-authenticated-user', exact).expect(200); + expect(includesReserved(response, paths[2])).toBe(grants); + expect(db.adminPrincipals).toHaveBeenCalledWith(expect.objectContaining({ id: canonical, authWorkosUserId: exact })); + expect(Object.isFrozen(db.adminPrincipals.mock.calls[0][0])).toBe(true); + }); + + it.each(['false', 'true'])('rejects forged event authority on the reserved group with include_subgroups=%s', async (includeSubgroups) => { + db.getWorkingGroupBySlug.mockResolvedValue(reserved); + await request(createApp()).get('/api/working-groups/aao-admin/events') + .query({ include_subgroups: includeSubgroups, isAdmin: true, authWorkosUserId: 'admin' }) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member').expect(404); + expect(db.getEventsByCommittee).not.toHaveBeenCalled(); + }); + + it.each(paths)('retains exact admin access through the ordinary parent at %s', async (path) => { + const response = await request(createApp()).get(path) + .set('x-test-user', 'member').set('x-test-authenticated-user', 'admin').expect(200); + expect(includesReserved(response, path)).toBe(true); + }); + + it.each(paths)('does not inherit reserved subgroup access through a canonical admin at %s', async (path) => { + const response = await request(createApp()).get(path) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member').expect(200); + expect(includesReserved(response, path)).toBe(false); + expect(db.getMembershipsByWorkingGroup).not.toHaveBeenCalledWith(reserved.id); + if (path.endsWith('/posts')) expect(db.query.mock.calls[0][1][0]).not.toContain(reserved.id); + if (path.endsWith('/events')) expect(db.getEventsByCommittee.mock.calls[0][0]).not.toContain(reserved.id); + }); + + it.each(paths)('honors break-glass for the reserved subgroup through %s', async (path) => { + process.env.ADMIN_EMAILS = 'break-glass@example.test'; + const response = await request(createApp()).get(path) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member') + .set('x-test-email', 'break-glass@example.test').expect(200); + expect(includesReserved(response, path)).toBe(true); + }); + + it.each(paths)('returns retryable unavailable before reading reserved subgroup data through %s', async (path) => { + db.authorityUnavailable = true; + const response = await request(createApp()).get(path) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member').expect(503); + expect(response.body.error).toBe('admin_authorization_unavailable'); + expect(response.headers['retry-after']).toBe('5'); + expect(db.getMembershipsByWorkingGroup).not.toHaveBeenCalledWith(reserved.id); + expect(db.getVisibleDescendantIds).not.toHaveBeenCalled(); + expect(db.query).not.toHaveBeenCalled(); + expect(db.getEventsByCommittee).not.toHaveBeenCalled(); + }); + + it.each(paths)('keeps the ordinary parent readable anonymously without its reserved subgroup at %s', async (path) => { + const response = await request(createApp()).get(path).expect(200); + expect(includesReserved(response, path)).toBe(false); + expect(db.getMembershipsByWorkingGroup).not.toHaveBeenCalledWith(reserved.id); + }); + + it('does not expose a reserved subgroup marked public in parent details', async () => { + db.listSubgroups.mockResolvedValue([{ ...reserved, is_private: false }]); + const response = await request(createApp()).get(paths[0]) + .set('x-test-user', 'admin').set('x-test-authenticated-user', 'member').expect(200); + expect(includesReserved(response, paths[0])).toBe(false); + expect(db.getMembershipsByWorkingGroup).not.toHaveBeenCalledWith(reserved.id); + }); + + it('preserves ordinary private-child event membership despite exact platform authority', async () => { + const response = await request(createApp()).get(paths[2]) + .set('x-test-user', 'member').set('x-test-authenticated-user', 'admin').expect(200); + expect(response.body).toEqual([{ id: 'reserved-event' }]); + expect(db.getVisibleDescendantIds).toHaveBeenCalledWith(publicGroup.id, 'member', { + canViewReservedAdminGroup: true, + }); + }); + }); + }); diff --git a/server/tests/unit/working-group-leader-admin-bypass.test.ts b/server/tests/unit/working-group-leader-admin-bypass.test.ts index 23fe1849868..6234c42b0a0 100644 --- a/server/tests/unit/working-group-leader-admin-bypass.test.ts +++ b/server/tests/unit/working-group-leader-admin-bypass.test.ts @@ -6,10 +6,9 @@ import type { Request, Response, NextFunction } from 'express'; * and member middleware factories (#7269). * * The bypass must recognize BOTH aao-admin working group membership (the - * deployed primary authority, via isWebUserAAOAdmin) and the ADMIN_EMAILS - * break-glass list — matching requireAdmin. A membership-lookup failure - * degrades to non-admin (isWebUserAAOAdmin fails closed) without disabling a - * valid break-glass grant. + * deployed primary authority) and the ADMIN_EMAILS break-glass list — + * matching requireAdmin. Lookup failures remain unavailable without disabling + * a valid independently configured break-glass grant. */ const mocks = vi.hoisted(() => ({ @@ -32,11 +31,17 @@ vi.mock('@workos-inc/node', () => ({ }, })); -vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ - isWebUserAAOAdmin: mocks.isWebUserAAOAdmin, +vi.mock('../../src/db/working-group-db.js', () => ({ + WorkingGroupDatabase: class { + getWorkingGroupIdBySlug = vi.fn().mockResolvedValue('wg_aao_admin'); + isMember = mocks.isWebUserAAOAdmin; + }, })); +import { invalidateAllAdminStatusCaches } from '../../src/addie/admin-status-cache.js'; + const { + requireAdmin, createRequireWorkingGroupLeader, createRequireWorkingGroupMember, stopAuthTimers, @@ -62,9 +67,16 @@ function createReqRes(email = 'user@example.test') { const req = { user: { id: 'user_web', email }, params: { slug: 'signals' }, + headers: { accept: 'application/json' }, + accepts: () => false, + originalUrl: '/api/admin/test', + path: '/admin/test', + method: 'GET', } as unknown as Request; const res = { + headers: {} as Record, + setHeader(name: string, value: string) { this.headers[name] = value; }, statusCode: 200, body: undefined as unknown, status(code: number) { @@ -83,6 +95,7 @@ function createReqRes(email = 'user@example.test') { beforeEach(() => { vi.clearAllMocks(); + invalidateAllAdminStatusCaches(); delete process.env.ADMIN_EMAILS; mocks.isWebUserAAOAdmin.mockResolvedValue(false); }); @@ -111,7 +124,7 @@ describe.each([ await factory(db)(req, res, next); expect(next).toHaveBeenCalledOnce(); - expect(mocks.isWebUserAAOAdmin).toHaveBeenCalledWith('user_web'); + expect(mocks.isWebUserAAOAdmin).toHaveBeenCalledWith('wg_aao_admin', 'user_web'); // Admin short-circuits before any group lookup. expect(db.getWorkingGroupBySlug).not.toHaveBeenCalled(); }); @@ -147,16 +160,62 @@ describe.each([ expect(next).toHaveBeenCalledOnce(); }); - it('denies when the admin membership lookup fails (fail closed)', async () => { - // isWebUserAAOAdmin fails closed to `false` on lookup error; a non-leader, - // non-break-glass user must then be denied rather than granted. - mocks.isWebUserAAOAdmin.mockResolvedValue(false); + it('never regains reserved platform authority through a canonical group grant', async () => { + const db = createWorkingGroupDb({ isLeader: true, isMember: true, group: { id: 'wg_aao_admin' } }); + const { req, res, next } = createReqRes(); + req.params.slug = 'aao-admin'; + req.user!.id = 'user_canonical_admin'; + req.user!.authWorkosUserId = 'user_authenticated_non_admin'; + + await factory(db)(req, res, next); + + expect(res.statusCode).toBe(403); + expect(next).not.toHaveBeenCalled(); + expect(db.getWorkingGroupBySlug).not.toHaveBeenCalled(); + expect(db.isLeader).not.toHaveBeenCalled(); + expect(db.isMember).not.toHaveBeenCalled(); + }); + + it('returns a retryable 503 when the administrator lookup is unavailable', async () => { + mocks.isWebUserAAOAdmin.mockRejectedValue(new Error('database unavailable')); const db = createWorkingGroupDb({ isLeader: false, isMember: false }); const { req, res, next } = createReqRes(); await factory(db)(req, res, next); expect(next).not.toHaveBeenCalled(); - expect((res as unknown as { statusCode: number }).statusCode).toBe(403); + expect((res as unknown as { statusCode: number }).statusCode).toBe(503); + expect(res.body).toMatchObject({ error: 'admin_authorization_unavailable' }); + }); +}); + + +describe.each([ + { label: 'platform admin', middleware: requireAdmin }, + { label: 'working-group leader', middleware: createRequireWorkingGroupLeader(createWorkingGroupDb()) }, + { label: 'working-group member', middleware: createRequireWorkingGroupMember(createWorkingGroupDb()) }, +])('$label credential boundary', ({ middleware }) => { + it.each([ + { authenticated: 'user_admin', canonical: 'user_member', allowed: true }, + { authenticated: 'user_member', canonical: 'user_admin', allowed: false }, + ])('authorizes $authenticated without inheriting $canonical', async ({ authenticated, canonical, allowed }) => { + mocks.isWebUserAAOAdmin.mockImplementation(async (_group: string, userId: string) => userId === 'user_admin'); + const { req, res, next } = createReqRes(); + req.user!.id = canonical; + req.user!.authWorkosUserId = authenticated; + await middleware(req, res, next); + expect(mocks.isWebUserAAOAdmin).toHaveBeenCalledWith('wg_aao_admin', authenticated); + expect(next).toHaveBeenCalledTimes(allowed ? 1 : 0); + expect(res.statusCode).toBe(allowed ? 200 : 403); + }); + + it('preserves independently configured break-glass authority during an outage', async () => { + process.env.ADMIN_EMAILS = 'ops@example.test'; + mocks.isWebUserAAOAdmin.mockRejectedValue(new Error('database unavailable')); + const { req, res, next } = createReqRes('OPS@example.test'); + req.user!.authWorkosUserId = 'user_authenticated'; + await middleware(req, res, next); + expect(next).toHaveBeenCalledOnce(); + expect(res.statusCode).toBe(200); }); }); diff --git a/server/tests/unit/working-group-perspective-url-validation.test.ts b/server/tests/unit/working-group-perspective-url-validation.test.ts index 5e12e5abd2f..ea949650def 100644 --- a/server/tests/unit/working-group-perspective-url-validation.test.ts +++ b/server/tests/unit/working-group-perspective-url-validation.test.ts @@ -52,6 +52,21 @@ vi.mock('../../src/addie/mcp/admin-tools.js', () => ({ invalidateWebAdminStatusCache: vi.fn(), isWebUserAAOAdmin: vi.fn().mockResolvedValue(false), })); + +vi.mock('../../src/addie/admin-status-lookup.js', async (importOriginal) => { + const actual = await importOriginal(); + const checkMembership = vi.fn().mockResolvedValue(false); + const resolve = async (principal: any, email?: string | null) => { + const id = typeof principal === 'string' ? principal : principal.authWorkosUserId ?? principal.id; + return actual.decideAAOAdminAccess(await checkMembership(id), typeof principal === 'string' ? email : principal.email); + }; + return { + ...actual, + isWebUserAAOAdmin: checkMembership, + resolveWebUserAAOAdminAccess: resolve, + isAuthenticatedUserAAOAdmin: async (principal: any) => (await resolve(principal)).isAdmin, + }; +}); vi.mock('../../src/slack/sync.js', () => ({ syncWorkingGroupMembersFromSlack: vi.fn(), syncAllWorkingGroupMembersFromSlack: vi.fn(), diff --git a/static/openapi/registry.yaml b/static/openapi/registry.yaml index 438b4165abc..a6d349f6f1d 100644 --- a/static/openapi/registry.yaml +++ b/static/openapi/registry.yaml @@ -8568,7 +8568,7 @@ paths: - error - retry_after "503": - description: Publisher crawl is temporarily busy + description: Publisher crawl is temporarily busy, or administrator authorization could not be checked headers: Retry-After: schema: @@ -8579,21 +8579,33 @@ paths: content: application/json: schema: - type: object - properties: - error: - type: string - code: - type: string - enum: - - publisher_crawl_busy - retry_after: - type: integer - description: Seconds to wait before retrying - required: - - error - - code - - retry_after + anyOf: + - type: object + properties: + error: + type: string + enum: + - admin_authorization_unavailable + message: + type: string + required: + - error + - message + - type: object + properties: + error: + type: string + code: + type: string + enum: + - publisher_crawl_busy + retry_after: + type: integer + description: Seconds to wait before retrying + required: + - error + - code + - retry_after /api/registry/brand/{domain}/force-crawl: post: operationId: forceBrandCrawl @@ -8736,6 +8748,27 @@ paths: application/json: schema: $ref: "#/components/schemas/Error" + "503": + description: Administrator authorization could not be checked + headers: + Retry-After: + schema: + type: string + required: true + content: + application/json: + schema: + type: object + properties: + error: + type: string + enum: + - admin_authorization_unavailable + message: + type: string + required: + - error + - message /api/registry/publisher/authorization: get: operationId: lookupPublisherAgentAuthorization @@ -11540,7 +11573,7 @@ paths: schema: $ref: "#/components/schemas/Error" "503": - description: Crawl status is temporarily unavailable + description: Crawl status or administrator authorization is temporarily unavailable headers: Retry-After: schema: @@ -11551,20 +11584,32 @@ paths: content: application/json: schema: - type: object - properties: - error: - type: string - code: - type: string - enum: - - crawl_status_unavailable - retry_after: - type: integer - required: - - error - - code - - retry_after + anyOf: + - type: object + properties: + error: + type: string + enum: + - admin_authorization_unavailable + message: + type: string + required: + - error + - message + - type: object + properties: + error: + type: string + code: + type: string + enum: + - crawl_status_unavailable + retry_after: + type: integer + required: + - error + - code + - retry_after /api/registry/manager-revalidation-request: post: operationId: requestManagerRevalidation @@ -13056,7 +13101,7 @@ paths: **Compliance re-run:** when the caller owns the agent or is an AAO admin and the capability probe succeeds, the full storyboard suite can run for several minutes on capability-rich agents with a fresh test session, and `agent_storyboard_status` is updated. Owner-triggered runs use `triggered_by: 'owner_test'`; admin-triggered support runs use `triggered_by: 'manual'`. Badge fan-out reissues verification badges off the new run. If the compliance call fails (timeout, OAuth wall, internal error), the capability/health portion still returns successfully — `compliance.ran` is `false` with an `error` string. - **Auth:** owner of the agent, AAO admin, or static `ADMIN_API_KEY`. + **Auth:** owner of the agent, AAO admin, or static `ADMIN_API_KEY`. Human submissions are temporarily fenced with HTTP 503 until durable authorization provenance is supported; static admin API key submissions remain available. **Rate limits:** 60 seconds per agent URL, 30 requests per user per hour. tags: @@ -13307,11 +13352,39 @@ paths: schema: $ref: "#/components/schemas/Error" "503": - description: Durable refresh queue unavailable or at capacity + description: Refresh queue or authorization unavailable. All human submissions are temporarily fenced with refresh_authorization_provenance_required; only static admin API key submissions are supported. + headers: + Retry-After: + schema: + type: string + required: true content: application/json: schema: - $ref: "#/components/schemas/Error" + anyOf: + - type: object + properties: + error: + type: string + enum: + - admin_authorization_unavailable + message: + type: string + required: + - error + - message + - type: object + properties: + error: + type: string + code: + type: string + retry_after: + type: integer + required: + - error + - code + - retry_after /api/registry/agents/{encodedUrl}/refreshes/{operationId}: get: operationId: getAgentRefreshOperation @@ -13452,11 +13525,23 @@ paths: required: - error "503": - description: Refresh status temporarily unavailable + description: Refresh status or administrator authorization temporarily unavailable content: application/json: schema: - $ref: "#/components/schemas/Error" + anyOf: + - type: object + properties: + error: + type: string + enum: + - admin_authorization_unavailable + message: + type: string + required: + - error + - message + - $ref: "#/components/schemas/Error" /api/registry/agents/{encodedUrl}/auth-status: get: operationId: getAgentAuthStatus