diff --git a/docs/operations.md b/docs/operations.md index 43a0bb32d..e4b112980 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -270,7 +270,7 @@ Run the worker as a separate OS user without access to the operator's home, toke `"display": true` says the worker can run tasks that render a UI (such as screenshot tasks, which require `display`); without it those tasks stay queued. For such a task the derived image adds software Vulkan and GL drivers (`mesa-vulkan-drivers`, `libvulkan1`, `libgl1-mesa-dri`, `libegl1`) and sets `WGPU_BACKEND=vulkan`; images of other tasks are unchanged. `gpu` is separate and only passes a GPU device through. -Only `coordinatorUrl`, `keyFile` and `workDir` are required. `workDir` must not contain commas, colons or spaces. Other keys: `userns` (default `keep-id`), `maxSourceMb` (300), `maxStepSec` (14400), `warmDir` (default `/../warm`, same path rules as `workDir`) and `warmMaxGb` (60). +`coordinatorUrl` may use plain `http` only for loopback, private-network (10/8, 172.16/12, 192.168/16, 100.64/10, fc00::/7) and cluster-internal hosts (single-label names, `.svc`, `.cluster.local`, `.internal`); any other host needs `https`. Only `coordinatorUrl`, `keyFile` and `workDir` are required. `workDir` must not contain commas, colons or spaces. Other keys: `userns` (default `keep-id`), `maxSourceMb` (300), `maxStepSec` (14400), `warmDir` (default `/../warm`, same path rules as `workDir`) and `warmMaxGb` (60). The worker records each step's peak memory from the container's cgroup (v2) while the step runs and sends it as `peakMemBytes`; `oomKilled` is true when the kernel killed the step for reaching the memory limit (`limits.memoryGb`). Both are omitted when the cgroup cannot be read. diff --git a/src/access.ts b/src/access.ts index b646fe27d..9a592ec2d 100644 --- a/src/access.ts +++ b/src/access.ts @@ -21,9 +21,10 @@ export function listAccess(db: DatabaseSync): AccessRow[] { return db.prepare("SELECT login, role, added_by, added_at, note FROM access ORDER BY login COLLATE NOCASE").all() as AccessRow[]; } -// The access entry's GitHub id is stored at the first sign-in. Later sign-ins -// must present the same id: a login that was renamed or released and taken by -// someone else is not the person who was added. +// The access entry's GitHub id is stored when the entry is added (or, for an +// entry added without one, at the first sign-in). Sign-ins must present the +// same id: a login that was renamed or released and taken by someone else is +// not the person who was added. export function checkGithubId(db: DatabaseSync, login: string, id: number): "ok" | "bound" | "mismatch" { const row = db.prepare("SELECT github_id FROM access WHERE login = ?").get(login) as { github_id: number | null } | undefined; if (!row) return "mismatch"; @@ -56,13 +57,13 @@ function tx(db: DatabaseSync, f: () => T): T { } } -export function addLogin(db: DatabaseSync, by: string, login: string, role: Role, note: string | null): void { +export function addLogin(db: DatabaseSync, by: string, login: string, role: Role, note: string | null, githubId: number | null = null): void { if (!LOGIN.test(login)) throw new AccessError(`not a GitHub login: ${JSON.stringify(login)}`); if (!isRole(role)) throw new AccessError(`role must be ${ROLES.join(", ")}`); tx(db, () => { if (getAccess(db, login)) throw new AccessError(`${login} is already on the access list`); - db.prepare("INSERT INTO access (login, role, added_by, added_at, note) VALUES (?, ?, ?, ?, ?)") - .run(login, role, by, new Date().toISOString(), note || null); + db.prepare("INSERT INTO access (login, role, added_by, added_at, note, github_id) VALUES (?, ?, ?, ?, ?, ?)") + .run(login, role, by, new Date().toISOString(), note || null, githubId); audit(db, by, "access-add", login, { role }); }); } diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index 3b29c4a8a..b55ae8ff2 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -7,7 +7,7 @@ import type { DatabaseSync } from "node:sqlite"; import type { AccessOverview, AuditEntry, AuditPage, Contributor, ContributorList, ContributorSort, RulePreview, RepoApproval, RepoLabels, Tier, TrackedRepo, WhitelistRule, } from "../../../web/src/api/types.ts"; -import { AccessError, addLogin, isRole, listAccess, removeLogin, ROLES, setRole } from "../../access.ts"; +import { AccessError, addLogin, getAccess, isRole, LOGIN, listAccess, removeLogin, ROLES, setRole } from "../../access.ts"; import { approvalOf, setApproval } from "../../labels/approval.ts"; import { commentApprovalOf, setCommentApproval } from "../../act/approval.ts"; import { pushApprovalOf, setPushApproval } from "../../fixup/approval.ts"; @@ -458,10 +458,28 @@ const roleOf = (v: unknown) => { return v; }; -export function accessAdd(db: DatabaseSync, req: Req): AccessOverview { +/** The numeric GitHub id of a login: null when GitHub has no such user; throws when GitHub can't be reached. */ +export type GithubUserLookup = (login: string) => Promise; + +export async function accessAdd(db: DatabaseSync, req: Req, lookup: GithubUserLookup): Promise { requireOperator(req, "manage access"); const b = body(req); - refused(() => addLogin(db, req.user.login, required(b.login, "login"), roleOf(b.role), text(b.note, ACCESS_NOTE_MAX, "note"))); + const login = required(b.login, "login"); + const role = roleOf(b.role); + const note = text(b.note, ACCESS_NOTE_MAX, "note"); + // Validates and rejects duplicates before GitHub is asked. + refused(() => { + if (!LOGIN.test(login)) throw new AccessError(`not a GitHub login: ${JSON.stringify(login)}`); + if (getAccess(db, login)) throw new AccessError(`${login} is already on the access list`); + }); + let id: number | null; + try { + id = await lookup(login); + } catch { + throw new HttpError(502, "GitHub could not be reached to look up that login. Try again."); + } + if (id === null) throw new HttpError(400, `${login} is not a GitHub user`); + refused(() => addLogin(db, req.user.login, login, role, note, id)); return accessOverview(db, req); } diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index ad567d844..4017e1935 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -19,6 +19,7 @@ import { HttpError, RateLimiter } from "../server/util.ts"; import { findingsOf, type PremergeRow } from "../../premerge/store.ts"; import type { Req, Res, Route } from "../types.ts"; import * as adm from "./admin.ts"; +import { githubUserId } from "../../github/users.ts"; import * as discord from "./discord.ts"; import * as agents from "./agents.ts"; import * as build from "./build.ts"; @@ -73,6 +74,8 @@ export type ApiOptions = { embedder?: Embedder; // Runs `gh` for the batch controls that close a PR; default: the real one. Tests fake it. exec?: Exec; + // Looks up a login's numeric GitHub id when an access entry is added; default: GitHub's API. Tests fake it. + githubUserId?: adm.GithubUserLookup; }; const ok = (fn: (db: DatabaseSync, req: Req) => unknown) => async (db: DatabaseSync, req: Req): Promise => { @@ -485,7 +488,7 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { post("/api/repos/pipeline-on", (db, req) => adm.pipelineSwitch(db, req, true)), post("/api/repos/pipeline-off", (db, req) => adm.pipelineSwitch(db, req, false)), get("/api/access", adm.accessOverview), - post("/api/access/add", adm.accessAdd), + post("/api/access/add", (db, req) => adm.accessAdd(db, req, opts.githubUserId ?? githubUserId)), post("/api/access/remove", adm.accessRemove), post("/api/access/role", adm.accessRole), post("/api/access/sessions/revoke", adm.revokeSession), diff --git a/src/dash/server/crypto.ts b/src/dash/server/crypto.ts index c991e65ca..18a860d45 100644 --- a/src/dash/server/crypto.ts +++ b/src/dash/server/crypto.ts @@ -13,7 +13,7 @@ export function safeEqual(a: string, b: string): boolean { // AES-256-GCM with a key derived from the session key. The AAD binds a // ciphertext to one session row, so a token can't be moved to another session. -// Values sealed under the earlier HKDF label stay readable through the legacy key. +// Values sealed under the earlier HKDF label are re-sealed once at startup (reseal.ts); `open` reads only the current key. const LABEL = "autocraft"; const LEGACY_LABEL = "craft-automation"; const deriveKey = (sessionKey: string, label: string): Buffer => Buffer.from(hkdfSync("sha256", sessionKey, label, "github-token", 32)); @@ -33,7 +33,13 @@ export class TokenBox { return Buffer.concat([iv, c.getAuthTag(), body]).toString("base64url"); } open(sealed: string, aad: string): string | null { - return this.#openWith(this.#key, sealed, aad) ?? this.#openWith(this.#legacyKey, sealed, aad); + return this.#openWith(this.#key, sealed, aad); + } + /** The value sealed under the current key when only the earlier key opens `sealed`; null when it is already current or unreadable. For the startup migration only. */ + resealLegacy(sealed: string, aad: string): string | null { + if (this.#openWith(this.#key, sealed, aad) !== null) return null; + const plain = this.#openWith(this.#legacyKey, sealed, aad); + return plain === null ? null : this.seal(plain, aad); } #openWith(key: Buffer, sealed: string, aad: string): string | null { try { diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index ee62af221..912343853 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -10,6 +10,7 @@ import { LOGIN, checkGithubId, getAccess } from "../../access.ts"; import { audit, auditRefusedSignIn } from "../audit.ts"; import type { Req, Res, Route } from "../types.ts"; import { isLoopbackHost, type Config } from "./config.ts"; +import { resealLegacyValues } from "./reseal.ts"; import { pkceChallenge, randomToken, safeEqual, TokenBox } from "./crypto.ts"; import { ImageIndex } from "./image-index.ts"; import { visibleTo } from "../api/visible.ts"; @@ -72,15 +73,16 @@ export type AppOptions = { live?: LiveOptions; // GET /api/live timing; defaults suit production // Opinions and comments per login per hour. The dashboard's routes and the MCP server's feedback must share one instance. feedbackLimiter?: RateLimiter; + githubUserId?: (login: string) => Promise; // numeric GitHub id of a login for new access entries; default: GitHub's API githubApi?: string; // base URL of the GitHub API for the GitHub App calls; default: api.github.com }; type Compiled = Route & { parts: string[] }; -export async function defaultRoutes(feedbackLimiter?: RateLimiter): Promise { +export async function defaultRoutes(feedbackLimiter?: RateLimiter, githubUserId?: AppOptions["githubUserId"]): Promise { const { apiRoutes } = await import("../api/index.ts"); - return apiRoutes({ limiter: feedbackLimiter }); + return apiRoutes({ limiter: feedbackLimiter, ...(githubUserId && { githubUserId }) }); } function compile(routes: Route[]): Compiled[] { @@ -158,6 +160,9 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { // The org setup link signs in with the OAuth App even when dashboard sign-in uses the GitHub App. const setupProvider = opts.provider ?? (config.devAuth ? provider : oauthProviderFor(config)); const box = new TokenBox(config.secrets.sessionKey); + const resealed = resealLegacyValues(db, box); + const resealedTotal = Object.values(resealed).reduce((a, b) => a + b, 0); + if (resealedTotal) console.log(`re-sealed ${resealedTotal} stored token values under the current key (${Object.entries(resealed).map(([t, n]) => `${t} ${n}`).join(", ")})`); // The GitHub App's own provider: it signs users in under login=github-app, and always makes and refreshes their user tokens (the "act as you" authorization). // Read at each use: registering or removing the app takes effect without a restart. const appProviderNow = (): Provider | null => { @@ -674,7 +679,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { export async function startServer(opts: AppOptions): Promise<{ server: Server; url: string; app: ReturnType; close(): Promise }> { const feedbackLimiter = opts.feedbackLimiter ?? new RateLimiter(60, 3600_000); - const app = createApp({ ...opts, feedbackLimiter, routes: opts.routes ?? (await defaultRoutes(feedbackLimiter)) }); + const app = createApp({ ...opts, feedbackLimiter, routes: opts.routes ?? (await defaultRoutes(feedbackLimiter, opts.githubUserId)) }); const server = createServer({ requestTimeout: 30_000, headersTimeout: 15_000 }, (req, res) => void app.handle(req, res)); await new Promise((resolve, reject) => { server.once("error", reject); diff --git a/src/dash/server/reseal.ts b/src/dash/server/reseal.ts new file mode 100644 index 000000000..9148b6333 --- /dev/null +++ b/src/dash/server/reseal.ts @@ -0,0 +1,42 @@ +// Startup migration: values sealed under the earlier key label are sealed again under the current key, so +// TokenBox.open never needs the earlier one. Every table that holds TokenBox-sealed values is listed here. +import type { DatabaseSync } from "node:sqlite"; +import type { TokenBox } from "./crypto.ts"; + +type Store = { table: string; key: string; cols: string[]; aad: (r: Record) => string }; + +const userAad = (login: string | null): string => `user_tokens:${login!.toLowerCase()}`; + +const STORES: Store[] = [ + { table: "sessions", key: "id_hash", cols: [], aad: (r) => r.id_hash! }, + { table: "user_tokens", key: "login", cols: [], aad: (r) => userAad(r.login!) }, + { table: "user_token_revocations", key: "id", cols: ["login", "aad"], aad: (r) => r.aad ?? userAad(r.login!) }, + { table: "reporter_tokens", key: "reporter", cols: [], aad: (r) => `reporter_tokens:${r.reporter!}` }, +]; + +/** Re-seals every legacy-sealed token_enc value in one transaction; returns the count per table (tables with a change only). Idempotent. */ +export function resealLegacyValues(db: DatabaseSync, box: TokenBox): Record { + const todo: Array<{ table: string; key: string; id: string | number; old: string; sealed: string }> = []; + for (const s of STORES) { + const rows = db.prepare(`SELECT ${[s.key, "token_enc", ...s.cols].join(", ")} FROM ${s.table} WHERE token_enc IS NOT NULL`).all() as Array>; + for (const r of rows) { + const old = String(r.token_enc); + const sealed = box.resealLegacy(old, s.aad(r as Record)); + if (sealed) todo.push({ table: s.table, key: s.key, id: r[s.key] as string | number, old, sealed }); + } + } + const counts: Record = {}; + if (!todo.length) return counts; + db.exec("BEGIN IMMEDIATE"); + try { + for (const t of todo) { + const r = db.prepare(`UPDATE ${t.table} SET token_enc = ? WHERE ${t.key} = ? AND token_enc = ?`).run(t.sealed, t.id, t.old); + if (Number(r.changes)) counts[t.table] = (counts[t.table] ?? 0) + 1; + } + db.exec("COMMIT"); + } catch (e) { + db.exec("ROLLBACK"); + throw e; + } + return counts; +} diff --git a/src/github/identity.ts b/src/github/identity.ts index a712f4aae..ac3052e40 100644 --- a/src/github/identity.ts +++ b/src/github/identity.ts @@ -6,6 +6,7 @@ // The instance-wide setting `github_identity` decides whether that is used at all: under `box` (the default) the box // account makes every write, and `as` only appears in the audit row as a record of what it would be. import type { DatabaseSync } from "node:sqlite"; +import { dropSessionTokens } from "../dash/server/user-tokens.ts"; import { audit } from "../dash/audit.ts"; import type { Grant, Guarded } from "../core/guard.ts"; import { ownerOf } from "../owners.ts"; @@ -33,7 +34,14 @@ export function setGithubIdentity(db: DatabaseSync, by: string, value: unknown): if (value === "box") db.prepare("DELETE FROM main.settings WHERE key = ?").run(KEY); else db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(KEY, value); audit(db, by, "github-identity", value, { identity: value, was }); - db.prepare("DELETE FROM sessions").run(); + // Each session's own token set is revoked as well (it may differ from the login's stored one). + const sessions = db.prepare("DELETE FROM sessions RETURNING login, id_hash, token_enc").all() as { login: string; id_hash: string; token_enc: string | null }[]; + for (const s of sessions) dropSessionTokens(db, s.login, s.id_hash, s.token_enc); + // The stored user tokens belong to the mode being left: queue their revocation at GitHub (the vault's sweep). + const stored = db.prepare("DELETE FROM user_tokens RETURNING login, token_enc").all() as { login: string; token_enc: string }[]; + const queue = db.prepare("INSERT INTO user_token_revocations (login, token_enc, queued_at, kind) VALUES (?, ?, ?, 'grant')"); + const at = new Date().toISOString(); + for (const t of stored) queue.run(t.login, t.token_enc, at); return true; } diff --git a/src/github/users.ts b/src/github/users.ts new file mode 100644 index 000000000..01655e331 --- /dev/null +++ b/src/github/users.ts @@ -0,0 +1,13 @@ +import { AppError, call, GITHUB_API } from "./app.ts"; + +/** The numeric id of a GitHub user, read without authentication. Null when there is no such user; throws when GitHub can't answer. */ +export async function githubUserId(login: string, base: string = GITHUB_API): Promise { + try { + const j = (await call(base, `/users/${encodeURIComponent(login)}`, null)) as { id?: unknown; type?: unknown }; + if (typeof j.id !== "number") throw new AppError("GitHub gave no user id"); + return j.id; + } catch (e) { + if (e instanceof AppError && e.status === 404) return null; + throw e; + } +} diff --git a/src/worker/config.ts b/src/worker/config.ts index fb9d1c64f..445c62721 100644 --- a/src/worker/config.ts +++ b/src/worker/config.ts @@ -64,11 +64,38 @@ function loadKey(file: string, make: (pem: Buffer) => KeyObject): KeyObject { } } +/** Hosts that plain http may reach: loopback, private ranges, and cluster-internal names. Anything else needs https. */ +export function plainHttpHostAllowed(hostname: string): boolean { + const h = hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (h === "localhost" || h === "::1") return true; + const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); + if (v4) { + const [a, b] = [Number(v4[1]), Number(v4[2])]; + return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127); + } + if (h.includes(":")) return /^f[cd][0-9a-f]{2}:/.test(h); + return !h.includes(".") || /\.(svc|cluster\.local|internal)$/.test(h); +} + +/** Throws unless `url` is https, or http to a host plainHttpHostAllowed accepts. */ +export function checkCoordinatorUrl(url: string): void { + let u: URL; + try { + u = new URL(url); + } catch { + throw new Error("config: coordinatorUrl must be an http(s) URL"); + } + if (u.protocol === "http:" && !plainHttpHostAllowed(u.hostname)) { + throw new Error("config: coordinatorUrl uses plain http, which is accepted only for loopback, private-network and cluster-internal hosts (single-label names, .svc, .cluster.local, .internal); use https"); + } +} + export function parseWorkerConfig(raw: unknown): WorkerConfig { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("config: expected a JSON object"); const o = raw as Record; const coordinatorUrl = str(o, "coordinatorUrl").replace(/\/+$/, ""); if (!/^https?:\/\/[^\s]+$/.test(coordinatorUrl)) throw new Error("config: coordinatorUrl must be an http(s) URL"); + checkCoordinatorUrl(coordinatorUrl); const keyFile = expand(str(o, "keyFile")); const workDir = expand(str(o, "workDir")); const warmDir = expand(typeof o.warmDir === "string" && o.warmDir ? o.warmDir : join(dirname(workDir), "warm")); diff --git a/test/admin.test.ts b/test/admin.test.ts index aa773a090..c611736c6 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -43,7 +43,15 @@ before(async () => { addLogin(db, "cli", "maint", "maintainer", null); scopeToTracked(db); const config = loadConfig({ AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: dbFile, AUTOCRAFT_DEV_PERMS: permsFile }); - const s = await startServer({ config, db, provider: new FakeProvider(permsFile), routes: apiRoutes() }); + const provider = new FakeProvider(permsFile); + // The id GitHub would give a login: the one the fake provider signs it in with. + const githubUserId = async (l: string): Promise => { + if (l === "ghost") return null; + const id = 5000 + l.length; + provider.ids.set(l.toLowerCase(), id); + return id; + }; + const s = await startServer({ config, db, provider, routes: apiRoutes({ githubUserId }) }); base = s.url; close = s.close; }); @@ -192,6 +200,7 @@ describe("admin api", () => { assert.equal(a.entries.find((e) => e.login === "second")!.role, "operator"); await boss.post("/api/access/add", { login: "second", role: "viewer" }, 400); await boss.post("/api/access/add", { login: "x", role: "owner" }, 400); + await boss.post("/api/access/add", { login: "ghost", role: "viewer" }, 400); const victim = await signedIn("second"); a = await boss.get("/api/access"); diff --git a/test/env-crypto.test.ts b/test/env-crypto.test.ts index cea93812d..5fdecbe61 100644 --- a/test/env-crypto.test.ts +++ b/test/env-crypto.test.ts @@ -10,7 +10,7 @@ test("envVar prefers AUTOCRAFT_ and falls back to CRAFT_AUTO_", () => { assert.equal(envVar("X", {}), undefined); }); -test("TokenBox opens a value sealed under the earlier key label", () => { +test("TokenBox refuses a value sealed under the earlier key label", () => { const key = hkdfSync("sha256", "session-key", "craft-automation", "github-token", 32); const iv = randomBytes(12); const c = createCipheriv("aes-256-gcm", Buffer.from(key), iv); @@ -18,6 +18,7 @@ test("TokenBox opens a value sealed under the earlier key label", () => { const body = Buffer.concat([c.update("tok", "utf8"), c.final()]); const sealed = Buffer.concat([iv, c.getAuthTag(), body]).toString("base64url"); const box = new TokenBox("session-key"); - assert.equal(box.open(sealed, "row"), "tok"); + assert.equal(box.open(sealed, "row"), null); + assert.equal(box.open(box.resealLegacy(sealed, "row")!, "row"), "tok"); assert.equal(box.open(box.seal("tok2", "row"), "row"), "tok2"); }); diff --git a/test/hardening-lead-a.test.ts b/test/hardening-lead-a.test.ts new file mode 100644 index 000000000..677e377f1 --- /dev/null +++ b/test/hardening-lead-a.test.ts @@ -0,0 +1,65 @@ +import assert from "node:assert/strict"; +import { createCipheriv, hkdfSync, randomBytes } from "node:crypto"; +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { test } from "node:test"; +import { connect } from "../src/db.ts"; +import { TokenBox } from "../src/dash/server/crypto.ts"; +import { resealLegacyValues } from "../src/dash/server/reseal.ts"; +import { addLogin, checkGithubId } from "../src/access.ts"; +import { setGithubIdentity } from "../src/github/identity.ts"; +import { parseWorkerConfig } from "../src/worker/config.ts"; +import { SCRATCH } from "./scratch.ts"; + +const KEY = "hardening-session-key-hardening-0"; + +function sealLegacy(plain: string, aad: string): string { + const iv = randomBytes(12); + const c = createCipheriv("aes-256-gcm", Buffer.from(hkdfSync("sha256", KEY, "craft-automation", "github-token", 32)), iv); + c.setAAD(Buffer.from(aad)); + const body = Buffer.concat([c.update(plain, "utf8"), c.final()]); + return Buffer.concat([iv, c.getAuthTag(), body]).toString("base64url"); +} + +test("legacy-sealed values are re-sealed at startup, then open; open alone refuses them", () => { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `hardening-a-${process.pid}.db`)); + const box = new TokenBox(KEY); + const legacy = sealLegacy("{}", "user_tokens:alice"); + assert.equal(box.open(legacy, "user_tokens:alice"), null); + db.prepare("INSERT INTO user_tokens (login, github_id, token_enc, version, updated_at, status) VALUES ('Alice', 1, ?, 1, 'x', 'ok')").run(legacy); + assert.deepEqual(resealLegacyValues(db, box), { user_tokens: 1 }); + const now = (db.prepare("SELECT token_enc FROM user_tokens").get() as { token_enc: string }).token_enc; + assert.equal(box.open(now, "user_tokens:alice"), "{}"); + assert.deepEqual(resealLegacyValues(db, box), {}); + db.close(); +}); + +test("switching the identity queues revocation of stored user tokens", () => { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `hardening-b-${process.pid}.db`)); + db.prepare("INSERT INTO user_tokens (login, github_id, token_enc, version, updated_at, status) VALUES ('bob', 2, 'enc', 1, 'x', 'ok')").run(); + assert.equal(setGithubIdentity(db, "op", "app"), true); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM user_tokens").get() as { n: number }).n, 0); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM user_token_revocations WHERE login = 'bob'").get() as { n: number }).n, 1); + db.close(); +}); + +test("an access entry added with a GitHub id rejects another id at sign-in", () => { + mkdirSync(SCRATCH, { recursive: true }); + const db = connect(join(SCRATCH, `hardening-c-${process.pid}.db`)); + addLogin(db, "op", "carol", "viewer", null, 7); + assert.equal(checkGithubId(db, "carol", 8), "mismatch"); + assert.equal(checkGithubId(db, "carol", 7), "ok"); + db.close(); +}); + +test("coordinatorUrl: plain http only for loopback, private and cluster-internal hosts", () => { + const cfg = (coordinatorUrl: string) => parseWorkerConfig({ coordinatorUrl, keyFile: "/k", workDir: "/w" }); + for (const u of ["http://127.0.0.1:8981", "http://localhost:1", "http://[::1]:1", "http://10.1.2.3", "http://172.20.0.1", "http://192.168.1.5", "http://100.64.0.9", "http://runner.svc", "http://coord", "http://a.b.cluster.local", "http://x.internal", "https://example.com"]) { + assert.doesNotThrow(() => cfg(u), u); + } + for (const u of ["http://example.com", "http://8.8.8.8", "http://172.32.0.1", "http://100.128.0.1", "http://coordinator.invalid"]) { + assert.throws(() => cfg(u), /plain http/, u); + } +});