diff --git a/.changeset/ithaca-settings-repository-identity.md b/.changeset/ithaca-settings-repository-identity.md new file mode 100644 index 0000000000..d9c613c437 --- /dev/null +++ b/.changeset/ithaca-settings-repository-identity.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Add owner-only GitHub repository metadata lookup for Settings with live grant, credential-recipient and operation-authority checks. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index c6b3651b74..00a656460c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -189,7 +189,7 @@ reclamation is observed. ## Fixed GitHub wire and identity authority (#3613) The concrete access owner (`createGitHubReferenceAccess`, -`packages/ui-server/src/brain/github-reference-access.ts:19-151`) uses the +`packages/ui-server/src/brain/github-reference-access.ts:19-189`) uses the fixed transport (`createGitHubReferenceWire`, `packages/ui-server/src/brain/github-reference-wire.ts:19-254`). @@ -205,6 +205,19 @@ Owner identity uses its own anonymous `/users/` operation, without a Git channel or credentialed mode. Parsed identity data carries no trust or approved-owner-boundary claim. +Settings repository lookup shares that metadata authority without selecting a +Git revision or fabricating an agent turn. Its separate owner-only operation +returns fresh repository/owner IDs through the same fixed anonymous-first path, +including the requesting owner's own grant for private metadata. Neither that +result nor anonymous owner lookup approves a trust boundary. The Settings +publisher must retain its independent human authority and bind a fresh identity +observation to reviewed publication; changing names or IDs cannot inherit an +old review. Cancellation and operation authority are retained before waits and +rechecked before returning the identity, including after wire shutdown. A +repository observation retains a synchronous authority check over its selected +grant and credential for the final publication boundary; invoking it does not +refresh metadata or approve the target. + The fixed wire shares one operation allowance across metadata, Git discovery, authentication and fetch, and charges the real turn counter. It counts TLS framing and both directions. Before forwarding each chunk it rechecks live diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 1e0772efd0..cfdc823a44 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -92,6 +92,20 @@ before the proxy exists, so expired GitHub source is withheld without network until an explicit turn request validates it. Other legacy repository transports remain unqualified for repository trust. +The same internal access service provides owner-only repository metadata +lookup without a Git revision, acquisition, agent turn or Git channel. It +reuses the anonymous-first and live private-grant/API-recipient checks above; +owner namespace lookup remains anonymous-only. Both operations snapshot the +principal, target, cancellation and operation-authority callback before waits, +recheck them after waits including shutdown, and return fresh fixed-endpoint +identity data. Repository lookup also retains a synchronous `assertAuthority()` +callback over that exact lookup's selected grant/credential and operation; it +allows the publisher to recheck after later waits without selecting replacement +authority. This callback is not metadata refresh or approval evidence. They return no credential, relay capability, approved-owner +boundary or source-trust flag. The Settings publisher still supplies its +independent password-mode human authority and must revalidate identity before +publishing. A lookup at review time is not permanent identity approval. + Migration 089 records a retained source acquisition's host-issued identity, brain/principal/turn, stable repository and owner identities, resolved ref, commit/tree, sealed native root ID/UUID/creation generation, selected grant and diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 8a75f33bbb..35049c83e0 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -33,125 +33,157 @@ export function createGitHubReferenceAccess(options: { throw new ReferenceTransportError("denied", "reference principal is no longer available"); }; + /** Shared metadata authority, without selecting a Git revision or starting a turn. */ + async function repositoryMetadata(input: RequestBounds & { principalId: string; repository: unknown; + withdrawPublic?: () => Promise }, ownerOnly: boolean) { + // Retain the operation's identity across waits; caller-owned objects cannot + // switch the principal, target, cancellation or authority callback mid-read. + const { principalId, repository: repositoryInput, current: currentOperation, signal, withdrawPublic, ...bounds } = input; + const assertOperation = () => { + signal?.throwIfAborted(); + if (currentOperation && !currentOperation()) throw new ReferenceTransportError("denied", "the reference operation is no longer available"); + principal(principalId, ownerOnly); + }; + const location = githubReferenceRepository(repositoryInput), repository = referenceRepository(location.cloneUrl); + assertOperation(); + let grant: ReferenceGrant | null = null, credential: string | null = null; + const authorize = (recipient: "git" | "metadata", credentialed: boolean) => { + assertOperation(); + if (grant) { + const current = coveringReferenceGrant(options.db, { brain: options.brain, principalId, repository, now: now() }); + // Recreated grants and a newly selected narrower grant cannot inherit this operation. + if (!current || current.id !== grant.id || current.credential !== grant.credential) + throw new ReferenceTransportError("denied", "the selected reference grant changed"); + if (recipient === "metadata" && credentialed && current.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) + throw new ReferenceTransportError("denied", "the selected grant does not permit the API credential recipient"); + if (credentialed && (!current.credential || options.credentials[current.credential] !== credential)) + throw new ReferenceTransportError("denied", "the selected host credential changed"); + } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); + }; + const wire = await createGitHubReferenceWire({ ...bounds, signal, repository: location.cloneUrl, ...options.wireTransport, authorize }); + let openingMetadata = true; + try { + let result = await wire.metadata(null); + if (result.status === 401 || result.status === 404) { + await withdrawPublic?.(); + // That observation is already contained. A missing private grant + // is not a second metadata observation after the withdrawal waits. + openingMetadata = false; + assertOperation(); + grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId, repository, now: now() }); + if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) + throw new ReferenceTransportError("denied", "private identity needs a live reference grant and explicit API credential permission"); + credential = options.credentials[grant.credential] ?? null; + if (!credential) throw new ReferenceTransportError("unavailable", "the granted host credential is not configured"); + authorize("metadata", true); + openingMetadata = true; + result = await wire.metadata(credential); + } + authorize("metadata", credential !== null); + if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); + const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value); + if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); + openingMetadata = false; + // Source/worktree effects outlive wire shutdown, but not this authority. + const assertAuthority = () => { + authorize("git", credential !== null); authorize("metadata", credential !== null); + }; + const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); }; + assertCurrent(); + return Object.freeze({ identity: Object.freeze(identity), repository, credential, wire, + domain: grant ? "private" as const : "public" as const, grantId: grant?.id ?? null, assertCurrent, assertAuthority, + /** A final fixed metadata observation must still describe this exact acquisition. */ + async revalidate() { + try { + assertCurrent(); + const result = await wire.metadata(credential); + assertCurrent(); + if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value))) + throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); + } catch (error) { + const interrupted = signal?.aborted || (currentOperation && !currentOperation()); + await wire.close(); + if (interrupted) throw error; + throw new GitHubReferenceMetadataError(error); + } + }, + close: () => wire.close(), + }); + } catch (error) { + // Retain an observed metadata failure before shutdown can outlive its turn. + const failure = openingMetadata && !signal?.aborted && (!currentOperation || currentOperation()) + ? new GitHubReferenceMetadataError(error) : error; + await wire.close(); throw failure; + } + } + return { - /** Settings still supplies its independent password-mode human publication authority. */ + /** Settings supplies independent password-mode human publication authority. */ async owner(input: RequestBounds & { principalId: string; owner: unknown }): Promise { - const owner = githubReferenceOwner(input.owner); - principal(input.principalId, true); - const wire = await createGitHubReferenceWire({ ...input, owner: owner.owner, ...options.wireTransport, - authorize: () => principal(input.principalId, true) }); + const { principalId, owner: ownerInput, current, signal, ...bounds } = input; + const owner = githubReferenceOwner(ownerInput); + const assertCurrent = () => { + signal?.throwIfAborted(); + if (current && !current()) throw new ReferenceTransportError("denied", "the Settings operation is no longer available"); + principal(principalId, true); + }; + assertCurrent(); + const wire = await createGitHubReferenceWire({ ...bounds, signal, owner: owner.owner, ...options.wireTransport, authorize: assertCurrent }); + let identity: GitHubReferenceOwner & { ownerId: string }; try { const result = await wire.metadata(null); - principal(input.principalId, true); + assertCurrent(); if (result.status !== 200) throw new ReferenceTransportError("unavailable", "GitHub owner identity is unavailable"); - return parseGitHubOwnerMetadata(owner.owner, result.value); + identity = parseGitHubOwnerMetadata(owner.owner, result.value); } finally { await wire.close(); } + assertCurrent(); + return Object.freeze(identity); + }, + + /** Fixed metadata only. No revision, Git channel, token or approval proof escapes. */ + async repository(input: RequestBounds & { principalId: string; repository: unknown }): Promise { + const access = await repositoryMetadata(input, true); + try { access.assertCurrent(); } + finally { await access.close(); } + // Wire shutdown is an asynchronous wait too. Its intentional abort does + // not invalidate the caller's independent live Settings authority. + access.assertAuthority(); + // A later synchronous publication fence must retain this operation's + // selected grant and credential, rather than select a replacement grant. + // This checks authority only; a new review/commit still needs fresh metadata. + return Object.freeze({ ...access.identity, assertAuthority: access.assertAuthority }); }, /** Open one host-only budget; anonymous metadata always precedes any permitted private retry. */ async open(input: RequestBounds & { principalId: string; repository: unknown; revision: unknown; /** The source host must hide prior public exposure before a credentialed retry can await. */ withdrawPublic?: () => Promise }) { - const location = githubReferenceRepository(input.repository), repository = referenceRepository(location.cloneUrl); const revision = referenceRevision(input.revision); - principal(input.principalId); - let grant: ReferenceGrant | null = null, credential: string | null = null; - const authorize = (recipient: "git" | "metadata", credentialed: boolean) => { - if (input.current && !input.current()) throw new ReferenceTransportError("denied", "the acquiring turn is no longer available"); - principal(input.principalId); - if (grant) { - const current = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); - // Recreated grants and a newly selected narrower grant cannot inherit this operation. - if (!current || current.id !== grant.id || current.credential !== grant.credential) - throw new ReferenceTransportError("denied", "the selected reference grant changed"); - if (recipient === "metadata" && credentialed && current.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) - throw new ReferenceTransportError("denied", "the selected grant does not permit the API credential recipient"); - if (credentialed && (!current.credential || options.credentials[current.credential] !== credential)) - throw new ReferenceTransportError("denied", "the selected host credential changed"); - } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); - }; - const wire = await createGitHubReferenceWire({ ...input, repository: location.cloneUrl, ...options.wireTransport, authorize }); - let openingMetadata = true; - try { - let result = await wire.metadata(null); - if (result.status === 401 || result.status === 404) { - await input.withdrawPublic?.(); - // That observation is already contained. A missing private grant - // is not a second metadata observation after the withdrawal waits. - openingMetadata = false; - principal(input.principalId); - grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); - if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) - throw new ReferenceTransportError("denied", "private identity needs a live reference grant and explicit API credential permission"); - credential = options.credentials[grant.credential] ?? null; - if (!credential) throw new ReferenceTransportError("unavailable", "the granted host credential is not configured"); - authorize("metadata", true); - openingMetadata = true; - result = await wire.metadata(credential); - } - authorize("metadata", credential !== null); - if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); - const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value); - if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); - openingMetadata = false; - // Source/worktree effects outlive wire shutdown, but not this authority. - const assertAuthority = () => { - authorize("git", credential !== null); authorize("metadata", credential !== null); - }; - const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); }; - let resolved: Extract | undefined; - assertCurrent(); - return Object.freeze({ - identity: Object.freeze(identity), - domain: grant ? "private" as const : "public" as const, - grantId: grant?.id ?? null, - revision, - signal: wire.signal, - bytes: wire.bytes, - assertCurrent, assertAuthority, - async resolve() { - assertCurrent(); - const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal }); - assertCurrent(); - if (resolved && (!result.ok || result.ref !== resolved.ref || result.commit !== resolved.commit)) { - await wire.close(); throw new ReferenceTransportError("invalid", "the selected Git reference changed during acquisition"); - } - if (result.ok) resolved = { ...result }; - return result; - }, - async fetch(root: string) { - assertCurrent(); - if (!resolved) throw new ReferenceTransportError("invalid", "reference fetch needs its resolved branch or tag"); - const result = await options.transport.fetch({ repository, ref: resolved.ref, root, token: credential, wire, signal: wire.signal }); - assertCurrent(); - if (result.commit !== resolved.commit) { - await wire.close(); throw new ReferenceTransportError("invalid", "the fetched commit differs from the selected reference"); - } - return result; - }, - /** A final fixed metadata observation must still describe this exact acquisition. */ - async revalidate() { - try { - assertCurrent(); - const result = await wire.metadata(credential); - assertCurrent(); - if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value))) - throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); - } catch (error) { - const interrupted = input.signal?.aborted || (input.current && !input.current()); - await wire.close(); - if (interrupted) throw error; - throw new GitHubReferenceMetadataError(error); - } - }, - close: () => wire.close(), - }); - } catch (error) { - // Retain an observed metadata failure before shutdown can outlive its turn. - const failure = openingMetadata && !input.signal?.aborted && (!input.current || input.current()) - ? new GitHubReferenceMetadataError(error) : error; - await wire.close(); throw failure; - } + const access = await repositoryMetadata(input, false); + const { identity, domain, grantId, wire, credential, repository, assertCurrent, assertAuthority, revalidate, close } = access; + let resolved: Extract | undefined; + return Object.freeze({ identity, domain, grantId, revision, signal: wire.signal, bytes: wire.bytes, assertCurrent, assertAuthority, revalidate, close, + async resolve() { + assertCurrent(); + const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal }); + assertCurrent(); + if (resolved && (!result.ok || result.ref !== resolved.ref || result.commit !== resolved.commit)) { + await close(); throw new ReferenceTransportError("invalid", "the selected Git reference changed during acquisition"); + } + if (result.ok) resolved = { ...result }; + return result; + }, + async fetch(root: string) { + assertCurrent(); + if (!resolved) throw new ReferenceTransportError("invalid", "reference fetch needs its resolved branch or tag"); + const result = await options.transport.fetch({ repository, ref: resolved.ref, root, token: credential, wire, signal: wire.signal }); + assertCurrent(); + if (result.commit !== resolved.commit) { + await close(); throw new ReferenceTransportError("invalid", "the fetched commit differs from the selected reference"); + } + return result; + }, + }); }, }; } diff --git a/packages/ui-server/tests/github-reference-access.test.ts b/packages/ui-server/tests/github-reference-access.test.ts index cc8fbbcc3e..2831359d14 100644 --- a/packages/ui-server/tests/github-reference-access.test.ts +++ b/packages/ui-server/tests/github-reference-access.test.ts @@ -213,6 +213,183 @@ test("owner Settings identity is anonymous and owner-scoped, without approval or } finally { await f.close(); } }); +test("Settings repository identity has no Git phase or revision and stays anonymous", async () => { + const f = await fixture(); f.grant({ principalId: f.owner.id }); + try { + const pending = Promise.resolve().then(() => f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" })); + await expect(pending, "SETTINGS_REPOSITORY_RESOLVES_WITHOUT_GIT_OR_AGENT_TURN").resolves.toEqual({ + owner: "odysseus", repository: "ithaca", canonical: "https://github.com/odysseus/ithaca", cloneUrl: "https://github.com/odysseus/ithaca.git", + metadataUrl: "https://api.github.com/repos/odysseus/ithaca", repositoryId: "101", ownerId: "201", private: false, + assertAuthority: expect.any(Function), + }); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git, "SETTINGS_METADATA_NEVER_DISPATCHES_GIT").toEqual([]); + await expect(f.service().repository({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca" }), + "SETTINGS_PUBLIC_METADATA_REQUIRES_OWNER").rejects.toMatchObject({ reason: "denied" }); + expect(f.received).toHaveLength(1); + } finally { await f.close(); } +}); + +test("owner metadata rechecks the Settings operation after its actual DNS wait", async () => { + let release!: () => void, ready!: () => void, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; }, + metadata: () => Response.json({ id: 201, login: "Odysseus", type: "User", url: "https://api.github.com/users/Odysseus", html_url: "https://github.com/Odysseus" }) }); + const pending = f.service().owner({ ...f.bounds, principalId: f.owner.id, owner: "odysseus", current: () => current }); + try { + await reached; current = false; release(); + const result = await pending.then(value => ({ ok: true, value }), () => ({ ok: false })); + expect(result, "SETTINGS_OWNER_OPERATION_RECHECKED_AFTER_DNS").toEqual({ ok: false }); + expect(f.connections, "SETTINGS_ENDED_OWNER_OPERATION_NEVER_CONNECTS").toEqual([]); + expect(f.received).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } +}); + +test("private Settings metadata uses the owner's own live grant and separately permitted API recipient", async () => { + const f = await fixture({ private: true }); + f.grant({ principalId: f.owner.id }); + try { + await expect(f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_PRIVATE_METADATA_USES_OWN_GRANT").resolves.toMatchObject({ repositoryId: "101", ownerId: "201", private: true }); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }, + { path: "/repos/odysseus/ithaca", authorization: `Bearer ${token}` }]); + await expect(f.service().repository({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca" }), + "SETTINGS_METADATA_REQUIRES_OWNER").rejects.toMatchObject({ reason: "denied" }); + expect(f.received).toHaveLength(2); + expect(f.git).toEqual([]); + } finally { await f.close(); } +}); + +for (const kind of ["grant", "replace", "narrower", "recipient", "credential", "principal", "operation", "cancel"] as const) + test(`Settings metadata retains a final synchronous ${kind} authority fence after wire cleanup`, async () => { + let current = true; + const credentials: Record = { GITHUB_TOKEN: token }, controller = new AbortController(); + const f = await fixture({ private: true, credentials }), grant = f.grant({ principalId: f.owner.id }); + try { + const result = await f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", + current: () => current, signal: controller.signal }); + expect(() => result.assertAuthority(), "SETTINGS_FRESH_METADATA_AUTHORITY_REMAINS_USABLE_AFTER_CLEANUP").not.toThrow(); + if (kind === "grant" || kind === "replace") { + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + if (kind === "replace") f.grant({ principalId: f.owner.id }); + } else if (kind === "narrower") f.grant({ principalId: f.owner.id, repositoryPrefix: "https://github.com/odysseus/ithaca" }); + else if (kind === "recipient") f.db.query("UPDATE reference_grants SET metadata_credential_recipient=NULL WHERE id=?").run(grant.id); + else if (kind === "credential") credentials.GITHUB_TOKEN = "changed-fixture-token"; + else if (kind === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); + else if (kind === "operation") current = false; + else controller.abort(); + expect(() => result.assertAuthority(), "SETTINGS_FINAL_PUBLICATION_FENCE_RETAINS_LOOKUP_AUTHORITY").toThrow(); + expect(f.received).toHaveLength(2); expect(f.git).toEqual([]); + } finally { await f.close(); } + }); + +for (const kind of ["absent", "legacy", "other-brain", "other-principal", "sibling-repository", "revoked", "credentialless"] as const) + test(`Settings private metadata refuses ${kind} authority without credential probing`, async () => { + let tokenReads = 0; + const f = await fixture({ private: true, credentials: { get GITHUB_TOKEN() { tokenReads++; return token; } } }); + try { + if (kind !== "absent") { + const grant = f.grant({ principalId: f.owner.id, ...(kind === "legacy" ? { metadataCredentialRecipient: null } + : kind === "other-brain" ? { brain: "troy-brain" } + : kind === "other-principal" ? { principalId: f.agent.id } + : kind === "sibling-repository" ? { repositoryPrefix: "https://github.com/odysseus-crew" } + : kind === "credentialless" ? { credential: null, metadataCredentialRecipient: null } : {}) }); + if (kind === "revoked") revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + } + await expect(f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_METADATA_NEEDS_OWN_LIVE_GRANT_AND_API_PERMISSION").rejects.toMatchObject({ reason: "denied" }); + expect(tokenReads, "SETTINGS_METADATA_REFUSAL_NEVER_PROBES_CREDENTIAL").toBe(0); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git).toEqual([]); + } finally { await f.close(); } + }); + +for (const kind of ["operation", "principal", "grant", "recipient", "credential", "cancel"] as const) + test(`Settings private metadata fences ${kind} loss during credentialed DNS`, async () => { + let release!: () => void, ready!: () => void, lookups = 0, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const credentials: Record = { GITHUB_TOKEN: token }, controller = new AbortController(); + const f = await fixture({ private: true, credentials, lookup: async () => { + if (++lookups === 2) { ready(); await held; } return [{ address: "93.184.216.34", family: 4 }]; + } }); + const grant = f.grant({ principalId: f.owner.id }); + const pending = f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", current: () => current, signal: controller.signal }); + try { + await reached; + if (kind === "operation") current = false; + else if (kind === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); + else if (kind === "grant") revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + else if (kind === "recipient") f.db.query("UPDATE reference_grants SET metadata_credential_recipient=NULL WHERE id=?").run(grant.id); + else if (kind === "credential") credentials.GITHUB_TOKEN = "changed-fixture-token"; + else controller.abort(); + release(); + const result = await pending.then(value => ({ ok: true, value }), () => ({ ok: false })); + expect(result, "SETTINGS_AUTHORITY_RECHECKED_AFTER_CREDENTIALED_DNS").toEqual({ ok: false }); + expect(f.connections, "SETTINGS_LOST_AUTHORITY_NEVER_REACHES_CREDENTIALED_TCP").toHaveLength(1); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } + }); + +for (const kind of ["owner", "repository"] as const) + test(`Settings ${kind} identity retains its original caller and operation across waits`, async () => { + let release!: () => void, ready!: () => void, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; } }); + const input = { ...f.bounds, principalId: f.owner.id, owner: "odysseus", repository: "odysseus/ithaca", current: () => current }; + const pending = kind === "owner" ? f.service().owner(input) : f.service().repository(input); + try { + await reached; current = false; + input.principalId = f.agent.id; input.current = () => true; input.owner = "penelope"; input.repository = "penelope/loom"; + release(); + expect(await pending.then(() => true, () => false), "SETTINGS_CALLER_MUTATION_CANNOT_REPLACE_OPERATION").toBe(false); + expect(f.connections).toEqual([]); expect(f.received).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } + }); + +test("each Settings lookup observes fresh provider identity and refuses redirects or unknown metadata", async () => { + const changes = [identity(), { ...identity(), id: 102 }, { ...identity(), owner: { id: 202, login: "Odysseus" } }, + { ...identity(), name: "Fleet", full_name: "Odysseus/Fleet", clone_url: "https://github.com/Odysseus/Fleet.git", url: "https://api.github.com/repos/Odysseus/Fleet" }]; + let selected = 0; + const f = await fixture({ metadata: () => Response.json(changes[selected]) }); + try { + const lookup = (repository = "odysseus/ithaca") => f.service().repository({ ...f.bounds, principalId: f.owner.id, repository }); + expect(await lookup()).toMatchObject({ repositoryId: "101", ownerId: "201" }); + selected = 1; expect(await lookup(), "SETTINGS_NAME_REUSE_RETURNS_NEW_IDENTITY").toMatchObject({ repositoryId: "102", ownerId: "201" }); + selected = 2; expect(await lookup(), "SETTINGS_OWNER_REUSE_RETURNS_NEW_BOUNDARY").toMatchObject({ repositoryId: "101", ownerId: "202" }); + selected = 3; + await expect(lookup(), "SETTINGS_RENAME_CANNOT_BORROW_OLD_NAME_RESPONSE").rejects.toThrow(); + expect(await lookup("odysseus/fleet"), "SETTINGS_RENAME_REQUIRES_FRESH_EXACT_NAME_OBSERVATION").toMatchObject({ repositoryId: "101", ownerId: "201", repository: "fleet" }); + expect(f.git).toEqual([]); + } finally { await f.close(); } + for (const status of [302, 403, 429, 500]) { + let tokenReads = 0; + const control = await fixture({ metadata: () => new Response(null, { status }), credentials: { get GITHUB_TOKEN() { tokenReads++; return token; } } }); + control.grant({ principalId: control.owner.id }); + try { + await expect(control.service().repository({ ...control.bounds, principalId: control.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_UNKNOWN_METADATA_CANNOT_DISPATCH_CREDENTIAL").rejects.toThrow(); + expect(tokenReads).toBe(0); expect(control.received).toHaveLength(1); expect(control.git).toEqual([]); + } finally { await control.close(); } + } +}); + +test("Settings cancellation closes a pending DNS operation before that lookup finishes", async () => { + let release!: () => void, ready!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const controller = new AbortController(); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; } }); + const pending = f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", signal: controller.signal }); + let timer: ReturnType | undefined; + try { + await reached; controller.abort(); + const result = await Promise.race([pending.then(() => "identity", () => "cancelled"), + new Promise(resolve => { timer = setTimeout(() => resolve("still_waiting"), 5000); })]); + expect(result, "SETTINGS_CANCEL_DOES_NOT_WAIT_FOR_DNS").toBe("cancelled"); + expect(f.connections).toEqual([]); expect(f.received).toEqual([]); + } finally { if (timer) clearTimeout(timer); release(); await pending.catch(() => {}); await f.close(); } +}); + test("one acquisition binds a short revision before network and refuses a moved fetched commit before checkout", async () => { const f = await fixture({ fetchCommit: "b".repeat(40) }); try {