41 lines
2.4 KiB
TypeScript
41 lines
2.4 KiB
TypeScript
// PEP-187: where an agent's container may go on the network. Packages registries, the platform's
|
|
// Gitea and relay, and addresses the project owner allowed. Everything else is closed and the
|
|
// refusal is written to the journal.
|
|
import type { Db } from "@peppa/db";
|
|
import { logEvent } from "./audit.ts";
|
|
import { getSetting, setSetting } from "./settings.ts";
|
|
|
|
/** Built-in allowance: package registries (a host also covers its subdomains). */
|
|
export const EGRESS_REGISTRIES = ["registry.npmjs.org", "registry.yarnpkg.com", "pypi.org", "files.pythonhosted.org", "proxy.golang.org", "sum.golang.org", "crates.io", "static.crates.io", "index.crates.io", "rubygems.org"];
|
|
|
|
/** Hosts of the platform itself: Gitea, the relay (web), the local docker gateway. */
|
|
export function platformHosts(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
const hosts = ["host.docker.internal", "localhost", "127.0.0.1"];
|
|
for (const v of [env.GITEA_URL, env.PEPPA_WEB_URL, env.PEPPA_AGENT_URL]) {
|
|
try {
|
|
if (v) hosts.push(new URL(v).hostname);
|
|
} catch {}
|
|
}
|
|
return hosts;
|
|
}
|
|
|
|
const norm = (h: string) => h.trim().toLowerCase().replace(/\.$/, "");
|
|
const matches = (host: string, allowed: string) => host === allowed || host.endsWith(`.${allowed}`);
|
|
|
|
export const projectEgressKey = (projectId: number) => `project.egress:${projectId}`;
|
|
export const getProjectEgress = async (db: Db, projectId: number): Promise<string[]> => (await getSetting<string[]>(db, projectEgressKey(projectId))) ?? [];
|
|
/** Only the owner allows a new address (the caller checks ownership). */
|
|
export const setProjectEgress = (db: Db, projectId: number, hosts: string[]) => setSetting(db, projectEgressKey(projectId), [...new Set(hosts.map(norm).filter(Boolean))]);
|
|
|
|
export function egressAllowed(host: string, projectHosts: string[] = [], env: NodeJS.ProcessEnv = process.env): boolean {
|
|
const h = norm(host);
|
|
return [...EGRESS_REGISTRIES, ...platformHosts(env), ...projectHosts].some((a) => matches(h, norm(a)));
|
|
}
|
|
|
|
/** The decision for one request of an agent's container; a refusal goes to the journal. */
|
|
export async function checkAgentEgress(db: Db, o: { projectId: number; taskId?: number | null; sessionId?: number | null; host: string }): Promise<boolean> {
|
|
if (egressAllowed(o.host, await getProjectEgress(db, o.projectId))) return true;
|
|
await logEvent(db, { projectId: o.projectId, taskId: o.taskId, sessionId: o.sessionId, type: "egress_blocked", payload: { host: norm(o.host) } });
|
|
return false;
|
|
}
|