diff --git a/modules/gitea/cmd/forge/account_test.go b/modules/gitea/cmd/forge/account_test.go index 54e7213a3..f0995aa60 100644 --- a/modules/gitea/cmd/forge/account_test.go +++ b/modules/gitea/cmd/forge/account_test.go @@ -32,7 +32,9 @@ func vaultHolding(t *testing.T, account, token string) *forgehttp.VaultToken { if token == "" { return nil, fmt.Errorf("the vault holds no secret named %s", a["name"]) } - box, err := seal.Seal(token, a["public_key"].(string)) + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), a["public_key"].(string)) if err != nil { return nil, err } diff --git a/modules/gitea/cmd/package-registry/seats_test.go b/modules/gitea/cmd/package-registry/seats_test.go index 33cab8930..5d30aff98 100644 --- a/modules/gitea/cmd/package-registry/seats_test.go +++ b/modules/gitea/cmd/package-registry/seats_test.go @@ -216,7 +216,9 @@ func vaultHolding(t *testing.T, account string, held map[string]string) *forgeht if !ok { return nil, fmt.Errorf("the vault holds no secret named %s", a["name"]) } - box, err := seal.Seal(token, a["public_key"].(string)) + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), a["public_key"].(string)) if err != nil { return nil, err } diff --git a/modules/gitea/cmd/package-registry/whole_integration_test.go b/modules/gitea/cmd/package-registry/whole_integration_test.go index 5f6848f07..1f4f511f4 100644 --- a/modules/gitea/cmd/package-registry/whole_integration_test.go +++ b/modules/gitea/cmd/package-registry/whole_integration_test.go @@ -143,7 +143,9 @@ func (p *player) handle(m wire) { p.answer(m.ID, nil, errors.New("the vault holds no secret named "+q.Name)) break } - box, err := seal.Seal(token, q.PublicKey) + // The value the minter writes: the token and the scopes it was minted with (H-A-439). + value, _ := json.Marshal(map[string]any{"token": token, "scopes": []string{"write:repository", "write:issue", "read:user", "read:package"}}) + box, err := seal.Seal(string(value), q.PublicKey) p.answer(m.ID, map[string]any{"name": q.Name, "generation": 1, "sealed": box}, err) case m.Method == "mesh/seat.publish": p.answer(m.ID, map[string]any{}, p.nc.Publish(a.Subject, a.Body)) diff --git a/modules/gitea/internal/forgehttp/vault.go b/modules/gitea/internal/forgehttp/vault.go index b6ad605c3..2fec629c6 100644 --- a/modules/gitea/internal/forgehttp/vault.go +++ b/modules/gitea/internal/forgehttp/vault.go @@ -61,11 +61,18 @@ func (t *VaultToken) Load() error { if err := json.Unmarshal(raw, &got); err != nil || got.Sealed == nil { return fmt.Errorf("the vault answered no sealed %s", VaultName(t.Account)) } - token, err := seal.Open(*got.Sealed, t.keys.PrivateKey) + opened, err := seal.Open(*got.Sealed, t.keys.PrivateKey) if err != nil { return fmt.Errorf("%s does not open with this process's key: %w", VaultName(t.Account), err) } - token = strings.TrimSpace(token) + // The value holds the token and the scopes it was minted with (H-A-439); the minter judges the scopes, this reads the token. + var value struct { + Token string `json:"token"` + } + if err := json.Unmarshal([]byte(opened), &value); err != nil { + return fmt.Errorf("the vault's %s is not a token with its scopes: %w", VaultName(t.Account), err) + } + token := strings.TrimSpace(value.Token) if token == "" { return fmt.Errorf("the vault's %s is empty", VaultName(t.Account)) } diff --git a/modules/gitea/test/token.test.ts b/modules/gitea/test/token.test.ts index 7231822c3..0bd3e0008 100644 --- a/modules/gitea/test/token.test.ts +++ b/modules/gitea/test/token.test.ts @@ -15,7 +15,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { collectTools } from "@novox/mesh-sdk/tools"; -import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, vaultOverBus, type MintedTokenOptions } from "../dist/token.js"; +import { AdminRefused, MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus, vaultValue, type MintedTokenOptions } from "../dist/token.js"; import { tokenLeaseTool } from "../dist/tools/tokenlease.js"; import { fakeBus } from "./fakebus.ts"; import { GiteaClient } from "../dist/client.js"; @@ -288,6 +288,8 @@ function source(env: NodeJS.ProcessEnv, logs: string[], extra: Partial) => openValue(bus.vault.get(VAULT)?.value ?? "").token; const forge = await fakeForge(); after(() => forge.close()); @@ -304,7 +306,8 @@ test("first start: mints mesh-tools-1 with the admin account, writes it through // Design 47 H2 §808, H-A-422 (2), H-A-426: named per mint, kept as the module's own secret, never a file. const token = forge.tokens.get("mesh-tools-1")!; assert.ok(token); - assert.deepEqual([bus.vault.get(VAULT)?.value, bus.vault.get(VAULT)?.generation], [token, 1]); + assert.deepEqual([vaulted(bus), bus.vault.get(VAULT)?.generation], [token, 1]); + assert.deepEqual(openValue(bus.vault.get(VAULT)!.value).scopes, [...TOKEN_SCOPES], "kept with the scopes it was minted with (H-A-439)"); await assert.rejects(stat(join(env.MESH_GITEA_STATE_DIR!, "token")), /ENOENT/); assert.ok(logs.some((l) => l.startsWith("minted mesh-tools-1")), logs.join("\n")); assert.ok(logs.every((l) => !l.includes(token) && !l.includes(PASSWORD)), logs.join("\n")); @@ -336,7 +339,7 @@ test("the forge rejects the vault's token: mesh-tools-2 is minted once, written assert.equal(repos.length, 1); assert.equal(forge.mints, before + 1); - assert.equal(bus.vault.get(VAULT)?.value, forge.tokens.get("mesh-tools-2")); + assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2")); // H-A-422 (2): the own-put first, the replaced token's delete after, by id; the forge holds one tools' token after. assert.deepEqual(ORDER, [`own-put ${VAULT} 2`, "delete mesh-tools-1"]); assert.deepEqual(forge.deletedBy, ["id"]); @@ -353,9 +356,9 @@ test("an own-put that fails leaves the old token standing, and the next mint rep forge.tokens.set("mesh-tools-1", "revoked-meanwhile"); ORDER.length = 0; let failPut = true; - const failing = minted(env, logs, { vault: { get: vaultOverBus().get, put: async (a, t) => { + const failing = minted(env, logs, { vault: { get: vaultOverBus().get, put: async (a, t, scopes) => { if (failPut) { failPut = false; throw new Error("the vault is away"); } - return vaultOverBus().put(a, t); + return vaultOverBus().put(a, t, scopes); } } }); await assert.rejects(failing.listRepos(), /the vault is away/); @@ -365,7 +368,7 @@ test("an own-put that fails leaves the old token standing, and the next mint rep assert.equal((await failing.listRepos()).length, 1); assert.deepEqual(ORDER, ["delete mesh-tools-2", `own-put ${VAULT} 2`, "delete mesh-tools-1"]); - assert.notEqual(bus.vault.get(VAULT)?.value, old); + assert.notEqual(vaulted(bus), old); }); test("a token older than token-ttl is minted again, and the one it replaces deleted", async () => { @@ -389,7 +392,7 @@ test("a token older than token-ttl is minted again, and the one it replaces dele assert.ok(logs.some((l) => l.includes("older than token-ttl")), logs.join("\n")); }); -test("a token lacking a scope the tools need: the forge refuses the call for the scope, the token is re-minted with the whole list, and the call goes through", async () => { +test("a token lacking a scope the tools need: the forge refuses the call for the scope, the token is re-minted with the whole list, and the call goes through", async (t) => { const { env, bus, logs } = await delivered(forge); forge.tokens.clear(); const client = minted(env, logs); @@ -403,7 +406,33 @@ test("a token lacking a scope the tools need: the forge refuses the call for the assert.equal(repos.length, 1); assert.equal(forge.mints, before + 1); assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); - assert.equal(bus.vault.get(VAULT)?.value, forge.tokens.get("mesh-tools-2")); + assert.equal(vaulted(bus), forge.tokens.get("mesh-tools-2")); + + // Design 47 H2 §808, H-A-439: the vault keeps the scopes beside the token, so one carrying a scope beyond the tools' + // is minted again unasked, as when they were kept in a file beside it. + await t.test("a token kept with write:admin is minted again without it at the next start, and the forge drops the old one", async () => { + const { env, bus, logs } = await delivered(forge); + forge.tokens.clear(); + await minted(env, logs).listRepos(); + const old = forge.tokens.get("mesh-tools-1")!; + // An earlier mint asked write:admin too, and the vault keeps what it asked. + bus.vault.get(VAULT)!.value = vaultValue(old, [...TOKEN_SCOPES, "write:admin"]); + forge.scopesOf.set(old, [...TOKEN_SCOPES, "write:admin"]); + const before = forge.mints; + + const again: string[] = []; + await minted(env, again).listRepos(); + + assert.equal(forge.mints, before + 1); + assert.deepEqual(forge.lastScopes, [...TOKEN_SCOPES]); + assert.ok(![...forge.tokens.values()].includes(old), "the old token still stands on the forge"); + assert.deepEqual(openValue(bus.vault.get(VAULT)!.value), { token: forge.tokens.get("mesh-tools-2"), scopes: [...TOKEN_SCOPES] }); + assert.ok(again.some((l) => l.includes("minted with other scopes")), again.join("\n")); + // An admin route through the escape hatch is refused before it is sent. + const tool = getGiteaTools(minted(env, again)).find((x) => x.name === "gitea_api")!; + await assert.rejects(tool.run({ path: "/admin/users/mesh_novox_builder", method: "PATCH", body: { admin: true } }, undefined as never), + /not a write gitea_api makes/); + }); }); test("the first mint deletes by id every token under the old fixed name, two raced ones too, and keeps the account's others", async () => { @@ -545,7 +574,7 @@ test("forge_token_lease says the lease's holder and since when, and each token's assert.equal(tool.name, "forge_token_lease"); assert.deepEqual(said.tokens.map((t: any) => [t.account, t.held, t.generation, t["age-seconds"]]), [["mesh-tools", true, 1, 90], ["mesh-packages", false, undefined, undefined]]); - assert.ok(!JSON.stringify(said).includes(bus.vault.get(VAULT)!.value), "the token is never said"); + assert.ok(!JSON.stringify(said).includes(vaulted(bus)), "the token is never said"); // The lease lives mint-lease: past it, nobody holds it. clock += 30_000; assert.deepEqual((await tool.run({}, undefined as never) as any).lease, { held: false }); diff --git a/modules/gitea/test/tools-account.test.ts b/modules/gitea/test/tools-account.test.ts index f486ae51b..2ef7431a9 100644 --- a/modules/gitea/test/tools-account.test.ts +++ b/modules/gitea/test/tools-account.test.ts @@ -14,7 +14,7 @@ import { mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, vaultOverBus } from "../dist/token.js"; +import { MintedToken, TOKEN_NAME, TOKEN_SCOPES, leaseOverState, openValue, vaultOverBus } from "../dist/token.js"; import { fakeBus } from "./fakebus.ts"; import { GiteaClient } from "../dist/client.js"; import { TOOLS_ACCOUNT, TOOLS_TEAM_UNITS, BUILDER_ACCOUNT, AGENT_ACCOUNT, meshAccounts } from "../dist/tools-account.js"; @@ -269,7 +269,7 @@ after(() => forge.close()); /** The bus of the environment made last: the vault's secrets and the lease (design 47 H2 §808). */ let bus = fakeBus(); -const vaulted = (account: string) => bus.vault.get(`module/gitea/${account}`)?.value; +const vaulted = (account: string) => { const v = bus.vault.get(`module/gitea/${account}`)?.value; return v === undefined ? undefined : openValue(v).token; }; async function environment(keepMainRules = false): Promise { bus = fakeBus(); diff --git a/modules/gitea/token.ts b/modules/gitea/token.ts index 9bfec2ca3..c02c3fa01 100644 --- a/modules/gitea/token.ts +++ b/modules/gitea/token.ts @@ -24,6 +24,9 @@ // setting, default 60 s) — and mint. A process that finds the lease taken waits for that key to change, at most the // lease, then reads the vault again; past it, the lease has expired and the waiter creates it itself; // - **minted again when older than `token-ttl`** (a setting, default 24 hours), its age the vault's `changed-at`; +// - **minted again when minted with other scopes** (H-A-439): the value the vault keeps holds the token and the scopes +// it was minted with, so a token carrying a scope beyond the ones the tools take (such as write:admin) is minted again +// unasked, and the one it replaces deleted, as when the scopes were kept in a file beside the token; // - minted for the account, not the administrator (novox/hq ADR 0365 §2, issue 469): the administrator's login mints // it for the account, after making that account and its team, and deletes any token named `mesh-tools` the // administrator itself still holds — the token the tools used before. @@ -138,19 +141,42 @@ export class AdminRefused extends Error { } } -/** A token as the vault holds it: the value, the generation and when it changed (`get`'s answer, opened). */ +/** A token as the vault holds it: the token, the scopes it was minted with, the generation and when it changed (`get`'s + * answer, opened). */ export interface VaultToken { readonly token: string; + readonly scopes: readonly string[]; readonly generation: number; readonly changedAt: string; } +/** The value the vault keeps for an account: the token and the scopes it was minted with (§808, H-A-439). */ +export function vaultValue(token: string, scopes: readonly string[]): string { + return JSON.stringify({ token, scopes: [...scopes] }); +} + +/** A value the vault keeps, opened: its token and scopes. A value of another form names no scopes, so it is minted again. */ +export function openValue(value: string): { token: string; scopes: readonly string[] } { + try { + const v = JSON.parse(value); + if (v && typeof v.token === "string" && Array.isArray(v.scopes)) return { token: v.token, scopes: v.scopes.map(String) }; + } catch { + // not the token and its scopes + } + return { token: value.trim(), scopes: [] }; +} + +/** Whether two lists name the same scopes, in any order. */ +function sameScopes(a: readonly string[], b: readonly string[]): boolean { + return [...a].sort().join(",") === [...b].sort().join(","); +} + /** The vault as the minter reaches it: the seat `mesh-vault`'s `get` and `own-put` (§808, §822). */ export interface TokenVault { /** The account's token the vault holds, or null when it holds none. */ get(account: string): Promise; - /** Write the account's token as the module's own; answers the generation the vault kept. */ - put(account: string, token: string): Promise; + /** Write the account's token and the scopes it was minted with as the module's own; answers the generation the vault kept. */ + put(account: string, token: string, scopes: readonly string[]): Promise; } /** The lease `mint` in the state `token-lease` (§808). */ @@ -182,12 +208,12 @@ export function vaultOverBus(request: (verb: string, body: unknown) => Promise