Files
PaperClipAI/packages/plugins/sandbox-providers/kubernetes/test/unit/network-policy.test.ts
DottaandPaperclip 7f766526a6 feat(sandbox): add task-scoped egress grants (#10155)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Confinement providers protect agent runs with default-deny network
policies
> - Kubernetes environments currently apply only provider-level,
namespace-wide egress allowances
> - Tasks that legitimately need GitHub or package registries therefore
cannot request narrow access, while network failures do not explain the
governing policy or how to request a grant
> - This pull request adds issue-scoped egress grants that become
workload-owned, run-label-selected policies and carries the effective
grant through lease audit metadata
> - The benefit is that internet-dependent work can run without enabling
broad egress for every concurrent task, and denied requests point
operators to the exact grant path

## Linked Issues or Issue Description

No public issue exists. Related but distinct: Refs #9944, which adds a
provider-wide open-internet posture; this PR keeps provider defaults
narrow and adds per-task grants.

**Problem / motivation**
Kubernetes sandbox egress is configured at the provider/tenant level. A
task that needs to clone from GitHub or install from PyPI cannot request
those destinations without changing the policy for every run in the
tenant namespace. DNS/connectivity failures also surface as generic tool
errors with no policy name or remediation path.

**Proposed solution**
Accept `executionWorkspaceSettings.networkEgress.allowFqdns` and
`allowCidrs`, forward the setting through heartbeat environment
acquisition, and create a workload-owned NetworkPolicy or
CiliumNetworkPolicy selected by `paperclip.io/run-id`. Record the
effective grant in lease activity/metadata, expose policy context
through `PAPERCLIP_NETWORK_EGRESS_*`, and append the grant path to
likely policy-related stderr failures.

**Alternatives considered**
A provider-wide open-internet switch is broader than required and is
already covered by #9944. Mutating the existing namespace policy would
leak each task's destinations to other concurrent runs. Standard
Kubernetes NetworkPolicy cannot enforce FQDNs exactly, so standard mode
uses the existing hardened public-IPv4 TCP 80/443 fallback only for the
selected run; Cilium mode remains exact.

**Roadmap alignment**
This extends the existing cloud/sandbox agent roadmap capability with
task-level control-plane policy and does not duplicate a planned roadmap
item.

## What Changed

- Added validated `networkEgress` grants to issue execution workspace
settings and forwarded them through environment lease acquisition.
- Added workload-owned, run-label-scoped
NetworkPolicy/CiliumNetworkPolicy resources for task FQDN/CIDR grants.
- Added lease audit metadata, sandbox policy environment variables, and
actionable network-denial stderr guidance.
- Added focused parser, manifest, policy creation, and denial-message
tests plus Kubernetes provider documentation.

## Verification

- `pnpm -C packages/shared exec vitest run src/validators/issue.test.ts`
— 27 passed.
- `pnpm -C packages/plugins/sandbox-providers/kubernetes test -- --run
test/unit/network-policy.test.ts test/unit/cilium-network-policy.test.ts
test/unit/scoped-network-egress.test.ts` — 21 passed.
- `pnpm -C server exec vitest run
src/__tests__/execution-workspace-policy.test.ts` — 15 passed.
- `pnpm exec vitest run
server/src/__tests__/heartbeat-plugin-environment.test.ts
server/src/__tests__/environment-runtime.test.ts` — 26 passed.
- `pnpm --dir packages/db build && pnpm --dir packages/shared build &&
pnpm --dir packages/plugins/sdk build` — passed, including migration
safety checks.
- `pnpm --dir packages/plugins/sandbox-providers/kubernetes typecheck &&
pnpm --dir server typecheck` — passed after refreshing the worktree's
frozen offline dependencies.
- End-to-end cluster validation of the `build-cython-ext` benchmark
remains for CI/maintainer Kubernetes infrastructure; the focused tests
assert `github.com` and `pypi.org` produce a policy selected only by the
granted run.

## Risks

- Standard NetworkPolicy cannot express FQDNs, so an FQDN grant allows
hardened public IPv4 TCP 80/443 for that run; use Cilium mode for exact
hostname enforcement.
- The new field is additive and absent by default, so existing runs keep
the current provider-level policy.
- Workload owner references garbage-collect scoped policies with the
Job/Sandbox; a cluster/controller that ignores owner references could
temporarily strand a policy that still selects no future run ID.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, exact model ID `gpt-5.6-sol`, high reasoning mode, tool
use and code execution. The runtime did not expose a context-window
size.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-07-24 09:58:58 -05:00

113 lines
4.7 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { buildNetworkPolicyManifests } from "../../src/network-policy.js";
describe("buildNetworkPolicyManifests", () => {
const baseInput = {
namespace: "paperclip-acme",
paperclipServerNamespace: "paperclip",
egressAllowCidrs: [] as string[],
};
it("produces a deny-all + egress allow pair", () => {
const manifests = buildNetworkPolicyManifests(baseInput);
expect(manifests).toHaveLength(2);
expect(manifests[0].metadata.name).toBe("paperclip-deny-all");
expect(manifests[1].metadata.name).toBe("paperclip-egress-allow");
});
it("deny-all has no ingress/egress rules and applies to all pods", () => {
const [denyAll] = buildNetworkPolicyManifests(baseInput);
expect(denyAll.spec.podSelector).toEqual({});
expect(denyAll.spec.policyTypes).toEqual(["Ingress", "Egress"]);
expect(denyAll.spec.ingress).toBeUndefined();
expect(denyAll.spec.egress).toBeUndefined();
});
it("egress allow includes kube-dns and paperclip-server callback", () => {
const [, egress] = buildNetworkPolicyManifests(baseInput);
const rules = egress.spec.egress;
const dnsRule = rules.find((r: { ports?: { protocol: string; port: number }[] }) =>
r.ports?.some((p) => p.port === 53),
);
expect(dnsRule).toBeDefined();
const paperclipRule = rules.find((r: { to: { namespaceSelector?: { matchLabels?: Record<string, string> } }[] }) =>
r.to.some((t) => t.namespaceSelector?.matchLabels?.["kubernetes.io/metadata.name"] === "paperclip"),
);
expect(paperclipRule).toBeDefined();
});
it("includes user-supplied CIDRs in egress allow", () => {
const [, egress] = buildNetworkPolicyManifests({ ...baseInput, egressAllowCidrs: ["10.0.0.0/8"] });
const cidrRule = egress.spec.egress.find((r: { to: { ipBlock?: { cidr: string } }[] }) =>
r.to.some((t) => t.ipBlock?.cidr === "10.0.0.0/8"),
);
expect(cidrRule).toBeDefined();
});
it("uses paperclip-server pod label selector for callback ingress to paperclip ns", () => {
const [, egress] = buildNetworkPolicyManifests(baseInput);
const callbackRule = egress.spec.egress.find((r: { to: { podSelector?: { matchLabels?: Record<string, string> } }[] }) =>
r.to.some((t) => t.podSelector?.matchLabels?.app === "paperclip-server"),
);
expect(callbackRule).toBeDefined();
expect(callbackRule.ports[0].port).toBe(3100);
});
it("adds public-IPv4 fallback (with private/link-local excluded) when FQDNs are configured and no CIDRs are supplied", () => {
const [, egress] = buildNetworkPolicyManifests({
...baseInput,
egressAllowFqdns: ["api.anthropic.com"],
});
const fallback = egress.spec.egress.find((r: { to: { ipBlock?: { cidr: string } }[] }) =>
r.to.some((t) => t.ipBlock?.cidr === "0.0.0.0/0"),
);
expect(fallback).toBeDefined();
expect(fallback.to[0].ipBlock.except).toEqual(
expect.arrayContaining(["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "127.0.0.0/8"]),
);
expect(fallback.ports).toEqual(
expect.arrayContaining([
{ protocol: "TCP", port: 443 },
{ protocol: "TCP", port: 80 },
]),
);
});
it("does NOT add the public-IPv4 fallback when operator supplied egressAllowCidrs", () => {
const [, egress] = buildNetworkPolicyManifests({
...baseInput,
egressAllowFqdns: ["api.anthropic.com"],
egressAllowCidrs: ["203.0.113.0/24"],
});
const fallback = egress.spec.egress.find((r: { to: { ipBlock?: { cidr: string } }[] }) =>
r.to.some((t) => t.ipBlock?.cidr === "0.0.0.0/0"),
);
expect(fallback).toBeUndefined();
});
it("does NOT add the public-IPv4 fallback when no FQDNs are configured", () => {
const [, egress] = buildNetworkPolicyManifests(baseInput);
const fallback = egress.spec.egress.find((r: { to: { ipBlock?: { cidr: string } }[] }) =>
r.to.some((t) => t.ipBlock?.cidr === "0.0.0.0/0"),
);
expect(fallback).toBeUndefined();
});
it("builds a task-scoped allow policy without namespace-wide base rules", () => {
const [, egress] = buildNetworkPolicyManifests({
...baseInput,
name: "pc-run-egress",
podSelector: { "paperclip.io/run-id": "run-123" },
includeBaseRules: false,
egressAllowFqdns: ["github.com", "pypi.org"],
ownerReferences: [{ apiVersion: "batch/v1", kind: "Job", name: "pc-run", uid: "uid-1" }],
});
expect(egress.metadata.name).toBe("pc-run-egress");
expect(egress.metadata.ownerReferences).toHaveLength(1);
expect(egress.spec.podSelector.matchLabels).toEqual({ "paperclip.io/run-id": "run-123" });
expect(egress.spec.egress).toHaveLength(1);
expect(egress.spec.egress[0].to[0].ipBlock.cidr).toBe("0.0.0.0/0");
});
});