cloud / internal-packages / installer / test / scopes.mjsmain at aacbc74
// What the consent asks (worker/scopes.js). Run: node test/scopes.mjs
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { test } from "node:test";
import {
CLOUDFLARE_TOKEN_EDITION as THE_STACKS_EDITION,
cloudflareTokenGroupsOf,
} from "../../../core/alchemy/src/cloudflare-token.ts";
import { CLOUDFLARE_TOKEN_EDITION as THE_MINDS_EDITION } from "../../../core/mind-worker/src/context/cloudflare-token.ts";
import worker from "../worker/index.js";
import {
CLOUDFLARE_TOKEN_EDITION,
cloudflareTokenCurrent,
connectionAfter,
NEEDED,
PERMISSIONS,
SCOPES,
TELEMETRY_SCOPE,
telemetryGranted,
cloudflareTokenGranted,
WIDER,
} from "../worker/scopes.js";
test("no scope is asked twice, and each has the shape of a Cloudflare scope", () => {
assert.equal(new Set(SCOPES).size, SCOPES.length);
for (const scope of SCOPES) assert.match(scope, /^[a-z0-9_-]+\.[a-z_]+$/);
assert.equal(SCOPES.length, 120);
// asked once and never used by the deploy or the erase
assert.ok(!SCOPES.includes("firewall-services.write"));
});
test("the scopes that the stack's deploy needs are needed ones: a consent without one is told", () => {
assert.equal(NEEDED.length, PERMISSIONS.length);
for (const scope of [
"zone-settings.write",
"email-routing-rule.write",
"workers-scripts.write",
"queues.write",
])
assert.ok(NEEDED.includes(scope), scope);
});
test("the consent asks for no scope that Cloudflare leaves unticked", () => {
// Cloudflare's page lists account-api-tokens.write under "Sensitive scopes", not ticked, and
// refuses the whole consent of a person who presses Authorize without the tick
assert.ok(!SCOPES.includes("account-api-tokens.write"));
});
test("the consent asks for no refresh token and for nothing beyond the account", () => {
// offline_access would give the Cloud standing access; the others reach the person's other
// accounts, or their profile
for (const scope of [
"offline_access",
"offline",
"user-api-tokens.write",
"user-details.write",
"memberships.write",
"scim-provisioning.write",
])
assert.ok(!SCOPES.includes(scope), scope);
});
test("each group of the wider list says what it is for", () => {
for (const [title, why, scopes] of WIDER) {
assert.ok(title && why.endsWith("."), title);
assert.ok(scopes.length > 0, title);
}
});
test("telemetry may turn on only with the scope that makes API tokens, which no plain consent has", () => {
assert.equal(telemetryGranted(SCOPES.join(" ")), false);
assert.equal(telemetryGranted([...SCOPES, TELEMETRY_SCOPE].join(" ")), true);
// a person can decline one of the three that make the warehouse
const declined = SCOPES.filter((scope) => scope !== "pipelines.write");
assert.equal(telemetryGranted([...declined, TELEMETRY_SCOPE].join(" ")), false);
assert.equal(telemetryGranted(undefined), false);
});
/** The Worker's consent against a KV in memory: what `/connect` asks Cloudflare for, and the row
* it keeps for the callback. */
async function connect(query) {
const rows = new Map();
const env = {
CLIENT_ID: "client",
SESSIONS: {
get: async (key) => rows.get(key) ?? null,
put: async (key, value) => void rows.set(key, value),
},
};
const ask = (path) => worker.fetch(new Request(`https://cloud.iterate.com${path}`), env);
const to = new URL((await ask(`/connect?${query}`)).headers.get("location"));
return {
ask,
rows,
asked: to.searchParams.get("scope").split(" "),
state: to.searchParams.get("state"),
};
}
test("the consent that asks for telemetry asks the token scope, and the plain consent does not", async () => {
const plain = await connect("level=full");
assert.deepEqual(plain.asked, SCOPES);
const telemetry = await connect("level=full&telemetry=1");
assert.deepEqual(telemetry.asked, [...SCOPES, TELEMETRY_SCOPE]);
// who you are is all that the first consent of a new account asks, whatever the link says
assert.deepEqual((await connect("level=identity&telemetry=1")).asked, ["user-details.read"]);
});
test("the consent that starts at Give this mind a Cloudflare connection asks the token scope once", async () => {
assert.deepEqual((await connect("level=full&cloudflare=1")).asked, [...SCOPES, TELEMETRY_SCOPE]);
assert.deepEqual((await connect("level=full&cloudflare=1&telemetry=1")).asked, [
...SCOPES,
TELEMETRY_SCOPE,
]);
assert.deepEqual((await connect("level=identity&cloudflare=1")).asked, ["user-details.read"]);
// the token scope alone is what the mind's token takes
assert.equal(cloudflareTokenGranted(SCOPES.join(" ")), false);
assert.equal(cloudflareTokenGranted(`user-details.read ${TELEMETRY_SCOPE}`), true);
assert.equal(cloudflareTokenGranted(undefined), false);
});
test("the consent's row keeps what the person pressed, so the scope alone turns on neither", async () => {
const kept = async (query) => {
const { rows, state } = await connect(query);
const { telemetry, cloudflare } = JSON.parse(rows.get(`state:${state}`));
return { telemetry, cloudflare };
};
assert.deepEqual(await kept("level=full&cloudflare=1"), { telemetry: false, cloudflare: true });
assert.deepEqual(await kept("level=full&telemetry=1"), { telemetry: true, cloudflare: false });
assert.deepEqual(await kept("level=full"), { telemetry: false, cloudflare: false });
// the wizard's full consent: a first deploy turns on both
assert.deepEqual(await kept("level=full&telemetry=1&cloudflare=1"), {
telemetry: true,
cloudflare: true,
});
});
test("a telemetry consent that Cloudflare did not give says what to tick; another one says only the error", async () => {
const back = async ({ ask, state }) => {
const answer = await ask(`/callback?error=access_denied&state=${state}`);
return decodeURIComponent(answer.headers.get("location"));
};
assert.match(
await back(await connect("level=full&telemetry=1")),
/^\/#error=access_denied\. To turn on telemetry, turn on “Account API Tokens Write” under “Sensitive scopes”/,
);
assert.match(
await back(await connect("level=full&cloudflare=1")),
/^\/#error=access_denied\. To give a mind a Cloudflare connection, turn on “Account API Tokens Write” under “Sensitive scopes”/,
);
assert.match(
await back(await connect("level=full&telemetry=1&cloudflare=1")),
/^\/#error=access_denied\. To turn on telemetry and give your mind a Cloudflare connection, turn on “Account API Tokens Write”/,
);
assert.equal(await back(await connect("level=full")), "/#error=access_denied");
});
/** The mind's token's groups, as one short hash: by id, each policy's sorted. */
function tokenGroupsHash() {
const { account, zone } = cloudflareTokenGroupsOf();
const ids = (groups) => groups.map(({ id }) => id).sort();
const both = JSON.stringify({ account: ids(account), zone: ids(zone) });
return createHash("sha256").update(both).digest("hex").slice(0, 16);
}
test("the edition of the mind's Cloudflare token goes with the groups that the stack gives it", () => {
// A change of the token's groups (core/alchemy/src/cloudflare-token.ts) fails here: bump
// CLOUDFLARE_TOKEN_EDITION there, in the mind Worker and here, and give its groups' hash here, so
// that every card of a stack with a token of an older list offers the consent that changes it.
const editions = { 3: "b28c0eeca06a2b09" };
// one number in three places: the stack that names the token, the mind that keeps it, this Cloud
assert.deepEqual(
[THE_STACKS_EDITION, THE_MINDS_EDITION],
[CLOUDFLARE_TOKEN_EDITION, CLOUDFLARE_TOKEN_EDITION],
);
assert.equal(tokenGroupsHash(), editions[CLOUDFLARE_TOKEN_EDITION]);
});
test("the consent asks a scope for the mind's Cloudflare token's one kind of write", () => {
// Cloudflare's refusal is the last word (core/alchemy README, "The mind's Cloudflare token"):
// the token's one write is the query of logs and traces
assert.ok(SCOPES.includes("workers-observability.write"));
});
test("a run's lines say whether the mind has its connection, and whether this release made its token", () => {
const made = ["cloudflare-connection on", "cloudflare-token made by this release"];
assert.deepEqual(connectionAfter(made, undefined), {
connection: true,
connectionEdition: CLOUDFLARE_TOKEN_EDITION,
});
// an update that kept the token keeps its edition, and one from before the editions has none
const kept = ["cloudflare-connection on"];
assert.deepEqual(connectionAfter(kept, { connection: true, connectionEdition: 1 }), {
connection: true,
connectionEdition: 1,
});
assert.equal(connectionAfter(kept, { connection: true }).connectionEdition, undefined);
assert.deepEqual(connectionAfter(["cloudflare-connection off"], { connection: true }), {
connection: false,
});
// a run that ended before its deploy said either keeps what the run before it said
assert.deepEqual(
connectionAfter(["The deploy failed (exit 1)."], { connection: true, connectionEdition: 2 }),
{
connection: true,
connectionEdition: 2,
},
);
});
test("a token of an older edition, or of none, is not this release's", () => {
assert.equal(
cloudflareTokenCurrent({ connection: true, connectionEdition: CLOUDFLARE_TOKEN_EDITION }),
true,
);
assert.equal(cloudflareTokenCurrent({ connection: true, connectionEdition: 1 }), false);
assert.equal(cloudflareTokenCurrent({ connection: true }), false);
assert.equal(cloudflareTokenCurrent({ connection: false }), false);
assert.equal(cloudflareTokenCurrent(undefined), false);
});