From 3232ae3a5646c53e0af03112af711fd352cb9206 Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Sat, 28 Nov 2026 21:29:06 -0600 Subject: [PATCH 01/33] Worker: an appliance key's link secret, and POST /api/license/link (#465) The box's owner accepts the license at setup, and their acceptance is linked to the box's appliance key. license.json holds no secret and the box's agent can read it, so the link needs proof that the box asks: a per-box secret the Worker mints with the key's first issue (and again on a move to a newer maker record), answered once as link_secret beside the document and kept only as its SHA-256 (migration 0005, additive). A repeat request for the same record gets no secret: its maker id is in the box's receipt, which the agent can read. POST /api/license/link {acceptance_id, license_id, device, link_secret} sets licenses.acceptance_id for an unrevoked, unreleased appliance key on that device whose secret matches (constant time, checked before anything about the acceptance is told), for an acceptance on record, not revoked and of the current license. The same acceptance again is a no-op; another moves it. Co-Authored-By: Claude Opus 5.5 --- worker/migrations/0005_license_link.sql | 15 ++ worker/src/index.js | 133 +++++++++++++- worker/test/license.test.mjs | 234 +++++++++++++++++++++++- 3 files changed, 362 insertions(+), 20 deletions(-) create mode 100644 worker/migrations/0005_license_link.sql diff --git a/worker/migrations/0005_license_link.sql b/worker/migrations/0005_license_link.sql new file mode 100644 index 00000000..1592a04a --- /dev/null +++ b/worker/migrations/0005_license_link.sql @@ -0,0 +1,15 @@ +-- teaport download gate: linking an appliance key to its owner's acceptance (teaport#465). +-- Applied by .github/workflows/worker-deploy.yml before each deploy, never by hand from a branch. +-- Additive only: one new column, empty on every row, so the Worker before it still runs +-- against this schema (a rollback), and nothing here needs one. +-- What it holds, and how long it is kept: docs/engine-license-data.md. + +-- An appliance key's link secret: SHA-256 of the 32 random bytes POST /api/license returns +-- (as link_secret, base64url) when it first issues the key to a maker acceptance, or moves +-- it to a newer one (a box provisioned again: a new secret, and this replaced). Lowercase +-- hex. The secret itself is never stored: install.sh writes it to the box's +-- /etc/teaport/license-link.secret (root's alone), and POST /api/license/link takes it as +-- the proof that the request comes from the box itself, which license.json, readable by +-- the box's agent, cannot be. Empty: a key issued before this (or a personal or commercial +-- key), which links only by hand. +ALTER TABLE licenses ADD COLUMN link_secret_hash TEXT; diff --git a/worker/src/index.js b/worker/src/index.js index 5f087e16..bc2a1979 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -46,6 +46,20 @@ // the current license (409 eula_changed after a change), an appliance // key is signed again under the current key. A device with any revoked // key gets none. Only ids are sent: never audio or transcripts. +// An appliance key's first issue, and its move to a box's newer maker +// acceptance, also answer link_secret beside the document (top level: +// {payload, signature, link_secret}), 32 random bytes, base64url, +// which only this answer ever holds: the Worker keeps their SHA-256 +// (migrations/0005), and a move replaces it. install.sh writes it to +// /etc/teaport/license-link.secret and the document alone to +// license.json. Asked again for the same record, or renewed: no +// secret (see applianceLicense). +// POST /api/license/link {acceptance_id, license_id, device, link_secret} -> {license_id, +// linked, changed}: the box's owner's acceptance, made at setup +// (teaport#465), recorded against its appliance key. The secret proves +// the request is the box's: license.json, which the box's agent can +// read, holds none. A later link with another acceptance moves it (a +// resale); the same one again changes nothing. // GET|HEAD /dl/engine/*, /dl/models/* Authorization: Bearer . Streams the file // from teaport-engine-dist, with byte ranges (curl -C - resumes the // multi-GB models), and logs the download against the acceptance. @@ -447,6 +461,19 @@ function newLicenseId() { return `TPL-${Array.from(crypto.getRandomValues(new Uint8Array(20)), (b) => CROCKFORD[b & 31]).join("")}`; } +// An appliance key's link secret (migrations/0005): {secret: 32 random bytes, base64url, +// for the answer only; hash: their SHA-256, lowercase hex, for the row}. +export const LINK_SECRET_BYTES = 32; +const LINK_SECRET = /^[A-Za-z0-9_-]{43}$/; // 32 bytes, base64url without padding + +const hex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join(""); +const linkHash = async (raw) => hex(await crypto.subtle.digest("SHA-256", raw)); + +async function newLinkSecret() { + const raw = crypto.getRandomValues(new Uint8Array(LINK_SECRET_BYTES)); + return { secret: b64url(raw), hash: await linkHash(raw) }; +} + // The signer, with the engine major version keys are issued for; null when either is not set // up right (sshsig.js signer(): no secret, no public line, or a secret that is not its key). async function licenseSigner(env) { @@ -548,9 +575,9 @@ export const LICENSE_SQL = { // An appliance key ?1 for device ?2 under maker acceptance ?6: one per maker acceptance // (OR IGNORE: the unique index), none for a device that holds a revoked key or already a // live appliance key (that one moves instead: applianceMove). first_maker_id records ?6 - // for good: a move changes maker_id only. - applianceInsert: `INSERT OR IGNORE INTO licenses (license_id, tier, device, kid, engine_major, issued_at, maker_id, first_maker_id, created_at, signed_at) - SELECT ?1, 'appliance', ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?7 WHERE NOT EXISTS (${revokedDevice("?2")}) + // for good: a move changes maker_id only. ?8: the hash of its link secret. + applianceInsert: `INSERT OR IGNORE INTO licenses (license_id, tier, device, kid, engine_major, issued_at, maker_id, first_maker_id, created_at, signed_at, link_secret_hash) + SELECT ?1, 'appliance', ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?7, ?8 WHERE NOT EXISTS (${revokedDevice("?2")}) AND NOT EXISTS (${spent("?6")}) AND NOT EXISTS (${liveAppliance("?2")})`, // A box provisioned again: its live appliance key, under an older maker acceptance for the @@ -561,8 +588,9 @@ export const LICENSE_SQL = { // nothing). A factory record that is gone (past its retention) is older, and of the box. // Another serial's record never takes it: with a leaked FACTORY_TOKEN and a box's tpdev2, // a made-up record could otherwise take the box's key, and revoking that record (the - // leak's cleanup) would stop the real box's renewals. - applianceMove: `UPDATE OR IGNORE licenses SET maker_id = ?1, kid = ?2, signed_at = ?3 + // leak's cleanup) would stop the real box's renewals. ?5: the hash of a new link secret, + // which replaces the one the box had in its previous life (the secret goes with the record). + applianceMove: `UPDATE OR IGNORE licenses SET maker_id = ?1, kid = ?2, signed_at = ?3, link_secret_hash = ?5 WHERE license_id = (SELECT d.license_id FROM licenses d INDEXED BY licenses_device WHERE d.device = ?4 AND d.tier = 'appliance' AND d.revoked_at IS NULL AND d.released_at IS NULL AND (SELECT (m.created_at, m.id) < (n.created_at, n.id) AND (m.id IS NULL OR m.device_id = n.device_id) @@ -583,6 +611,12 @@ export const LICENSE_SQL = { // renewed. Not when it is revoked or released, or its device holds a revoked key. resign: `UPDATE licenses SET kid = ?2, signed_at = ?3 WHERE license_id = ?1 AND revoked_at IS NULL AND released_at IS NULL AND NOT EXISTS (${revokedDevice("?4")})`, + // Appliance key ?1 (on device ?3, its link secret's hash ?4) linked to acceptance ?2: only + // while it is neither revoked nor released and the hash is still that one (a move to a + // newer record meanwhile replaced it). By the primary key. + link: `UPDATE licenses SET acceptance_id = ?2 + WHERE license_id = ?1 AND tier = 'appliance' AND device = ?3 AND link_secret_hash = ?4 + AND revoked_at IS NULL AND released_at IS NULL`, }; // device_cap, with how many other devices count; null when fewer than the cap do (the state @@ -687,6 +721,12 @@ async function personalLicense(env, sig, id, device, now) { // A record for another serial never takes it (403 maker_serial). A record that ever held a // key (license_makers) never issues or receives another (403 maker_spent): the one a box // provisioned again leaves behind holds nothing, and its id is still in the box's old receipt. +// The key's first issue, and a move, answer a new link secret (the header); the same record +// asking again gets the key without one. Not a new one: the maker id is in the box's receipt +// for MAKER_MAX_DAYS, where the box's agent can read it, and a secret minted for whoever +// asks would let that agent link the box to any acceptance (POST /api/license/link). Nor the +// old one, of which only the hash is kept. A box that lost the answer before it wrote the +// secret is provisioned again (a move mints one), or linked by hand. async function applianceLicense(env, sig, id, device, now) { if (!MAKER_ID.test(id)) return fail(400, "bad_request", "maker_id: the factory install record's id, maker- and 24 characters"); const maker = await env.DB.prepare("SELECT created_at, revoked_at FROM maker_acceptances WHERE id = ?1").bind(id).first(); @@ -695,17 +735,23 @@ async function applianceLicense(env, sig, id, device, now) { const find = () => env.DB.prepare("SELECT * FROM licenses WHERE maker_id = ?1").bind(id).first(); let row = await find(); for (let i = 0; !row && i < TRIES; i++) { - const moved = await env.DB.prepare(LICENSE_SQL.applianceMove).bind(id, sig.kid, iso(now), device).run(); + // A new link secret for each write: the one that lands is answered, once. + const moving = await newLinkSecret(); + const moved = await env.DB.prepare(LICENSE_SQL.applianceMove).bind(id, sig.kid, iso(now), device, moving.hash).run(); if (moved.meta.changes === 1) { row = await find(); - if (row?.device === device) return json(200, await licenseDoc(sig, payloadOf(row, sig.kid))); + // Still under this record, so still this secret: a later move would have changed both. + if (row?.device === device) return json(200, { ...(await licenseDoc(sig, payloadOf(row, sig.kid))), link_secret: moving.secret }); continue; // moved on to a newer record meanwhile: look again } const fresh = { license_id: newLicenseId(), tier: "appliance", device, issued_at: now, engine_major: sig.major }; + const issuing = await newLinkSecret(); await env.DB.prepare(LICENSE_SQL.applianceInsert) - .bind(fresh.license_id, device, sig.kid, sig.major, now, id, iso(now)).run(); + .bind(fresh.license_id, device, sig.kid, sig.major, now, id, iso(now), issuing.hash).run(); row = await find(); - if (row?.license_id === fresh.license_id) return json(200, await licenseDoc(sig, payloadOf(fresh, sig.kid))); + if (row?.license_id === fresh.license_id) { + return json(200, { ...(await licenseDoc(sig, payloadOf(fresh, sig.kid))), link_secret: issuing.secret }); + } // Another request for this maker acceptance wrote its key first: answer as for that one. if (row) break; if (await deviceRevoked(env, device)) return fail(403, "revoked", REVOKED_DEVICE); @@ -788,6 +834,71 @@ async function license(request, env, now) { return renewLicense(env, sig, id, b.device, now); } +// --- /api/license/link: an appliance key's owner (teaport#465) ------------------------------- + +// A refusal of the link secret: 403, the same for a key that has none (issued before +// migrations/0005) as for one that does not match, so the answer says nothing more to whoever +// has only the public values (the key file's license_id and device). +const BAD_LINK = () => fail(403, "bad_link_secret", `this box's link secret does not match its license key: contact ${CONTACT}`); + +// Constant-time comparison of two lowercase hex digests of the same length. +function sameHex(a, b) { + if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); + return diff === 0; +} + +// The owner's acceptance, from the box's setup, recorded against the box's appliance key. Who +// may: the box itself, which alone holds the link secret (root's file; the key file holds +// none). Checked in this order, so that nothing about the key's records or the acceptance is +// told to a request without it: the key on record, an appliance key, bound to , its +// secret's hash (constant time); then the key neither revoked nor released; then the +// acceptance, as /api/token checks it (on record, not revoked, of its channel's current +// license). A link to the acceptance already linked changes nothing (changed: false); one to +// another moves it (a resale: the new owner sets the box up). Written in one statement that +// checks the key and the hash again, so a move meanwhile (a new secret) leaves it unlinked. +// Nothing is logged, and the answer carries neither secret nor email. +async function link(request, env, now) { + const b = await body(request); + if (!b) return fail(400, "bad_request", "expected a JSON object of at most 4 KB"); + for (const k of ["acceptance_id", "license_id", "device"]) { + if (typeof b[k] !== "string") return fail(400, "bad_request", "acceptance_id, license_id and device, each a string, with link_secret"); + } + if (MAKER_ID.test(b.acceptance_id)) return fail(400, "bad_request", "acceptance_id: the owner's acceptance, not a factory install record"); + if (!/^[A-Za-z0-9_-]{8,64}$/.test(b.acceptance_id)) return fail(400, "bad_request", "acceptance_id: the id the owner's acceptance was recorded under"); + if (!LICENSE_ID.test(b.license_id)) return fail(400, "bad_request", "license_id: the license_id of this box's license.json"); + if (!TPDEV2.test(b.device)) return fail(400, "bad_request", "device: this box's, from its license.json: tpdev2- and 32 lowercase hex digits"); + // No secret, or one that is not 32 bytes of base64url, is a wrong one: 403, as for one + // that does not match (a request with only the public values is refused as such). + let raw = null; + if (typeof b.link_secret === "string" && LINK_SECRET.test(b.link_secret)) { + try { raw = unb64url(b.link_secret); } catch { raw = null; } + } + const given = raw && raw.length === LINK_SECRET_BYTES ? await linkHash(raw) : null; + for (let i = 0; i < TRIES; i++) { + const row = await env.DB.prepare( + "SELECT tier, device, acceptance_id, link_secret_hash, revoked_at, released_at FROM licenses WHERE license_id = ?1").bind(b.license_id).first(); + if (!row) return fail(404, "unknown_license", "no license key is recorded under this id"); + if (row.tier !== "appliance") return fail(403, "not_appliance", "only a Teaport appliance's license key is linked to its owner here"); + if (row.device !== b.device) return fail(403, "device_mismatch", "this license key is bound to another device"); + if (!given || !row.link_secret_hash || !sameHex(given, row.link_secret_hash)) return BAD_LINK(); + if (row.revoked_at) return fail(403, "revoked", REVOKED_KEY); + if (row.released_at) return fail(403, "released", RELEASED_KEY); + const acc = await env.DB.prepare( + "SELECT channel, eula_version, eula_sha256, revoked_at FROM acceptances WHERE id = ?1").bind(b.acceptance_id).first(); + if (!acc) return fail(404, "unknown_acceptance", "no acceptance is recorded under this id: accept the license again"); + if (acc.revoked_at) return fail(403, "revoked", `this acceptance was revoked: contact ${CONTACT}`); + const stale = await eulaRefusal(env, acc, now); + if (stale) return stale; + if (row.acceptance_id === b.acceptance_id) return json(200, { license_id: b.license_id, linked: true, changed: false }); + const { meta } = await env.DB.prepare(LICENSE_SQL.link).bind(b.license_id, b.acceptance_id, b.device, row.link_secret_hash).run(); + if (meta.changes === 1) return json(200, { license_id: b.license_id, linked: true, changed: true }); + // Changed under it (revoked, released or moved meanwhile): look again. + } + return CONFLICT(); +} + // --- /dl ----------------------------------------------------------------------------------- const DENIED = "This file downloads only after the Teaport Engine License is accepted: install with " @@ -884,7 +995,8 @@ export default { const url = new URL(request.url); const now = Math.floor(Date.now() / 1000); const path = url.pathname; - if (path === "/api/accept" || path === "/api/token" || path === "/api/factory" || path === "/api/license") { + if (path === "/api/accept" || path === "/api/token" || path === "/api/factory" || path === "/api/license" + || path === "/api/license/link") { if (request.method !== "POST") return fail(405, "method_not_allowed", "POST only", { allow: "POST" }); if (env.ACCEPT_LIMIT) { const { success } = await env.ACCEPT_LIMIT.limit({ key: client(request).ip || "unknown" }); @@ -892,6 +1004,7 @@ export default { } if (path === "/api/factory") return factory(request, env, now); if (path === "/api/license") return license(request, env, now); + if (path === "/api/license/link") return link(request, env, now); return path === "/api/accept" ? accept(request, env, now) : token(request, env, now); } if (path.startsWith("/dl/engine/") || path.startsWith("/dl/models/")) { diff --git a/worker/test/license.test.mjs b/worker/test/license.test.mjs index d404f759..245d276d 100644 --- a/worker/test/license.test.mjs +++ b/worker/test/license.test.mjs @@ -10,7 +10,8 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "n import { tmpdir } from "node:os"; import { join } from "node:path"; import { DatabaseSync } from "node:sqlite"; -import worker, { LICENSE_SQL, PERSONAL_DAYS, PERSONAL_DEVICES, expire, resetCache } from "../src/index.js"; +import { createHash } from "node:crypto"; +import worker, { LICENSE_SQL, LINK_SECRET_BYTES, PERSONAL_DAYS, PERSONAL_DEVICES, expire, resetCache } from "../src/index.js"; import { armor, jcs, parsePubkeyLine, parseSshsig, pubkeyBlob, signedData, sshsigBlob } from "../src/sshsig.js"; import { MIGRATIONS, SHA, bucket, d1, manifest } from "./fakes.mjs"; @@ -74,12 +75,16 @@ async function maker(serial = "cd".repeat(32)) { // serial: the record's devic return (await res.json()).acceptance_id; } -// A 200 license.json, its signature checked: {payload, signature, blob}. +// A 200 license.json, its signature checked: {payload, signature}, and link_secret beside +// them when the answer has one (an appliance key's first issue, or a move). async function issued(body, key = KEY) { const res = await ask(body); assert.equal(res.status, 200, await res.clone().text()); const doc = await res.json(); - assert.deepEqual(Object.keys(doc).sort(), ["payload", "signature"]); + const keys = Object.keys(doc).sort(); + assert.ok(JSON.stringify(keys) === '["payload","signature"]' || JSON.stringify(keys) === '["link_secret","payload","signature"]', + JSON.stringify(keys)); + if ("link_secret" in doc) assert.match(doc.link_secret, /^[A-Za-z0-9_-]{43}$/); await assertSigned(doc, key); return doc; } @@ -457,9 +462,10 @@ test("an appliance key: with the maker id, no expiry, recorded against the maker test("one appliance key per maker acceptance: the same device gets it again, another is refused", async () => { const maker_id = await maker(); - const first = await issued({ maker_id, device: dev(7) }); + const { link_secret, ...first } = await issued({ maker_id, device: dev(7) }); + assert.ok(link_secret, "the first issue answers a link secret"); const again = await issued({ maker_id, device: dev(7) }); - assert.deepEqual(again, first, "the same terms, signed again (Ed25519 is deterministic)"); + assert.deepEqual(again, first, "the same terms, signed again (Ed25519 is deterministic), and no link secret"); const b = await err(await ask({ maker_id, device: dev(8) }), 403, "maker_device"); assert.match(b.message, /stefano@teaspoon\.tech/); // Asked at once, still one: the unique index holds it. @@ -761,7 +767,8 @@ test("the rate limit covers /api/license, before anything is read", async () => test("migration 0004 only adds: the tables before it keep their columns, and the Worker before it its statements", () => { const files = readdirSync(MIGRATIONS).filter((f) => f.endsWith(".sql")).sort(); - assert.deepEqual(files.slice(0, 4), ["0001_acceptances.sql", "0002_drop_acceptance_name.sql", "0003_factory.sql", "0004_licenses.sql"]); + assert.deepEqual(files.slice(0, 5), ["0001_acceptances.sql", "0002_drop_acceptance_name.sql", "0003_factory.sql", "0004_licenses.sql", + "0005_license_link.sql"]); const db = new DatabaseSync(":memory:"); for (const f of files.slice(0, 3)) db.exec(readFileSync(new URL(f, MIGRATIONS), "utf8")); const shape = () => ["acceptances", "downloads", "maker_acceptances"].map((t) => db.prepare(`PRAGMA table_info(${t})`).all()); @@ -792,9 +799,9 @@ test("the cap's statements, as the Worker runs them, start from the email index for (let i = 0; i < 500; i++) { ins.run(`acc${i}xxxxx`, `p${i}@example.com`); key.run(`TPL-${i}000`, dev(i % 250), `acc${i}xxxxx`); } assert.equal(db.prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'sqlite_stat1'").get().n, 0); const args = { counted: ["acc1xxxxx", 0, dev(1)], held: ["acc1xxxxx", dev(1)], revoked: [dev(1)], - applianceInsert: ["TPL-NEWA", dev(1), KID, 1, 0, "maker-x", "x"], resign: ["TPL-1000", KID, "x", dev(1)], - applianceMove: ["maker-x", KID, "x", dev(1)], applianceHeld: ["maker-x", dev(1)], - spent: ["maker-x"], + applianceInsert: ["TPL-NEWA", dev(1), KID, 1, 0, "maker-x", "x", "h"], resign: ["TPL-1000", KID, "x", dev(1)], + applianceMove: ["maker-x", KID, "x", dev(1), "h"], applianceHeld: ["maker-x", dev(1)], + spent: ["maker-x"], link: ["TPL-1000", "acc1xxxxx", dev(1), "h"], insert: ["TPL-NEW0", dev(1), KID, 1, 0, 1, "acc1xxxxx", "x", 3], renew: ["TPL-1000", "acc1xxxxx", 0, 1, 1, KID, "x", dev(1), 3] }; assert.deepEqual(Object.keys(LICENSE_SQL).sort(), Object.keys(args).sort()); @@ -804,7 +811,7 @@ test("the cap's statements, as the Worker runs them, start from the email index assert.ok(!plan.some((d) => /^SCAN (l|licenses)\b/.test(d)), `${name} reads every key:\n${text}`); assert.ok(!plan.some((d) => /^SCAN a\b/.test(d)), `${name} reads every acceptance:\n${text}`); assert.ok(!plan.some((d) => /^SCAN d\b/.test(d)), `${name} reads every key:\n${text}`); - if (!["revoked", "applianceInsert", "resign", "applianceMove", "applianceHeld", "spent"].includes(name)) { + if (!["revoked", "applianceInsert", "resign", "applianceMove", "applianceHeld", "spent", "link"].includes(name)) { assert.match(text, /SEARCH a USING INDEX acceptances_email_norm/, name); assert.match(text, /SEARCH l USING INDEX licenses_acceptance/, name); } @@ -834,3 +841,210 @@ test("the retention cron deletes a personal key's row once it has been expired R await expire(env, now + 100 * 365 * 86400); assert.deepEqual(rows().map((r) => r.tier), ["appliance"]); }); + +// --- the link secret and POST /api/license/link (teaport#465) -------------------------------- + +const sha256hex = (b64u) => createHash("sha256").update(Buffer.from(b64u, "base64url")).digest("hex"); +const linkCall = (body) => call("POST", "/api/license/link", { body }); +const otherSecret = () => Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url"); +const row = (license_id) => ({ ...env.DB.db.prepare("SELECT * FROM licenses WHERE license_id = ?").get(license_id) }); + +// A factory box: its maker acceptance and appliance key, {license_id, device, link_secret}. +async function applianceBox(device = dev(7), serial = "cd".repeat(32)) { + const doc = await issued({ maker_id: await maker(serial), device }); + return { license_id: doc.payload.license_id, device, link_secret: doc.link_secret }; +} + +async function linked(body) { + const res = await linkCall(body); + assert.equal(res.status, 200, await res.clone().text()); + return res.json(); +} + +test("an appliance key's first issue answers a link secret, kept only as its SHA-256; asked again or renewed, none", async () => { + const maker_id = await maker(); + const first = await issued({ maker_id, device: dev(7) }); + assert.equal(Buffer.from(first.link_secret, "base64url").length, LINK_SECRET_BYTES); + assert.equal(LINK_SECRET_BYTES, 32); + const r = row(first.payload.license_id); + assert.equal(r.link_secret_hash, sha256hex(first.link_secret)); + assert.ok(!Object.values(r).includes(first.link_secret), "the secret itself is in no column"); + assert.ok(!JSON.stringify(env.DB.db.prepare("SELECT * FROM license_makers").all()).includes(first.link_secret)); + // The same record again, and a renewal: the key, no secret, and the hash unchanged. + assert.ok(!("link_secret" in await issued({ maker_id, device: dev(7) }))); + assert.ok(!("link_secret" in await issued({ license_id: first.payload.license_id, device: dev(7) }))); + assert.equal(row(first.payload.license_id).link_secret_hash, r.link_secret_hash); + // Personal keys have none. + const p = await issued({ acceptance_id: await accepted(), device: dev(1) }); + assert.ok(!("link_secret" in p)); + assert.equal(row(p.payload.license_id).link_secret_hash, null); + // Two boxes, two secrets. + const other = await applianceBox(dev(8), "ee".repeat(32)); + assert.notEqual(other.link_secret, first.link_secret); +}); + +test("a link records the owner's acceptance against the appliance key; the same one again changes nothing; another moves it", async () => { + const box = await applianceBox(); + const ada = await accepted(); + assert.deepEqual(await linked({ acceptance_id: ada, ...box }), { license_id: box.license_id, linked: true, changed: true }); + assert.equal(row(box.license_id).acceptance_id, ada); + const before = JSON.stringify(rows()); + assert.deepEqual(await linked({ acceptance_id: ada, ...box }), { license_id: box.license_id, linked: true, changed: false }); + assert.equal(JSON.stringify(rows()), before, "nothing written"); + // A resale: the new owner's acceptance replaces the old link. + const grace = await accepted({ email: "grace@example.com" }); + assert.equal((await linked({ acceptance_id: grace, ...box })).changed, true); + assert.equal(row(box.license_id).acceptance_id, grace); + // The key's terms and its other records are untouched, and it still renews. + const r = row(box.license_id); + assert.deepEqual([r.tier, r.device, r.revoked_at, r.released_at, r.expires_at], ["appliance", box.device, null, null, null]); + await issued({ license_id: box.license_id, device: box.device }); +}); + +test("a link with only the public values, or a wrong secret, gets 403 and writes nothing", async () => { + const box = await applianceBox(); + const other = await applianceBox(dev(8), "ee".repeat(32)); + const acceptance_id = await accepted({ email: "mallory@example.com" }); + const before = JSON.stringify(rows()); + const { link_secret, ...pub } = box; + for (const secret of [undefined, null, "", 12345, otherSecret(), other.link_secret, link_secret.slice(0, 42), + `${link_secret}A`, link_secret.replace(/^./, (c) => (c === "A" ? "B" : "A")), "!".repeat(43), + Buffer.from(link_secret, "base64url").toString("hex"), sha256hex(link_secret)]) { + const body = { acceptance_id, ...pub, ...(secret === undefined ? {} : { link_secret: secret }) }; + const b = await err(await linkCall(body), 403, "bad_link_secret"); + assert.match(b.message, /stefano@teaspoon\.tech/); + } + // The secret is checked before the acceptance: a request without it learns nothing of it. + await err(await linkCall({ ...pub, acceptance_id: "nosuchacceptance" }), 403, "bad_link_secret"); + assert.equal(JSON.stringify(rows()), before); + await linked({ acceptance_id, ...box }); // the box itself can +}); + +test("a box provisioned again gets a new link secret: the old one gets 403 after the move, the new one links", async () => { + const [m1, m2] = await makers(3600, 60); + const first = await issued({ maker_id: m1, device: dev(7) }); + const ada = await accepted(); + const box = { license_id: first.payload.license_id, device: dev(7) }; + await linked({ acceptance_id: ada, ...box, link_secret: first.link_secret }); + const moved = await issued({ maker_id: m2, device: dev(7) }); + assert.equal(moved.payload.license_id, box.license_id, "the same key"); + assert.notEqual(moved.link_secret, first.link_secret); + assert.equal(row(box.license_id).link_secret_hash, sha256hex(moved.link_secret)); + // The box's previous life's secret links nothing now, not even to its old owner. + const grace = await accepted({ email: "grace@example.com" }); + await err(await linkCall({ acceptance_id: grace, ...box, link_secret: first.link_secret }), 403, "bad_link_secret"); + await err(await linkCall({ acceptance_id: ada, ...box, link_secret: first.link_secret }), 403, "bad_link_secret"); + assert.equal(row(box.license_id).acceptance_id, ada, "the old link stands until the new owner links"); + assert.equal((await linked({ acceptance_id: grace, ...box, link_secret: moved.link_secret })).changed, true); + assert.equal(row(box.license_id).acceptance_id, grace); + // The older record asking again gets no secret (it gets no key at all). + await err(await ask({ maker_id: m1, device: dev(7) }), 409, "maker_superseded"); +}); + +test("the acceptance must be on record, not revoked, and of the current license", async () => { + const box = await applianceBox(); + const acceptance_id = await accepted(); + const before = JSON.stringify(rows()); + await err(await linkCall({ ...box, acceptance_id: "nosuchacceptance" }), 404, "unknown_acceptance"); + await err(await linkCall({ ...box, acceptance_id: `maker-${"x".repeat(24)}` }), 400, "bad_request"); + env.PUBLIC.objects.set("manifest/stable.json", manifest("2.0", "d".repeat(64))); + resetCache(); + const b = await err(await linkCall({ ...box, acceptance_id }), 409, "eula_changed"); + assert.deepEqual([b.eula_version, b.eula_sha256], ["2.0", "d".repeat(64)]); + env.PUBLIC.objects.set("manifest/stable.json", manifest()); + resetCache(); + env.DB.db.prepare("UPDATE acceptances SET revoked_at = 'now'").run(); + await err(await linkCall({ ...box, acceptance_id }), 403, "revoked"); + assert.equal(JSON.stringify(rows()), before); + // A licensed acceptance (the appliance's own license id) links like any other. + const licensed = await accepted({ use: "licensed", license_id: box.license_id }); + assert.equal((await linked({ ...box, acceptance_id: licensed })).changed, true); +}); + +test("the key must be an unrevoked, unreleased appliance key, on that device, with a secret", async () => { + const box = await applianceBox(); + const acceptance_id = await accepted(); + await err(await linkCall({ acceptance_id, ...box, device: dev(8) }), 403, "device_mismatch"); + await err(await linkCall({ acceptance_id, ...box, license_id: "TPL-NOSUCHLICENSE0000" }), 404, "unknown_license"); + const personal = (await issued({ acceptance_id, device: dev(1) })).payload; + await err(await linkCall({ acceptance_id, license_id: personal.license_id, device: dev(1), link_secret: box.link_secret }), 403, "not_appliance"); + env.DB.db.prepare("UPDATE licenses SET revoked_at = 'now' WHERE license_id = ?").run(box.license_id); + await err(await linkCall({ acceptance_id, ...box }), 403, "revoked"); + env.DB.db.prepare("UPDATE licenses SET revoked_at = NULL, released_at = 'now' WHERE license_id = ?").run(box.license_id); + await err(await linkCall({ acceptance_id, ...box }), 403, "released"); + // A key issued before migration 0005 has no secret: it links only by hand. + env.DB.db.prepare("UPDATE licenses SET released_at = NULL, link_secret_hash = NULL WHERE license_id = ?").run(box.license_id); + await err(await linkCall({ acceptance_id, ...box }), 403, "bad_link_secret"); + assert.equal(row(box.license_id).acceptance_id, null); + for (const bad of [{}, { ...box }, { acceptance_id, ...box, license_id: "tpl-lower" }, { acceptance_id, ...box, device: "ab".repeat(16) }, + { acceptance_id: 12345678, license_id: box.license_id, device: box.device, link_secret: box.link_secret }, + { acceptance_id: "short", ...box }]) { + await err(await linkCall(bad), 400, "bad_request"); + } + assert.equal((await call("GET", "/api/license/link")).status, 405); +}); + +test("a move between the check and the write leaves the key unlinked: its secret is no longer the box's", async () => { + const [m1, m2] = await makers(3600, 60); + const first = await issued({ maker_id: m1, device: dev(7) }); + const box = { license_id: first.payload.license_id, device: dev(7), link_secret: first.link_secret }; + const acceptance_id = await accepted(); + const real = env.DB; + let moved = null; + env.DB = { db: real.db, prepare(sql) { + // The box provisioned again while the link is under way: just before its write. + if (sql === LICENSE_SQL.link && !moved) { + moved = "pending"; + return { bind(...a) { this.a = a; return this; }, + async run() { env.DB = real; moved = await issued({ maker_id: m2, device: dev(7) }); env.DB = wrapper; return real.prepare(sql).bind(...this.a).run(); } }; + } + return real.prepare(sql); + } }; + const wrapper = env.DB; + await err(await linkCall({ acceptance_id, ...box }), 403, "bad_link_secret"); + env.DB = real; + assert.equal(row(box.license_id).acceptance_id, null); + assert.equal((await linked({ acceptance_id, ...box, link_secret: moved.link_secret })).changed, true); +}); + +test("the rate limit covers /api/license/link, before anything is read; the Worker logs nothing", async () => { + const box = await applianceBox(); + const acceptance_id = await accepted(); + const logged = []; + const saved = {}; + for (const k of ["log", "info", "warn", "error", "debug"]) { saved[k] = console[k]; console[k] = (...a) => logged.push(a); } + try { + await linked({ acceptance_id, ...box }); + await err(await linkCall({ acceptance_id, ...box, link_secret: otherSecret() }), 403, "bad_link_secret"); + } finally { + Object.assign(console, saved); + } + assert.deepEqual(logged, []); + env.ACCEPT_LIMIT = { async limit() { return { success: false }; } }; + const touched = []; + env.DB = { prepare(sql) { touched.push(sql); throw new Error("D1 read after the rate limit"); } }; + const request = new Request("https://get.teaspoon.tech/api/license/link", { + method: "POST", headers: { "cf-connecting-ip": "203.0.113.7" }, body: JSON.stringify({ acceptance_id, ...box }) }); + await err(await worker.fetch(request, env, ctx), 429, "rate_limited"); + assert.equal(request.bodyUsed, false); + assert.deepEqual(touched, []); +}); + +test("migration 0005 only adds licenses.link_secret_hash: the tables keep their columns, and the Worker before it its statements", () => { + const files = readdirSync(MIGRATIONS).filter((f) => f.endsWith(".sql")).sort(); + const db = new DatabaseSync(":memory:"); + for (const f of files.slice(0, 4)) db.exec(readFileSync(new URL(f, MIGRATIONS), "utf8")); + const shape = (t) => db.prepare(`PRAGMA table_info(${t})`).all().map((c) => ({ ...c })); + const tables = ["acceptances", "downloads", "maker_acceptances", "licenses", "license_makers"]; + const old = Object.fromEntries(tables.map((t) => [t, shape(t)])); + db.exec(readFileSync(new URL(files[4], MIGRATIONS), "utf8")); + for (const t of tables.filter((x) => x !== "licenses")) assert.deepEqual(shape(t), old[t], t); + const now = shape("licenses"); + assert.deepEqual(now.slice(0, -1), old.licenses); + assert.deepEqual([now.at(-1).name, now.at(-1).type, now.at(-1).notnull, now.at(-1).dflt_value], ["link_secret_hash", "TEXT", 0, null]); + // The Worker before it: an appliance key written without the column, and moved. + db.prepare(`INSERT INTO licenses (license_id, tier, device, kid, engine_major, issued_at, maker_id, first_maker_id, created_at, signed_at) + VALUES ('TPL-A', 'appliance', 'tpdev2-x', 'k', 1, 0, 'm', 'm', 'x', 'x')`).run(); + db.prepare("UPDATE licenses SET maker_id = 'n' WHERE license_id = 'TPL-A'").run(); + assert.equal(db.prepare("SELECT link_secret_hash FROM licenses").get().link_secret_hash, null); +}); From 870fa03f2e409b18707b26271708e22b1bcf707a Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Sat, 28 Nov 2026 21:58:07 -0600 Subject: [PATCH 02/33] Worker tests: the acceptance a box's setup makes is taken, and links (#465) license_accept.py records the owner's acceptance with method tty (the CHECK of acceptances.method takes tty or flag only), installer setup:git:, the appliance serial's hash as device_id, and licensed use under the box's appliance key. Co-Authored-By: Claude Opus 5.5 --- worker/test/license.test.mjs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/worker/test/license.test.mjs b/worker/test/license.test.mjs index 245d276d..737ab542 100644 --- a/worker/test/license.test.mjs +++ b/worker/test/license.test.mjs @@ -941,6 +941,17 @@ test("a box provisioned again gets a new link secret: the old one gets 403 after await err(await ask({ maker_id: m1, device: dev(7) }), 409, "maker_superseded"); }); +test("the acceptance the box's setup makes (license_accept.py) is taken, and links", async () => { + // method tty (acceptances.method's CHECK takes tty or flag), installer "setup:" and the + // brain's revision, the appliance serial's hash as device_id, licensed under the box's key. + const box = await applianceBox(); + const acceptance_id = await accepted({ installer: "setup:git:0123abcd", use: "licensed", license_id: box.license_id, + device_id: createHash("sha256").update("teaport-appliance:TP-20261128-0042").digest("hex") }); + const a = { ...env.DB.db.prepare("SELECT method, installer, use_type, license_id FROM acceptances WHERE id = ?").get(acceptance_id) }; + assert.deepEqual(a, { method: "tty", installer: "setup:git:0123abcd", use_type: "licensed", license_id: box.license_id }); + assert.equal((await linked({ acceptance_id, ...box })).changed, true); +}); + test("the acceptance must be on record, not revoked, and of the current license", async () => { const box = await applianceBox(); const acceptance_id = await accepted(); From e6f773171663a9c92e1e8821de88dd6cdd3bb89e Mon Sep 17 00:00:00 2001 From: teaspoonai Date: Sat, 28 Nov 2026 21:58:07 -0600 Subject: [PATCH 03/33] Box: the owner's license helpers, to record and link their acceptance (#465) license_accept.py (root, behind sudo) takes the owner's email and the SHA-256 of the text the page showed, never an acceptance id. It makes POST /api/accept itself and records the returned id in install.sh's own receipt, /var/lib/teaport/eula-accepted.json ("method": "setup"), so later runs get tokens from it. Offline it queues the email in a root-owned /var/lib/teaport/eula-queued.json and sends it once online. It works only while provisioning's marker /var/lib/teaport-owner/license-pending is there, and once: a recorded or queued acceptance is never replaced. Device id: the appliance serial's hash on a factory box, the machine id's elsewhere. license_link.py (root) takes nothing: it reads the record, license.json and /etc/teaport/license-link.secret (root 0600) and calls POST /api/license/link. For the run user only while setup is unfinished: the Settings session cannot be verified (its key is in brain.env, which the run user reads); root and an administrator through sudo may always. A link removes the marker; a re-link of the same acceptance sends nothing; no secret file: logged, nothing done. teaport-license-owner.timer (enabled by the package) runs both as root after boot and every 15 minutes, only while a queue or the marker is there. sudoers-sync writes a line for each helper (NOLOG_INPUT for the email). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 +- brain/teaport_brain/license_accept.py | 512 ++++++++++++++++++++ brain/teaport_brain/license_link.py | 394 +++++++++++++++ brain/tests/test_license_accept.py | 470 ++++++++++++++++++ brain/tests/test_license_link.py | 304 ++++++++++++ brain/tests/test_update_apply.py | 12 +- brain/tests/test_wifi_apply.py | 7 +- packaging/deb/postinst | 3 + packaging/deb/sudoers-sync | 21 +- packaging/deb/teaport-license-owner.service | 21 + packaging/deb/teaport-license-owner.timer | 17 + packaging/nfpm.yaml | 39 ++ 12 files changed, 1796 insertions(+), 9 deletions(-) create mode 100644 brain/teaport_brain/license_accept.py create mode 100644 brain/teaport_brain/license_link.py create mode 100644 brain/tests/test_license_accept.py create mode 100644 brain/tests/test_license_link.py create mode 100644 packaging/deb/teaport-license-owner.service create mode 100644 packaging/deb/teaport-license-owner.timer diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 602ad80b..57732619 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -148,12 +148,15 @@ jobs: /opt/teaport/brain/bin/teaport-brain --help >/dev/null test -x /usr/bin/teaport && bash -n /usr/bin/teaport # compile(), not py_compile: that would write a __pycache__ beside the helper. - for p in /usr/lib/teaport/config_apply.py /usr/lib/teaport/update_apply.py /usr/lib/teaport/wifi_apply.py /usr/lib/teaport/login_apply.py; do + for p in /usr/lib/teaport/config_apply.py /usr/lib/teaport/update_apply.py /usr/lib/teaport/wifi_apply.py /usr/lib/teaport/login_apply.py /usr/lib/teaport/license_accept.py /usr/lib/teaport/license_link.py; do /usr/bin/python3 -I -c 'import sys; p = sys.argv[1]; compile(open(p).read(), p, "exec")' "$p" done # The update's unit, as systemd reads it (it is static: nothing enables it). systemd-analyze verify /usr/lib/systemd/system/teaport-update.service [ "$(systemctl show -p UnitFileState --value teaport-update.service)" = static ] + # The owner's license retry (#465): enabled by the package's own link. + systemd-analyze verify /usr/lib/systemd/system/teaport-license-owner.service /usr/lib/systemd/system/teaport-license-owner.timer + [ "$(readlink /usr/lib/systemd/system/timers.target.wants/teaport-license-owner.timer)" = /usr/lib/systemd/system/teaport-license-owner.timer ] - name: dpkg -V is clean, and the package owns every file under its root run: | out="$(dpkg -V teaport-brain)" diff --git a/brain/teaport_brain/license_accept.py b/brain/teaport_brain/license_accept.py new file mode 100644 index 00000000..606f26cc --- /dev/null +++ b/brain/teaport_brain/license_accept.py @@ -0,0 +1,512 @@ +# +# teaport — the owner's acceptance of the Teaport Engine License at setup (#465): the one +# way the run user can have the box record who accepted it. As root, behind sudo. +# +# A factory box ships with its engine installed under Teaspoon AI's maker record and its +# appliance key (#464, #474), and no one's acceptance of the license: its owner accepts it +# at setup, on the setup page (wifi_setup.py, offline) or in Settings (config_ui.py, +# online), both through owner_license.py. This helper records that acceptance, and nothing +# else. The run user is the agent's (#416, #418): it may ask, never decide. So: +# - it takes the owner's email and nothing else that says who accepted: never an +# acceptance id (a request that names one, or anything not listed below, is refused). +# It makes POST /accept itself and records the id the license server returns, so +# the record can only ever name an acceptance made here, with the email the owner typed; +# - it works only while setup is unfinished: while provisioning's marker (GATE_PATH, in +# the same root-only directory as the login's, login_apply.py) is there, and only once: +# an acceptance recorded (RECORD_PATH) or queued (QUEUE_PATH) is never replaced through +# it. After setup the acceptance changes only through a new setup (a resale: the box is +# reset, its record removed and the marker written again), or through support; +# - the text the owner accepts is the one the page showed: the page names its SHA-256 +# (eula_sha256), and the helper refuses it unless it is the current license's, read +# from the channel's manifest and checked against it (text). +# The record is install.sh's own receipt, /var/lib/teaport/eula-accepted.json (root's, +# 0600): a later `install.sh` or `teaport update` gets its download tokens with it, as from +# an acceptance made at the installer. Never the run user's $STATE: the record is what the +# link helper (license_link.py) puts on the box's license key, so the run user must not be +# able to write it. Beside it, the accepted text (EULA-v.txt, 0644), as install.sh +# keeps it. +# +# Offline (the setup page has no internet: the box is not on the owner's network yet), the +# email waits in QUEUE_PATH, root's 0600, and this helper sends it itself when the box is +# next online: `flush`, which teaport-license-owner.timer runs as root (OnBootSec, then every +# few minutes, only while a queue or the marker is there). A timer, not NetworkManager's +# dispatcher or the brain's own online watcher (first_boot.py): the watcher runs as the run +# user, and a dispatcher hook runs once per event while a POST can fail for a reason that +# lasts (the license server busy, a captive network): it needs a retry either way, and a +# timer is that retry, from boot, whatever brought the box online. A queued acceptance the +# server refuses for good (the license changed meanwhile: 409 eula_changed; or a request it +# does not take) is dropped, and the setup step is offered again; anything else stays queued. +# +# Which device: a factory box (/etc/appliance-id, the serial the station assigned) sends +# SHA-256 of "teaport-appliance:" and its serial, as the station's maker record does +# (docs/engine-license-data.md), so the owner's acceptance and the maker's match; any other +# box, SHA-256 of "teaport-device:" and its machine id, as install.sh sends. Which use: a box +# with an appliance key (/etc/teaport/license.json, tier "appliance") is used under that key's +# license, so "licensed" with its license_id; any other, "personal". Method: "tty", as an +# acceptance read and made at the installer's prompt (the license server's acceptances.method +# takes tty or flag only, a CHECK that only a table rebuild could widen), and the installer +# field says where: "setup:" and the brain's revision. The box's own record says "setup". +# +# Verbs (the only argument; the request is a JSON object on stdin, the reply one on stdout; +# a request this does not do gets {"refused": why, "why": code} and exit 2): +# status {state}: PENDING (setup unfinished, nothing accepted), QUEUED, RECORDED (an +# acceptance is on the box, the installer's included), NOT_OFFERED (no marker: +# a box no provisioning marked, or a setup that finished); +# text {version, sha256, text}: the license to accept now, only while the marker is +# there: from the channel's manifest (the installed one when offline) and the text +# kept on the box, or downloaded and checked against the manifest's SHA-256; +# accept {email, eula_sha256} -> {ok, state}: RECORDED, or QUEUED (offline); +# flush {} -> {ok, state}: a queued acceptance sent, if there is one (while the marker +# is there). +# The email reaches the license server, the queue and the record, and nothing else: no +# reply, no log line, no error carries it. Nothing here writes, renames or removes +# PROTECTED (the engine's license files, teaport#474 F1). +# +# Run as the sudoers line (packaging/deb/sudoers-sync) names it: +# /usr/bin/python3 /usr/lib/teaport/license_accept.py +# the root-owned copy the teaport-brain package ships, on the SYSTEM python, never the +# venv's (like login_apply.py). Standard library only. Tests run it in-process (handle()) +# against a pretend license server and a temporary tree (Box). +# +import hashlib +import json +import os +import re +import stat +import sys +import tempfile +import time +import urllib.error +import urllib.request + +STATE_DIR = "/var/lib/teaport" +RECORD_PATH = STATE_DIR + "/eula-accepted.json" # install.sh's EULA_RECEIPT +QUEUE_PATH = STATE_DIR + "/eula-queued.json" +# Setup is unfinished while this is there: provisioning writes it at seal (beside the +# login's pending marker, Teaspoon-AI/teaport-appliance#3), the link helper removes it once +# the owner's acceptance is on the box's key (license_link.py). Nothing in this package +# writes it. +GATE_PATH = "/var/lib/teaport-owner/license-pending" +INSTALLED_MANIFEST = "/opt/teaport/manifest.json" +MANIFEST_BASE = "https://get.teaspoon.tech/manifest" +APPLIANCE_ID = "/etc/appliance-id" +MACHINE_ID = "/etc/machine-id" +LICENSE_PATH = "/etc/teaport/license.json" +BUILD_RECORD = "/opt/teaport/brain/teaport-build.json" +# The engine's license files (teaport#474 F1): no root helper the run user reaches writes, +# renames or removes them. The same tuple in every one of them (tests hold them equal). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") +CHANNELS = ("stable", "beta") +MAX_REQUEST = 4096 +MAX_MANIFEST = 1 << 20 +MAX_TEXT = 1 << 20 +NET_SECS = 20 +# The license server's own rule for an email (worker/src/index.js accept()), so a typo is +# the page's to show, not a queued request the server later refuses. +EMAIL = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") +CONTROL = re.compile(r"[\x00-\x1f\x7f]") +ACCEPTANCE_ID = re.compile(r"[A-Za-z0-9_-]{8,64}") +LICENSE_ID = re.compile(r"[A-Za-z0-9._:-]{1,100}") +# status's answers. +PENDING, QUEUED, RECORDED, NOT_OFFERED = "pending", "queued", "recorded", "not_offered" +# Why a request was refused, as codes; owner_license.py turns them into the words people see. +REFUSED, ACCEPTED, EMAIL_BAD, CHANGED, UNAVAILABLE, DROPPED, FAILED = ( + "refused", "accepted", "email", "changed", "unavailable", "dropped", "failed") +# What each verb takes: nothing else, an acceptance id least of all. +FIELDS = {"status": set(), "text": set(), "accept": {"email", "eula_sha256"}, "flush": set()} + + +class Refused(Exception): + """A request this helper does not do. `why` is one of the codes above.""" + + def __init__(self, text: str, why: str = REFUSED): + super().__init__(text) + self.why = why + + +def guard(path: str) -> str: + """`path`, unless it is one of PROTECTED, by name or through a link (teaport#474 F1).""" + if os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED: + raise Refused(f"{path} is the engine's license, which this helper never writes") + return path + + +class Marker: + """Provisioning's marker: there, and root's alone (login_apply.Marker's rule): one in a + directory the run user can write, or a file that is not root's or is a link, is none.""" + + def __init__(self, path: str = GATE_PATH, owner: int = 0): + self.path, self.owner = path, owner + + def _roots(self, st: os.stat_result, kind) -> bool: + return kind(st.st_mode) and st.st_uid == self.owner and not st.st_mode & 0o022 + + def present(self) -> bool: + try: + directory = os.lstat(os.path.dirname(self.path)) + marker = os.lstat(self.path) + except FileNotFoundError: + return False + return self._roots(directory, stat.S_ISDIR) and self._roots(marker, stat.S_ISREG) + + +def _no_redirect(): + """An opener that follows no redirect: every URL here is https and named by the + manifest, and a redirect would let whoever answers send the email elsewhere.""" + class Refuse(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + return urllib.request.build_opener(Refuse) + + +def fetch(url: str, body: dict | None = None, limit: int = MAX_MANIFEST) -> tuple[int, bytes]: + """GET `url`, or POST `body` as JSON: (status, at most `limit` bytes of the answer); + status 0 when there is no answer (offline, a timeout, a URL that is not https).""" + if not url.startswith("https://"): + return 0, b"" + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method="POST" if data is not None else "GET", + headers={"content-type": "application/json", + "user-agent": "teaport-license-accept"}) + try: + with _no_redirect().open(req, timeout=NET_SECS) as r: # noqa: S310 -- https only + return r.status, r.read(limit + 1)[:limit] + except urllib.error.HTTPError as e: + try: + return e.code, e.read(limit) + except OSError: + return e.code, b"" + except (OSError, ValueError): + return 0, b"" + + +class Box: + """Where this helper reads and writes, and how it reaches the network (a test's own).""" + + def __init__(self, state_dir: str = STATE_DIR, gate: Marker | None = None, + installed_manifest: str = INSTALLED_MANIFEST, appliance_id: str = APPLIANCE_ID, + machine_id: str = MACHINE_ID, license_path: str = LICENSE_PATH, + build_record: str = BUILD_RECORD, net=fetch, now=time.time): + self.state_dir, self.gate = state_dir, gate or Marker() + self.record = os.path.join(state_dir, os.path.basename(RECORD_PATH)) + self.queue = os.path.join(state_dir, os.path.basename(QUEUE_PATH)) + self.installed_manifest, self.appliance_id = installed_manifest, appliance_id + self.machine_id, self.license_path, self.build_record = machine_id, license_path, build_record + self.net, self.now = net, now + + def text_path(self, version: str) -> str: + return os.path.join(self.state_dir, f"EULA-v{version}.txt") + + +# ------------------------------------------------------------------ files + +def _read_json(path: str, limit: int = MAX_MANIFEST) -> dict | None: + """A JSON object from a regular file (not a link), else None.""" + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return None + data = json.loads(f.read(limit + 1)[:limit]) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def _read_text(path: str) -> str | None: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as f: + return f.read(MAX_TEXT + 1)[:MAX_TEXT].decode("utf-8") if stat.S_ISREG(os.fstat(f.fileno()).st_mode) else None + except (OSError, ValueError): + return None + + +def write_file(path: str, data: bytes, mode: int) -> None: + """`data` into `path`, whole or not at all: a temporary file of root's own in the same + directory (made root's 0755 if it is not there), at `mode` before a byte is written, + synced, renamed into place, and the directory synced.""" + guard(path) + directory = os.path.dirname(path) + os.makedirs(directory, mode=0o755, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=directory, prefix="." + os.path.basename(path) + ".") + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + dfd = os.open(directory, os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + + +def _remove(path: str) -> None: + guard(path) + try: + os.unlink(path) + except FileNotFoundError: + pass + + +# ------------------------------------------------------------------ what the box is + +def device_id(box: Box) -> str: + """Which device the acceptance names (the module comment): the appliance serial's hash + on a factory box, the machine id's elsewhere; "" when the box has neither.""" + serial = _read_text(box.appliance_id) + if serial is not None: + serial = serial[:-1] if serial.endswith("\n") else serial + if serial and not re.search(r"\s", serial) and not CONTROL.search(serial): + return hashlib.sha256(f"teaport-appliance:{serial}".encode()).hexdigest() + machine = re.sub(r"\s", "", _read_text(box.machine_id) or "") + return hashlib.sha256(f"teaport-device:{machine}".encode()).hexdigest() if machine else "" + + +def use_of(box: Box) -> tuple[str, str | None]: + """("licensed", the appliance key's license_id) for a box with an appliance key, else + ("personal", None). Only the key's id and tier are read: it is never written here.""" + doc = _read_json(box.license_path, limit=64 * 1024) or {} + payload = doc.get("payload") if isinstance(doc.get("payload"), dict) else {} + lid = payload.get("license_id") + if payload.get("tier") == "appliance" and isinstance(lid, str) and LICENSE_ID.fullmatch(lid): + return "licensed", lid + return "personal", None + + +def installer(box: Box) -> str: + """Where the acceptance was made, for its `installer` (the license server's rule: at + most 64 of [A-Za-z0-9._:+-]): the setup page, and the brain's revision.""" + rev = (_read_json(box.build_record) or {}).get("revision") + if isinstance(rev, str) and re.fullmatch(r"[0-9a-f]{7,40}(-dirty)?", rev): + return f"setup:git:{rev}"[:64] + return "setup:unknown" + + +def _eula_of(manifest: dict) -> dict | None: + """{channel, version, url, sha256, api} of a manifest's license and license server; None + when it has no released license, or names a server or text that is not https.""" + e = (manifest.get("engine") or {}).get("eula") if isinstance(manifest.get("engine"), dict) else None + api = (manifest.get("access") or {}).get("api") if isinstance(manifest.get("access"), dict) else None + if not isinstance(e, dict) or not isinstance(api, str) or not api.startswith("https://"): + return None + version, url, sha = e.get("version"), e.get("url"), e.get("sha256") + if not (isinstance(version, str) and re.fullmatch(r"[A-Za-z0-9._-]{1,32}", version) + and isinstance(url, str) and url.startswith("https://") and "TODO" not in url + and isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{64}", sha)): + return None + channel = manifest.get("channel") if manifest.get("channel") in CHANNELS else "stable" + return {"channel": channel, "version": version, "url": url, "sha256": sha, "api": api.rstrip("/")} + + +def current(box: Box) -> dict | None: + """The license to accept now (_eula_of): the channel's manifest, else (offline) the + installed one's.""" + installed = _read_json(box.installed_manifest) or {} + channel = installed.get("channel") if installed.get("channel") in CHANNELS else "stable" + status, data = box.net(f"{MANIFEST_BASE}/{channel}.json") + if status == 200: + try: + fresh = _eula_of(json.loads(data)) + except ValueError: + fresh = None + if fresh: + return fresh + return _eula_of(installed) + + +def license_text(box: Box, eula: dict) -> str | None: + """The text of `eula`, checked against its SHA-256: the copy on the box, else downloaded + and kept there (0644, as install.sh keeps it); None when neither can be had.""" + path = box.text_path(eula["version"]) + try: + with open(path, "rb") as f: + data = f.read(MAX_TEXT + 1) + except OSError: + data = None + if data is None or hashlib.sha256(data).hexdigest() != eula["sha256"]: + status, data = box.net(eula["url"], limit=MAX_TEXT) + if status != 200 or hashlib.sha256(data).hexdigest() != eula["sha256"]: + return None + write_file(path, data, 0o644) + try: + return data.decode("utf-8") + except ValueError: + return None + + +# ------------------------------------------------------------------ the record + +def recorded(box: Box) -> dict | None: + """The acceptance on the box: a receipt with an acceptance id that is not the factory's + (install.sh's, or this helper's), else None.""" + r = _read_json(box.record) + if not r or r.get("method") == "factory": + return None + aid = r.get("acceptance_id") + return r if isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-") else None + + +def state(box: Box) -> str: + if recorded(box): + return RECORDED + if not box.gate.present(): + return NOT_OFFERED + return QUEUED if _read_json(box.queue) else PENDING + + +def send(box: Box) -> str: + """The queued acceptance, sent: RECORDED (the record written, the queue gone), QUEUED + (no answer, or one that may change: it waits), or DROPPED (refused for good: the queue + goes, and the step is offered again).""" + q = _read_json(box.queue) + if not q: + return RECORDED if recorded(box) else PENDING + body = {"channel": q.get("channel"), "eula_version": q.get("version"), "eula_sha256": q.get("sha256"), + "email": q.get("email"), "use": q.get("use"), "device_id": q.get("device_id") or None, + "method": "tty", "installer": q.get("installer")} + if q.get("use") == "licensed": + body["license_id"] = q.get("license_id") + status, data = box.net(f"{q.get('api')}/accept", body) + try: + answer = json.loads(data) if status else {} + except ValueError: + answer = {} + aid = answer.get("acceptance_id") if isinstance(answer, dict) else None + if status == 200 and isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-"): + rec = {"version": q["version"], "sha256": q["sha256"], + "date": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(box.now())), + "method": "setup", "acceptance_id": aid, "recorded_with": q["api"], + "email": q["email"], "use": q["use"], "channel": q["channel"]} + if q.get("use") == "licensed": + rec["license_id"] = q["license_id"] + # The record first, then the queue: a cut between the two leaves both, and the next + # flush finds the record and drops the queue (recorded() wins in state()). + write_file(box.record, (json.dumps(rec) + "\n").encode(), 0o600) + _remove(box.queue) + return RECORDED + if status in (400, 404, 409): # the license changed meanwhile, or a request it refuses + _remove(box.queue) + return DROPPED + return QUEUED + + +def text(box: Box) -> dict: + if not box.gate.present(): + raise Refused("setup is finished on this box: the license is accepted through it no more", NOT_OFFERED) + eula = current(box) + body = license_text(box, eula) if eula else None + if body is None: + raise Refused("the license text is not on this box, and it cannot be fetched now", UNAVAILABLE) + return {"version": eula["version"], "sha256": eula["sha256"], "text": body} + + +def accept(box: Box, req: dict) -> dict: + if not box.gate.present(): + raise Refused("setup is finished on this box: the license is accepted through it no more", NOT_OFFERED) + if recorded(box) or _read_json(box.queue): + raise Refused("the license is already accepted on this box", ACCEPTED) + email = req.get("email") + if not isinstance(email, str) or len(email.strip()) > 254 or CONTROL.search(email) \ + or not EMAIL.match(email.strip()): + raise Refused("that is not an email address", EMAIL_BAD) + eula = current(box) + if not eula or license_text(box, eula) is None: + raise Refused("the license text is not on this box, and it cannot be fetched now", UNAVAILABLE) + if req.get("eula_sha256") != eula["sha256"]: + raise Refused("the license shown is not the current one: read it again", CHANGED) + use, lid = use_of(box) + q = {"email": email.strip(), "channel": eula["channel"], "version": eula["version"], + "sha256": eula["sha256"], "api": eula["api"], "device_id": device_id(box), "use": use, + "installer": installer(box), "queued_at": int(box.now())} + if lid: + q["license_id"] = lid + write_file(box.queue, (json.dumps(q) + "\n").encode(), 0o600) + got = send(box) + if got == DROPPED: + return {"ok": False, "why": DROPPED} + return {"ok": True, "state": got} + + +def flush(box: Box) -> dict: + """The queued acceptance, sent; only while setup is unfinished, as a queue is written only + then (and the marker goes only once its acceptance is recorded and linked): a queue found + without it was not this helper's.""" + if not box.gate.present(): + return {"ok": True, "state": RECORDED if recorded(box) else NOT_OFFERED, "sent": False} + queued = _read_json(box.queue) is not None + got = send(box) + return {"ok": got != DROPPED, "state": got, "sent": queued, + **({"why": DROPPED} if got == DROPPED else {})} + + +def handle(box: Box, verb: str, req) -> dict: + """One request: check it, do it, say how it went. Raises Refused for anything else.""" + if not isinstance(req, dict): + raise Refused("the request must be a JSON object") + if verb not in FIELDS: + raise Refused(f"unknown request {verb!r}") + extra = set(req) - FIELDS[verb] + if extra: + # An acceptance id above all: this helper records the one the license server + # returns, never one it is given. + raise Refused(f"{verb} takes no {', '.join(sorted(extra))}") + if verb == "status": + return {"state": state(box)} + if verb == "text": + return text(box) + if verb == "accept": + return accept(box, req) + return flush(box) + + +def _reply(obj: dict) -> None: + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + +def main(argv: list[str] | None = None, box: Box | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + if box is None and os.geteuid() != 0: + _reply({"refused": "run as root, through the sudoers line", "why": REFUSED}) + return 2 + if len(argv) != 1: + _reply({"refused": "usage: license_accept.py (the request as JSON on stdin)", "why": REFUSED}) + return 2 + try: + data = sys.stdin.read(MAX_REQUEST + 1) if not sys.stdin.isatty() else "" + if len(data) > MAX_REQUEST: + raise Refused("the request is too long") + try: + req = json.loads(data) if data.strip() else {} + except ValueError: + raise Refused("the request is not JSON") from None + reply = handle(box or Box(), argv[0], req) + except Refused as e: + _reply({"refused": str(e), "why": e.why}) + return 2 + except Exception as e: # noqa: BLE001 -- by its type alone: an exception's text can quote the email + sys.stderr.write(f"license_accept: {type(e).__name__}\n") + _reply({"ok": False, "why": FAILED}) + return 1 + if argv[0] == "flush" and reply.get("sent"): + sys.stderr.write(f"license_accept: the queued acceptance: {reply.get('state')}\n") # the timer's journal + _reply(reply) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brain/teaport_brain/license_link.py b/brain/teaport_brain/license_link.py new file mode 100644 index 00000000..2b37a460 --- /dev/null +++ b/brain/teaport_brain/license_link.py @@ -0,0 +1,394 @@ +# +# teaport — the owner's acceptance put on the box's appliance key (#465): POST +# /license/link, as root, behind sudo, and from teaport-license-owner.timer. +# +# The box's engine license key (/etc/teaport/license.json, #474) holds no personal data: +# the license server links it to its owner's acceptance instead, which the owner made at +# setup (license_accept.py). The link needs proof that the box itself asks, since the box's +# agent can read license.json: the link secret the license server returned with the key at +# the factory, which install.sh keeps in /etc/teaport/license-link.secret, root's 0600 (the +# run user, the agent included, cannot read it). This helper sends it, with ids only: +# - it takes no acceptance id, nor anything else (a request that names anything is +# refused). It links the acceptance on the box's record (/var/lib/teaport/eula-accepted.json, +# which only root writes: license_accept.py's, or install.sh's), the key in license.json +# and the secret, all three read here; +# - when the run user asks (through its sudoers line), only while setup is unfinished +# (provisioning's marker, GATE_PATH, is there). Setup finishes when the link is made: +# the marker goes. Not "while an owner's session from the setup page is open": the +# session (settings_access.py) is signed with a key in brain.env, which the run user +# reads, so the run user could make one, and no root helper can tell it from the +# owner's. The owner's own login (`teaport`, in the sudo group) reaches it through sudo +# with their password at any time, and root's own call (the timer) does: sudo sets +# SUDO_UID itself, so the run user cannot pass for either; +# - so a prompt-injected agent can at worst have the box linked to the acceptance on its +# own record, the owner's, again: a link to the acceptance already linked changes +# nothing (no request at all: LINKED_PATH says so), and the license server's answer for +# one sent anyway is the same. +# A box without the secret file (installed before install.sh wrote it, teaport#475) is +# logged and left as it is: nothing is sent, and Teaspoon AI links it by hand. A box with +# no appliance key, or no recorded acceptance, has nothing to link. A refusal from the +# license server is remembered for that acceptance, key and secret (LINKED_PATH): root's +# own call does not ask again until one of them changes; the run user or the owner may. +# +# Verbs (the only argument; the request is a JSON object on stdin, the reply one on stdout; +# a request this does not do gets {"refused": why, "why": code} and exit 2): +# status {state}: LINKED, UNLINKED, NO_SECRET, NO_KEY or NO_ACCEPTANCE; +# link {} -> {ok, linked, changed} or {ok: false, why}. +# The secret reaches the license server and nothing else: no reply, no log line, no error. +# Nothing here writes, renames or removes PROTECTED (the engine's license files, #474 F1). +# +# Run as the sudoers line (packaging/deb/sudoers-sync) names it: +# /usr/bin/python3 /usr/lib/teaport/license_link.py +# the root-owned copy the teaport-brain package ships, on the SYSTEM python, never the +# venv's. Standard library only. Tests run it in-process (handle()) against a pretend +# license server and a temporary tree (Box). +# +import hashlib +import json +import os +import pwd +import re +import stat +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +RECORD_PATH = "/var/lib/teaport/eula-accepted.json" +LINKED_PATH = "/var/lib/teaport/license-link.json" +GATE_PATH = "/var/lib/teaport-owner/license-pending" # license_accept.GATE_PATH +LICENSE_PATH = "/etc/teaport/license.json" +SECRET_PATH = "/etc/teaport/license-link.secret" +# The engine's license files (teaport#474 F1): no root helper the run user reaches writes, +# renames or removes them. The one list: every other helper's copy must equal it (tests). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") +BRAIN_UNIT = "teaport-brain.service" +MAX_REQUEST = 4096 +NET_SECS = 20 +# The secret as install.sh writes it: 32 bytes, base64url without padding (43 characters), +# then at most a newline. +SECRET = re.compile(r"[A-Za-z0-9_-]{43}\n?") +ACCEPTANCE_ID = re.compile(r"[A-Za-z0-9_-]{8,64}") +LICENSE_ID = re.compile(r"[A-Z0-9][A-Z0-9-]{3,39}") +TPDEV2 = re.compile(r"tpdev2-[0-9a-f]{32}") +SERVER_CODE = re.compile(r"[a-z_]{1,40}") +LINKED, UNLINKED, NO_SECRET, NO_KEY, NO_ACCEPTANCE = "linked", "unlinked", "no_secret", "no_key", "no_acceptance" +REFUSED, SETUP_DONE, UNREACHABLE, FAILED = "refused", "setup_done", "unreachable", "failed" +TOOL_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} + + +class Refused(Exception): + def __init__(self, text: str, why: str = REFUSED): + super().__init__(text) + self.why = why + + +def guard(path: str) -> str: + """`path`, unless it is one of PROTECTED, by name or through a link (teaport#474 F1).""" + if os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED: + raise Refused(f"{path} is the engine's license, which this helper never writes") + return path + + +class Marker: + """Provisioning's marker (license_accept.Marker): there, and root's alone.""" + + def __init__(self, path: str = GATE_PATH, owner: int = 0): + self.path, self.owner = path, owner + + def _roots(self, st: os.stat_result, kind) -> bool: + return kind(st.st_mode) and st.st_uid == self.owner and not st.st_mode & 0o022 + + def present(self) -> bool: + try: + directory = os.lstat(os.path.dirname(self.path)) + marker = os.lstat(self.path) + except FileNotFoundError: + return False + return self._roots(directory, stat.S_ISDIR) and self._roots(marker, stat.S_ISREG) + + def remove(self) -> None: + guard(self.path) + try: + os.unlink(self.path) + except FileNotFoundError: + pass + + +def _no_redirect(): + class Refuse(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + return urllib.request.build_opener(Refuse) + + +def post(url: str, body: dict) -> tuple[int, bytes]: + """POST `body` as JSON to an https `url`: (status, the answer); 0 for no answer. No + redirect is followed: one would take the secret wherever it said.""" + if not url.startswith("https://"): + return 0, b"" + req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"content-type": "application/json", + "user-agent": "teaport-license-link"}) + try: + with _no_redirect().open(req, timeout=NET_SECS) as r: # noqa: S310 -- https only + return r.status, r.read(65536) + except urllib.error.HTTPError as e: + try: + return e.code, e.read(65536) + except OSError: + return e.code, b"" + except (OSError, ValueError): + return 0, b"" + + +def run_user(run=subprocess.run) -> str: + """The brain's User= (as sudoers-sync reads it): "" when it cannot be told.""" + try: + p = run(["systemctl", "show", "-p", "User", "--value", BRAIN_UNIT], + capture_output=True, text=True, timeout=10, env=TOOL_ENV) + return p.stdout.strip() if p.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + return "" + + +def uid_of(name: str) -> int | None: + try: + return pwd.getpwnam(name).pw_uid + except (KeyError, TypeError): + return None + + +class Box: + """Where this helper reads and writes, who asks, and how it reaches the network (a + test's own). `caller`: SUDO_UID as sudo set it (None: root's own call, the timer); + `run_uid`: the brain's user's uid (None when it cannot be told).""" + + def __init__(self, record: str = RECORD_PATH, linked: str = LINKED_PATH, + gate: Marker | None = None, license_path: str = LICENSE_PATH, + secret: str = SECRET_PATH, net=post, caller: int | None = None, + run_uid=None, now=time.time, secret_owner: int = 0): + self.record, self.linked, self.gate = record, linked, gate or Marker() + self.license_path, self.secret, self.net, self.now = license_path, secret, net, now + self.caller, self.secret_owner = caller, secret_owner + self._run_uid = run_uid + + def run_uid(self) -> int | None: + if callable(self._run_uid): + return self._run_uid() + return self._run_uid + + @classmethod + def real(cls) -> "Box": + raw = os.environ.get("SUDO_UID") + caller = int(raw) if raw and raw.isdigit() else None + return cls(caller=caller, run_uid=lambda: uid_of(run_user())) + + +def _read_json(path: str, limit: int = 65536) -> dict | None: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return None + data = json.loads(f.read(limit + 1)[:limit]) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def write_file(path: str, data: bytes, mode: int) -> None: + """Whole or not at all, as license_accept.write_file.""" + guard(path) + directory = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(dir=directory, prefix="." + os.path.basename(path) + ".") + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +# ------------------------------------------------------------------ what there is to link + +def acceptance(box: Box) -> tuple[str, str] | None: + """(acceptance id, the license server it was recorded with) from the box's record: an + acceptance's, not the factory's maker record; None when there is none.""" + r = _read_json(box.record) + if not r or r.get("method") == "factory": + return None + aid, api = r.get("acceptance_id"), r.get("recorded_with") + if not (isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-")): + return None + if not (isinstance(api, str) and api.startswith("https://")): + return None + return aid, api.rstrip("/") + + +def appliance_key(box: Box) -> tuple[str, str] | None: + """(license_id, device) of the box's appliance key, read only; None for no key, or one + of another tier (a personal key's acceptance is the one it was issued under).""" + doc = _read_json(box.license_path) or {} + p = doc.get("payload") if isinstance(doc.get("payload"), dict) else {} + lid, device = p.get("license_id"), p.get("device") + if p.get("tier") != "appliance" or not (isinstance(lid, str) and LICENSE_ID.fullmatch(lid)) \ + or not (isinstance(device, str) and TPDEV2.fullmatch(device)): + return None + return lid, device + + +def link_secret(box: Box) -> str | None: + """The secret, from a regular file of root's that nobody else can read or write; None + when there is no file. Refused when it is there but not so (it may have been read), or + not one.""" + try: + fd = os.open(box.secret, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return None + except OSError: + raise Refused(f"{box.secret} cannot be read", FAILED) from None + with os.fdopen(fd, "rb") as f: + st = os.fstat(f.fileno()) + if not stat.S_ISREG(st.st_mode) or st.st_uid != box.secret_owner or st.st_mode & 0o077: + raise Refused(f"{box.secret} must be a file of root's, mode 0600", FAILED) + data = f.read(64).decode("ascii", "replace") + if not SECRET.fullmatch(data): + raise Refused(f"{box.secret} is not a link secret", FAILED) + return data.rstrip("\n") + + +def _fingerprint(aid: str, lid: str, secret: str) -> str: + """What a remembered refusal was for: the acceptance, the key and the secret's hash.""" + return hashlib.sha256(f"{aid}\0{lid}\0{secret}".encode()).hexdigest() + + +def status(box: Box) -> dict: + acc, key = acceptance(box), appliance_key(box) + if not key: + return {"state": NO_KEY} + if not acc: + return {"state": NO_ACCEPTANCE} + if not os.path.lexists(box.secret): + return {"state": NO_SECRET} + done = _read_json(box.linked) or {} + ok = done.get("acceptance_id") == acc[0] and done.get("license_id") == key[0] and done.get("linked") is True + return {"state": LINKED if ok else UNLINKED} + + +def _allowed(box: Box) -> None: + """The run user asks only while setup is unfinished (the module comment). Who asks is + sudo's SUDO_UID: none is root's own call; one that is not the brain's user is another + administrator's, who gave sudo a password. A brain's user that cannot be told counts as + the caller's: refused unless setup is unfinished.""" + if box.caller is None or box.caller == 0: + return + run = box.run_uid() + if (run is None or box.caller == run) and not box.gate.present(): + raise Refused("setup is finished on this box: its owner's acceptance is linked through it no more", + SETUP_DONE) + + +def link(box: Box, log=lambda line: sys.stderr.write(f"license_link: {line}\n")) -> dict: + _allowed(box) + acc, key = acceptance(box), appliance_key(box) + if not key: + return {"ok": True, "linked": False, "why": NO_KEY} + if not acc: + return {"ok": True, "linked": False, "why": NO_ACCEPTANCE} + secret = link_secret(box) + if secret is None: + log(f"no link secret on this box ({box.secret}, written by install.sh since teaport#475): " + "nothing is linked; Teaspoon AI links the owner by hand") + return {"ok": True, "linked": False, "why": NO_SECRET} + (aid, api), (lid, device) = acc, key + done = _read_json(box.linked) or {} + if done.get("acceptance_id") == aid and done.get("license_id") == lid and done.get("linked") is True: + box.gate.remove() # linked already: setup is finished, if a cut left the marker + return {"ok": True, "linked": True, "changed": False} + mark = _fingerprint(aid, lid, secret) + if box.caller is None and done.get("refused_for") == mark: + return {"ok": False, "why": done.get("why") or REFUSED} + status_code, data = box.net(f"{api}/license/link", + {"acceptance_id": aid, "license_id": lid, "device": device, "link_secret": secret}) + try: + answer = json.loads(data) if status_code else {} + except ValueError: + answer = {} + answer = answer if isinstance(answer, dict) else {} + if status_code == 200 and answer.get("linked") is True: + write_file(box.linked, (json.dumps({"acceptance_id": aid, "license_id": lid, "linked": True, + "at": int(box.now())}) + "\n").encode(), 0o600) + box.gate.remove() + log("the owner's acceptance is linked to this box's license key" + + ("" if answer.get("changed") is not False else " (it was already)")) + return {"ok": True, "linked": True, "changed": answer.get("changed") is not False} + code = answer.get("error") if isinstance(answer.get("error"), str) and SERVER_CODE.fullmatch(answer["error"]) else None + if status_code in (400, 403, 404, 409): + write_file(box.linked, (json.dumps({"refused_for": mark, "why": code or REFUSED, "status": status_code, + "at": int(box.now())}) + "\n").encode(), 0o600) + log(f"the license server refused the link (HTTP {status_code}{', ' + code if code else ''})") + return {"ok": False, "why": code or REFUSED} + log(f"the license server could not be asked now (HTTP {status_code or 'none'}): the timer asks again") + return {"ok": False, "why": UNREACHABLE} + + +def handle(box: Box, verb: str, req) -> dict: + if not isinstance(req, dict): + raise Refused("the request must be a JSON object") + if verb not in ("status", "link"): + raise Refused(f"unknown request {verb!r}") + if req: + # An acceptance id above all: this links the one on the box's record, never one given. + raise Refused(f"{verb} takes nothing: not {', '.join(sorted(map(str, req)))}") + return status(box) if verb == "status" else link(box) + + +def _reply(obj: dict) -> None: + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + +def main(argv: list[str] | None = None, box: Box | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + if box is None and os.geteuid() != 0: + _reply({"refused": "run as root, through the sudoers line", "why": REFUSED}) + return 2 + if len(argv) != 1: + _reply({"refused": "usage: license_link.py (nothing on stdin, or {})", "why": REFUSED}) + return 2 + try: + data = sys.stdin.read(MAX_REQUEST + 1) if not sys.stdin.isatty() else "" + if len(data) > MAX_REQUEST: + raise Refused("the request is too long") + try: + req = json.loads(data) if data.strip() else {} + except ValueError: + raise Refused("the request is not JSON") from None + reply = handle(box or Box.real(), argv[0], req) + except Refused as e: + _reply({"refused": str(e), "why": e.why}) + return 2 + except Exception as e: # noqa: BLE001 -- by its type alone: never the secret + sys.stderr.write(f"license_link: {type(e).__name__}\n") + _reply({"ok": False, "why": FAILED}) + return 1 + _reply(reply) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brain/tests/test_license_accept.py b/brain/tests/test_license_accept.py new file mode 100644 index 00000000..0f799c7f --- /dev/null +++ b/brain/tests/test_license_accept.py @@ -0,0 +1,470 @@ +# +# The owner's license helper (license_accept.py, #465) is the run user's only way to have +# the box record who accepted the Teaport Engine License, and the run user is the agent's: +# what it takes must be the owner's email, once, while setup is unfinished. What has to hold: +# - a request that names an acceptance id (or anything else a verb does not take) is +# refused, and the helper records only the id the license server returns to its own POST; +# - it refuses once setup is finished (no marker, or one the run user could have made), +# and once an acceptance is recorded or queued; +# - online, it sends the owner's email with the current license's version and SHA-256, +# method "tty" and installer "setup:" (the license server takes tty or flag), +# the box's device id (the appliance serial's hash on a factory box, +# the machine id's on any other), and the appliance key's license id for licensed use; +# the record is install.sh's receipt, root's 0600; +# - offline, it queues the email (root's 0600), and a later flush sends it and records the +# returned id; one the server refuses for good is dropped and the step offered again; +# - the text is the manifest's, checked against its SHA-256, kept on the box, and the page +# names the one it showed; +# - the email reaches no reply, no stdout or stderr line. +# Every email address and id here is made up for the test. +# +# Run: python test_license_accept.py (or via pytest test_suite.py) +# +import hashlib +import io +import json +import os +import pathlib +import re + +import pytest + +from teaport_brain import license_accept as la + +ROOT = pathlib.Path(__file__).resolve().parents[2] +TEXT = "Teaport Engine License 2.0\nThe terms.\n" +SHA = hashlib.sha256(TEXT.encode()).hexdigest() +API = "https://get.teaspoon.tech/api" +EMAIL = "owner@example.com" +SERIAL = "TP-20261128-0042" +AID = "Acc0123456789abcdefABCDEF" + + +def manifest(version="2.0", sha=SHA, channel="stable"): + return {"channel": channel, "access": {"api": API}, + "engine": {"eula": {"version": version, "url": "https://get.teaspoon.tech/eula/l.txt", "sha256": sha}}} + + +class Server: + """The license server, its manifest and the text, as the helper reaches them: every + request logged; `online` False answers nothing (status 0).""" + + def __init__(self, online=True, accept=(200, {"acceptance_id": AID, "token": "tok", "expires_at": "x"})): + self.online, self.accept, self.calls = online, accept, [] + self.manifest, self.text = manifest(), TEXT.encode() + + def __call__(self, url, body=None, limit=la.MAX_MANIFEST): + self.calls.append((url, body)) + if not self.online: + return 0, b"" + if url.endswith("/manifest/stable.json") or url.endswith("/manifest/beta.json"): + return 200, json.dumps(self.manifest).encode() + if url.endswith("/eula/l.txt"): + return 200, self.text + if url == f"{API}/accept": + status, answer = self.accept + return status, json.dumps(answer).encode() + return 404, b"{}" + + def posts(self): + return [b for u, b in self.calls if u.endswith("/accept")] + + +def _box(tmp_path, gate=True, factory=True, key=True, server=None, installed=None): + """A pretend box: /var/lib/teaport, provisioning's marker (root's here = this test's + uid), the installed manifest, its serial and machine id, and its appliance key.""" + tmp_path.mkdir(parents=True, exist_ok=True) + state = tmp_path / "state" + state.mkdir() + owner = tmp_path / "owner" + owner.mkdir(mode=0o700) + if gate: + (owner / "license-pending").write_text("") + (owner / "license-pending").chmod(0o600) + (tmp_path / "manifest.json").write_text(json.dumps(installed or manifest())) + if factory: + (tmp_path / "appliance-id").write_text(SERIAL + "\n") + (tmp_path / "machine-id").write_text("0123456789abcdef0123456789abcdef\n") + if key: + (tmp_path / "license.json").write_text(json.dumps({"payload": { + "v": 2, "license_id": "TPL-0123456789ABCDEFGHJK", "tier": "appliance", + "device": "tpdev2-" + "ab" * 16, "issued_at": 1, "engine_major": 1, "kid": "k"}, "signature": "x"})) + (tmp_path / "build.json").write_text(json.dumps({"revision": "0123abcd"})) + server = server or Server() + box = la.Box(str(state), la.Marker(str(owner / "license-pending"), owner=os.getuid()), + str(tmp_path / "manifest.json"), str(tmp_path / "appliance-id"), str(tmp_path / "machine-id"), + str(tmp_path / "license.json"), str(tmp_path / "build.json"), net=server, now=lambda: 1764300000) + return box, server + + +def _offline(box, server): + """The box with the license's text kept (as a factory install keeps it), then offline.""" + la.handle(box, "text", {}) + server.online = False + + +def _accept(box, email=EMAIL, sha=SHA): + return la.handle(box, "accept", {"email": email, "eula_sha256": sha}) + + +def _mode(path): + return os.stat(path).st_mode & 0o777 + + +# ------------------------------------------------------------------ what it takes + + +@pytest.mark.parametrize("verb, req", [ + ("accept", {"email": EMAIL, "eula_sha256": SHA, "acceptance_id": AID}), + ("accept", {"acceptance_id": AID}), + ("accept", {"email": EMAIL, "eula_sha256": SHA, "id": AID}), + ("accept", {"email": EMAIL, "eula_sha256": SHA, "maker_id": "maker-" + "x" * 24}), + ("accept", {"email": EMAIL, "eula_sha256": SHA, "device_id": "ab" * 32}), + ("flush", {"acceptance_id": AID}), + ("status", {"acceptance_id": AID}), + ("text", {"url": "https://evil.example/eula.txt"}), +]) +def test_an_acceptance_id_or_anything_else_it_does_not_take_is_refused(tmp_path, verb, req): + box, server = _box(tmp_path) + with pytest.raises(la.Refused) as e: + la.handle(box, verb, req) + assert e.value.why == la.REFUSED and "takes no" in str(e.value) + assert server.calls == [] and not os.listdir(box.state_dir) + + +@pytest.mark.parametrize("verb, req", [("nope", {}), ("accept", ["a list"]), ("status", "text")]) +def test_anything_else_is_refused(tmp_path, verb, req): + box, _ = _box(tmp_path) + with pytest.raises(la.Refused): + la.handle(box, verb, req) + + +def test_the_id_recorded_is_the_one_the_license_server_returned(tmp_path): + box, server = _box(tmp_path) + assert _accept(box) == {"ok": True, "state": la.RECORDED} + rec = json.loads(pathlib.Path(box.record).read_text()) + assert rec["acceptance_id"] == AID and rec["method"] == "setup" and rec["recorded_with"] == API + # An answer with something that is not an acceptance id records nothing: it waits. + box2, _ = _box(tmp_path / "b", server=Server(accept=(200, {"acceptance_id": "maker-" + "x" * 24}))) + assert _accept(box2) == {"ok": True, "state": la.QUEUED} and not os.path.exists(box2.record) + + +# ------------------------------------------------------------------ only during setup + + +def test_once_setup_is_finished_it_refuses(tmp_path): + box, server = _box(tmp_path, gate=False) + for verb, req in (("accept", {"email": EMAIL, "eula_sha256": SHA}), ("text", {})): + with pytest.raises(la.Refused) as e: + la.handle(box, verb, req) + assert e.value.why == la.NOT_OFFERED + assert la.handle(box, "status", {}) == {"state": la.NOT_OFFERED} + assert server.posts() == [] and not os.path.exists(box.queue) + + +@pytest.mark.parametrize("change", ["dir_writable", "file_writable", "link", "not_a_file"]) +def test_a_marker_the_run_user_could_have_made_is_no_marker(tmp_path, change): + box, server = _box(tmp_path) + marker = pathlib.Path(box.gate.path) + if change == "dir_writable": + marker.parent.chmod(0o777) + elif change == "file_writable": + marker.chmod(0o666) + elif change == "link": + marker.unlink() + (tmp_path / "elsewhere").write_text("") + marker.symlink_to(tmp_path / "elsewhere") + else: + marker.unlink() + marker.mkdir() + with pytest.raises(la.Refused) as e: + _accept(box) + assert e.value.why == la.NOT_OFFERED and server.posts() == [] + + +def test_a_marker_that_is_not_roots_is_no_marker(tmp_path): + box, _ = _box(tmp_path) + box.gate.owner = os.getuid() + 1 + with pytest.raises(la.Refused): + _accept(box) + + +def test_it_works_once_an_acceptance_recorded_or_queued_is_never_replaced(tmp_path): + box, server = _box(tmp_path) + _accept(box) + for email in (EMAIL, "stranger@example.org"): + with pytest.raises(la.Refused) as e: + _accept(box, email) + assert e.value.why == la.ACCEPTED + assert len(server.posts()) == 1 + assert json.loads(pathlib.Path(box.record).read_text())["email"] == EMAIL + # Queued (offline): the same. + box2, _ = _box(tmp_path / "q", server=Server(online=False)) + pathlib.Path(box2.text_path("2.0")).write_text(TEXT) # the copy the factory install kept + assert _accept(box2)["state"] == la.QUEUED + with pytest.raises(la.Refused) as e: + _accept(box2, "stranger@example.org") + assert e.value.why == la.ACCEPTED + assert json.loads(pathlib.Path(box2.queue).read_text())["email"] == EMAIL + + +def test_an_installers_acceptance_on_the_box_is_one_and_a_factory_receipt_is_none(tmp_path): + box, server = _box(tmp_path) + pathlib.Path(box.record).write_text(json.dumps({"method": "factory", "acceptance_id": "maker-" + "x" * 24})) + assert la.handle(box, "status", {}) == {"state": la.PENDING} + assert _accept(box)["state"] == la.RECORDED # the owner's replaces the maker's + assert json.loads(pathlib.Path(box.record).read_text())["method"] == "setup" + box2, _ = _box(tmp_path / "i") + pathlib.Path(box2.record).write_text(json.dumps({"version": "2.0", "method": "tty", "acceptance_id": AID})) + assert la.handle(box2, "status", {}) == {"state": la.RECORDED} + with pytest.raises(la.Refused) as e: + _accept(box2) + assert e.value.why == la.ACCEPTED + + +# ------------------------------------------------------------------ what it sends and keeps + + +def test_online_it_records_the_owners_acceptance_with_teaspoon_ai(tmp_path): + box, server = _box(tmp_path) + assert la.handle(box, "status", {}) == {"state": la.PENDING} + assert _accept(box, " " + EMAIL + " ") == {"ok": True, "state": la.RECORDED} + [body] = server.posts() + assert body == {"channel": "stable", "eula_version": "2.0", "eula_sha256": SHA, "email": EMAIL, + "use": "licensed", "license_id": "TPL-0123456789ABCDEFGHJK", + "device_id": hashlib.sha256(f"teaport-appliance:{SERIAL}".encode()).hexdigest(), + "method": "tty", "installer": "setup:git:0123abcd"} + assert "acceptance_id" not in body + rec = json.loads(pathlib.Path(box.record).read_text()) + assert rec == {"version": "2.0", "sha256": SHA, "date": rec["date"], "method": "setup", "acceptance_id": AID, + "recorded_with": API, "email": EMAIL, "use": "licensed", "channel": "stable", + "license_id": "TPL-0123456789ABCDEFGHJK"} + assert _mode(box.record) == 0o600 and not os.path.exists(box.queue) + assert pathlib.Path(box.text_path("2.0")).read_text() == TEXT and _mode(box.text_path("2.0")) == 0o644 + assert la.handle(box, "status", {}) == {"state": la.RECORDED} + + +def test_a_box_that_is_not_a_factory_one_sends_what_install_sh_sends(tmp_path): + box, server = _box(tmp_path, factory=False, key=False) + _accept(box) + [body] = server.posts() + assert body["device_id"] == hashlib.sha256(b"teaport-device:0123456789abcdef0123456789abcdef").hexdigest() + assert body["use"] == "personal" and "license_id" not in body + # The same hash install.sh's device_id() makes. + sh = (ROOT / "install.sh").read_text() + assert "printf 'teaport-device:%s' \"$(tr -d '[:space:]' /license/link as the box reaches it: each request logged.""" + + def __init__(self, answer=(200, {"license_id": LID, "linked": True, "changed": True})): + self.answer, self.calls = answer, [] + + def __call__(self, url, body): + self.calls.append((url, body)) + status, answer = self.answer + return status, json.dumps(answer).encode() + + +def _box(tmp_path, gate=True, record=True, key=True, secret=True, caller=None, run_uid=RUN_UID, server=None, + tier="appliance", method="setup"): + """A pretend box: the record, provisioning's marker, license.json and the secret file + (root's here = this test's uid). `caller`: SUDO_UID (None: root's own call).""" + tmp_path.mkdir(parents=True, exist_ok=True) + owner = tmp_path / "owner" + owner.mkdir(mode=0o700) + if gate: + (owner / "license-pending").write_text("") + (owner / "license-pending").chmod(0o600) + state = tmp_path / "state" + state.mkdir() + if record: + (state / "eula-accepted.json").write_text(json.dumps({ + "version": "2.0", "method": method, "acceptance_id": AID if method != "factory" else "maker-" + "x" * 24, + "recorded_with": API, "email": "owner@example.com"})) + etc = tmp_path / "etc" + etc.mkdir() + if key: + (etc / "license.json").write_text(json.dumps({"payload": { + "v": 2, "license_id": LID, "tier": tier, "device": DEVICE, "issued_at": 1, "engine_major": 1, "kid": "k"}, + "signature": "x"})) + if secret: + (etc / "license-link.secret").write_text(SECRET + "\n") + (etc / "license-link.secret").chmod(0o600) + server = server or Server() + box = ll.Box(str(state / "eula-accepted.json"), str(state / "license-link.json"), + ll.Marker(str(owner / "license-pending"), owner=os.getuid()), str(etc / "license.json"), + str(etc / "license-link.secret"), net=server, caller=caller, run_uid=run_uid, + now=lambda: 1764300000, secret_owner=os.getuid()) + return box, server + + +def _link(box, log=None): + lines = [] if log is None else log + return ll.link(box, log=lines.append) + + +# ------------------------------------------------------------------ what it takes + + +@pytest.mark.parametrize("req", [{"acceptance_id": AID}, {"acceptance_id": "Stranger0123456789"}, + {"license_id": LID}, {"link_secret": SECRET}, {"device": DEVICE}, {"x": 1}]) +@pytest.mark.parametrize("verb", ["link", "status"]) +def test_an_acceptance_argument_or_any_other_is_refused(tmp_path, verb, req): + box, server = _box(tmp_path, caller=RUN_UID) + with pytest.raises(ll.Refused) as e: + ll.handle(box, verb, req) + assert e.value.why == ll.REFUSED and "takes nothing" in str(e.value) + assert server.calls == [] and os.path.exists(box.gate.path) + + +def test_it_links_the_acceptance_on_the_record_with_the_key_and_the_secret(tmp_path): + box, server = _box(tmp_path, caller=RUN_UID) + lines = [] + assert _link(box, lines) == {"ok": True, "linked": True, "changed": True} + assert server.calls == [(f"{API}/license/link", + {"acceptance_id": AID, "license_id": LID, "device": DEVICE, "link_secret": SECRET})] + done = json.loads(pathlib.Path(box.linked).read_text()) + assert done == {"acceptance_id": AID, "license_id": LID, "linked": True, "at": 1764300000} + assert os.stat(box.linked).st_mode & 0o777 == 0o600 + # Setup is finished: the marker is gone. + assert not os.path.exists(box.gate.path) + assert ll.handle(box, "status", {}) == {"state": ll.LINKED} + assert SECRET not in "\n".join(lines) + json.dumps(done) + + +# ------------------------------------------------------------------ who may ask + + +def test_outside_setup_the_run_user_is_refused(tmp_path): + box, server = _box(tmp_path, gate=False, caller=RUN_UID) + with pytest.raises(ll.Refused) as e: + _link(box) + assert e.value.why == ll.SETUP_DONE and server.calls == [] + # A brain's user that cannot be told counts as the run user. + box2, server2 = _box(tmp_path / "u", gate=False, caller=RUN_UID, run_uid=None) + with pytest.raises(ll.Refused): + _link(box2) + assert server2.calls == [] + + +def test_outside_setup_root_and_the_owners_own_login_may(tmp_path): + for i, caller in enumerate((None, 0, OWNER_UID)): + box, server = _box(tmp_path / str(i), gate=False, caller=caller) + assert _link(box)["linked"] is True and len(server.calls) == 1 + + +def test_during_setup_the_run_user_may_and_only_links_the_record(tmp_path): + box, server = _box(tmp_path, caller=RUN_UID) + assert _link(box)["linked"] is True + assert server.calls[0][1]["acceptance_id"] == AID + + +def test_the_caller_is_sudos_word_not_the_run_users(monkeypatch): + monkeypatch.setenv("SUDO_UID", str(RUN_UID)) + assert ll.Box.real().caller == RUN_UID + monkeypatch.delenv("SUDO_UID") + assert ll.Box.real().caller is None + monkeypatch.setenv("SUDO_UID", "not a number") + assert ll.Box.real().caller is None + + +# ------------------------------------------------------------------ a no-op, and nothing to link + + +def test_a_relink_to_the_same_acceptance_is_a_no_op(tmp_path): + box, server = _box(tmp_path, caller=RUN_UID) + _link(box) + pathlib.Path(box.gate.path).write_text("") # a cut before the marker went + os.chmod(box.gate.path, 0o600) + before = pathlib.Path(box.linked).read_text() + assert _link(box) == {"ok": True, "linked": True, "changed": False} + assert len(server.calls) == 1, "no second request" + assert pathlib.Path(box.linked).read_text() == before and not os.path.exists(box.gate.path) + # The server's own answer for one sent anyway (another box state): the same. + box2, server2 = _box(tmp_path / "s", server=Server((200, {"license_id": LID, "linked": True, "changed": False}))) + lines = [] + assert _link(box2, lines) == {"ok": True, "linked": True, "changed": False} + assert "(it was already)" in lines[-1] + + +def test_a_new_acceptance_on_the_record_is_linked_again(tmp_path): + box, server = _box(tmp_path) + _link(box) + rec = json.loads(pathlib.Path(box.record).read_text()) + rec["acceptance_id"] = "NewOwner0123456789abcdef" # a resale: the next owner's setup + pathlib.Path(box.record).write_text(json.dumps(rec)) + assert _link(box)["linked"] is True and server.calls[-1][1]["acceptance_id"] == "NewOwner0123456789abcdef" + + +def test_without_the_secret_file_it_logs_that_and_does_nothing(tmp_path): + box, server = _box(tmp_path, secret=False, caller=RUN_UID) + lines = [] + assert _link(box, lines) == {"ok": True, "linked": False, "why": ll.NO_SECRET} + assert server.calls == [] and os.path.exists(box.gate.path) and not os.path.exists(box.linked) + assert len(lines) == 1 and "no link secret on this box" in lines[0] and "teaport#475" in lines[0] + assert ll.handle(box, "status", {}) == {"state": ll.NO_SECRET} + + +@pytest.mark.parametrize("what", ["no_key", "personal_key", "no_record", "factory_record"]) +def test_with_nothing_to_link_it_sends_nothing(tmp_path, what): + kw = {"no_key": {"key": False}, "personal_key": {"tier": "personal"}, "no_record": {"record": False}, + "factory_record": {"method": "factory"}}[what] + box, server = _box(tmp_path, **kw) + r = _link(box) + assert r["ok"] is True and r["linked"] is False and r["why"] in (ll.NO_KEY, ll.NO_ACCEPTANCE) + assert server.calls == [] and os.path.exists(box.gate.path) + + +@pytest.mark.parametrize("mode", [0o640, 0o644, 0o604, 0o660]) +def test_a_secret_file_anyone_else_can_read_or_write_is_refused(tmp_path, mode): + box, server = _box(tmp_path) + os.chmod(box.secret, mode) + with pytest.raises(ll.Refused) as e: + _link(box) + assert e.value.why == ll.FAILED and server.calls == [] + assert SECRET not in str(e.value) + + +@pytest.mark.parametrize("text", ["short\n", SECRET + "=\n", SECRET + "\n\n", " " + SECRET, SECRET[:-1] + "!"]) +def test_a_file_that_is_not_a_secret_is_refused(tmp_path, text): + box, server = _box(tmp_path) + pathlib.Path(box.secret).write_text(text) + with pytest.raises(ll.Refused): + _link(box) + assert server.calls == [] + + +def test_a_secret_that_is_a_link_is_refused(tmp_path): + box, server = _box(tmp_path) + real = pathlib.Path(tmp_path, "elsewhere") + real.write_text(SECRET) + real.chmod(0o600) + os.unlink(box.secret) + os.symlink(real, box.secret) + with pytest.raises(ll.Refused): + _link(box) + assert server.calls == [] + + +# ------------------------------------------------------------------ the license server's answers + + +def test_a_refusal_is_not_asked_again_by_the_timer_but_is_by_an_explicit_call(tmp_path): + box, server = _box(tmp_path, server=Server((403, {"error": "bad_link_secret", "message": "no"}))) + lines = [] + assert _link(box, lines) == {"ok": False, "why": "bad_link_secret"} + assert "HTTP 403, bad_link_secret" in lines[-1] and SECRET not in "\n".join(lines) + assert _link(box) == {"ok": False, "why": "bad_link_secret"} and len(server.calls) == 1 # the timer: not again + box.caller = OWNER_UID + _link(box) + assert len(server.calls) == 2 # the owner: again + assert os.path.exists(box.gate.path) + # A new secret (the box provisioned again) is asked at once, even by the timer. + box.caller = None + other = base64.urlsafe_b64encode(bytes(range(1, 33))).decode().rstrip("=") + pathlib.Path(box.secret).write_text(other) + server.answer = (200, {"license_id": LID, "linked": True, "changed": True}) + assert _link(box)["linked"] is True and server.calls[-1][1]["link_secret"] == other + + +@pytest.mark.parametrize("status", [0, 500, 503, 429]) +def test_no_answer_or_a_busy_server_is_asked_again_and_keeps_setup_open(tmp_path, status): + box, server = _box(tmp_path, server=Server((status, {"error": "busy"}))) + assert _link(box) == {"ok": False, "why": ll.UNREACHABLE} + assert _link(box)["why"] == ll.UNREACHABLE and len(server.calls) == 2 + assert os.path.exists(box.gate.path) and not os.path.exists(box.linked) + + +def test_a_server_code_that_is_not_one_is_not_passed_on(tmp_path): + box, _ = _box(tmp_path, server=Server((403, {"error": "