The Entra ID rewrite
From the provider-abstraction design to the token validator and the install flow that configures it — and where the shipped code deliberately diverges from the plan.
backend/src/lib/auth/providers/entra.ts247 lines · validateEntraToken L96–246
Outline 13 symbols
- JwtHeader interface
- EntraClaims interface
- JwkKey interface
- b64urlToBuffer function
- asString function
- asStringArray function
- nowEpochSeconds function
- JWKS_TTL_MS const
- cache const
- getJwks function
- verifySignature function
- configMissingLogged const
- validateEntraToken function export
1import { createPublicKey, createVerify } from "node:crypto";
2import type { AuthValidationResult } from "../types.js";
3import { getConfig } from "../../config.js";
4
5interface JwtHeader {
6 alg?: unknown;
7 kid?: unknown;
8}
9
10interface EntraClaims {
11 oid?: unknown;
12 // Email-shaped claims. v2.0 tokens use preferred_username; v1.0 tokens
13 // typically use upn or unique_name instead. email is an optional claim
14 // in both versions and only present if added in the app registration.
15 preferred_username?: unknown;
16 email?: unknown;
17 upn?: unknown;
18 unique_name?: unknown;
19 // Display-name claims. `name` is a default claim in both v1.0 and v2.0
20 // tokens for human users. given_name / family_name require the optional
21 // claims block in the app registration so they may be undefined.
22 name?: unknown;
23 given_name?: unknown;
24 family_name?: unknown;
25 tid?: unknown;
26 iss?: unknown;
27 aud?: unknown;
28 exp?: unknown;
29 nbf?: unknown;
30 ver?: unknown;
31 groups?: unknown;
32 _claim_names?: unknown;
33}
34
35interface JwkKey {
36 kid?: string;
37 kty?: string;
38 use?: string;
39 n?: string;
40 e?: string;
41}
42
43function b64urlToBuffer(input: string): Buffer {
44 const padded = input + "=".repeat((4 - (input.length % 4)) % 4);
45 return Buffer.from(padded.replace(/-/g, "+").replace(/_/g, "/"), "base64");
46}
47
48function asString(v: unknown): string | undefined {
49 return typeof v === "string" ? v : undefined;
50}
51
52function asStringArray(v: unknown): string[] {
53 return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
54}
55
56function nowEpochSeconds() {
57 return Math.floor(Date.now() / 1000);
58}
59
60const JWKS_TTL_MS = 5 * 60 * 1000;
61let cache: { tenantId: string; fetchedAt: number; keys: JwkKey[] } | undefined;
62
63async function getJwks(tenantId: string): Promise<JwkKey[]> {
64 const now = Date.now();
65 if (cache && cache.tenantId === tenantId && now - cache.fetchedAt < JWKS_TTL_MS) {
66 return cache.keys;
67 }
68
69 const response = await fetch(`https://login.microsoftonline.com/${tenantId}/discovery/v2.0/keys`);
70 if (!response.ok) {
71 throw new Error("Failed to fetch JWKS");
72 }
73
74 const body = (await response.json()) as { keys?: unknown };
75 const keys = Array.isArray(body.keys) ? (body.keys as JwkKey[]) : [];
76 cache = { tenantId, fetchedAt: now, keys };
77 return keys;
78}
79
80function verifySignature(token: string, key: JsonWebKey): boolean {
81 const [headerB64, payloadB64, sigB64] = token.split(".");
82 const verifier = createVerify("RSA-SHA256");
83 verifier.update(`${headerB64}.${payloadB64}`);
84 verifier.end();
85
86 const publicKey = createPublicKey({ key, format: "jwk" });
87 return verifier.verify(publicKey, b64urlToBuffer(sigB64));
88}
89
90// One-shot diagnostic flag so the "Server auth is not configured" path
91// emits a clear log line exactly once per process lifetime. Without this
92// the operator sees opaque 401s with no signal pointing at the missing
93// KV / env state — see 040 Entry 11.
94let configMissingLogged = false;
95
96export async function validateEntraToken(token: string): Promise<AuthValidationResult> {
97 // getConfig() checks process.env first (uppercased, hyphens → underscores)
98 // and falls back to KV via the install backend's UAMI. Marketplace installs
99 // populate KV via create-entra-apps.ps1 or 039's deploy-time provisioning;
100 // OSS / dev deploys still work via ENTRA_TENANT_ID / ENTRA_BACKEND_CLIENT_ID
101 // env vars. Single call site, both sources, no further plumbing required.
102 // Closes 040 Entry 11.
103 const tenantId = await getConfig("entra-tenant-id").catch(() => "");
104 const backendClientId = await getConfig("entra-backend-client-id").catch(() => "");
105
106 if (!tenantId || !backendClientId) {
107 if (!configMissingLogged) {
108 console.error(
109 "auth.entra.config_missing",
110 "Token validation cannot proceed — neither KV (entra-tenant-id / entra-backend-client-id) nor env (ENTRA_TENANT_ID / ENTRA_BACKEND_CLIENT_ID) provided values. Run create-entra-apps.ps1 from /install OR set the env vars on the Container App. This warning is logged once per process.",
111 );
112 configMissingLogged = true;
113 }
114 return { ok: false, status: 401, detail: "Server auth is not configured" };
115 }
116
117 const parts = token.split(".");
118 if (parts.length !== 3) {
119 return { ok: false, status: 401, detail: "Malformed JWT" };
120 }
121
122 let header: JwtHeader;
123 let claims: EntraClaims;
124 try {
125 header = JSON.parse(b64urlToBuffer(parts[0]).toString("utf8"));
126 claims = JSON.parse(b64urlToBuffer(parts[1]).toString("utf8"));
127 } catch {
128 return { ok: false, status: 401, detail: "Malformed JWT" };
129 }
130
131 if (header.alg !== "RS256") {
132 return { ok: false, status: 401, detail: "Invalid token algorithm" };
133 }
134
135 const kid = asString(header.kid);
136 if (!kid) {
137 return { ok: false, status: 401, detail: "Missing token key id" };
138 }
139
140 try {
141 const keys = await getJwks(tenantId);
142 const jwk = keys.find((key) => key.kid === kid && key.kty === "RSA") as JsonWebKey | undefined;
143 if (!jwk || !jwk.n || !jwk.e) {
144 return { ok: false, status: 401, detail: "Invalid or expired token" };
145 }
146
147 if (!verifySignature(token, jwk)) {
148 return { ok: false, status: 401, detail: "Invalid or expired token" };
149 }
150 } catch {
151 return { ok: false, status: 401, detail: "Invalid or expired token" };
152 }
153
154 // Issuer check accepts both token versions. Entra issues v1.0 tokens by
155 // default unless the API app registration sets accessTokenAcceptedVersion: 2
156 // in its manifest — forcing every customer to flip that switch is
157 // unreasonable, so we accept either.
158 // v1.0: https://sts.windows.net/<tid>/
159 // v2.0: https://login.microsoftonline.com/<tid>/v2.0
160 const v1Iss = `https://sts.windows.net/${tenantId}/`;
161 const v2Iss = `https://login.microsoftonline.com/${tenantId}/v2.0`;
162 if (claims.iss !== v1Iss && claims.iss !== v2Iss) {
163 return { ok: false, status: 401, detail: "Invalid issuer" };
164 }
165
166 // Audience check accepts both shapes. v2.0 tokens use the bare client ID
167 // GUID; v1.0 tokens use `api://<guid>` (the application ID URI). Both
168 // identify the same application — the customer's manifest decides which
169 // form lands in the token.
170 const validAudiences = new Set<string>([
171 backendClientId,
172 `api://${backendClientId}`,
173 ]);
174 if (typeof claims.aud !== "string" || !validAudiences.has(claims.aud)) {
175 return { ok: false, status: 401, detail: "Invalid audience" };
176 }
177
178 if (claims.tid !== tenantId) {
179 return { ok: false, status: 401, detail: "Invalid tenant" };
180 }
181
182 const exp = typeof claims.exp === "number" ? claims.exp : undefined;
183 if (!exp) {
184 return { ok: false, status: 401, detail: "Token missing exp claim" };
185 }
186 if (exp <= nowEpochSeconds()) {
187 return { ok: false, status: 401, detail: "Token expired" };
188 }
189
190 const nbf = typeof claims.nbf === "number" ? claims.nbf : undefined;
191 if (nbf && nbf > nowEpochSeconds()) {
192 return { ok: false, status: 401, detail: "Token is not yet valid" };
193 }
194
195 const userId = asString(claims.oid);
196 if (!userId) {
197 return { ok: false, status: 401, detail: "Token missing oid claim" };
198 }
199
200 const overage = typeof claims._claim_names === "object" && claims._claim_names !== null && "groups" in claims._claim_names;
201 if (overage) {
202 console.warn("auth.entra.groups_overage", { provider: "entra", userId });
203 }
204
205 // Email-claim fallback chain covers both v2.0 (preferred_username) and
206 // v1.0 (upn / unique_name) tokens. email is optional in both and only
207 // present if added to the app registration's optional claims.
208 const email =
209 asString(claims.preferred_username) ??
210 asString(claims.email) ??
211 asString(claims.upn) ??
212 asString(claims.unique_name) ??
213 "";
214 if (!email) {
215 console.warn("auth.entra.email_missing", { provider: "entra", userId });
216 }
217
218 // Resolve a display name from the token. `name` is the canonical default
219 // claim; if the directory entry has been kept clean it's just "First Last".
220 // We fall back to assembling given+family ourselves (only present when the
221 // app registration adds them as optional claims), then to the UPN-shaped
222 // preferred_username as a last resort so the row never gets a blank
223 // display name on first login when at least one identifying field exists.
224 const nameClaim = asString(claims.name)?.trim();
225 const givenName = asString(claims.given_name)?.trim();
226 const familyName = asString(claims.family_name)?.trim();
227 const assembledName = [givenName, familyName].filter(Boolean).join(" ");
228 const displayName =
229 nameClaim ||
230 (assembledName.length > 0 ? assembledName : undefined) ||
231 asString(claims.preferred_username)?.trim() ||
232 undefined;
233
234 return {
235 ok: true,
236 principal: {
237 userId,
238 email: email.toLowerCase(),
239 displayName,
240 tenantId,
241 groups: overage ? [] : asStringArray(claims.groups),
242 roles: [],
243 provider: "entra",
244 },
245 };
246}
247