iterate.com / cloud

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

cloud / internal-packages / cloud-clients / src / signed.tsmain at aacbc74

// signed.ts — A SIGNED STATEMENT, the one credential between the Cloud and a deployment. Its shape
// is the deployment's (core/lib src/signed.ts, `iterate/signed` on a stack); this is the Cloud's
// copy of the two things it does with one: sign with its own key, and check a deployment's.
//
//   statement   exact JSON text: { mind, path, type, payload, at, expires, nonce }, where `mind`
//               is the deployment's name, its control plane's hostname; the times are
//               milliseconds
//   the bytes   DSSE: "DSSEv1 " + len(T) + " " + T + " " + len(text) + " " + text, lengths in bytes
//   the Cloud's own key
//     signature   `p256`: ECDSA P-256 with SHA-256 over those bytes, raw r‖s, base64url
//     public key  SubjectPublicKeyInfo DER, base64url; its id is base64url(SHA-256(DER))
//   a deployment's stack key, as `/keys/stack.json` shows it
//     signature   `ML-DSA-65`: pure ML-DSA-65 (FIPS 204), empty context, over those bytes, base64url
//     public key  the raw key, 1952 bytes, base64url; its id is base64url(SHA-256(raw))
//   A Worker that checks ML-DSA-65 has the compatibility flag `webcrypto_modern_algorithms`
//   (internal-packages/installer wrangler.jsonc).
//
// Nobody serializes a statement twice: the text that was signed is the text that travels.

const T = "application/vnd.iterate.statement+json";
const P256 = { name: "ECDSA", namedCurve: "P-256" } as const;
const SIGN = { name: "ECDSA", hash: "SHA-256" } as const;
const ML_DSA_65 = { name: "ML-DSA-65" } as const;
/** How each format's key is read and its signature checked. `raw-public` is the format of an
 *  ML-DSA public key, which TypeScript's library does not list yet: the cast names one it knows,
 *  and the runtime gets the string as written. */
const CHECKS: Record<
  string,
  {
    keyFormat: "spki" | "raw";
    key: SubtleCryptoImportKeyAlgorithm;
    verify: SubtleCryptoSignAlgorithm;
  }
> = {
  p256: { keyFormat: "spki", key: P256, verify: SIGN },
  "ML-DSA-65": { keyFormat: "raw-public" as "raw", key: ML_DSA_65, verify: ML_DSA_65 },
};
const encoder = new TextEncoder();

/** Everything of a statement but its nonce. `mind` is the deployment that the Cloud's statement
 *  is for, or that a deployment's own statement is from: its control plane's hostname. */
type Fields = {
  mind: string;
  path: string;
  type: string;
  payload: unknown;
  at: number;
  expires: number;
};
export type Statement = Fields & { nonce: string };

/** A statement as it travels: the body of `POST https://<mind>/statements`, and the value of a
 *  deployment's `iterate-auth-statement` header (base64url of this JSON; `iterate-statement` is
 *  still read). The Cloud's own key signs
 *  `p256`; a deployment's stack, and the Cloud's own mind, sign `ML-DSA-65`. */
export type Signed = {
  statement: string;
  signature: { format: "p256" | "ML-DSA-65"; key: string; sig: string };
};

export const base64url = (bytes: ArrayBuffer | Uint8Array) =>
  Buffer.from(bytes as Uint8Array).toString("base64url");

const signedBytes = (statement: string) => {
  const body = encoder.encode(statement);
  return Buffer.concat([
    encoder.encode(`DSSEv1 ${encoder.encode(T).length} ${T} ${body.length} `),
    body,
  ]);
};

export const keyIdOf = async (publicKey: string) =>
  base64url(await crypto.subtle.digest("SHA-256", Buffer.from(publicKey, "base64url")));

/** The Cloud's key, from its private JWK: its public half and id, and `sign`, which adds the nonce
 *  and answers the statement as it travels. */
export async function signerOf(privateJwk: JsonWebKey) {
  const { kty, crv, x, y } = privateJwk;
  const privateKey = await crypto.subtle.importKey("jwk", privateJwk, P256, false, ["sign"]);
  const publicKey = base64url(
    (await crypto.subtle.exportKey(
      "spki",
      await crypto.subtle.importKey("jwk", { kty, crv, x, y }, P256, true, ["verify"]),
    )) as ArrayBuffer,
  );
  const key = await keyIdOf(publicKey);
  return {
    key,
    publicKey,
    async sign(fields: Fields): Promise<Signed> {
      const nonce = base64url(crypto.getRandomValues(new Uint8Array(16)));
      const statement = JSON.stringify({ ...fields, nonce });
      const sig = await crypto.subtle.sign(SIGN, privateKey, signedBytes(statement));
      return { statement, signature: { format: "p256", key, sig: base64url(sig) } };
    },
  };
}

/** The statement `signed` holds, when `publicKey` signed exactly that text and it has not expired;
 *  null for anything else. The signature's format names the check: `ML-DSA-65` under a raw key,
 *  as a deployment's `/keys/stack.json` shows it, and `p256` under SubjectPublicKeyInfo, the
 *  Cloud's own. A key of the other algorithm does not import, and answers null. */
export async function statementOf(
  signed: Signed,
  publicKey: string,
  now = Date.now(),
): Promise<Statement | null> {
  try {
    const { format, key: id, sig } = signed.signature;
    if (id !== (await keyIdOf(publicKey))) return null;
    const check = CHECKS[format];
    if (!check) return null;
    const key = await crypto.subtle.importKey(
      check.keyFormat,
      Buffer.from(publicKey, "base64url"),
      check.key,
      false,
      ["verify"],
    );
    const good = await crypto.subtle.verify(
      check.verify,
      key,
      Buffer.from(sig, "base64url"),
      signedBytes(signed.statement),
    );
    if (!good) return null;
    const statement = JSON.parse(signed.statement) as Statement;
    if (typeof statement.expires !== "number" || statement.expires <= now) return null;
    return statement;
  } catch {
    return null;
  }
}