mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
feat(egress-guard): derive the scope lists from the operator-approved task scope
egress-guard reads hand-edited lists/scope-domains.txt and scope-cidrs.txt, while the sandbox egress proxy builds its policy from PostgreSQL. Nothing connected the two, so the overlay could drift from the approved scope (#421). egress-guard/export-scope.sh regenerates both lists through the new artex -export-egress-guard-scope. The export calls taskSandboxRunInfoChecked (the error-returning form of taskSandboxRunInfo) and sandbox.NewEgressPolicy, the derivation and parser of the per-task proxy, so only operator-approved task scope, frozen company grants and operator task allow rules are exported. Agent-added, auto-added and expanded rows are not. Fail closed: taskSandboxRunInfoChecked reports the read errors the proxy path ignores, any error fails the whole export, and the script touches neither list until a complete, well-formed export was read; each list is then replaced by rename. An empty export is refused unless --allow-empty, because empty lists with EGRESS_MODE unset make the guard fall back to monitor. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
048e8a84d3
commit
ebb37c20bb
8 changed files with 999 additions and 6 deletions
|
|
@ -19,6 +19,8 @@ All notable changes to this project are documented in this file. The format is b
|
|||
|
||||
- **`domain_suffix` asset interception rule kind**: a domain and its subdomains, matched on a label boundary. `example.com` matches `example.com` and `a.example.com`, but not `a.example.com.other.net` or `badexample.com`, which `fuzzy_domain`'s substring match also lets through; that makes it the kind to use for a task allow-list that covers a site. `*.example.com` and `.example.com` are stored as `example.com`. It is the label-boundary semantics the sandbox egress policy already applies, and a `domain_suffix` allow rule is now a scope domain for that policy too (`taskSandboxRunInfo` already read the kind). `fuzzy_domain` is unchanged. Migration `0026_asset_intercept_domain_suffix.sql` widens the `kind` CHECK constraint of both rule tables.
|
||||
|
||||
- **egress-guard scope lists can be derived from the approved task scope** (#421): `egress-guard/export-scope.sh` regenerates `lists/scope-domains.txt` and `lists/scope-cidrs.txt` from PostgreSQL through the new `artex -export-egress-guard-scope`. It reuses the derivation of the per-task sandbox egress proxy, so only operator-approved task scope, frozen company grants and operator task allow rules are exported, never agent-added, auto-added or expanded rows. Each list is replaced by rename, and only after the complete export was read and checked; an export that fails or is malformed changes neither list, and an empty export is refused unless `--allow-empty` is given. The overlay stays opt-in and still reads the lists at startup, so the guard is restarted to apply them.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A command that exits 124 no longer removes the Docker worker.** The runner treated every exit code 124 as its own timeout and removed the task's worker container, which also stopped the task's background jobs. Commands such as `timeout 5 curl ...` exit 124 by themselves. An exit 124 now counts as a runner timeout only when the command ran for at least `timeout_ms`.
|
||||
|
|
|
|||
285
cmd/artex/egress_guard_export_test.go
Normal file
285
cmd/artex/egress_guard_export_test.go
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
//go:build unix
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
const (
|
||||
egressListDomainsOld = "# hand-written\nold.example.com\n"
|
||||
egressListCIDRsOld = "# hand-written\n192.0.2.0/24\n"
|
||||
)
|
||||
|
||||
// runExportScopeScript runs egress-guard/export-scope.sh against a lists
|
||||
// directory seeded with the "old" lists. The artex binary is replaced by a
|
||||
// stub that prints exportOutput and exits with exportExit.
|
||||
func runExportScopeScript(t *testing.T, exportOutput string, exportExit int, extraArgs ...string) (listsDir, output string, err error) {
|
||||
t.Helper()
|
||||
if _, lookErr := exec.LookPath("bash"); lookErr != nil {
|
||||
t.Skip("bash not available")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
listsDir = filepath.Join(tmp, "lists")
|
||||
if mkErr := os.MkdirAll(listsDir, 0o755); mkErr != nil {
|
||||
t.Fatal(mkErr)
|
||||
}
|
||||
for name, body := range map[string]string{"scope-domains.txt": egressListDomainsOld, "scope-cidrs.txt": egressListCIDRsOld} {
|
||||
if wErr := os.WriteFile(filepath.Join(listsDir, name), []byte(body), 0o644); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
}
|
||||
payload := filepath.Join(tmp, "export.out")
|
||||
if wErr := os.WriteFile(payload, []byte(exportOutput), 0o644); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
argsLog := filepath.Join(tmp, "args.log")
|
||||
stub := filepath.Join(tmp, "artex-stub")
|
||||
stubBody := "#!/usr/bin/env bash\nprintf '%s\\n' \"$*\" > '" + argsLog + "'\ncat '" + payload + "'\nexit " + strconv.Itoa(exportExit) + "\n"
|
||||
if wErr := os.WriteFile(stub, []byte(stubBody), 0o755); wErr != nil {
|
||||
t.Fatal(wErr)
|
||||
}
|
||||
script := filepath.Join("..", "..", "egress-guard", "export-scope.sh")
|
||||
args := append([]string{script, "--lists", listsDir}, extraArgs...)
|
||||
args = append(args, "--", stub)
|
||||
out, err := exec.Command("bash", args...).CombinedOutput()
|
||||
if raw, rErr := os.ReadFile(argsLog); rErr == nil {
|
||||
output = "stub args: " + string(raw)
|
||||
}
|
||||
return listsDir, output + string(out), err
|
||||
}
|
||||
|
||||
func readEgressList(t *testing.T, listsDir, name string) string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(listsDir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
// egressListEntries reads a list the way egress-guard/entrypoint.sh read_list
|
||||
// does: comments and blank lines dropped.
|
||||
func egressListEntries(t *testing.T, listsDir, name string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
for _, line := range strings.Split(readEgressList(t, listsDir, name), "\n") {
|
||||
if i := strings.Index(line, "#"); i >= 0 {
|
||||
line = line[:i]
|
||||
}
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func assertEgressListsUnchanged(t *testing.T, listsDir string) {
|
||||
t.Helper()
|
||||
if got := readEgressList(t, listsDir, "scope-domains.txt"); got != egressListDomainsOld {
|
||||
t.Fatalf("scope-domains.txt changed on a failed export:\n%s", got)
|
||||
}
|
||||
if got := readEgressList(t, listsDir, "scope-cidrs.txt"); got != egressListCIDRsOld {
|
||||
t.Fatalf("scope-cidrs.txt changed on a failed export:\n%s", got)
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
func assertNoStagedEgressFiles(t *testing.T, listsDir string) {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(listsDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("staged files left in the lists directory: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportScopeScriptReplacesLists(t *testing.T) {
|
||||
export := "# artex egress-guard scope export v1\n# tasks: 3,7\n" +
|
||||
"domain app.example.org\ndomain example.net\ncidr 198.51.100.0/24\n" +
|
||||
"# skipped \"2001:db8::/32\": IPv6, egress-guard is IPv4-only\n" +
|
||||
"# end domains=2 cidrs=1\n"
|
||||
listsDir, out, err := runExportScopeScript(t, export, 0, "--tasks", "3,7")
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh failed: %v\n%s", err, out)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-domains.txt"); strings.Join(got, ",") != "app.example.org,example.net" {
|
||||
t.Fatalf("scope-domains.txt entries = %v", got)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-cidrs.txt"); strings.Join(got, ",") != "198.51.100.0/24" {
|
||||
t.Fatalf("scope-cidrs.txt entries = %v", got)
|
||||
}
|
||||
if !strings.Contains(out, "stub args: -export-egress-guard-scope -export-egress-guard-tasks 3,7\n") {
|
||||
t.Fatalf("artex was not called with the export flags:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "not exported: \"2001:db8::/32\"") {
|
||||
t.Fatalf("skipped entry was not reported:\n%s", out)
|
||||
}
|
||||
for _, name := range []string{"scope-domains.txt", "scope-cidrs.txt"} {
|
||||
st, err := os.Stat(filepath.Join(listsDir, name))
|
||||
if err != nil || st.Mode().Perm() != 0o644 {
|
||||
t.Fatalf("%s mode = %#o err=%v, want 0644 (read by the egress-guard container)", name, st.Mode().Perm(), err)
|
||||
}
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
// A failed or damaged export must leave both lists byte-for-byte as they were:
|
||||
// a partial list would silently widen or narrow what the overlay enforces.
|
||||
func TestExportScopeScriptLeavesListsOnFailure(t *testing.T) {
|
||||
good := "# artex egress-guard scope export v1\n# tasks: 3\ndomain new.example.org\ncidr 198.51.100.0/24\n"
|
||||
cases := []struct {
|
||||
name string
|
||||
export string
|
||||
exit int
|
||||
want string
|
||||
}{
|
||||
{"export command fails after printing", good + "# end domains=1 cidrs=1\n", 1, "export command failed"},
|
||||
{"missing trailer", good, 0, "truncated or inconsistent"},
|
||||
{"trailer count mismatch", good + "# end domains=2 cidrs=1\n", 0, "truncated or inconsistent"},
|
||||
{"no output", "", 0, "truncated or inconsistent"},
|
||||
{"data after trailer", good + "# end domains=1 cidrs=1\ndomain late.example.org\n", 0, "data after the export trailer"},
|
||||
{"domain with dnsmasq syntax", "domain evil.test/artex_allow\n# end domains=1 cidrs=0\n", 0, "malformed domain entry"},
|
||||
{"cidr that is not IPv4", "cidr 2001:db8::/32\n# end domains=0 cidrs=1\n", 0, "malformed cidr entry"},
|
||||
{"unknown line", "allow everything\n# end domains=0 cidrs=0\n", 0, "unexpected line"},
|
||||
{"empty export", "# artex egress-guard scope export v1\n# tasks: \n# end domains=0 cidrs=0\n", 0, "fall back to monitor"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
listsDir, out, err := runExportScopeScript(t, tc.export, tc.exit)
|
||||
if err == nil {
|
||||
t.Fatalf("export-scope.sh succeeded, want a failure:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(strings.Join(strings.Fields(out), " "), strings.Join(strings.Fields(tc.want), " ")) {
|
||||
t.Fatalf("output lacks %q:\n%s", tc.want, out)
|
||||
}
|
||||
assertEgressListsUnchanged(t, listsDir)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An empty export is written only on request, for an overlay pinned to enforce.
|
||||
// A list path that is a directory must be refused up front: mv would move the
|
||||
// new list inside it and report success, leaving the guard reading nothing.
|
||||
func TestExportScopeScriptRefusesDirectoryTarget(t *testing.T) {
|
||||
if _, err := exec.LookPath("bash"); err != nil {
|
||||
t.Skip("bash not available")
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
listsDir := filepath.Join(tmp, "lists")
|
||||
if err := os.MkdirAll(filepath.Join(listsDir, "scope-cidrs.txt"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(listsDir, "scope-domains.txt"), []byte(egressListDomainsOld), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ran := filepath.Join(tmp, "ran")
|
||||
stub := filepath.Join(tmp, "artex-stub")
|
||||
stubBody := "#!/usr/bin/env bash\n: > '" + ran + "'\nprintf 'domain new.example.com\\ncidr 198.51.100.0/24\\n# end domains=1 cidrs=1\\n'\n"
|
||||
if err := os.WriteFile(stub, []byte(stubBody), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join("..", "..", "egress-guard", "export-scope.sh")
|
||||
out, err := exec.Command("bash", script, "--lists", listsDir, "--", stub).CombinedOutput()
|
||||
if err == nil {
|
||||
t.Fatalf("export onto a directory target succeeded:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(string(out), "is a directory") {
|
||||
t.Fatalf("missing directory diagnostic:\n%s", out)
|
||||
}
|
||||
if _, statErr := os.Stat(ran); statErr == nil {
|
||||
t.Fatal("export command ran although a list target is a directory")
|
||||
}
|
||||
if got := readEgressList(t, listsDir, "scope-domains.txt"); got != egressListDomainsOld {
|
||||
t.Fatalf("scope-domains.txt changed: %q", got)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Join(listsDir, "scope-cidrs.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("a file was moved into the scope-cidrs.txt directory: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportScopeScriptAllowEmpty(t *testing.T) {
|
||||
export := "# artex egress-guard scope export v1\n# tasks: \n# end domains=0 cidrs=0\n"
|
||||
listsDir, out, err := runExportScopeScript(t, export, 0, "--allow-empty")
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh --allow-empty failed: %v\n%s", err, out)
|
||||
}
|
||||
for _, name := range []string{"scope-domains.txt", "scope-cidrs.txt"} {
|
||||
if got := egressListEntries(t, listsDir, name); len(got) != 0 {
|
||||
t.Fatalf("%s entries = %v, want none", name, got)
|
||||
}
|
||||
}
|
||||
assertNoStagedEgressFiles(t, listsDir)
|
||||
}
|
||||
|
||||
// End to end without Docker: the output of -export-egress-guard-scope, read
|
||||
// from PostgreSQL, goes through export-scope.sh into the two lists.
|
||||
func TestExportEgressGuardScopeToLists(t *testing.T) {
|
||||
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
|
||||
if dsn == "" {
|
||||
t.Skip("ARTEX_PG_DSN not set")
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.Close() })
|
||||
|
||||
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
opDom := "cli-op-" + sfx + ".test"
|
||||
agentDom := "cli-agent-" + sfx + ".test"
|
||||
task, err := pg.CreateTaskWithOptions("egress-export-cli-"+sfx, "goal", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })
|
||||
as := pg.Assets()
|
||||
if _, err := as.AddOperatorScope(task.ID, "subdomain", opDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope: %v", err)
|
||||
}
|
||||
if _, err := as.AddOperatorScope(task.ID, "cidr", "198.51.100.0/24", "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope cidr: %v", err)
|
||||
}
|
||||
if _, err := as.AddAgentScope(task.ID, "subdomain", agentDom, "agent", "agent"); err != nil {
|
||||
t.Fatalf("AddAgentScope: %v", err)
|
||||
}
|
||||
|
||||
taskArg := strconv.FormatInt(task.ID, 10)
|
||||
var buf bytes.Buffer
|
||||
if rc := runExportEgressGuardScope(taskArg, &buf); rc != 0 {
|
||||
t.Fatalf("runExportEgressGuardScope rc=%d output=%q", rc, buf.String())
|
||||
}
|
||||
listsDir, out, err := runExportScopeScript(t, buf.String(), 0, "--tasks", taskArg)
|
||||
if err != nil {
|
||||
t.Fatalf("export-scope.sh failed: %v\n%s", err, out)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-domains.txt"); len(got) != 1 || got[0] != opDom {
|
||||
t.Fatalf("scope-domains.txt entries = %v, want [%s]", got, opDom)
|
||||
}
|
||||
if got := egressListEntries(t, listsDir, "scope-cidrs.txt"); len(got) != 1 || got[0] != "198.51.100.0/24" {
|
||||
t.Fatalf("scope-cidrs.txt entries = %v", got)
|
||||
}
|
||||
|
||||
// A failed export prints nothing, so the script has nothing to install.
|
||||
for _, bad := range []string{"0", "abc", ",", strconv.FormatInt(1<<60, 10)} {
|
||||
buf.Reset()
|
||||
if rc := runExportEgressGuardScope(bad, &buf); rc == 0 || buf.Len() != 0 {
|
||||
t.Fatalf("runExportEgressGuardScope(%q) rc=%d output=%q, want a failure and no output", bad, rc, buf.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
|
@ -125,12 +126,18 @@ func run() int {
|
|||
rotateSecrets = flag.Bool("rotate-secrets", false, "re-encrypt database secrets from -rotate-old-secret-file to -rotate-new-secret-file, invalidate active JWT sessions, and exit")
|
||||
rotateOldSecretFile = flag.String("rotate-old-secret-file", "", "path to current secret.key (used with -rotate-secrets)")
|
||||
rotateNewSecretFile = flag.String("rotate-new-secret-file", "", "path to staged new secret.key (used with -rotate-secrets)")
|
||||
// Scope export for the optional egress-guard overlay, invoked by egress-guard/export-scope.sh.
|
||||
exportEgressGuardScope = flag.Bool("export-egress-guard-scope", false, "print the operator-approved task scope in the form egress-guard/export-scope.sh reads, and exit")
|
||||
exportEgressGuardTasks = flag.String("export-egress-guard-tasks", "", "comma-separated task ids for -export-egress-guard-scope (default: every task that is not finished)")
|
||||
)
|
||||
flag.Parse()
|
||||
|
||||
if *rotateSecrets {
|
||||
return runRotateSecrets(*rotateOldSecretFile, *rotateNewSecretFile)
|
||||
}
|
||||
if *exportEgressGuardScope {
|
||||
return runExportEgressGuardScope(*exportEgressGuardTasks, os.Stdout)
|
||||
}
|
||||
|
||||
// hand the build version and source revision to the server package so
|
||||
// GET /api/health can report them to the frontend top bar.
|
||||
|
|
@ -348,6 +355,51 @@ func envBool(name string, def bool) bool {
|
|||
return v
|
||||
}
|
||||
|
||||
// runExportEgressGuardScope prints the egress-guard allowlist derived from the
|
||||
// operator-approved task scope. Nothing is written to out unless the whole
|
||||
// export succeeded, so a failed run cannot hand the caller a partial list.
|
||||
func runExportEgressGuardScope(tasksCSV string, out io.Writer) int {
|
||||
var taskIDs []int64
|
||||
for _, part := range strings.Split(tasksCSV, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.ParseInt(part, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
slog.Error("[egress-guard-export] invalid task id in -export-egress-guard-tasks", "value", part)
|
||||
return 2
|
||||
}
|
||||
taskIDs = append(taskIDs, id)
|
||||
}
|
||||
if strings.TrimSpace(tasksCSV) != "" && len(taskIDs) == 0 {
|
||||
slog.Error("[egress-guard-export] -export-egress-guard-tasks names no task")
|
||||
return 2
|
||||
}
|
||||
dsn, _, err := config.PostgresDSN()
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] database DSN unavailable", "err", err)
|
||||
return 1
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] open database failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
defer pg.Close()
|
||||
|
||||
scope, err := server.ExportEgressGuardScope(pg, taskIDs)
|
||||
if err != nil {
|
||||
slog.Error("[egress-guard-export] export failed, nothing written", "err", err)
|
||||
return 1
|
||||
}
|
||||
if err := scope.Render(out); err != nil {
|
||||
slog.Error("[egress-guard-export] write failed", "err", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// runRotateSecrets atomically re-encrypts database secrets from oldPath to
|
||||
// newPath and increments auth.password_version to invalidate active sessions.
|
||||
func runRotateSecrets(oldPath, newPath string) int {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,8 @@ built, so if setup fails the ARTEX container loses outbound connectivity (except
|
|||
DNS) until the guard restarts cleanly.
|
||||
|
||||
## Operation
|
||||
- New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt`, then
|
||||
- New engagement: edit `lists/scope-domains.txt` and `lists/scope-cidrs.txt` (or
|
||||
generate them, see "Deriving the scope lists from ARTEX"), then
|
||||
`docker compose -f docker-compose.yml -f docker-compose.egress.yml restart egress-guard`.
|
||||
- Calibrate: `sudo egress-guard/report.sh` (or pass `"48 hours ago"`). Lists flagged
|
||||
connections and resolved names outside the allowlist.
|
||||
|
|
@ -43,6 +44,44 @@ DNS) until the guard restarts cleanly.
|
|||
- Stopping the service removes the rules. If dnsmasq dies on its own, the rules stay
|
||||
(fail-closed).
|
||||
|
||||
## Deriving the scope lists from ARTEX
|
||||
`export-scope.sh` writes `lists/scope-domains.txt` and `lists/scope-cidrs.txt` from
|
||||
the ARTEX database instead of by hand, so the overlay cannot drift from the scope
|
||||
the operator approved:
|
||||
|
||||
```bash
|
||||
egress-guard/export-scope.sh # every task that is not finished
|
||||
egress-guard/export-scope.sh --tasks 12,15
|
||||
docker compose -f docker-compose.yml -f docker-compose.egress.yml restart egress-guard
|
||||
```
|
||||
|
||||
- **Same source as the sandbox egress proxy.** The export runs the derivation the
|
||||
per-task `artex-egress-proxy` policy is built from (see `docs/SANDBOX.md`):
|
||||
operator-approved task scope (`approved_by_operator = true`), the company grants
|
||||
frozen at approval, and enabled operator task allow rules. Agent-added,
|
||||
auto-added and expanded rows are coverage-only and are never exported.
|
||||
- **One allowlist for all tasks.** The overlay filters the whole ARTEX network, so
|
||||
the lists are the union over the exported tasks; it cannot tell tasks apart the
|
||||
way the per-task proxy does. `base-domains.txt` is not touched.
|
||||
- **Fails closed.** The lists are replaced only when the whole export succeeded
|
||||
(database read, every entry parsed, output complete); an export that fails or
|
||||
is malformed changes neither file. Each file is then replaced by rename, one
|
||||
after the other. An export with no entry is refused unless
|
||||
`--allow-empty` is given: with `EGRESS_MODE` unset, empty scope lists make the
|
||||
guard fall back to `monitor`. Set `EGRESS_MODE=enforce` explicitly when the
|
||||
lists are generated.
|
||||
- **Not live.** The guard reads the lists at startup. Re-run the export and
|
||||
restart the guard after approving or revoking scope, and when a task starts or
|
||||
finishes; the restart also flushes the IPs allowed for a revoked domain.
|
||||
- **IPv4 only.** IPv6 scope entries are reported and skipped (see Known gaps). A
|
||||
domain is allowed for whatever it resolves to, including a private address the
|
||||
proxy would refuse.
|
||||
- The script runs `docker compose exec -T artex /app/artex -export-egress-guard-scope`.
|
||||
Pass another command after `--` for a different compose invocation or a
|
||||
binary outside the container (with `ARTEX_PG_DSN` set). The command opens the
|
||||
database the way the server does, which applies the schema and migrations, so
|
||||
that binary must be the same version as the running server.
|
||||
|
||||
## Known gaps
|
||||
- **IPv6 is not filtered.** The allowlist is IPv4-only (ipset `hash:ip`/`hash:net`).
|
||||
Keep the ARTEX network IPv4-only (do not set `enable_ipv6` on it) — then the
|
||||
|
|
|
|||
122
egress-guard/export-scope.sh
Executable file
122
egress-guard/export-scope.sh
Executable file
|
|
@ -0,0 +1,122 @@
|
|||
#!/usr/bin/env bash
|
||||
# Regenerate egress-guard/lists/scope-domains.txt and scope-cidrs.txt from the
|
||||
# operator-approved task scope in the ARTEX database, so the overlay enforces
|
||||
# the same boundary as the per-task sandbox egress proxy instead of a list
|
||||
# maintained by hand. See README.md, "Deriving the scope lists from ARTEX".
|
||||
#
|
||||
# Usage:
|
||||
# egress-guard/export-scope.sh [--lists DIR] [--tasks IDS] [--allow-empty] [-- COMMAND...]
|
||||
#
|
||||
# --lists DIR directory holding the scope lists (default: lists/ next to this script)
|
||||
# --tasks IDS comma-separated task ids (default: every task that is not finished)
|
||||
# --allow-empty write the lists even when the export has no entry. Only safe with
|
||||
# EGRESS_MODE=enforce set explicitly: with EGRESS_MODE unset, empty
|
||||
# scope lists make egress-guard fall back to monitor and block nothing.
|
||||
# COMMAND how to run the artex binary
|
||||
# (default: docker compose exec -T artex /app/artex)
|
||||
#
|
||||
# Guarantees:
|
||||
# 1. The lists are replaced only after the whole export was read and checked:
|
||||
# the command exited 0, every line is a well-formed entry, and the trailer
|
||||
# counts match. Until then neither list is touched.
|
||||
# 2. Each list is replaced by an atomic rename within DIR, one after the
|
||||
# other. The two renames are not one transaction: if the second fails
|
||||
# (the script exits non-zero and says so), scope-domains.txt is already new.
|
||||
# 3. egress-guard reads the lists at startup only. Restart it to apply them.
|
||||
set -euo pipefail
|
||||
umask 022
|
||||
|
||||
DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
LISTS="$DIR/lists"
|
||||
TASKS=""
|
||||
ALLOW_EMPTY=0
|
||||
CMD=(docker compose exec -T artex /app/artex)
|
||||
|
||||
usage() {
|
||||
sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'
|
||||
}
|
||||
|
||||
die() {
|
||||
echo "[export-scope] ERROR: $*" >&2
|
||||
echo "[export-scope] scope lists left unchanged." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--lists) [ $# -ge 2 ] || { usage >&2; exit 2; }; LISTS="$2"; shift 2 ;;
|
||||
--tasks) [ $# -ge 2 ] || { usage >&2; exit 2; }; TASKS="$2"; shift 2 ;;
|
||||
--allow-empty) ALLOW_EMPTY=1; shift ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
--) shift; [ $# -gt 0 ] || { usage >&2; exit 2; }; CMD=("$@"); break ;;
|
||||
*) echo "export-scope.sh: unknown argument: $1" >&2; usage >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[ -d "$LISTS" ] || die "lists directory not found: $LISTS"
|
||||
# mv onto a directory would move the new list inside it and report success.
|
||||
for target in "$LISTS/scope-domains.txt" "$LISTS/scope-cidrs.txt"; do
|
||||
if [ -d "$target" ]; then die "$target is a directory, not a list file"; fi
|
||||
done
|
||||
|
||||
# Staged in the same directory as the targets so rename(2) is atomic.
|
||||
RAW="$(mktemp "$LISTS/.scope-export.XXXXXX")"
|
||||
NEW_DOMAINS="$RAW.domains"
|
||||
NEW_CIDRS="$RAW.cidrs"
|
||||
cleanup() {
|
||||
rm -f "$RAW" "$NEW_DOMAINS" "$NEW_CIDRS"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
ARGS=(-export-egress-guard-scope)
|
||||
[ -n "$TASKS" ] && ARGS+=(-export-egress-guard-tasks "$TASKS")
|
||||
"${CMD[@]}" "${ARGS[@]}" > "$RAW" || die "export command failed: ${CMD[*]} ${ARGS[*]}"
|
||||
|
||||
HEADER="# Generated by egress-guard/export-scope.sh from the operator-approved ARTEX task scope.
|
||||
# Do not edit: the next export overwrites this file. Change the scope in ARTEX (Task Scope)."
|
||||
printf '%s\n' "$HEADER" > "$NEW_DOMAINS"
|
||||
printf '%s\n' "$HEADER" > "$NEW_CIDRS"
|
||||
|
||||
domains=0
|
||||
cidrs=0
|
||||
trailer=""
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
line="${line%$'\r'}"
|
||||
[ -z "$trailer" ] || die "data after the export trailer"
|
||||
case "$line" in
|
||||
"# end "*) trailer="$line" ;;
|
||||
"# tasks: "*) printf '%s\n' "$line" | tee -a "$NEW_DOMAINS" >> "$NEW_CIDRS" ;;
|
||||
"# skipped "*) echo "[export-scope] WARN: not exported: ${line#\# skipped }" >&2 ;;
|
||||
"#"*|"") ;;
|
||||
"domain "*)
|
||||
v="${line#domain }"
|
||||
[[ "$v" =~ ^[a-z0-9_]([a-z0-9_.-]*[a-z0-9_])?$ ]] || die "malformed domain entry"
|
||||
printf '%s\n' "$v" >> "$NEW_DOMAINS"
|
||||
domains=$((domains + 1))
|
||||
;;
|
||||
"cidr "*)
|
||||
v="${line#cidr }"
|
||||
[[ "$v" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}/[0-9]{1,2}$ ]] || die "malformed cidr entry"
|
||||
printf '%s\n' "$v" >> "$NEW_CIDRS"
|
||||
cidrs=$((cidrs + 1))
|
||||
;;
|
||||
*) die "unexpected line in export output" ;;
|
||||
esac
|
||||
done < "$RAW"
|
||||
|
||||
[ "$trailer" = "# end domains=$domains cidrs=$cidrs" ] \
|
||||
|| die "export output is truncated or inconsistent (read domains=$domains cidrs=$cidrs, trailer: ${trailer:-missing})"
|
||||
|
||||
if [ $((domains + cidrs)) -eq 0 ] && [ "$ALLOW_EMPTY" -ne 1 ]; then
|
||||
die "the export has no entry. With EGRESS_MODE unset, empty scope lists make egress-guard fall back to monitor (no blocking). Set EGRESS_MODE=enforce in .env and re-run with --allow-empty to write empty lists"
|
||||
fi
|
||||
|
||||
mv -f "$NEW_DOMAINS" "$LISTS/scope-domains.txt" \
|
||||
|| die "could not replace $LISTS/scope-domains.txt"
|
||||
if ! mv -f "$NEW_CIDRS" "$LISTS/scope-cidrs.txt"; then
|
||||
echo "[export-scope] ERROR: could not replace $LISTS/scope-cidrs.txt; scope-domains.txt was already replaced. Fix the cause and re-run before restarting egress-guard." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[export-scope] wrote $domains domain suffix(es) and $cidrs CIDR(s) to $LISTS"
|
||||
echo "[export-scope] restart egress-guard to apply: docker compose -f docker-compose.yml -f docker-compose.egress.yml restart egress-guard"
|
||||
145
server/egress_guard_export.go
Normal file
145
server/egress_guard_export.go
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
// EgressGuardScope is the operator-approved scope of a set of tasks in the
|
||||
// form the egress-guard overlay reads (egress-guard/lists/scope-domains.txt
|
||||
// and scope-cidrs.txt). The overlay has one allowlist for the whole ARTEX
|
||||
// network, so this is the union over the tasks.
|
||||
type EgressGuardScope struct {
|
||||
TaskIDs []int64
|
||||
Domains []string // domain suffixes, sorted
|
||||
CIDRs []string // IPv4 prefixes, sorted
|
||||
Skipped []string // entries the overlay cannot express, with the reason
|
||||
}
|
||||
|
||||
// egressGuardDomainRE is what may be written as a dnsmasq "ipset=/<suffix>/..."
|
||||
// line: dot-separated labels of letters, digits, "-" and "_". Anything else
|
||||
// could not match a hostname in the proxy either, and must not reach the
|
||||
// overlay's dnsmasq configuration.
|
||||
var egressGuardDomainRE = regexp.MustCompile(`^[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)*$`)
|
||||
|
||||
// ExportEgressGuardScope derives the egress-guard allowlist from the same
|
||||
// source as the per-task sandbox egress proxy: taskSandboxRunInfo, parsed by
|
||||
// sandbox.NewEgressPolicy. Only operator-approved task scope, frozen company
|
||||
// grants and operator task allow rules are exported; agent-added, auto-added
|
||||
// and expanded rows are not.
|
||||
//
|
||||
// With no taskIDs, every task that is not in a terminal state is exported.
|
||||
// Any read or parse error fails the whole export: a partial list must not
|
||||
// replace the one the overlay already has.
|
||||
func ExportEgressGuardScope(pg *db.DB, taskIDs []int64) (EgressGuardScope, error) {
|
||||
var out EgressGuardScope
|
||||
if pg == nil {
|
||||
return out, fmt.Errorf("no database")
|
||||
}
|
||||
if len(taskIDs) == 0 {
|
||||
tasks, err := pg.ListTasks()
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("list tasks: %w", err)
|
||||
}
|
||||
for _, t := range tasks {
|
||||
if !db.IsTerminal(t.Status) {
|
||||
taskIDs = append(taskIDs, t.ID)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, id := range taskIDs {
|
||||
t, err := pg.GetTask(id)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("task %d: %w", id, err)
|
||||
}
|
||||
if t == nil {
|
||||
return out, fmt.Errorf("task %d does not exist", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
seenTask := map[int64]bool{}
|
||||
seenDom := map[string]bool{}
|
||||
seenCIDR := map[string]bool{}
|
||||
seenSkip := map[string]bool{}
|
||||
skip := func(entry, reason string) {
|
||||
s := fmt.Sprintf("%q: %s", entry, reason)
|
||||
if !seenSkip[s] {
|
||||
seenSkip[s] = true
|
||||
out.Skipped = append(out.Skipped, s)
|
||||
}
|
||||
}
|
||||
for _, id := range taskIDs {
|
||||
if seenTask[id] {
|
||||
continue
|
||||
}
|
||||
seenTask[id] = true
|
||||
out.TaskIDs = append(out.TaskIDs, id)
|
||||
info, err := taskSandboxRunInfoChecked(pg, "", strconv.FormatInt(id, 10))
|
||||
if err != nil {
|
||||
return EgressGuardScope{}, fmt.Errorf("task %d: read scope: %w", id, err)
|
||||
}
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
return EgressGuardScope{}, fmt.Errorf("task %d: %w", id, err)
|
||||
}
|
||||
for _, d := range pol.Domains {
|
||||
if !egressGuardDomainRE.MatchString(d) {
|
||||
skip(d, "not a hostname suffix")
|
||||
continue
|
||||
}
|
||||
if !seenDom[d] {
|
||||
seenDom[d] = true
|
||||
out.Domains = append(out.Domains, d)
|
||||
}
|
||||
}
|
||||
for _, p := range pol.CIDRs {
|
||||
c := p.String()
|
||||
if !p.Addr().Is4() {
|
||||
skip(c, "IPv6, egress-guard is IPv4-only")
|
||||
continue
|
||||
}
|
||||
if !seenCIDR[c] {
|
||||
seenCIDR[c] = true
|
||||
out.CIDRs = append(out.CIDRs, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(out.TaskIDs, func(i, j int) bool { return out.TaskIDs[i] < out.TaskIDs[j] })
|
||||
sort.Strings(out.Domains)
|
||||
sort.Strings(out.CIDRs)
|
||||
sort.Strings(out.Skipped)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Render writes the scope as the line protocol egress-guard/export-scope.sh
|
||||
// reads: "domain <suffix>" and "cidr <prefix>" lines, then a trailer carrying
|
||||
// both counts so a truncated stream is detectable. Comment lines start with "#".
|
||||
func (s EgressGuardScope) Render(w io.Writer) error {
|
||||
var b strings.Builder
|
||||
ids := make([]string, 0, len(s.TaskIDs))
|
||||
for _, id := range s.TaskIDs {
|
||||
ids = append(ids, strconv.FormatInt(id, 10))
|
||||
}
|
||||
b.WriteString("# artex egress-guard scope export v1\n")
|
||||
fmt.Fprintf(&b, "# tasks: %s\n", strings.Join(ids, ","))
|
||||
for _, d := range s.Domains {
|
||||
fmt.Fprintf(&b, "domain %s\n", d)
|
||||
}
|
||||
for _, c := range s.CIDRs {
|
||||
fmt.Fprintf(&b, "cidr %s\n", c)
|
||||
}
|
||||
for _, sk := range s.Skipped {
|
||||
fmt.Fprintf(&b, "# skipped %s\n", sk)
|
||||
}
|
||||
fmt.Fprintf(&b, "# end domains=%d cidrs=%d\n", len(s.Domains), len(s.CIDRs))
|
||||
_, err := io.WriteString(w, b.String())
|
||||
return err
|
||||
}
|
||||
321
server/egress_guard_export_test.go
Normal file
321
server/egress_guard_export_test.go
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
func openEgressGuardExportPG(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
|
||||
if dsn == "" {
|
||||
t.Skip("ARTEX_PG_DSN not set")
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.Close() })
|
||||
return pg
|
||||
}
|
||||
|
||||
func newEgressGuardExportTask(t *testing.T, pg *db.DB, name string) int64 {
|
||||
t.Helper()
|
||||
task, err := pg.CreateTaskWithOptions(name, "goal", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })
|
||||
return task.ID
|
||||
}
|
||||
|
||||
// TestEgressGuardExportMatchesSandboxPolicy pins the reason the exporter exists:
|
||||
// the egress-guard lists are derived from the scope the per-task egress proxy
|
||||
// enforces, so operator-approved rows and operator allow rules are exported and
|
||||
// agent-added, auto-added, denied and disabled entries are not.
|
||||
func TestEgressGuardExportMatchesSandboxPolicy(t *testing.T) {
|
||||
pg := openEgressGuardExportPG(t)
|
||||
as := pg.Assets()
|
||||
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
|
||||
opDom := "op-" + sfx + ".test"
|
||||
ruleDom := "rule-" + sfx + ".test"
|
||||
otherDom := "other-" + sfx + ".test"
|
||||
agentDom := "agent-" + sfx + ".test"
|
||||
autoDom := "auto-" + sfx + ".test"
|
||||
denyDom := "deny-" + sfx + ".test"
|
||||
offDom := "off-" + sfx + ".test"
|
||||
|
||||
a := newEgressGuardExportTask(t, pg, "egress-export-a-"+sfx)
|
||||
b := newEgressGuardExportTask(t, pg, "egress-export-b-"+sfx)
|
||||
|
||||
for _, in := range []struct{ kind, value string }{
|
||||
{"subdomain", opDom},
|
||||
{"cidr", "198.51.100.0/24"},
|
||||
{"ip", "203.0.113.7"},
|
||||
{"ip", "2001:db8::7"},
|
||||
} {
|
||||
if ts, err := as.AddOperatorScope(a, in.kind, in.value, "operator"); err != nil || !ts.ApprovedByOperator {
|
||||
t.Fatalf("AddOperatorScope %s %s: ts=%+v err=%v", in.kind, in.value, ts, err)
|
||||
}
|
||||
}
|
||||
if _, err := as.AddAgentScope(a, "subdomain", agentDom, "agent", "agent"); err != nil {
|
||||
t.Fatalf("AddAgentScope: %v", err)
|
||||
}
|
||||
if _, err := as.AddAgentScope(a, "cidr", "192.0.2.0/24", "agent", "agent"); err != nil {
|
||||
t.Fatalf("AddAgentScope cidr: %v", err)
|
||||
}
|
||||
if err := as.AddAutoScope(a, "subdomain", autoDom, "", ""); err != nil {
|
||||
t.Fatalf("AddAutoScope: %v", err)
|
||||
}
|
||||
for _, r := range []struct {
|
||||
action, pattern string
|
||||
enabled bool
|
||||
}{
|
||||
{"allow", ruleDom, true},
|
||||
{"deny", denyDom, true},
|
||||
{"allow", offDom, false},
|
||||
} {
|
||||
if _, err := as.CreateTaskInterceptRule(a, r.action, "exact_domain", r.pattern, "test", r.enabled); err != nil {
|
||||
t.Fatalf("CreateTaskInterceptRule %s %s: %v", r.action, r.pattern, err)
|
||||
}
|
||||
}
|
||||
// A second task: the overlay has one allowlist, so the export is the union.
|
||||
if _, err := as.AddOperatorScope(b, "subdomain", otherDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope b: %v", err)
|
||||
}
|
||||
if _, err := as.AddOperatorScope(b, "cidr", "198.51.100.0/24", "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope b cidr: %v", err)
|
||||
}
|
||||
|
||||
got, err := ExportEgressGuardScope(pg, []int64{b, a, a})
|
||||
if err != nil {
|
||||
t.Fatalf("ExportEgressGuardScope: %v", err)
|
||||
}
|
||||
wantDomains := []string{opDom, otherDom, ruleDom}
|
||||
if strings.Join(got.Domains, ",") != strings.Join(wantDomains, ",") {
|
||||
t.Fatalf("Domains = %v, want %v", got.Domains, wantDomains)
|
||||
}
|
||||
wantCIDRs := []string{"198.51.100.0/24", "203.0.113.7/32"}
|
||||
if strings.Join(got.CIDRs, ",") != strings.Join(wantCIDRs, ",") {
|
||||
t.Fatalf("CIDRs = %v, want %v", got.CIDRs, wantCIDRs)
|
||||
}
|
||||
if len(got.TaskIDs) != 2 {
|
||||
t.Fatalf("TaskIDs = %v, want the two tasks once each", got.TaskIDs)
|
||||
}
|
||||
if len(got.Skipped) != 1 || !strings.Contains(got.Skipped[0], "2001:db8::7/128") || !strings.Contains(got.Skipped[0], "IPv6") {
|
||||
t.Fatalf("Skipped = %v, want the IPv6 entry", got.Skipped)
|
||||
}
|
||||
|
||||
// No second derivation: every exported entry is one the proxy policy of one
|
||||
// of the tasks holds, and every IPv4 entry of those policies is exported.
|
||||
inProxy := map[string]bool{}
|
||||
for _, id := range []int64{a, b} {
|
||||
info := taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(id, 10))
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEgressPolicy: %v", err)
|
||||
}
|
||||
for _, d := range pol.Domains {
|
||||
inProxy[d] = true
|
||||
}
|
||||
for _, p := range pol.CIDRs {
|
||||
if p.Addr().Is4() {
|
||||
inProxy[p.String()] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
exported := append(append([]string{}, got.Domains...), got.CIDRs...)
|
||||
if len(exported) != len(inProxy) {
|
||||
t.Fatalf("export %v differs from the proxy policies %v", exported, inProxy)
|
||||
}
|
||||
for _, e := range exported {
|
||||
if !inProxy[e] {
|
||||
t.Fatalf("exported %q is not in any proxy policy %v", e, inProxy)
|
||||
}
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := got.Render(&buf); err != nil {
|
||||
t.Fatalf("Render: %v", err)
|
||||
}
|
||||
out := buf.String()
|
||||
for _, want := range []string{
|
||||
"domain " + opDom + "\n",
|
||||
"cidr 198.51.100.0/24\n",
|
||||
"# skipped \"2001:db8::7/128\": IPv6, egress-guard is IPv4-only\n",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("rendered export lacks %q:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if !strings.HasSuffix(out, "# end domains=3 cidrs=2\n") {
|
||||
t.Fatalf("rendered export lacks the trailer:\n%s", out)
|
||||
}
|
||||
|
||||
// Revoking the operator row removes it from the next export.
|
||||
rows, err := as.ListTaskScope(a)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTaskScope: %v", err)
|
||||
}
|
||||
revoked := false
|
||||
for _, r := range rows {
|
||||
if r.Domain == opDom {
|
||||
if ok, err := as.DeleteTaskScope(a, r.ID); err != nil || !ok {
|
||||
t.Fatalf("DeleteTaskScope: ok=%v err=%v", ok, err)
|
||||
}
|
||||
revoked = true
|
||||
}
|
||||
}
|
||||
if !revoked {
|
||||
t.Fatal("operator scope row not found")
|
||||
}
|
||||
got, err = ExportEgressGuardScope(pg, []int64{a, b})
|
||||
if err != nil {
|
||||
t.Fatalf("ExportEgressGuardScope after revoke: %v", err)
|
||||
}
|
||||
if scopeHas(got.Domains, opDom) {
|
||||
t.Fatalf("revoked scope still exported: %v", got.Domains)
|
||||
}
|
||||
}
|
||||
|
||||
// With no task list the export covers the tasks that can still run commands:
|
||||
// a finished task's scope is dropped, and naming the task brings it back.
|
||||
func TestEgressGuardExportDefaultsToNonTerminalTasks(t *testing.T) {
|
||||
pg := openEgressGuardExportPG(t)
|
||||
as := pg.Assets()
|
||||
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
liveDom := "live-" + sfx + ".test"
|
||||
doneDom := "done-" + sfx + ".test"
|
||||
|
||||
live := newEgressGuardExportTask(t, pg, "egress-export-live-"+sfx)
|
||||
done := newEgressGuardExportTask(t, pg, "egress-export-done-"+sfx)
|
||||
if _, err := as.AddOperatorScope(live, "subdomain", liveDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope live: %v", err)
|
||||
}
|
||||
if _, err := as.AddOperatorScope(done, "subdomain", doneDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope done: %v", err)
|
||||
}
|
||||
if err := pg.SetStatus(done, "done"); err != nil {
|
||||
t.Fatalf("SetStatus: %v", err)
|
||||
}
|
||||
|
||||
got, err := ExportEgressGuardScope(pg, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ExportEgressGuardScope: %v", err)
|
||||
}
|
||||
if !scopeHas(got.Domains, liveDom) {
|
||||
t.Fatalf("running task scope missing: %v", got.Domains)
|
||||
}
|
||||
if scopeHas(got.Domains, doneDom) {
|
||||
t.Fatalf("finished task scope exported by default: %v", got.Domains)
|
||||
}
|
||||
|
||||
got, err = ExportEgressGuardScope(pg, []int64{done})
|
||||
if err != nil {
|
||||
t.Fatalf("ExportEgressGuardScope explicit: %v", err)
|
||||
}
|
||||
if len(got.Domains) != 1 || got.Domains[0] != doneDom {
|
||||
t.Fatalf("explicit task export = %v, want [%s]", got.Domains, doneDom)
|
||||
}
|
||||
}
|
||||
|
||||
// An export that cannot be completed returns an error and no scope, so the
|
||||
// caller has nothing to write over the lists the overlay already enforces.
|
||||
func TestEgressGuardExportFailsClosed(t *testing.T) {
|
||||
pg := openEgressGuardExportPG(t)
|
||||
as := pg.Assets()
|
||||
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
okDom := "ok-" + sfx + ".test"
|
||||
|
||||
good := newEgressGuardExportTask(t, pg, "egress-export-good-"+sfx)
|
||||
if _, err := as.AddOperatorScope(good, "subdomain", okDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope: %v", err)
|
||||
}
|
||||
|
||||
assertEmpty := func(t *testing.T, got EgressGuardScope, err error) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatalf("expected an error, got scope %+v", got)
|
||||
}
|
||||
if len(got.Domains)+len(got.CIDRs)+len(got.TaskIDs) != 0 {
|
||||
t.Fatalf("failed export returned a scope: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("unknown task", func(t *testing.T) {
|
||||
got, err := ExportEgressGuardScope(pg, []int64{good, 1 << 60})
|
||||
assertEmpty(t, got, err)
|
||||
})
|
||||
|
||||
t.Run("no database", func(t *testing.T) {
|
||||
got, err := ExportEgressGuardScope(nil, []int64{good})
|
||||
assertEmpty(t, got, err)
|
||||
})
|
||||
|
||||
t.Run("closed database", func(t *testing.T) {
|
||||
closed, err := db.Open(strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")))
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
_ = closed.Close()
|
||||
got, err := ExportEgressGuardScope(closed, nil)
|
||||
assertEmpty(t, got, err)
|
||||
// The derivation itself reports the failed read (the proxy path ignores
|
||||
// it and denies by default).
|
||||
if _, err := taskSandboxRunInfoChecked(closed, "", strconv.FormatInt(good, 10)); err == nil {
|
||||
t.Fatal("taskSandboxRunInfoChecked on a closed database returned no error")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("entry the proxy cannot parse", func(t *testing.T) {
|
||||
bad := newEgressGuardExportTask(t, pg, "egress-export-bad-"+sfx)
|
||||
if _, err := pg.Exec(`INSERT INTO task_intercept_rules(task_id, enabled, action, kind, pattern, note) VALUES ($1,true,'allow','cidr','not-a-cidr','test')`, bad); err != nil {
|
||||
t.Fatalf("insert rule: %v", err)
|
||||
}
|
||||
got, err := ExportEgressGuardScope(pg, []int64{good, bad})
|
||||
assertEmpty(t, got, err)
|
||||
if err != nil && !strings.Contains(err.Error(), strconv.FormatInt(bad, 10)) {
|
||||
t.Fatalf("error does not name the task: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
// A pattern that is not a hostname must never reach the overlay's dnsmasq
|
||||
// configuration, where the suffix is written into an "ipset=/<suffix>/" line.
|
||||
t.Run("pattern that is not a hostname", func(t *testing.T) {
|
||||
odd := newEgressGuardExportTask(t, pg, "egress-export-odd-"+sfx)
|
||||
pattern := "x-" + sfx + ".test/artex_allow\nipset=/"
|
||||
if _, err := pg.Exec(`INSERT INTO task_intercept_rules(task_id, enabled, action, kind, pattern, note) VALUES ($1,true,'allow','exact_domain',$2,'test')`, odd, pattern); err != nil {
|
||||
t.Fatalf("insert rule: %v", err)
|
||||
}
|
||||
if _, err := as.AddOperatorScope(odd, "subdomain", okDom, "operator"); err != nil {
|
||||
t.Fatalf("AddOperatorScope: %v", err)
|
||||
}
|
||||
got, err := ExportEgressGuardScope(pg, []int64{odd})
|
||||
if err != nil {
|
||||
t.Fatalf("ExportEgressGuardScope: %v", err)
|
||||
}
|
||||
if len(got.Domains) != 1 || got.Domains[0] != okDom {
|
||||
t.Fatalf("Domains = %q, want only %q", got.Domains, okDom)
|
||||
}
|
||||
if len(got.Skipped) != 1 || !strings.Contains(got.Skipped[0], "not a hostname suffix") {
|
||||
t.Fatalf("Skipped = %q, want the rejected pattern", got.Skipped)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := got.Render(&buf); err != nil {
|
||||
t.Fatalf("Render: %v", err)
|
||||
}
|
||||
for _, line := range strings.Split(strings.TrimSuffix(buf.String(), "\n"), "\n") {
|
||||
if !strings.HasPrefix(line, "#") && line != "domain "+okDom {
|
||||
t.Fatalf("unexpected line %q in:\n%s", line, buf.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ package server
|
|||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"path/filepath"
|
||||
|
|
@ -79,17 +80,28 @@ func (s *Server) checkSandboxReady(ctx context.Context) error {
|
|||
// taskSandboxRunInfo builds the per-task sandbox metadata (including scope
|
||||
// domains and CIDRs for the per-task egress proxy) from PostgreSQL.
|
||||
func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo {
|
||||
// A read error leaves the scope narrower, which the deny-by-default proxy
|
||||
// turns into a denial, so the error is not needed here.
|
||||
info, _ := taskSandboxRunInfoChecked(pg, dataDir, taskID)
|
||||
return info
|
||||
}
|
||||
|
||||
// taskSandboxRunInfoChecked is taskSandboxRunInfo plus the read errors it met.
|
||||
// The returned scope is the same either way; a caller that persists the scope
|
||||
// (the egress-guard export) uses the error to refuse a partial result.
|
||||
func taskSandboxRunInfoChecked(pg *db.DB, dataDir, taskID string) (agent.SandboxRunInfo, error) {
|
||||
info := agent.SandboxRunInfo{
|
||||
TaskID: taskID,
|
||||
TaskDir: filepath.Join(dataDir, "tasks", taskID),
|
||||
}
|
||||
if pg == nil {
|
||||
return info
|
||||
return info, errors.New("no database")
|
||||
}
|
||||
tid, err := strconv.ParseInt(taskID, 10, 64)
|
||||
if err != nil || tid <= 0 {
|
||||
return info
|
||||
return info, fmt.Errorf("invalid task id %q", taskID)
|
||||
}
|
||||
var errs []error
|
||||
seenDom := map[string]bool{}
|
||||
seenCIDR := map[string]bool{}
|
||||
addDom := func(d string) {
|
||||
|
|
@ -115,7 +127,9 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
|||
for rows.Next() {
|
||||
var kind, dom, netStr, val string
|
||||
var compID int64
|
||||
if rows.Scan(&kind, &dom, &netStr, &val, &compID) == nil {
|
||||
if err := rows.Scan(&kind, &dom, &netStr, &val, &compID); err != nil {
|
||||
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
||||
} else {
|
||||
switch kind {
|
||||
case "company":
|
||||
if compID > 0 && !seenComp[compID] {
|
||||
|
|
@ -137,6 +151,11 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
|||
}
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
||||
}
|
||||
} else {
|
||||
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
||||
}
|
||||
// Company grants are frozen at operator-approval time in task_scope_egress.
|
||||
// Reading live company_scope/assets here let the planner's add_company_scope
|
||||
|
|
@ -144,6 +163,7 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
|||
for _, cid := range companyIDs {
|
||||
entries, err := pg.CompanyEgressForTask(tid, cid)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("task_scope_egress: %w", err))
|
||||
continue
|
||||
}
|
||||
for _, e := range entries {
|
||||
|
|
@ -159,7 +179,9 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
|||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var kind, pat string
|
||||
if rows.Scan(&kind, &pat) == nil {
|
||||
if err := rows.Scan(&kind, &pat); err != nil {
|
||||
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
||||
} else {
|
||||
switch kind {
|
||||
case "exact_domain", "domain_suffix":
|
||||
addDom(pat)
|
||||
|
|
@ -170,8 +192,13 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
|||
}
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
||||
}
|
||||
} else {
|
||||
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
||||
}
|
||||
return info
|
||||
return info, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// emptyEgressScopeWarning describes the chat-spawn scope trap (#830): the task
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue