cloud / internal-packages / installer / test / access.mjsmain at aacbc74
// access.mjs — the Cloud's side of a deployment (worker/access.js) against a fake deployment: a
// stubbed fetch that verifies every statement's signature with WebCrypto, as the deployment does,
// and an in-memory KV. Run: node test/access.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import {
announceUpdate,
ask,
dsseOf,
enrol,
handle,
handOver,
kept,
keyIdOf,
leave,
mindWhoami,
poll,
trustOf,
} from "../worker/access.js";
import {
newWebSocketRpcSession,
RpcTarget,
upgradeWebSocketResponse,
WebSocketPair,
} from "capnweb";
const P256 = { name: "ECDSA", namedCurve: "P-256" };
const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
const DOMAIN = "example.com";
// the mind's name: its control plane's hostname, `iterate.<domain>` by default
const MIND = `iterate.${DOMAIN}`;
const BASE = `https://${MIND}`;
const ORIGIN = "https://cloud.test";
const TOKEN = "deployment-access-token-SECRET";
/** KV in memory, with `expiration` (seconds) kept as the real one does, and pages of two keys. */
function memoryKv() {
const rows = new Map();
return {
rows,
async get(key) {
return rows.get(key)?.value ?? null;
},
async put(key, value, { expiration, expirationTtl } = {}) {
const at =
expiration ?? (expirationTtl ? Math.floor(Date.now() / 1000) + expirationTtl : undefined);
if (at !== undefined)
assert.ok(at >= Date.now() / 1000 + 59, `KV refuses an expiration under 60 s (${key})`);
rows.set(key, { value, expiration: at });
},
async delete(key) {
rows.delete(key);
},
async list({ prefix = "", cursor } = {}) {
const names = [...rows.keys()].filter((k) => k.startsWith(prefix)).sort();
const from = Number(cursor || 0);
const keys = names
.slice(from, from + 2)
.map((name) => ({ name, expiration: rows.get(name).expiration }));
const done = from + 2 >= names.length;
return { keys, list_complete: done, cursor: done ? undefined : String(from + 2) };
},
};
}
/** The link of the enrol page's first step: the deployment's own /keys/enrol. */
async function allowLinkOf(env) {
const page = await get(env, `/enrol?domain=${DOMAIN}`);
assert.equal(page.status, 200);
return /href="([^"]*\/keys\/enrol[^"]*)"/.exec(await page.text())[1].replaceAll("&", "&");
}
/** The fake deployment at `base`, its control plane: trusts a key only after /keys/enrol, and
* verifies each statement. Its key is published as a mind of the stack publishes its own: raw
* ML-DSA-65 bytes, whose id is their SHA-256. */
async function fakeDeployment(base = BASE) {
const ownKey = crypto.getRandomValues(new Uint8Array(1952));
const d = { trusted: null, events: [], polls: 0, revoked: [], decline: false };
/** Why the deployment does not believe an envelope, or null: the key it trusts must have signed it. */
d.refusalOf = async ({ statement, signature }) => {
if (!d.trusted) return "unknown key";
const spki = Buffer.from(d.trusted, "base64url");
if (signature.format !== "p256" || signature.key !== (await keyIdOf(spki)))
return "unknown key";
const key = await crypto.subtle.importKey("spki", spki, P256, false, ["verify"]);
const good = await crypto.subtle.verify(
{ name: "ECDSA", hash: "SHA-256" },
key,
Buffer.from(signature.sig, "base64url"),
dsseOf(statement),
);
return good ? null : "bad signature";
};
d.fetch = async (input, init = {}) => {
const url = new URL(typeof input === "string" ? input : input.url);
assert.equal(url.origin, base, `only the deployment is called, not ${url.origin}`);
const body = typeof init.body === "string" ? init.body : init.body?.toString();
const json = (value, status = 200) =>
new Response(JSON.stringify(value), {
status,
headers: { "content-type": "application/json" },
});
switch (url.pathname) {
case "/keys/stack.json":
return json({
mind: url.hostname,
key: await keyIdOf(ownKey),
publicKey: b64url(ownKey),
algorithm: "ML-DSA-65",
listed: true,
});
case "/keys/enrol":
// a member's consent confines the key to the paths it named
assert.equal(url.searchParams.get("paths"), "/integrations/");
// the deployment reads the key at this origin before it gives the key the Cloud's name
assert.equal(url.searchParams.get("cloud"), ORIGIN);
d.trusted = url.searchParams.get("publicKey");
return new Response(null, {
status: 302,
headers: { location: url.searchParams.get("next") },
});
case "/statements": {
const { statement, signature } = JSON.parse(body);
const refusal = await d.refusalOf({ statement, signature });
if (refusal) return new Response(refusal, { status: 403 });
const parsed = JSON.parse(statement);
// a mind of the stack takes a statement for its control plane's hostname alone
if (parsed.mind !== url.hostname)
return json({ refused: "the statement is for another mind" }, 403);
assert.ok(parsed.path.startsWith("/integrations/"), `a statement at ${parsed.path}`);
assert.equal(parsed.expires - parsed.at, 5 * 60_000);
assert.equal(Buffer.from(parsed.nonce, "base64url").length, 16);
d.events.push(parsed);
return json({ ok: true }, 202);
}
case "/oauth2/register":
assert.deepEqual(JSON.parse(body).grant_types, [
"urn:ietf:params:oauth:grant-type:device_code",
]);
return json({ client_id: "client-1" }, 201);
case "/oauth2/device_authorization": {
const f = new URLSearchParams(body);
assert.equal(f.get("resource"), `${base}/api`);
assert.equal(f.get("access_seconds"), "3600");
// the request proves who asks: the Cloud's key signed exactly what is asked
const proof = JSON.parse(f.get("signed"));
assert.equal(await d.refusalOf(proof), null);
const asked = JSON.parse(proof.statement);
assert.equal(asked.type, "events.iterate.com/cloud/let-in-request-signed");
assert.deepEqual(asked.payload, {
client: f.get("client_id"),
seconds: 3600,
reason: f.get("reason"),
});
return json({
device_code: "DEVICE-SECRET",
user_code: "ABCD-EFGH",
verification_uri: `${base}/device`,
verification_uri_complete: `${base}/device?code=ABCD-EFGH`,
expires_in: 600,
interval: 5,
});
}
case "/oauth2/token": {
const f = new URLSearchParams(body);
if (f.has("token"))
return (d.revoked.push(f.get("token")), new Response(null, { status: 200 }));
assert.equal(f.get("device_code"), "DEVICE-SECRET");
if (d.decline) return json({ error: "access_denied" }, 400);
if (d.polls++ === 0) return json({ error: "authorization_pending" }, 400);
return json({
access_token: TOKEN,
token_type: "Bearer",
expires_in: 3600,
refresh_token: "REFRESH-SECRET",
});
}
}
return new Response("not found", { status: 404 });
};
return d;
}
async function setup() {
const pair = await crypto.subtle.generateKey(P256, true, ["sign", "verify"]);
const env = {
SESSIONS: memoryKv(),
CLOUD_KEY: JSON.stringify(await crypto.subtle.exportKey("jwk", pair.privateKey)),
};
const deployment = await fakeDeployment();
// the Cloud's own calls. The two that anybody can cause through /enrolled follow no redirect and
// have an end.
globalThis.fetch = (input, init = {}) => {
const { pathname } = new URL(input);
if (pathname === "/statements" || pathname === "/keys/stack.json") {
assert.equal(init.redirect, "manual", pathname);
assert.ok(init.signal instanceof AbortSignal, pathname);
}
return deployment.fetch(input, init);
};
return { env, deployment };
}
const get = (env, path, headers = {}) =>
handle(new Request(ORIGIN + path, { headers }), env, {
whoami: async (_d, token) => (assert.equal(token, TOKEN), "cloud@iterate.com"),
});
test("enrol stores the record only when the deployment accepted the signed statement", async () => {
const { env, deployment } = await setup();
const refused = await enrol(env, ORIGIN, DOMAIN);
assert.equal(refused.ok, false);
assert.match(refused.detail, /unknown key/);
assert.equal(env.SESSIONS.rows.has(`enrolled:${DOMAIN}`), false);
const back = await deployment.fetch(await allowLinkOf(env));
assert.equal(back.headers.get("location"), `${ORIGIN}/enrolled?domain=${DOMAIN}`);
const done = await get(env, `/enrolled?domain=${DOMAIN}`);
assert.equal(done.status, 200);
assert.match(await done.text(), /trusts the Cloud's key/);
assert.equal(JSON.parse(env.SESSIONS.rows.get(`enrolled:${DOMAIN}`).value).domain, DOMAIN);
assert.equal(deployment.events.at(-1).type, "events.iterate.com/cloud/deployment-enrolled");
assert.equal((await get(env, "/enrol?domain=evil.com/x")).status, 400);
// what a new deployment's config names is the key that signs
const [trusted0] = await trustOf(env);
assert.deepEqual(
{ ...trusted0, publicKey: undefined },
{
actor: "iterate-cloud",
publicKey: undefined,
label: "iterate Cloud",
paths: ["/integrations/"],
},
);
assert.equal(trusted0.publicKey, deployment.trusted);
// the owner removes the Cloud's key: the next enrol is refused, and the record goes
const trusted = deployment.trusted;
deployment.trusted = null;
assert.equal((await enrol(env, ORIGIN, DOMAIN)).ok, false);
assert.equal(env.SESSIONS.rows.has(`enrolled:${DOMAIN}`), false);
deployment.trusted = trusted;
// the fake's check is real: one changed byte of the statement, and the signature fails
let sent;
globalThis.fetch = (url, init) => ((sent = JSON.parse(init.body)), deployment.fetch(url, init));
assert.ok((await announceUpdate(env, ORIGIN, DOMAIN, { commit: "a" })).ok);
const forged = { ...sent, statement: sent.statement.replace('"commit":"a"', '"commit":"b"') };
const answer = await deployment.fetch(`${BASE}/statements`, {
method: "POST",
body: JSON.stringify(forged),
});
assert.equal(await answer.text(), "bad signature");
});
test("/enrolled names the mind by its control plane: the statement, the record, and the wake of its held deliveries", async () => {
const { env, deployment } = await setup();
deployment.trusted = new URL(await allowLinkOf(env)).searchParams.get("publicKey");
const woken = [];
const done = await handle(new Request(`${ORIGIN}/enrolled?domain=${DOMAIN}`), env, {
onEnrolled: (_domain, record) => woken.push(record.mind),
});
assert.equal(done.status, 200);
assert.match(
await done.text(),
/example\.com trusts the Cloud's key, and the Cloud knows the mind's key\. Events for its connected accounts are delivered from now\./,
);
assert.equal(deployment.events.at(-1).mind, MIND);
assert.equal(JSON.parse(env.SESSIONS.rows.get(`enrolled:${DOMAIN}`).value).mind, MIND);
assert.deepEqual(woken, [MIND]);
});
test("?mind= names another control plane of the domain, every later call goes there, and a host outside the domain is refused", async () => {
const other = "https://ctl.example.com";
const { env } = await setup();
const deployment = await fakeDeployment(other);
globalThis.fetch = (input, init = {}) => deployment.fetch(input, init);
const enrolPage = await get(env, `/enrol?domain=${DOMAIN}&mind=ctl.example.com`);
const link = new URL(
/href="([^"]*\/keys\/enrol[^"]*)"/.exec(await enrolPage.text())[1].replaceAll("&", "&"),
);
assert.equal(link.origin, other);
assert.equal(
link.searchParams.get("next"),
`${ORIGIN}/enrolled?domain=${DOMAIN}&mind=ctl.example.com`,
);
deployment.trusted = link.searchParams.get("publicKey");
assert.equal((await get(env, `/enrolled?domain=${DOMAIN}&mind=ctl.example.com`)).status, 200);
assert.equal(
JSON.parse(env.SESSIONS.rows.get(`enrolled:${DOMAIN}`).value).mind,
"ctl.example.com",
);
assert.ok((await announceUpdate(env, ORIGIN, DOMAIN, { commit: "a" })).ok);
assert.equal(deployment.events.at(-1).mind, "ctl.example.com");
for (const mind of ["evil.com", "example.com.evil.com", "ctl.example.com/x"])
assert.equal((await get(env, `/enrolled?domain=${DOMAIN}&mind=${mind}`)).status, 400, mind);
});
test("a refusal by another hostname of the domain keeps the mind's enrolment", async () => {
const { env, deployment } = await setup();
await deployment.fetch(await allowLinkOf(env));
assert.equal((await get(env, `/enrolled?domain=${DOMAIN}`)).status, 200);
// anybody can open /enrolled with another hostname of the domain, which refuses the statement
const elsewhere = await fakeDeployment("https://dash.example.com");
const real = globalThis.fetch;
globalThis.fetch = (input, init = {}) => elsewhere.fetch(input, init);
assert.equal((await get(env, `/enrolled?domain=${DOMAIN}&mind=dash.example.com`)).status, 409);
globalThis.fetch = real;
assert.equal(JSON.parse(env.SESSIONS.rows.get(`enrolled:${DOMAIN}`).value).mind, MIND);
// the enrolled mind's own refusal still ends it
deployment.trusted = null;
assert.equal((await get(env, `/enrolled?domain=${DOMAIN}`)).status, 409);
assert.equal(env.SESSIONS.rows.has(`enrolled:${DOMAIN}`), false);
});
test("/enrolled that did not enrol says why and what to do next", async () => {
const { env } = await setup();
// the mind has not allowed the Cloud's key yet
const refused = await get(env, `/enrolled?domain=${DOMAIN}`);
assert.equal(refused.status, 409);
const said = await refused.text();
assert.match(said, /<h1>Not enrolled yet<\/h1>/);
assert.match(
said,
/iterate\.example\.com does not trust the Cloud's key yet\. Go back to <a href="[^"]*\/enrol\?domain=example\.com">the first step<\/a>/,
);
// nothing answers at the mind's address
globalThis.fetch = async () => new Response("not found", { status: 404 });
const nobody = await (await get(env, `/enrolled?domain=${DOMAIN}`)).text();
assert.match(nobody, /The Cloud found no mind at iterate\.example\.com\./);
});
test("ask, poll, kept and leave", async () => {
const { env, deployment } = await setup();
deployment.trusted = new URL(await allowLinkOf(env)).searchParams.get("publicKey");
assert.ok((await enrol(env, ORIGIN, DOMAIN)).ok);
env.SESSIONS.rows.set("t:abcdefghijkl", {
value: JSON.stringify({ token: "CF-SECRET", expiresAt: Date.now() + 3e6 }),
});
env.SESSIONS.rows.set("mystery", { value: "x" });
const asked = await ask(env, DOMAIN, { seconds: 3600, reason: "Fix the broken deploy" });
assert.equal(asked.state, "asked");
assert.equal(asked.deviceCode, undefined);
const request = deployment.events.at(-1);
assert.equal(request.type, "events.iterate.com/cloud/let-in-requested");
assert.deepEqual(request.payload, {
reason: "Fix the broken deploy",
seconds: 3600,
approve: `${BASE}/device?code=ABCD-EFGH`,
code: "ABCD-EFGH",
});
const whoami = async () => "cloud@iterate.com";
assert.equal((await poll(env, DOMAIN, whoami)).state, "asked");
const inside = await poll(env, DOMAIN, whoami);
assert.equal(inside.state, "in");
assert.equal(inside.as, "cloud@iterate.com");
assert.equal(inside.token, undefined);
const stored = env.SESSIONS.rows.get(`access:${DOMAIN}`);
assert.equal(stored.value.includes("REFRESH"), false);
assert.equal(stored.expiration, Math.floor(JSON.parse(stored.value).until / 1000));
// the operator's view: the start of each id
const { records } = await kept(env, { ids: true });
assert.equal(records.length, 4);
assert.equal(records.filter((r) => r.reaches === "a deployment").length, 1);
assert.equal(records.filter((r) => r.reaches === "a Cloudflare account").length, 1);
assert.equal(records.find((r) => r.kind === "t").key, "t:abcdef…");
assert.equal(records.find((r) => r.key.startsWith("myster")).kind, "unknown");
// where there is a relay, its namespace is listed too: what an app registered is kept apart
// from the installer's rows, and the page still shows it
env.RELAY = memoryKv();
await env.RELAY.put("client:0123456789", "{}");
await env.RELAY.put("grant:user:0123456789", "{}");
const both = (await kept(env, { ids: true })).records;
assert.equal(both.length, 6);
assert.equal(both.find((r) => r.kind === "client").key, "client:012345…");
assert.equal(
both.find((r) => r.kind === "grant").reaches,
"a deployment, and only with the app's own token",
);
delete env.RELAY;
// anybody's view: the same rows, and no part of an id (a domain, an account id, a session's id)
const open = (await kept(env)).records;
assert.deepEqual(open.map((r) => r.key).sort(), ["access:", "enrolled:", "t:", "unknown"]);
// the page with no sign-in wakes no run's object, and names no part of a domain
env.SESSIONS.rows.set("dep:0123456789abcdef:example-com", { value: "{}" });
let woken = 0;
env.DEPLOYER = {
getByName: (name) => ({
kept: async () => (
woken++,
{
records: [
name === "sign-ins"
? { where: "Durable Object storage", key: "claim:", what: "A claim." }
: { where: "Durable Object storage", key: "state", what: "The run." },
],
}
),
}),
};
env.OPERATOR_TOKEN = "operator-secret";
const anybody = await get(env, "/kept");
assert.equal(anybody.headers.get("content-security-policy"), "frame-ancestors 'none'");
assert.equal(anybody.headers.get("x-frame-options"), "DENY");
const page = await anybody.text();
assert.equal(woken, 0);
for (const part of ["exampl", "012345", "abcdef", "myster", "Durable Object storage"])
assert.equal(page.includes(part), false, part);
assert.match(page, /The operator's view of this page lists those records/);
const operators = await (
await get(env, "/kept", { cookie: "__Host-operator=operator-secret" })
).text();
assert.equal(woken, 2);
assert.match(operators, /run 012345… state/);
assert.match(operators, /sign-ins claim:/);
assert.match(operators, /enrolled:exampl…/);
for (const text of [JSON.stringify(records), page, operators]) {
for (const secret of [TOKEN, "CF-SECRET", "DEVICE-SECRET", "abcdefghijkl"])
assert.equal(text.includes(secret), false, secret);
}
assert.match(page, /1 row reaches a deployment, and 1 row reaches a Cloudflare account/);
env.SESSIONS.rows.delete("dep:0123456789abcdef:example-com");
delete env.DEPLOYER;
delete env.OPERATOR_TOKEN;
assert.ok((await announceUpdate(env, ORIGIN, DOMAIN, { commit: "abc123" })).ok);
assert.deepEqual(deployment.events.at(-1).payload, { commit: "abc123", update: `${ORIGIN}/` });
await leave(env, DOMAIN);
assert.deepEqual(deployment.revoked, [TOKEN]);
assert.equal((await kept(env)).records.filter((r) => r.reaches === "a deployment").length, 0);
deployment.decline = true;
await ask(env, DOMAIN, { seconds: 3600, reason: "again" });
assert.equal((await poll(env, DOMAIN, whoami)).state, "declined");
});
test("an installation is handed over once, to the deployment it names", async () => {
const { env, deployment } = await setup();
const words = { installation: "/installations/cf-user-1", summary: "They want a family mind." };
// not before the deployment is enrolled: the Cloud hands over only what a run of its own made
assert.deepEqual(
[(await handOver(env, ORIGIN, DOMAIN, words)).status, deployment.events.length],
[409, 0],
);
deployment.trusted = new URL(await allowLinkOf(env)).searchParams.get("publicKey");
assert.ok((await enrol(env, ORIGIN, DOMAIN)).ok);
for (const bad of [
{ ...words, installation: "" },
{ ...words, installation: "a b" },
{ ...words, summary: "" },
{ ...words, summary: "x".repeat(8_001) },
{ ...words, summary: 5 },
])
assert.equal((await handOver(env, ORIGIN, DOMAIN, bad)).status, 400);
assert.equal((await handOver(env, ORIGIN, "evil.com/x", words)).status, 400);
// the deployment is down: nothing is accepted, and the next try carries the same id
const trusted = deployment.trusted;
deployment.trusted = null;
assert.equal((await handOver(env, ORIGIN, DOMAIN, words)).status, 403);
const kept0 = JSON.parse(env.SESSIONS.rows.get(`handover:${DOMAIN}`).value);
assert.equal(kept0.accepted, undefined);
deployment.trusted = trusted;
const first = await handOver(env, ORIGIN, DOMAIN, words);
assert.deepEqual(first, { ok: true, handover: kept0.handover, sent: true });
const event = deployment.events.at(-1);
assert.equal(event.type, "events.iterate.com/cloud/installation-handed-over");
assert.equal(event.path, "/integrations/cloud");
// bound to its destination twice: the statement's own name (the fake asserts it), and the payload
assert.deepEqual(event.payload, {
handover: first.handover,
destination: DOMAIN,
cloud: ORIGIN,
installation: words.installation,
summary: words.summary,
});
// again: nothing goes, whatever the words now say
const count = deployment.events.length;
assert.deepEqual(await handOver(env, ORIGIN, DOMAIN, { ...words, summary: "Other words." }), {
ok: true,
handover: first.handover,
sent: false,
});
// another installation cannot speak to this deployment's onboarding agent
assert.equal(
(await handOver(env, ORIGIN, DOMAIN, { ...words, installation: "/installations/cf-user-2" }))
.status,
409,
);
assert.equal(deployment.events.length, count);
// the row says that it happened, not what was said, and /kept names it
assert.equal(env.SESSIONS.rows.get(`handover:${DOMAIN}`).value.includes(words.summary), false);
assert.ok((await kept(env)).records.some((r) => r.kind === "handover" && r.what !== "unknown"));
});
test("a refused request keeps no device code", async () => {
const { env, deployment } = await setup();
env.SESSIONS.rows.set(`enrolled:${DOMAIN}`, { value: "{}" }); // enrolled, but the deployment trusts no key
const row = await ask(env, DOMAIN, { seconds: 3600, reason: "help" });
assert.equal(row.state, "refused");
assert.equal(env.SESSIONS.rows.get(`access:${DOMAIN}`).value.includes("DEVICE"), false);
assert.equal(deployment.events.length, 0);
});
test("the operator's pages", async () => {
const { env, deployment } = await setup();
assert.equal((await get(env, "/access")).status, 404);
assert.equal((await get(env, "/access?operator=x")).status, 404);
env.OPERATOR_TOKEN = "operator-secret";
const signIn = (operator, origin = ORIGIN) =>
handle(
new Request(`${ORIGIN}/access/sign-in`, {
method: "POST",
headers: { origin },
body: new URLSearchParams({ operator }),
}),
env,
);
// the token in the address is refused unread, the right one too: an address is logged
const inAddress = await get(env, "/access?operator=operator-secret");
assert.equal(inAddress.status, 400);
assert.equal(inAddress.headers.get("set-cookie"), null);
assert.match(await inAddress.text(), /does not go in the address/);
const asked = await get(env, "/access");
assert.equal(asked.status, 403);
assert.equal(asked.headers.get("content-security-policy"), "frame-ancestors 'none'");
assert.match(await asked.text(), /<form method="post" action="\/access\/sign-in">/);
assert.equal((await signIn("wrong")).status, 403);
assert.equal((await signIn("operator-secret", "https://evil.test")).status, 403);
assert.equal((await get(env, "/access", { cookie: "__Host-operator=wrong" })).status, 403);
assert.equal((await get(env, "/access", { cookie: "__Host-operator=%E0%A4%A" })).status, 403);
// the cookie of before this rule, with the right token, is no sign-in
assert.equal((await get(env, "/access", { cookie: "operator=operator-secret" })).status, 403);
const signedIn = await signIn("operator-secret");
assert.equal(signedIn.status, 303);
assert.equal(signedIn.headers.get("location"), "/access");
const cookie = signedIn.headers.get("set-cookie");
assert.match(cookie, /^__Host-operator=[^;]+; Path=\/; HttpOnly; Secure; SameSite=Strict$/);
const headers = { cookie: cookie.split(";")[0] };
deployment.trusted = new URL(await allowLinkOf(env)).searchParams.get("publicKey");
await enrol(env, ORIGIN, DOMAIN);
const post = (path, fields, origin = ORIGIN) =>
handle(
new Request(ORIGIN + path, {
method: "POST",
headers: { ...headers, origin },
body: new URLSearchParams(fields),
}),
env,
);
assert.equal(
(
await post(
"/access/ask",
{ domain: DOMAIN, seconds: "3600", reason: "x" },
"https://evil.test",
)
).status,
403,
);
assert.equal(
(await post("/access/ask", { domain: DOMAIN, seconds: "3600", reason: "<b>help</b>" })).status,
303,
);
const waiting = await get(env, "/access", headers);
const html = await waiting.text();
assert.match(html, /Waiting for the owner/);
assert.match(html, /http-equiv="refresh" content="6"/);
const now = await (await get(env, "/access", headers)).text();
assert.match(now, /Let in as cloud@iterate\.com until .* UTC\. This cannot be renewed\./);
assert.equal(now.includes("<b>help</b>"), false);
assert.equal(now.includes(TOKEN), false);
assert.equal((await post("/access/leave", { domain: DOMAIN })).status, 303);
assert.equal(env.SESSIONS.rows.has(`access:${DOMAIN}`), false);
assert.equal(await get(env, "/elsewhere"), null);
// Forget: the record goes, and the page lists no deployment
assert.equal((await post("/access/forget", { domain: DOMAIN })).status, 303);
assert.equal(env.SESSIONS.rows.has(`enrolled:${DOMAIN}`), false);
});
test("who the deployment says the token is: one WebSocket session of its API, authenticated in the call and closed after it", async () => {
/** A deployment's API: `authenticate(token).mind.whoami()`, as the control plane answers it. */
const deployment = (seen) => {
class Mind extends RpcTarget {
whoami() {
return { path: "/", principal: { actor: "user_cloud", email: "cloud@iterate.com" } };
}
}
class Session extends RpcTarget {
get mind() {
return new Mind();
}
}
class Root extends RpcTarget {
authenticate(token) {
seen.tokens.push(token);
if (token !== TOKEN)
throw Object.assign(new Error("sign in again"), { code: "UNAUTHENTICATED" });
return new Session();
}
}
return async (url, init = {}) => {
seen.requests.push({ url: String(url), ...init });
const pair = new WebSocketPair();
pair[1].accept();
pair[1].addEventListener("close", ({ code }) => seen.closed.push(code));
newWebSocketRpcSession(pair[1], new Root());
return upgradeWebSocketResponse(pair[0]);
};
};
const seen = { requests: [], tokens: [], closed: [] };
globalThis.fetch = deployment(seen);
assert.equal(await mindWhoami(MIND, TOKEN), "cloud@iterate.com");
// an upgrade, with the token in the call and in no header, and no redirect followed
assert.deepEqual(seen.requests, [
{ url: `${BASE}/api`, headers: { upgrade: "websocket" }, redirect: "manual" },
]);
assert.deepEqual(seen.tokens, [TOKEN]);
// the socket is closed after the one question
await new Promise((resolve) => setTimeout(resolve, 20));
assert.deepEqual(seen.closed, [1000]);
// a token that the deployment refuses is nobody's, and its socket is closed too
await assert.rejects(mindWhoami(MIND, "another-token"), { code: "UNAUTHENTICATED" });
await new Promise((resolve) => setTimeout(resolve, 20));
assert.deepEqual(seen.closed, [1000, 1000]);
// a deployment that answers no socket (the API has no other transport) says nobody
globalThis.fetch = async () => new Response("open this address as a WebSocket", { status: 426 });
assert.equal(await mindWhoami(MIND, TOKEN), null);
});