iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / worker / cloudflare-access.jsmain at aacbc74

// cloudflare-access.js — THE INSTALLER'S CLOUDFLARE SIGN-IN, WITH NO REFRESH TOKEN ANYWHERE: the
// code exchange, the revoke, and the hand-over of the token from the session to a deploy run.
// iterate's Cloud keeps no Cloudflare token: the person's access token lasts about an hour and is
// never renewed. worker/index.js calls these; worker/deploy-run.js revokes the token at a run's end.

/** The rule the session follows (worker/index.js).
 *
 *  A sign-in is two KV records. `t:<id>` holds Cloudflare's access token and when it ends; KV
 *  deletes the record at that time, about an hour after the sign-in. `s:<id>` holds who the person
 *  is and no credential, and lives longer. Nothing writes `t:<id>` after the sign-in, so no late
 *  write can put a token back. There is never a refresh token: the installer does not ask for
 *  offline_access, and revokes a refresh token that Cloudflare sends all the same. When a deploy
 *  starts, takeToken deletes `t:<id>` and gives the token to the run alone, which revokes it at
 *  its end. A sign-out, and a new consent that replaces a sign-in, revoke the token that
 *  `t:<id>` still holds (worker/index.js `endSession`).
 *
 *  ONE OF THE TWO ENDS A TOKEN, NEVER BOTH. KV answers a read from a cache for about a minute, so
 *  `t:<id>` can still show a token that a run took or a sign-out revoked. A run that took such a
 *  token would work with a dead one; a sign-out that revoked such a token would end a run's access
 *  in the middle of a deploy. So each of them first claims the sign-in (`claimToken`), in a record
 *  that is read strongly: the first claim of a sign-in gets the token, each later one gets nothing. */

// Cloudflare's own endpoints, the defaults: the installer's config may name others (a pretend
// Cloudflare, a test), and passes them in.
// the endpoint https://dash.cloudflare.com/.well-known/openid-configuration names
const REVOKE_URL = "https://dash.cloudflare.com/oauth2/revoke";
// Only the run's deploy step uses the token, for a few minutes: one that ends sooner than this
// could fail in the middle.
const LEAST_LEFT_FOR_A_DEPLOY = 10 * 60 * 1000;

/** Exchanges an authorization code (with its PKCE verifier) for an access token. Answers
 *  `{ token, expiresAt, scope }`, `expiresAt` in milliseconds since the epoch. A refresh token that
 *  Cloudflare sends all the same is revoked at once and never returned: `refresh` says whether
 *  one came, as `{ revoke }`, the status of that revoke, or null. Throws when Cloudflare refuses
 *  the code or sends no access token. */
export async function exchange({
  code,
  verifier,
  redirectUri,
  clientId,
  clientSecret,
  tokenUrl = "https://dash.cloudflare.com/oauth2/token",
  revokeUrl = REVOKE_URL,
  fetch = globalThis.fetch,
}) {
  const answer = await fetch(tokenUrl, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      redirect_uri: redirectUri,
      client_id: clientId,
      client_secret: clientSecret,
      code_verifier: verifier,
    }),
  });
  const tokens = await answer.json().catch(() => ({}));
  const refresh = tokens.refresh_token
    ? await revoke({ token: tokens.refresh_token, clientId, clientSecret, revokeUrl, fetch })
    : null;
  if (!answer.ok)
    throw new Error(
      `Cloudflare refused the code: ${tokens.error_description || tokens.error || answer.status}`,
    );
  if (!tokens.access_token) throw new Error("Cloudflare sent no token");
  return {
    token: tokens.access_token,
    expiresAt: Date.now() + (Number(tokens.expires_in) || 3600) * 1000,
    scope: tokens.scope || "",
    refresh: refresh && { revoke: refresh.status },
  };
}

/** Asks Cloudflare to revoke a token (RFC 7009), an access token or a refresh token. Answers
 *  `{ ok, status }`; `status` is 0 when Cloudflare could not be reached. Never throws: the caller
 *  says a failed revoke, it does not hide it. */
export async function revoke({
  token,
  clientId,
  clientSecret,
  revokeUrl = REVOKE_URL,
  fetch = globalThis.fetch,
}) {
  try {
    const answer = await fetch(revokeUrl, {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({ token, client_id: clientId, client_secret: clientSecret }),
    });
    await answer.body?.cancel();
    return { ok: answer.ok, status: answer.status };
  } catch {
    return { ok: false, status: 0 };
  }
}

/** Gives up a token at a run's end, and proves it: asks Cloudflare to revoke the token, then asks
 *  Cloudflare with that token for the account it could read (`GET /accounts/<id>`). Answers
 *  `{ revoke, revoked, probe, works }`: the status of the revoke and whether it was a success,
 *  the status the token then got (0: no answer), and `works`: false when Cloudflare refuses the
 *  token (401, 403), true when Cloudflare still answers it, null when the question got no
 *  answer. A token that is not refused yet is asked about again, `tries` times at most, `pause`
 *  ms apart: the revoke's answer does not say when every part of Cloudflare knows. Never throws. */
export async function giveUp({
  token,
  accountId,
  clientId,
  clientSecret,
  revokeUrl = REVOKE_URL,
  api = "https://api.cloudflare.com/client/v4",
  fetch = globalThis.fetch,
  tries = 8,
  pause = 2500,
}) {
  const revoked = await revoke({ token, clientId, clientSecret, revokeUrl, fetch });
  let probe = 0;
  /** @type {boolean | null} */
  let works = null;
  for (let attempt = 1; attempt <= tries; attempt++) {
    try {
      const answer = await fetch(`${api}/accounts/${accountId}`, {
        headers: { authorization: `Bearer ${token}` },
      });
      await answer.body?.cancel();
      probe = answer.status;
      works = answer.ok ? true : probe === 401 || probe === 403 ? false : null;
    } catch {
      probe = 0;
      works = null;
    }
    if (works === false) break;
    if (attempt < tries) await new Promise((done) => setTimeout(done, pause));
  }
  return { revoke: revoked.status, revoked: revoked.ok, probe, works };
}

/** What a run's last step says about `giveUp`'s answer: one line with both statuses, and, when
 *  the token still works, the run's stop with what the person does about it. `ends`: when the
 *  access ends by itself, as a sentence. */
export function forgetLinesOf({ revoke, revoked, probe, works }, ends) {
  const first = revoked
    ? `Cloudflare revoked the access (${revoke}).`
    : `Cloudflare did not revoke the access (${revoke || "no answer"}).`;
  if (works === false) return [`${first} The token now gets ${probe}.`];
  if (works === null)
    return [
      `${first} Whether the token still works could not be checked (${probe || "no answer"}). ${ends}`,
    ];
  return [
    `${first} The token still works: it gets ${probe}.`,
    `Stopped: iterate could not give up its access to your Cloudflare account. Remove “Iterate Cloud” yourself: in the Cloudflare dashboard, open your profile, then Access Management, then Connected Applications. ${ends}`,
  ];
}

/** The KV `expirationTtl` of a token's record, in seconds: until the token ends, at least 60 (KV's least). */
export const tokenTtlOf = (expiresAt) => Math.max(60, Math.ceil((expiresAt - Date.now()) / 1000));

/** The object of the run class that runs nothing and keeps the claims (`Deployer.claim`). */
export const CLAIMS = "sign-ins";
// longer than a token lasts (an hour), so a claim outlives every copy of its token
const CLAIM_KEPT_MS = 2 * 60 * 60 * 1000;

/** Claims the token of the sign-in `sessionId`, for the one who ends it: a run (which revokes it
 *  at its end) or the session's end (which revokes it at once). True for the first claim of a
 *  sign-in, false for each later one. */
export const claimToken = (env, sessionId) => env.DEPLOYER.getByName(CLAIMS).claim(sessionId);

/** `Deployer.claim` on the object's `storage`: true when nobody claimed `sessionId` before, and
 *  then it is claimed. Claims older than a token can be are dropped on the way. */
export async function claimIn(storage, sessionId, now = Date.now()) {
  const old = [...(await storage.list({ prefix: "claim:" }))]
    .filter(([, at]) => now - at > CLAIM_KEPT_MS)
    .map(([key]) => key);
  if (old.length > 0) await storage.delete(old.slice(0, 128));
  const key = `claim:${sessionId}`;
  if (await storage.get(key)) return false;
  await storage.put(key, now);
  return true;
}

/** Takes the token of the sign-in `sessionId` out of `env.SESSIONS`, for a deploy run: deletes
 *  `t:<sessionId>` and answers `{ token, expiresAt }`. Call it just before `Deployer.start`; from
 *  then on, KV holds no token. Throws when there is no token, one that ends too soon for a
 *  deploy, or one that another run or a sign-out claimed before: the person connects Cloudflare
 *  again. */
export async function takeToken(env, sessionId) {
  const key = `t:${sessionId}`;
  const access = JSON.parse((await env.SESSIONS.get(key)) || "null");
  if (!access?.token) throw new Error("no access to Cloudflare: connect Cloudflare again");
  if (access.expiresAt - Date.now() < LEAST_LEFT_FOR_A_DEPLOY)
    throw new Error(
      "the access to Cloudflare ends too soon for a deploy: connect Cloudflare again",
    );
  const mine = await claimToken(env, sessionId);
  await env.SESSIONS.delete(key);
  if (!mine) throw new Error("no access to Cloudflare: connect Cloudflare again");
  return access;
}