cloud / internal-packages / installer / test / same-origin.mjsmain at aacbc74
// same-origin.mjs — a write to the Cloud comes from the Cloud's own page, and a sign-in ends in the
// browser that started it (worker/index.js `refusedWrite`, `connect`, `callback`), against a KV in
// memory and a stubbed Cloudflare. Run: node test/same-origin.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { claimIn, takeToken } from "../worker/cloudflare-access.js";
import worker from "../worker/index.js";
const CLOUD = "https://cloud.iterate.com";
const ACCOUNT = "a".repeat(32);
/** The Worker's bindings: KV in memory, and a Cloudflare that says yes and counts what it got. */
function cloud() {
const rows = new Map();
const asked = [];
const revoked = [];
const claims = new Map();
const storage = {
list: async () => claims,
get: async (key) => claims.get(key),
put: async (key, value) => void claims.set(key, value),
delete: async (keys) => keys.forEach((key) => claims.delete(key)),
};
const env = {
CLIENT_ID: "client",
CLIENT_SECRET: "secret",
SESSIONS: {
get: async (key) => rows.get(key) ?? null,
put: async (key, value) => void rows.set(key, value),
delete: async (key) => void rows.delete(key),
},
// the object `sign-ins` of the run class, with the real rule
DEPLOYER: { getByName: () => ({ claim: (id) => claimIn(storage, id) }) },
CF_SERVICE: {
fetch: async (input, init = {}) => {
asked.push(`${init.method || "GET"} ${new URL(input).pathname}`);
if (String(input).endsWith("/revoke")) revoked.push(Object.fromEntries(init.body));
return Response.json(
String(input).endsWith("/token")
? { access_token: "TOKEN", expires_in: 3600, scope: "user-details.read" }
: { success: true, result: { domains: [] } },
);
},
},
};
/** A sign-in with a token, as the callback writes one. */
const signIn = (id) => {
rows.set(`s:${id}`, JSON.stringify({ level: "full", until: Date.now() + 3600_000 }));
rows.set(`t:${id}`, JSON.stringify({ token: "TOKEN", expiresAt: Date.now() + 3600_000 }));
};
const ask = (path, init) => worker.fetch(new Request(`${CLOUD}${path}`, init), env);
return { env, rows, asked, revoked, claims, storage, signIn, ask };
}
const suggest = (headers, body = JSON.stringify({ account: ACCOUNT, name: "ada" })) => ({
method: "POST",
headers: { cookie: "__Host-sid=person", ...headers },
body,
});
const JSON_TYPE = { "content-type": "application/json" };
const cookiesOf = (answer) => answer.headers.getSetCookie();
test("the page's own write goes on", async () => {
const { ask, asked, signIn } = cloud();
signIn("person");
const answer = await ask("/api/suggest", suggest({ origin: CLOUD, ...JSON_TYPE }));
assert.equal(answer.status, 200);
assert.deepEqual(asked, [`POST /client/v4/accounts/${ACCOUNT}/registrar-sandbox/domain-check`]);
});
test("a write from another host of the Cloud's zone is refused, and so is one with no Origin", async () => {
const { ask, asked, signIn } = cloud();
signIn("person");
for (const origin of ["https://agents.iterate.com", "https://example.com", "null", undefined]) {
const answer = await ask(
"/api/suggest",
suggest({ ...(origin === undefined ? {} : { origin }), ...JSON_TYPE }),
);
assert.equal(answer.status, 403, `Origin: ${origin}`);
}
// each route that writes, also the ones outside /api
for (const [method, path] of [
["POST", "/api/deploy"],
["POST", "/api/register"],
["PUT", "/api/zone/check"],
["DELETE", "/api/deploy"],
["POST", "/access/forget"],
["POST", "/logout"],
]) {
const answer = await ask(path, {
method,
headers: { cookie: "__Host-sid=person", origin: "https://agents.iterate.com", ...JSON_TYPE },
body: "{}",
});
assert.equal(answer.status, 403, `${method} ${path}`);
}
assert.deepEqual(asked, [], "a refused write asks Cloudflare nothing");
});
test("signing out is the page's own POST: a link or an image of another site ends no session", async () => {
const { ask, rows, signIn } = cloud();
signIn("person");
// a GET is what another site's link, image or redirect makes, with the person's cookie on it
// when the site is another host of the Cloud's zone
const linked = await ask("/logout", { headers: { cookie: "__Host-sid=person" } });
assert.equal(linked.status, 405);
assert.deepEqual(cookiesOf(linked), []);
assert.deepEqual([rows.has("s:person"), rows.has("t:person")], [true, true]);
// the page's own button: the session and the Cloud's copy of the access both go
const pressed = await ask("/logout", {
method: "POST",
headers: { cookie: "__Host-sid=person", origin: CLOUD },
});
assert.equal(pressed.status, 200);
assert.match(cookiesOf(pressed)[0], /^__Host-sid=; .*Max-Age=0/);
assert.deepEqual([rows.has("s:person"), rows.has("t:person")], [false, false]);
});
test("a sign-out revokes the access at Cloudflare, and says what Cloudflare answered", async () => {
const press = (ask) =>
ask("/logout", { method: "POST", headers: { cookie: "__Host-sid=person", origin: CLOUD } });
const { ask, asked, revoked, signIn } = cloud();
signIn("person");
assert.deepEqual(await (await press(ask)).json(), { access: "ended" });
assert.deepEqual(asked, ["POST /oauth2/revoke"]);
assert.deepEqual(revoked, [{ token: "TOKEN", client_id: "client", client_secret: "secret" }]);
// no token (it ran out, or a deploy run took it): nothing to ask Cloudflare
assert.deepEqual(await (await press(ask)).json(), { access: "none" });
assert.equal(asked.length, 1);
// Cloudflare refuses, or does not answer: the records go all the same, and the page hears it
for (const fetch of [async () => new Response("no", { status: 503 }), () => Promise.reject()]) {
const broken = cloud();
broken.signIn("person");
broken.env.CF_SERVICE = { fetch };
assert.deepEqual(await (await press(broken.ask)).json(), { access: "kept" });
assert.deepEqual([broken.rows.has("s:person"), broken.rows.has("t:person")], [false, false]);
}
});
test("a token is ended once: by the run that took it, or by the sign-in's end, never by both", async () => {
const press = (ask) =>
ask("/logout", { method: "POST", headers: { cookie: "__Host-sid=person", origin: CLOUD } });
// A run took the token, and KV still answers the record from its cache: the sign-out revokes
// nothing, so the run's deploy keeps its access.
const running = cloud();
running.signIn("person");
assert.equal((await takeToken(running.env, "person")).token, "TOKEN");
running.signIn("person"); // what the cache still shows
assert.deepEqual(await (await press(running.ask)).json(), { access: "none" });
assert.deepEqual(running.asked, []);
assert.deepEqual([running.rows.has("s:person"), running.rows.has("t:person")], [false, false]);
// The sign-out revoked the token, and KV still shows the record: no run starts with it.
const gone = cloud();
gone.signIn("person");
assert.deepEqual(await (await press(gone.ask)).json(), { access: "ended" });
gone.signIn("person");
await assert.rejects(takeToken(gone.env, "person"), /connect Cloudflare again/);
assert.equal(gone.rows.has("t:person"), false);
// a second run with the same cached record gets nothing either
running.signIn("person");
await assert.rejects(takeToken(running.env, "person"), /connect Cloudflare again/);
// a claim is dropped when no copy of its token can be good any more
const { claims, storage } = cloud();
const then = Date.now() - 3 * 60 * 60 * 1000;
assert.equal(await claimIn(storage, "old", then), true);
assert.equal(await claimIn(storage, "old", then), false);
assert.equal(await claimIn(storage, "new"), true);
assert.deepEqual([...claims.keys()], ["claim:new"]);
});
test("a new consent revokes the access of the sign-in it replaces", async () => {
const { ask, asked, revoked, rows, signIn } = cloud();
signIn("person");
const begun = await ask("/connect?level=full", { headers: { cookie: "__Host-sid=person" } });
const state = new URL(begun.headers.get("location")).searchParams.get("state");
const cookie = ["__Host-sid=person", ...cookiesOf(begun).map((each) => each.split(";")[0])];
rows.set("t:person", JSON.stringify({ token: "OLD", expiresAt: Date.now() + 3600_000 }));
const back = await ask(`/callback?code=c&state=${state}`, {
headers: { cookie: cookie.join("; ") },
});
assert.equal(back.status, 302);
assert.match(back.headers.get("location"), /#connected=full$/);
assert.deepEqual([rows.has("s:person"), rows.has("t:person")], [false, false]);
assert.deepEqual(
revoked.map((each) => each.token),
["OLD"],
);
assert.ok(asked.indexOf("POST /oauth2/revoke") > asked.indexOf("POST /oauth2/token"));
});
test("a body that is not JSON is refused: a form of another site can send text", async () => {
const { ask, asked, signIn } = cloud();
signIn("person");
for (const type of ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data"]) {
const answer = await ask("/api/suggest", suggest({ origin: CLOUD, "content-type": type }));
assert.equal(answer.status, 415, type);
}
assert.deepEqual(asked, []);
});
test("a read needs no Origin: a browser sends none on its own page's GET", async () => {
const { ask, signIn } = cloud();
signIn("person");
const answer = await ask("/api/deploy?account=x", { headers: { cookie: "__Host-sid=person" } });
assert.notEqual(answer.status, 403);
assert.notEqual(answer.status, 401);
});
test("a cookie named sid is no sign-in: another host of the zone can set one", async () => {
const { ask, signIn } = cloud();
signIn("person");
const answer = await ask("/api/me", { headers: { cookie: "sid=person" } });
assert.equal(answer.status, 401);
});
test("a sign-in ends in the browser that started it", async () => {
const { ask, rows, asked, signIn } = cloud();
signIn("before");
const start = await ask("/connect", { headers: { cookie: "__Host-sid=before" } });
const state = new URL(start.headers.get("location")).searchParams.get("state");
const [kept] = cookiesOf(start);
assert.match(
kept,
new RegExp(`^__Host-state-${state}=1; Path=/; HttpOnly; Secure; SameSite=Lax`),
);
// another person's browser gets the address of the callback: no cookie, so no sign-in
const other = await ask(`/callback?state=${state}&code=CODE`);
assert.match(other.headers.get("location"), /^\/#error=/);
assert.deepEqual(cookiesOf(other), []);
assert.deepEqual(asked, [], "the code is not spent");
assert.ok(rows.has(`state:${state}`), "the state stays for the browser that started it");
assert.ok(rows.has("s:before"));
// the browser that started it. It sends no sid cookie here: the way back starts at Cloudflare
const back = await ask(`/callback?state=${state}&code=CODE`, {
headers: { cookie: `__Host-state-${state}=1` },
});
assert.equal(back.headers.get("location"), "/#connected=full");
const [sid, spent] = cookiesOf(back);
assert.match(
sid,
/^__Host-sid=[A-Za-z0-9_-]+; Path=\/; HttpOnly; Secure; Max-Age=\d+; SameSite=Strict$/,
);
assert.match(spent, new RegExp(`^__Host-state-${state}=; .*Max-Age=0$`));
const id = /^__Host-sid=([^;]+)/.exec(sid)[1];
assert.ok(rows.has(`s:${id}`) && rows.has(`t:${id}`));
assert.ok(!rows.has("s:before") && !rows.has("t:before"), "the sign-in before it ended");
assert.ok(!rows.has(`state:${state}`));
// the state works once
const again = await ask(`/callback?state=${state}&code=CODE`, {
headers: { cookie: `__Host-state-${state}=1` },
});
assert.match(again.headers.get("location"), /^\/#error=/);
});