Skip to content

g1t/services/runner/src/guard.ts

161 lines5,915 bytesCodeBlame
1/**
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
17import {
18 ABUSE_HOST,
19 type ModelHosts,
20 type RunGuard,
21 type WorkflowJob,
22 allows,
23 buildHosts,
24 jobHosts,
25 refusal,
26 sandboxHosts,
27 sandboxNamespace,
28} from "./egress";
29
30export {
31 ABUSE_EXIT_CODE,
32 ABUSE_HOST,
33 ABUSE_MESSAGE,
34 SANDBOX_BINDINGS,
35 harnessEnv,
36 jobHosts,
37 newlyBlocked,
38 sandboxNamespace,
39 timeCapMessage,
40 withPlanLimits,
41} from "./egress";
42export type { PlanLimits, RunGuard, WorkflowJob } from "./egress";
43
44/** What the outbound handler is given: the hosts this sandbox may reach. */
45export type EgressParams = { hosts: string[] };
46
47
48/** The stop by the sandbox's alarm comes this long after the harness's own. */
49export const ALARM_GRACE_SECONDS = 3 * 60;
50
51/**
52 * The guardrails of a run in `repo`. Throws when they cannot be read: a
53 * sandbox is not started without them.
54 */
55export async function guardFor(work: ServiceBinding, repo: RepoPath, kind: RunKind): Promise<RunGuard> {
56 const found = await guardrailsClient(work).runGuardrails(repo);
57 if (!found.ok) throw new Error(`g1t could not read this project's guardrails: ${found.error.message}`);
58 const policy = found.value;
59 return { policy, minutes: policy.minutes[kind] ?? 60 };
60}
61
62/**
63 * The guardrails of a workflow job, deploy build or security update in
64 * `repo`: its project's network list, plus what builds need (`buildHosts`), and the
65 * time cap it was given. `repo` is the project, not a pull request's
66 * working copy; `repoId`, when known, finds it however it has moved.
67 * A workflow job of a trusted run also gets the workflow-only domains
68 * that name its workflow and environment (`jobHosts`); nothing else
69 * ever does. Throws when they cannot be read: no build starts without them.
70 */
71export async function buildGuardFor(
72 work: ServiceBinding,
73 repo: RepoPath,
74 kind: "actions" | "deploy" | "bump",
75 minutes: number,
76 repoId?: string | null,
77 job?: WorkflowJob | null,
78 extra: readonly string[] = [],
79): Promise<RunGuard> {
80 const found = await guardrailsClient(work).runGuardrails(repo, repoId);
81 if (!found.ok) throw new Error(`g1t could not read this project's guardrails: ${found.error.message}`);
82 const policy = found.value;
83 const hosts = [...policy.hosts, ...buildHosts(kind), ...jobHosts(policy, kind, job), ...extra];
84 return { policy: { ...policy, hosts: [...new Set(hosts)] }, minutes };
85}
86
87
88/** Every host the sandbox may reach, for the outbound handler. */
89export function egressHosts(guard: RunGuard, env: ModelHosts, sandboxEnv: Record<string, string>): string[] {
90 return sandboxHosts(guard.policy.hosts, env, sandboxEnv);
91}
92
93/**
94 * The outbound handler of a guarded sandbox: every HTTP and HTTPS request
95 * it makes. An allowed host is fetched as asked; any other is refused, and
96 * the sandbox told so it can say so on the run.
97 */
98export async function egress(
99 request: Request,
100 env: { SANDBOX: DurableObjectNamespace },
101 ctx: OutboundHandlerContext<EgressParams>,
102): Promise<Response> {
103 const host = new URL(request.url).host;
104 // A sandbox reporting that it stopped itself for mining.
105 if (host === ABUSE_HOST) return abuse(request, env, ctx);
106 if (allows(ctx.params?.hosts ?? [], host)) return fetch(request);
107 try {
108 const namespace = sandboxNamespace(env, ctx.className);
109 const sandbox = namespace.get(namespace.idFromString(ctx.containerId)) as unknown as {
110 noteBlocked(host: string): Promise<void>;
111 };
112 await sandbox.noteBlocked(host);
113 } catch (error) {
114 console.log("blocked host not reported", host, String(error));
115 }
116 return refusal(host);
117}
118
119/**
120 * A sandbox's report that it stopped itself for mining (crates/runner
121 * abuse.rs), handed to its Durable Object. Reached through `egress` for a
122 * guarded sandbox and as the handler for `ABUSE_HOST` for any other.
123 */
124export async function abuse(
125 request: Request,
126 env: { SANDBOX: DurableObjectNamespace },
127 ctx: OutboundHandlerContext<unknown>,
128): Promise<Response> {
129 let verdict: unknown = null;
130 try {
131 verdict = ((await request.json()) as { verdict?: unknown }).verdict ?? null;
132 } catch {
133 // A report without its metrics still stops the run.
134 }
135 try {
136 const namespace = sandboxNamespace(env, ctx.className);
137 const sandbox = namespace.get(namespace.idFromString(ctx.containerId)) as unknown as {
138 flagAbuse(verdict: unknown): Promise<void>;
139 };
140 await sandbox.flagAbuse(verdict);
141 } catch (error) {
142 console.log("abuse report not handled", String(error));
143 }
144 return new Response("noted\n");
145}
146
147/** Adds a step to a run, with its token. Never fails the caller. */
148export async function reportRun(
149 work: ServiceBinding,
150 tracked: { runId: string; token: string },
151 report: { steps?: string[]; halt?: "budget" | "time" | "abuse"; error?: string },
152): Promise<void> {
153 await work
154 .fetch("https://service/rpc/report_run", {
155 method: "POST",
156 headers: { "content-type": "application/json" },
157 body: JSON.stringify({ runId: tracked.runId, token: tracked.token, ...report }),
158 })
159 .catch((error: unknown) => console.log("run report failed", tracked.runId, String(error)));
160}
161