flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/sudo/app/lib/access.ts

270 lines10,511 bytesCodeBlame
1/**
2 * Who is asking: sudo sits behind Cloudflare Access, and checks Access's
3 * work itself on every request. Access signs a JWT for each request it
4 * lets through and sends it in `Cf-Access-Jwt-Assertion`; this verifies
5 * its RS256 signature against the team's published keys, its audience,
6 * issuer and lifetime, and then that its email belongs to g1t staff.
7 *
8 * Plain Web Crypto, no dependencies and no Workers imports, so the tests
9 * run it under Node as it runs on Workers.
10 */
11
12/** Where sudo is served; the only origin a change may be posted from. */
13export const ORIGIN = "https://sudo.g1t.sh";
14
15/** How far clocks may disagree, in seconds. */
16const LEEWAY_SECONDS = 30;
17/** How long the team's keys are trusted before they are fetched again. */
18const JWKS_TTL_MS = 5 * 60_000;
19/** A token signed by a key not seen yet refetches the keys, at most this often. */
20const JWKS_REFETCH_MS = 30_000;
21/** Access tokens are a few kilobytes; anything far larger is not one. */
22const MAX_TOKEN_LENGTH = 16_384;
23
24export type AccessSettings = {
25 /** The Zero Trust team domain, such as `g1t.cloudflareaccess.com`. */
26 teamDomain: string;
27 /** The Access application's Audience (AUD) tag. */
28 aud: string;
29 /** Lowercased staff emails, and `@domain` for everyone at a domain. */
30 staff: string[];
31};
32
33export type AccessEnv = {
34 ACCESS_TEAM_DOMAIN?: string;
35 ACCESS_AUD?: string;
36 STAFF_EMAILS?: string;
37};
38
39/**
40 * Reads the settings, or null when any is missing or malformed: sudo then
41 * refuses everything rather than guess.
42 */
43export function readSettings(env: AccessEnv): AccessSettings | null {
44 const teamDomain = normalizeTeamDomain(env.ACCESS_TEAM_DOMAIN ?? "");
45 const aud = (env.ACCESS_AUD ?? "").trim();
46 const staff = parseStaff(env.STAFF_EMAILS ?? "");
47 if (!teamDomain || !/^[A-Za-z0-9]{16,128}$/.test(aud) || staff.length === 0) return null;
48 return { teamDomain, aud, staff };
49}
50
51/**
52 * `g1t.cloudflareaccess.com`, given with or without its scheme. Only a
53 * Cloudflare Access team domain is accepted, since that is where the
54 * signing keys are fetched from.
55 */
56export function normalizeTeamDomain(raw: string): string | null {
57 const host = raw
58 .trim()
59 .toLowerCase()
60 .replace(/^https:\/\//, "")
61 .replace(/\/+$/, "");
62 return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.cloudflareaccess\.com$/.test(host) ? host : null;
63}
64
65/**
66 * The staff list: emails, and `@g1t.sh` for everyone with an address at
67 * that domain. Access proves the address belongs to whoever signed in.
68 */
69export function parseStaff(raw: string): string[] {
70 return raw
71 .split(/[,\s]+/)
72 .map((email) => email.trim().toLowerCase())
73 .filter((email) => /^[^@\s]*@[a-z0-9.-]+\.[a-z]{2,}$/.test(email));
74}
75
76/** Whether a signed-in email is on the staff list: exactly, or by its whole domain. */
77export function isStaff(email: string, staff: string[]): boolean {
78 const at = email.lastIndexOf("@");
79 if (at <= 0 || email.indexOf("@") !== at) return false;
80 const domain = email.slice(at);
81 return staff.some((entry) => (entry.startsWith("@") ? entry === domain : entry === email));
82}
83
84export type AccessClaims = {
85 iss: string;
86 aud: string | string[];
87 exp: number;
88 nbf?: number;
89 iat?: number;
90 sub?: string;
91 email?: string;
92 [claim: string]: unknown;
93};
94
95export type Verified = { ok: true; claims: AccessClaims } | { ok: false; reason: string };
96
97export type VerifyOptions = {
98 /** Fetches the team's keys; the global `fetch` unless a test gives another. */
99 fetcher?: (url: string) => Promise<Response>;
100 /** Milliseconds since the epoch. */
101 now?: number;
102};
103
104type KeySet = { keys: Map<string, CryptoKey>; fetchedAt: number };
105
106/** The team's signing keys, by team domain, kept briefly in memory. */
107const keySets = new Map<string, KeySet>();
108
109/** Forgets the cached keys. For tests. */
110export function clearKeyCache(): void {
111 keySets.clear();
112}
113
114const RSA = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
115
116async function fetchKeySet(
117 teamDomain: string,
118 fetcher: (url: string) => Promise<Response>,
119 now: number,
120): Promise<KeySet> {
121 const response = await fetcher(`https://${teamDomain}/cdn-cgi/access/certs`);
122 if (!response.ok) throw new Error(`Access keys answered ${response.status}`);
123 const body = (await response.json()) as { keys?: unknown };
124 const keys = new Map<string, CryptoKey>();
125 for (const jwk of Array.isArray(body.keys) ? body.keys : []) {
126 if (!jwk || typeof jwk !== "object") continue;
127 const { kid, kty, n, e, alg, use } = jwk as Record<string, unknown>;
128 if (typeof kid !== "string" || kty !== "RSA" || typeof n !== "string" || typeof e !== "string") continue;
129 if (alg !== undefined && alg !== "RS256") continue;
130 if (use !== undefined && use !== "sig") continue;
131 try {
132 keys.set(kid, await crypto.subtle.importKey("jwk", { kty, n, e }, RSA, false, ["verify"]));
133 } catch {
134 // A key that does not import is skipped; tokens signed by it fail.
135 }
136 }
137 return { keys, fetchedAt: now };
138}
139
140/** The key a token names, fetching the team's keys when they are stale or it is new. */
141async function keyFor(
142 teamDomain: string,
143 kid: string,
144 fetcher: (url: string) => Promise<Response>,
145 now: number,
146): Promise<CryptoKey | null> {
147 let set = keySets.get(teamDomain);
148 const stale = !set || now - set.fetchedAt >= JWKS_TTL_MS;
149 const unknown = set && !set.keys.has(kid) && now - set.fetchedAt >= JWKS_REFETCH_MS;
150 if (stale || unknown) {
151 try {
152 set = await fetchKeySet(teamDomain, fetcher, now);
153 keySets.set(teamDomain, set);
154 } catch {
155 // Keys that could not be refreshed are not trusted past their time.
156 if (stale) {
157 keySets.delete(teamDomain);
158 return null;
159 }
160 }
161 }
162 return set?.keys.get(kid) ?? null;
163}
164
165function base64UrlBytes(segment: string): Uint8Array<ArrayBuffer> {
166 const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
167 const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
168 const bytes = new Uint8Array(binary.length);
169 for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
170 return bytes;
171}
172
173function decodeJson(segment: string): Record<string, unknown> | null {
174 try {
175 const value: unknown = JSON.parse(new TextDecoder().decode(base64UrlBytes(segment)));
176 return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
177 } catch {
178 return null;
179 }
180}
181
182/** Verifies an Access JWT: signature, algorithm, issuer, audience and lifetime. */
183export async function verifyAccessJwt(
184 token: string,
185 settings: Pick<AccessSettings, "teamDomain" | "aud">,
186 options: VerifyOptions = {},
187): Promise<Verified> {
188 const now = options.now ?? Date.now();
189 const fetcher = options.fetcher ?? ((url: string) => fetch(url));
190
191 if (token.length > MAX_TOKEN_LENGTH) return { ok: false, reason: "token too long" };
192 const parts = token.split(".");
193 if (parts.length !== 3 || !parts.every((part) => /^[A-Za-z0-9_-]+$/.test(part))) {
194 return { ok: false, reason: "malformed token" };
195 }
196 const [encodedHeader, encodedPayload, encodedSignature] = parts;
197 const header = decodeJson(encodedHeader);
198 const payload = decodeJson(encodedPayload);
199 if (!header || !payload) return { ok: false, reason: "malformed token" };
200 // Only RS256: never `none`, and never a symmetric algorithm keyed with a public key.
201 if (header.alg !== "RS256") return { ok: false, reason: "unexpected algorithm" };
202 if (typeof header.kid !== "string" || !header.kid) return { ok: false, reason: "no key id" };
203
204 const key = await keyFor(settings.teamDomain, header.kid, fetcher, now);
205 if (!key) return { ok: false, reason: "unknown signing key" };
206
207 let signature: Uint8Array<ArrayBuffer>;
208 try {
209 signature = base64UrlBytes(encodedSignature);
210 } catch {
211 return { ok: false, reason: "malformed signature" };
212 }
213 const signed = new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`);
214 const valid = await crypto.subtle.verify(RSA, key, signature, signed);
215 if (!valid) return { ok: false, reason: "bad signature" };
216
217 // Only now that the signature holds do the claims mean anything.
218 if (payload.iss !== `https://${settings.teamDomain}`) return { ok: false, reason: "wrong issuer" };
219 const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
220 if (!audiences.includes(settings.aud)) return { ok: false, reason: "wrong audience" };
221 const seconds = Math.floor(now / 1000);
222 if (typeof payload.exp !== "number") return { ok: false, reason: "no expiry" };
223 if (seconds >= payload.exp + LEEWAY_SECONDS) return { ok: false, reason: "expired" };
224 if (payload.nbf !== undefined) {
225 if (typeof payload.nbf !== "number") return { ok: false, reason: "malformed nbf" };
226 if (seconds + LEEWAY_SECONDS < payload.nbf) return { ok: false, reason: "not yet valid" };
227 }
228 return { ok: true, claims: payload as AccessClaims };
229}
230
231export type Authorized = { ok: true; email: string } | { ok: false; reason: string; email?: string };
232
233/**
234 * Whether a request comes from g1t staff, through Access: a valid token
235 * whose email is on the staff list. Service tokens carry no email and are
236 * refused.
237 */
238export async function authorize(
239 request: Request,
240 settings: AccessSettings,
241 options: VerifyOptions = {},
242): Promise<Authorized> {
243 const token = request.headers.get("cf-access-jwt-assertion");
244 if (!token) return { ok: false, reason: "no Access token" };
245 const verified = await verifyAccessJwt(token, settings, options);
246 if (!verified.ok) return verified;
247 const email = typeof verified.claims.email === "string" ? verified.claims.email.trim().toLowerCase() : "";
248 if (!email) return { ok: false, reason: "token has no email" };
249 if (!isStaff(email, settings.staff)) return { ok: false, reason: "not staff", email };
250 return { ok: true, email };
251}
252
253/**
254 * Whether a change was posted from sudo's own pages: the browser's
255 * `Origin`, or failing that its `Referer`, must be sudo's. A request that
256 * says neither is refused.
257 */
258export function isSameOrigin(request: Request): boolean {
259 const site = request.headers.get("sec-fetch-site");
260 if (site !== null && site !== "same-origin") return false;
261 const origin = request.headers.get("origin");
262 if (origin !== null) return origin === ORIGIN;
263 const referer = request.headers.get("referer");
264 if (!referer) return false;
265 try {
266 return new URL(referer).origin === ORIGIN;
267 } catch {
268 return false;
269 }
270}