iterate.com / kernel

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

kernel / core / itx / src / caller.tsmain at 949894f

import { itxExpressionStepName, type ItxExpressionPrefix } from "iterate/expression";
import { codedError } from "iterate/lib";
import type { MemberPrincipal, MindPrincipal, Person, Principal } from "iterate/principal";
import type { EventCopiedFrom, StreamEventInput } from "iterate/stream/processor";
import { storedCause, type Cause } from "./cause.ts";
import type { OnBehalfOf } from "./on-behalf-of.ts";

// Set only by trusted code: the DO's `invoke` is a Workers-RPC verb, never capnweb-exposed, so a
// client cannot supply its own `Caller`.
export type Caller = {
  // A member, or null. Never another mind: that rides `mind`, so no check that reads this field
  // can take a mind for a member. The two types differ, so a swapped assignment does not compile.
  principal: MemberPrincipal | null;
  grant?: string;
  // The signed-in person of a visitor, member or not, as the boundary stamped them on the request
  // that this call serves (iterate/principal `stampedCallerOf`). Read there alone: a Request that
  // the kernel hands to loaded code names the person from here (./context/rpc-stubs.ts
  // `stampCallerHeaders`), never from its own headers.
  person?: Person;
  // Another mind that asks, as the boundary stamped it on the request that this call serves
  // (iterate/principal `principalStampOf`): `{ actor: <mind id>, kind: "mind", hostname }`. Read
  // there alone, and carried wherever `person` is. It gives NO authority: nothing decides by it,
  // no event is stamped with it, and to the kernel the call is one that names no member. A Request
  // that the kernel hands to loaded code names it in `x-itx-mind` when no member asks
  // (./context/rpc-stubs.ts `stampCallerHeaders`), so the mind's own code can decide by its id.
  mind?: MindPrincipal;
  // A member's session held by a page of the mind's own host (serve-host.ts `itxSession`).
  via?: { appPage: string };
  // Set by the first `cd` hop. Its presence means the input expression was already admitted;
  // fresh env.ITX calls never inherit it.
  path?: string;
  app?: true;
  // Loaded code that is the mind's published config itself: the Worker the config pointer names,
  // never a script or a worker it loads. Its rows may have built-in targets, so it can build a
  // jail whose names reach exactly what it grants (`admitRowsOfCall`). Set only by
  // `ItxEntrypoint`, from a prop that only the host mints (host.ts `itxEntrypointFor`).
  config?: true;
  // Set only by the host's own code, on a fact it vouches for (`refuseNonPlatformWrites`).
  platform?: true;
  // The exact text of an act that a member approved, on the one call that does it. Set only by the
  // host's own code and by a resolver that sends an approved call on. The call is no platform's
  // call (./context/itx-expression-rewriting.ts `invokeApproved` says how it is handled).
  approvedAct?: string;
  // The key that signed what this call appends, as the auth Worker verified it. Set only where the
  // auth Worker's own answer is appended (the mind Worker's `Mind.append`): an event never names its
  // own signer. `member`: whether the signer was a member of the mind at the signing.
  signer?: { principal: Principal; key: string; member?: boolean };
  // The SHA-256 of what a delivery delivers: a target answers only what it names, so nothing it
  // reaches can hand a subscriber an event its log never held.
  delivery?: string;
  // This call runs the target of a stored row: a subscription's delivery, or the ingress row for
  // a request. A row that it writes is checked as loaded code's own is
  // (./context/itx-expression-rewriting.ts `admitRowsOfCall` says why). Set only where a row's
  // target is run, and it stays on the caller across contexts.
  runsRow?: true;
  // This call is the platform's own MCP server asking a config's class what a server offers, or
  // calling one of its tools (iterate/sdk `IterateConfigEntrypoint.mcpCall`). Set only by the
  // mind Worker's MCP server and by serve-host.ts, where the platform itself names the client and
  // the person: no other caller reaches `mcpCall` (./context/built-ins.ts `workersRoot`).
  mcpServer?: true;
  // The token of the one request that serve-host.ts hands to the ingress row's target
  // (iterate/mind-ingress `ITERATE_SERVE_TOKEN_HEADER`). Set only there. It is written on the
  // Request that loaded code gets from this call (./context/rpc-stubs.ts `requestForLoadedCode`)
  // and crosses no hop: a call that loaded code makes has a caller of its own, with none.
  serveToken?: string;
  // An internal hop made through `libraryItx` (`repos`, `sandboxes`, `files`) on behalf of an
  // outer expression: activity tracking records the outer call alone so internal hops do not stack
  // duplicate pills underneath it.
  libraryHop?: true;
  copiedFrom?: EventCopiedFrom;
  cause?: Cause;
  onBehalfOf?: OnBehalfOf;
};
export const ITX_GRANT_HEADER = "x-itx-grant";
// Stripped from every Request that arrives from outside.
export const ITX_APP_HEADER = "x-itx-app";
export const ITX_CALLER_PATH_HEADER = "x-itx-caller-path";
export const ITX_RUNS_ROW_HEADER = "x-itx-runs-row";

// A writer's own `source` is dropped but `processor`. `origin` is advisory: a `run-requested`
// anyone appends runs, and is stamped, where it lands.
export function stampCaller<E extends { source?: StreamEventInput["source"] }>(
  event: E,
  caller: Caller,
  here: string,
): E & { source: NonNullable<StreamEventInput["source"]> } {
  const source: NonNullable<StreamEventInput["source"]> = { origin: caller.path || here };
  if (caller.cause) source.cause = storedCause(caller.cause);
  if (event.source?.processor) source.processor = event.source.processor;
  // a member alone: `caller.mind` is no principal, and stamps nothing
  if (caller.principal) source.principal = caller.principal;
  if (caller.principal && caller.grant) source.grant = caller.grant;
  if (caller.principal && caller.via) source.via = caller.via;
  if (caller.onBehalfOf) source.onBehalfOf = caller.onBehalfOf;
  // A signed statement the platform carries in is its signer's word, never the platform's.
  if (caller.platform && caller.signer) source.signer = caller.signer;
  else if (caller.platform) source.platform = true;
  if (caller.copiedFrom) source.copiedFrom = caller.copiedFrom;
  const stamped = { ...event, source };
  // `signed` stays only beside the signer the auth Worker verified: a writer's own copy, which
  // nobody checked, would look like a signature on an event its key never signed
  if (!source.signer) delete (stamped as { signed?: unknown }).signed;
  return stamped;
}

/** THE PLATFORM'S OWN IDEMPOTENCY KEYS: a key that starts with one of the platform's namespaces.
 *  The platform appends its facts under such keys (`mind/identity-record:<hash>`,
 *  `mind/stack-deployed:<version>`), and a key that somebody took first would answer the
 *  platform's append with the other event, or refuse it for good.
 *
 *  THE KEYS OF THE MIND'S IDENTITY (`mind/identity-record:` and `mind/identity-record-refused:`)
 *  are the platform's alone: every caller without the explicit platform flag is refused them.
 *  That includes a call that runs a stored row's target, which has no principal and is no
 *  loaded code, and whose row a member or loaded code may have written: an ordinary event under
 *  a record's key would keep that record out of the mind's log for good.
 *
 *  THE OTHER KEYS are refused to every caller from outside the platform's code: loaded code, a
 *  person or a key (`principal`), and a signed statement that the platform carries in. The
 *  kernel's first-party code keeps them: it calls with no principal and is no loaded code, and
 *  a facet of the mind's own Worker appends `mind/created` and its like so.
 *
 *  An event that a schedule will append is held to the same rules when the schedule is set: it
 *  fires under its maker's stamp. */
export function refusePlatformIdempotencyKeys(
  events: readonly StreamEventInput[],
  caller: Caller,
): void {
  if (caller.platform && !caller.signer) return;
  // another mind's request is from outside, as a member's is, though it names no member
  const fromOutside = caller.app || caller.principal || caller.mind || caller.signer;
  for (const event of events) {
    if (event.type === "events.iterate.com/itx/schedule-set")
      // the cast: a schedule's payload holds the events that it will append
      refusePlatformIdempotencyKeys(
        (event.payload as { events?: StreamEventInput[] }).events || [],
        caller,
      );
    const key = event.idempotencyKey;
    if (!key) continue;
    if (
      /^mind\/identity-record(?:-refused)?:/.test(key) ||
      (fromOutside && /^(?:itx|mind|repo|workspace|sandbox|secret)[/@]/.test(key))
    )
      throw codedError("FORBIDDEN", `idempotency key ${JSON.stringify(key)} is the platform's`);
  }
}

// Readers trust these by type alone, so the append boundary refuses anyone else's.
const PLATFORM_FACT_TYPES: ReadonlySet<string> = new Set([
  "events.iterate.com/mind/worker-updated",
  "events.iterate.com/mind/worker-update-failed",
  // the record of a deploy: the mind's processor keeps the latest as the stack's config
  "events.iterate.com/mind/stack-deployed",
  // the mind's identity: a signed record that the auth Worker checked, accepted or refused
  "events.iterate.com/mind/identity-record-accepted",
  "events.iterate.com/mind/identity-record-refused",
  "events.iterate.com/email/received",
  "events.iterate.com/email/sent",
  "events.iterate.com/email/forward-failed",
  // what became of a request to forward a received mail
  "events.iterate.com/email/forwarded",
  // the place on the log after which no request to forward a mail is served
  "events.iterate.com/email/forward-requests-closed",
  "events.iterate.com/email/send-failed",
  "events.iterate.com/email/delivery-failed",
  "events.iterate.com/webhook/received",
  "events.iterate.com/mcp/webhook-received",
  // what Cloudflare said of a repo; a push to the config repo's main publishes the mind
  "events.iterate.com/repo/pushed",
  "events.iterate.com/repo/cloned",
  "events.iterate.com/repo/fetched",
  "events.iterate.com/repo/token-created",
  "events.iterate.com/repo/token-revoked",
  // the vault's gate for acts (iterate/acts): its rules and its lock decide what waits
  "events.iterate.com/approval/act-held",
  "events.iterate.com/approval/act-approved",
  "events.iterate.com/approval/act-rejected",
  "events.iterate.com/approval/hold-expired",
  "events.iterate.com/approval/act-done",
  "events.iterate.com/approval/rule-set",
  "events.iterate.com/approval/rule-proposed",
  // the two ends of a proposal that a reader counts by: anyone else's would hide one that is open
  "events.iterate.com/approval/rule-proposal-signed",
  "events.iterate.com/approval/rule-proposal-rejected",
  "events.iterate.com/approval/locked",
  "events.iterate.com/approval/unlocked",
  // the record of a request sent as the mind (./context/built-ins.ts `recordSignedRequest`)
  "events.iterate.com/itx/signed-request-sent",
]);

export const isConfigPointerMatch = (match: ItxExpressionPrefix) =>
  itxExpressionStepName(match[1]) === "config";

// An occurrence fires under its schedule's stamp, so what one may not append it may not schedule.
// A signed statement the platform carries in is held to this like anyone's.
export function refuseNonPlatformWrites(events: readonly StreamEventInput[], caller: Caller): void {
  if (!caller.platform || caller.signer) refuseThePlatformsOwn(events);
  refusePlatformIdempotencyKeys(events, caller);
}

function refuseThePlatformsOwn(events: readonly StreamEventInput[]): void {
  for (const event of events) {
    if (event.type === "events.iterate.com/itx/schedule-set")
      refuseThePlatformsOwn((event.payload as { events: StreamEventInput[] }).events);
    if (PLATFORM_FACT_TYPES.has(event.type))
      throw codedError(
        "FORBIDDEN",
        `${event.type} is the platform's own fact: no one else appends or schedules it`,
      );
    if (
      event.type === "events.iterate.com/itx/rewrite-rule-configured" &&
      isConfigPointerMatch((event.payload as { match: ItxExpressionPrefix }).match)
    )
      throw codedError(
        "FORBIDDEN",
        "`itx.config` is the mind's published config: only the platform's publication writes it (commit to /repos/config)",
      );
  }
}

const encoder = new TextEncoder();
const decoder = new TextDecoder();
const base64url = (bytes: Uint8Array): string =>
  btoa(String.fromCharCode(...bytes))
    .replaceAll("+", "-")
    .replaceAll("/", "_")
    .replace(/=+$/, "");
const bytesFromBase64url = (text: string): Uint8Array<ArrayBuffer> =>
  Uint8Array.from(
    atob(
      text
        .replaceAll("-", "+")
        .replaceAll("_", "/")
        .padEnd(Math.ceil(text.length / 4) * 4, "="),
    ),
    (c) => c.charCodeAt(0),
  );

async function hmacKey(secret: string, usage: "sign" | "verify") {
  return crypto.subtle.importKey(
    "raw",
    encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    [usage],
  );
}

export async function signClaims(claims: unknown, secret: string): Promise<string> {
  const payload = base64url(encoder.encode(JSON.stringify(claims)));
  const signature = await crypto.subtle.sign(
    "HMAC",
    await hmacKey(secret, "sign"),
    encoder.encode(payload),
  );
  return `${payload}.${base64url(new Uint8Array(signature))}`;
}

// Null for every bad token alike. The caller checks the claims' shape and expiry.
export async function verifyClaims(token: string, secret: string): Promise<unknown> {
  if (!secret) return null;
  const dot = token.indexOf(".");
  if (dot <= 0) return null;
  const payload = token.slice(0, dot);
  let signature: Uint8Array<ArrayBuffer>;
  let claims: unknown;
  try {
    signature = bytesFromBase64url(token.slice(dot + 1));
    claims = JSON.parse(decoder.decode(bytesFromBase64url(payload)));
  } catch {
    return null;
  }
  const valid = await crypto.subtle.verify(
    "HMAC",
    await hmacKey(secret, "verify"),
    signature,
    encoder.encode(payload),
  );
  return valid ? claims : null;
}

export const sha256Hex = async (text: string): Promise<string> =>
  Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(text))), (byte) =>
    byte.toString(16).padStart(2, "0"),
  ).join("");