C4: the vault keeps the forge token with the scopes it was minted with
The file beside the token that kept its scopes went with C4, and with it the re-mint of a token carrying a scope beyond the tools' (write:admin). The value written through own-put now holds the token and its scopes; a token minted with other scopes, or a value naming none, is minted again unasked and the one it replaces deleted at the forge. The Go bundles read the token out of that value. The lost test is back as a row of the scope test in test/token.test.ts. Builds: design 47 H2 §808; H-A-439
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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<MintedTok
|
||||
}
|
||||
|
||||
const VAULT = "module/gitea/mesh-tools";
|
||||
/** The token the vault keeps for the tools' account, out of the value that holds it with its scopes (H-A-439). */
|
||||
const vaulted = (bus: ReturnType<typeof fakeBus>) => 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 });
|
||||
|
||||
@@ -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<NodeJS.ProcessEnv & { MESH_GITEA_STATE_DIR: string }> {
|
||||
bus = fakeBus();
|
||||
|
||||
+39
-10
@@ -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<VaultToken | null>;
|
||||
/** Write the account's token as the module's own; answers the generation the vault kept. */
|
||||
put(account: string, token: string): Promise<number>;
|
||||
/** 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<number>;
|
||||
}
|
||||
|
||||
/** The lease `mint` in the state `token-lease` (§808). */
|
||||
@@ -182,12 +208,12 @@ export function vaultOverBus(request: (verb: string, body: unknown) => Promise<u
|
||||
throw err;
|
||||
}
|
||||
if (!answer?.sealed) throw new Error(`the vault answered no sealed ${vaultName(account)}`);
|
||||
return { token: open(answer.sealed, keys.privateKey), generation: answer.generation ?? 0, changedAt: answer["changed-at"] ?? "" };
|
||||
return { ...openValue(open(answer.sealed, keys.privateKey)), generation: answer.generation ?? 0, changedAt: answer["changed-at"] ?? "" };
|
||||
},
|
||||
async put(account, token) {
|
||||
async put(account, token, scopes) {
|
||||
const opened = (await request("seat:mesh-vault.own-put", { name: account })) as { call?: string; seal_to?: string };
|
||||
if (!opened?.call || !opened.seal_to) throw new Error(`the vault opened no own-put call for ${vaultName(account)}`);
|
||||
const kept = (await request("seat:mesh-vault.own-put", { call: opened.call, sealed: sealAnonymous(token, opened.seal_to) })) as { generation?: number };
|
||||
const kept = (await request("seat:mesh-vault.own-put", { call: opened.call, sealed: sealAnonymous(vaultValue(token, scopes), opened.seal_to) })) as { generation?: number };
|
||||
return kept?.generation ?? 0;
|
||||
},
|
||||
};
|
||||
@@ -333,6 +359,9 @@ export class MintedToken implements TokenSource {
|
||||
const kept = await this.opts.vault.get(this.opts.account);
|
||||
if (kept === null) return this.mint("the vault holds no token for this account — minting one", null);
|
||||
if (this.expired(kept)) return this.mint(`the vault's token is older than token-ttl (${this.ttlMs / 1000}s) — minting one`, kept.token);
|
||||
if (!sameScopes(kept.scopes, this.scopes)) {
|
||||
return this.mint(`the vault's token was minted with other scopes than the tools take now (${kept.scopes.join(", ") || "none kept"}) — minting one with them`, kept.token);
|
||||
}
|
||||
if (this.held === null) {
|
||||
this.log(`reusing the token the vault keeps as ${vaultName(this.opts.account)} (generation ${kept.generation})`);
|
||||
// A retirement of the admin's old token that failed after the mint is tried again, once a process.
|
||||
@@ -386,7 +415,7 @@ export class MintedToken implements TokenSource {
|
||||
if (await this.opts.lease.take(this.holder, this.leaseMs)) {
|
||||
try {
|
||||
const kept = await this.opts.vault.get(this.opts.account);
|
||||
if (kept !== null && kept.token !== stale && !this.expired(kept)) {
|
||||
if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) {
|
||||
this.held = kept;
|
||||
this.log(`another process minted it meanwhile — reusing the vault's generation ${kept.generation}`);
|
||||
return kept.token;
|
||||
@@ -401,7 +430,7 @@ export class MintedToken implements TokenSource {
|
||||
this.log(`another process holds the mint lease${other ? ` (${other.holder} since ${other.since})` : ""} — waiting for it, at most mint-lease (${this.leaseMs / 1000}s)`);
|
||||
await this.opts.lease.changed(this.leaseMs);
|
||||
const kept = await this.opts.vault.get(this.opts.account);
|
||||
if (kept !== null && kept.token !== stale && !this.expired(kept)) {
|
||||
if (kept !== null && kept.token !== stale && !this.expired(kept) && sameScopes(kept.scopes, this.scopes)) {
|
||||
this.held = kept;
|
||||
this.log(`the process that held the mint lease minted generation ${kept.generation} — reusing it`);
|
||||
return kept.token;
|
||||
@@ -495,9 +524,9 @@ export class MintedToken implements TokenSource {
|
||||
const token = typeof res.body?.sha1 === "string" ? res.body.sha1 : null;
|
||||
if (!token) throw new Error(`Gitea POST /users/${account}/tokens: ${res.status} but no token in the reply`);
|
||||
|
||||
const kept = await this.opts.vault.put(account, token);
|
||||
const kept = await this.opts.vault.put(account, token, this.scopes);
|
||||
if (kept !== generation) this.log(`the vault kept ${vaultName(account)} at generation ${kept}, the forge names it ${name}`);
|
||||
this.held = { token, generation: kept, changedAt: this.now().toISOString() };
|
||||
this.held = { token, scopes: this.scopes, generation: kept, changedAt: this.now().toISOString() };
|
||||
this.log(`minted ${name} for "${account}" (${this.scopes.join(", ")}), kept in the vault as ${vaultName(account)}`);
|
||||
|
||||
// Only now, with the new token kept, does the one it replaces go.
|
||||
|
||||
Reference in New Issue
Block a user