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

258 lines9,922 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Billing accounts, terms and enterprises; g1t is no longer free1/**
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. */
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
65export function parseStaff(raw: string): string[] {
66 return raw
67 .split(/[,\s]+/)
68 .map((email) => email.trim().toLowerCase())
69 .filter((email) => /^[^@\s]+@[^@\s]+$/.test(email));
70}
71
72export type AccessClaims = {
73 iss: string;
74 aud: string | string[];
75 exp: number;
76 nbf?: number;
77 iat?: number;
78 sub?: string;
79 email?: string;
80 [claim: string]: unknown;
81};
82
83export type Verified = { ok: true; claims: AccessClaims } | { ok: false; reason: string };
84
85export type VerifyOptions = {
86 /** Fetches the team's keys; the global `fetch` unless a test gives another. */
87 fetcher?: (url: string) => Promise<Response>;
88 /** Milliseconds since the epoch. */
89 now?: number;
90};
91
92type KeySet = { keys: Map<string, CryptoKey>; fetchedAt: number };
93
94/** The team's signing keys, by team domain, kept briefly in memory. */
95const keySets = new Map<string, KeySet>();
96
97/** Forgets the cached keys. For tests. */
98export function clearKeyCache(): void {
99 keySets.clear();
100}
101
102const RSA = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
103
104async function fetchKeySet(
105 teamDomain: string,
106 fetcher: (url: string) => Promise<Response>,
107 now: number,
108): Promise<KeySet> {
109 const response = await fetcher(`https://${teamDomain}/cdn-cgi/access/certs`);
110 if (!response.ok) throw new Error(`Access keys answered ${response.status}`);
111 const body = (await response.json()) as { keys?: unknown };
112 const keys = new Map<string, CryptoKey>();
113 for (const jwk of Array.isArray(body.keys) ? body.keys : []) {
114 if (!jwk || typeof jwk !== "object") continue;
115 const { kid, kty, n, e, alg, use } = jwk as Record<string, unknown>;
116 if (typeof kid !== "string" || kty !== "RSA" || typeof n !== "string" || typeof e !== "string") continue;
117 if (alg !== undefined && alg !== "RS256") continue;
118 if (use !== undefined && use !== "sig") continue;
119 try {
120 keys.set(kid, await crypto.subtle.importKey("jwk", { kty, n, e }, RSA, false, ["verify"]));
121 } catch {
122 // A key that does not import is skipped; tokens signed by it fail.
123 }
124 }
125 return { keys, fetchedAt: now };
126}
127
128/** The key a token names, fetching the team's keys when they are stale or it is new. */
129async function keyFor(
130 teamDomain: string,
131 kid: string,
132 fetcher: (url: string) => Promise<Response>,
133 now: number,
134): Promise<CryptoKey | null> {
135 let set = keySets.get(teamDomain);
136 const stale = !set || now - set.fetchedAt >= JWKS_TTL_MS;
137 const unknown = set && !set.keys.has(kid) && now - set.fetchedAt >= JWKS_REFETCH_MS;
138 if (stale || unknown) {
139 try {
140 set = await fetchKeySet(teamDomain, fetcher, now);
141 keySets.set(teamDomain, set);
142 } catch {
143 // Keys that could not be refreshed are not trusted past their time.
144 if (stale) {
145 keySets.delete(teamDomain);
146 return null;
147 }
148 }
149 }
150 return set?.keys.get(kid) ?? null;
151}
152
153function base64UrlBytes(segment: string): Uint8Array<ArrayBuffer> {
154 const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
155 const binary = atob(base64 + "=".repeat((4 - (base64.length % 4)) % 4));
156 const bytes = new Uint8Array(binary.length);
157 for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
158 return bytes;
159}
160
161function decodeJson(segment: string): Record<string, unknown> | null {
162 try {
163 const value: unknown = JSON.parse(new TextDecoder().decode(base64UrlBytes(segment)));
164 return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
165 } catch {
166 return null;
167 }
168}
169
170/** Verifies an Access JWT: signature, algorithm, issuer, audience and lifetime. */
171export async function verifyAccessJwt(
172 token: string,
173 settings: Pick<AccessSettings, "teamDomain" | "aud">,
174 options: VerifyOptions = {},
175): Promise<Verified> {
176 const now = options.now ?? Date.now();
177 const fetcher = options.fetcher ?? ((url: string) => fetch(url));
178
179 if (token.length > MAX_TOKEN_LENGTH) return { ok: false, reason: "token too long" };
180 const parts = token.split(".");
181 if (parts.length !== 3 || !parts.every((part) => /^[A-Za-z0-9_-]+$/.test(part))) {
182 return { ok: false, reason: "malformed token" };
183 }
184 const [encodedHeader, encodedPayload, encodedSignature] = parts;
185 const header = decodeJson(encodedHeader);
186 const payload = decodeJson(encodedPayload);
187 if (!header || !payload) return { ok: false, reason: "malformed token" };
188 // Only RS256: never `none`, and never a symmetric algorithm keyed with a public key.
189 if (header.alg !== "RS256") return { ok: false, reason: "unexpected algorithm" };
190 if (typeof header.kid !== "string" || !header.kid) return { ok: false, reason: "no key id" };
191
192 const key = await keyFor(settings.teamDomain, header.kid, fetcher, now);
193 if (!key) return { ok: false, reason: "unknown signing key" };
194
195 let signature: Uint8Array<ArrayBuffer>;
196 try {
197 signature = base64UrlBytes(encodedSignature);
198 } catch {
199 return { ok: false, reason: "malformed signature" };
200 }
201 const signed = new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`);
202 const valid = await crypto.subtle.verify(RSA, key, signature, signed);
203 if (!valid) return { ok: false, reason: "bad signature" };
204
205 // Only now that the signature holds do the claims mean anything.
206 if (payload.iss !== `https://${settings.teamDomain}`) return { ok: false, reason: "wrong issuer" };
207 const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
208 if (!audiences.includes(settings.aud)) return { ok: false, reason: "wrong audience" };
209 const seconds = Math.floor(now / 1000);
210 if (typeof payload.exp !== "number") return { ok: false, reason: "no expiry" };
211 if (seconds >= payload.exp + LEEWAY_SECONDS) return { ok: false, reason: "expired" };
212 if (payload.nbf !== undefined) {
213 if (typeof payload.nbf !== "number") return { ok: false, reason: "malformed nbf" };
214 if (seconds + LEEWAY_SECONDS < payload.nbf) return { ok: false, reason: "not yet valid" };
215 }
216 return { ok: true, claims: payload as AccessClaims };
217}
218
219export type Authorized = { ok: true; email: string } | { ok: false; reason: string; email?: string };
220
221/**
222 * Whether a request comes from g1t staff, through Access: a valid token
223 * whose email is on the staff list. Service tokens carry no email and are
224 * refused.
225 */
226export async function authorize(
227 request: Request,
228 settings: AccessSettings,
229 options: VerifyOptions = {},
230): Promise<Authorized> {
231 const token = request.headers.get("cf-access-jwt-assertion");
232 if (!token) return { ok: false, reason: "no Access token" };
233 const verified = await verifyAccessJwt(token, settings, options);
234 if (!verified.ok) return verified;
235 const email = typeof verified.claims.email === "string" ? verified.claims.email.trim().toLowerCase() : "";
236 if (!email) return { ok: false, reason: "token has no email" };
237 if (!settings.staff.includes(email)) return { ok: false, reason: "not staff", email };
238 return { ok: true, email };
239}
240
241/**
242 * Whether a change was posted from sudo's own pages: the browser's
243 * `Origin`, or failing that its `Referer`, must be sudo's. A request that
244 * says neither is refused.
245 */
246export function isSameOrigin(request: Request): boolean {
247 const site = request.headers.get("sec-fetch-site");
248 if (site !== null && site !== "same-origin") return false;
249 const origin = request.headers.get("origin");
250 if (origin !== null) return origin === ORIGIN;
251 const referer = request.headers.get("referer");
252 if (!referer) return false;
253 try {
254 return new URL(referer).origin === ORIGIN;
255 } catch {
256 return false;
257 }
258}