iterate.com / cloud

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

cloud / internal-packages / cloud-clients / src / secrets-compat.test.tsmain at aacbc74

// The Cloud's derived keys against the secrets Worker's operations: a mind's secret that holds
// `CLOUD_KEY` seals, opens and proves exactly as keys.ts does, so the Cloud can move into a mind's
// secret with no change for the minds that hold its sealed values and proofs.
import { timingSafeEqual } from "node:crypto";
import { expect, test } from "vitest";
import {
  hmacKeyOf,
  sealedText,
  unsealedText,
} from "../../../core/secrets-worker/src/secret/key-ops.ts";
import { signSecretHmac, verifySecretHmac } from "../../../core/secrets-worker/src/secrets.ts";
import { botProofOf, keysOf, seal, unseal } from "./keys.ts";

// workerd's own comparison, which Node's Web Crypto has not got
Object.assign(crypto.subtle, { timingSafeEqual });

const HELD = { token: "a refresh token", mind: "iterate.example.com", client: "google" };

test("a value the Cloud seals opens in the secret, and one the secret seals opens at the Cloud", async () => {
  const { cloudKey, material } = await cloudKeyPair();
  const { sealKey } = await keysOf(cloudKey);
  const info = "iterate-cloud/seal";
  const sealed = await seal(sealKey, HELD);
  expect(JSON.parse(await unsealedText(material, { info, sealed }))).toEqual(HELD);
  const ours = await sealedText(material, { info, plaintext: JSON.stringify(HELD) });
  expect(await unseal(sealKey, ours)).toEqual(HELD);
});

test("a proof the secret makes with derive is the Cloud's proof, and the Cloud's verifies there", async () => {
  const { cloudKey, material } = await cloudKeyPair();
  const { proofKey } = await keysOf(cloudKey);
  const until = 1_800_000_000_000;
  const payload = `bot-link\nx\n${until}`;
  const input = { payload, derive: { info: "iterate-cloud/proof" } };
  const hex = await signSecretHmac(await hmacKeyOf(material, input), input);
  const cloudProof = await botProofOf(proofKey, "link", "x", until);
  expect(Buffer.from(hex!, "hex").toString("base64url")).toBe(cloudProof);
  const signature = Buffer.from(cloudProof, "base64url").toString("hex");
  expect(await verifySecretHmac(await hmacKeyOf(material, input), { ...input, signature })).toBe(
    true,
  );
});

/** A P-256 key made here, as `CLOUD_KEY` (a private JWK as JSON) and as a signing secret holds it. */
async function cloudKeyPair() {
  const P256 = { name: "ECDSA", namedCurve: "P-256" } as const;
  const pair = (await crypto.subtle.generateKey(P256, true, ["sign", "verify"])) as CryptoKeyPair;
  // the cast: a "jwk" export answers a JsonWebKey; the generated types answer either form
  const { kty, crv, x, y, d } = (await crypto.subtle.exportKey(
    "jwk",
    pair.privateKey,
  )) as JsonWebKey;
  const cloudKey = JSON.stringify({ kty, crv, x, y, d });
  return { cloudKey, material: { privateKey: cloudKey } };
}