A request through the backend
Follow an authenticated browser request from the auth middleware, through the access checks, to the data layer — and see why @supabase/supabase-js is still the data client.
backend/src/middleware/auth.ts182 lines · requireAuth L34–181
Outline 2 symbols
- reportAuthFailure function
- requireAuth function export
1import { Request, Response, NextFunction } from "express";
2import { validateSupabaseToken } from "../lib/auth/providers/supabase.js";
3import { validateLocalToken } from "../lib/auth/providers/local.js";
4import { validateEntraToken } from "../lib/auth/providers/entra.js";
5import { authorizationEmail } from "../lib/auth/types.js";
6import { tenantAccess } from "./tenantAccess.js";
7import { upsertUserProfile } from "../lib/userLookup.js";
8import { createServerSupabase } from "../lib/supabase.js";
9import { getConfig } from "../lib/config.js";
10import { readServerSession, refreshServerSession } from "../lib/serverSession.js";
11import { requestOriginIsTrusted } from "../lib/origins.js";
12import { renewEntraCredential } from "../lib/auth/providers/entraRefresh.js";
13import { renewSupabaseCredential } from "../lib/auth/providers/supabaseSession.js";
14import { reportError, requestRoutePattern, setCurrentUser } from "../lib/observability/sentry";
15import { AppError, type ErrorKind } from "../lib/appError";
16
17function reportAuthFailure(req: Request, kind: ErrorKind, cause: unknown): void {
18 reportError(new AppError(kind, "Authentication dependency failed", { cause }), {
19 tags: { component: "http", http_method: req.method, http_route: requestRoutePattern(req) },
20 });
21}
22
23// Upstream divergence (sync-log: 3a10943): upstream added app-level MFA
24// enforcement here (enforceLoginMfaIfEnabled / requireMfaIfEnrolled) built
25// on Supabase Auth's MFA APIs (admin.auth.mfa.getAuthenticatorAssuranceLevel,
26// auth.getUser factor listings). Dev's auth is provider-pluggable
27// (supabase | local | entra) with Entra as the production provider; those
28// Supabase Auth MFA primitives do not exist for Entra, where MFA/step-up is
29// enforced by the identity provider (Conditional Access), not application
30// code. NOT adopted — do not re-introduce Supabase-session MFA checks in
31// this middleware. If app-level step-up is ever needed, it must be designed
32// per-provider behind lib/auth/providers/.
33
34export async function requireAuth(
35 req: Request,
36 res: Response,
37 next: NextFunction,
38): Promise<void> {
39 const auth = req.headers.authorization ?? "";
40 const provider = (await getConfig("auth-provider").catch(() => process.env.AUTH_PROVIDER)) ?? "supabase";
41 let token = "";
42 let cookieSession = false;
43 let sessionUserId: string | null = null;
44
45 // An explicit credential has precedence. Invalid or malformed bearer
46 // headers never fall back to a different identity in a browser cookie.
47 if (auth) {
48 if (!auth.startsWith("Bearer ") || !auth.slice(7).trim()) {
49 res.status(401).json({ detail: "Invalid Authorization header" });
50 return;
51 }
52 token = auth.slice(7).trim();
53 } else {
54 // Cookie-authenticated writes need a browser Origin. Bearer API clients
55 // remain callable without an Origin header.
56 if (!["GET", "HEAD", "OPTIONS"].includes(req.method) && !requestOriginIsTrusted(req.get("origin"))) {
57 res.status(403).json({ code: "untrusted_origin", detail: "The request origin is not allowed." });
58 return;
59 }
60 cookieSession = true;
61 {
62 let session;
63 try { session = await readServerSession(req); }
64 catch (error) { reportAuthFailure(req, "auth.session_lookup_failed", error); res.status(503).json({ detail: "Auth session is unavailable" }); return; }
65 if (session?.credential.provider === provider) {
66 if (Date.parse(session.row.token_expires_at) <= Date.now() + 60_000) {
67 if (!session.credential.refreshToken || provider === "local") {
68 res.status(401).json({ detail: "Invalid or expired session" });
69 return;
70 }
71 try {
72 const renewed = await refreshServerSession(session, provider === "supabase" ? renewSupabaseCredential : renewEntraCredential);
73 const claimedVersion = session.row.version;
74 session = await readServerSession(req);
75 // A second replica can lose the CAS claim while the owner is
76 // refreshing. Do not turn that ordinary race into a 401/logout.
77 if (!renewed && session && Date.parse(session.row.token_expires_at) <= Date.now()) {
78 for (let attempt = 0; attempt < 10 && session && session.row.version <= claimedVersion; attempt++) {
79 await new Promise(resolve => setTimeout(resolve, 200));
80 session = await readServerSession(req);
81 }
82 }
83 if (session && Date.parse(session.row.token_expires_at) <= Date.now()) {
84 res.setHeader("Retry-After", "1");
85 res.status(503).json({ detail: "Auth session refresh is in progress" });
86 return;
87 }
88 } catch (error) {
89 reportAuthFailure(req, "auth.session_lookup_failed", error);
90 res.status(503).json({ detail: "Auth session is unavailable" });
91 return;
92 }
93 }
94 token = session?.credential.accessToken ?? "";
95 sessionUserId = session?.credential.userId ?? null;
96 }
97 }
98 }
99
100 if (!token) {
101 res.status(401).json({ detail: "Invalid or expired session" });
102 return;
103 }
104
105 let result;
106 if (provider === "supabase") {
107 result = await validateSupabaseToken(token);
108 } else if (provider === "local") {
109 result = await validateLocalToken(token);
110 } else if (provider === "entra") {
111 result = await validateEntraToken(token);
112 } else {
113 res.status(500).json({ detail: `Auth provider '${provider}' is not yet implemented` });
114 return;
115 }
116
117 if (!result.ok) {
118 res.status(result.status).json({ detail: result.detail });
119 return;
120 }
121 if (sessionUserId && result.principal.userId !== sessionUserId) {
122 res.status(401).json({ detail: "Invalid or expired session" });
123 return;
124 }
125
126 // A revoked cookie is insufficient for Entra: an already-issued bearer
127 // token remains valid at the IdP. The durable tombstone blocks both token
128 // transports before profile seeding or any application write can run.
129 try {
130 const { data: erasure, error: erasureError } = await createServerSupabase()
131 .from("account_erasure_requests")
132 .select("status")
133 .eq("user_id", result.principal.userId)
134 .maybeSingle();
135 if (erasureError) throw erasureError;
136 if (erasure) {
137 res.status(410).json({ detail: "This account has been closed." });
138 return;
139 }
140 } catch (error) {
141 reportAuthFailure(req, "db.query_failed", error);
142 res.status(503).json({ detail: "Account status is unavailable" });
143 return;
144 }
145
146 res.locals.userId = result.principal.userId;
147 // Grant/invitation matching input: an unconfirmed address matches nothing
148 // (upstream d146998d; see authorizationEmail). The profile mirror below
149 // keeps the IdP email for display.
150 res.locals.userEmail = authorizationEmail(result.principal);
151 res.locals.token = token;
152 res.locals.principal = result.principal;
153 res.locals.authSource = cookieSession ? "cookie" : "bearer";
154 setCurrentUser(result.principal.userId);
155
156 try {
157 await upsertUserProfile(
158 result.principal.userId,
159 result.principal.email,
160 result.principal.displayName,
161 );
162 } catch (error) {
163 reportAuthFailure(req, "db.query_failed", error);
164 res.status(500).json({ detail: "Unable to initialize user profile" });
165 return;
166 }
167
168 // Upstream divergence (sync-log: 3ca82155): Dev owns profile creation
169 // after validated Entra/local identity and session/tombstone checks. A
170 // personal-org failure must not undo profile initialization or sign-in.
171 try {
172 const { error } = await createServerSupabase().rpc("ensure_personal_organization", {
173 p_user_id: result.principal.userId,
174 });
175 if (error) console.warn("[auth/personal-org] initialization failed", { code: error.code });
176 } catch {
177 console.warn("[auth/personal-org] initialization unavailable");
178 }
179
180 await tenantAccess(req, res, next);
181}
182