g1t/services/runner/src/guard.ts

130 lines5,351 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1/**
2 * Guardrails, as the runner applies them to a sandbox: what it may reach,
3 * what its harness refuses, and how long and how much a run may take.
4 *
5 * - The network list is enforced here, outside the sandbox: a guarded
6 * sandbox starts with no internet, and every HTTP(S) request it makes
7 * comes to `egress` below, which forwards it or refuses it.
8 * - Command rules and the cost cap are handed to the harness inside the
9 * sandbox as `GUARDRAILS`, which applies them to the agent.
10 * - The time cap is enforced twice: by the harness, and by the sandbox's
11 * own alarm here, which stops the whole sandbox a little after.
12 */
13import type { OutboundHandlerContext } from "@cloudflare/containers";
14
15import { type RepoPath, type RunKind, type ServiceBinding, guardrailsClient } from "@g1t/contracts";
16
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look17import { ABUSE_HOST, type ModelHosts, type RunGuard, allows, buildHosts, refusal, sandboxHosts } from "./egress";
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API18
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look19export { ABUSE_EXIT_CODE, ABUSE_HOST, ABUSE_MESSAGE, harnessEnv, newlyBlocked, timeCapMessage, withPlanLimits } from "./egress";
20export type { PlanLimits, RunGuard } from "./egress";
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API21
22/** What the outbound handler is given: the hosts this sandbox may reach. */
23export type EgressParams = { hosts: string[] };
24
25/** The stop by the sandbox's alarm comes this long after the harness's own. */
26export const ALARM_GRACE_SECONDS = 3 * 60;
27
28/**
29 * The guardrails of a run in `repo`. Throws when they cannot be read: a
30 * sandbox is not started without them.
31 */
32export async function guardFor(work: ServiceBinding, repo: RepoPath, kind: RunKind): Promise<RunGuard> {
33 const found = await guardrailsClient(work).runGuardrails(repo);
34 if (!found.ok) throw new Error(`g1t could not read this project's guardrails: ${found.error.message}`);
35 const policy = found.value;
36 return { policy, minutes: policy.minutes[kind] ?? 60 };
37}
38
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look39/**
40 * The guardrails of a workflow job or deploy build in `repo`: its
41 * project's network list, plus what builds need (`buildHosts`), and the
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas42 * time cap it was given. `repo` is the project, not a pull request's
43 * working copy; `repoId`, when known, finds it however it has moved.
44 * Throws when they cannot be read: no build starts without them.
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look45 */
46export async function buildGuardFor(
47 work: ServiceBinding,
48 repo: RepoPath,
49 kind: "actions" | "deploy",
50 minutes: number,
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas51 repoId?: string | null,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look52): Promise<RunGuard> {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas53 const found = await guardrailsClient(work).runGuardrails(repo, repoId);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look54 if (!found.ok) throw new Error(`g1t could not read this project's guardrails: ${found.error.message}`);
55 const policy = found.value;
56 return { policy: { ...policy, hosts: [...new Set([...policy.hosts, ...buildHosts(kind)])] }, minutes };
57}
58
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API59/** Every host the sandbox may reach, for the outbound handler. */
60export function egressHosts(guard: RunGuard, env: ModelHosts, sandboxEnv: Record<string, string>): string[] {
61 return sandboxHosts(guard.policy.hosts, env, sandboxEnv);
62}
63
64/**
65 * The outbound handler of a guarded sandbox: every HTTP and HTTPS request
66 * it makes. An allowed host is fetched as asked; any other is refused, and
67 * the sandbox told so it can say so on the run.
68 */
69export async function egress(
70 request: Request,
71 env: { SANDBOX: DurableObjectNamespace },
72 ctx: OutboundHandlerContext<EgressParams>,
73): Promise<Response> {
74 const host = new URL(request.url).host;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look75 // A sandbox reporting that it stopped itself for mining.
76 if (host === ABUSE_HOST) return abuse(request, env, ctx);
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API77 if (allows(ctx.params?.hosts ?? [], host)) return fetch(request);
78 try {
79 const sandbox = env.SANDBOX.get(env.SANDBOX.idFromString(ctx.containerId)) as unknown as {
80 noteBlocked(host: string): Promise<void>;
81 };
82 await sandbox.noteBlocked(host);
83 } catch (error) {
84 console.log("blocked host not reported", host, String(error));
85 }
86 return refusal(host);
87}
88
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look89/**
90 * A sandbox's report that it stopped itself for mining (crates/runner
91 * abuse.rs), handed to its Durable Object. Reached through `egress` for a
92 * guarded sandbox and as the handler for `ABUSE_HOST` for any other.
93 */
94export async function abuse(
95 request: Request,
96 env: { SANDBOX: DurableObjectNamespace },
97 ctx: OutboundHandlerContext<unknown>,
98): Promise<Response> {
99 let verdict: unknown = null;
100 try {
101 verdict = ((await request.json()) as { verdict?: unknown }).verdict ?? null;
102 } catch {
103 // A report without its metrics still stops the run.
104 }
105 try {
106 const sandbox = env.SANDBOX.get(env.SANDBOX.idFromString(ctx.containerId)) as unknown as {
107 flagAbuse(verdict: unknown): Promise<void>;
108 };
109 await sandbox.flagAbuse(verdict);
110 } catch (error) {
111 console.log("abuse report not handled", String(error));
112 }
113 return new Response("noted\n");
114}
115
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API116/** Adds a step to a run, with its token. Never fails the caller. */
117export async function reportRun(
118 work: ServiceBinding,
119 tracked: { runId: string; token: string },
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look120 report: { steps?: string[]; halt?: "budget" | "time" | "abuse"; error?: string },
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API121): Promise<void> {
122 await work
123 .fetch("https://service/rpc/report_run", {
124 method: "POST",
125 headers: { "content-type": "application/json" },
126 body: JSON.stringify({ runId: tracked.runId, token: tracked.token, ...report }),
127 })
128 .catch((error: unknown) => console.log("run report failed", tracked.runId, String(error)));
129}
130