diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc9dd70..674a20d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,6 +116,18 @@ jobs: # service, so parallel package runs delete each other's rows. - run: go test -p 1 ./... + govulncheck: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + # The official action uses the Go version declared by go.mod and reports + # only vulnerabilities reachable from this module's packages. + - uses: golang/govulncheck-action@v1 + with: + go-version-file: go.mod + go-package: ./... + shell: runs-on: ubuntu-latest steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index ed83caf..3bb4b5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,13 @@ All notable changes to this project are documented in this file. The format is b - **Stream viewer direction filter** (follow-up to #380): the Traffic detail's Stream tab can show all messages, client-to-server messages or server-to-client messages. Pagination and refresh keep the selected direction, changing the filter resets the list, and opening another exchange resets the direction to all. Recording-limit warnings remain visible but are excluded from the displayed message counts. - **Security response headers on every response**: `X-Content-Type-Options: nosniff`, a same-origin referrer policy, `X-Frame-Options: SAMEORIGIN` and a `frame-ancestors 'self'` CSP are now set by one wrapper around the whole handler tree, so the JSON API carries them too; previously only the console route did. Console documents additionally get `Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a peer in `ARTEX_TRUSTED_PROXIES`, so a direct client cannot claim HTTPS on its own. The README reverse-proxy recipe now starts with an 80 to 443 redirect. - **Global company switcher**: the sidebar header carries a company picker (search, an explicit "all companies", the asset count). It persists per browser and narrows these views on the server: the findings list, grouped view, asset tree and stat cards (`GET /api/exploration/findings`, `/groups`, `/asset-tree`, `/stats` take `company`), the dashboard findings panels (same list endpoint), the task list (`GET /api/tasks?company=`), the traffic list (`GET /api/traffic?company=`, the hosts the company owns) and the asset tabs (`GET /api/assets?company_id=`, plain and DSL path; the company clause is ANDed outside the compiled DSL). A finding belongs to a company through its live assets. A finding with no live asset belongs to a company only when its task is scoped to that company (`task_scope` kind `company`); otherwise it shows under "all companies" only. An unknown or non-numeric company id returns nothing (#425). +- **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`. ### Fixed +- **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host. +- **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays. +- **A named pipe in the task workspace no longer hangs the archive worker**: packing opened every non-directory entry, and opening a FIFO blocks until a writer appears, so the single archive worker stopped there and every later archive, restore and delete job waited behind it. A socket failed the archive instead, and a device was packed but refused on restore. The packer now skips every entry that is neither a directory nor a regular file, as it already did for symlinks. - **Task form does not keep test-account secrets on screen**: after a task is created the credential rows are cleared, and the password field is masked. - **LLM connection-test logs stay one line**: the response body written by a connection test has CR and LF replaced with spaces before it is logged, so the body cannot start a second log record. - **Benchmark judge validation**: grading and the judge's falsification battery require one verdict per ground-truth ID, actual boolean decisions and gates, and matches to the supplied scanner findings. Invalid grading responses use the existing three-attempt budget and abort without writing scores, rather than counting duplicate IDs or truthy strings such as `"false"`. @@ -305,7 +309,7 @@ Ollama support, a setup token for the first-run claim, secret scrubbing for chil - **The build context includes local secrets**: `.dockerignore` does not exclude `.env`, `config.json` or `jwt.key`, so the build stage's `COPY . .` puts them in a build-stage layer of the local builder cache. They are not copied into the final image. - **Image supply chain**: the recon tools are downloaded at pinned versions but not checksum-verified, sqlmap tracks its default branch, and the Playwright packages are installed at `@latest`. Draft #127 proposes checksum verification. - **No Docker image is published for this release**: the release workflow's `docker` job only runs when `DOCKERHUB_ENABLED` is set, and it still downloads prebuilt binaries into `dist/` that the Dockerfile no longer uses. Build the image from the checkout with `docker compose up -d --build`. -- **CI gaps**: `./server` is not run under `-race`; there is no `govulncheck` step and no `docker build` job. Four tests skip themselves (fresh-database or timing failures, see #9). +- **CI gaps**: there is no `docker build` job. Four tests skip themselves (fresh-database or timing failures, see #9). - **Reported and not fixed in this release**: `list_task_credentials` emits an invalid `"required": [""]` schema that strict LLM providers reject (#130), and the MCP Streamable HTTP client fails against servers that only support protocol version 2025-11-25 (#131; fix proposed in #132). ## [0.4.0] - 2026-10-23 diff --git a/README.md b/README.md index 40a586d..3430e48 100644 --- a/README.md +++ b/README.md @@ -871,7 +871,8 @@ CGO_ENABLED=0 go build -tags embedui -o artex ./cmd/artex - Backend: `go run ./cmd/artex` (without `-tags embedui`, the frontend is not embedded) - Frontend: `cd web && npm run dev` (`/api` is reverse-proxied to the backend, with hot reload) - Tests: `go test ./...` -- Reproduce all CI checks locally: `./scripts/verify.sh` (add `--full` for `-race` and the static web build) +- Reproduce the fast CI checks locally: `./scripts/verify.sh` (add `--full` for `-race` and the static web build; add `--security` for `govulncheck`) +- Security scan: install `govulncheck` and run `./scripts/verify.sh --security` (CI runs this on every push and pull request) - Mock preview (no backend): `cd web && NEXT_PUBLIC_MOCK=1 npm run dev` --- diff --git a/db/triggers.go b/db/triggers.go index 932de91..98ab3ba 100644 --- a/db/triggers.go +++ b/db/triggers.go @@ -189,13 +189,14 @@ ORDER BY n.id`, lastID) return out, rows.Err() } -// TimedOutTasksSince returns tasks that reached status='timeout' with id > lastID, -// ordered by id (monotonic watermark → no double-fire across restarts). -func (d *DB) TimedOutTasksSince(lastID int64) ([]TaskEvent, error) { +// TimedOutTasks returns all live tasks in status='timeout', ordered by id. Tasks +// time out in deadline order, not id order, so the scheduler filters out the +// ones it already fired for via its persisted fired-set, not an id watermark. +func (d *DB) TimedOutTasks() ([]TaskEvent, error) { rows, err := d.Query(` SELECT id, description, goal FROM tasks -WHERE status='timeout' AND deleted_at IS NULL AND id > $1 -ORDER BY id`, lastID) +WHERE status='timeout' AND deleted_at IS NULL +ORDER BY id`) if err != nil { return nil, err } @@ -206,7 +207,7 @@ ORDER BY id`, lastID) if err := rows.Scan(&e.NodeID, &e.TaskDesc, &e.TaskGoal); err != nil { return nil, err } - e.TaskID = e.NodeID // task id doubles as NodeID for the watermark + e.TaskID = e.NodeID // task id doubles as NodeID for the fired-set e.Summary = e.TaskGoal out = append(out, e) } diff --git a/go.mod b/go.mod index d3950d5..2d5fbb7 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 - github.com/gorilla/websocket v1.5.3 + github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 github.com/jackc/pgx/v5 v5.10.0 github.com/klauspost/compress v1.20.2 github.com/lqqyt2423/go-mitmproxy v1.9.2 diff --git a/go.sum b/go.sum index 3fb4d3f..6433406 100644 --- a/go.sum +++ b/go.sum @@ -67,8 +67,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= -github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= -github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 h1:PYKzliEgITjLJoJqbV90S0YRaG8LNAsICH6fp6MApC0= +github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02 h1:AgcIVYPa6XJnU3phs104wLj8l5GEththEw6+F79YsIY= diff --git a/scripts/verify.sh b/scripts/verify.sh index c231edd..47a7bd9 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -2,9 +2,10 @@ # Verify ARTEX locally, reproducing the checks from .github/workflows/ci.yml. # # Usage: -# scripts/verify.sh [--full] [--go-only] [--web-only] [--keep-going] +# scripts/verify.sh [--full] [--security] [--go-only] [--web-only] [--keep-going] # # --full also run `go test -race` (the CI package list) and the web static build +# --security run `govulncheck ./...` (requires govulncheck in PATH) # --go-only run only the Go checks # --web-only run only the web checks # --keep-going continue after a failed step and report every failure at the end @@ -18,12 +19,14 @@ cd "$(dirname "$0")/.." usage() { sed -n '2,14p' "$0" | sed 's/^# \?//'; } FULL=0 +SECURITY=0 GO_ONLY=0 WEB_ONLY=0 KEEP_GOING=0 while [ $# -gt 0 ]; do case "$1" in --full) FULL=1; shift ;; + --security) SECURITY=1; shift ;; --go-only) GO_ONLY=1; shift ;; --web-only) WEB_ONLY=1; shift ;; --keep-going) KEEP_GOING=1; shift ;; @@ -35,6 +38,10 @@ if [ "$GO_ONLY" -eq 1 ] && [ "$WEB_ONLY" -eq 1 ]; then echo "--go-only and --web-only are mutually exclusive" >&2 exit 2 fi +if [ "$SECURITY" -eq 1 ] && [ "$WEB_ONLY" -eq 1 ]; then + echo "--security requires the Go checks and cannot be combined with --web-only" >&2 + exit 2 +fi FAILED=0 run_step() { @@ -109,6 +116,11 @@ if want_go; then run_step "go vet" go vet ./... run_step "go test -p 1" go test -p 1 ./... + if [ "$SECURITY" -eq 1 ]; then + require_cmd govulncheck + run_step "govulncheck" govulncheck ./... + fi + if [ "$FULL" -eq 1 ]; then RACE_PKGS=( ./agent ./cmd/artex ./config ./db ./evidence ./guard diff --git a/server/parse_target_test.go b/server/parse_target_test.go new file mode 100644 index 0000000..2ee9c78 --- /dev/null +++ b/server/parse_target_test.go @@ -0,0 +1,38 @@ +package server + +import "testing" + +func TestParseTargetURLFollowedByPunctuation(t *testing.T) { + cases := []struct { + text string + scheme string + host string + port int + }{ + {"Assess http://juiceshop:3000, then report.", "http", "juiceshop", 3000}, + {"Assess http://juiceshop:3000.", "http", "juiceshop", 3000}, + {"Scope: http://juiceshop:3000; nothing else", "http", "juiceshop", 3000}, + {"The lab (http://juiceshop:3000) is ours", "http", "juiceshop", 3000}, + {"Test https://app.example.com:8080, only the API", "https", "app.example.com", 8080}, + {"Target is https://example.com.", "https", "example.com", 443}, + {"Start at https://example.com/login?next=/a, then pivot", "https", "example.com", 443}, + {"http://juiceshop:3000", "http", "juiceshop", 3000}, + {"Assess http://juiceshop.", "http", "juiceshop", 80}, + {"Assess http://10.0.0.5.", "http", "10.0.0.5", 80}, + {"Assess http://juiceshop:3000。", "http", "juiceshop", 3000}, + {"Assess “http://juiceshop:3000”", "http", "juiceshop", 3000}, + {"See https://en.wikipedia.org/wiki/Foo_(bar).", "https", "en.wikipedia.org", 443}, + {"(https://en.wikipedia.org/wiki/Foo_(bar))", "https", "en.wikipedia.org", 443}, + {"http://[::1]", "http", "::1", 80}, + {"http://[::1]:8080", "http", "::1", 8080}, + {"Assess http://[fd00::10].", "http", "fd00::10", 80}, + {"[http://[::1]:8080]", "http", "::1", 8080}, + } + for _, c := range cases { + scheme, host, port, ok := parseTarget(c.text) + if !ok || scheme != c.scheme || host != c.host || port != c.port { + t.Errorf("parseTarget(%q) = %q, %q, %d, %v; want %q, %q, %d, true", + c.text, scheme, host, port, ok, c.scheme, c.host, c.port) + } + } +} diff --git a/server/scheduler.go b/server/scheduler.go index 0ad124f..cd07c67 100644 --- a/server/scheduler.go +++ b/server/scheduler.go @@ -28,7 +28,7 @@ type Scheduler struct { const ( schedKeyLastFinding = "last_finding_id" // watermark: max finding node id fired for schedKeyFiredGoals = "fired_goals" // JSON array of goal node ids already fired - schedKeyLastTimeout = "last_timeout_id" // watermark: max task id fired for task timeout + schedKeyFiredTimeouts = "fired_timeouts" // JSON array of task ids already fired for task timeout schedKeyLastToolCall = "last_toolcall_id" // watermark: max activity id fired for tool call schedKeyLastTaskCreate = "last_taskcreate_id" // watermark: max task id fired for task create ) @@ -77,18 +77,16 @@ func (sc *Scheduler) init() { set[e.NodeID] = true } } - sc.saveFiredGoalSet(set) + sc.saveFiredSet(schedKeyFiredGoals, set) } - if sc.mustState(schedKeyLastTimeout) == "" { - var maxID int64 - if evs, err := sc.pg.TimedOutTasksSince(0); err == nil { + if sc.mustState(schedKeyFiredTimeouts) == "" { + set := map[int64]bool{} + if evs, err := sc.pg.TimedOutTasks(); err == nil { for _, e := range evs { - if e.NodeID > maxID { - maxID = e.NodeID - } + set[e.NodeID] = true } } - _ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10)) + sc.saveFiredSet(schedKeyFiredTimeouts, set) } if sc.mustState(schedKeyLastToolCall) == "" { var maxID int64 @@ -195,7 +193,7 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) { } // Mark goals as consumed whether or not a trigger is active, so enabling an // on_goal_met trigger later doesn't replay every already-met goal. - fired := sc.firedGoalSet() + fired := sc.firedSet(schedKeyFiredGoals) changed := false for _, e := range events { if fired[e.NodeID] { @@ -212,12 +210,14 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) { } } if changed { - sc.saveFiredGoalSet(fired) + sc.saveFiredSet(schedKeyFiredGoals, fired) } } // fireTaskTimeouts fires on_task_timeout triggers for tasks that newly reached -// status='timeout' above the persisted watermark (task id → no double-fire). +// status='timeout'. Tasks time out in deadline order, not id order, so fired +// tasks are kept in a persisted set (like goals) rather than an id watermark: +// a watermark would skip an older task that times out after a newer one. func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) { var want []*db.AgentTrigger for _, tr := range triggers { @@ -225,17 +225,8 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) { want = append(want, tr) } } - last, _ := strconv.ParseInt(sc.mustState(schedKeyLastTimeout), 10, 64) - events, err := sc.pg.TimedOutTasksSince(last) - if err != nil || len(events) == 0 { - return - } - // Advance the watermark even with no active trigger — see fireFindings. - maxID := last - for _, e := range events { - if e.NodeID > maxID { - maxID = e.NodeID - } + // Consume the timeouts even with no active trigger — see fireFindings. + for _, e := range sc.newTaskTimeouts() { if len(want) == 0 { continue } @@ -244,7 +235,28 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) { sc.s.StartTriggeredRun(tr.AgentKey, fmt.Sprintf("Timeout trigger · task#%d", e.TaskID), tr.TaskTimeoutMessage+msgCtx, e.TaskID, true, e.TaskDesc, e.TaskGoal) } } - _ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10)) +} + +// newTaskTimeouts returns the timed-out tasks not fired for yet and records +// them as consumed. +func (sc *Scheduler) newTaskTimeouts() []db.TaskEvent { + events, err := sc.pg.TimedOutTasks() + if err != nil || len(events) == 0 { + return nil + } + fired := sc.firedSet(schedKeyFiredTimeouts) + var out []db.TaskEvent + for _, e := range events { + if fired[e.NodeID] { + continue + } + fired[e.NodeID] = true + out = append(out, e) + } + if len(out) > 0 { + sc.saveFiredSet(schedKeyFiredTimeouts, fired) + } + return out } // fireTaskCreates fires on_task_create triggers for tasks newly created above the @@ -347,9 +359,9 @@ func (sc *Scheduler) mustState(key string) string { return v } -func (sc *Scheduler) firedGoalSet() map[int64]bool { +func (sc *Scheduler) firedSet(key string) map[int64]bool { out := map[int64]bool{} - raw := sc.mustState(schedKeyFiredGoals) + raw := sc.mustState(key) if raw == "" { return out } @@ -362,13 +374,13 @@ func (sc *Scheduler) firedGoalSet() map[int64]bool { return out } -func (sc *Scheduler) saveFiredGoalSet(set map[int64]bool) { +func (sc *Scheduler) saveFiredSet(key string, set map[int64]bool) { ids := make([]int64, 0, len(set)) for id := range set { ids = append(ids, id) } b, _ := json.Marshal(ids) - if err := sc.pg.SetSchedState(schedKeyFiredGoals, string(b)); err != nil { - log.Printf("[scheduler] save fired goals failed: %v", err) + if err := sc.pg.SetSchedState(key, string(b)); err != nil { + log.Printf("[scheduler] save %s failed: %v", key, err) } } diff --git a/server/scheduler_timeout_test.go b/server/scheduler_timeout_test.go new file mode 100644 index 0000000..434ae47 --- /dev/null +++ b/server/scheduler_timeout_test.go @@ -0,0 +1,58 @@ +package server + +import ( + "testing" + + "github.com/Autumn-27/artex/db" +) + +// Tasks time out in deadline order, not in id order: a task created later with +// a shorter timeout can time out first. Each timeout must still fire once. +func TestSchedulerTaskTimeoutsFireOutOfIDOrder(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + sc := &Scheduler{pg: m.pg} + sc.newTaskTimeouts() // consume timeouts other tests left behind + + var ids [2]int64 + for i := range ids { + task, err := m.pg.CreateTaskWithOptions("timeout order", "goal", db.TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + ids[i] = task.ID + t.Cleanup(func() { _ = m.pg.DeleteTask(task.ID) }) + } + older, newer := ids[0], ids[1] + timeOut := func(id int64) { + t.Helper() + if _, err := m.pg.Exec(`UPDATE tasks SET status='timeout' WHERE id=$1`, id); err != nil { + t.Fatal(err) + } + } + fired := func() []int64 { + var out []int64 + for _, e := range sc.newTaskTimeouts() { + if e.TaskID == older || e.TaskID == newer { + out = append(out, e.TaskID) + } + } + return out + } + + timeOut(newer) + if got := fired(); len(got) != 1 || got[0] != newer { + t.Fatalf("after the newer task timed out: fired %v, want [%d]", got, newer) + } + timeOut(older) + if got := fired(); len(got) != 1 || got[0] != older { + t.Fatalf("after the older task timed out: fired %v, want [%d]", got, older) + } + if got := fired(); len(got) != 0 { + t.Fatalf("second scan fired %v again, want nothing", got) + } +} diff --git a/server/server.go b/server/server.go index ae98539..d2d85f5 100644 --- a/server/server.go +++ b/server/server.go @@ -23,6 +23,7 @@ import ( "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/archivestore" @@ -1945,11 +1946,33 @@ var ( reDomain = regexp.MustCompile(`\b((?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})(?::(\d{1,5}))?`) ) +// trimURLTail drops sentence punctuation that free text puts after a URL +// ("Assess http://host:3000."). A closing bracket is dropped only when it has no +// opener in the URL, so "http://[::1]" keeps its "]". +func trimURLTail(s string) string { + for s != "" { + r, size := utf8.DecodeLastRuneInString(s) + switch r { + case '.', ',', ';', ':', '!', '?', '。', ',', '、', ';', ':', '!', '?', '”', '’': + case ')', ']', '}', '>': + open := string("([{<"[strings.IndexRune(")]}>", r)]) + if strings.Count(s, open) >= strings.Count(s, string(r)) { + return s + } + default: + return s + } + s = s[:len(s)-size] + } + return s +} + // parseTarget extracts a target (scheme, host, port) from free text, supporting // full URLs, IP[:port] and domain[:port]. ok=false when nothing parseable. func parseTarget(text string) (scheme, host string, port int, ok bool) { text = strings.TrimSpace(text) if m := reURL.FindString(text); m != "" { + m = trimURLTail(m) if u, err := url.Parse(m); err == nil && u.Hostname() != "" { scheme = strings.ToLower(u.Scheme) host = strings.ToLower(u.Hostname()) diff --git a/server/task_archive_package.go b/server/task_archive_package.go index 496a740..a19b2e6 100644 --- a/server/task_archive_package.go +++ b/server/task_archive_package.go @@ -639,6 +639,12 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive log.Printf("[task-archive] skipping symlink (unsupported by the archive, other files unaffected): %s", current) return nil } + if !entry.IsDir() && !info.Mode().IsRegular() { + // A named pipe, socket or device left by a command: opening a pipe blocks until + // a writer appears, tar refuses a socket, and the unpacker refuses the rest. + log.Printf("[task-archive] skipping a file that is not regular (unsupported by the archive): %s", current) + return nil + } header, err := tar.FileInfoHeader(info, "") if err != nil { return err diff --git a/server/task_archive_special_unix_test.go b/server/task_archive_special_unix_test.go new file mode 100644 index 0000000..79b0426 --- /dev/null +++ b/server/task_archive_special_unix_test.go @@ -0,0 +1,70 @@ +//go:build unix + +package server + +import ( + "net" + "os" + "path/filepath" + "syscall" + "testing" + + pgdb "github.com/Autumn-27/artex/db" +) + +// A named pipe or a socket left in the task workspace by a command must not +// make the archive unrestorable, nor stop the task from being archived. +func TestTaskArchiveSkipsSpecialFiles(t *testing.T) { + // A short root: a socket path is limited to about 100 bytes. + dataDir, err := os.MkdirTemp("/tmp", "arch") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dataDir) }) + taskID := "42" + runDir := filepath.Join(dataDir, "tasks", taskID, "main") + if err := os.MkdirAll(runDir, 0o755); err != nil { + t.Fatal(err) + } + evidence := filepath.Join(runDir, "evidence.txt") + if err := os.WriteFile(evidence, []byte("task evidence"), 0o600); err != nil { + t.Fatal(err) + } + if err := syscall.Mkfifo(filepath.Join(runDir, "backpipe"), 0o600); err != nil { + t.Skipf("mkfifo: %v", err) + } + ln, err := net.Listen("unix", filepath.Join(runDir, "ctl.sock")) + if err != nil { + t.Skipf("unix socket: %v", err) + } + ln.(*net.UnixListener).SetUnlinkOnClose(false) + ln.Close() + + stage, err := stageTaskArchiveFiles(dataDir, 1, taskID, 7) + if err != nil { + t.Fatal(err) + } + archivePath := taskArchivePath(dataDir, 1, taskID) + snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42, ExplorationID: 7} + _, _, checksum, err := writeTaskArchivePackage(archivePath, stage.payload, snapshot) + if err != nil { + t.Fatalf("the task could not be archived: %v", err) + } + if err := stage.commit(); err != nil { + t.Fatal(err) + } + extracted := filepath.Join(dataDir, "restore") + if err := extractTaskArchivePackage(archivePath, checksum, extracted); err != nil { + t.Fatalf("the archive of the task cannot be restored: %v", err) + } + installed, err := installTaskArchiveFiles(dataDir, extracted, taskID, 1, ExecPrivilege{}) + if err != nil { + t.Fatal(err) + } + if err := installed.commit(); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(evidence); err != nil || string(got) != "task evidence" { + t.Fatalf("restored %s = %q, %v", evidence, got, err) + } +}