iterate.com / cloud

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

cloud / internal-packages / cloud-ai / src / auth.tsmain at aacbc74

import { identityKeyIdOf } from "iterate/mind-identity";
import { type PublishedMind, publishedMindOf } from "iterate/mind-identity-log";
import {
  type Envelope,
  envelopeOfStatementHeader,
  isMindControlPlaneHostname,
  isMindId,
  ITERATE_STATEMENT_HEADER,
  MIND_FETCH_STATEMENT_TYPE,
  statementOf,
  verifySignature,
} from "iterate/signed";
import { z } from "zod";

const FetchPayload = z.strictObject({
  method: z.string(),
  url: z.string(),
});

export type EnrolmentsBinding = {
  enrolled(mindId: string): Promise<boolean>;
};

export type CloudAiAuthEnv = {
  MIND_ID?: string;
  MIND_HOSTNAME?: string;
  ENROLMENTS?: EnrolmentsBinding;
  /** `"on"` (default): require `ENROLMENTS.enrolled(mindId)`. `"off"`: skip enrolment check in standalone dev. */
  CLOUD_ENROLMENT?: string;
  /** THE HOUSE ACCOUNTS, as JSON: `{ "<mind id>": { "hostname": "<its control plane>" } }`. A house
   *  account is a mind that iterate serves by this configuration, with no enrolment row and with
   *  no spend limit of the Cloud's own (Jonas, 25 Nov 2026: "our mind has no spend limit, but
   *  others do"). Every mind's requests go through the ONE gateway (Jonas, 26 Nov 2026: "we only
   *  want one ai gateway for all customers including ourselves"); a house account's carry
   *  `spendPlan: "house"` there, any other mind's `"standard"` (`SpendPlan`). The Cloud's own mind is one, because a mind does not meld with itself
   *  (core/auth-worker minds.ts) and so cannot enrol. It is an entry here like any other, not a
   *  case in the code: another of iterate's minds is one more entry. Text that does not parse
   *  names nobody. */
  CLOUD_AI_HOUSE_ACCOUNTS?: string;
};

const HouseAccounts = z.record(z.string(), z.strictObject({ hostname: z.string().min(1) }));

/** The house account of the mind `mindId` when its statement comes from that account's hostname,
 *  or null. Both must hold: the id that the mind's log proved, and the hostname it wrote from. */
function houseAccountOf(env: CloudAiAuthEnv, mindId: string, hostname: string) {
  if (!env.CLOUD_AI_HOUSE_ACCOUNTS) return null;
  let parsed: unknown;
  try {
    parsed = JSON.parse(env.CLOUD_AI_HOUSE_ACCOUNTS);
  } catch {
    parsed = null;
  }
  const accounts = HouseAccounts.safeParse(parsed);
  if (!accounts.success) {
    console.error({ event: "cloud-ai.house-accounts-unreadable" });
    return null;
  }
  const account = isMindId(mindId) ? accounts.data[mindId] : undefined;
  return account && account.hostname === hostname ? account : null;
}

/** WHICH SPEND RULES OF THE GATEWAY COUNT A MIND'S REQUESTS. The Cloud writes it on every
 *  request as the metadata entry `spendPlan`, and a spend rule of the gateway names the plan that
 *  it is for (the rule's `spendPlan` dimension, "Filter by value"). So one gateway holds a limit
 *  for each customer mind (`standard`) and another, or none, for a house account (`house`); the
 *  rule with no dimension bounds all of them together. The rules are the gateway's settings, not
 *  code: docs/api-keys.md. */
export type SpendPlan = "house" | "standard";

export type AuthenticatedMind = {
  mindId: string;
  mindSlug: string;
  /** Not given is `standard`: only this module's authenticator names a house account. */
  spendPlan?: SpendPlan;
  expiresAtMs: number;
};

export type MindAuthenticatorOptions = {
  fetcher?: (request: Request) => Promise<Response>;
  now?: () => number;
};

/** Stateful verifier for signed mind requests (`iterate-auth-statement`). Keeps the latest verified
 *  identity-log head per `mindId` so another hostname serving an older head cannot revive a revoked
 *  working key, and caches positive/negative enrolment lookups briefly within the statement's expiry. */
export function createMindAuthenticator(options: MindAuthenticatorOptions = {}) {
  const fetcher = options.fetcher || ((request: Request) => fetch(request));
  const nowOf = options.now || (() => Date.now());
  const keptLogs = new Map<string, PublishedMind>();
  const enrolments = new Map<string, { enrolled: boolean; until: number }>();

  return async function authenticateMindRequest(
    request: Request,
    env: CloudAiAuthEnv,
  ): Promise<{ caller: AuthenticatedMind } | { response: Response }> {
    const asked = URL.parse(request.url);
    if (!asked) return { response: jsonError(400, "request URL must be absolute") };

    const header = request.headers.get(ITERATE_STATEMENT_HEADER);
    if (!header) {
      return {
        response: jsonError(401, `missing ${ITERATE_STATEMENT_HEADER} header`),
      };
    }

    const envelope = envelopeOfStatementHeader(header);
    if (!envelope) {
      return {
        response: jsonError(401, `${ITERATE_STATEMENT_HEADER} holds no signed statement`),
      };
    }

    const fields = statementOf(envelope.statement);
    if ("refused" in fields) return { response: jsonError(401, fields.refused) };

    if (fields.type !== MIND_FETCH_STATEMENT_TYPE) {
      return { response: jsonError(401, `statement type must be ${MIND_FETCH_STATEMENT_TYPE}`) };
    }
    if (envelope.signature.format !== "ML-DSA-65") {
      return {
        response: jsonError(401, "a mind's signed request must use its ML-DSA-65 working key"),
      };
    }
    if (fields.path !== "/") {
      return { response: jsonError(401, 'a signed request statement must target path "/"') };
    }

    const expectedMindId = env.MIND_ID;
    const expectedHostname = env.MIND_HOSTNAME || asked.hostname;
    const matchesAudience =
      (Boolean(expectedMindId) && fields.mind === expectedMindId) ||
      fields.mind === expectedHostname ||
      fields.mind === asked.hostname;
    if (!matchesAudience) {
      return { response: jsonError(401, "statement is addressed to another mind") };
    }

    const payload = FetchPayload.safeParse(fields.payload);
    if (!payload.success) {
      return { response: jsonError(401, "statement payload must be { method, url }") };
    }
    const method = request.method.toUpperCase();
    if (payload.data.method !== method) {
      return {
        response: jsonError(401, `statement is signed for ${payload.data.method}, not ${method}`),
      };
    }
    if (payload.data.url !== asked.href) {
      return { response: jsonError(401, "statement is signed for another URL") };
    }

    const startNow = nowOf();
    if (fields.expires <= startNow) {
      return { response: jsonError(401, "statement has expired") };
    }
    if (
      fields.at >= fields.expires ||
      fields.at > startNow + 30_000 ||
      fields.expires - fields.at > 300_000
    ) {
      return {
        response: jsonError(
          401,
          "statement must start near now and expire within five minutes of `at`",
        ),
      };
    }

    const sender = senderFromFields(fields.from, fields.fromHost);
    if ("refused" in sender) return { response: jsonError(401, sender.refused) };

    // A HOST THAT FAILS IS NOT A HOST WITH NO LOG. A 5xx of the mind's host says nothing about its
    // keys: the same read may pass a moment later (27 Nov 2026: one 500 from a D1 read behind the
    // host). `publishedMindOf` keeps every answer of a host for a minute, and does not keep a read
    // whose fetcher threw. So a 5xx is thrown here: the request is still refused, with 503 in
    // place of 401, and the next request reads again. Nothing is served from an older state.
    let hostFailed = false;
    const reading = async (asked: Request) => {
      const answer = await fetcher(asked).catch((error: unknown) => {
        hostFailed = true;
        throw error;
      });
      if (answer.status < 500) return answer;
      hostFailed = true;
      await answer.body?.cancel().catch(() => {});
      throw new Error(`it answered ${answer.status}`);
    };
    let published = await publishedMindOf(
      sender.host,
      reading,
      sender.id ? keptLogs.get(sender.id) : undefined,
    );
    if (!sender.id && !("why" in published)) {
      const kept = keptLogs.get(published.expected);
      if (kept && kept.head !== published.head) {
        published = await publishedMindOf(sender.host, reading, kept);
      }
    }
    if ("why" in published && hostFailed) {
      console.warn({
        event: "cloud-ai.key-history-read-failed",
        host: sender.host,
        why: published.why,
      });
      return {
        response: jsonError(503, `${sender.host.slice(0, 80)} gave no keys now: ${published.why}`, {
          "retry-after": "5",
        }),
      };
    }
    if ("why" in published) {
      return {
        response: jsonError(401, `${sender.host.slice(0, 80)} gave no keys: ${published.why}`),
      };
    }
    if (sender.id && published.expected !== sender.id) {
      return {
        response: jsonError(
          401,
          `${sender.host.slice(0, 80)} serves another mind's log than statement.from`,
        ),
      };
    }
    // A HOUSE ACCOUNT (`CLOUD_AI_HOUSE_ACCOUNTS`) is served with no enrolment row. Everything above
    // and below holds for it as for any mind: the audience, the URL, the times, its log and its
    // working key's signature. The Cloud's own mind is served only as such an entry.
    const houseAccount = houseAccountOf(env, published.expected, sender.host);

    rememberBounded(keptLogs, published.expected, published);

    const publicKey = await workingKeyOf(published, envelope);
    if (!publicKey) {
      return {
        response: jsonError(401, `${sender.host.slice(0, 80)} lists no matching statement key`),
      };
    }

    const verified = await verifySignature(envelope, publicKey, {
      origin: asked.origin,
      rpId: asked.hostname,
    });
    if ("refused" in verified) return { response: jsonError(401, verified.refused) };

    const settledNow = nowOf();
    if (settledNow >= fields.expires) {
      return { response: jsonError(401, "statement expired during verification") };
    }

    if (!houseAccount) {
      const enrolmentStatus = await checkEnrolment(
        published.expected,
        fields.expires,
        settledNow,
        env,
        enrolments,
      );
      if ("response" in enrolmentStatus) return enrolmentStatus;
    }

    console.info({
      event: "cloud-ai.mind-authenticated",
      mindId: published.expected,
      mindSlug: sender.host,
      pathname: asked.pathname,
      ...(houseAccount && { houseAccount: true }),
    });

    return {
      caller: {
        mindId: published.expected,
        mindSlug: sender.host,
        spendPlan: houseAccount ? "house" : "standard",
        expiresAtMs: fields.expires,
      },
    };
  };
}

function senderFromFields(
  from: string | undefined,
  fromHost: string | undefined,
): { id?: string; host: string } | { refused: string } {
  if (!from) return { refused: "statement names no sending mind in `from`" };
  if (isMindId(from) && fromHost && isMindControlPlaneHostname(fromHost)) {
    return { id: from, host: fromHost };
  }
  if (!fromHost && isMindControlPlaneHostname(from)) {
    return { host: from };
  }
  return { refused: "statement `from` must be a mind id with `fromHost` (or control-plane host)" };
}

async function workingKeyOf(published: PublishedMind, envelope: Envelope): Promise<string | null> {
  for (const key of published.current.workingKeys) {
    if (key.purpose !== "statements") continue;
    if ((await identityKeyIdOf(key.publicKey)) !== envelope.signature.key) continue;
    return key.publicKey;
  }
  return null;
}

async function checkEnrolment(
  mindId: string,
  statementExpiresMs: number,
  now: number,
  env: CloudAiAuthEnv,
  cache: Map<string, { enrolled: boolean; until: number }>,
): Promise<{ ok: true } | { response: Response }> {
  if (env.CLOUD_ENROLMENT === "off") return { ok: true };
  if (!env.ENROLMENTS) {
    return {
      response: jsonError(503, "Cloud enrolment service is not configured", { "retry-after": "5" }),
    };
  }

  const cached = cache.get(mindId);
  if (cached && cached.until > now) {
    return cached.enrolled
      ? { ok: true }
      : { response: jsonError(403, `mind ${mindId} is not enrolled in Iterate Cloud`) };
  }

  let enrolled: boolean;
  try {
    enrolled = await env.ENROLMENTS.enrolled(mindId);
  } catch (error) {
    console.warn({
      event: "cloud-ai.enrolment-check-failed",
      mindId,
      error: error instanceof Error ? error.message : String(error),
    });
    return {
      response: jsonError(503, "enrolment check temporarily unavailable", { "retry-after": "5" }),
    };
  }

  if (!enrolled) {
    console.info({ event: "cloud-ai.mind-not-enrolled", mindId });
    return { response: jsonError(403, `mind ${mindId} is not enrolled in Iterate Cloud`) };
  }

  const until = Math.min(now + 60_000, statementExpiresMs);
  rememberBounded(cache, mindId, { enrolled: true, until });
  return { ok: true };
}

function rememberBounded<Value>(map: Map<string, Value>, key: string, value: Value) {
  map.delete(key);
  map.set(key, value);
  if (map.size > 1_000) {
    const oldest = map.keys().next().value;
    if (oldest) map.delete(oldest);
  }
}

export function jsonError(
  status: number,
  error: string,
  extraHeaders?: Record<string, string>,
): Response {
  return Response.json(
    { error },
    {
      status,
      headers: {
        "cache-control": "no-store",
        ...extraHeaders,
      },
    },
  );
}