@coffre/conformance 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/chrome.ts CHANGED
@@ -20,6 +20,8 @@ export type Loaded = {
20
20
  href: string;
21
21
  /** The text of the dialog open at the end, as after `then` opened one; null for none. */
22
22
  dialog: string | null;
23
+ /** What `then` returned, as JSON gives it; null without one. */
24
+ answer: unknown;
23
25
  errors: string[];
24
26
  };
25
27
 
@@ -141,7 +143,7 @@ export class Chrome {
141
143
  * shows once its scripts have run and settled, and every uncaught error,
142
144
  * console error and failed load along the way. `then`, a script run once
143
145
  * the page settles, does what a person would next, such as open a dialog,
144
- * whose text is read with the rest.
146
+ * whose text is read with the rest, and may answer what it saw.
145
147
  */
146
148
  async load(url: string, cookies: [string, string][], settle = 2_000, then?: string): Promise<Loaded> {
147
149
  const { targetId } = (await this.#send('Target.createTarget', { url: 'about:blank' })) as { targetId: string };
@@ -173,8 +175,12 @@ export class Chrome {
173
175
  await Promise.race([load, new Promise((resolve) => setTimeout(resolve, 30_000))]);
174
176
  // What streams in after the load, and hydration, have their time: the page may render, then fail.
175
177
  await new Promise((resolve) => setTimeout(resolve, settle));
178
+ let answer: unknown = null;
176
179
  if (then !== undefined) {
177
- await this.#send('Runtime.evaluate', { expression: then, awaitPromise: true }, sessionId);
180
+ const { result } = (await this.#send('Runtime.evaluate', { expression: then, awaitPromise: true, returnByValue: true }, sessionId)) as {
181
+ result: { value?: unknown };
182
+ };
183
+ answer = result.value ?? null;
178
184
  // What it asked of the server has its time to come back.
179
185
  await new Promise((resolve) => setTimeout(resolve, settle));
180
186
  }
@@ -190,7 +196,7 @@ export class Chrome {
190
196
  const { result } = (await this.#send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)) as {
191
197
  result: { value: { heading: string | null; tab: string | null; cards: string[]; text: string; href: string; dialog: string | null } };
192
198
  };
193
- return { ...result.value, errors };
199
+ return { ...result.value, answer, errors };
194
200
  } finally {
195
201
  this.#listeners.delete(listener);
196
202
  await this.#send('Target.closeTarget', { targetId }).catch(() => {});
package/src/harness.ts CHANGED
@@ -40,8 +40,8 @@ export type Deployment = {
40
40
  kind: Kind;
41
41
  origin: string;
42
42
  idp: DevIdp;
43
- /** The one root admin the vault is told of. */
44
- rootAdmin: string;
43
+ /** The one bootstrap Owner the vault is told of: the first to sign in, who owns the instance. */
44
+ owner: string;
45
45
  /** Whether no heartbeat has run yet, so /readyz fails until `scheduled` runs. */
46
46
  beforeFirstBeat: boolean;
47
47
  /** What the Cron trigger does every five minutes. */
@@ -61,7 +61,15 @@ export type Deployment = {
61
61
  stop(): Promise<void>;
62
62
  };
63
63
 
64
- const ROOT_ADMIN = 'root@conformance.example';
64
+ const OWNER = 'root@conformance.example';
65
+
66
+ /**
67
+ * The vault's Owners, under each name a deployment's vault may read them by:
68
+ * `OWNERS`, and `BOOTSTRAP_OWNERS` and 0.5's `ROOT_ADMINS`, read until 0.7,
69
+ * as an older deployment's vault entry still does. Each Worker gets only the
70
+ * vars its wrangler.jsonc declares.
71
+ */
72
+ export const OWNER_VARS = { OWNERS: OWNER, BOOTSTRAP_OWNERS: OWNER, ROOT_ADMINS: OWNER };
65
73
 
66
74
  type Child = { name: string; child: ChildProcess; daemon: boolean; exited: boolean; output: Buffer[] };
67
75
 
@@ -226,7 +234,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
226
234
  APP_KEY: KEYS.APP_KEY,
227
235
  VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
228
236
  VAULT_KEY: KEYS.VAULT_KEY,
229
- ROOT_ADMINS: ROOT_ADMIN,
237
+ ...OWNER_VARS,
230
238
  CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE: runtime,
231
239
  CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_VAULT_HYPERDRIVE: vaultRuntime,
232
240
  WRANGLER_SEND_METRICS: 'false',
@@ -235,7 +243,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
235
243
  kind,
236
244
  origin,
237
245
  idp,
238
- rootAdmin: ROOT_ADMIN,
246
+ owner: OWNER,
239
247
  beforeFirstBeat: true,
240
248
  async scheduled(options = {}) {
241
249
  const response = await fetch(`${origin}/cdn-cgi/local/scheduled?cron=*/5+*+*+*+*`);
@@ -260,7 +268,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
260
268
  DATABASE_URL: `file:${database}`,
261
269
  VAULT_KEY_ID: KEYS.VAULT_KEY_ID,
262
270
  VAULT_KEY: KEYS.VAULT_KEY,
263
- ROOT_ADMINS: ROOT_ADMIN,
271
+ ...OWNER_VARS,
264
272
  });
265
273
  await until('the vault socket', async () => existsSync(socket), 30, alive);
266
274
  // The pages as they run: the deployment's Start app, built by its own Vite.
@@ -281,7 +289,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
281
289
  kind,
282
290
  origin,
283
291
  idp,
284
- rootAdmin: ROOT_ADMIN,
292
+ owner: OWNER,
285
293
  beforeFirstBeat: false,
286
294
  // `serve` runs the job as it starts, and every five minutes after:
287
295
  // so restart the server.
@@ -0,0 +1,259 @@
1
+ import { createPublicKey, generateKeyPair, randomBytes, type KeyObject } from 'node:crypto';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { promisify } from 'node:util';
4
+
5
+ import { jwtVerify } from 'jose';
6
+
7
+ import { authorizationToken, sendJson, type Route } from './http.ts';
8
+
9
+ const API = '/github/api';
10
+ const DOCS = 'https://docs.github.com/rest';
11
+
12
+ export type FakeRepository = { id: number; name: string; private: boolean };
13
+ export type FakeInstallation = {
14
+ id: number;
15
+ account: { login: string; id: number; type: 'Organization' | 'User' };
16
+ suspended: boolean;
17
+ repositories: FakeRepository[];
18
+ };
19
+
20
+ /** acme's repositories, private ones among them, and a user's; one installation suspended. */
21
+ export function fakeInstallations(): FakeInstallation[] {
22
+ return [
23
+ {
24
+ id: 1,
25
+ account: { login: 'acme', id: 9919, type: 'Organization' },
26
+ suspended: false,
27
+ repositories: [
28
+ { id: 41532, name: 'api', private: false },
29
+ { id: 41533, name: 'web', private: false },
30
+ { id: 41540, name: 'infra', private: true },
31
+ { id: 41541, name: 'payments', private: true },
32
+ { id: 41550, name: 'deploy-actions', private: true },
33
+ ],
34
+ },
35
+ {
36
+ id: 2,
37
+ account: { login: 'octo-dev', id: 583231, type: 'User' },
38
+ suspended: false,
39
+ repositories: [{ id: 70001, name: 'dotfiles', private: true }],
40
+ },
41
+ {
42
+ id: 3,
43
+ account: { login: 'old-co', id: 77001, type: 'Organization' },
44
+ suspended: true,
45
+ repositories: [{ id: 80001, name: 'legacy', private: true }],
46
+ },
47
+ ];
48
+ }
49
+
50
+ /**
51
+ * The deployment's GitHub App, as GitHub's REST API answers it, under
52
+ * `/github/api` beside the fake GitHub's sign-in: the app's JWT, checked
53
+ * against its public key as GitHub does, buys installation tokens, which
54
+ * list each installation's repositories. What `@coffre/core`'s `GitHubApp`
55
+ * runs against, through its real code paths.
56
+ *
57
+ * Its private key is GitHub's download, PKCS #1: `privateKey`, for the
58
+ * deployment's configuration, made at `start()` unless given.
59
+ */
60
+ export class FakeGitHubApp {
61
+ readonly #origin: () => string;
62
+ readonly appId = '1001';
63
+ readonly name = 'Coffre (dev)';
64
+ readonly slug = 'coffre-dev';
65
+ /** Its OAuth client, for signing people in: a GitHub App's client ID, and a local fixture for its secret. */
66
+ readonly clientId = 'Iv23li-coffre-dev';
67
+ readonly clientSecret = 'coffre-dev-app-secret';
68
+ /**
69
+ * What it may do, as its settings page grants it. Its user tokens carry
70
+ * these, not OAuth scopes: their email addresses with `emails`, and
71
+ * organization memberships with `members`, where it is installed.
72
+ */
73
+ permissions: { metadata: 'read'; emails?: 'read'; members?: 'read' } = { metadata: 'read', emails: 'read', members: 'read' };
74
+ /** The installations, by account; a test edits them as it likes. */
75
+ installations: FakeInstallation[] = fakeInstallations();
76
+ /** How long an installation token lives: an hour, as GitHub's. */
77
+ tokenTtlMs = 60 * 60 * 1000;
78
+ /** Installation tokens issued so far. */
79
+ tokensIssued = 0;
80
+ /** Every request answered 503 when set: GitHub down. */
81
+ down = false;
82
+ #privateKey: string | undefined;
83
+ #publicKey: KeyObject | null = null;
84
+ readonly #tokens = new Map<string, { installation: number; expiresAt: number }>();
85
+
86
+ constructor(origin: () => string, privateKey?: string) {
87
+ this.#origin = origin;
88
+ this.#privateKey = privateKey;
89
+ }
90
+
91
+ /** The app's private key, PKCS #1 PEM, as GitHub downloads it. */
92
+ get privateKey(): string {
93
+ if (this.#privateKey === undefined) throw new Error('the fake GitHub App is not started');
94
+ return this.#privateKey;
95
+ }
96
+
97
+ /** What a deployment's `githubApp(…)` names to reach this one, for repositories and sign-in alike. */
98
+ get options(): { appId: string; privateKey: string; clientId: string; clientSecret: string; webUrl: string; apiUrl: string } {
99
+ return {
100
+ appId: this.appId,
101
+ privateKey: this.privateKey,
102
+ clientId: this.clientId,
103
+ clientSecret: this.clientSecret,
104
+ webUrl: `${this.#origin()}/github`,
105
+ apiUrl: `${this.#origin()}${API}`,
106
+ };
107
+ }
108
+
109
+ /** Whether it is installed on this account, and not suspended: where its user tokens reach. */
110
+ installedOn(login: string): boolean {
111
+ return this.installations.some((each) => each.account.login.toLowerCase() === login.toLowerCase() && !each.suspended);
112
+ }
113
+
114
+ async start(): Promise<void> {
115
+ if (this.#privateKey === undefined) {
116
+ const { privateKey } = await promisify(generateKeyPair)('rsa', { modulusLength: 2048 });
117
+ this.#privateKey = privateKey.export({ type: 'pkcs1', format: 'pem' }) as string;
118
+ }
119
+ this.#publicKey = createPublicKey(this.#privateKey);
120
+ }
121
+
122
+ /** Every token issued dies now: as when the app is reinstalled. */
123
+ revokeTokens(): void {
124
+ this.#tokens.clear();
125
+ }
126
+
127
+ routes(): Route[] {
128
+ const repo = '([A-Za-z0-9-]+)/([A-Za-z0-9._-]+)';
129
+ return [
130
+ { method: 'GET', path: `${API}/app`, handler: async (req, res) => this.#asApp(req, res, () => this.#app()) },
131
+ {
132
+ method: 'GET',
133
+ path: `${API}/app/installations`,
134
+ handler: async (req, res, url) => this.#asApp(req, res, () => [200, this.#installations(url)]),
135
+ },
136
+ {
137
+ method: 'POST',
138
+ path: new RegExp(`^${API}/app/installations/[0-9]+/access_tokens$`),
139
+ handler: async (req, res, url) => this.#asApp(req, res, () => this.#issue(Number(url.pathname.split('/').at(-2)))),
140
+ },
141
+ {
142
+ method: 'GET',
143
+ path: new RegExp(`^${API}/repos/${repo}/installation$`),
144
+ handler: async (req, res, url) => this.#asApp(req, res, () => this.#installationOf(url.pathname.split('/').slice(-3, -1).join('/'))),
145
+ },
146
+ {
147
+ method: 'GET',
148
+ path: `${API}/installation/repositories`,
149
+ handler: async (req, res, url) => this.#asInstallation(req, res, (installation) => [200, this.#page(installation, url)]),
150
+ },
151
+ {
152
+ method: 'GET',
153
+ path: new RegExp(`^${API}/repos/${repo}$`),
154
+ handler: async (req, res, url) =>
155
+ this.#asInstallation(req, res, (installation) => {
156
+ const name = url.pathname.split('/').slice(-2).join('/');
157
+ const found = installation.repositories.find((each) => `${installation.account.login}/${each.name}`.toLowerCase() === name.toLowerCase());
158
+ return found === undefined ? notFound() : [200, this.#repository(installation, found)];
159
+ }),
160
+ },
161
+ ];
162
+ }
163
+
164
+ #app(): Answer {
165
+ return [200, { id: Number(this.appId), slug: this.slug, name: this.name, client_id: this.clientId, html_url: `${this.#origin()}/github/apps/${this.slug}`, permissions: this.permissions }];
166
+ }
167
+
168
+ /** https://docs.github.com/en/rest/apps/apps#list-installations-for-the-authenticated-app */
169
+ #installations(url: URL): unknown[] {
170
+ const perPage = Math.min(Number(url.searchParams.get('per_page') ?? 30), 100);
171
+ return this.installations.slice(0, perPage).map((installation) => ({
172
+ id: installation.id,
173
+ account: { login: installation.account.login, id: installation.account.id, type: installation.account.type },
174
+ repository_selection: 'selected',
175
+ app_id: Number(this.appId),
176
+ suspended_at: installation.suspended ? '2026-01-01T00:00:00Z' : null,
177
+ }));
178
+ }
179
+
180
+ /** https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app */
181
+ #issue(id: number): Answer {
182
+ const installation = this.installations.find((each) => each.id === id);
183
+ if (installation === undefined) return notFound();
184
+ if (installation.suspended) return [403, { message: 'This installation has been suspended', documentation_url: DOCS }];
185
+ const token = `ghs_${randomBytes(18).toString('hex')}`;
186
+ const expiresAt = Date.now() + this.tokenTtlMs;
187
+ this.#tokens.set(token, { installation: id, expiresAt });
188
+ this.tokensIssued++;
189
+ return [201, { token, expires_at: new Date(expiresAt).toISOString().replace(/\.\d{3}Z$/, 'Z'), permissions: this.permissions, repository_selection: 'selected' }];
190
+ }
191
+
192
+ /** https://docs.github.com/en/rest/apps/apps#get-a-repository-installation-for-the-authenticated-app */
193
+ #installationOf(name: string): Answer {
194
+ const installation = this.installations.find((each) =>
195
+ each.repositories.some((repository) => `${each.account.login}/${repository.name}`.toLowerCase() === name.toLowerCase()),
196
+ );
197
+ if (installation === undefined) return notFound();
198
+ return [200, { id: installation.id, account: { login: installation.account.login, id: installation.account.id }, suspended_at: installation.suspended ? '2026-01-01T00:00:00Z' : null }];
199
+ }
200
+
201
+ /** https://docs.github.com/en/rest/apps/installations#list-repositories-accessible-to-the-app-installation */
202
+ #page(installation: FakeInstallation, url: URL): unknown {
203
+ const perPage = Math.min(Number(url.searchParams.get('per_page') ?? 30), 100);
204
+ const page = Math.max(Number(url.searchParams.get('page') ?? 1), 1);
205
+ return {
206
+ total_count: installation.repositories.length,
207
+ repository_selection: 'selected',
208
+ repositories: installation.repositories.slice((page - 1) * perPage, page * perPage).map((each) => this.#repository(installation, each)),
209
+ };
210
+ }
211
+
212
+ #repository(installation: FakeInstallation, repository: FakeRepository): unknown {
213
+ const { login, id, type } = installation.account;
214
+ return {
215
+ id: repository.id,
216
+ node_id: `R_dev${repository.id}`,
217
+ name: repository.name,
218
+ full_name: `${login}/${repository.name}`,
219
+ private: repository.private,
220
+ owner: { login, id, type },
221
+ html_url: `https://github.com/${login}/${repository.name}`,
222
+ };
223
+ }
224
+
225
+ /** As the app, by its JWT: RS256 under its key, issued by its ID, for ten minutes at most. */
226
+ async #asApp(req: IncomingMessage, res: ServerResponse, answer: () => Answer): Promise<void> {
227
+ if (this.down) return send(res, [503, { message: 'Service Unavailable' }]);
228
+ const jwt = authorizationToken(req, ['bearer']);
229
+ try {
230
+ if (jwt === undefined || this.#publicKey === null) throw new Error('no JWT');
231
+ const { payload } = await jwtVerify(jwt, this.#publicKey, { algorithms: ['RS256'], issuer: this.appId, clockTolerance: 60 });
232
+ if (typeof payload.iat !== 'number' || typeof payload.exp !== 'number' || payload.exp - payload.iat > 600) throw new Error('too long');
233
+ } catch {
234
+ return send(res, [401, { message: 'A JSON web token could not be decoded', documentation_url: DOCS }]);
235
+ }
236
+ send(res, answer());
237
+ }
238
+
239
+ /** As an installation, by a token it issued that lives still. */
240
+ async #asInstallation(req: IncomingMessage, res: ServerResponse, answer: (installation: FakeInstallation) => Answer): Promise<void> {
241
+ if (this.down) return send(res, [503, { message: 'Service Unavailable' }]);
242
+ const token = this.#tokens.get(authorizationToken(req, ['bearer', 'token']) ?? '');
243
+ const installation = this.installations.find((each) => each.id === token?.installation);
244
+ if (token === undefined || token.expiresAt <= Date.now() || installation === undefined || installation.suspended) {
245
+ return send(res, [401, { message: 'Bad credentials', documentation_url: DOCS }]);
246
+ }
247
+ send(res, answer(installation));
248
+ }
249
+ }
250
+
251
+ type Answer = [number, unknown];
252
+
253
+ function notFound(): Answer {
254
+ return [404, { message: 'Not Found', documentation_url: DOCS }];
255
+ }
256
+
257
+ function send(res: ServerResponse, [status, body]: Answer): void {
258
+ sendJson(res, status, body, { 'x-github-api-version-selected': '2022-11-28' });
259
+ }
package/src/idp/github.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
3
 
3
4
  import type { AuthorizationServer, Flavor, Grant } from './authorize.ts';
@@ -74,10 +75,11 @@ export class FakeGitHub {
74
75
  * https://docs.github.com/en/apps/oauth-apps/maintaining-oauth-apps/troubleshooting-oauth-app-access-token-request-errors
75
76
  */
76
77
  async #accessToken(req: IncomingMessage, res: ServerResponse): Promise<void> {
77
- const reply = (body: Record<string, string>) => {
78
+ // Numbers stay numbers in JSON, and are strings in a form, as everything there is.
79
+ const reply = (body: Record<string, string | number>) => {
78
80
  if ((req.headers.accept ?? '').includes('application/json')) return sendJson(res, 200, body);
79
81
  res.writeHead(200, { 'content-type': 'application/x-www-form-urlencoded; charset=utf-8' });
80
- res.end(new URLSearchParams(body).toString());
82
+ res.end(new URLSearchParams(Object.entries(body).map(([key, value]) => [key, String(value)])).toString());
81
83
  };
82
84
  const fail = (error: string, description: string) =>
83
85
  reply({ error, error_description: description, error_uri: `${TROUBLESHOOTING}#${error.replaceAll('_', '-')}` });
@@ -97,14 +99,15 @@ export class FakeGitHub {
97
99
  return fail('incorrect_client_credentials', 'The client_id and/or client_secret passed are incorrect.');
98
100
  }
99
101
 
102
+ // A GitHub App's user tokens expire in eight hours; an OAuth app's do not, unless it opts in.
103
+ const app = this.#isApp(client.clientId);
100
104
  const result = this.#authz.exchange('github', {
101
105
  client,
102
106
  code: params.get('code') ?? '',
103
107
  redirectUri: params.get('redirect_uri') ?? undefined,
104
108
  codeVerifier: params.get('code_verifier') ?? '',
105
- // OAuth app tokens do not expire unless the app opts in.
106
- accessTokenTtl: Infinity,
107
- accessTokenPrefix: 'gho_',
109
+ accessTokenTtl: app ? 8 * 60 * 60 : Infinity,
110
+ accessTokenPrefix: app ? 'ghu_' : 'gho_',
108
111
  });
109
112
  if (!result.ok) {
110
113
  if (result.error === 'redirect_uri_mismatch') {
@@ -112,6 +115,18 @@ export class FakeGitHub {
112
115
  }
113
116
  return fail('bad_verification_code', 'The code passed is incorrect or expired.');
114
117
  }
118
+ // https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app
119
+ // An expiring user token comes with a refresh token, for six months; coffre uses neither, and keeps no token.
120
+ if (app) {
121
+ return reply({
122
+ access_token: result.accessToken,
123
+ expires_in: 8 * 60 * 60,
124
+ refresh_token: `ghr_${randomBytes(30).toString('hex')}`,
125
+ refresh_token_expires_in: 15_897_600,
126
+ token_type: 'bearer',
127
+ scope: '',
128
+ });
129
+ }
115
130
  reply({ access_token: result.accessToken, token_type: 'bearer', scope: result.grant.scope.join(',') });
116
131
  }
117
132
 
@@ -140,7 +155,10 @@ export class FakeGitHub {
140
155
  #emails(req: IncomingMessage, res: ServerResponse): void {
141
156
  const auth = this.#authenticate(req, res);
142
157
  if (!auth) return;
143
- if (!this.#hasScope(auth.grant, ['user:email', 'user'])) return this.#notFound(res, auth.grant);
158
+ // A GitHub App's user token carries the app's permissions, not scopes: "Email addresses", read.
159
+ if (this.#isApp(auth.grant.clientId)) {
160
+ if (this.#idp.githubApp.permissions.emails === undefined) return this.#notAccessible(res, auth.grant);
161
+ } else if (!this.#hasScope(auth.grant, ['user:email', 'user'])) return this.#notFound(res, auth.grant);
144
162
  this.#json(res, auth.grant, 200, auth.account.emails);
145
163
  }
146
164
 
@@ -153,7 +171,11 @@ export class FakeGitHub {
153
171
  #membership(req: IncomingMessage, res: ServerResponse, org: string): void {
154
172
  const auth = this.#authenticate(req, res);
155
173
  if (!auth) return;
156
- if (!this.#hasScope(auth.grant, ['read:org', 'write:org', 'admin:org', 'user'])) {
174
+ // A GitHub App's user token reaches an organization's members only with the app's "Members" permission, and only
175
+ // where the app is installed: elsewhere, "Resource not accessible by integration".
176
+ if (this.#isApp(auth.grant.clientId)) {
177
+ if (this.#idp.githubApp.permissions.members === undefined || !this.#idp.githubApp.installedOn(org)) return this.#notAccessible(res, auth.grant);
178
+ } else if (!this.#hasScope(auth.grant, ['read:org', 'write:org', 'admin:org', 'user'])) {
157
179
  return this.#json(res, auth.grant, 403, {
158
180
  message: 'You need at least read:org scope or user scope to read organization memberships.',
159
181
  documentation_url: DOCS,
@@ -192,6 +214,15 @@ export class FakeGitHub {
192
214
  return { grant, account: this.#idp.gitHubUserFor(normalizeEmail(grant.email)) };
193
215
  }
194
216
 
217
+ /** The deployment's GitHub App's OAuth client, whose tokens are user tokens of the app's. */
218
+ #isApp(clientId: string): boolean {
219
+ return clientId === this.#idp.githubApp.clientId;
220
+ }
221
+
222
+ #notAccessible(res: ServerResponse, grant: Grant): void {
223
+ this.#json(res, grant, 403, { message: 'Resource not accessible by integration', documentation_url: DOCS });
224
+ }
225
+
195
226
  #hasScope(grant: Grant, accepted: readonly string[]): boolean {
196
227
  return grant.scope.some((s) => accepted.includes(s));
197
228
  }
package/src/idp/idp.ts CHANGED
@@ -3,6 +3,7 @@ import { exportJWK, generateKeyPair, SignJWT, type JWK, type CryptoKey } from 'j
3
3
 
4
4
  import { AuthorizationServer } from './authorize.ts';
5
5
  import { FakeGitHub } from './github.ts';
6
+ import { FakeGitHubApp } from './github-app.ts';
6
7
  import type { Route } from './http.ts';
7
8
  import { OidcProvider } from './oidc.ts';
8
9
  import { WorkloadIssuer } from './workloads.ts';
@@ -34,6 +35,8 @@ export interface DevIdpOptions {
34
35
  clients?: readonly DevIdpClient[];
35
36
  /** Skip the persona page when the request carries a login hint. For tests. */
36
37
  autoApprove?: boolean;
38
+ /** The fake GitHub App's private key, PKCS #1 PEM: made at start unless given. */
39
+ githubAppKey?: string;
37
40
  }
38
41
 
39
42
  /** Built in, so local dev needs no registration step. */
@@ -48,7 +51,7 @@ export const DEFAULT_CLIENT = Object.freeze({
48
51
  * For Cloudflare Access, it generates a keypair, serves a JWKS at the same
49
52
  * `cdn-cgi` path Access uses, and mints Access-shaped tokens. It is also an
50
53
  * OpenID Connect provider (under `/oauth`) signing with the same key, and an
51
- * imitation of GitHub's OAuth apps and REST API (under `/github`). The
54
+ * imitation of GitHub's OAuth apps, a GitHub App and REST API (under `/github`). The
52
55
  * point is that the code under test runs its real remote code paths against
53
56
  * real HTTP endpoints -- local mode is a different implementation of the same
54
57
  * interface, never a branch that skips verification.
@@ -77,17 +80,28 @@ export class DevIdp {
77
80
  /** A CI platform's ID tokens, under `/workloads`, for trust bindings. */
78
81
  readonly workloads = new WorkloadIssuer(() => this.origin);
79
82
 
83
+ /** A deployment's GitHub App, under `/github/api` beside the fake GitHub. */
84
+ readonly githubApp: FakeGitHubApp;
85
+
80
86
  constructor(options: DevIdpOptions = {}) {
81
87
  this.autoApprove = options.autoApprove ?? false;
88
+ this.githubApp = new FakeGitHubApp(() => this.origin, options.githubAppKey);
82
89
  this.#clients.set(DEFAULT_CLIENT.clientId, {
83
90
  ...DEFAULT_CLIENT,
84
91
  redirectUris: [],
85
92
  anyLoopbackRedirect: true,
86
93
  });
87
94
  for (const client of options.clients ?? []) this.registerClient(client);
95
+ // The GitHub App's own OAuth client, which signs people in as the fake GitHub's do.
96
+ this.#clients.set(this.githubApp.clientId, {
97
+ clientId: this.githubApp.clientId,
98
+ clientSecret: this.githubApp.clientSecret,
99
+ redirectUris: [],
100
+ anyLoopbackRedirect: true,
101
+ });
88
102
 
89
103
  const authz = new AuthorizationServer(this);
90
- this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes(), ...this.workloads.routes()];
104
+ this.#routes = [...new OidcProvider(this, authz).routes(), ...new FakeGitHub(this, authz).routes(), ...this.githubApp.routes(), ...this.workloads.routes()];
91
105
  }
92
106
 
93
107
  get origin(): string {
@@ -110,6 +124,7 @@ export class DevIdp {
110
124
  this.privateKey = privateKey;
111
125
  this.publicJwk = { ...(await exportJWK(publicKey)), kid: this.kid, alg: 'RS256', use: 'sig' };
112
126
  await this.workloads.start();
127
+ await this.githubApp.start();
113
128
 
114
129
  this.#server = createServer((req, res) => {
115
130
  // Dev-only: stands in for `cloudflared access login`. Cloudflare Access
package/src/idp/index.ts CHANGED
@@ -3,4 +3,5 @@
3
3
  // it; the dev loop and the tests use it too.
4
4
  export { DEFAULT_CLIENT, DevIdp, type DevIdpClient, type DevIdpOptions, type RegisteredClient } from './idp.ts';
5
5
  export { PERSONAS, type GitHubAccount, type GitHubAccountPatch, type Persona } from './people.ts';
6
+ export { fakeInstallations, FakeGitHubApp, type FakeInstallation, type FakeRepository } from './github-app.ts';
6
7
  export { GITHUB_RUN, WorkloadIssuer } from './workloads.ts';
package/src/idp/people.ts CHANGED
@@ -13,8 +13,8 @@ export interface Persona {
13
13
  * lands on a seeded account.
14
14
  */
15
15
  export const PERSONAS: readonly Persona[] = Object.freeze([
16
- { email: 'admin@acme.example', name: 'Ada Admin', note: 'root admin' },
17
- { email: 'lead@acme.example', name: 'Lea Lead', note: 'owner' },
16
+ { email: 'admin@acme.example', name: 'Ada Admin', note: 'owner of coffre' },
17
+ { email: 'lead@acme.example', name: 'Lea Lead', note: 'owner of market' },
18
18
  { email: 'dev@acme.example', name: 'Devon Dev', note: 'developer on dev' },
19
19
  { email: 'auditor@acme.example', name: 'Audrey Auditor', note: 'auditor' },
20
20
  { email: 'accessmgr@acme.example', name: 'Max Access', note: 'access manager' },
package/src/suite.ts CHANGED
@@ -16,7 +16,7 @@ import { editedGeneration, forgedCredential, forgedIdentity, forgedApproval } fr
16
16
  import { canaryScan } from './checks/canaries.ts';
17
17
  import { Cli, cliLogin, manageByCli, verifyAsOwner, verifyAsUser, verifyInterrupted, verifyKeys, verifyLeftovers, verifyWithToken } from './checks/cli.ts';
18
18
  import { pageLoad, personas, setUp, setUpLive, signInAdmin } from './checks/people.ts';
19
- import { pagesInBrowser, signinErrorOnce } from './checks/pages.ts';
19
+ import { pagesInBrowser, pastedValues, signinErrorOnce } from './checks/pages.ts';
20
20
  import { browserBundle, headers, health } from './checks/surface.ts';
21
21
  import { cliSignsIn, exchangesLimited, runSignsIn, runsRefused, runUnbound, spentOnce, tokensUnlogged, trustRun } from './checks/workloads.ts';
22
22
 
@@ -30,6 +30,7 @@ export async function conform(deployment: Deployment, options: { bulkLimit: numb
30
30
  await report.check('security headers', { admin }, ({ admin }) => headers(deployment, admin));
31
31
  const canaries = await report.check('setup', { admin }, ({ admin }) => setUp(admin));
32
32
  await report.check('pages in a browser', { admin, canaries }, ({ admin }) => pagesInBrowser(deployment, admin, options.browser));
33
+ await report.check('pasted values', { admin }, ({ admin }) => pastedValues(deployment, admin, options.browser));
33
34
  await report.check('sign-in error, once', { admin }, ({ admin }) => signinErrorOnce(deployment, admin, options.browser));
34
35
  const people = await report.check('personas', { admin, canaries }, ({ admin }) => personas(deployment, admin));
35
36
  const all = { people, canaries };