mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-02 20:53:56 +08:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e38f58d46e | ||
|
|
e14570a7ff | ||
|
|
f94294867f | ||
|
|
f856460889 | ||
|
|
8f91643b78 | ||
|
|
44f6f035ac | ||
|
|
33c24bbc63 | ||
|
|
52131ab78d | ||
|
|
b1a48c8ef8 | ||
|
|
8c9619672a | ||
|
|
2fb715043b | ||
|
|
8024a30c84 | ||
|
|
3489f7443c | ||
|
|
d05740cad7 | ||
|
|
7419ae5f77 | ||
|
|
2615f05fc9 | ||
|
|
175b423536 | ||
|
|
4aaf5b3375 | ||
|
|
0769120e1b | ||
|
|
442c48fddd | ||
|
|
5654a9d78f | ||
|
|
1b1eb1aa42 |
@@ -206,7 +206,7 @@ jobs:
|
||||
working-directory: web
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
@@ -239,7 +239,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: python3 scripts/posture_check_test.py
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
@@ -172,12 +172,12 @@ jobs:
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name == 'push'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
id: meta
|
||||
with:
|
||||
images: ghcr.io/baarai/artex-${{ matrix.name }}
|
||||
@@ -185,7 +185,7 @@ jobs:
|
||||
type=ref,event=tag
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
file: ${{ matrix.dockerfile }}
|
||||
@@ -229,18 +229,18 @@ jobs:
|
||||
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name == 'push'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Log in to Docker Hub
|
||||
if: github.event_name == 'push' && vars.DOCKERHUB_ENABLED == 'true'
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
- uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
id: meta
|
||||
with:
|
||||
images: |
|
||||
@@ -250,7 +250,7 @@ jobs:
|
||||
type=ref,event=tag
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=latest
|
||||
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
- uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
@@ -7,9 +7,15 @@ All notable changes to this project are documented in this file. The format is b
|
||||
### Security
|
||||
|
||||
- **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only.
|
||||
- **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out.
|
||||
|
||||
### Added
|
||||
|
||||
- **`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.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
|
||||
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
|
||||
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
|
||||
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
|
||||
|
||||
@@ -879,6 +879,11 @@ For a recurring problem, share the ARTEX version or commit, the model and versio
|
||||
excerpt of the affected input and result. Remove credentials, target data, and other sensitive
|
||||
content before sharing.
|
||||
|
||||
### Reviewing a published vulnerability advisory
|
||||
|
||||
See [Reviewing a published vulnerability advisory](docs/operator-advisory-review.md) for the
|
||||
CVE and GHSA review workflow.
|
||||
|
||||
### Backups
|
||||
|
||||
`scripts/backup.sh` dumps the Postgres database (and optionally the data directory) with
|
||||
|
||||
@@ -9,7 +9,7 @@ import "time"
|
||||
type AssetInterceptRule struct {
|
||||
ID int64 `json:"id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
|
||||
Kind string `json:"kind"` // exact_domain|exact_ip|exact_url|domain_suffix|fuzzy_domain|fuzzy_ip|fuzzy_url|cidr
|
||||
Pattern string `json:"pattern"`
|
||||
Note string `json:"note"`
|
||||
Builtin bool `json:"builtin"`
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A database created before domain_suffix has the seven-kind CHECK constraints.
|
||||
// Migration 0026 widens them, idempotently, on both rule tables; an unknown
|
||||
// kind is still refused.
|
||||
func TestDomainSuffixKindMigration0026(t *testing.T) {
|
||||
d := openTargetDB(t)
|
||||
const oldKinds = `('exact_domain','exact_ip','exact_url','fuzzy_domain','fuzzy_ip','fuzzy_url','cidr')`
|
||||
if _, err := d.Exec(`
|
||||
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
|
||||
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);
|
||||
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
|
||||
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check CHECK (kind IN ` + oldKinds + `);`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := fs.ReadFile(migrationsFS(), "0026_asset_intercept_domain_suffix.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Whatever happens below, leave the current constraints in place.
|
||||
t.Cleanup(func() { _, _ = d.Exec(string(migration)) })
|
||||
|
||||
// Disabled, so the global rule cannot affect another test sharing the database.
|
||||
global := func(kind string) error {
|
||||
r, err := d.CreateAssetInterceptRule(kind, "example.com", "domain_suffix migration test", false)
|
||||
if err == nil {
|
||||
t.Cleanup(func() { _ = d.DeleteAssetInterceptRule(r.ID) })
|
||||
}
|
||||
return err
|
||||
}
|
||||
task, err := d.CreateTaskWithOptions("domain_suffix migration test", "goal", TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM tasks WHERE id=$1`, task.ID) })
|
||||
perTask := func(kind string) error {
|
||||
_, err := d.Assets().CreateTaskInterceptRule(task.ID, "allow", kind, "example.com", "", true)
|
||||
return err
|
||||
}
|
||||
|
||||
if global("domain_suffix") == nil || perTask("domain_suffix") == nil {
|
||||
t.Fatal("the old constraints accepted a domain_suffix rule")
|
||||
}
|
||||
for range 2 { // idempotent
|
||||
if _, err := d.Exec(string(migration)); err != nil {
|
||||
t.Fatalf("apply migration: %v", err)
|
||||
}
|
||||
}
|
||||
if err := global("domain_suffix"); err != nil {
|
||||
t.Fatalf("global domain_suffix rule refused after the migration: %v", err)
|
||||
}
|
||||
if err := perTask("domain_suffix"); err != nil {
|
||||
t.Fatalf("task domain_suffix rule refused after the migration: %v", err)
|
||||
}
|
||||
_, allow, err := d.Assets().TaskInterceptRulesSplit(task.ID)
|
||||
if err != nil || len(allow) != 1 || allow[0].Kind != "domain_suffix" {
|
||||
t.Fatalf("task allow rules = %+v, %v; want the domain_suffix rule", allow, err)
|
||||
}
|
||||
if global("domain_glob") == nil || perTask("domain_glob") == nil {
|
||||
t.Fatal("an unknown kind was accepted")
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,19 @@ func CanonicalInterceptDomain(s string) string {
|
||||
return d
|
||||
}
|
||||
|
||||
// DomainSuffixPattern canonicalizes a domain_suffix pattern: the domain itself,
|
||||
// with one leading "*." or "." dropped, so "*.Example.com" and ".example.com"
|
||||
// both mean example.com and its subdomains. Empty when nothing is left.
|
||||
func DomainSuffixPattern(s string) string {
|
||||
d := strings.TrimSpace(s)
|
||||
if rest, ok := strings.CutPrefix(d, "*."); ok {
|
||||
d = rest
|
||||
} else {
|
||||
d = strings.TrimPrefix(d, ".")
|
||||
}
|
||||
return CanonicalInterceptDomain(d)
|
||||
}
|
||||
|
||||
// CanonicalInterceptIP canonicalizes one side of an IP comparison: IPv4-mapped
|
||||
// IPv6 addresses are unmapped and any zone is dropped, so "0:0:0:0:0:0:0:1"
|
||||
// and "::1" compare equal. ok is false when s is not an IP literal.
|
||||
@@ -52,6 +65,8 @@ func AssetInterceptKindLabel(kind string) string {
|
||||
return "IP (exact)"
|
||||
case "exact_url":
|
||||
return "URL (exact)"
|
||||
case "domain_suffix":
|
||||
return "Domain (suffix)"
|
||||
case "fuzzy_domain":
|
||||
return "Domain (fuzzy)"
|
||||
case "fuzzy_ip":
|
||||
@@ -119,6 +134,19 @@ func matchOne(r AssetInterceptRule, domains, ips, urls []string) (string, bool)
|
||||
return u, true
|
||||
}
|
||||
}
|
||||
case "domain_suffix":
|
||||
// The domain and its subdomains, on a label boundary: "example.com"
|
||||
// matches "a.example.com" but not "a.example.com.evil.net" or
|
||||
// "badexample.com", which fuzzy_domain's substring match lets through.
|
||||
want := DomainSuffixPattern(p)
|
||||
if want == "" {
|
||||
return "", false
|
||||
}
|
||||
for _, d := range domains {
|
||||
if cd := CanonicalInterceptDomain(d); cd == want || strings.HasSuffix(cd, "."+want) {
|
||||
return d, true
|
||||
}
|
||||
}
|
||||
case "fuzzy_domain":
|
||||
lp := CanonicalInterceptDomain(p)
|
||||
if lp == "" {
|
||||
|
||||
@@ -44,6 +44,29 @@ func TestMatchAssetInterceptRules(t *testing.T) {
|
||||
[]string{"xn--bcher-kva.example"}, nil, nil, true, "xn--bcher-kva.example"},
|
||||
{"fuzzy domain uppercase trailing-dot rule", []AssetInterceptRule{rule("fuzzy_domain", "EXAMPLE.COM.", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix hits the domain itself", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"EXAMPLE.com."}, nil, nil, true, "EXAMPLE.com."},
|
||||
{"domain suffix hits a subdomain", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.b.example.com"}, nil, nil, true, "a.b.example.com"},
|
||||
{"domain suffix wildcard spelling", []AssetInterceptRule{rule("domain_suffix", "*.Example.COM.", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix leading-dot spelling", []AssetInterceptRule{rule("domain_suffix", ".example.com", true)},
|
||||
[]string{"api.example.com"}, nil, nil, true, "api.example.com"},
|
||||
{"domain suffix IDNA rule", []AssetInterceptRule{rule("domain_suffix", "bücher.example", true)},
|
||||
[]string{"shop.xn--bcher-kva.example"}, nil, nil, true, "shop.xn--bcher-kva.example"},
|
||||
// Where fuzzy_domain's substring match hits, a label-boundary suffix must not.
|
||||
{"domain suffix misses a name that only contains it", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.example.com.evil.net"}, nil, nil, false, ""},
|
||||
{"domain suffix misses a longer last label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"a.example.community"}, nil, nil, false, ""},
|
||||
{"domain suffix misses a longer first label", []AssetInterceptRule{rule("domain_suffix", "example.com", true)},
|
||||
[]string{"badexample.com"}, nil, nil, false, ""},
|
||||
{"domain suffix misses the parent domain", []AssetInterceptRule{rule("domain_suffix", "api.example.com", true)},
|
||||
[]string{"example.com"}, nil, nil, false, ""},
|
||||
{"fuzzy domain hits a name that only contains it", []AssetInterceptRule{rule("fuzzy_domain", ".example.com", true)},
|
||||
[]string{"a.example.com.evil.net"}, nil, nil, true, "a.example.com.evil.net"},
|
||||
{"empty domain suffix no hit", []AssetInterceptRule{rule("domain_suffix", "*.", true)},
|
||||
[]string{"example.com"}, nil, nil, false, ""},
|
||||
{"fuzzy IP uppercase rule", []AssetInterceptRule{rule("fuzzy_ip", "FE80::", true)},
|
||||
nil, []string{"fe80::1"}, nil, true, "fe80::1"},
|
||||
{"fuzzy IP prefix hit", []AssetInterceptRule{rule("fuzzy_ip", "203.0.113.", true)},
|
||||
@@ -117,6 +140,20 @@ func TestEvaluateAssetGate(t *testing.T) {
|
||||
); d.Allowed {
|
||||
t.Fatal("interception should take priority over allow")
|
||||
}
|
||||
|
||||
// 7. A domain_suffix allow-list admits the site and refuses look-alikes
|
||||
// that fuzzy_domain would admit.
|
||||
suffix := []AssetInterceptRule{rule("domain_suffix", "example.com", true)}
|
||||
for host, want := range map[string]bool{
|
||||
"example.com": true,
|
||||
"api.example.com": true,
|
||||
"api.example.com.evil.net": false,
|
||||
"api.example.community": false,
|
||||
} {
|
||||
if d := EvaluateAssetGate(nil, suffix, []string{host}, nil, nil); d.Allowed != want {
|
||||
t.Fatalf("domain_suffix allow-list: %s allowed=%v, want %v", host, d.Allowed, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssetInterceptCandidates(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- domain_suffix: a domain and its subdomains, matched on a label boundary
|
||||
-- (example.com, a.example.com; not a.example.com.other.net). Existing rules
|
||||
-- keep their kind; the CHECK constraints only gain the new value.
|
||||
ALTER TABLE asset_intercept_rules DROP CONSTRAINT IF EXISTS asset_intercept_rules_kind_check;
|
||||
ALTER TABLE asset_intercept_rules ADD CONSTRAINT asset_intercept_rules_kind_check
|
||||
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
|
||||
ALTER TABLE task_intercept_rules DROP CONSTRAINT IF EXISTS task_intercept_rules_kind_check;
|
||||
ALTER TABLE task_intercept_rules ADD CONSTRAINT task_intercept_rules_kind_check
|
||||
CHECK (kind IN ('exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url', 'cidr'));
|
||||
+4
-3
@@ -1374,8 +1374,9 @@ ALTER TABLE side_question_requests ADD COLUMN IF NOT EXISTS context_info JSONB N
|
||||
-- Independent from §K command interception (intercept_rules): intercept_rules matches tool names/input text,
|
||||
-- while this table matches "target assets" — exact/fuzzy domains, IPs, URLs, and CIDR ranges.
|
||||
-- Rules only; the concrete match/intercept logic is implemented elsewhere.
|
||||
-- Seven kinds:
|
||||
-- Eight kinds:
|
||||
-- exact_domain / exact_ip / exact_url —— exact match
|
||||
-- domain_suffix —— a domain and its subdomains (label boundary)
|
||||
-- fuzzy_domain / fuzzy_ip / fuzzy_url —— fuzzy match
|
||||
-- cidr —— CIDR range
|
||||
-- =====================================================================
|
||||
@@ -1383,7 +1384,7 @@ CREATE TABLE IF NOT EXISTS asset_intercept_rules (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
kind TEXT NOT NULL CHECK (kind IN (
|
||||
'exact_domain', 'exact_ip', 'exact_url',
|
||||
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
|
||||
'cidr')),
|
||||
pattern TEXT NOT NULL,
|
||||
@@ -1412,7 +1413,7 @@ CREATE TABLE IF NOT EXISTS task_intercept_rules (
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
action TEXT NOT NULL DEFAULT 'block' CHECK (action IN ('block','allow')),
|
||||
kind TEXT NOT NULL CHECK (kind IN (
|
||||
'exact_domain', 'exact_ip', 'exact_url',
|
||||
'exact_domain', 'exact_ip', 'exact_url', 'domain_suffix',
|
||||
'fuzzy_domain', 'fuzzy_ip', 'fuzzy_url',
|
||||
'cidr')),
|
||||
pattern TEXT NOT NULL,
|
||||
|
||||
@@ -70,6 +70,28 @@ ARTEX_SANDBOX=off
|
||||
|
||||
## Security Hardening Notes
|
||||
|
||||
### Worker cleanup after execution errors
|
||||
|
||||
Command timeout, cancellation or a broken execution stream removes the worker
|
||||
container that ran the command. The runner also removes it when Docker cannot
|
||||
confirm that the exec has finished. This terminates detached children and **all
|
||||
other concurrent commands and background services in that task**. The next exec
|
||||
recreates the worker; the task's `/workspace` directory survives. Successful
|
||||
commands keep their worker and may leave intentional background services running.
|
||||
|
||||
Cleanup uses the captured container ID, so a delayed completion cannot remove a
|
||||
replacement worker or another task's worker. Failed removal returns an error and
|
||||
keeps the worker tracked for retry. Deleting a task removes its worker before its
|
||||
proxy and network, including when no application processes remain in the worker.
|
||||
|
||||
Run the unit and simulated Engine tests with `go test -race ./sandbox`. On a
|
||||
dedicated Docker host with the sandbox images built, enable the detached-child
|
||||
cleanup test with:
|
||||
|
||||
```bash
|
||||
ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox -run TestDockerTimeoutRemovesDetachedChild -v
|
||||
```
|
||||
|
||||
- **Tamper-proof egress audit log**: `artex-egress-<id>` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit/<id>/egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/<id>:/workspace:rw` and cannot read, truncate, or forge the egress audit log.
|
||||
- **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-<id>` runs `/usr/local/bin/artex-exec-wrap --init` as PID 1 (reaping all orphaned children). On `POST /v1/tasks/{id}/kill`, `artex-runner` executes `/usr/local/bin/artex-exec-wrap --kill-uid 10001` as uid `10001` (preserving `--cap-drop ALL`) scanning `/proc` directly (defeating `setsid`, `nohup`, nested double-forked daemons, `trap '' TERM`, and `/tmp` tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls back to force-removing the worker container if any check fails.
|
||||
- **Browser & `WebFetch` containment**: In `ARTEX_SANDBOX=required` mode, local stdio MCP servers (including the default private browser MCP) are skipped on the panel; `WebFetch` enforces the task's `sandbox.EgressPolicy` on every URL, redirect hop, and pinned dial (with direct retry disabled); and the opt-in panel-hosted shared browser MCP is only attached when `target_gate` is enabled or an explicit egress proxy is configured, with every browser navigation URL gated against the task's `sandbox.EgressPolicy` (execution containment + scope-gated panel fetch/browser; full subresource browser network isolation requires running the shared browser behind `egress-guard` in `EGRESS_MODE=enforce`).
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Reviewing a published vulnerability advisory
|
||||
|
||||
When a finding cites a CVE or GHSA identifier, look up that exact identifier in the
|
||||
[NVD vulnerability search](https://nvd.nist.gov/vuln/search) or the
|
||||
[GitHub Advisory Database](https://github.com/advisories). Check the issuer's advisory for the
|
||||
affected product, version range and fixed versions. An identifier alone cannot confirm that an
|
||||
installed version is affected.
|
||||
|
||||
Record the identifier, source URL, advisory's last-updated date when available, and the installed
|
||||
version in your review notes. If the advisory and the observed version disagree, document the
|
||||
difference and defer the applicability decision until you can confirm it. Search using public identifiers
|
||||
and keep private hostnames, logs and credentials in your ARTEX instance.
|
||||
+82
-34
@@ -40,8 +40,8 @@ type taskContainers struct {
|
||||
proxyID string
|
||||
netName string
|
||||
scopeHash string
|
||||
// cleanupMu serializes Kill and Delete for this task. A pause racing a
|
||||
// delete must not interleave two cleanup sequences over the same IDs.
|
||||
// cleanupMu serializes creation, recovery on exec, and cleanup for this task.
|
||||
// Commands may execute concurrently, but lifecycle changes share this lock.
|
||||
cleanupMu sync.Mutex
|
||||
}
|
||||
|
||||
@@ -441,14 +441,28 @@ func scopeFingerprint(domains, cidrs []string) string {
|
||||
func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*taskContainers, error) {
|
||||
b.mu.Lock()
|
||||
tc := b.tasks[taskID]
|
||||
if tc == nil {
|
||||
tc = &taskContainers{taskID: taskID, netName: b.cfg.TaskNetPrefix + taskID}
|
||||
b.tasks[taskID] = tc
|
||||
}
|
||||
b.mu.Unlock()
|
||||
tc.cleanupMu.Lock()
|
||||
defer tc.cleanupMu.Unlock()
|
||||
// Delete may have completed while this request waited for the lifecycle lock.
|
||||
b.mu.Lock()
|
||||
current := b.tasks[taskID] == tc
|
||||
b.mu.Unlock()
|
||||
if !current {
|
||||
return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID)
|
||||
}
|
||||
|
||||
netName := b.cfg.TaskNetPrefix + taskID
|
||||
tc.netName = netName
|
||||
proxyName := "artex-egress-" + taskID
|
||||
workerName := "artex-worker-" + taskID
|
||||
sh := scopeFingerprint(scopeDomains, scopeCIDRs)
|
||||
|
||||
if tc != nil && tc.scopeHash == sh {
|
||||
if tc.scopeHash == sh {
|
||||
proxyOK := tc.proxyID != "" && b.startContainer(ctx, tc.proxyID) == nil
|
||||
if !proxyOK && tc.proxyID != "" {
|
||||
b.removeContainer(ctx, tc.proxyID)
|
||||
@@ -488,7 +502,7 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
|
||||
}
|
||||
|
||||
// Recreate proxy if missing or scope changed.
|
||||
if tc == nil || tc.proxyID == "" || tc.scopeHash != sh {
|
||||
if tc.proxyID == "" || tc.scopeHash != sh {
|
||||
b.removeContainer(ctx, proxyName)
|
||||
proxySpec := map[string]any{
|
||||
"Image": b.cfg.ProxyImage,
|
||||
@@ -529,9 +543,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
|
||||
b.removeContainer(ctx, pid)
|
||||
return nil, err
|
||||
}
|
||||
if tc == nil {
|
||||
tc = &taskContainers{taskID: taskID, netName: netName}
|
||||
}
|
||||
tc.proxyID = pid
|
||||
tc.scopeHash = sh
|
||||
}
|
||||
@@ -591,9 +602,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma
|
||||
tc.workerID = wid
|
||||
}
|
||||
|
||||
b.mu.Lock()
|
||||
b.tasks[taskID] = tc
|
||||
b.mu.Unlock()
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
@@ -605,6 +613,12 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
|
||||
if err != nil {
|
||||
return ExecResponse{}, err
|
||||
}
|
||||
tc.cleanupMu.Lock()
|
||||
workerID := tc.workerID
|
||||
tc.cleanupMu.Unlock()
|
||||
if workerID == "" {
|
||||
return ExecResponse{}, fmt.Errorf("%w: task %s worker was removed", ErrNotFound, taskID)
|
||||
}
|
||||
|
||||
// Wrap argv with artex-exec-wrap so every exec gets its own process group,
|
||||
// enforces timeout_ms (SIGTERM group -> 5s -> SIGKILL -> exit 124) without
|
||||
@@ -623,7 +637,7 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
|
||||
}
|
||||
sort.Strings(envList)
|
||||
|
||||
createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(tc.workerID)+"/exec", map[string]any{
|
||||
createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{
|
||||
"AttachStdout": true,
|
||||
"AttachStderr": true,
|
||||
"Tty": false,
|
||||
@@ -656,28 +670,44 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
|
||||
"Tty": false,
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
_ = b.Kill(context.Background(), taskID)
|
||||
}
|
||||
return ExecResponse{}, err
|
||||
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
|
||||
}
|
||||
defer startResp.Body.Close()
|
||||
|
||||
stdout, stderr, truncated, _ := demuxDockerStream(startResp.Body, MaxOutputBytes)
|
||||
|
||||
inspectResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
|
||||
exitCode := -1
|
||||
if err == nil {
|
||||
defer inspectResp.Body.Close()
|
||||
var ins struct {
|
||||
ExitCode int `json:"ExitCode"`
|
||||
}
|
||||
if json.NewDecoder(inspectResp.Body).Decode(&ins) == nil {
|
||||
exitCode = ins.ExitCode
|
||||
}
|
||||
if startResp.StatusCode >= 300 {
|
||||
return ExecResponse{}, errors.Join(fmt.Errorf("start exec: HTTP %d", startResp.StatusCode), b.removeExecWorker(ctx, tc, workerID))
|
||||
}
|
||||
|
||||
stdout, stderr, truncated, streamErr := demuxDockerStream(startResp.Body, MaxOutputBytes)
|
||||
if err := errors.Join(streamErr, execCtx.Err()); err != nil {
|
||||
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
|
||||
}
|
||||
|
||||
ic, cancelInspect := cleanupContext(ctx)
|
||||
defer cancelInspect()
|
||||
inspectResp, err := b.dockerDo(ic, http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
|
||||
if err != nil {
|
||||
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
|
||||
}
|
||||
defer inspectResp.Body.Close()
|
||||
var ins struct {
|
||||
ExitCode *int `json:"ExitCode"`
|
||||
Running *bool `json:"Running"`
|
||||
}
|
||||
decodeErr := json.NewDecoder(inspectResp.Body).Decode(&ins)
|
||||
completed := ins.ExitCode != nil && ins.Running != nil && !*ins.Running
|
||||
if decodeErr != nil || inspectResp.StatusCode != http.StatusOK || !completed {
|
||||
return ExecResponse{}, errors.Join(fmt.Errorf("cannot prove exec completed (HTTP %d): %v", inspectResp.StatusCode, decodeErr), b.removeExecWorker(ctx, tc, workerID))
|
||||
}
|
||||
|
||||
exitCode := *ins.ExitCode
|
||||
timedOut := exitCode == 124
|
||||
if timedOut || ctx.Err() != nil {
|
||||
// Process-group timeout cannot kill setsid/double-fork descendants.
|
||||
// Destroy the captured container, including its PID namespace and cgroup.
|
||||
if err := b.removeExecWorker(ctx, tc, workerID); err != nil {
|
||||
return ExecResponse{}, err
|
||||
}
|
||||
}
|
||||
return ExecResponse{
|
||||
ExitCode: exitCode,
|
||||
Stdout: stdout,
|
||||
@@ -688,6 +718,21 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest
|
||||
}, nil
|
||||
}
|
||||
|
||||
// removeExecWorker removes the exact container that ran this exec. A timeout
|
||||
// also terminates sibling execs in that task, while preserving /workspace.
|
||||
// Never remove a replacement worker, or forget a failed cleanup.
|
||||
func (b *DockerBackend) removeExecWorker(ctx context.Context, tc *taskContainers, workerID string) error {
|
||||
tc.cleanupMu.Lock()
|
||||
defer tc.cleanupMu.Unlock()
|
||||
cctx, cancel := cleanupContext(ctx)
|
||||
defer cancel()
|
||||
if err := b.removeContainer(cctx, workerID); err != nil {
|
||||
return fmt.Errorf("exec cleanup for task %s: %w", tc.taskID, err)
|
||||
}
|
||||
b.clearWorkerID(tc, workerID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Kill terminates EVERY uid-10001 process inside the task's worker container
|
||||
// (excluding PID 1) by running a root exec scanning /proc directly — never
|
||||
// trusting any agent-writable state. If root exec fails or reports surviving
|
||||
@@ -751,7 +796,6 @@ func (b *DockerBackend) clearWorkerID(tc *taskContainers, workerID string) {
|
||||
cur.workerID = ""
|
||||
}
|
||||
b.mu.Unlock()
|
||||
tc.workerID = ""
|
||||
}
|
||||
|
||||
func (b *DockerBackend) killWorkerByProcScan(ctx context.Context, workerID string) error {
|
||||
@@ -827,9 +871,13 @@ func (b *DockerBackend) Delete(ctx context.Context, taskID string) error {
|
||||
cctx, cancel := cleanupContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := b.killCaptured(cctx, tc); err != nil {
|
||||
return fmt.Errorf("delete task %s: %w", taskID, err)
|
||||
// Removing the worker also stops its processes and detaches the network
|
||||
// endpoint. A process scan alone leaves PID 1 and the endpoint alive.
|
||||
workerID := tc.workerID
|
||||
if err := b.removeContainer(cctx, workerID); err != nil {
|
||||
return fmt.Errorf("delete task %s worker: %w", taskID, err)
|
||||
}
|
||||
b.clearWorkerID(tc, workerID)
|
||||
|
||||
var errs []error
|
||||
if err := b.removeContainer(cctx, tc.proxyID); err != nil {
|
||||
@@ -861,7 +909,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
|
||||
hdr := make([]byte, 8)
|
||||
for {
|
||||
if _, err := io.ReadFull(r, hdr); err != nil {
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
return outBuf.String(), errBuf.String(), truncated, err
|
||||
@@ -884,7 +932,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
|
||||
take = rem
|
||||
truncated = true
|
||||
}
|
||||
if _, err := io.CopyN(dst, r, take); err != nil && !errors.Is(err, io.EOF) {
|
||||
if _, err := io.CopyN(dst, r, take); err != nil {
|
||||
return outBuf.String(), errBuf.String(), truncated, err
|
||||
}
|
||||
frameLen -= take
|
||||
@@ -892,7 +940,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca
|
||||
truncated = true
|
||||
}
|
||||
if frameLen > 0 {
|
||||
if _, err := io.CopyN(io.Discard, r, frameLen); err != nil && !errors.Is(err, io.EOF) {
|
||||
if _, err := io.CopyN(io.Discard, r, frameLen); err != nil {
|
||||
return outBuf.String(), errBuf.String(), truncated, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,11 +15,20 @@ import (
|
||||
// the request sequence so tests can assert cleanup ordering, and lets each test
|
||||
// fail specific delete calls.
|
||||
type fakeDocker struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
execStatus int // POST /containers/{id}/exec, 0 means 200
|
||||
deleteCode map[string]int // container name -> status, 0 means 204
|
||||
networkCode int // 0 means 204
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
execStatus int // POST /containers/{id}/exec, 0 means 200
|
||||
deleteCode map[string]int // container name -> status, 0 means 204
|
||||
networkCode int // 0 means 204
|
||||
requireWorkerRemoval bool // model Docker rejecting a network with a live worker endpoint
|
||||
execExitCode int
|
||||
execRunning bool
|
||||
execStream []byte
|
||||
execStartCode int
|
||||
inspectCode int
|
||||
inspectBody string
|
||||
streamReady chan struct{}
|
||||
streamStarted bool
|
||||
}
|
||||
|
||||
func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -29,6 +38,8 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Unlock()
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"):
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"):
|
||||
if f.execStatus != 0 {
|
||||
w.WriteHeader(f.execStatus)
|
||||
@@ -36,9 +47,37 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
|
||||
case r.Method == http.MethodPost && strings.HasPrefix(p, "/exec/") && strings.HasSuffix(p, "/start"):
|
||||
if f.execStartCode != 0 {
|
||||
w.WriteHeader(f.execStartCode)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
f.mu.Lock()
|
||||
firstStream := f.streamReady != nil && !f.streamStarted
|
||||
if firstStream {
|
||||
f.streamStarted = true
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if firstStream {
|
||||
w.(http.Flusher).Flush()
|
||||
close(f.streamReady)
|
||||
<-r.Context().Done()
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(f.execStream)
|
||||
case r.Method == http.MethodGet && strings.HasPrefix(p, "/exec/"):
|
||||
_ = json.NewEncoder(w).Encode(map[string]int{"ExitCode": 0})
|
||||
if f.inspectBody != "" {
|
||||
if f.inspectCode != 0 {
|
||||
w.WriteHeader(f.inspectCode)
|
||||
}
|
||||
_, _ = w.Write([]byte(f.inspectBody))
|
||||
return
|
||||
}
|
||||
if f.inspectCode != 0 {
|
||||
w.WriteHeader(f.inspectCode)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": f.execExitCode, "Running": f.execRunning})
|
||||
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"):
|
||||
name := strings.TrimPrefix(p, "/containers/")
|
||||
if code := f.deleteCode[name]; code >= 300 {
|
||||
@@ -47,6 +86,10 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/networks/"):
|
||||
if f.requireWorkerRemoval && !f.seen("DELETE /containers/worker-1") {
|
||||
http.Error(w, "network has active endpoints", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if f.networkCode >= 300 {
|
||||
w.WriteHeader(f.networkCode)
|
||||
return
|
||||
@@ -68,7 +111,7 @@ func (f *fakeDocker) seen(prefix string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func newFakeDockerBackend(t *testing.T, f *fakeDocker) *DockerBackend {
|
||||
func newFakeDockerBackend(t *testing.T, f http.Handler) *DockerBackend {
|
||||
t.Helper()
|
||||
sock := filepath.Join(t.TempDir(), "docker.sock")
|
||||
ln, err := net.Listen("unix", sock)
|
||||
@@ -181,26 +224,26 @@ func TestDeleteKeepsStateWhenProxyRemovalFails(t *testing.T) {
|
||||
if !f.seen("DELETE /containers/proxy-1") {
|
||||
t.Fatal("Delete never attempted the proxy removal")
|
||||
}
|
||||
// The kill sequence must run before the proxy delete.
|
||||
// Removing the worker stops its processes before the proxy is removed.
|
||||
f.mu.Lock()
|
||||
killIdx, proxyIdx := -1, -1
|
||||
workerIdx, proxyIdx := -1, -1
|
||||
for i, c := range f.calls {
|
||||
if strings.HasPrefix(c, "POST /containers/worker-1/exec") {
|
||||
killIdx = i
|
||||
if c == "DELETE /containers/worker-1" {
|
||||
workerIdx = i
|
||||
}
|
||||
if c == "DELETE /containers/proxy-1" {
|
||||
proxyIdx = i
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
if killIdx == -1 || proxyIdx == -1 || killIdx > proxyIdx {
|
||||
t.Fatalf("Delete did not kill the worker before removing the proxy: %v", f.calls)
|
||||
if workerIdx == -1 || proxyIdx == -1 || workerIdx > proxyIdx {
|
||||
t.Fatalf("Delete did not remove the worker before removing the proxy: %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteUnpublishesOnlyAfterFullSuccess covers the happy path.
|
||||
func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) {
|
||||
f := &fakeDocker{}
|
||||
f := &fakeDocker{requireWorkerRemoval: true}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
|
||||
@@ -210,11 +253,26 @@ func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) {
|
||||
if _, ok := b.tasks["t1"]; ok {
|
||||
t.Fatal("Delete left the task in the map after full success")
|
||||
}
|
||||
if !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") {
|
||||
if !f.seen("DELETE /containers/worker-1") || !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") {
|
||||
t.Fatalf("Delete skipped resources: %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteRetainsWorkerAfterRemovalFailure(t *testing.T) {
|
||||
f := &fakeDocker{deleteCode: map[string]int{"worker-1": http.StatusInternalServerError}}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
if err := b.Delete(context.Background(), "t1"); err == nil {
|
||||
t.Fatal("Delete succeeded although the worker could not be removed")
|
||||
}
|
||||
if b.tasks["t1"] != tc || tc.workerID != "worker-1" {
|
||||
t.Fatal("Delete lost the worker needed for a cleanup retry")
|
||||
}
|
||||
if f.seen("DELETE /networks/") {
|
||||
t.Fatal("network deletion attempted while worker is still attached")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteUsesFreshContextAfterCancellation: deletion from a cancelled HTTP
|
||||
// request must still stop the containers.
|
||||
func TestDeleteUsesFreshContextAfterCancellation(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A real Engine is needed to prove the kernel kills a detached child, not just
|
||||
// that the runner requests removal. The child writes a canary and performs no
|
||||
// network activity. Build the worker/proxy images before opting in.
|
||||
func TestDockerTimeoutRemovesDetachedChild(t *testing.T) {
|
||||
if os.Getenv("ARTEX_SANDBOX_DOCKER_TEST") != "1" {
|
||||
t.Skip("requires live Docker and built sandbox images")
|
||||
}
|
||||
ws, au := t.TempDir(), t.TempDir()
|
||||
id := fmt.Sprintf("timeout-%d", time.Now().UnixNano())
|
||||
egressNet := "artex-test-egress-" + id
|
||||
for _, dir := range []string{ws, au, filepath.Join(ws, id), filepath.Join(au, id)} {
|
||||
if err := os.MkdirAll(dir, 0o777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(dir, 0o777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
b := NewDockerBackend(DockerConfig{WorkspaceRoot: ws, HostWorkspaceRoot: ws, AuditRoot: au, HostAuditRoot: au,
|
||||
TaskNetPrefix: "artex-test-task-", EgressNet: egressNet})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
t.Cleanup(func() {
|
||||
_ = b.Delete(context.Background(), id)
|
||||
_ = b.removeNetwork(context.Background(), egressNet)
|
||||
})
|
||||
if err := b.Ping(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tc, err := b.ensureTask(ctx, id, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
worker := tc.workerID
|
||||
script := `import subprocess,sys,time
|
||||
child="import time; f=open('/workspace/timeout-canary','ab',buffering=0); [(f.write(b'x'),time.sleep(.05)) for _ in range(200)]"
|
||||
subprocess.Popen([sys.executable,'-c',child],start_new_session=True,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
time.sleep(10)`
|
||||
res, err := b.Exec(ctx, id, ExecRequest{Argv: []string{"python3", "-c", script}, Workdir: "/workspace", TimeoutMS: 1000})
|
||||
if err != nil || !res.TimedOut {
|
||||
t.Fatalf("response=%+v error=%v", res, err)
|
||||
}
|
||||
r, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+worker+"/json", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
if r.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("timed-out worker still exists: HTTP %d", r.StatusCode)
|
||||
}
|
||||
before, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary"))
|
||||
if err != nil || len(before) == 0 {
|
||||
t.Fatalf("child never ran: %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
after, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary"))
|
||||
if err != nil || len(after) != len(before) {
|
||||
t.Fatalf("child continued after timeout: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExecFailsClosedAndRemovesWorker(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
fake *fakeDocker
|
||||
wantErr bool
|
||||
}{
|
||||
{"timeout", &fakeDocker{execExitCode: 124}, false},
|
||||
{"still_running", &fakeDocker{execRunning: true}, true},
|
||||
{"truncated_stream", &fakeDocker{execStream: []byte{1, 0, 0}}, true},
|
||||
{"truncated_payload", &fakeDocker{execStream: []byte{1, 0, 0, 0, 0, 0, 0, 4, 'x'}}, true},
|
||||
{"inspect_failure", &fakeDocker{inspectCode: http.StatusInternalServerError}, true},
|
||||
{"missing_exit_code", &fakeDocker{inspectBody: `{"Running":false}`}, true},
|
||||
{"missing_running_status", &fakeDocker{inspectBody: `{"ExitCode":0}`}, true},
|
||||
{"malformed_inspect", &fakeDocker{inspectBody: `{`}, true},
|
||||
{"start_failure", &fakeDocker{execStartCode: http.StatusInternalServerError}, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
b := newFakeDockerBackend(t, test.fake)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
tc.scopeHash = scopeFingerprint(nil, nil)
|
||||
res, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000})
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("response=%+v error=%v", res, err)
|
||||
}
|
||||
if !test.wantErr && !res.TimedOut {
|
||||
t.Fatalf("timeout lost: %+v", res)
|
||||
}
|
||||
if tc.workerID != "" || !test.fake.seen("DELETE /containers/worker-1") {
|
||||
t.Fatal("worker survived failed/timed-out execution")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecCancellationCleansUpWithFreshContext(t *testing.T) {
|
||||
f := &fakeDocker{streamReady: make(chan struct{})}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
tc.scopeHash = scopeFingerprint(nil, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := b.Exec(ctx, "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); done <- err }()
|
||||
select {
|
||||
case <-f.streamReady:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("exec did not start")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatal("cancelled exec reported success")
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("cleanup hung")
|
||||
}
|
||||
if tc.workerID != "" || !f.seen("DELETE /containers/worker-1") {
|
||||
t.Fatal("cancelled exec left worker alive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecTimeoutRemovalFailureKeepsWorker(t *testing.T) {
|
||||
f := &fakeDocker{execExitCode: 124, deleteCode: map[string]int{"worker-1": 500}}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
tc.scopeHash = scopeFingerprint(nil, nil)
|
||||
if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err == nil {
|
||||
t.Fatal("cleanup failure hidden")
|
||||
}
|
||||
if tc.workerID != "worker-1" {
|
||||
t.Fatal("worker lost before cleanup was proven")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessfulExecPreservesWorker(t *testing.T) {
|
||||
f := &fakeDocker{}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1")
|
||||
tc.scopeHash = scopeFingerprint(nil, nil)
|
||||
if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.workerID != "worker-1" || f.seen("DELETE /containers/worker-1") {
|
||||
t.Fatal("successful exec lost its worker")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelayedExecCleanupPreservesReplacementWorker(t *testing.T) {
|
||||
f := &fakeDocker{}
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "replacement-worker", "proxy-1", "artex-task-t1")
|
||||
if err := b.removeExecWorker(context.Background(), tc, "old-worker"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tc.workerID != "replacement-worker" || f.seen("DELETE /containers/replacement-worker") || !f.seen("DELETE /containers/old-worker") {
|
||||
t.Fatal("late cleanup targeted or forgot replacement worker")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A timed-out command removes its task's worker, ending sibling exec streams.
|
||||
// An exec in another task must remain live until it finishes independently.
|
||||
func TestExecTimeoutStopsSiblingsButPreservesOtherTask(t *testing.T) {
|
||||
siblingStarted := make(chan struct{})
|
||||
otherStarted := make(chan struct{})
|
||||
workerRemoved := make(chan struct{})
|
||||
finishOther := make(chan struct{})
|
||||
var removedOnce sync.Once
|
||||
var mu sync.Mutex
|
||||
var removed []string
|
||||
f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
switch {
|
||||
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"):
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"):
|
||||
var spec struct{ Cmd []string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&spec); err != nil || len(spec.Cmd) == 0 {
|
||||
http.Error(w, "missing command", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"Id": spec.Cmd[len(spec.Cmd)-1]})
|
||||
case p == "/exec/sibling/start" || p == "/exec/other/start":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
if p == "/exec/sibling/start" {
|
||||
close(siblingStarted)
|
||||
select {
|
||||
case <-workerRemoved:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
} else {
|
||||
close(otherStarted)
|
||||
select {
|
||||
case <-finishOther:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
case p == "/exec/timeout/start":
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case p == "/exec/sibling/json":
|
||||
http.Error(w, "worker removed", http.StatusNotFound)
|
||||
case p == "/exec/timeout/json":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 124, "Running": false})
|
||||
case p == "/exec/other/json":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 0, "Running": false})
|
||||
case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"):
|
||||
mu.Lock()
|
||||
removed = append(removed, p)
|
||||
mu.Unlock()
|
||||
if p == "/containers/worker-a" {
|
||||
removedOnce.Do(func() { close(workerRemoved) })
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
b := newFakeDockerBackend(t, f)
|
||||
a := seedTask(b, "a", "worker-a", "proxy-a", "net-a")
|
||||
other := seedTask(b, "b", "worker-b", "proxy-b", "net-b")
|
||||
a.scopeHash = scopeFingerprint(nil, nil)
|
||||
other.scopeHash = a.scopeHash
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
siblingDone := make(chan error, 1)
|
||||
otherDone := make(chan error, 1)
|
||||
run := func(task, command string, done chan<- error) {
|
||||
res, err := b.Exec(ctx, task, ExecRequest{Argv: []string{command}, TimeoutMS: 1000})
|
||||
if err == nil && res.ExitCode != 0 {
|
||||
err = errors.New("unexpected nonzero exit")
|
||||
}
|
||||
done <- err
|
||||
}
|
||||
go run("a", "sibling", siblingDone)
|
||||
waitSignal(t, ctx, siblingStarted)
|
||||
go run("b", "other", otherDone)
|
||||
waitSignal(t, ctx, otherStarted)
|
||||
res, err := b.Exec(ctx, "a", ExecRequest{Argv: []string{"timeout"}, TimeoutMS: 1000})
|
||||
if err != nil || !res.TimedOut {
|
||||
t.Fatalf("timeout response=%+v err=%v", res, err)
|
||||
}
|
||||
select {
|
||||
case err := <-siblingDone:
|
||||
if err == nil {
|
||||
t.Fatal("sibling reported success after its worker was removed")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("sibling did not finish after worker removal")
|
||||
}
|
||||
select {
|
||||
case err := <-otherDone:
|
||||
t.Fatalf("another task's exec stopped early: %v", err)
|
||||
default:
|
||||
}
|
||||
mu.Lock()
|
||||
deletions := append([]string(nil), removed...)
|
||||
mu.Unlock()
|
||||
for _, path := range deletions {
|
||||
if path != "/containers/worker-a" {
|
||||
t.Fatalf("removed an unrelated resource: %s", path)
|
||||
}
|
||||
}
|
||||
if a.workerID != "" || other.workerID != "worker-b" {
|
||||
t.Fatalf("worker state: task a=%q, task b=%q", a.workerID, other.workerID)
|
||||
}
|
||||
close(finishOther)
|
||||
select {
|
||||
case err := <-otherDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("other task did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func waitSignal(t *testing.T, ctx context.Context, signal <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-signal:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("timed out waiting for simulated Docker request")
|
||||
}
|
||||
}
|
||||
|
||||
// Delete must retain the lifecycle lock until resources and the map entry are
|
||||
// removed. An exec waiting behind it must not recreate the deleted task.
|
||||
func TestEnsureTaskDoesNotRecreateDuringDelete(t *testing.T) {
|
||||
deleting := make(chan struct{})
|
||||
releaseDelete := make(chan struct{})
|
||||
creationAttempt := make(chan struct{}, 1)
|
||||
f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodDelete {
|
||||
if r.URL.Path == "/containers/worker-1" {
|
||||
close(deleting)
|
||||
select {
|
||||
case <-releaseDelete:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case creationAttempt <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
})
|
||||
b := newFakeDockerBackend(t, f)
|
||||
tc := seedTask(b, "t1", "worker-1", "proxy-1", "net-1")
|
||||
tc.scopeHash = scopeFingerprint(nil, nil)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(releaseDelete) }) }
|
||||
defer release()
|
||||
deleteDone := make(chan error, 1)
|
||||
go func() { deleteDone <- b.Delete(ctx, "t1") }()
|
||||
waitSignal(t, ctx, deleting)
|
||||
ensureDone := make(chan error, 1)
|
||||
go func() { _, err := b.ensureTask(ctx, "t1", nil, nil); ensureDone <- err }()
|
||||
select {
|
||||
case <-creationAttempt:
|
||||
t.Fatal("ensureTask contacted Docker while Delete held the worker")
|
||||
case err := <-ensureDone:
|
||||
t.Fatalf("ensureTask returned before Delete completed: %v", err)
|
||||
case <-time.After(50 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-deleteDone:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("Delete did not finish")
|
||||
}
|
||||
select {
|
||||
case err := <-ensureDone:
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("ensureTask after deletion: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("ensureTask did not finish")
|
||||
}
|
||||
if b.WorkerCount() != 0 {
|
||||
t.Fatal("deleted task was re-registered")
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,12 @@ func validateAssetInterceptRuleReq(req *assetInterceptRuleReq) error {
|
||||
return fmt.Errorf("%s is not a valid domain: %s", req.Kind, req.Pattern)
|
||||
}
|
||||
req.Pattern = d
|
||||
case "domain_suffix":
|
||||
d := db.DomainSuffixPattern(req.Pattern)
|
||||
if d == "" || strings.ContainsAny(d, "*/:") || strings.HasPrefix(d, ".") {
|
||||
return fmt.Errorf("domain_suffix is not a valid domain (e.g. example.com): %s", req.Pattern)
|
||||
}
|
||||
req.Pattern = d
|
||||
case "exact_ip":
|
||||
ip, ok := db.CanonicalInterceptIP(req.Pattern)
|
||||
if !ok {
|
||||
|
||||
@@ -22,6 +22,15 @@ func TestValidateAssetInterceptRuleCanonicalizes(t *testing.T) {
|
||||
{"unicode domain is punycoded", "exact_domain", "bücher.example", "xn--bcher-kva.example", false},
|
||||
{"bare dot domain is refused", "exact_domain", ".", "", true},
|
||||
{"fuzzy domain is canonicalized", "fuzzy_domain", " .GOV.CN. ", ".gov.cn", false},
|
||||
{"domain suffix is canonicalized", "domain_suffix", " Example.COM. ", "example.com", false},
|
||||
{"domain suffix drops a wildcard label", "domain_suffix", "*.example.com", "example.com", false},
|
||||
{"domain suffix drops a leading dot", "domain_suffix", ".example.com", "example.com", false},
|
||||
{"unicode domain suffix is punycoded", "domain_suffix", "*.bücher.example", "xn--bcher-kva.example", false},
|
||||
{"domain suffix wildcard inside a label is refused", "domain_suffix", "*example.com", "", true},
|
||||
{"domain suffix deeper wildcard is refused", "domain_suffix", "api.*.example.com", "", true},
|
||||
{"domain suffix double dot is refused", "domain_suffix", "..example.com", "", true},
|
||||
{"domain suffix URL is refused", "domain_suffix", "https://example.com", "", true},
|
||||
{"bare wildcard domain suffix is refused", "domain_suffix", "*.", "", true},
|
||||
{"fuzzy IP is lower-cased", "fuzzy_ip", "FE80::", "fe80::", false},
|
||||
{"CIDR is masked", "cidr", "192.168.1.5/16", "192.168.0.0/16", false},
|
||||
{"invalid CIDR is refused", "cidr", "not-a-cidr", "", true},
|
||||
|
||||
+37
-18
@@ -13,6 +13,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -175,6 +176,13 @@ func samePath(a, b string) bool {
|
||||
return a == b
|
||||
}
|
||||
|
||||
// jwtIssuer and jwtAudience go into every new session token. Tokens issued
|
||||
// before they were added carry neither claim and are still accepted.
|
||||
const (
|
||||
jwtIssuer = "artex"
|
||||
jwtAudience = "artex-api"
|
||||
)
|
||||
|
||||
// sessionClaims carries the password version the token was signed under.
|
||||
// Two changes in the same second get different versions, so a cutoff based on
|
||||
// the issued-at second cannot leave the older token valid.
|
||||
@@ -193,6 +201,8 @@ func signJWTVersion(key []byte, version int64) (string, error) {
|
||||
return jwt.NewWithClaims(jwt.SigningMethodHS256, sessionClaims{
|
||||
Pwd: version,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: jwtIssuer,
|
||||
Audience: jwt.ClaimStrings{jwtAudience},
|
||||
Subject: "ARTEX",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtTTL)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
@@ -200,18 +210,33 @@ func signJWTVersion(key []byte, version int64) (string, error) {
|
||||
}).SignedString(key)
|
||||
}
|
||||
|
||||
// verifyJWT returns true when tokenStr is a valid, non-expired HS256 token.
|
||||
// version 0 means no password change is stored yet, and any valid token is
|
||||
// accepted. A later version requires the token's pwd claim to equal it.
|
||||
func verifyJWT(tokenStr string, key []byte, version int64) bool {
|
||||
// parseSessionJWT returns the claims of tokenStr when it is a valid,
|
||||
// non-expired session token. Only HS256 is accepted. The iss and aud claims
|
||||
// are checked when present; tokens issued before they were added have neither.
|
||||
func parseSessionJWT(tokenStr string, key []byte) (*sessionClaims, bool) {
|
||||
claims := &sessionClaims{}
|
||||
t, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
t, err := jwt.ParseWithClaims(tokenStr, claims, func(*jwt.Token) (any, error) {
|
||||
return key, nil
|
||||
})
|
||||
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
if err != nil || !t.Valid {
|
||||
return nil, false
|
||||
}
|
||||
if claims.Issuer != "" && claims.Issuer != jwtIssuer {
|
||||
return nil, false
|
||||
}
|
||||
if len(claims.Audience) > 0 && !slices.Contains(claims.Audience, jwtAudience) {
|
||||
return nil, false
|
||||
}
|
||||
return claims, true
|
||||
}
|
||||
|
||||
// verifyJWT returns true when tokenStr is a valid, non-expired session token
|
||||
// (parseSessionJWT). version 0 means no password change is stored yet, and any
|
||||
// valid token is accepted. A later version requires the token's pwd claim to
|
||||
// equal it.
|
||||
func verifyJWT(tokenStr string, key []byte, version int64) bool {
|
||||
claims, ok := parseSessionJWT(tokenStr, key)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if version > 0 && claims.Pwd != version {
|
||||
@@ -251,16 +276,10 @@ func (s *Server) applyPasswordVersion(n int64) {
|
||||
}
|
||||
|
||||
// jwtSubject returns the subject of tokenStr when it is a valid, non-expired
|
||||
// HS256 token, and "" otherwise.
|
||||
// session token (parseSessionJWT), and "" otherwise.
|
||||
func jwtSubject(tokenStr string, key []byte) string {
|
||||
var claims jwt.RegisteredClaims
|
||||
t, err := jwt.ParseWithClaims(tokenStr, &claims, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return key, nil
|
||||
})
|
||||
if err != nil || !t.Valid {
|
||||
claims, ok := parseSessionJWT(tokenStr, key)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return claims.Subject
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func testJWTClaims(iss string, aud []string, pwd int64) sessionClaims {
|
||||
return sessionClaims{
|
||||
Pwd: pwd,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: iss,
|
||||
Audience: aud,
|
||||
Subject: "ARTEX",
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func signTestJWT(t *testing.T, method jwt.SigningMethod, key any, c sessionClaims) string {
|
||||
t.Helper()
|
||||
tok, err := jwt.NewWithClaims(method, c).SignedString(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
// New tokens carry iss and aud and are accepted.
|
||||
func TestSignJWTSetsIssuerAndAudience(t *testing.T) {
|
||||
key := []byte("0123456789abcdef0123456789abcdef")
|
||||
tok, err := signJWTVersion(key, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claims, ok := parseSessionJWT(tok, key)
|
||||
if !ok {
|
||||
t.Fatal("new token rejected")
|
||||
}
|
||||
if claims.Issuer != jwtIssuer || !slices.Equal(claims.Audience, jwt.ClaimStrings{jwtAudience}) {
|
||||
t.Errorf("iss=%q aud=%v, want %q and [%q]", claims.Issuer, claims.Audience, jwtIssuer, jwtAudience)
|
||||
}
|
||||
if !verifyJWT(tok, key, 3) || jwtSubject(tok, key) != "ARTEX" {
|
||||
t.Error("new token not accepted by verifyJWT or jwtSubject")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyJWTClaimsAndAlgorithm(t *testing.T) {
|
||||
key := []byte("0123456789abcdef0123456789abcdef")
|
||||
aud := []string{jwtAudience}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
tok string
|
||||
accept bool
|
||||
}{
|
||||
// Tokens issued by earlier releases have no iss or aud and keep working.
|
||||
{"legacy claims, HS256", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", nil, 0)), true},
|
||||
{"iss without aud", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, nil, 0)), true},
|
||||
{"aud without iss", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", aud, 0)), true},
|
||||
{"aud list with ours", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, []string{"other", jwtAudience}, 0)), true},
|
||||
{"wrong iss", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("someone-else", aud, 0)), false},
|
||||
{"wrong aud", signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims(jwtIssuer, []string{"other-api"}, 0)), false},
|
||||
{"HS384", signTestJWT(t, jwt.SigningMethodHS384, key, testJWTClaims(jwtIssuer, aud, 0)), false},
|
||||
{"HS512", signTestJWT(t, jwt.SigningMethodHS512, key, testJWTClaims(jwtIssuer, aud, 0)), false},
|
||||
{"HS512 legacy claims", signTestJWT(t, jwt.SigningMethodHS512, key, testJWTClaims("", nil, 0)), false},
|
||||
{"alg none", signTestJWT(t, jwt.SigningMethodNone, jwt.UnsafeAllowNoneSignatureType, testJWTClaims(jwtIssuer, aud, 0)), false},
|
||||
{"other key", signTestJWT(t, jwt.SigningMethodHS256, []byte("another-key-another-key-another-k"), testJWTClaims(jwtIssuer, aud, 0)), false},
|
||||
} {
|
||||
if got := verifyJWT(tc.tok, key, 0); got != tc.accept {
|
||||
t.Errorf("%s: verifyJWT=%v, want %v", tc.name, got, tc.accept)
|
||||
}
|
||||
if got := jwtSubject(tc.tok, key) == "ARTEX"; got != tc.accept {
|
||||
t.Errorf("%s: jwtSubject accepted=%v, want %v", tc.name, got, tc.accept)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The password version check still applies to legacy tokens.
|
||||
func TestVerifyJWTLegacyTokenPasswordVersion(t *testing.T) {
|
||||
key := []byte("0123456789abcdef0123456789abcdef")
|
||||
tok := signTestJWT(t, jwt.SigningMethodHS256, key, testJWTClaims("", nil, 2))
|
||||
if !verifyJWT(tok, key, 2) {
|
||||
t.Error("legacy token at the current password version rejected")
|
||||
}
|
||||
if verifyJWT(tok, key, 3) {
|
||||
t.Error("legacy token at an old password version accepted")
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -150,7 +150,9 @@ func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo
|
||||
switch kind {
|
||||
case "exact_domain", "domain_suffix":
|
||||
addDom(pat)
|
||||
case "cidr", "ip":
|
||||
// The single-address kind is exact_ip (asset_intercept_match.go);
|
||||
// NewEgressPolicy reads a bare address as a host prefix.
|
||||
case "cidr", "exact_ip":
|
||||
addCIDR(pat)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
// TestSandboxEgressFromTaskAllowRules covers the operator's task allow rules
|
||||
// as sandbox egress. An exact_ip allow rule used to grant none: the switch
|
||||
// looked for an "ip" kind that the rule tables never store, so a task scoped
|
||||
// to one address could not reach it from the sandbox.
|
||||
func TestSandboxEgressFromTaskAllowRules(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() })
|
||||
|
||||
suffix := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
allowedDom := "allow-" + suffix + ".test"
|
||||
rule := func(action, kind, pattern string, enabled bool) db.TaskInterceptRuleInput {
|
||||
return db.TaskInterceptRuleInput{Action: action, Kind: kind, Pattern: pattern, Enabled: enabled}
|
||||
}
|
||||
task, err := pg.CreateTaskWithOptions("allow-egress-"+suffix, "goal", db.TaskCreateOptions{
|
||||
InterceptRules: []db.TaskInterceptRuleInput{
|
||||
rule("allow", "exact_ip", "10.20.30.40", true),
|
||||
rule("allow", "cidr", "198.51.100.0/24", true),
|
||||
rule("allow", "exact_domain", allowedDom, true),
|
||||
rule("allow", "exact_ip", "10.20.30.41", false), // disabled
|
||||
rule("block", "exact_ip", "10.20.30.42", true), // a block rule grants nothing
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.DeleteTask(task.ID) })
|
||||
|
||||
info := taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(task.ID, 10))
|
||||
for _, want := range []string{"10.20.30.40", "198.51.100.0/24"} {
|
||||
if !scopeHas(info.ScopeCIDRs, want) {
|
||||
t.Fatalf("allow rule %s missing from ScopeCIDRs=%v", want, info.ScopeCIDRs)
|
||||
}
|
||||
}
|
||||
for _, unwanted := range []string{"10.20.30.41", "10.20.30.42"} {
|
||||
if scopeHas(info.ScopeCIDRs, unwanted) {
|
||||
t.Fatalf("%s reached ScopeCIDRs=%v", unwanted, info.ScopeCIDRs)
|
||||
}
|
||||
}
|
||||
if !scopeHas(info.ScopeDomains, allowedDom) {
|
||||
t.Fatalf("allow rule %s missing from ScopeDomains=%v", allowedDom, info.ScopeDomains)
|
||||
}
|
||||
|
||||
// The egress policy reads the bare address as a host prefix: the private
|
||||
// address the operator allowed is reachable, its neighbour is not.
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEgressPolicy: %v", err)
|
||||
}
|
||||
ctx := t.Context()
|
||||
if err := pol.CheckURL(ctx, "http://10.20.30.40/"); err != nil {
|
||||
t.Fatalf("allowed address refused: %v", err)
|
||||
}
|
||||
if err := pol.CheckURL(ctx, "http://10.20.30.43/"); err == nil {
|
||||
t.Fatal("an address outside the allow rules was accepted")
|
||||
}
|
||||
}
|
||||
@@ -1101,6 +1101,7 @@ const TASK_RULE_KIND_OPTIONS: { value: AssetInterceptKind; label: string; placeh
|
||||
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
|
||||
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
|
||||
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
|
||||
{ value: "domain_suffix", label: t("Domain (suffix)"), placeholder: "example.com" },
|
||||
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
|
||||
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
|
||||
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
|
||||
|
||||
@@ -26,6 +26,7 @@ const KIND_OPTIONS: { value: AssetInterceptKind; label: string; group: string; p
|
||||
{ value: "exact_domain", label: t("Domain (exact)"), group: "Exact match", placeholder: "example.gov.cn" },
|
||||
{ value: "exact_ip", label: t("IP (exact)"), group: "Exact match", placeholder: "203.0.113.10" },
|
||||
{ value: "exact_url", label: t("URL (exact)"), group: "Exact match", placeholder: "https://example.gov.cn/login" },
|
||||
{ value: "domain_suffix", label: t("Domain (suffix)"), group: "Exact match", placeholder: "example.gov.cn" },
|
||||
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), group: "Fuzzy match", placeholder: ".gov.cn" },
|
||||
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), group: "Fuzzy match", placeholder: "203.0.113." },
|
||||
{ value: "fuzzy_url", label: t("URL (fuzzy)"), group: "Fuzzy match", placeholder: "/admin" },
|
||||
|
||||
@@ -18,6 +18,7 @@ export const ASSET_INTERCEPT_KIND_OPTIONS: {
|
||||
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
|
||||
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
|
||||
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
|
||||
{ value: "domain_suffix", label: t("Domain (suffix)"), placeholder: "example.com" },
|
||||
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
|
||||
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
|
||||
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
|
||||
|
||||
@@ -789,6 +789,7 @@
|
||||
"domain (e.g. target.example.com)": "domínio (por exemplo, target.example.com)",
|
||||
"Domain (exact)": "Domínio (exato)",
|
||||
"Domain (fuzzy)": "Domínio (aproximado)",
|
||||
"Domain (suffix)": "Domínio (sufixo)",
|
||||
"Domain (root domain/subdomain/service domain)": "Domínio (domínio raiz/subdomínio/domínio de serviço)",
|
||||
"Domain or IP": "Domínio ou IP",
|
||||
"Done": "Concluído",
|
||||
|
||||
@@ -789,6 +789,7 @@
|
||||
"domain (e.g. target.example.com)": "alan adı (ör. target.example.com)",
|
||||
"Domain (exact)": "Alan adı (tam)",
|
||||
"Domain (fuzzy)": "Alan adı (bulanık)",
|
||||
"Domain (suffix)": "Alan adı (sonek)",
|
||||
"Domain (root domain/subdomain/service domain)": "Alan adı (kök alan adı/alt alan adı/servis alan adı)",
|
||||
"Domain or IP": "Alan adı veya IP",
|
||||
"Done": "Bitti",
|
||||
|
||||
@@ -789,6 +789,7 @@
|
||||
"domain (e.g. target.example.com)": "tên miền (ví dụ target.example.com)",
|
||||
"Domain (exact)": "Tên miền (chính xác)",
|
||||
"Domain (fuzzy)": "Tên miền (mờ)",
|
||||
"Domain (suffix)": "Tên miền (hậu tố)",
|
||||
"Domain (root domain/subdomain/service domain)": "Tên miền (tên miền gốc/tên miền con/tên miền dịch vụ)",
|
||||
"Domain or IP": "Tên miền hoặc IP",
|
||||
"Done": "Xong",
|
||||
|
||||
@@ -789,6 +789,7 @@
|
||||
"domain (e.g. target.example.com)": "域名(例如 target.example.com)",
|
||||
"Domain (exact)": "域名(全等)",
|
||||
"Domain (fuzzy)": "域名(模糊)",
|
||||
"Domain (suffix)": "域名(后缀)",
|
||||
"Domain (root domain/subdomain/service domain)": "域名(根域名/子域名/服务域名)",
|
||||
"Domain or IP": "域名或 IP",
|
||||
"Done": "完成",
|
||||
|
||||
@@ -1437,6 +1437,7 @@ export type AssetInterceptKind =
|
||||
| "exact_domain"
|
||||
| "exact_ip"
|
||||
| "exact_url"
|
||||
| "domain_suffix"
|
||||
| "fuzzy_domain"
|
||||
| "fuzzy_ip"
|
||||
| "fuzzy_url"
|
||||
|
||||
Reference in New Issue
Block a user