diff --git a/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md index 8aadddc..1f59d10 100644 --- a/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md +++ b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md @@ -347,10 +347,14 @@ independent. Reconciliation should: 6. persist a cursor or last-success marker; 7. log counts and classifications without response bodies. -Public unauthenticated GitHub API access is sufficient at the current -repository count. If its limit becomes operationally inadequate, use a -least-privileged GitHub App installation token; do not introduce a broad -personal token. +Public unauthenticated GitHub API access is the default. It can fail under +upstream limits or other access conditions; HTTP 403 alone does not identify +the cause. The optional [catalog-only GitHub App mode](../worker/README.md#github-release-ingestion-operators) +uses one selected repository per metadata-only token, fresh public repository +and organization checks, current expiry fences and no retry. It cannot reuse +engineering write credentials. Its public-release compatibility and deployed +CPU cost require qualification before separate host activation. Do not +introduce a broad personal token or widen contents permissions after a refusal. ## Operational visibility diff --git a/src/data/components.ts b/src/data/components.ts index 84db87f..39afaca 100644 --- a/src/data/components.ts +++ b/src/data/components.ts @@ -199,7 +199,7 @@ export const components: readonly PegmaComponent[] = [ 'Being a hosted SaaS — hosts run it, own its data, and choose its providers', 'AI processing before the host documents what may leave its boundary', ], - now: 'The 0.1.0 package set is published on npm from the signed v0.1.0 release (2026-07-29); host deployments are the next step.', + now: 'The 0.2.12 package set is published on npm and composed by the Cloudflare reference host; optional AI routes remain host-controlled.', plan: 'docs/PROJECT_PLAN.md', }, { diff --git a/worker/README.md b/worker/README.md index d37999c..f27c035 100644 --- a/worker/README.md +++ b/worker/README.md @@ -350,6 +350,67 @@ remaining slots return without database or GitHub I/O. The 60-slot capacity is checked in code. Fetches use stable numeric repository IDs, conditional ETags, and bounded timeouts/bodies. Full-catalog backfill remains available explicitly. +Reconciliation defaults to anonymous public reads. The optional dedicated +catalog GitHub App mode is selected only by `GITHUB_RELEASE_AUTH_MODE=github_app`; +omission or `anonymous` preserves the default. An invalid or unavailable +configured App mode fails closed, without an anonymous retry. It never uses +the engineering App credentials or enables engineering/AI capabilities. + +The separate `GITHUB_RELEASE_APP_CONFIGURATION` JSON has exactly `appId`, +`installationId`, `version`, and UTC `validUntil` fields. The host supplies its +dedicated PKCS#8 PEM signing key as the secret +`GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8`, never a committed var. The existing +organization ID and exact 13-ID repository allowlist must be configured. No +App, installation, key or enabled mode is supplied by the default deployment. +The dedicated App installation must select only those 13 public repositories +and grant metadata-read only. +Both IDs are positive decimal **JSON strings**, not numbers. `version` is a +1–100 character string of letters, digits, dot, underscore or hyphen; +`validUntil` is a future UTC ISO timestamp ending in `Z` (optional millisecond +precision). The allowlist var is shared with webhook ingestion and public +release display. This App mode deliberately requires the complete 13-ID +deployment contract; narrowing it makes App mode unavailable. Do not widen an +ingestion allowlist merely to repair a configured authentication refusal. +The issuer signs a fresh RS256 App JWT and requests a selected installation +token for one scheduled immutable repository ID with **metadata-read only**. +It refuses any contents, issues or write permission in the returned grant. + +Public latest-release access with this metadata-only token is an inference +from GitHub's public-resource access contract, not a deployed compatibility +claim. Before activation, verify that exact public read using the separately +approved App/installation; a refusal must not prompt broader permissions. +See GitHub's [latest-release access contract](https://docs.github.com/en/rest/releases/releases#get-the-latest-release), +[installation-token scope](https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app) +and [App JWT requirements](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app). +After each authenticated 200, 304 or 404, a fresh metadata read must confirm +the exact repository is public and belongs to the configured Pegma organization +before projection or progress advances. Inaccessible, private, transferred, +expired or changed authority holds the prior state. Authenticated requests +reject redirects. Minting, release access, metadata verification and projection +preparation share one ten-second admission deadline, with at most three GitHub +requests and no retry/cache. Authority is checked after awaited preparation +and synchronously at atomic transaction submission. Public Store transactions +cannot be canceled once submitted: the caller awaits their actual outcome, +including a late acknowledgement, rather than reporting a false timeout while +an abandoned write continues. A refusal or timeout before submission cannot +later resume into a write. Issuer and reconciliation must share one clock and +transport; the production root wires both explicitly. +Local tests do not prove deployed signing CPU cost or grant live access. + +HTTP 403/429 summaries retain only bounded numeric `rateLimitRemaining` (up to +2,147,483,647) and `retryAfterSeconds` (decimal seconds up to 86,400), or null. +HTTP-date, malformed and out-of-bound Retry-After values are deliberately +discarded. Zero remaining or a retained numeric Retry-After is a throttle +signal; absent hints or nonzero remaining do not establish permission failure +or exclude secondary limiting. No error response body, raw headers, key, JWT +or token is logged. The [issuer and reconciliation tests](src/release-catalog-auth.test.ts) +exercise the optional contract with fictional responses. +Authentication failures use only the closed reason codes +`invalid_configuration`, `issuer_unavailable`, `invalid_grant` and +`authority_unavailable`. Metadata failures retain their own response status and +classification; they never combine a release body's byte count with a +different response. + Each successful scheduled shard records its scheduled timestamp durably in the existing operations collection. Global reconciliation health advances only when every currently allowlisted catalog repository has succeeded in that diff --git a/worker/src/index.ts b/worker/src/index.ts index 180856f..494ccd9 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -45,6 +45,7 @@ import { type GitHubReleaseWebhookEnv, } from './github-release-webhook'; import { loadReleaseHealthDetail } from './release-health'; +import { releaseCatalogAuthenticationFor, type ReleaseCatalogAuthenticationEnv } from './release-catalog-auth'; import { RELEASE_RECONCILIATION_CRON, runReleaseReconciliation, @@ -92,6 +93,7 @@ type AppEnv = Omit env, { clock: releaseClock, fetch: releaseFetch }), + clock: releaseClock, + fetchImpl: releaseFetch, followupTracking: () => followupTrackingFor(env), }); } catch (error) { diff --git a/worker/src/release-catalog-auth.test.ts b/worker/src/release-catalog-auth.test.ts new file mode 100644 index 0000000..507d76c --- /dev/null +++ b/worker/src/release-catalog-auth.test.ts @@ -0,0 +1,270 @@ +import { createMemoryStore } from '@pegma/storage-core'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; +import { RELEASE_CATALOG } from './release-catalog'; +import { componentReleaseCollection, componentReleaseKey } from './component-release'; +import { readReleaseOpsState } from './release-ops-state'; +import { runReleaseReconciliation } from './release-reconciliation'; +import { + releaseCatalogAuthenticationFor, releaseRateHints, + type ReleaseCatalogAuthentication, type ReleaseCatalogAuthenticationEnv, +} from './release-catalog-auth'; + +const ID = RELEASE_CATALOG[0]!.repositoryId; +const ORG = '309286193'; +const START = Date.parse('2026-11-14T06:00:00Z'); +const TOKEN = 'fictional-catalog-token'; +const latest = { id: 123, tag_name: 'v1.0.0', published_at: '2026-11-01T00:00:00Z', draft: false, prerelease: false }; +let pem: string, publicKey: CryptoKey; +beforeAll(async () => { + const keys = await crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, + publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify']); + publicKey = keys.publicKey; + const bytes = new Uint8Array(await crypto.subtle.exportKey('pkcs8', keys.privateKey)); + pem = '-----BEGIN PRIVATE KEY-----\n' + btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join('')) + '\n-----END PRIVATE KEY-----'; +}); + +function fixture() { + const state = { now: START }; + const env: { -readonly [K in keyof ReleaseCatalogAuthenticationEnv]: ReleaseCatalogAuthenticationEnv[K] } = { + GITHUB_RELEASE_AUTH_MODE: 'github_app', GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8: pem, + GITHUB_RELEASE_APP_CONFIGURATION: JSON.stringify({ appId: '10', installationId: '20', version: 'fixture-v1', + validUntil: new Date(START + 3_600_000).toISOString() }), + GITHUB_ORGANIZATION_ID: ORG, + GITHUB_ALLOWED_REPOSITORY_IDS: RELEASE_CATALOG.map(entry => entry.repositoryId).join(','), + }; + const grant = { token: TOKEN, expires_at: new Date(START + 3_600_000).toISOString(), + repository_selection: 'selected', permissions: { metadata: 'read' }, repositories: [{ id: Number(ID), private: false }] }; + const metadata = { id: Number(ID), private: false, visibility: 'public', owner: { id: Number(ORG), login: 'pegma-dev', type: 'Organization' } }; + const transport = vi.fn(async (url) => { + if (String(url).endsWith('/access_tokens')) return Response.json(grant, { status: 201 }); + if (String(url).endsWith('/releases/latest')) return Response.json(latest, { headers: { ETag: 'fictional-etag' } }); + return Response.json(metadata); + }); + const clock = { now: () => new Date(state.now).toISOString() }; + const auth = () => releaseCatalogAuthenticationFor(() => env, { clock, fetch: transport })!; + const resolve = (signal = new AbortController().signal) => auth().resolve({ + purpose: 'public_release_catalog_read', repositoryId: ID, deadline: state.now + 10_000, + }, signal); + const store = createMemoryStore(); + const log = vi.fn(); + const run = () => runReleaseReconciliation({ store, logger: { log }, config: { allowedRepositoryIds: new Set([ID]) }, + scheduledTime: START, now: new Date(START).toISOString(), clock, authentication: auth(), fetchImpl: transport }); + const row = () => store.collection(componentReleaseCollection()).get(componentReleaseKey(ID)); + const seed = () => store.collection(componentReleaseCollection()).update(componentReleaseKey(ID), () => ({ action: 'write', value: { + repositoryId: ID, repositoryName: 'spine', releaseId: '999', tagName: 'v0.9.0', + publishedAt: '2026-10-01T00:00:00Z', observedAt: '2026-11-13T00:00:00Z', + releaseUrl: 'https://github.com/pegma-dev/spine/releases/tag/v0.9.0', + } })); + return { state, env, grant, metadata, transport, clock, auth, resolve, store, log, run, row, seed }; +} + +describe('dedicated catalog App issuer', () => { + it('keeps absent/anonymous mode credential-free, even when engineering credentials exist', () => { + const read = vi.fn(() => { throw new Error('must not read a key'); }); + for (const mode of [undefined, 'anonymous']) { + const env = { GITHUB_RELEASE_AUTH_MODE: mode }; + Object.defineProperty(env, 'GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8', { get: read }); + Object.defineProperty(env, 'SUPPORT_ENGINEERING_APP_JWT', { get: read }); + expect(releaseCatalogAuthenticationFor(() => env)).toBeUndefined(); + } + expect(read).not.toHaveBeenCalled(); + }); + + it('signs RS256 with bounded claims and mints one metadata-only exact-ID token', async () => { + const f = fixture(); const result = await f.resolve(); + expect(result).toMatchObject({ repositoryId: ID, organizationId: ORG, token: TOKEN }); + expect(result!.current()).toBe(true); + expect(f.transport).toHaveBeenCalledTimes(1); + const [url, init] = f.transport.mock.calls[0]!; + expect(url).toBe('https://api.github.com/app/installations/20/access_tokens'); + expect(init).toMatchObject({ method: 'POST', redirect: 'error' }); + expect(JSON.parse(String(init!.body))).toEqual({ repository_ids: [Number(ID)], permissions: { metadata: 'read' } }); + const jwt = new Headers(init!.headers).get('Authorization')!.slice('Bearer '.length); + const parts = jwt.split('.'); + const decode = (value: string) => Uint8Array.from(atob(value.replace(/-/gu, '+').replace(/_/gu, '/')), char => char.charCodeAt(0)); + expect(JSON.parse(new TextDecoder().decode(decode(parts[0]!)))).toEqual({ alg: 'RS256', typ: 'JWT' }); + expect(JSON.parse(new TextDecoder().decode(decode(parts[1]!)))).toEqual({ iss: '10', iat: START / 1000 - 60, exp: START / 1000 + 540 }); + expect(await crypto.subtle.verify('RSASSA-PKCS1-v1_5', publicKey, decode(parts[2]!), + new TextEncoder().encode(parts[0] + '.' + parts[1]))).toBe(true); + f.env.GITHUB_RELEASE_APP_CONFIGURATION = f.env.GITHUB_RELEASE_APP_CONFIGURATION!.replace('fixture-v1', 'fixture-v2'); + expect(result!.current()).toBe(false); + }); + + it.each(['missing-key', 'bad-mode', 'bad-json', 'expired-config', 'outside-allowlist', 'extra-allowlist', 'unknown-config-field'])( + 'refuses %s before minting and never substitutes engineering authentication', async (fault) => { + const f = fixture(); + if (fault === 'missing-key') delete f.env.GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8; + if (fault === 'bad-mode') f.env.GITHUB_RELEASE_AUTH_MODE = 'mistyped'; + if (fault === 'bad-json') f.env.GITHUB_RELEASE_APP_CONFIGURATION = 'not-json'; + if (fault === 'expired-config') f.state.now += 3_600_000; + if (fault === 'outside-allowlist') f.env.GITHUB_ALLOWED_REPOSITORY_IDS = '999'; + if (fault === 'extra-allowlist') f.env.GITHUB_ALLOWED_REPOSITORY_IDS += ',999'; + if (fault === 'unknown-config-field') f.env.GITHUB_RELEASE_APP_CONFIGURATION = JSON.stringify({ + ...JSON.parse(f.env.GITHUB_RELEASE_APP_CONFIGURATION!), token: 'not-a-supported-config-field' }); + await expect(f.resolve()).rejects.toMatchObject({ reason: 'invalid_configuration' }); + expect(f.transport).not.toHaveBeenCalled(); + }, + ); + + it.each(['contents-read', 'issues-write', 'extra-repository', 'wrong-repository', 'private', 'all-repositories', 'expired-token'])( + 'rejects a %s grant instead of accepting broader or stale authority', async (fault) => { + const f = fixture(); const grant: Record = { ...f.grant }; + if (fault === 'contents-read') grant.permissions = { metadata: 'read', contents: 'read' }; + if (fault === 'issues-write') grant.permissions = { metadata: 'read', issues: 'write' }; + if (fault === 'extra-repository') grant.repositories = [...f.grant.repositories, { id: 999, private: false }]; + if (fault === 'wrong-repository') grant.repositories = [{ id: 999, private: false }]; + if (fault === 'private') grant.repositories = [{ id: Number(ID), private: true }]; + if (fault === 'all-repositories') grant.repository_selection = 'all'; + if (fault === 'expired-token') grant.expires_at = new Date(START).toISOString(); + f.transport.mockResolvedValueOnce(Response.json(grant, { status: 201 })); + if (fault === 'expired-token') await expect(f.resolve()).rejects.toThrow('Catalog authentication unavailable'); + else await expect(f.resolve()).rejects.toMatchObject({ reason: 'invalid_grant' }); + expect(f.transport).toHaveBeenCalledTimes(1); + }, + ); + + it('refuses cancellation and an unapproved purpose/repository without a network call', async () => { + const f = fixture(); const controller = new AbortController(); controller.abort(); + expect(await f.resolve(controller.signal)).toBeNull(); + // Deliberately invalid runtime input: exercise the guard beyond TS callers. + expect(await f.auth().resolve({ purpose: 'support_bug_assessment' as 'public_release_catalog_read', repositoryId: ID, + deadline: START + 10_000 }, new AbortController().signal)).toBeNull(); + expect(await f.auth().resolve({ purpose: 'public_release_catalog_read', repositoryId: '999', deadline: START + 10_000 }, new AbortController().signal)).toBeNull(); + expect(f.transport).not.toHaveBeenCalled(); + }); +}); + +describe('authenticated catalog observation', () => { + it.each([200, 304, 404])('requires fresh public metadata after latest HTTP %i before changing catalog state', async (status) => { + const f = fixture(); await f.seed(); + f.transport.mockImplementation(async url => String(url).endsWith('/access_tokens') ? Response.json(f.grant, { status: 201 }) : + String(url).endsWith('/releases/latest') ? (status === 200 ? Response.json(latest) : new Response(null, { status })) : Response.json(f.metadata)); + const result = await f.run(); + expect(result).toEqual({ examined: 1, upserted: status === 200 ? 1 : 0, cleared: status === 404 ? 1 : 0, + notModified: status === 304 ? 1 : 0, failed: 0 }); + expect(f.transport.mock.calls.map(([url]) => String(url))).toEqual([ + 'https://api.github.com/app/installations/20/access_tokens', + `https://api.github.com/repositories/${ID}/releases/latest`, `https://api.github.com/repositories/${ID}`, + ]); + for (const [, init] of f.transport.mock.calls.slice(1)) { + expect(init).toMatchObject({ method: 'GET', redirect: 'error' }); + expect(new Headers(init!.headers).get('Authorization')).toBe('Bearer ' + TOKEN); + } + expect((await readReleaseOpsState(f.store)).lastSuccessfulReconciliationAt).toBe(new Date(START).toISOString()); + if (status === 404) expect(await f.row()).toBeNull(); + else expect((await f.row())!.releaseId).toBe(status === 200 ? '123' : '999'); + expect(JSON.stringify(f.log.mock.calls)).not.toContain(TOKEN); + }); + + it.each(['private', 'cross-org', 'wrong-id', 'wrong-owner-type'])('preserves the prior projection when the current HTTP 200 repository is %s', async (fault) => { + const f = fixture(); await f.seed(); const before = await f.row(); + if (fault === 'private') { f.metadata.private = true; f.metadata.visibility = 'private'; } + if (fault === 'cross-org') f.metadata.owner.id = 999; + if (fault === 'wrong-id') f.metadata.id = 999; + if (fault === 'wrong-owner-type') f.metadata.owner.type = 'User'; + expect((await f.run()).failed).toBe(1); + expect(await f.row()).toEqual(before); + expect((await readReleaseOpsState(f.store)).lastSuccessfulReconciliationAt).toBeNull(); + expect(f.transport).toHaveBeenCalledTimes(3); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [expect.objectContaining({ phase: 'repository', failureClass: 'invalid_repository' })], + })); + }); + + it('uses immutable organization identity when its display login changes', async () => { + const f = fixture(); f.metadata.owner.login = 'renamed-display-login'; + expect((await f.run()).upserted).toBe(1); + expect((await f.row())!.releaseId).toBe('123'); + }); + + it.each([ + ['fetch', 'fetch_rejected', undefined], ['status', 'http_status', 403], + ['JSON', 'invalid_json', 200], ['size', 'too_large', 200], + ] as const)('keeps metadata %s failures separate from the earlier release body', async (fault, failureClass, httpStatus) => { + const f = fixture(); const normal = f.transport.getMockImplementation()!; + f.transport.mockImplementation(async (url, init) => { + if (!String(url).endsWith('/repositories/' + ID)) return normal(url, init); + if (fault === 'fetch') throw new Error('PRIVATE_METADATA_ERROR'); + if (fault === 'status') return new Response('PRIVATE_METADATA_ERROR', { status: 403 }); + if (fault === 'JSON') return new Response('PRIVATE_METADATA_ERROR'); + return new Response('PRIVATE_METADATA_ERROR', { headers: { 'Content-Length': '65537' } }); + }); + expect((await f.run()).failed).toBe(1); + const fields = f.log.mock.calls[0]![2]; + expect(fields.failureDetails[0]).toMatchObject({ phase: 'repository', failureClass }); + expect(fields.failureDetails[0].httpStatus).toBe(httpStatus); + expect(fields.failureDetails[0]).not.toHaveProperty('bodyBytes'); + expect(fields.failureDetails[0]).not.toHaveProperty('bodyBytesSource'); + expect(JSON.stringify(fields)).not.toContain('PRIVATE_METADATA_ERROR'); + }); + + it.each([304, 404])('does not treat HTTP %i as success when public repository access cannot be verified', async status => { + const f = fixture(); await f.seed(); const before = await f.row(); + f.transport.mockImplementation(async url => String(url).endsWith('/access_tokens') ? Response.json(f.grant, { status: 201 }) : + new Response(null, { status: String(url).endsWith('/releases/latest') ? status : 404 })); + expect((await f.run()).failed).toBe(1); expect(await f.row()).toEqual(before); + expect((await readReleaseOpsState(f.store)).lastSuccessfulReconciliationAt).toBeNull(); + }); + + it('keeps missing configured authority unavailable with no anonymous request or retry', async () => { + const f = fixture(); await f.seed(); const before = await f.row(); delete f.env.GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8; + expect((await f.run()).failed).toBe(1); expect(await f.row()).toEqual(before); + expect(f.transport).not.toHaveBeenCalled(); + }); + + it('retains only numeric hints for a 403, never reads its body and never retries', async () => { + const f = fixture(); await f.seed(); const before = await f.row(); + const response = new Response('PRIVATE_UPSTREAM_MESSAGE', { status: 403, + headers: { 'x-ratelimit-remaining': '0', 'retry-after': '60', 'x-unrelated': TOKEN } }); + const read = vi.fn(() => { throw new Error('must not read an error body'); }); + Object.defineProperty(response, 'body', { get: read }); + f.transport.mockImplementation(async url => String(url).endsWith('/access_tokens') ? Response.json(f.grant, { status: 201 }) : response); + expect((await f.run()).failed).toBe(1); expect(await f.row()).toEqual(before); + expect(f.transport).toHaveBeenCalledTimes(2); expect(read).not.toHaveBeenCalled(); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [{ repositoryId: ID, phase: 'status', failureClass: 'http_status', httpStatus: 403, + rateLimitRemaining: 0, retryAfterSeconds: 60 }], + })); + expect(JSON.stringify(f.log.mock.calls)).not.toMatch(/PRIVATE_UPSTREAM_MESSAGE|fictional-catalog-token|x-unrelated/u); + }); + + it.each(['expiry', 'configuration'])('refuses %s changes across an awaited repository read', async fault => { + const f = fixture(); await f.seed(); const before = await f.row(); + const normal = f.transport.getMockImplementation()!; + f.transport.mockImplementation(async (url, init) => { + const response = await normal(url, init); + if (String(url).endsWith('/repositories/' + ID)) { + if (fault === 'expiry') f.state.now += 10_001; + else f.env.GITHUB_RELEASE_AUTH_MODE = 'anonymous'; + } + return response; + }); + expect((await f.run()).failed).toBe(1); expect(await f.row()).toEqual(before); + expect((await readReleaseOpsState(f.store)).lastSuccessfulReconciliationAt).toBeNull(); + expect(f.transport).toHaveBeenCalledTimes(3); + }); + + it('applies one ten-second deadline even to an issuer that does not settle', async () => { + vi.useFakeTimers(); + try { + const f = fixture(); const resolve = vi.fn(() => new Promise(() => {})); + const run = runReleaseReconciliation({ store: f.store, logger: { log: f.log }, + config: { allowedRepositoryIds: new Set([ID]) }, scheduledTime: START, + authentication: { resolve }, clock: f.clock, fetchImpl: f.transport }); + await vi.advanceTimersByTimeAsync(10_000); + expect((await run).failed).toBe(1); expect(resolve).toHaveBeenCalledTimes(1); + expect(resolve.mock.calls[0]![1].aborted).toBe(true); + expect(f.transport).not.toHaveBeenCalled(); + expect((await readReleaseOpsState(f.store)).lastSuccessfulReconciliationAt).toBeNull(); + } finally { vi.useRealTimers(); } + }); +}); + +describe('finite response hints', () => { + it.each(['-1', '0.5', 'infinite', '999999999999999999999', 'Wed, 14 Nov 2026 06:01:00 GMT'])( + 'retains no raw value for %s', value => { + expect(releaseRateHints(new Response(null, { headers: { 'x-ratelimit-remaining': value, 'retry-after': value } }))) + .toEqual({ rateLimitRemaining: null, retryAfterSeconds: null }); + }, + ); +}); diff --git a/worker/src/release-catalog-auth.ts b/worker/src/release-catalog-auth.ts new file mode 100644 index 0000000..3d6be89 --- /dev/null +++ b/worker/src/release-catalog-auth.ts @@ -0,0 +1,216 @@ +import { systemClock, type Clock } from '@pegma/spine'; +import { RELEASE_CATALOG } from './release-catalog'; + +/** Catalog-only configuration. Never uses the engineering App credentials. */ +export interface ReleaseCatalogAuthenticationEnv { + readonly GITHUB_RELEASE_AUTH_MODE?: string; + readonly GITHUB_RELEASE_APP_CONFIGURATION?: string; + readonly GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8?: string; + readonly GITHUB_ALLOWED_REPOSITORY_IDS?: string; + readonly GITHUB_ORGANIZATION_ID?: string; +} + +export interface ReleaseCatalogCredential { + readonly repositoryId: string; + readonly organizationId: string; + readonly token: string; + readonly expiresAt: number; + /** Synchronous current configuration, clock and cancellation fence. */ + current(): boolean; +} + +export interface ReleaseCatalogAuthentication { + resolve(input: { + readonly purpose: 'public_release_catalog_read'; + readonly repositoryId: string; + readonly deadline: number; + }, signal: AbortSignal): Promise; +} + +export function releaseRateHints(response: Response) { + function integer(name: string, maximum: number): number | null { + const value = response.headers.get(name); + if (value === null || !/^\d{1,10}$/u.test(value)) return null; + const parsed = Number(value); + return Number.isSafeInteger(parsed) && parsed <= maximum ? parsed : null; + } + return { + rateLimitRemaining: integer('x-ratelimit-remaining', 2_147_483_647), + retryAfterSeconds: integer('retry-after', 86_400), + }; +} + +/** Only finite public response facts may cross the issuer boundary. */ +export class ReleaseCatalogAuthenticationUnavailable extends Error { + constructor(readonly response?: { + readonly httpStatus: number; + readonly rateLimitRemaining: number | null; + readonly retryAfterSeconds: number | null; + }, readonly reason: 'invalid_configuration' | 'issuer_unavailable' | 'invalid_grant' | 'authority_unavailable' = 'authority_unavailable') { + super('Catalog authentication unavailable'); + } +} + +export class CatalogResponseError extends Error { + constructor(readonly reason: 'too_large' | 'invalid_json') { super('Catalog response unavailable'); } +} + +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function numericId(value: unknown): value is string { + return typeof value === 'string' && /^[1-9]\d{0,15}$/u.test(value) && + Number.isSafeInteger(Number(value)); +} +function timestamp(value: unknown): number { + return typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/u.test(value) + ? Date.parse(value) : NaN; +} +function base64url(bytes: Uint8Array): string { + return btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join('')) + .replace(/=/gu, '').replace(/\+/gu, '-').replace(/\//gu, '_'); +} + +/** Bounded streaming JSON for credential and public repository responses. */ +export async function readCatalogAuthenticationJson(response: Response, signal: AbortSignal): Promise { + const limit = 65_536; + const declared = response.headers.get('content-length'); + if (declared !== null && /^\d+$/u.test(declared) && Number(declared) > limit) + throw new CatalogResponseError('too_large'); + const reader = response.body?.getReader(); + if (!reader) throw new CatalogResponseError('invalid_json'); + const chunks: Uint8Array[] = []; + let total = 0, reads = 0; + const cancel = () => { void reader.cancel().catch(() => {}); }; + signal.addEventListener('abort', cancel, { once: true }); + try { + for (;;) { + if (signal.aborted) throw new ReleaseCatalogAuthenticationUnavailable(); + if (++reads > limit + 64) throw new CatalogResponseError('too_large'); + const next = await reader.read(); + if (signal.aborted) throw new ReleaseCatalogAuthenticationUnavailable(); + if (next.done) break; + total += next.value.byteLength; + if (total > limit) throw new CatalogResponseError('too_large'); + chunks.push(next.value); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + try { return JSON.parse(new TextDecoder().decode(bytes)); } + catch { throw new CatalogResponseError('invalid_json'); } + } finally { + signal.removeEventListener('abort', cancel); + cancel(); + } +} + +/** + * Optional dedicated issuer; absent/anonymous mode performs no credential read. + * Invalid or incomplete configured App mode is unavailable, never anonymous. + * No private key, JWT, token or unprojected response escapes to logs/storage. + */ +export function releaseCatalogAuthenticationFor( + environment: () => ReleaseCatalogAuthenticationEnv, + options: { readonly clock?: Clock; readonly fetch?: typeof fetch } = {}, +): ReleaseCatalogAuthentication | undefined { + const mode = environment().GITHUB_RELEASE_AUTH_MODE; + if (mode === undefined || mode === 'anonymous') return undefined; + const clock = options.clock ?? systemClock; + const transport = options.fetch ?? fetch; + return { + async resolve(input, signal) { + const env = environment(); + if (signal.aborted || input.purpose !== 'public_release_catalog_read' || + !RELEASE_CATALOG.some(entry => entry.repositoryId === input.repositoryId)) return null; + if (env.GITHUB_RELEASE_AUTH_MODE !== 'github_app') + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + const raw = env.GITHUB_RELEASE_APP_CONFIGURATION; + const pem = env.GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8; + const allowed = env.GITHUB_ALLOWED_REPOSITORY_IDS; + const organizationId = env.GITHUB_ORGANIZATION_ID; + if (typeof raw !== 'string' || raw.length > 2_048 || typeof pem !== 'string' || + pem.length > 16_384 || typeof allowed !== 'string' || !numericId(organizationId)) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + let config: unknown; + try { config = JSON.parse(raw); } + catch { throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); } + const ids = allowed.split(',').map(value => value.trim()); + if (!record(config) || Object.keys(config).sort().join(',') !== 'appId,installationId,validUntil,version' || + !numericId(config.appId) || !numericId(config.installationId) || + typeof config.version !== 'string' || !/^[A-Za-z0-9._-]{1,100}$/u.test(config.version) || + ids.length !== RELEASE_CATALOG.length || new Set(ids).size !== ids.length || + !RELEASE_CATALOG.every(entry => ids.includes(entry.repositoryId))) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + const validUntil = timestamp(config.validUntil); + const started = new Date(clock.now()).getTime(); + if (!Number.isFinite(started) || !Number.isFinite(validUntil) || + !Number.isFinite(input.deadline) || validUntil <= started || input.deadline <= started) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + let expiresAt = Math.min(validUntil, input.deadline); + function current() { + const now = new Date(clock.now()).getTime(), latest = environment(); + return !signal.aborted && Number.isFinite(now) && now >= started && now < expiresAt && + latest.GITHUB_RELEASE_AUTH_MODE === 'github_app' && + latest.GITHUB_RELEASE_APP_CONFIGURATION === raw && + latest.GITHUB_ALLOWED_REPOSITORY_IDS === allowed && + latest.GITHUB_ORGANIZATION_ID === organizationId && + latest.GITHUB_RELEASE_APP_PRIVATE_KEY_PKCS8 === pem; + } + function assertCurrent() { if (!current()) throw new ReleaseCatalogAuthenticationUnavailable(); } + const match = /^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----\s*$/u.exec(pem); + if (!match) throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + let key: CryptoKey; + try { + key = await crypto.subtle.importKey('pkcs8', + Uint8Array.from(atob(match[1]!.replace(/\s/gu, '')), char => char.charCodeAt(0)), + { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign']); + } catch { throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); } + assertCurrent(); + if (!('modulusLength' in key.algorithm) || typeof key.algorithm.modulusLength !== 'number' || + key.algorithm.modulusLength < 2_048 || key.algorithm.modulusLength > 4_096) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_configuration'); + const seconds = Math.floor(new Date(clock.now()).getTime() / 1_000); + const jwtExpiry = (seconds + 540) * 1_000; + expiresAt = Math.min(expiresAt, jwtExpiry); + const encode = (value: unknown) => base64url(new TextEncoder().encode(JSON.stringify(value))); + const unsigned = encode({ alg: 'RS256', typ: 'JWT' }) + '.' + + encode({ iat: seconds - 60, exp: seconds + 540, iss: config.appId }); + const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', key, new TextEncoder().encode(unsigned)); + assertCurrent(); + const jwt = unsigned + '.' + base64url(new Uint8Array(signature)); + const url = 'https://api.github.com/app/installations/' + config.installationId + '/access_tokens'; + const response = await transport(url, { + method: 'POST', redirect: 'error', signal, + headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'pegma-dev-release-catalog', + 'X-GitHub-Api-Version': '2022-11-28', Authorization: 'Bearer ' + jwt, + 'Content-Type': 'application/json' }, + body: JSON.stringify({ repository_ids: [Number(input.repositoryId)], permissions: { metadata: 'read' } }), + }); + assertCurrent(); + if (response.status !== 201) throw new ReleaseCatalogAuthenticationUnavailable({ + httpStatus: response.status, ...releaseRateHints(response), + }, 'issuer_unavailable'); + if (response.redirected || (response.url !== '' && response.url !== url)) + throw new ReleaseCatalogAuthenticationUnavailable(); + let grant: unknown; + try { grant = await readCatalogAuthenticationJson(response, signal); } + catch (error) { + if (error instanceof ReleaseCatalogAuthenticationUnavailable) throw error; + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_grant'); + } + assertCurrent(); + if (!record(grant) || typeof grant.token !== 'string' || !/^[\x21-\x7E]{1,2048}$/u.test(grant.token) || + grant.repository_selection !== 'selected' || !record(grant.permissions) || + grant.permissions.metadata !== 'read' || Object.keys(grant.permissions).length !== 1 || + !Array.isArray(grant.repositories) || grant.repositories.length !== 1) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_grant'); + const repository: unknown = grant.repositories[0]; + if (!record(repository) || String(repository.id) !== input.repositoryId || repository.private !== false) + throw new ReleaseCatalogAuthenticationUnavailable(undefined, 'invalid_grant'); + expiresAt = Math.min(expiresAt, timestamp(grant.expires_at)); + assertCurrent(); + return { repositoryId: input.repositoryId, organizationId, token: grant.token, expiresAt, current }; + }, + }; +} diff --git a/worker/src/release-catalog-fences.test.ts b/worker/src/release-catalog-fences.test.ts new file mode 100644 index 0000000..da5b54d --- /dev/null +++ b/worker/src/release-catalog-fences.test.ts @@ -0,0 +1,137 @@ +import { createMemoryStore, type Store, type CollectionDefinition, type CollectionStore } from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import { componentReleaseCollection, componentReleaseKey } from './component-release'; +import { readReleaseOpsState } from './release-ops-state'; +import { runReleaseReconciliation } from './release-reconciliation'; + +const ID = '1312512520', ORG = '309286193'; +const START = Date.parse('2026-11-14T06:00:00Z'); +const latest = { id: 123, tag_name: 'v1.0.0', published_at: '2026-11-01T00:00:00Z', draft: false, prerelease: false }; +function latch() { + let release!: () => void, entered!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const wait = new Promise(resolve => { release = resolve; }); + return { release, ready, async pause() { entered(); await wait; } }; +} + +async function fixture(status: 200 | 304 | 404) { + const base = createMemoryStore(); + await base.collection(componentReleaseCollection()).update(componentReleaseKey(ID), () => ({ action: 'write', value: { + repositoryId: ID, repositoryName: 'spine', releaseId: '99', tagName: 'v0.9.0', + publishedAt: '2026-10-01T00:00:00Z', observedAt: '2026-11-13T00:00:00Z', + releaseUrl: 'https://github.com/pegma-dev/spine/releases/tag/v0.9.0', + } })); + const state = { now: START, enabled: true, submissions: 0 }; + const hooks: { read?: (key: string) => Promise; acknowledgement?: () => Promise; reject?: boolean } = {}; + const store: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const actual = base.collection(definition); + if (definition.name !== 'componentReleases') return actual; + return { ...actual, + async getVersioned(key) { const result = await actual.getVersioned(key); await hooks.read?.(key.id); return result; }, + async transact(partition, actions) { + state.submissions++; + const outcome = hooks.reject ? { committed: false as const, reason: 'changed' as const } : await actual.transact(partition, actions); + await hooks.acknowledgement?.(); + return outcome; + }, + }; + }, + }; + const log = vi.fn(); + const transport = vi.fn(async url => String(url).endsWith('/releases/latest') ? + (status === 200 ? Response.json(latest) : new Response(null, { status })) : + Response.json({ id: Number(ID), private: false, visibility: 'public', owner: { id: Number(ORG), type: 'Organization' } })); + const run = () => runReleaseReconciliation({ store, logger: { log }, config: { allowedRepositoryIds: new Set([ID]) }, + scheduledTime: START, now: new Date(START).toISOString(), clock: { now: () => new Date(state.now).toISOString() }, fetchImpl: transport, + authentication: { async resolve() { return { repositoryId: ID, organizationId: ORG, token: 'fictional-token', + expiresAt: START + 10_000, current: () => state.enabled }; } }, + }); + const row = () => base.collection(componentReleaseCollection()).get(componentReleaseKey(ID)); + return { base, state, hooks, log, transport, run, row }; +} + +describe('catalog authority at actual transaction submission', () => { + for (const status of [200, 304, 404] as const) { + for (const read of ['epoch', 'projection'] as const) { + it.each(['timeout', 'expiry', 'configuration'] as const)(`HTTP ${status} never writes after %s during the ${read} read`, async fault => { + vi.useFakeTimers(); + try { + const f = await fixture(status); const before = await f.row(); const paused = latch(); + f.hooks.read = key => (read === 'epoch' ? key.startsWith('followup-epoch:') : key === ID) ? paused.pause() : Promise.resolve(); + const running = f.run(); await paused.ready; + if (fault === 'timeout') await vi.advanceTimersByTimeAsync(10_000); + if (fault === 'expiry') f.state.now += 10_001; + if (fault === 'configuration') f.state.enabled = false; + paused.release(); + expect((await running).failed).toBe(1); + await vi.advanceTimersByTimeAsync(0); + expect(f.state.submissions).toBe(0); + expect(await f.row()).toEqual(before); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [expect.objectContaining({ phase: 'projection' })], + })); + } finally { vi.useRealTimers(); } + }); + } + + it(`HTTP ${status} awaits a submitted transaction's real late acknowledgement`, async () => { + vi.useFakeTimers(); + try { + const f = await fixture(status); const paused = latch(); f.hooks.acknowledgement = paused.pause; + let settled = false; + const running = f.run().then(value => { settled = true; return value; }); + await paused.ready; expect(f.state.submissions).toBe(1); + await vi.advanceTimersByTimeAsync(10_000); + expect(settled).toBe(false); + paused.release(); const result = await running; + expect(result).toEqual({ examined: 1, upserted: status === 200 ? 1 : 0, cleared: status === 404 ? 1 : 0, + notModified: status === 304 ? 1 : 0, failed: 0 }); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBe(new Date(START).toISOString()); + if (status === 404) expect(await f.row()).toBeNull(); + else expect((await f.row())!.releaseId).toBe(status === 200 ? '123' : '99'); + } finally { vi.useRealTimers(); } + }); + } + + it('does not retry a rejected transaction when its acknowledgement arrives after expiry', async () => { + vi.useFakeTimers(); + try { + const f = await fixture(200), before = await f.row(), paused = latch(); + f.hooks.reject = true; f.hooks.acknowledgement = paused.pause; + const running = f.run(); await paused.ready; await vi.advanceTimersByTimeAsync(10_000); + paused.release(); expect((await running).failed).toBe(1); + expect(f.state.submissions).toBe(1); expect(await f.row()).toEqual(before); + expect((await readReleaseOpsState(f.base)).lastSuccessfulReconciliationAt).toBeNull(); + } finally { vi.useRealTimers(); } + }); + + it.each(['fetch', 'body', 'repository'] as const)('preserves the actual %s phase when the common deadline expires', async phase => { + vi.useFakeTimers(); + try { + const f = await fixture(200), paused = latch(); + let body: ReadableStreamDefaultController | undefined; + f.transport.mockImplementation(async url => { + if ((phase === 'fetch' && String(url).endsWith('/releases/latest')) || + (phase === 'repository' && String(url).endsWith('/repositories/' + ID))) { + await paused.pause(); + } + if (String(url).endsWith('/releases/latest')) { + if (phase === 'body') return new Response(new ReadableStream({ start(controller) { body = controller; } })); + return Response.json(latest); + } + return Response.json({ id: Number(ID), private: false, visibility: 'public', owner: { id: Number(ORG), type: 'Organization' } }); + }); + const running = f.run(); + if (phase !== 'body') await paused.ready; + await vi.advanceTimersByTimeAsync(10_000); + expect((await running).failed).toBe(1); + expect(f.log).toHaveBeenCalledWith('error', 'release_reconciliation.partial_failure', expect.objectContaining({ + failureDetails: [expect.objectContaining({ phase })], + })); + paused.release(); body?.close(); await vi.advanceTimersByTimeAsync(0); + expect(f.state.submissions).toBe(0); + } finally { vi.useRealTimers(); } + }); +}); diff --git a/worker/src/release-projection.ts b/worker/src/release-projection.ts index bef6f08..1ca6135 100644 --- a/worker/src/release-projection.ts +++ b/worker/src/release-projection.ts @@ -1,6 +1,6 @@ import type { Store } from '@pegma/storage-core'; import type { ComponentRelease } from './component-release'; -import { updateSupportFollowupRelease } from './support-release-followup-releases'; +import { updateSupportFollowupRelease, type ReleaseProjectionFence } from './support-release-followup-releases'; const GITHUB_ORG_PREFIX = 'https://github.com/pegma-dev/'; const SAFE_REPO_NAME = /^[A-Za-z0-9_.-]+$/; @@ -148,6 +148,7 @@ export async function applyReleaseProjection( export async function applyAuthoritativeCurrentRelease( store: Store, release: ComponentRelease, + fence?: ReleaseProjectionFence, ): Promise<'written' | 'unchanged'> { const result = await updateSupportFollowupRelease( store, @@ -161,6 +162,7 @@ export async function applyAuthoritativeCurrentRelease( ) ? undefined : release, + fence, ); return result.changed ? 'written' : 'unchanged'; } @@ -170,12 +172,13 @@ export async function touchCurrentReleaseObservedAt( store: Store, repositoryId: string, observedAt: string, + fence?: ReleaseProjectionFence, ): Promise { return ( await updateSupportFollowupRelease(store, repositoryId, (current) => current === null || current.observedAt === observedAt ? undefined - : { ...current, observedAt }, + : { ...current, observedAt }, fence, ) ).changed; } @@ -185,10 +188,11 @@ export async function touchCurrentReleaseObservedAt( export async function clearCurrentRelease( store: Store, repositoryId: string, + fence?: ReleaseProjectionFence, ): Promise { return ( await updateSupportFollowupRelease(store, repositoryId, (current) => - current === null ? undefined : null, + current === null ? undefined : null, fence, ) ).changed; } diff --git a/worker/src/release-reconciliation-diagnostics.test.ts b/worker/src/release-reconciliation-diagnostics.test.ts index b0eeb90..c5a2530 100644 --- a/worker/src/release-reconciliation-diagnostics.test.ts +++ b/worker/src/release-reconciliation-diagnostics.test.ts @@ -128,7 +128,8 @@ describe('bounded release reconciliation diagnostics', () => { const expected = { level: 'error', message: 'release_reconciliation.partial_failure', fields: { examined: 1, upserted: 0, cleared: 0, notModified: 0, failed: 1, - failureDetails: [{ repositoryId: ID, phase: 'status', failureClass: 'http_status', httpStatus: 403 }], + failureDetails: [{ repositoryId: ID, phase: 'status', failureClass: 'http_status', httpStatus: 403, + rateLimitRemaining: null, retryAfterSeconds: null }], failureDetailsOmitted: 0, }, }; diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index a91df79..aa662f2 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -1,5 +1,13 @@ import type { Store } from '@pegma/storage-core'; -import type { Logger } from '@pegma/spine'; +import { systemClock, type Clock, type Logger } from '@pegma/spine'; +import { + ReleaseCatalogAuthenticationUnavailable, + CatalogResponseError, + readCatalogAuthenticationJson, + releaseRateHints, + type ReleaseCatalogAuthentication, + type ReleaseCatalogCredential, +} from './release-catalog-auth'; import { componentReleaseStateCollection } from './component-release'; import { allowedReleaseCatalog, @@ -18,6 +26,7 @@ import { type ReleaseEventFacts, } from './release-projection'; import type { ComponentRelease } from './component-release'; +import type { ReleaseProjectionFence } from './support-release-followup-releases'; /** One repository per minute during each six-hour reconciliation window. */ export const RELEASE_RECONCILIATION_CRON = '0-59 */6 * * *'; @@ -35,7 +44,7 @@ const MAX_FAILURE_DETAILS = 4; * declared oversized length from actual bytes consumed from the stream. */ interface ReleaseFailureDetail { readonly repositoryId: string; - phase: 'fetch' | 'status' | 'body' | 'facts' | 'url' | 'projection'; + phase: 'authentication' | 'repository' | 'fetch' | 'status' | 'body' | 'facts' | 'url' | 'projection'; failureClass: | 'operation_rejected' | 'fetch_rejected' @@ -43,7 +52,11 @@ interface ReleaseFailureDetail { | 'too_large' | 'invalid_json' | 'invalid_release' + | 'invalid_repository' | 'unsafe_release_url'; + rateLimitRemaining?: number | null; + retryAfterSeconds?: number | null; + authenticationFailure?: 'invalid_configuration' | 'issuer_unavailable' | 'invalid_grant' | 'authority_unavailable'; httpStatus?: number; bodyBytes?: number; bodyBytesSource?: 'declared' | 'streamed'; @@ -68,6 +81,8 @@ export interface RunReleaseReconciliationOptions { readonly config: ReleaseReconciliationConfig; readonly now?: string; readonly fetchImpl?: typeof fetch; + readonly authentication?: ReleaseCatalogAuthentication; + readonly clock?: Clock; /** Cron timestamp selects one catalog slot; omit for explicit full backfill. */ readonly scheduledTime?: number; } @@ -189,19 +204,29 @@ async function readBoundedJson( } } -async function reconcileOneRepository(options: { +interface ReconcileOneOptions { readonly store: Store; readonly entry: ReleaseCatalogEntry; readonly etag: string | undefined; readonly observedAt: string; readonly fetchImpl: typeof fetch; readonly failure: ReleaseFailureDetail; + readonly authentication?: ReleaseCatalogAuthentication; + readonly clock: Clock; +} + +async function reconcileOneRepositoryRequest(options: ReconcileOneOptions & { + readonly signal: AbortSignal; + readonly credential?: ReleaseCatalogCredential; + readonly assertCurrent: () => void; + readonly fence?: ReleaseProjectionFence; }): Promise<{ readonly outcome: 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; readonly etag: string | undefined; }> { const { store, entry, observedAt, fetchImpl, failure } = options; + const { credential, signal, assertCurrent } = options; // Fetch by stable numeric repository ID so a rename/recreate cannot attach // another repo's release under this catalog slot. const url = `${GITHUB_API}/repositories/${entry.repositoryId}/releases/latest`; @@ -213,32 +238,92 @@ async function reconcileOneRepository(options: { if (options.etag !== undefined) { headers['If-None-Match'] = options.etag; } + if (credential) headers.Authorization = 'Bearer ' + credential.token; + async function verifyPublicRepository() { + if (!credential) return; + failure.phase = 'repository'; + failure.failureClass = 'operation_rejected'; + delete failure.httpStatus; + delete failure.bodyBytes; + delete failure.bodyBytesSource; + delete failure.rateLimitRemaining; + delete failure.retryAfterSeconds; + const metadataUrl = `${GITHUB_API}/repositories/${entry.repositoryId}`; + assertCurrent(); + let metadata: Response; + try { + metadata = await fetchImpl(metadataUrl, { + method: 'GET', redirect: 'error', signal, + headers: { Accept: headers.Accept!, 'User-Agent': USER_AGENT, + 'X-GitHub-Api-Version': headers['X-GitHub-Api-Version']!, Authorization: headers.Authorization! }, + }); + } catch { + failure.failureClass = 'fetch_rejected'; + throw new ReleaseCatalogAuthenticationUnavailable(); + } + assertCurrent(); + failure.httpStatus = metadata.status; + if (metadata.status !== 200) { + failure.failureClass = 'http_status'; + if (metadata.status === 403 || metadata.status === 429) Object.assign(failure, releaseRateHints(metadata)); + throw new ReleaseCatalogAuthenticationUnavailable(); + } + if (metadata.redirected || (metadata.url !== '' && metadata.url !== metadataUrl)) { + failure.failureClass = 'invalid_repository'; + throw new ReleaseCatalogAuthenticationUnavailable(); + } + let payload: unknown; + try { payload = await readCatalogAuthenticationJson(metadata, signal); } + catch (error) { + if (error instanceof CatalogResponseError) failure.failureClass = error.reason; + throw new ReleaseCatalogAuthenticationUnavailable(); + } + const value = asRecord(payload); + assertCurrent(); + const owner = asRecord(value?.owner); + if (value === null || asId(value.id) !== entry.repositoryId || value.private !== false || + value.visibility !== 'public' || owner?.type !== 'Organization' || + asId(owner.id) !== credential.organizationId) { + failure.failureClass = 'invalid_repository'; + throw new ReleaseCatalogAuthenticationUnavailable(); + } + } let response: Response; try { + assertCurrent(); response = await fetchImpl(url, { method: 'GET', headers, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + signal, + ...(credential ? { redirect: 'error' as const } : {}), }); - } catch { + assertCurrent(); + } catch (error) { + if (error instanceof ReleaseCatalogAuthenticationUnavailable) throw error; failure.failureClass = 'fetch_rejected'; return { outcome: 'failed', etag: options.etag }; } + if (credential && (response.redirected || (response.url !== '' && response.url !== url))) + throw new ReleaseCatalogAuthenticationUnavailable(); failure.phase = 'status'; failure.httpStatus = response.status; if (response.status === 304) { + await verifyPublicRepository(); + assertCurrent(); failure.phase = 'projection'; - await touchCurrentReleaseObservedAt(store, entry.repositoryId, observedAt); + await touchCurrentReleaseObservedAt(store, entry.repositoryId, observedAt, options.fence); return { outcome: 'not_modified', etag: options.etag }; } const nextEtag = response.headers.get('etag') ?? undefined; if (response.status === 404) { + await verifyPublicRepository(); + assertCurrent(); failure.phase = 'projection'; - const cleared = await clearCurrentRelease(store, entry.repositoryId); + const cleared = await clearCurrentRelease(store, entry.repositoryId, options.fence); return { outcome: cleared ? 'cleared' : 'unchanged', etag: undefined, @@ -246,12 +331,15 @@ async function reconcileOneRepository(options: { } if (response.status < 200 || response.status >= 300) { + if (response.status === 403 || response.status === 429) + Object.assign(failure, releaseRateHints(response)); failure.failureClass = 'http_status'; return { outcome: 'failed', etag: options.etag }; } failure.phase = 'body'; const parsed = await readBoundedJson(response, failure); + assertCurrent(); if (!parsed.ok) { failure.failureClass = parsed.reason; return { outcome: 'failed', etag: options.etag }; @@ -277,6 +365,8 @@ async function reconcileOneRepository(options: { failure.failureClass = 'unsafe_release_url'; return { outcome: 'failed', etag: options.etag }; } + await verifyPublicRepository(); + assertCurrent(); const release: ComponentRelease = { repositoryId: facts.repositoryId, @@ -290,13 +380,64 @@ async function reconcileOneRepository(options: { // Authoritative path: GitHub's current stable wins even when older than a // local row left behind by a missed delete/unpublish webhook. failure.phase = 'projection'; - const wrote = await applyAuthoritativeCurrentRelease(store, release); + const wrote = await applyAuthoritativeCurrentRelease(store, release, options.fence); return { outcome: wrote === 'written' ? 'upserted' : 'unchanged', etag: nextEtag, }; } +async function reconcileOneRepository(options: ReconcileOneOptions) { + if (!options.authentication) return reconcileOneRepositoryRequest({ + ...options, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), assertCurrent: () => {}, + }); + const controller = new AbortController(); + const started = new Date(options.clock.now()).getTime(); + const deadline = started + REQUEST_TIMEOUT_MS; + let credential: ReleaseCatalogCredential | null = null; + let submitting = false; + const unavailable = () => ({ outcome: 'failed' as const, etag: options.etag }); + const aborted = new Promise((_resolve, reject) => { + controller.signal.addEventListener('abort', () => { + if (!submitting) reject(new ReleaseCatalogAuthenticationUnavailable()); + }, { once: true }); + }); + const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + const assertCurrent = () => { + const now = new Date(options.clock.now()).getTime(); + if (!credential || controller.signal.aborted || !Number.isFinite(started) || !Number.isFinite(deadline) || !Number.isFinite(now) || now < started || + now >= deadline || now >= credential.expiresAt || !credential.current()) + throw new ReleaseCatalogAuthenticationUnavailable(); + }; + async function run() { + options.failure.phase = 'authentication'; + credential = await options.authentication!.resolve({ + purpose: 'public_release_catalog_read', repositoryId: options.entry.repositoryId, deadline, + }, controller.signal); + if (!credential || credential.repositoryId !== options.entry.repositoryId || + !/^[\x21-\x7E]{1,2048}$/u.test(credential.token) || !Number.isFinite(credential.expiresAt)) + throw new ReleaseCatalogAuthenticationUnavailable(); + assertCurrent(); + options.failure.phase = 'fetch'; + return reconcileOneRepositoryRequest({ ...options, credential, signal: controller.signal, assertCurrent, + fence: { current: assertCurrent, submitted: () => { assertCurrent(); submitting = true; }, settled: () => { submitting = false; } }, + }); + } + try { + return await Promise.race([run(), aborted]); + } catch (error) { + // No raw issuer/provider error, credential or response body is logged. + if (options.failure.phase === 'authentication') options.failure.authenticationFailure = + error instanceof ReleaseCatalogAuthenticationUnavailable ? error.reason : 'issuer_unavailable'; + if (error instanceof ReleaseCatalogAuthenticationUnavailable && error.response) + Object.assign(options.failure, error.response); + return unavailable(); + } finally { + clearTimeout(timer); + controller.abort(); + } +} + /** * Authoritative sync of current stable releases from GitHub's public API. * Also serves as initial backfill when the catalog is empty. @@ -359,6 +500,8 @@ export async function runReleaseReconciliation( observedAt, fetchImpl, failure, + authentication: options.authentication, + clock: options.clock ?? systemClock, }); } catch { // Version conflicts and unexpected store errors stay per-repository so diff --git a/worker/src/support-release-followup-releases.ts b/worker/src/support-release-followup-releases.ts index d9ce3c6..c5b4821 100644 --- a/worker/src/support-release-followup-releases.ts +++ b/worker/src/support-release-followup-releases.ts @@ -14,6 +14,14 @@ export { type FollowupReleaseObservation, } from './component-release'; +/** Optional host authority fence. Once submitted, Store transactions cannot be + * canceled; the caller must await their actual outcome rather than abandon them. */ +export interface ReleaseProjectionFence { + current(): void; + submitted(): void; + settled(): void; +} + /** Refresh timestamps are not release changes. Deletion/republication advances * the durable epoch even if the release later has identical display facts. */ export function supportFollowupReleaseFingerprint(value: ComponentRelease) { @@ -36,6 +44,7 @@ export async function updateSupportFollowupRelease( decide: ( current: ComponentRelease | null, ) => ComponentRelease | null | undefined, + fence?: ReleaseProjectionFence, ): Promise<{ release: ComponentRelease | null; changed: boolean; @@ -45,7 +54,9 @@ export async function updateSupportFollowupRelease( const key = componentReleaseKey(repositoryId); const epochKey = supportFollowupReleaseObservationKey(repositoryId); for (let attempt = 0; attempt < 3; attempt++) { + fence?.current(); const prior = await records.getVersioned(epochKey); + fence?.current(); if ( prior !== null && (prior.value.kind !== 'observation' || @@ -53,6 +64,7 @@ export async function updateSupportFollowupRelease( ) throw new TypeError('Invalid release observation identity'); const stored = await records.getVersioned(key); + fence?.current(); if ( stored !== null && (stored.value.kind !== 'release' || @@ -72,6 +84,7 @@ export async function updateSupportFollowupRelease( const fingerprint = basis ? await supportFollowupReleaseFingerprint(basis) : previous!.fingerprint; + fence?.current(); const state = release ? ('active' as const) : ('withdrawn' as const); const same = previous?.state === state && previous.fingerprint === fingerprint; @@ -104,8 +117,17 @@ export async function updateSupportFollowupRelease( actions.push({ action: 'put', value: { kind: 'release', release } }); else if (stored !== null) actions.push({ action: 'delete', key }); } - if ((await records.transact(key.partition, actions)).committed) + fence?.current(); + fence?.submitted(); + let committed: boolean; + try { + committed = (await records.transact(key.partition, actions)).committed; + } finally { + fence?.settled(); + } + if (committed) return { release, changed, observation }; + fence?.current(); } throw new TypeError('Release observation changed'); }