Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions server/src/db/working-group-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string[]> {
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);
Expand Down
42 changes: 28 additions & 14 deletions server/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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' });
}
Expand All @@ -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' });
}
Expand Down Expand Up @@ -3811,14 +3812,15 @@ 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' });
}

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' });
}
Expand Down Expand Up @@ -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' });
Expand Down Expand Up @@ -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' });
Expand Down Expand Up @@ -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' });
}
Expand All @@ -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' });
}
Expand All @@ -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' });
}
Expand All @@ -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' });
}
Expand Down Expand Up @@ -4285,14 +4290,15 @@ 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' });
}

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' });
}
Expand Down Expand Up @@ -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' });
}
Expand All @@ -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' });
Expand Down Expand Up @@ -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' });
}
Expand Down Expand Up @@ -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' });
}
Expand All @@ -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' });
}
Expand All @@ -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' });
}
Expand All @@ -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' });
}
Expand All @@ -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' });
}
Expand Down Expand Up @@ -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;

Expand All @@ -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' });
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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');
}
Expand Down Expand Up @@ -8637,7 +8649,7 @@ ${p.category ? `<category>${p.category}</category>\n` : ''}<url>${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;
Expand Down Expand Up @@ -8694,6 +8706,7 @@ ${p.category ? `<category>${p.category}</category>\n` : ''}<url>${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',
Expand Down Expand Up @@ -10381,6 +10394,7 @@ ${p.category ? `<category>${p.category}</category>\n` : ''}<url>${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
Expand Down
57 changes: 41 additions & 16 deletions server/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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({
Expand Down
Loading
Loading