diff --git a/.gitattributes b/.gitattributes index d78c7d0..9d1d5b1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ *.bat text eol=crlf *.sh text eol=lf +scripts/poc/ export-ignore +skills/edr-bypass-re/ export-ignore +skills/php2shell/ export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f949165..062d338 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,7 +71,7 @@ jobs: ARTEX_PG_DSN: postgres://artex:testpass@localhost:5432/artextest_race?sslmode=disable run: >- - go test -race -p 1 ./agent ./cmd/artex ./config ./db ./evidence ./guard + go test -race -p 1 ./agent ./archivestore ./cmd/artex ./config ./db ./evidence ./guard ./intercept ./llmpool ./llmrec ./mcphttp ./notify ./server ./sidequestion ./traffic ./traffic/rewrite @@ -149,6 +149,7 @@ jobs: - run: npm run test:polling - run: npm run test:replay - run: npm run test:upload + - run: npm run test:i18n - run: npm run build:static python: diff --git a/CHANGELOG.md b/CHANGELOG.md index 74f6a55..d2cdd92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ All notable changes to this project are documented in this file. The format is b - **Capture-proxy rewrite rules, storage and API**: `GET`, `POST`, `PUT` and `DELETE /api/traffic/rewrite-rules` and `POST /api/traffic/rewrite-rules/{id}/toggle` manage rules that match a request or a response (method, host, URL, headers, body, status) and describe a rewrite (method, path and query, headers, body, status). Rules are validated on save, limited to 100 of which 50 enabled, created disabled, and stored in the new table `traffic_rewrite_rules` (migration `0005_traffic_rewrite_rules.sql`) with `matchers` and `actions` encrypted at rest. The value of an action marked `sensitive` is never returned, and an update sent without it keeps the stored one. The server compiles the enabled rules at startup and after every change and hands the snapshot to the proxy. The proxy applies them from the next entry. See `docs/traffic-rewrite-rules.md`. - **Capture-proxy rewrite rules applied**: the capture proxy applies enabled rules to each HTTP request before it is sent to the target and to each response before it reaches the client. Each action that ran is recorded in the new table `exchange_rewrites` in the same transaction as the exchange, `traffic_get` shows a `REWRITTEN` line, and `traffic_search` never finds a value a rule wrote. SSE status and headers are rewritten at the start of the stream. **WebSocket handshakes are not rewritten**: the capture library runs its hook after the upgrade, so the status and headers cannot be changed, and frames pass unchanged. **Responses of 5 MiB or more** are forwarded unchanged and not recorded in full, because the library does not call the response hook for them. Snapshots of original requests are capped at 1024 entries and 64 MiB. Replays go through the proxy, so the rules apply to them. Archives, a per-replay rule toggle, the web UI and the proof flag come later. - **Bulk finding status** (#298): select findings in the findings table and apply one disposition to all of them, up to 500 per call, in one transaction; each row still goes through the single-decision notification semantics and the change is mirrored onto its exploration node (#289). +- **Stream message direction filter** (#379): `GET /api/traffic/stream` and the `traffic_messages` agent tool take an optional `direction` (`c2s` or `s2c`) that lists only one side of a WebSocket or SSE conversation. `total` and `offset` apply to the filtered list, each row keeps its `seq` in the whole stream, and the `meta` row (messages dropped past the recorder limits) stays in a filtered page. Any other value is a 400 (API) or a tool error. - **Traffic replay** (#266): replay a recorded request from the traffic detail with its method, URL, headers and stored body; replay is disabled when only the body preview is loaded. - **Finding proof strength in reports** (#268): the Markdown report and the export show each finding's proof strength next to its verification status. - **Opt-in Keenable web search backend** (#295): the search tool gains Keenable alongside Brave and Tavily; the key is stored encrypted and can be cleared independently. @@ -49,6 +50,15 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Workspace and skill symlink confinement**: workspace file operations, the skill file APIs and the skill loader resolve symlinks in every path component and refuse a target outside their root, so a link planted in the workspace or a skill directory cannot expose another file. +- **Target gate behind proxies**: a target approval is name-only whenever a proxy is in the path, including the recording proxy, the global egress proxy and a custom tool's own proxy, so the gate never claims an IP binding the proxy does not enforce. +- **Remote MCP response bound**: Streamable HTTP JSON-RPC bodies and SSE data payloads are refused above 8 MiB, so a remote MCP server cannot force an unbounded decode. +- **LLM response capture bound**: each recorded provider attempt keeps at most 1 MiB, and a call keeps at most 8 attempts, so a large or retrying stream cannot grow the recorder without bound. The live stream is unchanged. +- **Intercept audit ring**: `preToolUse` records allow only after intercept and the target gate decide, so a blocked call no longer leaves a leftover allow row in `Guard.Audit()`. +- **DSN password redaction**: `config.Redact` now masks libpq `password=` keywords and `?password=` query values as well as URL userinfo, so a ping-failure log cannot print the database password. +- **Asset DSL nesting**: `ParseDSL` refuses queries longer than 4 KiB or nested more than 32 parentheses deep, so a crafted `dsl` cannot grow the goroutine stack without bound. +- **Retry-After overflow**: a 429/503 `Retry-After` of huge seconds no longer wraps `time.Duration` into a tiny delay. Values above `MaxDelay` are not retried. +- **Conversation message pages**: `GET /api/conversations/{id}/messages` clamps `limit` (200 for history, 1000 for `?since=`), so a huge query cannot load the whole transcript in one response. - **Findings CSV formula cells**: `FindingsCSV` prefixes name, class, summary, task, and other text fields that start with `=`, `+`, `-`, `@`, tab, or CR so Excel/LibreOffice do not evaluate them as formulas when the export is opened. - **Asset service links**: the Services tab only uses an asset URL as `href` when it is `http:` or `https:`. `javascript:`, `data:`, and other schemes render as text. - **Chat session directories**: `ChatAgent.Chat` accepts only `[A-Za-z0-9_-]` session ids (at most 64 bytes) before joining them under `/sessions`, so `..` and path separators cannot escape that directory. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9df2e6c..cc70af0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,6 +5,7 @@ - **At most 7 open pull requests per contributor.** The repository enforces this with GitHub's pull request creation limit, drafts included: when you reach it, close or merge one before opening another. Review is manual, one change at a time, so a larger batch makes the queue unmanageable and slows everyone down, including you. If you have more changes queued, open one issue that lists them and wait for the current ones to be reviewed. - **One focused change per PR.** If a change has independent parts, split it into a small number of PRs and say in each description what the other parts depend on. - **Describe the change.** State the problem, the behavior change and what you tested. A pull request with no description is a request for changes. +- **Provider support stays generic.** Any OpenAI- or Anthropic-compatible endpoint works through a model profile; provider convenience goes in as a neutral preset (name and base URL) or a docs recipe, with no vendor logos, promotional codes, baked vendor endpoints, or vendor-specific environment variables. A new wire format needs a schema migration, a profile save/load test, and a live connection test. ## Issues @@ -12,4 +13,4 @@ ## Security -- Do not open a public issue for a vulnerability in ARTEX itself. Use the private advisory form in the repository's Security tab. +- Do not open a public issue for a vulnerability in ARTEX itself. Follow the [private reporting instructions](SECURITY.md#reporting-a-vulnerability). diff --git a/README.md b/README.md index 307a035..c198402 100644 --- a/README.md +++ b/README.md @@ -428,6 +428,14 @@ runtime supports it. `/chat/completions` (or `/responses` for `openai-responses`), so their base **does** end in `/v1` (for example `https://api.openai.com/v1`). +**OpenAI-compatible gateways**: any provider that serves an OpenAI-style +`/v1/chat/completions` endpoint works through the **OpenAI** format — no dedicated format +needed. Create a profile with format **OpenAI**, set **Base URL** to the gateway's `/v1` +root, paste the key, then click the **↻** button next to *Model* to load the provider's +catalog (`GET /v1/models`) and pick a model; models the provider adds later appear on the +next refresh. For example, [NotHoly](https://notholy.com) (offensive-security models) uses +base URL `https://api.notholy.com/v1` with an API key from its console. + **Concurrency**: work agents per task, in "System Settings" (default 3). **Untrusted-output boundary (on by default)**: tool results for the worker, planner, chat and main diff --git a/SECURITY.md b/SECURITY.md index 1bdbe4a..49ccd93 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,7 +14,7 @@ Notes: **Do not open a public issue for a security vulnerability.** -Report through **GitHub Security Advisories**: **Security** tab → **Report a vulnerability** in the `BaaRai/ARTEX` repository. This is the only reporting channel. +Sign in to GitHub and use the [private vulnerability report form](https://github.com/BaaRai/ARTEX/security/advisories/new). You can also reach it from the repository's **Security and quality** tab under **Advisories** → **Report a vulnerability**. This is the only reporting channel. Please include: - A description of the vulnerability and its expected impact. @@ -43,6 +43,12 @@ The enforced trust boundary for asset insertion is `insert_assets`, which runs e Accepted gap: when a task has no allow-list, there is no allow rule to apply (block rules still run), and any host carried on an in-scope event that is not blocked enters the graph as an asset. Operators who rely on the scanner's scope rules alone should configure an allow-list per task, or review `output.json` before feeding it to ARTEX. Cross-checking ingested events against ARTEX's own rule set would change what existing scanner configurations mean for those operators, so it is treated as a deliberate design question (see #317), not an accepted vulnerability. +## Outbound Model Listing (`POST /api/llm/models`) + +`POST /api/llm/models` fetches model lists from the provider endpoint and optional HTTP proxy supplied in the request. By default, ARTEX allows only `http` and `https` URLs whose hosts resolve exclusively to public IP addresses (blocking loopback, RFC1918 private networks, IPv6 unique-local `fc00::/7`, link-local/cloud metadata such as `169.254.169.254`, unspecified, and multicast addresses), and enforces the same checks on redirects and at dial time. The built-in local Ollama default (`http://127.0.0.1:11434/v1`) is permitted only when the request leaves `base_url` empty for the `ollama` provider. + +Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge can allow specific endpoints with `ARTEX_LLM_PRIVATE_ENDPOINTS`, a comma-separated list of exact `host:port` entries (for example, `127.0.0.1:11434,host.docker.internal:11434,192.168.1.10:11434`). A URL whose `host:port` matches an entry may resolve to a loopback or private address while scheme restrictions, link-local/cloud-metadata blocks, and redirect validation still apply; everything else stays refused. Leaving `ARTEX_LLM_PRIVATE_ENDPOINTS` unset or empty keeps the strict public-only policy. + ## What to Expect This is an open-source project maintained on a best-effort basis. We aim to acknowledge a report within about a week and keep you updated, but we cannot guarantee specific response or fix timeframes. diff --git a/archivestore/config_test.go b/archivestore/config_test.go new file mode 100644 index 0000000..1fe54a5 --- /dev/null +++ b/archivestore/config_test.go @@ -0,0 +1,89 @@ +package archivestore + +import ( + "strings" + "testing" +) + +func TestArchiveStorageEnvironment(t *testing.T) { + for _, key := range []string{ + "ARTEX_ARCHIVE_STORAGE", "ARTEX_ARCHIVE_S3_ENDPOINT", "ARTEX_ARCHIVE_S3_REGION", + "ARTEX_ARCHIVE_S3_BUCKET", "ARTEX_ARCHIVE_S3_PREFIX", "ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", + "ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "ARTEX_ARCHIVE_S3_PATH_STYLE", + "ARTEX_ARCHIVE_S3_SESSION_TOKEN", "ARTEX_ARCHIVE_S3_SSE", "ARTEX_ARCHIVE_S3_KMS_KEY_ID", + } { + t.Setenv(key, "") + } + for _, backend := range []string{"", "local"} { + t.Setenv("ARTEX_ARCHIVE_STORAGE", backend) + if store, err := FromEnv(); err != nil || store != nil { + t.Fatalf("local default: %v %v", store, err) + } + } + for _, backend := range []string{"unknown", "s3"} { + t.Setenv("ARTEX_ARCHIVE_STORAGE", backend) + if _, err := FromEnv(); err == nil { + t.Fatalf("%q silently fell back to local", backend) + } + } + t.Setenv("ARTEX_ARCHIVE_S3_ENDPOINT", "http://127.0.0.1:9000") + t.Setenv("ARTEX_ARCHIVE_S3_BUCKET", "test-bucket") + t.Setenv("ARTEX_ARCHIVE_S3_ACCESS_KEY_ID", "test-key") + t.Setenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "test-secret") + t.Setenv("ARTEX_ARCHIVE_S3_PATH_STYLE", "true") + store, err := FromEnv() + if err != nil { + t.Fatal(err) + } + if uri := store.URI(1, 2, "checksum"); uri != "s3://test-bucket/artex/tasks/task-1-2-checksum.tar.zst" { + t.Fatal("unexpected default object location", uri) + } + t.Setenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY", "") + if _, err := FromEnv(); err == nil { + t.Fatal("missing credentials accepted") + } +} + +func TestArchiveEndpointValidation(t *testing.T) { + config := Config{Bucket: "test", AccessKey: "test-key", SecretKey: "test-secret"} + for _, endpoint := range []string{"https://objects.example.test", "http://127.0.0.1:9000", "http://127.0.0.2:9000", "http://[::1]:9000", "http://localhost:9000"} { + config.Endpoint = endpoint + if _, err := New(config); err != nil { + t.Errorf("rejected %s: %v", endpoint, err) + } + } + for _, endpoint := range []string{"http://objects.example.test", "https://user:test-secret@objects.example.test", "https://objects.example.test/bucket", "https://objects.example.test?token=test-secret", "https://objects.example.test#fragment"} { + config.Endpoint = endpoint + if _, err := New(config); err == nil { + t.Error("accepted endpoint with non-loopback HTTP, credentials, path, query or fragment") + } else if strings.Contains(err.Error(), "test-secret") { + t.Fatal("configuration error disclosed a secret") + } + } +} + +func TestArchiveEncryptionConfiguration(t *testing.T) { + c := Config{Endpoint: "https://objects.example.test", Bucket: "test", AccessKey: "test", SecretKey: "test"} + for _, mode := range []string{"none", "invalid"} { + c.SSE = mode + if _, err := New(c); err == nil { + t.Fatal("unencrypted/invalid mode accepted") + } + } + c.SSE = "AES256" + c.KMSKeyID = "alias/archive" + if _, err := New(c); err == nil { + t.Fatal("KMS key accepted with SSE-S3") + } + c.SSE = "aws:kms" + for _, key := range []string{"alias/archive", "bare-key-id", "arn:aws:kms:us-east-1:123456789012:alias/archive"} { + c.KMSKeyID = key + if _, err := New(c); err == nil { + t.Fatalf("accepted noncanonical KMS key %q", key) + } + } + c.KMSKeyID = "arn:aws:kms:us-east-1:123456789012:key/test-key" + if _, err := New(c); err != nil { + t.Fatal(err) + } +} diff --git a/archivestore/credentials_test.go b/archivestore/credentials_test.go new file mode 100644 index 0000000..6c667ed --- /dev/null +++ b/archivestore/credentials_test.go @@ -0,0 +1,132 @@ +package archivestore + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func isolateAWSCredentials(t *testing.T) { + t.Helper() + for _, key := range []string{ + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", + "AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME", "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "AWS_CONTAINER_AUTHORIZATION_TOKEN", "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", + "AWS_EC2_METADATA_SERVICE_ENDPOINT", "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", + } { + t.Setenv(key, "") + } + dir := t.TempDir() + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "credentials")) + t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "config")) + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") +} + +func TestArchiveCredentialChain(t *testing.T) { + config := Config{Endpoint: "https://objects.example.test", Bucket: "test"} + for _, mode := range []string{"explicit-session", "environment", "shared-profile", "ecs", "imds"} { + t.Run(mode, func(t *testing.T) { + isolateAWSCredentials(t) + c := config + switch mode { + case "explicit-session": + t.Setenv("AWS_ACCESS_KEY_ID", "other-key") + t.Setenv("AWS_SECRET_ACCESS_KEY", "other-secret") + c.AccessKey, c.SecretKey, c.SessionToken = "fixture-key", "fixture-secret", "fixture-session" + case "environment": + t.Setenv("AWS_ACCESS_KEY_ID", "fixture-key") + t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture-secret") + t.Setenv("AWS_SESSION_TOKEN", "fixture-session") + case "shared-profile": + t.Setenv("AWS_PROFILE", "archive") + data := `[archive] +aws_access_key_id=fixture-key +aws_secret_access_key=fixture-secret +aws_session_token=fixture-session +` + if err := os.WriteFile(os.Getenv("AWS_SHARED_CREDENTIALS_FILE"), []byte(data), 0600); err != nil { + t.Fatal(err) + } + case "ecs", "imds": + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if mode == "imds" { + switch r.URL.Path { + case "/latest/api/token": + if r.Method != "PUT" { + t.Error("IMDS did not use token request") + } + w.Header().Set("X-aws-ec2-metadata-token-ttl-seconds", "21600") + fmt.Fprint(w, "fixture-imds-token") + return + case "/latest/meta-data/iam/security-credentials/": + if r.Header.Get("X-aws-ec2-metadata-token") != "fixture-imds-token" { + t.Error("missing IMDSv2 token") + } + fmt.Fprint(w, "archive-role") + return + case "/latest/meta-data/iam/security-credentials/archive-role": + if r.Header.Get("X-aws-ec2-metadata-token") != "fixture-imds-token" { + t.Error("missing IMDSv2 token") + } + default: + t.Errorf("unexpected IMDS request %s", r.URL.Path) + w.WriteHeader(404) + return + } + } else if r.Header.Get("Authorization") != "fixture-container-token" { + t.Error("missing ECS authorization token") + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "Code": "Success", "AccessKeyId": "fixture-key", "SecretAccessKey": "fixture-secret", + "Token": "fixture-session", "Expiration": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + }) + })) + defer srv.Close() + if mode == "imds" { + t.Setenv("AWS_EC2_METADATA_DISABLED", "false") + t.Setenv("AWS_EC2_METADATA_V1_DISABLED", "true") + t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", srv.URL) + } else { + t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", srv.URL+"/credentials") + t.Setenv("AWS_CONTAINER_AUTHORIZATION_TOKEN", "fixture-container-token") + } + } + store, err := New(c) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + credentials, err := store.client.Options().Credentials.Retrieve(ctx) + if err != nil { + t.Fatal(err) + } + if credentials.AccessKeyID != "fixture-key" || credentials.SecretAccessKey != "fixture-secret" || credentials.SessionToken != "fixture-session" { + t.Fatal("wrong credential provider or session token") + } + if (mode == "imds" || mode == "ecs") && !credentials.CanExpire { + t.Fatal("role credentials must remain refreshable") + } + }) + } +} + +func TestArchiveIncompleteCredentialOverride(t *testing.T) { + isolateAWSCredentials(t) + t.Setenv("AWS_ACCESS_KEY_ID", "valid-ambient-key") + t.Setenv("AWS_SECRET_ACCESS_KEY", "valid-ambient-secret") + for _, c := range []Config{{AccessKey: "private-value"}, {SecretKey: "private-value"}, {SessionToken: "private-value"}} { + c.Endpoint, c.Bucket = "https://objects.example.test", "test" + if _, err := New(c); err == nil || strings.Contains(err.Error(), "private-value") { + t.Fatalf("partial override must fail without disclosing credentials: %v", err) + } + } +} diff --git a/archivestore/s3.go b/archivestore/s3.go new file mode 100644 index 0000000..5761a83 --- /dev/null +++ b/archivestore/s3.go @@ -0,0 +1,372 @@ +// Package archivestore stores immutable cold-task packages in S3-compatible storage. +package archivestore + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "path" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/arn" + "github.com/aws/aws-sdk-go-v2/aws/retry" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/feature/s3/manager" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" +) + +type Config struct { + Endpoint, Region, Bucket, Prefix, AccessKey, SecretKey string + PathStyle bool + SessionToken, SSE, KMSKeyID string +} + +type Store struct { + client *s3.Client + bucket, prefix string + encryption types.ServerSideEncryption + kmsKeyID string +} + +// FromEnv returns nil for the default local backend. A configured but invalid +// backend is an error, never a silent fallback to the machine's local disk. +func FromEnv() (*Store, error) { + switch os.Getenv("ARTEX_ARCHIVE_STORAGE") { + case "", "local": + return nil, nil + case "s3": + return New(Config{ + Endpoint: os.Getenv("ARTEX_ARCHIVE_S3_ENDPOINT"), Region: os.Getenv("ARTEX_ARCHIVE_S3_REGION"), + Bucket: os.Getenv("ARTEX_ARCHIVE_S3_BUCKET"), Prefix: os.Getenv("ARTEX_ARCHIVE_S3_PREFIX"), + AccessKey: os.Getenv("ARTEX_ARCHIVE_S3_ACCESS_KEY_ID"), SecretKey: os.Getenv("ARTEX_ARCHIVE_S3_SECRET_ACCESS_KEY"), + PathStyle: os.Getenv("ARTEX_ARCHIVE_S3_PATH_STYLE") == "true", + SessionToken: os.Getenv("ARTEX_ARCHIVE_S3_SESSION_TOKEN"), + SSE: os.Getenv("ARTEX_ARCHIVE_S3_SSE"), KMSKeyID: os.Getenv("ARTEX_ARCHIVE_S3_KMS_KEY_ID"), + }) + default: + return nil, errors.New("ARTEX_ARCHIVE_STORAGE must be local or s3") + } +} + +func New(c Config) (*Store, error) { + u, err := url.Parse(c.Endpoint) + loopback := false + if err == nil { + loopback = u.Hostname() == "localhost" + if ip := net.ParseIP(u.Hostname()); ip != nil { + loopback = ip.IsLoopback() + } + } + if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || + (u.Scheme != "https" && !(u.Scheme == "http" && loopback)) { + return nil, errors.New("archive S3 endpoint must be an HTTPS origin (HTTP allowed only on loopback)") + } + c.Prefix = strings.Trim(c.Prefix, "/") + if c.Prefix == "" { + c.Prefix = "artex/tasks" + } + if path.Clean(c.Prefix) != c.Prefix || strings.Contains(c.Prefix, "..") || strings.ContainsAny(c.Prefix, "\\?#") { + return nil, errors.New("invalid archive S3 prefix") + } + if c.Bucket == "" || strings.ContainsAny(c.Bucket, "/\\:@?# ") { + return nil, errors.New("a valid archive S3 bucket is required") + } + explicitCredentials := c.AccessKey != "" || c.SecretKey != "" || c.SessionToken != "" + if explicitCredentials && (c.AccessKey == "" || c.SecretKey == "") { + return nil, errors.New("archive S3 access key and secret key must both be set when overriding AWS credentials") + } + if c.SSE == "" { + c.SSE = "AES256" + } + if c.SSE != "AES256" && c.SSE != "aws:kms" { + return nil, errors.New("archive S3 SSE must be AES256 or aws:kms; encryption cannot be disabled") + } + if c.KMSKeyID != "" && c.SSE != "aws:kms" { + return nil, errors.New("archive S3 KMS key requires SSE=aws:kms") + } + if c.KMSKeyID != "" { + key, err := arn.Parse(c.KMSKeyID) + if err != nil || key.Service != "kms" || key.Region == "" || key.AccountID == "" || + !strings.HasPrefix(key.Resource, "key/") || len(key.Resource) <= len("key/") { + return nil, errors.New("archive S3 KMS key must be a full key ARN, not an alias or bare key ID") + } + } + if c.Region == "" { + c.Region = "us-east-1" + } + // Load shared AWS settings (including custom CAs) for both credential modes. + httpClient := awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { + t.ResponseHeaderTimeout = 60 * time.Second + }) + options := []func(*awsconfig.LoadOptions) error{ + awsconfig.WithRegion(c.Region), awsconfig.WithHTTPClient(httpClient), + } + if explicitCredentials { + options = append(options, awsconfig.WithCredentialsProvider( + credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, c.SessionToken))) + } + cfg, err := awsconfig.LoadDefaultConfig(context.Background(), options...) + if err != nil { + return nil, fmt.Errorf("load archive S3 AWS configuration: %w", err) + } + // The SDK's default client still follows 307/308. Use its CA-configured + // transport, but never redirect a signed archive request to another origin. + configuredClient := cfg.HTTPClient.(*awshttp.BuildableClient) + cfg.HTTPClient = &http.Client{ + Transport: configuredClient.GetTransport(), Timeout: configuredClient.GetTimeout(), + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + client := s3.NewFromConfig(cfg, func(o *s3.Options) { + o.BaseEndpoint = aws.String(c.Endpoint) + o.UsePathStyle = c.PathStyle + o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired + o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired + }) + return &Store{client: client, bucket: c.Bucket, prefix: c.Prefix + "/", + encryption: types.ServerSideEncryption(c.SSE), kmsKeyID: c.KMSKeyID}, nil +} + +func (s *Store) URI(taskID, archiveID int64, checksum string) string { + return "s3://" + s.bucket + "/" + s.prefix + fmt.Sprintf("task-%d-%d-%s.tar.zst", taskID, archiveID, checksum) +} + +func (s *Store) key(uri string) (string, error) { + if s == nil { + return "", errors.New("S3 archive storage is not configured") + } + u, err := url.Parse(uri) + if err != nil || u.Scheme != "s3" || u.Host != s.bucket || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "", errors.New("archive object is outside the configured bucket") + } + key := strings.TrimPrefix(u.Path, "/") + if !strings.HasPrefix(key, s.prefix) || len(key) <= len(s.prefix) || path.Clean(key) != key || strings.Contains(key, "\\") { + return "", errors.New("archive object is outside the configured prefix") + } + return key, nil +} + +func (s *Store) Validate(uri string) error { _, err := s.key(uri); return err } + +// Upload verifies the entire uploaded object by reading it back, including +// multipart uploads whose ETag is not a checksum. Callers retain source data +// until verification succeeds and PostgreSQL commits the remote location. +func (s *Store) Upload(ctx context.Context, uri, filename, checksum string) error { + key, err := s.key(uri) + if err != nil { + return err + } + if decoded, err := hex.DecodeString(checksum); err != nil || len(decoded) != sha256.Size { + return errors.New("invalid archive SHA-256") + } + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + info, err := f.Stat() + if err != nil { + return err + } + uploader := manager.NewUploader(s.client, func(u *manager.Uploader) { + u.PartSize = 8 << 20 + u.Concurrency = 2 + u.LeavePartsOnError = true // Abort below with a fresh, bounded cleanup context. + u.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired + }) + input := &s3.PutObjectInput{ + Bucket: aws.String(s.bucket), Key: aws.String(key), Body: f, + ContentType: aws.String("application/zstd"), Metadata: map[string]string{"sha256": checksum}, + ServerSideEncryption: s.encryption, + } + if s.kmsKeyID != "" { + input.SSEKMSKeyId = aws.String(s.kmsKeyID) + } + result, err := uploader.Upload(ctx, input) + if err != nil { + uploadErr := fmt.Errorf("upload archive: %w", err) + var multipart manager.MultiUploadFailure + if errors.As(err, &multipart) { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + defer cancel() + _, cleanupErr := s.client.AbortMultipartUpload(cleanupCtx, &s3.AbortMultipartUploadInput{ + Bucket: aws.String(s.bucket), Key: aws.String(key), UploadId: aws.String(multipart.UploadID()), + }) + if cleanupErr != nil { + return errors.Join(uploadErr, fmt.Errorf("abort archive multipart upload: %w", cleanupErr)) + } + } + return uploadErr + } + if err := s.readVerified(ctx, key, io.Discard, checksum, info.Size(), true); err != nil { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + defer cancel() + // Versioned buckets require deleting the version just uploaded; an + // unversioned DELETE would only hide it behind a delete marker. + _, cleanupErr := s.client.DeleteObject(cleanupCtx, &s3.DeleteObjectInput{ + Bucket: aws.String(s.bucket), Key: aws.String(key), VersionId: result.VersionID, + }) + if cleanupErr != nil { + return errors.Join(err, fmt.Errorf("delete unverified archive: %w", cleanupErr)) + } + return err + } + return nil +} + +func (s *Store) readVerified(ctx context.Context, key string, out io.Writer, checksum string, expectedSize int64, requireEncryption bool) error { + if decoded, err := hex.DecodeString(checksum); err != nil || len(decoded) != sha256.Size { + return errors.New("invalid archive SHA-256") + } + if expectedSize < 0 { + return errors.New("invalid archive size") + } + object, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)}) + if err != nil { + return fmt.Errorf("inspect archive: %w", err) + } + if requireEncryption && (object.ServerSideEncryption != s.encryption || + (s.encryption == types.ServerSideEncryptionAwsKms && (aws.ToString(object.SSEKMSKeyId) == "" || + (s.kmsKeyID != "" && aws.ToString(object.SSEKMSKeyId) != s.kmsKeyID)))) { + return errors.New("remote archive did not confirm the requested server-side encryption; source data retained") + } + if object.ContentLength == nil || *object.ContentLength != expectedSize || aws.ToString(object.ETag) == "" { + return errors.New("remote archive size mismatch or missing ETag; source data retained") + } + // Commit only complete, validated chunks to the output and hash. A broken + // connection can then retry its chunk without duplicating bytes or restarting + // a multi-gigabyte read. IfMatch pins every request to the same object. + h := sha256.New() + for offset := int64(0); offset < expectedSize; { + end := offset + min(archiveReadChunkSize, expectedSize-offset) - 1 + data, err := s.readArchiveChunk(ctx, key, aws.ToString(object.ETag), offset, end, expectedSize) + if err != nil { + return err + } + n, err := out.Write(data) + if err != nil { + return err + } + if n != len(data) { + return io.ErrShortWrite + } + _, _ = h.Write(data) + offset += int64(len(data)) + } + if !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), checksum) { + return errors.New("remote archive size or SHA-256 mismatch; source data retained") + } + return nil +} + +const ( + archiveReadChunkSize = int64(8 << 20) + archiveReadAttempts = 5 +) + +func (s *Store) readArchiveChunk(ctx context.Context, key, etag string, start, end, total int64) ([]byte, error) { + var lastErr error + for attempt := 0; attempt < archiveReadAttempts; attempt++ { + if err := ctx.Err(); err != nil { + return nil, err + } + if attempt > 0 { + timer := time.NewTimer((250 * time.Millisecond) << (attempt - 1)) + select { + case <-ctx.Done(): + timer.Stop() + return nil, ctx.Err() + case <-timer.C: + } + } + data, retry, err := s.readArchiveChunkOnce(ctx, key, etag, start, end, total) + if err == nil { + return data, nil + } + if !retry { + return nil, err + } + lastErr = err + } + return nil, fmt.Errorf("read archive bytes %d-%d after %d attempts: %w", start, end, archiveReadAttempts, lastErr) +} + +func (s *Store) readArchiveChunkOnce(ctx context.Context, key, etag string, start, end, total int64) ([]byte, bool, error) { + requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + object, err := s.client.GetObject(requestCtx, &s3.GetObjectInput{ + Bucket: aws.String(s.bucket), Key: aws.String(key), IfMatch: aws.String(etag), + Range: aws.String(fmt.Sprintf("bytes=%d-%d", start, end)), + }, func(o *s3.Options) { + // This loop owns both HTTP and interrupted-body retries: at most five + // wire requests per chunk, rather than five times the SDK's attempts. + o.RetryMaxAttempts = 1 + }) + if err != nil { + var networkError net.Error + var responseError *awshttp.ResponseError + throttled := errors.As(err, &responseError) && responseError.HTTPStatusCode() == http.StatusTooManyRequests + shouldRetry := throttled || retry.NewStandard().IsErrorRetryable(err) || errors.As(err, &networkError) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, context.DeadlineExceeded) + return nil, shouldRetry, fmt.Errorf("read archive range: %w", err) + } + defer object.Body.Close() + want := end - start + 1 + if aws.ToString(object.ETag) != etag || aws.ToString(object.ContentRange) != fmt.Sprintf("bytes %d-%d/%d", start, end, total) || object.ContentLength == nil || *object.ContentLength != want { + return nil, false, errors.New("remote archive changed or returned an invalid byte range; source data retained") + } + data, err := io.ReadAll(io.LimitReader(object.Body, want+1)) + if err != nil { + return nil, true, err + } + if int64(len(data)) < want { + return nil, true, io.ErrUnexpectedEOF + } + if int64(len(data)) != want { + return nil, false, errors.New("remote archive range exceeds its declared size") + } + return data, false, nil +} + +func (s *Store) Download(ctx context.Context, uri, filename, checksum string, size int64) (err error) { + key, err := s.key(uri) + if err != nil { + return err + } + if size <= 0 { + return errors.New("invalid archive size") + } + f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + defer func() { + err = errors.Join(err, f.Close()) + if err != nil { + _ = os.Remove(filename) + } + }() + if err = s.readVerified(ctx, key, f, checksum, size, false); err != nil { + return err + } + return f.Sync() +} + +func (s *Store) Delete(ctx context.Context, uri string) error { + key, err := s.key(uri) + if err != nil { + return err + } + _, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.bucket), Key: aws.String(key)}) + return err +} diff --git a/archivestore/s3_test.go b/archivestore/s3_test.go new file mode 100644 index 0000000..84049e3 --- /dev/null +++ b/archivestore/s3_test.go @@ -0,0 +1,420 @@ +package archivestore + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" +) + +func TestS3RoundTripAndIntegrity(t *testing.T) { + for _, sse := range []string{"AES256", "aws:kms"} { + kms := "" + if sse == "aws:kms" { + kms = "arn:aws:kms:us-east-1:123456789012:key/test-key" + } + for _, size := range []int{1024, 10 << 20} { + t.Run(sse+"/"+strconv.Itoa(size), func(t *testing.T) { + var mu sync.Mutex + var object []byte + parts := map[int][]byte{} + corrupt, multipart := false, false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + q := r.URL.Query() + if (r.Method == "PUT" && !q.Has("partNumber")) || (r.Method == "POST" && q.Has("uploads")) { + if r.Header.Get("X-Amz-Server-Side-Encryption") != sse || r.Header.Get("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id") != kms { + t.Error("upload did not explicitly request the configured encryption") + } + } + if r.Method == "HEAD" { + if r.Header.Get("X-Amz-Server-Side-Encryption") != "" { + t.Error("encryption write header leaked into HEAD") + } + w.Header().Set("X-Amz-Server-Side-Encryption", sse) + if kms != "" { + w.Header().Set("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", kms) + } + } + w.Header().Set("ETag", `"test-etag"`) + switch { + case r.Method == "POST" && q.Has("uploads"): + multipart = true + fmt.Fprint(w, `test-upload`) + case r.Method == "PUT" && q.Has("partNumber"): + n, _ := strconv.Atoi(q.Get("partNumber")) + parts[n], _ = io.ReadAll(r.Body) + case r.Method == "POST" && q.Has("uploadId"): + for i := 1; i <= len(parts); i++ { + object = append(object, parts[i]...) + } + fmt.Fprint(w, `test-etag`) + case r.Method == "PUT": + object, _ = io.ReadAll(r.Body) + case r.Method == "HEAD": + w.Header().Set("Content-Length", strconv.Itoa(len(object))) + case r.Method == "GET": + data := object + if corrupt { + data = bytes.Clone(object) + data[0] ^= 0xff + } + serveArchiveRange(t, w, r, data) + case r.Method == "DELETE": + object = nil + w.WriteHeader(204) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL) + w.WriteHeader(400) + } + })) + defer srv.Close() + store, err := New(Config{Endpoint: srv.URL, Bucket: "test-bucket", Prefix: "test/tasks", AccessKey: "test", SecretKey: "test", PathStyle: true, SSE: sse, KMSKeyID: kms}) + if err != nil { + t.Fatal(err) + } + data := bytes.Repeat([]byte{0x42}, size) + h := sha256.Sum256(data) + checksum := hex.EncodeToString(h[:]) + root := t.TempDir() + source := filepath.Join(root, "source") + if err := os.WriteFile(source, data, 0600); err != nil { + t.Fatal(err) + } + uri := store.URI(1, 2, checksum) + ctx := context.Background() + if err := store.Upload(ctx, uri, source, checksum); err != nil { + t.Fatal(err) + } + if multipart != (size > 8<<20) { + t.Fatalf("multipart=%v size=%d", multipart, size) + } + dest := filepath.Join(root, "download") + if err := store.Download(ctx, uri, dest, checksum, int64(size)); err != nil { + t.Fatal(err) + } + got, _ := os.ReadFile(dest) + if !bytes.Equal(got, data) { + t.Fatal("download differs") + } + mu.Lock() + corrupt = true + mu.Unlock() + bad := filepath.Join(root, "bad") + if err := store.Download(ctx, uri, bad, checksum, int64(size)); err == nil { + t.Fatal("accepted corrupt object") + } + if _, err := os.Stat(bad); !os.IsNotExist(err) { + t.Fatal("left corrupt download") + } + if err := store.Upload(ctx, uri, source, checksum); err == nil { + t.Fatal("upload accepted failed readback") + } + if err := store.Delete(ctx, uri); err != nil { + t.Fatal(err) + } + }) + } + } +} + +func serveArchiveRange(t *testing.T, w http.ResponseWriter, r *http.Request, data []byte) { + t.Helper() + var start, end int64 + if n, err := fmt.Sscanf(r.Header.Get("Range"), "bytes=%d-%d", &start, &end); err != nil || n != 2 || start < 0 || end < start || end >= int64(len(data)) { + t.Errorf("invalid range %q", r.Header.Get("Range")) + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + return + } + if r.Header.Get("If-Match") != `"test-etag"` { + t.Errorf("missing object version condition: %q", r.Header.Get("If-Match")) + w.WriteHeader(http.StatusPreconditionFailed) + return + } + w.Header().Set("ETag", `"test-etag"`) + w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10)) + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data))) + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write(data[start : end+1]) +} + +func TestS3ReadbackRetriesInterruptedRange(t *testing.T) { + data := append(bytes.Repeat([]byte{0x42}, int(archiveReadChunkSize)), bytes.Repeat([]byte{0x73}, 1024)...) + var mu sync.Mutex + var ranges []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + w.Header().Set("ETag", `"test-etag"`) + if r.Method == "HEAD" { + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + return + } + ranges = append(ranges, r.Header.Get("Range")) + if len(ranges) == 2 { + w.Header().Set("Content-Length", strconv.FormatInt(int64(len(data))-archiveReadChunkSize, 10)) + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", archiveReadChunkSize, len(data)-1, len(data))) + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write(data[archiveReadChunkSize : archiveReadChunkSize+128]) // Close during a later chunk. + return + } + serveArchiveRange(t, w, r, data) + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + h := sha256.Sum256(data) + checksum := hex.EncodeToString(h[:]) + dest := filepath.Join(t.TempDir(), "archive") + if err := store.Download(context.Background(), store.URI(1, 2, checksum), dest, checksum, int64(len(data))); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(dest) + if err != nil || !bytes.Equal(got, data) { + t.Fatalf("retried download differs: %v", err) + } + mu.Lock() + defer mu.Unlock() + if len(ranges) != 3 || ranges[1] != ranges[2] || ranges[0] != fmt.Sprintf("bytes=0-%d", archiveReadChunkSize-1) || ranges[2] != fmt.Sprintf("bytes=%d-%d", archiveReadChunkSize, len(data)-1) { + t.Fatalf("retry did not stay within the interrupted range: %v", ranges) + } +} + +func testRangeStore(t *testing.T, endpoint string) *Store { + t.Helper() + s, err := New(Config{Endpoint: endpoint, Bucket: "test-bucket", Prefix: "test/tasks", AccessKey: "test", SecretKey: "test", PathStyle: true}) + if err != nil { + t.Fatal(err) + } + return s +} + +func TestS3ReadbackRejectsInvalidRangesAndExhaustedRetries(t *testing.T) { + for _, mode := range []string{"ignored-range", "changed-etag", "changed-object", "truncated"} { + t.Run(mode, func(t *testing.T) { + data := bytes.Repeat([]byte{0x42}, 1024) + var mu sync.Mutex + gets := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + w.Header().Set("ETag", `"test-etag"`) + if r.Method == "HEAD" { + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + return + } + gets++ + if mode == "changed-object" { + w.WriteHeader(http.StatusPreconditionFailed) + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + if mode == "ignored-range" { + _, _ = w.Write(data) + return + } + if mode == "changed-etag" { + w.Header().Set("ETag", `"different-object"`) + } + w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(data)-1, len(data))) + w.WriteHeader(http.StatusPartialContent) + if mode == "truncated" { + _, _ = w.Write(data[:128]) + } else { + _, _ = w.Write(data) + } + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + h := sha256.Sum256(data) + checksum := hex.EncodeToString(h[:]) + dest := filepath.Join(t.TempDir(), "archive") + if err := store.Download(context.Background(), store.URI(1, 2, checksum), dest, checksum, int64(len(data))); err == nil { + t.Fatal("accepted invalid or incomplete readback") + } + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatal("left a failed download on disk") + } + mu.Lock() + defer mu.Unlock() + want := 1 + if mode == "truncated" { + want = archiveReadAttempts + } + if gets != want { + t.Fatalf("GET count %d, want %d", gets, want) + } + }) + } +} + +type failedArchiveWriter struct{ err error } + +func (w failedArchiveWriter) Write([]byte) (int, error) { return 0, w.err } + +func TestS3ReadbackPropagatesOutputFailure(t *testing.T) { + data := []byte("test archive") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"test-etag"`) + if r.Method == "HEAD" { + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + return + } + serveArchiveRange(t, w, r, data) + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + h := sha256.Sum256(data) + outputError := errors.New("output disk full") + err := store.readVerified(context.Background(), "test/tasks/archive", failedArchiveWriter{outputError}, hex.EncodeToString(h[:]), int64(len(data)), false) + if !errors.Is(err, outputError) { + t.Fatalf("lost output error: %v", err) + } +} + +func TestS3ReadbackStopsOnCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + data := bytes.Repeat([]byte{0x42}, 1024) + gets := make(chan struct{}, archiveReadAttempts+1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"test-etag"`) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + if r.Method == "HEAD" { + return + } + gets <- struct{}{} + w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(data)-1, len(data))) + w.WriteHeader(http.StatusPartialContent) + _, _ = w.Write(data[:128]) + w.(http.Flusher).Flush() + cancel() + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + h := sha256.Sum256(data) + checksum := hex.EncodeToString(h[:]) + dest := filepath.Join(t.TempDir(), "archive") + err := store.Download(ctx, store.URI(1, 2, checksum), dest, checksum, int64(len(data))) + if !errors.Is(err, context.Canceled) || len(gets) != 1 { + t.Fatalf("cancellation was not honored: error=%v GETs=%d", err, len(gets)) + } + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatal("left a cancelled download on disk") + } +} + +func TestS3RejectsForeignLocations(t *testing.T) { + s, err := New(Config{Endpoint: "https://sfo3.digitaloceanspaces.com", Bucket: "allowed", Prefix: "archives/tasks", AccessKey: "test", SecretKey: "test"}) + if err != nil { + t.Fatal(err) + } + for _, uri := range []string{"s3://other/archives/tasks/a", "s3://allowed/archives/other/a", "s3://allowed/archives/tasks/../a", "s3://allowed/archives/tasks/%2e%2e/a", "s3://allowed/archives/tasks/a?secret=x", "s3://user@allowed/archives/tasks/a", "file:///etc/passwd"} { + if err := s.Validate(uri); err == nil { + t.Errorf("accepted %s", uri) + } + } + var absent *Store + if absent.Validate("s3://allowed/archives/tasks/a") == nil { + t.Fatal("missing config accepted") + } +} + +func TestS3UploadRejectsUnconfirmedEncryption(t *testing.T) { + for _, mode := range []string{"missing", "different", "kms-without-key"} { + t.Run(mode, func(t *testing.T) { + data := []byte("private archive") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "PUT": + _, _ = io.Copy(io.Discard, r.Body) + case "DELETE": + w.WriteHeader(204) + case "HEAD": + w.Header().Set("ETag", `"test-etag"`) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + if mode != "missing" { + w.Header().Set("X-Amz-Server-Side-Encryption", "aws:kms") + } + default: + t.Errorf("content must not be accepted before encryption confirmation: %s", r.Method) + w.WriteHeader(400) + } + })) + defer srv.Close() + c := Config{Endpoint: srv.URL, Bucket: "test", Prefix: "tasks", AccessKey: "test", SecretKey: "test", PathStyle: true} + if mode == "kms-without-key" { + c.SSE = "aws:kms" + } + store, err := New(c) + if err != nil { + t.Fatal(err) + } + filename := filepath.Join(t.TempDir(), "source") + if err := os.WriteFile(filename, data, 0600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(data) + checksum := hex.EncodeToString(sum[:]) + if err := store.Upload(context.Background(), store.URI(1, 2, checksum), filename, checksum); err == nil || !strings.Contains(err.Error(), "encryption") { + t.Fatalf("unconfirmed encryption accepted: %v", err) + } + if got, err := os.ReadFile(filename); err != nil || !bytes.Equal(got, data) { + t.Fatal("source was not retained", err) + } + }) + } +} + +func TestS3MultipartFailureAbortsUpload(t *testing.T) { + var aborted atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + switch { + case r.Method == "POST" && q.Has("uploads"): + if r.Header.Get("X-Amz-Server-Side-Encryption") != "AES256" { + t.Error("multipart encryption missing") + } + fmt.Fprint(w, `failed-upload`) + case r.Method == "PUT" && q.Has("partNumber"): + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(403) + case r.Method == "DELETE" && q.Get("uploadId") == "failed-upload": + aborted.Store(true) + w.WriteHeader(204) + default: + t.Errorf("unexpected failed-upload request: %s", r.Method) + w.WriteHeader(400) + } + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + data := bytes.Repeat([]byte("x"), 9<<20) + checksum := sha256.Sum256(data) + sum := hex.EncodeToString(checksum[:]) + filename := filepath.Join(t.TempDir(), "source") + if err := os.WriteFile(filename, data, 0600); err != nil { + t.Fatal(err) + } + if err := store.Upload(context.Background(), store.URI(1, 2, sum), filename, sum); err == nil { + t.Fatal("failed part accepted") + } + if !aborted.Load() { + t.Fatal("failed multipart upload was not aborted") + } + if info, err := os.Stat(filename); err != nil || info.Size() != int64(len(data)) { + t.Fatal("source was not retained", err) + } +} diff --git a/archivestore/safety_test.go b/archivestore/safety_test.go new file mode 100644 index 0000000..9afe47b --- /dev/null +++ b/archivestore/safety_test.go @@ -0,0 +1,231 @@ +package archivestore + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/pem" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" +) + +func archiveSource(t *testing.T, data []byte) (string, string) { + t.Helper() + filename := filepath.Join(t.TempDir(), "source") + if err := os.WriteFile(filename, data, 0600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(data) + return filename, hex.EncodeToString(sum[:]) +} + +func TestS3VerificationFailureCleansUploadedVersion(t *testing.T) { + for _, failure := range []string{"wrong-kms", "checksum", "cancelled", "delete-denied"} { + t.Run(failure, func(t *testing.T) { + data := []byte("private archive") + source, checksum := archiveSource(t, data) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var present, deleted atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case "PUT": + _, _ = io.Copy(io.Discard, r.Body) + present.Store(true) + w.Header().Set("X-Amz-Version-Id", "uploaded-version") + case "HEAD": + w.Header().Set("ETag", `"test-etag"`) + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Header().Set("X-Amz-Server-Side-Encryption", "aws:kms") + kms := "arn:aws:kms:us-east-1:123456789012:key/expected" + if failure == "wrong-kms" { + kms = "arn:aws:kms:us-east-1:123456789012:key/different" + } + w.Header().Set("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", kms) + if failure == "cancelled" { + cancel() + } + case "GET": + corrupt := bytes.Clone(data) + corrupt[0] ^= 0xff + serveArchiveRange(t, w, r, corrupt) + case "DELETE": + if r.URL.Query().Get("versionId") != "uploaded-version" { + t.Error("cleanup did not target uploaded version") + } + deleted.Store(true) + if failure == "delete-denied" { + w.WriteHeader(403) + return + } + present.Store(false) + w.WriteHeader(204) + default: + t.Errorf("unexpected request %s", r.Method) + w.WriteHeader(400) + } + })) + defer srv.Close() + store, err := New(Config{Endpoint: srv.URL, Bucket: "test", AccessKey: "test", SecretKey: "test", PathStyle: true, + SSE: "aws:kms", KMSKeyID: "arn:aws:kms:us-east-1:123456789012:key/expected"}) + if err != nil { + t.Fatal(err) + } + err = store.Upload(ctx, store.URI(1, 2, checksum), source, checksum) + if err == nil { + t.Fatal("accepted failed verification") + } + if failure == "wrong-kms" && !strings.Contains(err.Error(), "encryption") { + t.Fatal(err) + } + if failure == "cancelled" && !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + if failure == "delete-denied" && (!strings.Contains(err.Error(), "SHA-256") || !strings.Contains(err.Error(), "delete unverified archive")) { + t.Fatalf("verification and cleanup errors must both survive: %v", err) + } + if !deleted.Load() || present.Load() != (failure == "delete-denied") { + t.Fatal("unverified object cleanup was not attempted/completed") + } + if got, readErr := os.ReadFile(source); readErr != nil || !bytes.Equal(got, data) { + t.Fatal("source changed", readErr) + } + }) + } +} + +func TestS3CancelledMultipartAbortsWithFreshContext(t *testing.T) { + for _, denyAbort := range []bool{false, true} { + t.Run(strconv.FormatBool(denyAbort), func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var aborted atomic.Bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + switch { + case r.Method == "POST" && q.Has("uploads"): + fmt.Fprint(w, `cancelled-upload`) + case r.Method == "PUT" && q.Has("partNumber"): + cancel() + _, _ = io.Copy(io.Discard, r.Body) + w.WriteHeader(403) + case r.Method == "DELETE" && q.Get("uploadId") == "cancelled-upload": + aborted.Store(true) + if denyAbort { + w.WriteHeader(403) + } else { + w.WriteHeader(204) + } + default: + t.Errorf("unexpected request %s", r.Method) + w.WriteHeader(400) + } + })) + defer srv.Close() + data := bytes.Repeat([]byte("x"), 9<<20) + source, sum := archiveSource(t, data) + store := testRangeStore(t, srv.URL) + err := store.Upload(ctx, store.URI(1, 2, sum), source, sum) + if !errors.Is(err, context.Canceled) || !aborted.Load() { + t.Fatalf("cancelled upload not aborted: %v", err) + } + if denyAbort && !strings.Contains(err.Error(), "abort archive multipart upload") { + t.Fatalf("cleanup failure lost: %v", err) + } + if got, readErr := os.ReadFile(source); readErr != nil || !bytes.Equal(got, data) { + t.Fatal("source changed", readErr) + } + }) + } +} + +func TestS3SignedRequestsNeverFollowRedirects(t *testing.T) { + var reached atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached.Add(1); w.WriteHeader(204) })) + defer target.Close() + for _, status := range []int{301, 302, 303, 307, 308} { + t.Run(strconv.Itoa(status), func(t *testing.T) { + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "" || r.Header.Get("X-Amz-Security-Token") != "fixture-session" { + t.Error("fixture request must be signed with session credentials") + } + w.Header().Set("Location", target.URL+"/redirected") + w.WriteHeader(status) + })) + defer origin.Close() + store, err := New(Config{Endpoint: origin.URL, Bucket: "test", AccessKey: "test", SecretKey: "test", SessionToken: "fixture-session", PathStyle: true}) + if err != nil { + t.Fatal(err) + } + if err := store.Delete(context.Background(), store.URI(1, 2, "test")); err == nil { + t.Fatal("redirect accepted") + } + if reached.Load() != 0 { + t.Fatal("signed request followed redirect") + } + }) + } +} + +func TestS3CustomCABundleForBothCredentialModes(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })) + defer srv.Close() + for _, explicit := range []bool{false, true} { + t.Run(strconv.FormatBool(explicit), func(t *testing.T) { + isolateAWSCredentials(t) + ca := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("AWS_CA_BUNDLE", ca) + c := Config{Endpoint: srv.URL, Bucket: "test", PathStyle: true} + if explicit { + c.AccessKey, c.SecretKey = "fixture", "fixture" + } else { + t.Setenv("AWS_ACCESS_KEY_ID", "fixture") + t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture") + } + store, err := New(c) + if err != nil { + t.Fatal(err) + } + if err := store.Delete(context.Background(), store.URI(1, 2, "test")); err != nil { + t.Fatalf("configured CA not used: %v", err) + } + }) + } +} + +func TestS3RangeRetriesHaveOneWireAttemptEach(t *testing.T) { + for _, status := range []int{403, 429, 503} { + t.Run(strconv.Itoa(status), func(t *testing.T) { + var gets atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gets.Add(1) + w.WriteHeader(status) + })) + defer srv.Close() + store := testRangeStore(t, srv.URL) + if _, err := store.readArchiveChunk(context.Background(), "key", `"etag"`, 0, 9, 10); err == nil { + t.Fatal("failed request accepted") + } + want := int32(archiveReadAttempts) + if status == 403 { + want = 1 + } + if got := gets.Load(); got != want { + t.Fatalf("wire requests=%d want=%d", got, want) + } + }) + } +} diff --git a/cmd/artex-archive-check/main.go b/cmd/artex-archive-check/main.go new file mode 100644 index 0000000..af0efd9 --- /dev/null +++ b/cmd/artex-archive-check/main.go @@ -0,0 +1,64 @@ +// artex-archive-check tests the configured object store without touching tasks. +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "log" + "os" + "path/filepath" + "time" + + "github.com/Autumn-27/artex/archivestore" +) + +func main() { + if err := check(); err != nil { + log.Fatal(err) + } +} + +func check() error { + s, err := archivestore.FromEnv() + if err != nil { + return err + } + if s == nil { + return fmt.Errorf("S3 archive storage is not configured") + } + dir, err := os.MkdirTemp("", "artex-archive-check-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + data := []byte("ARTEX object storage connectivity check " + time.Now().UTC().Format(time.RFC3339Nano)) + h := sha256.Sum256(data) + checksum := hex.EncodeToString(h[:]) + uri := s.URI(0, time.Now().UnixNano(), checksum) + file := filepath.Join(dir, "check") + if err := os.WriteFile(file, data, 0600); err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if err := s.Delete(cleanup, uri); err != nil { + log.Printf("test object cleanup failed for %s: %v", uri, err) + } + }() + if err := s.Upload(ctx, uri, file, checksum); err != nil { + return err + } + if err := s.Download(ctx, uri, filepath.Join(dir, "download"), checksum, int64(len(data))); err != nil { + return err + } + if err := s.Delete(ctx, uri); err != nil { + return err + } + fmt.Println("S3 upload, full SHA-256 verification, download and delete passed") + return nil +} diff --git a/config/config.go b/config/config.go index b966429..d17cb9a 100644 --- a/config/config.go +++ b/config/config.go @@ -10,6 +10,7 @@ import ( "net/url" "os" "path/filepath" + "regexp" "strconv" "strings" ) @@ -209,16 +210,30 @@ func (d Database) buildDSN() string { return u.String() } -// String is a redacted view of the resolved DSN (password masked) for logging. +// libpqPassword matches a libpq keyword DSN password field, including quoted +// values. pgx accepts this form as well as the URL form. +var libpqPassword = regexp.MustCompile(`(?i)\b(password)\s*=\s*(?:'[^']*'|"[^"]*"|\S*)`) + +// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo +// passwords, `?password=` query values, and libpq `password=` keywords. +// Unrecognised input still runs the keyword mask so a parse failure cannot +// print the secret. func Redact(dsn string) string { - u, err := url.Parse(dsn) - if err != nil { + if dsn == "" { return dsn } - if u.User != nil { - if _, hasPw := u.User.Password(); hasPw { - u.User = url.UserPassword(u.User.Username(), "****") + if u, err := url.Parse(dsn); err == nil && (u.Scheme == "postgres" || u.Scheme == "postgresql") { + if u.User != nil { + if _, hasPw := u.User.Password(); hasPw { + u.User = url.UserPassword(u.User.Username(), "****") + } } + q := u.Query() + if q.Has("password") { + q.Set("password", "****") + u.RawQuery = q.Encode() + } + return u.String() } - return fmt.Sprintf("%s", u.String()) + return libpqPassword.ReplaceAllString(dsn, `${1}=****`) } diff --git a/config/config_test.go b/config/config_test.go index e30c7bc..7be1683 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -44,6 +44,22 @@ func TestPostgresDSNPrecedence(t *testing.T) { // A config file that exists but is not valid JSON must fail loudly, not run with // defaults (or report "no database config") as if the file were absent. +func TestRedactMasksEveryDSNPasswordForm(t *testing.T) { + cases := []struct{ in, secret string }{ + {"postgres://u:secret@localhost:5432/d?sslmode=require", "secret"}, + {"postgresql://localhost/d?password=secret&sslmode=require", "secret"}, + {"host=localhost user=u password=secret dbname=d", "secret"}, + {"host=localhost password='p a ss' dbname=d", "p a ss"}, + {"not a dsn password=stillsecret", "stillsecret"}, + } + for _, c := range cases { + got := Redact(c.in) + if strings.Contains(got, c.secret) { + t.Errorf("Redact(%q)=%q still contains %q", c.in, got, c.secret) + } + } +} + func TestMalformedConfigIsAnError(t *testing.T) { cfgPath := filepath.Join(t.TempDir(), "config.json") // What install.sh used to write for a password containing a double quote. diff --git a/db/asset_dsl.go b/db/asset_dsl.go index 8d2b633..a1f0ab5 100644 --- a/db/asset_dsl.go +++ b/db/asset_dsl.go @@ -136,9 +136,15 @@ func tokenize(s string) ([]tok, error) { // and_expr = atom (AND atom)* // atom = FIELD | BARE | '(' expr ')' +const ( + dslMaxLen = 4096 + dslMaxDepth = 32 +) + type dslParser struct { tokens []tok pos int + depth int } func (p *dslParser) peek() tok { @@ -201,8 +207,13 @@ func (p *dslParser) parseAtom() (*astNode, error) { p.consume() return leafNode(*t.expr), nil case tkLP: + if p.depth >= dslMaxDepth { + return nil, fmt.Errorf("DSL syntax error: nested parentheses too deep") + } + p.depth++ p.consume() node, err := p.parseOr() + p.depth-- if err != nil { return nil, err } @@ -234,6 +245,9 @@ func ParseDSL(s string) (*astNode, error) { if strings.TrimSpace(s) == "" { return nil, nil } + if len(s) > dslMaxLen { + return nil, fmt.Errorf("DSL query is too long") + } tokens, err := tokenize(s) if err != nil { return nil, err @@ -288,7 +302,11 @@ func (b *whereBuilder) build(node *astNode) (string, error) { } parts = append(parts, "("+clause+")") } - return strings.Join(parts, " OR "), nil + // The whole disjunction must be parenthesised: callers append their own + // clauses with AND (the task scope in QueryDSLInScope, the type filter), + // and AND binds tighter than OR, so "(a) OR (b) AND scope" would let the + // first branch escape the scope. + return "(" + strings.Join(parts, " OR ") + ")", nil case "leaf": return b.buildLeaf(*node.expr) } diff --git a/db/asset_dsl_limit_test.go b/db/asset_dsl_limit_test.go new file mode 100644 index 0000000..bea4883 --- /dev/null +++ b/db/asset_dsl_limit_test.go @@ -0,0 +1,23 @@ +package db + +import ( + "strings" + "testing" +) + +func TestParseDSLRejectsDeepNesting(t *testing.T) { + deep := strings.Repeat("(", dslMaxDepth+1) + "a" + strings.Repeat(")", dslMaxDepth+1) + if _, err := ParseDSL(deep); err == nil { + t.Fatal("deep nesting accepted") + } + ok := strings.Repeat("(", dslMaxDepth) + "a" + strings.Repeat(")", dslMaxDepth) + if _, err := ParseDSL(ok); err != nil { + t.Fatalf("depth %d refused: %v", dslMaxDepth, err) + } +} + +func TestParseDSLRejectsOversize(t *testing.T) { + if _, err := ParseDSL(strings.Repeat("a", dslMaxLen+1)); err == nil { + t.Fatal("oversize query accepted") + } +} diff --git a/db/asset_dsl_or_scope_test.go b/db/asset_dsl_or_scope_test.go new file mode 100644 index 0000000..9e06d6b --- /dev/null +++ b/db/asset_dsl_or_scope_test.go @@ -0,0 +1,86 @@ +package db + +import ( + "fmt" + "strings" + "testing" + "time" +) + +// A top-level OR must be parenthesised as a whole. QueryDSLInScope appends the +// task-scope clause with AND, and AND binds tighter than OR, so an unparenthesised +// disjunction lets the first branch return rows from outside the task scope. +func TestBuildDSLWhereWrapsOr(t *testing.T) { + node, err := ParseDSL("domain=alpha OR domain=beta") + if err != nil { + t.Fatal(err) + } + where, _, err := buildDSLWhereBase(node, 0) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(where, "((") || !strings.HasSuffix(where, "))") { + t.Fatalf("compiled to %q: the whole OR group must be parenthesised", where) + } +} + +// TestQueryDSLInScopeOrDoesNotEscape is the behavioural form: an OR query whose +// first branch matches every row must not return an asset outside the task scope. +func TestQueryDSLInScopeOrDoesNotEscape(t *testing.T) { + d, assets, _ := testSetup(t) + t.Cleanup(func() { d.Close() }) + + task, err := d.CreateTask("or scope", "goal", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cleanupErr(t, "task", d.DeleteTask(task.ID)) }) + + stamp := time.Now().UnixNano() + root := fmt.Sprintf("in%d.invalid", stamp) + out := fmt.Sprintf("x%d.invalid", stamp) + marker := fmt.Sprintf("or%d", stamp) + + if err := assets.upsertTaskScope(TaskScope{TaskID: task.ID, Kind: "root_domain", Domain: root}); err != nil { + t.Fatalf("seed scope: %v", err) + } + + var inID, outID int64 + for _, r := range []struct { + domain, root string + id *int64 + }{ + {"a." + root, root, &inID}, + {out, out, &outID}, + } { + if err := d.QueryRow(`INSERT INTO assets(type,domain,root_domain,page_title,last_seen) + VALUES ('subdomain',$1,$2,$3,now()) RETURNING id`, r.domain, r.root, marker).Scan(r.id); err != nil { + t.Fatalf("insert %s: %v", r.domain, err) + } + } + t.Cleanup(func() { + cleanupExec(t, d, `DELETE FROM assets WHERE id=ANY($1::bigint[])`, []int64{inID, outID}) + }) + + // The bare marker matches both rows; the second branch names the out-of-scope + // host. Only the in-scope row may come back. + got, err := assets.QueryDSLInScope(marker+" OR domain="+out, "", task.ID, 50, 0) + if err != nil { + t.Fatal(err) + } + var sawIn, sawOut bool + for _, a := range got { + switch a.ID { + case inID: + sawIn = true + case outID: + sawOut = true + } + } + if !sawIn { + t.Fatalf("in-scope asset %d missing from %+v", inID, got) + } + if sawOut { + t.Fatalf("out-of-scope asset %d leaked through an OR query", outID) + } +} diff --git a/egress/egress.go b/egress/egress.go index e64e474..a21390c 100644 --- a/egress/egress.go +++ b/egress/egress.go @@ -250,8 +250,15 @@ func (g *Governor) reserve(h *hostState) time.Duration { // asks for more than MaxDelay. func (g *Governor) backoff(h http.Header, attempt int) (d time.Duration, ok bool) { v := strings.TrimSpace(h.Get("Retry-After")) - if n, err := strconv.Atoi(v); err == nil && n >= 0 { - return time.Duration(n) * time.Second, time.Duration(n)*time.Second <= g.p.MaxDelay + if n, err := strconv.ParseInt(v, 10, 64); err == nil && n >= 0 { + maxSec := int64(g.p.MaxDelay / time.Second) + if maxSec < 0 { + maxSec = 0 + } + if n > maxSec { + return 0, false + } + return time.Duration(n) * time.Second, true } if t, err := http.ParseTime(v); err == nil { return max(time.Until(t), 0), time.Until(t) <= g.p.MaxDelay diff --git a/egress/egress_test.go b/egress/egress_test.go index 11a16ec..55424e5 100644 --- a/egress/egress_test.go +++ b/egress/egress_test.go @@ -145,6 +145,10 @@ func TestBackoff(t *testing.T) { if d, ok := g.backoff(h, 0); !ok || d <= 0 || d > 2*time.Second { t.Fatalf("HTTP-date Retry-After: %s, %v", d, ok) } + // A huge second count used to wrap Duration and look like an immediate retry. + if d, ok := g.backoff(http.Header{"Retry-After": {"9223372036854775807"}}, 0); ok || d != 0 { + t.Fatalf("overflow Retry-After: %s %v, want refuse", d, ok) + } } func TestDedupeAndCache(t *testing.T) { diff --git a/go.mod b/go.mod index 8160b04..353f837 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,11 @@ go 1.26.10 require ( github.com/Autumn-27/norma v0.4.11 + github.com/aws/aws-sdk-go-v2 v1.47.5 + github.com/aws/aws-sdk-go-v2/config v1.33.13 + github.com/aws/aws-sdk-go-v2/credentials v1.20.13 + github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19 + 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 @@ -22,6 +27,20 @@ require ( require ( github.com/andybalholm/brotli v1.2.1 // indirect github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect + github.com/aws/smithy-go v1.28.7 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/creack/pty v1.1.24 // indirect github.com/dustin/go-humanize v1.0.1 // indirect diff --git a/go.sum b/go.sum index de01417..a950b0c 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,44 @@ github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eT github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/aws/aws-sdk-go-v2 v1.47.5 h1:5yA+A+BiXbDq1ZLbYwPViwhEGDMdR0MEhL8Jh2LnLS4= +github.com/aws/aws-sdk-go-v2 v1.47.5/go.mod h1:iNIkogrRvFwm+1OQIUOP2lPBtlXZboOIUWiCa+pHEMw= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25 h1:MW0Iql1SOTgQPj8mCxrU/eH/K/AIDWi08ItOsXaWRLU= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.25/go.mod h1:+ucVYmHYB3JqVueY0E1RHahdXAnKQbIHqybSbvOUbOM= +github.com/aws/aws-sdk-go-v2/config v1.33.13 h1:u52x6ISQOx172tpwM0VRxhJzEsTJYpMcEYUGM2A1wrw= +github.com/aws/aws-sdk-go-v2/config v1.33.13/go.mod h1:/ixtz6XPHb42zekjQ0LqD9XjTpTysNWhIGwufY1OzI4= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13 h1:j4z41OtspmQ3ftQycaDunJ26b69a9SHfaSVUPqgRv8k= +github.com/aws/aws-sdk-go-v2/credentials v1.20.13/go.mod h1:SgPA1oS3b+dlMxZb618jDmGNscpXSCaxz15igS52OlE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5 h1:iXjy2SFhGYNB1jWZBhQqq8HbhsbPF23w+/zbMvPXsTg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.5/go.mod h1:k0RUiBnyXU0AXRJ9tJmY2jQke6XUIX2PNVnWtvgaPtc= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19 h1:+JWfo9Mkg5HWwDwnpRPu7WNiiyEmiQRTaNSFsZ/1KIY= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.23.19/go.mod h1:l4/tI+TfymypMqq2oRCkhMAB7Gi7nlt5JaoUUz+cUbI= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8 h1:gzIWc3DTPfPbWKrQnmL6BV6WD7NPD1htxzgdk/bQ/Z4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.8/go.mod h1:vvUA5cDAZWGo4R14FZPZfXfJCmgsafOWEq78Kg0D+ug= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8 h1:PWv+vG8aCLS8qd+HPdYhK7Vees90aKHWFFQ1AGYD/8E= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.8/go.mod h1:xxPZEpflYHJA12366ZGyq66z9dHPCoeCIu99Jck+MPw= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8 h1:WOp5De9iWdEHDPh2Kb0tBP3vGBm/dVAuRGh4a4tqduo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.8/go.mod h1:z8W8YgfhbWl62XqcTtK+CxPrE+iHGRVUOtrrbIOp7ZY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23 h1:MCIR6iZaCKO4UE0hUvoWWLI6JVjppopV64JfAJaMjng= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.23/go.mod h1:pphWFS+z0MmIPivj8c/6bATd1Z+Av7Ust75DPdEFsPA= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9 h1:GACgECI422Xt5n4Pojr3O0aocPv8lfH4PJe2Aon5Wv8= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.9/go.mod h1:lPfnRkHpn1qWZJLbVEw10rIqSuCee1pNQTyGkUjAYh8= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8 h1:+PMpWlJYOn2tm7sm6OZ/ZLd4jStl17T7wjNapd1Rczs= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.8/go.mod h1:cnG3xZLGQL4c/bt8pjdzlFtZsW7epBBuNS04a5xMjdo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 h1:RS1Wt+K0r4X0ci9Vf4JYTUfHzsQihYA2LgGJeEneKpk= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8/go.mod h1:adMnTy5kyoUW86jhXnGSVc/mvMQI4GZd1qYWMeaS8M8= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 h1:to7+Vr3rLkpYRwVKJ5QRriI0eE306vrVN/6TnVHgxvY= +github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6/go.mod h1:Jc89ASa2k7HMAskj3bSnt8bf+k+p2IApzkoXnEjkgUw= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1 h1:WZLC+k/CZx11kZGQDqu9mpA8yhiXGX2I//jhuJE1FDo= +github.com/aws/aws-sdk-go-v2/service/signin v1.12.1/go.mod h1:wxAk0D2oVBSjuXEIzvcKxTZfM90zticdAbh/VD42L0Y= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1 h1:4VB/dnDo7pmXSLQMszSoBzWndENuc7mzwTpD6lQn77A= +github.com/aws/aws-sdk-go-v2/service/sso v1.39.1/go.mod h1:UGsEYgWz4Gi+46vDQ5zkFLqUgJziyOE2SXjZjgmfmHc= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 h1:w8yui2ZqdHmGwVBDGvazoIvKw/DnLENBLkYnN8q8iqo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1/go.mod h1:gJSdIY6YUzDvqQLcMtPVZgBRHrFwzHryvpE8Igzbxps= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 h1:BVjKrtRUtSYKztBCCfE1oAB+d3ViKcW2cKZfserOqMQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.51.6/go.mod h1:eSukFLeLkPMm+1OxDR+F0joauZdyBkF47Ow7MqjZiJw= +github.com/aws/smithy-go v1.28.7 h1:h/n1SHrwVtaDYLz8mR1/Kq4Xh4RaFbFW7bOYckg9mfE= +github.com/aws/smithy-go v1.28.7/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= diff --git a/guard/argv_test.go b/guard/argv_test.go index 90541a9..a5b5d3e 100644 --- a/guard/argv_test.go +++ b/guard/argv_test.go @@ -15,12 +15,12 @@ import ( func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) { ic := intercept.New(nil) ic.SetRulesForTest([]db.InterceptRule{ - {ID: 1, Name: "no force push", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "string", + {ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "string", Pattern: "--force", Action: "deny", Message: "force push is forbidden"}, {ID: 2, Name: "argv allow curl", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["curl"]`, Action: "allow"}, - {ID: 3, Name: "argv allow git push", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv", - Pattern: `["git","push"]`, Action: "allow"}, + {ID: 3, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv", + Pattern: `["nmap"]`, Action: "allow"}, }) g := NewWithInterceptor(ic) gate := &fakeGate{t: t, check: unpinnedOnce, request: func(int, []intercept.TargetRequest, *intercept.Decision) intercept.TargetResult { @@ -29,7 +29,7 @@ func TestArgvAllowKeepsDenyAndTargetGate(t *testing.T) { g.gate = gate ctx := gateOn(context.Background(), "7", time.Minute) - if block, msg := pre(g, ctx, "Bash", `{"command":"git push --force origin"}`); !block || !strings.Contains(msg, "force push is forbidden") { + if block, msg := pre(g, ctx, "Bash", `{"command":"nmap --force 10.0.0.1"}`); !block || !strings.Contains(msg, "force push is forbidden") { t.Fatalf("deny over argv allow: block=%v msg=%q", block, msg) } if gate.checks != 0 { diff --git a/guard/guard.go b/guard/guard.go index 42aaa49..3663722 100644 --- a/guard/guard.go +++ b/guard/guard.go @@ -82,31 +82,40 @@ func (g *Guard) setGate(ic *intercept.Interceptor) { func (g *Guard) Hooks() *hook.Registry { return g.reg } func (g *Guard) preToolUse(ctx context.Context, ev hook.Event) hook.Result { + cmd := toolAuditCommand(ev) + res := g.applyIntercept(ctx, ev, cmd) if g.targetOnly { - // Not recorded: the audit ring is for the gated worker and chat calls. - return g.applyIntercept(ctx, ev) + // Not recorded on a pass: the audit ring is for the gated worker and chat + // calls. A block still writes through block(). + return res } - // Extract the shell-command surface for the audit log: Bash + the interactive-shell - // tools (shell_open's command, shell_send's text). Destructive/exfil gating is no - // longer hard-coded here — it now lives in the DB intercept rules, evaluated by - // applyIntercept below. Other tools record an empty command. - var cmd string + // Record the final decision only. An allow written before applyIntercept + // stayed in the ring when the call was later blocked, so Audit() showed a + // call as allowed that never ran. + if res.Decision != "block" { + g.record(ev.ToolName, "allow", "", cmd) + } + return res +} + +// toolAuditCommand is the shell-command surface for the audit log: Bash and +// shell_open's command, shell_send's text. Other tools record an empty command. +func toolAuditCommand(ev hook.Event) string { switch ev.ToolName { case "Bash", "shell_open": var in struct { Command string `json:"command"` } _ = json.Unmarshal(ev.Input, &in) - cmd = in.Command + return in.Command case "shell_send": var in struct { Text string `json:"text"` } _ = json.Unmarshal(ev.Input, &in) - cmd = in.Text + return in.Text } - g.record(ev.ToolName, "allow", "", cmd) - return g.applyIntercept(ctx, ev) + return "" } // targetGate is the approval gate for asset targets, as the guard uses it. @@ -138,7 +147,7 @@ func (g *Guard) gateScope(ctx context.Context) (intercept.TargetScope, bool) { // is on: a deny blocks first, before any target request exists; an allow by a // rule or by the judge does not satisfy the gate; an ask and an unpinned target // share one approval request. -func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result { +func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event, cmd string) hook.Result { if g.targetOnly && g.interceptor != nil { // The planner and the main agent run Bash too (#124, F11): the built-in // deny rules apply to them, before the target gate. User rules and the @@ -146,7 +155,7 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result { if dec, ok := g.interceptor.MatchBuiltin(ev.ToolName, ev.Input); ok { ctx = intercept.WithCall(ctx, ev.ToolName, ev.Input) g.interceptor.Log(ctx, intercept.ConvIDFromContext(ctx), dec, ev.ToolName, ev.Input, "denied") - return g.block(ev.ToolName, systemBlockMessage(dec.Message), "") + return g.block(ev.ToolName, systemBlockMessage(dec.Message), cmd) } } scope, gated := g.gateScope(ctx) @@ -168,13 +177,13 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result { if dec.Action == "deny" { // Note: a deny hit does not block for approval; it directly logs a denied entry (visible on the history / task interception pages). g.interceptor.Log(ctx, intercept.ConvIDFromContext(ctx), dec, ev.ToolName, ev.Input, "denied") - return g.block(ev.ToolName, systemBlockMessage(dec.Message), "") + return g.block(ev.ToolName, systemBlockMessage(dec.Message), cmd) } var unpinned []intercept.TargetRequest if gated { var res intercept.TargetResult if unpinned, res = g.gate.CheckTargets(ctx, scope, ev.ToolName, ev.Input); res.Code != "" { - return g.block(ev.ToolName, TargetBlockMessage(res), "") + return g.block(ev.ToolName, TargetBlockMessage(res), cmd) } } var ask *intercept.Decision @@ -187,14 +196,14 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result { // immediately without creating a pending record — avoids orphaned DB entries // and makes execOne complete fast, reducing the race against drainSynthetic. if ctx.Err() != nil { - return g.block(ev.ToolName, systemBlockMessage("work cancelled; platform safety controls blocked execution"), "") + return g.block(ev.ToolName, systemBlockMessage("work cancelled; platform safety controls blocked execution"), cmd) } ask = &dec } if len(unpinned) > 0 { res, merged := g.requestTargets(ctx, scope, ev, unpinned, ask) if res.Code != "" { - return g.block(ev.ToolName, TargetBlockMessage(res), "") + return g.block(ev.ToolName, TargetBlockMessage(res), cmd) } if merged { // The approval of the target request answered the ask as well. @@ -204,7 +213,7 @@ func (g *Guard) applyIntercept(ctx context.Context, ev hook.Event) hook.Result { if ask != nil { convID := intercept.ConvIDFromContext(ctx) if !g.interceptor.HandleAsk(ctx, convID, dec, ev.ToolName, ev.Input) { - return g.block(ev.ToolName, systemBlockMessage("manual approval not granted (user rejected or approval timed out)"), "") + return g.block(ev.ToolName, systemBlockMessage("manual approval not granted (user rejected or approval timed out)"), cmd) } } return hook.Result{} diff --git a/guard/guard_test.go b/guard/guard_test.go index f4d5801..e49dced 100644 --- a/guard/guard_test.go +++ b/guard/guard_test.go @@ -41,6 +41,34 @@ func TestPreToolUsePassthrough(t *testing.T) { } } +// A deny must not leave a prior allow row in the audit ring. +func TestPreToolUseAuditIsFinalDecision(t *testing.T) { + ic := intercept.New(nil) + ic.SetRulesForTest([]db.InterceptRule{{ + ID: 1, Name: "deny nmap", Enabled: true, Priority: 10, + MatchTarget: "tool_input", MatchType: "string", Action: "deny", + Pattern: "nmap", Message: "no nmap", + }}) + g := NewWithInterceptor(ic) + input, _ := json.Marshal(map[string]string{"command": "nmap -sV x"}) + block, _, _ := g.Hooks().PreToolUse(context.Background(), "Bash", input) + if !block { + t.Fatal("expected block") + } + audit := g.Audit() + if len(audit) != 1 || audit[0].Action != "block" || audit[0].Tool != "Bash" { + t.Fatalf("audit=%+v, want a single block", audit) + } + if audit[0].Command != "nmap -sV x" { + t.Fatalf("block command=%q, want the denied command", audit[0].Command) + } + for _, e := range audit { + if e.Action == "allow" { + t.Fatalf("blocked call still has an allow row: %+v", audit) + } + } +} + // The target-only guard (planner, main agent) runs the built-in deny rules and // the target gate: no user intercept rule, no fallback judge, no audit-ring entry // for a call that passes (in production the built-in rules come from the store, diff --git a/guard/target_gate_test.go b/guard/target_gate_test.go index f22b5d9..d9b935e 100644 --- a/guard/target_gate_test.go +++ b/guard/target_gate_test.go @@ -530,7 +530,9 @@ func TestGateOffLeavesEveryBranchUnchanged(t *testing.T) { for name, ctx := range off { before := len(g.rows()) // 1. A tool outside the enabled set: passes, nothing is written. - for _, c := range []struct{ tool, input string }{{"Monitor", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} { + // Monitor and ExecuteExtraTool are in the default set now, so use read-only + // tools and an MCP name (inner names are not in the set). + for _, c := range []struct{ tool, input string }{{"list_assets", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} { if block, msg := pre(guard, ctx, c.tool, c.input); block { t.Fatalf("%s: %s blocked: %s", name, c.tool, msg) } diff --git a/intercept/alwaysallow_denylist.go b/intercept/alwaysallow_denylist.go index ea02dac..1fdb472 100644 --- a/intercept/alwaysallow_denylist.go +++ b/intercept/alwaysallow_denylist.go @@ -27,6 +27,8 @@ var alwaysAllowDenylist = func() map[string]bool { // package managers and build tools: run package scripts and hooks "npm npx pnpm yarn bunx corepack pip pipx uv uvx poetry conda composer gem bundle bundler rake cargo go " + "mvn gradle dotnet apt apt-get dpkg dnf yum rpm pacman apk brew snap flatpak", + // version control and build generators: run hooks, aliases and script files + "git cmake ctest cpack", // orchestration: run images, playbooks and plans "docker docker-compose podman nerdctl kubectl helm ansible ansible-playbook terraform pulumi vagrant", // destructive diff --git a/intercept/alwaysallow_denylist_test.go b/intercept/alwaysallow_denylist_test.go index 1027c04..60a0156 100644 --- a/intercept/alwaysallow_denylist_test.go +++ b/intercept/alwaysallow_denylist_test.go @@ -13,12 +13,13 @@ func TestArgvAllowDenylist(t *testing.T) { "python", "python3", "python3.11", "/usr/bin/python3.11", "php8.2", "ruby3.2", "perl5", "pip3", "env", "/usr/bin/env", "bash", "/bin/sh", "find", "rm", "mkfs", "mkfs.ext4", "/sbin/mkfs.xfs", "docker", "kubectl", "npm", "sudo", "xargs", "Rscript", ".", + "git", "/usr/bin/git", "cmake", "cmake3", "/usr/bin/cmake", "ctest", "cpack", } { if !ArgvAllowDenied(prog) { t.Errorf("%q is not denied", prog) } } - for _, prog := range []string{"nmap", "git", "/usr/bin/git", "curl", "ls", "gh", "x", "7z", "pythonic"} { + for _, prog := range []string{"nmap", "curl", "ls", "gh", "x", "7z", "pythonic"} { if ArgvAllowDenied(prog) { t.Errorf("%q is denied, want allowable", prog) } @@ -30,8 +31,8 @@ func TestAlwaysAllowPrefix(t *testing.T) { b, _ := json.Marshal(map[string]string{"command": cmd}) return b } - if got, err := AlwaysAllowPrefix("Bash", bash("git push --force origin main")); err != nil || !slices.Equal(got, []string{"git", "push"}) { - t.Fatalf("git push: %q %v", got, err) + if got, err := AlwaysAllowPrefix("Bash", bash("gh pr list --limit 5")); err != nil || !slices.Equal(got, []string{"gh", "pr", "list"}) { + t.Fatalf("gh pr list: %q %v", got, err) } if got, err := AlwaysAllowPrefix("Bash", bash("nmap -p 80 10.0.0.1")); err != nil || !slices.Equal(got, []string{"nmap"}) { t.Fatalf("nmap: %q %v", got, err) @@ -40,10 +41,10 @@ func TestAlwaysAllowPrefix(t *testing.T) { tool string input []byte }{ - "not Bash": {"shell_open", bash("git push")}, - "compound": {"Bash", bash("git push; id")}, - "substitution": {"Bash", bash("git push $(id)")}, - "redirection": {"Bash", bash("git push > out")}, + "not Bash": {"shell_open", bash("gh pr list")}, + "compound": {"Bash", bash("gh pr list; id")}, + "substitution": {"Bash", bash("gh pr list $(id)")}, + "redirection": {"Bash", bash("gh pr list > out")}, "empty": {"Bash", bash("")}, "no command": {"Bash", []byte(`{}`)}, "not json": {"Bash", []byte(`not json`)}, @@ -52,6 +53,11 @@ func TestAlwaysAllowPrefix(t *testing.T) { "find": {"Bash", bash("find . -exec sh -c id ;")}, "rm": {"Bash", bash("rm -rf /")}, "docker": {"Bash", bash("docker run --privileged x")}, + "git": {"Bash", bash("git status")}, + "path to git": {"Bash", bash("/usr/bin/git status")}, + "git config": {"Bash", bash("git config user.name x")}, + "cmake": {"Bash", bash("cmake --version")}, + "ctest": {"Bash", bash("ctest -N")}, } { if got, err := AlwaysAllowPrefix(c.tool, c.input); err == nil { t.Errorf("%s: prefix %q, want a refusal", name, got) @@ -59,6 +65,20 @@ func TestAlwaysAllowPrefix(t *testing.T) { } } +// The arity table is keyed by program name, so a path-qualified binary derives +// the same prefix length as the bare name. +func TestArgvPrefixLenUsesBasename(t *testing.T) { + if got := argvPrefixLen([]string{"/usr/bin/gh", "pr", "list"}); got != 3 { + t.Errorf("path-qualified gh prefix length = %d, want 3", got) + } + if got := argvPrefixLen([]string{"/usr/bin/git", "status"}); got != 2 { + t.Errorf("path-qualified git prefix length = %d, want 2", got) + } + if got, err := ArgvPrefix("/usr/bin/gh pr list"); err != nil || !slices.Equal(got, []string{"/usr/bin/gh", "pr", "list"}) { + t.Errorf("path-qualified gh prefix = %q, %v", got, err) + } +} + // The denylist neutralises argv allow rules at matching time (a rule created // before the denylist, or written straight into the database), and only them: // an argv deny or ask rule for the same program still matches. diff --git a/intercept/argv.go b/intercept/argv.go index b1f350a..630733b 100644 --- a/intercept/argv.go +++ b/intercept/argv.go @@ -25,9 +25,17 @@ var argvArity = map[string]int{ } // argvPrefixLen returns the number of leading tokens that form the prefix. +// The arity table is keyed by program name, so a path-qualified binary +// (/usr/bin/git) uses the same arity as the bare name. func argvPrefixLen(tokens []string) int { + if len(tokens) == 0 { + return 0 + } + key := make([]string, len(tokens)) + copy(key, tokens) + key[0] = argvProgramName(tokens[0]) for n := len(tokens); n > 0; n-- { - if a, ok := argvArity[strings.Join(tokens[:n], " ")]; ok { + if a, ok := argvArity[strings.Join(key[:n], " ")]; ok { return min(a, len(tokens)) } } diff --git a/intercept/argv_compound.go b/intercept/argv_compound.go new file mode 100644 index 0000000..1ff824f --- /dev/null +++ b/intercept/argv_compound.go @@ -0,0 +1,1156 @@ +package intercept + +import ( + "encoding/json" + "path" + "strings" + + "mvdan.cc/sh/v3/syntax" +) + +// argvMaxNestedPayloads bounds how deeply nested shell/eval/env -S payloads +// (for example, bash -c "bash -c ...") are re-parsed and walked. +const argvMaxNestedPayloads = 3 + +// argvMaxWrapperCandidates bounds option-disambiguation branching (for example +// repeated ambiguous optional-value flags like xargs -l) so pathological input +// cannot cause exponential work. +const argvMaxWrapperCandidates = 8 + +// callWord is one argument word of a *syntax.CallExpr for deny/ask matching. +// Literal is true when the word contains no runtime expansion; Value holds the +// unquoted text. AssignLike is true when the word begins with a literal +// NAME= prefix (for example FOO=1 or FOO=$(id)), so wrappers like env and sudo +// can skip environment assignments without skipping arbitrary opaque tokens. +type callWord struct { + Value string + Literal bool + AssignLike bool +} + +// argvCompoundMatches reports whether any command executed within a Bash tool +// call matches the deny/ask prefix rule tokens. It parses the entire Bash line, +// walks every *syntax.CallExpr in the AST, strips known wrapper programs, and +// recurses into eval, shell -c, env -S, flock -c, and parallel command-string +// payloads up to argvMaxNestedPayloads deep. +// +// Parse errors never panic and always return false (no match). +func argvCompoundMatches(tokens []string, toolName string, input []byte) bool { + if toolName != "Bash" || len(tokens) == 0 { + return false + } + var in struct { + Command string `json:"command"` + } + if json.Unmarshal(input, &in) != nil { + return false + } + if strings.TrimSpace(in.Command) == "" { + return false + } + return bashCommandMatchesArgv(tokens, in.Command, 0) +} + +func bashCommandMatchesArgv(rule []string, command string, depth int) bool { + f, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "") + if err != nil { + return false + } + matched := false + syntax.Walk(f, func(n syntax.Node) bool { + if matched { + return false + } + call, ok := n.(*syntax.CallExpr) + if !ok || len(call.Args) == 0 { + return true + } + words := make([]callWord, len(call.Args)) + for i, w := range call.Args { + words[i] = callWordOf(w) + } + if callMatchesArgv(rule, words, depth) { + matched = true + return false + } + return true + }) + return matched +} + +// callMatchesArgv checks a single call's argv against rule, stripping known +// wrappers repeatedly and recursing into nested Bash payloads up to +// argvMaxNestedPayloads deep. +func callMatchesArgv(rule []string, argv []callWord, depth int) bool { + if len(argv) == 0 { + return false + } + if argvMatchesRulePrefix(rule, argv) { + return true + } + if !argv[0].Literal || argv[0].Value == "" { + return false + } + prog := path.Base(argv[0].Value) + rest := argv[1:] + + switch { + case prog == "eval": + if depth >= argvMaxNestedPayloads { + return false + } + payload, ok := evalPayload(rest) + if !ok { + return false + } + return bashCommandMatchesArgv(rule, payload, depth+1) + + case isShellWrapper(prog): + if depth >= argvMaxNestedPayloads { + return false + } + payload, ok := shellDashCPayload(rest) + if !ok { + return false + } + return bashCommandMatchesArgv(rule, payload, depth+1) + + case prog == "env": + return envMatchesArgv(rule, rest, depth) + + case prog == "find": + return findExecMatches(rule, rest, depth) + + case prog == "flock": + return flockMatchesArgv(rule, rest, depth) + + case prog == "parallel": + return parallelMatchesArgv(rule, rest, depth) + } + + for _, next := range stripOneWrapperCandidates(prog, rest) { + if len(next) > 0 && len(next) < len(argv) { + if callMatchesArgv(rule, next, depth) { + return true + } + } + } + return false +} + +// argvMatchesRulePrefix compares rule against the first len(rule) tokens of +// argv. For token 0, a rule token without a path separator matches the basename +// of the actual program; a rule token with a separator must match verbatim. +func argvMatchesRulePrefix(rule []string, argv []callWord) bool { + if len(rule) == 0 || len(argv) < len(rule) { + return false + } + for i, want := range rule { + if !argv[i].Literal { + return false + } + got := argv[i].Value + if i == 0 { + if got == "" { + return false + } + if !strings.ContainsAny(want, "/\\") { + got = path.Base(got) + } + } + if got != want { + return false + } + } + return true +} + +// callWordOf converts a Bash AST word into a callWord. Words containing any +// expansion (parameter, command/process substitution, arithmetic, glob, brace +// expansion, tilde, ANSI-C/locale quoting) become opaque (Literal: false) +// rather than failing the whole call. +func callWordOf(w *syntax.Word) callWord { + if w == nil || len(w.Parts) == 0 { + return callWord{} + } + assignLike := false + if firstLit, ok := w.Parts[0].(*syntax.Lit); ok && hasAssignPrefix(firstLit.Value) { + assignLike = true + } + + var sb strings.Builder + literal := true + for _, part := range w.Parts { + switch p := part.(type) { + case *syntax.Lit: + s, ok := unescapeBareLit(p.Value) + if !ok { + literal = false + continue + } + sb.WriteString(s) + case *syntax.SglQuoted: + if p.Dollar { + literal = false + continue + } + sb.WriteString(p.Value) + case *syntax.DblQuoted: + if p.Dollar { + literal = false + continue + } + for _, q := range p.Parts { + lit, ok := q.(*syntax.Lit) + if !ok { + literal = false + break + } + sb.WriteString(unescapeDblQuotedLit(lit.Value)) + } + default: + literal = false + } + } + if !literal { + return callWord{Literal: false, AssignLike: assignLike} + } + val := sb.String() + if !assignLike && hasAssignPrefix(val) { + assignLike = true + } + return callWord{Value: val, Literal: true, AssignLike: assignLike} +} + +func unescapeBareLit(s string) (string, bool) { + var sb strings.Builder + sb.Grow(len(s)) + hasOpenBrace := false + hasCloseBrace := false + for i := 0; i < len(s); i++ { + c := s[i] + if c == '\\' { + if i+1 >= len(s) { + return "", false + } + i++ + if s[i] == '\n' { + continue + } + sb.WriteByte(s[i]) + continue + } + switch c { + case '*', '?', '[', ']', '~': + return "", false + case '{': + hasOpenBrace = true + case '}': + hasCloseBrace = true + } + sb.WriteByte(c) + } + if hasOpenBrace && hasCloseBrace && (strings.Contains(s, ",") || strings.Contains(s, "..")) { + return "", false + } + return sb.String(), true +} + +func unescapeDblQuotedLit(s string) string { + var sb strings.Builder + sb.Grow(len(s)) + for i := 0; i < len(s); i++ { + if s[i] == '\\' && i+1 < len(s) { + switch s[i+1] { + case '\n': + i++ + continue + case '"', '$', '`', '\\': + i++ + sb.WriteByte(s[i]) + continue + } + } + sb.WriteByte(s[i]) + } + return sb.String() +} + +func hasAssignPrefix(s string) bool { + eq := strings.IndexByte(s, '=') + if eq <= 0 { + return false + } + for i := 0; i < eq; i++ { + c := s[i] + isLetter := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' + isDigit := c >= '0' && c <= '9' + if i == 0 && !isLetter { + return false + } + if !isLetter && !isDigit { + return false + } + } + return true +} + +func isShellWrapper(prog string) bool { + switch prog { + case "sh", "bash", "zsh", "dash", "ksh", "fish": + return true + } + return false +} + +// Known leading options of POSIX/Bash/Zsh/Dash/Ksh/Fish shells. +// Short flags may appear with '-' or '+' (only '-c' enables command mode); +// -o/+o and -O/+O take a single option-name value. +const shellShortNoArg = "abBCdefhHiklmnpPrstuvxETLN" + +var ( + shellLongNoArg = strSet( + "debugger", "dump-po-strings", "dump-strings", "interactive", "login", + "no-config", "noediting", "noprofile", "norc", "posix", "pretty-print", + "private", "restricted", "verbose", + ) + shellLongArg = strSet("init-file", "rcfile") +) + +// shellDashCPayload parses a shell's leading options (combined short clusters +// containing c, -o/+o and -O/+O with a value, known long options, and --) and +// returns the literal command string if -c (or --command) was given. +// No -c (script/stdin mode), unknown options, or opaque options before -c +// return ("", false). +func shellDashCPayload(args []callWord) (string, bool) { + hasC := false + i := 0 + for i < len(args) { + if !args[i].Literal { + return "", false + } + tok := args[i].Value + if tok == "--" || tok == "-" { + i++ + break + } + if !strings.HasPrefix(tok, "-") && !strings.HasPrefix(tok, "+") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "command" { + return val, true + } + if shellLongArg[flagName] { + i++ + continue + } + return "", false + } + if name == "command" { + if i+1 >= len(args) || !args[i+1].Literal { + return "", false + } + return args[i+1].Value, true + } + if shellLongNoArg[name] { + i++ + continue + } + if shellLongArg[name] { + if i+1 >= len(args) { + return "", false + } + i += 2 + continue + } + return "", false + } + + // Short option or combined short-option cluster starting with '-' or '+'. + sign := tok[0] + flags := tok[1:] + if flags == "" { + break + } + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'c' && sign == '-': + hasC = true + case ch == 'o' || ch == 'O': + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return "", false + } + consumedNext = true + } + case strings.IndexByte(shellShortNoArg, ch) >= 0: + continue + default: + return "", false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + if !hasC || i >= len(args) || !args[i].Literal { + return "", false + } + return args[i].Value, true +} + +// evalPayload joins eval's arguments with spaces for re-parsing as Bash. +// A leading "--" is stripped. Opaque arguments are substituted with an +// unexpanded placeholder ($__opaque) so they never shift a later literal word +// into command position, while trailing opaque args still let a leading literal +// command match. +func evalPayload(args []callWord) (string, bool) { + if len(args) > 0 && args[0].Literal && args[0].Value == "--" { + args = args[1:] + } + if len(args) == 0 { + return "", false + } + parts := make([]string, 0, len(args)) + hasLiteral := false + for _, a := range args { + if a.Literal { + parts = append(parts, a.Value) + hasLiteral = true + } else { + parts = append(parts, "$__opaque") + } + } + if !hasLiteral { + return "", false + } + return strings.Join(parts, " "), true +} + +// envMatchesArgv handles env's options (including -S/--split-string, whose +// value is re-parsed as a Bash line at depth+1), NAME=VALUE assignments, and +// any trailing wrapped command. Unknown options are over-approximated (tried +// as 0-arg and, when applicable, 1-arg) up to argvMaxWrapperCandidates. +func envMatchesArgv(rule []string, args []callWord, depth int) bool { + spec := wrapperSpecs["env"] + checkSplitString := func(val string) bool { + if depth >= argvMaxNestedPayloads || strings.TrimSpace(val) == "" { + return false + } + if bashCommandMatchesArgv(rule, val, depth+1) { + return true + } + // If the split-string payload starts with env options (e.g. -i or -u), + // also evaluate it as an env invocation. + if strings.HasPrefix(strings.TrimSpace(val), "-") { + return bashCommandMatchesArgv(rule, "env "+val, depth+1) + } + return false + } + + candidates := 0 + seenIdx := map[int]bool{} + var walk func(i int) bool + walk = func(i int) bool { + if candidates >= argvMaxWrapperCandidates { + return false + } + for i < len(args) { + if !args[i].Literal { + if args[i].AssignLike { + break + } + return false + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if tok == "-" { + i++ + continue + } + if !strings.HasPrefix(tok, "-") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "split-string" && checkSplitString(val) { + return true + } + // Known or unknown --flag=val skips one token. + i++ + continue + } + if name == "help" || name == "version" { + return false + } + if name == "split-string" { + if i+1 >= len(args) { + return false + } + if args[i+1].Literal && checkSplitString(args[i+1].Value) { + return true + } + i += 2 + continue + } + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return false + } + i += 2 + continue + } + // Unknown long option without "=": try 0-arg and 1-arg. + if walk(i + 1) { + return true + } + if i+1 < len(args) && walk(i+2) { + return true + } + return false + } + + flags := tok[1:] + consumedNext := false + unknownOpt := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'S': + if j+1 < len(flags) { + if checkSplitString(flags[j+1:]) { + return true + } + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + if args[i+1].Literal && checkSplitString(args[i+1].Value) { + return true + } + consumedNext = true + } + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + consumedNext = true + } + default: + unknownOpt = true + j = len(flags) + } + } + if unknownOpt { + if walk(i + 1) { + return true + } + if i+1 < len(args) && walk(i+2) { + return true + } + return false + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + for i < len(args) && args[i].AssignLike { + i++ + } + if i >= len(args) || seenIdx[i] { + return false + } + seenIdx[i] = true + candidates++ + return callMatchesArgv(rule, args[i:], depth) + } + return walk(0) +} + +// findExecMatches walks every -exec, -execdir, -ok, and -okdir clause inside a +// find invocation (terminated by literal ";" or "+") and runs callMatchesArgv +// on each wrapped command. +func findExecMatches(rule []string, args []callWord, depth int) bool { + for i := 0; i < len(args); i++ { + if !args[i].Literal { + continue + } + switch args[i].Value { + case "-exec", "-execdir", "-ok", "-okdir": + start := i + 1 + end := start + terminated := false + for end < len(args) { + if args[end].Literal && (args[end].Value == ";" || args[end].Value == "+") { + terminated = true + break + } + end++ + } + if terminated && end > start { + if callMatchesArgv(rule, args[start:end], depth) { + return true + } + i = end + } + } + } + return false +} + +// flockMatchesArgv handles both "flock [opts] " and +// "flock [opts] -c " / "flock [opts] -c ". +func flockMatchesArgv(rule []string, args []callWord, depth int) bool { + spec := wrapperSpecs["flock"] + i := 0 + for i < len(args) { + if !args[i].Literal { + return false + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if !strings.HasPrefix(tok, "-") || tok == "-" { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName, val := name[:eq], name[eq+1:] + if flagName == "command" { + if depth < argvMaxNestedPayloads && bashCommandMatchesArgv(rule, val, depth+1) { + return true + } + i++ + continue + } + if spec.longArg[flagName] { + i++ + continue + } + return false + } + if name == "command" { + if i+1 >= len(args) { + return false + } + if depth < argvMaxNestedPayloads && args[i+1].Literal && bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) { + return true + } + i += 2 + continue + } + if spec.longNoArg[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return false + } + i += 2 + continue + } + return false + } + + flags := tok[1:] + consumedNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case ch == 'c': + if j+1 < len(flags) { + if depth < argvMaxNestedPayloads && bashCommandMatchesArgv(rule, flags[j+1:], depth+1) { + return true + } + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + if depth < argvMaxNestedPayloads && args[i+1].Literal && bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) { + return true + } + consumedNext = true + } + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return false + } + consumedNext = true + } + default: + return false + } + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + // Skip positional . + if i >= len(args) { + return false + } + i++ + if i >= len(args) { + return false + } + // Handle "flock -c " / "flock --command ". + if args[i].Literal { + tok := args[i].Value + if tok == "-c" || tok == "--command" { + if i+1 < len(args) && args[i+1].Literal && depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, args[i+1].Value, depth+1) + } + return false + } + if strings.HasPrefix(tok, "--command=") { + if depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, strings.TrimPrefix(tok, "--command="), depth+1) + } + return false + } + if strings.HasPrefix(tok, "-c") && len(tok) > 2 { + if depth < argvMaxNestedPayloads { + return bashCommandMatchesArgv(rule, tok[2:], depth+1) + } + return false + } + } + return callMatchesArgv(rule, args[i:], depth) +} + +// parallelMatchesArgv strips parallel's leading options, stops before GNU +// parallel's input separators (:::, :::+, ::::, ::::+), and matches the +// wrapped command (including single-string shell commands like +// "parallel 'nmap -p 80 {}' ::: target"). +// +// When no command precedes ":::", GNU parallel executes each argument after +// ":::" as a command line, so each literal argument up to the next separator +// is parsed as a Bash line at depth+1. +// +// Note: "parallel -a FILE" / "--arg-file FILE" and "parallel :::: FILE" read +// command lines from a file that the matcher does not read. +func parallelMatchesArgv(rule []string, args []callWord, depth int) bool { + isParallelSep := func(w callWord) bool { + return w.Literal && (w.Value == ":::" || w.Value == ":::+" || w.Value == "::::" || w.Value == "::::+") + } + for _, cand := range stripOneWrapperCandidates("parallel", args) { + end := len(cand) + for idx, w := range cand { + if isParallelSep(w) { + end = idx + break + } + } + cmd := cand[:end] + if len(cmd) == 0 { + // No command before separator: for ":::" each following literal + // argument (until any subsequent separator) runs as a command line. + // For ":::+", "::::", and "::::+", do not guess. + if end < len(cand) && cand[end].Literal && cand[end].Value == ":::" && depth < argvMaxNestedPayloads { + for _, arg := range cand[end+1:] { + if isParallelSep(arg) { + break + } + if arg.Literal && bashCommandMatchesArgv(rule, arg.Value, depth+1) { + return true + } + } + } + continue + } + if callMatchesArgv(rule, cmd, depth) { + return true + } + if len(cmd) == 1 && cmd[0].Literal && depth < argvMaxNestedPayloads { + if bashCommandMatchesArgv(rule, cmd[0].Value, depth+1) { + return true + } + } + } + return false +} + +// wrapperSpec describes the leading-option layout for a known wrapper program. +// Explicit non-executing modes (stopShort / stopLong, plus --help / --version) +// skip unwrapping. Unknown options on a known wrapper are over-approximated +// (trying both 0-arg and 1-arg interpretations, capped by +// argvMaxWrapperCandidates) rather than returning no match. +type wrapperSpec struct { + shortNoArg string // short flags that take no argument + shortArg string // short flags that take one argument (attached or next token) + shortOptAtt string // short flags that accept only an optional attached argument (never next token) + shortOptAmb string // short flags with optional attached OR separate next-token value (try both) + stopShort string // short flags indicating a non-executing mode (skip unwrapping) + longNoArg map[string]bool // --flag (no value) + longArg map[string]bool // --flag VAL or --flag=VAL + longOptVal map[string]bool // --flag or --flag=VAL (never consumes next token) + stopLong map[string]bool // --flag indicating a non-executing mode (skip unwrapping) + allowBareMin bool // treat bare "-" as a no-arg option + allowNumFlag bool // treat - as a no-arg option (nice -10) + skipAssigns bool // skip NAME=VALUE tokens after options (env, sudo) + posBeforeCmd int // required positional arguments before the wrapped command +} + +func strSet(names ...string) map[string]bool { + m := make(map[string]bool, len(names)) + for _, n := range names { + m[n] = true + } + return m +} + +var wrapperSpecs = map[string]wrapperSpec{ + "env": { + shortNoArg: "i0v", + shortArg: "uCa", + longNoArg: strSet("ignore-environment", "null", "debug"), + longArg: strSet("unset", "chdir", "argv0"), + longOptVal: strSet("block-signal", "default-signal", "ignore-signal"), + allowBareMin: true, + skipAssigns: true, + }, + "command": { + shortNoArg: "p", + stopShort: "vV", + }, + "builtin": {}, + "exec": { + shortNoArg: "cl", + shortArg: "a", + }, + "nohup": {}, + "setsid": { + shortNoArg: "cfw", + longNoArg: strSet("ctty", "fork", "wait"), + }, + "stdbuf": { + shortArg: "ioe", + longArg: strSet("input", "output", "error"), + }, + "nice": { + shortArg: "n", + longArg: strSet("adjustment"), + allowNumFlag: true, + }, + "ionice": { + shortNoArg: "t", + shortArg: "cn", + stopShort: "pPu", + longNoArg: strSet("ignore"), + longArg: strSet("class", "classdata"), + stopLong: strSet("pid", "pgid", "uid"), + }, + "timeout": { + shortNoArg: "fpv", + shortArg: "ks", + longNoArg: strSet("foreground", "preserve-status", "verbose"), + longArg: strSet("kill-after", "signal"), + posBeforeCmd: 1, // DURATION + }, + "taskset": { + shortNoArg: "ca", + stopShort: "p", + longNoArg: strSet("cpu-list", "all-tasks"), + stopLong: strSet("pid"), + posBeforeCmd: 1, // MASK / CPU-LIST + }, + "chrt": { + shortNoArg: "abdforiRv", + shortArg: "TPD", + stopShort: "pm", + longNoArg: strSet("all-tasks", "batch", "deadline", "fifo", "idle", "other", "rr", "reset-on-fork", "verbose"), + longArg: strSet("sched-runtime", "sched-period", "sched-deadline"), + stopLong: strSet("pid", "max"), + posBeforeCmd: 1, // PRIORITY + }, + "sudo": { + shortNoArg: "AbBEHikKnPsSv", + shortArg: "CDghprRtTuU", + stopShort: "elV", + longNoArg: strSet("askpass", "background", "bell", "set-home", "login", "reset-timestamp", "remove-timestamp", "non-interactive", "preserve-groups", "shell", "stdin", "validate"), + longArg: strSet("close-from", "chdir", "group", "host", "prompt", "role", "chroot", "type", "command-timeout", "user", "other-user"), + longOptVal: strSet("preserve-env"), + stopLong: strSet("edit", "list"), + skipAssigns: true, + }, + "doas": { + shortNoArg: "Lns", + shortArg: "au", + stopShort: "C", + }, + "watch": { + shortNoArg: "bcCegprtwx", + shortArg: "nq", + shortOptAmb: "d", + longNoArg: strSet("beep", "color", "no-color", "errexit", "chgexit", "precise", "no-rerun", "no-title", "no-wrap", "exec"), + longArg: strSet("interval", "equexit"), + longOptVal: strSet("differences"), + }, + "flock": { + shortNoArg: "sxeunFo", + shortArg: "wE", + longNoArg: strSet("shared", "exclusive", "unlock", "nb", "nonblock", "no-fork", "close", "verbose"), + longArg: strSet("timeout", "wait", "conflict-exit-code"), + posBeforeCmd: 1, // LOCKFILE + }, + "strace": { + shortNoArg: "cCdfFikqrtTvwxyYzZ", + shortArg: "abeEIoOpPsSuUX", + longNoArg: strSet("summary-only", "summary", "debug", "follow-forks", "instruction-pointer", "stack-traces", "quiet", "relative-timestamps", "absolute-timestamps", "syscall-times", "no-abbrev", "summary-wall-clock", "hex", "decode-fds", "decode-pids", "successful-only", "failed-only"), + longArg: strSet("columns", "detach-on", "trace", "env", "interruptible", "output", "output-separately", "attach", "trace-path", "string-limit", "summary-sort-by", "user", "signal", "status", "inject", "fault", "raw", "read", "write", "abbrev", "verbose", "silence", "strings-in-hex", "const-print-style"), + }, + "ltrace": { + shortNoArg: "bcCfiLrStT", + shortArg: "aADeFlnopsuwx", + longNoArg: strSet("no-signals", "demangle", "syscalls"), + longArg: strSet("align", "arraylen", "config", "debug", "library", "indent", "output", "attach", "strsize", "username", "where"), + }, + "xargs": { + shortNoArg: "0oprtx", + shortArg: "adEILnPsR", + shortOptAtt: "ei", + shortOptAmb: "l", + longNoArg: strSet("null", "open-tty", "interactive", "no-run-if-empty", "verbose", "exit", "show-limits"), + longArg: strSet("arg-file", "delimiter", "eof", "replace", "max-lines", "max-args", "max-procs", "max-chars", "process-slot-var"), + }, + "busybox": { + stopLong: strSet("list", "list-full", "list-modules", "install"), + }, + "chroot": { + longNoArg: strSet("skip-chdir"), + longArg: strSet("userspec", "groups"), + posBeforeCmd: 1, // NEWROOT + }, + "parallel": { + shortNoArg: "0kmquvXi", + shortArg: "jnNPILSadEC", + longNoArg: strSet("null", "keep-order", "quote", "ungroup", "verbose", "bar", "eta", "progress", "no-notice", "will-cite", "plain", "pipe", "pipepart", "line-buffer", "group", "dry-run", "shuf", "link", "xargs"), + longArg: strSet("jobs", "max-args", "max-procs", "max-lines", "sshlogin", "sshloginfile", "basefile", "transferfile", "total-jobs", "block", "recstart", "recend", "compress-program", "use-compress-program", "nice", "sshdelay", "arg-file", "delimiter", "colsep", "tagstring", "timeout", "delay", "retries", "results", "joblog", "workdir", "wd", "env", "halt", "memfree", "load"), + longOptVal: strSet("tag"), + }, +} + +// stripOneWrapperCandidates returns the possible wrapped-command slices after +// stripping prog's options, assignments, and required positional arguments. +// For unambiguous known options it returns one slice; for optional-argument +// flags (such as xargs -l) or unknown options on a known wrapper it tries both +// 0-arg and 1-arg interpretations up to argvMaxWrapperCandidates. +func stripOneWrapperCandidates(prog string, args []callWord) [][]callWord { + spec, ok := wrapperSpecs[prog] + if !ok { + return nil + } + var out [][]callWord + seenIdx := map[int]bool{} + var walk func(i int) + walk = func(i int) { + if len(out) >= argvMaxWrapperCandidates { + return + } + for i < len(args) { + if !args[i].Literal { + if spec.skipAssigns && args[i].AssignLike { + break + } + return + } + tok := args[i].Value + if tok == "--" { + i++ + break + } + if tok == "-" { + if spec.allowBareMin { + i++ + continue + } + break + } + if !strings.HasPrefix(tok, "-") { + break + } + if strings.HasPrefix(tok, "--") { + name := tok[2:] + if eq := strings.IndexByte(name, '='); eq >= 0 { + flagName := name[:eq] + if spec.stopLong[flagName] { + return + } + // Known or unknown --flag=val consumes one token. + i++ + continue + } + if name == "help" || name == "version" || spec.stopLong[name] { + return + } + if spec.longNoArg[name] || spec.longOptVal[name] { + i++ + continue + } + if spec.longArg[name] { + if i+1 >= len(args) { + return + } + i += 2 + continue + } + // Unknown long option without "=": try both 0-arg and 1-arg. + walk(i + 1) + if i+1 < len(args) { + walk(i + 2) + } + return + } + + flags := tok[1:] + if spec.allowNumFlag && isAllDigits(flags) { + i++ + continue + } + consumedNext := false + ambiguousNext := false + unknownNext := false + for j := 0; j < len(flags); j++ { + ch := flags[j] + switch { + case strings.IndexByte(spec.stopShort, ch) >= 0: + return + case strings.IndexByte(spec.shortNoArg, ch) >= 0: + continue + case strings.IndexByte(spec.shortOptAtt, ch) >= 0: + j = len(flags) + case strings.IndexByte(spec.shortOptAmb, ch) >= 0: + if j+1 < len(flags) { + // Attached value (e.g. -l5) consumes the rest of this token. + j = len(flags) + } else { + // Bare flag: try treating as no-arg AND (if a next token + // could be its optional argument) consuming the next token. + ambiguousNext = true + } + case strings.IndexByte(spec.shortArg, ch) >= 0: + if j+1 < len(flags) { + j = len(flags) + } else { + if i+1 >= len(args) { + return + } + consumedNext = true + } + default: + // Unknown short flag on a known wrapper: try both 0-arg and 1-arg. + unknownNext = true + j = len(flags) + } + } + if unknownNext { + walk(i + 1) + if i+1 < len(args) { + walk(i + 2) + } + return + } + if ambiguousNext && !consumedNext { + // Interpretation 1: no-arg. + walk(i + 1) + // Interpretation 2: consumes next token as optional value + // (e.g. xargs -l 5 nmap, watch -d permanent nmap). + if i+1 < len(args) && optAmbMayConsume(prog, args[i+1]) { + walk(i + 2) + } + return + } + if consumedNext { + i += 2 + } else { + i++ + } + } + + if spec.skipAssigns { + for i < len(args) && args[i].AssignLike { + i++ + } + } + if spec.posBeforeCmd > 0 { + if i+spec.posBeforeCmd > len(args) { + return + } + i += spec.posBeforeCmd + } + if i >= len(args) || seenIdx[i] { + return + } + seenIdx[i] = true + out = append(out, args[i:]) + } + walk(0) + return out +} + +func optAmbMayConsume(prog string, next callWord) bool { + if !next.Literal { + return true + } + switch prog { + case "xargs": + return isAllDigits(next.Value) + case "watch": + return next.Value == "permanent" || next.Value == "cumulative" + default: + return !strings.HasPrefix(next.Value, "-") + } +} + +func isAllDigits(s string) bool { + if s == "" { + return false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} diff --git a/intercept/argv_compound_test.go b/intercept/argv_compound_test.go new file mode 100644 index 0000000..2ee2110 --- /dev/null +++ b/intercept/argv_compound_test.go @@ -0,0 +1,291 @@ +package intercept + +import ( + "encoding/json" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func bashInput(cmd string) []byte { + b, _ := json.Marshal(map[string]string{"command": cmd}) + return b +} + +func matchSingleArgvRule(action, pattern, toolName string, input []byte) (Decision, bool) { + ic := New(nil) + ic.SetRulesForTest([]db.InterceptRule{{ + ID: 1, + Name: action + " " + pattern, + Enabled: true, + Priority: 100, + MatchTarget: "tool_input", + MatchType: "argv", + Pattern: pattern, + Action: action, + }}) + return ic.Match(toolName, input) +} + +func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) { + nmapShouldMatch := []struct { + name string + cmd string + }{ + {"plain", "nmap -p 80 x"}, + {"command wrapper", "command nmap -p 80 x"}, + {"command double dash", "command -- nmap -p 80 x"}, + {"command -p", "command -p nmap -p 80 x"}, + {"path qualified", "/usr/bin/nmap -p 80 x"}, + {"sudo", "sudo nmap -p 80 x"}, + {"sudo with flags and assign", "sudo -u root -n FOO=1 nmap -p 80 x"}, + {"doas", "doas -u root nmap -p 80 x"}, + {"env with assign", "env FOO=1 nmap -p 80 x"}, + {"env with flags", "env -i -u HOME -C /tmp -S arg FOO=1 nmap -p 80 x"}, + {"env with expansion in assign", "env FOO=$(id) nmap -p 80 x"}, + {"env -S separate", "env -S 'nmap -p 80 x'"}, + {"env -S attached", "env -S'nmap -p 80 x'"}, + {"env --split-string equals", "env --split-string='nmap -p 80 x'"}, + {"env --split-string separate", "env --split-string 'nmap -p 80 x'"}, + {"env -S with env flags", "env -S '-i FOO=1 nmap -p 80 x'"}, + {"timeout", "timeout 30 nmap -p 80 x"}, + {"timeout with flags", "timeout -k 5 -s KILL 30 nmap -p 80 x"}, + {"nohup", "nohup nmap -p 80 x"}, + {"setsid", "setsid -f nmap -p 80 x"}, + {"stdbuf", "stdbuf -oL -eL nmap -p 80 x"}, + {"nice -n", "nice -n 10 nmap -p 80 x"}, + {"nice numeric flag", "nice -10 nmap -p 80 x"}, + {"ionice", "ionice -c 3 nmap -p 80 x"}, + {"taskset", "taskset -c 0-1 nmap -p 80 x"}, + {"chrt", "chrt -f 50 nmap -p 80 x"}, + {"watch", "watch -n 5 nmap -p 80 x"}, + {"watch -d permanent", "watch -d permanent nmap -p 80 x"}, + {"flock", "flock -n /tmp/lock nmap -p 80 x"}, + {"flock -c after lockfile", "flock /tmp/lock -c 'nmap -p 80 x'"}, + {"flock -c before lockfile", "flock -n -c 'nmap -p 80 x' /tmp/lock"}, + {"strace", "strace -f -o /tmp/trace nmap -p 80 x"}, + {"ltrace", "ltrace -f -o /tmp/ltrace nmap -p 80 x"}, + {"xargs", "echo 10.0.0.1 | xargs -n 1 nmap -p 80"}, + {"xargs -I", "xargs -I{} nmap -p 80 {}"}, + {"xargs -l bare", "xargs -l nmap"}, + {"xargs -l5 attached", "xargs -l5 nmap"}, + {"xargs -l 5 separate", "xargs -l 5 nmap"}, + {"find -exec", `find . -maxdepth 0 -exec nmap -p 80 x \;`}, + {"find -execdir", `find . -execdir nmap -p 80 x \;`}, + {"find -ok", `find . -ok nmap -p 80 x \;`}, + {"find -okdir plus", `find . -okdir nmap -p 80 x +`}, + {"find multiple -exec clauses", `find . -exec echo {} \; -exec nmap -p 80 {} \;`}, + {"find -exec shell wrapper", `find . -exec sh -ec 'nmap -p 80 x' \;`}, + {"parallel bare", "parallel nmap"}, + {"parallel with jobs and :::", "parallel -j 4 nmap -p 80 {} ::: 10.0.0.1"}, + {"parallel quoted shell string", "parallel -j 4 'nmap -p 80 {}' ::: 10.0.0.1"}, + {"parallel no command ::: bare", "parallel ::: nmap"}, + {"parallel no command ::: quoted line", `parallel ::: "nmap -p 80 x"`}, + {"parallel no command -j2 ::: bare", "parallel -j2 ::: nmap"}, + {"parallel no command ::: multiple lines", "parallel ::: echo nmap"}, + {"parallel --link ::: nmap", "parallel --link ::: nmap"}, + {"parallel --xargs ::: nmap", "parallel --xargs ::: nmap"}, + {"parallel unknown no-arg long opt", "parallel --future-flag ::: nmap"}, + {"parallel unknown value long opt", "parallel --future-val 42 nmap -p 80 x"}, + {"sudo unknown flag over-approximated", "sudo --unknown-flag nmap -p 80 x"}, + {"env unknown flag over-approximated", "env -Z nmap -p 80 x"}, + {"busybox", "busybox nmap -p 80 x"}, + {"busybox sh -c", "busybox sh -c 'nmap -p 80 x'"}, + {"chroot", "chroot / nmap -p 80 x"}, + {"chroot with userspec", "chroot --userspec=0:0 /mnt nmap -p 80 x"}, + {"exec", "exec -- nmap -p 80 x"}, + {"exec -a", "exec -a fake nmap -p 80 x"}, + {"semicolon list", "nmap -p 80 x; true"}, + {"and list", "true && nmap -p 80 x"}, + {"or list", "false || nmap -p 80 x"}, + {"pipeline", "nmap -p 80 x | tee out"}, + {"subshell", "(nmap -p 80 x)"}, + {"redirect", "nmap -p 80 x > out"}, + {"background", "nmap -p 80 x &"}, + {"prefix assign", "FOO=1 nmap -p 80 x"}, + {"expansion in later arg", "nmap $(id)"}, + {"param expansion in later arg", "nmap $TARGET"}, + {"command subst inside echo", "echo $(nmap -p 80 x)"}, + {"bash -c single quoted", "bash -c 'nmap -p 80 x'"}, + {"bash -x -c", "bash -x -c 'nmap -p 80 x'"}, + {"bash -lc", "bash -lc 'nmap -p 80 x'"}, + {"bash -ec", "bash -ec 'nmap -p 80 x'"}, + {"bash -o pipefail -c", "bash -o pipefail -c 'nmap -p 80 x'"}, + {"bash +o pipefail -c", "bash +o pipefail -c 'nmap -p 80 x'"}, + {"bash -O extglob -c", "bash -O extglob -c 'nmap -p 80 x'"}, + {"bash --norc -c", "bash --norc -c 'nmap -p 80 x'"}, + {"bash --noprofile --rcfile /dev/null -c --", "bash --noprofile --rcfile /dev/null -c -- 'nmap -p 80 x'"}, + {"sh -c double quoted", `sh -c "nmap -p 80 x"`}, + {"zsh -c", "zsh -c 'nmap -p 80 x'"}, + {"dash -c", "dash -c 'nmap -p 80 x'"}, + {"ksh -c", "ksh -c 'nmap -p 80 x'"}, + {"fish -c", "fish -c 'nmap -p 80 x'"}, + {"fish --command", "fish --command='nmap -p 80 x'"}, + {"path qualified bash -c", "/bin/bash -c 'nmap -p 80 x'"}, + {"eval quoted", "eval 'nmap -p 80 x'"}, + {"eval separate args", "eval nmap -p 80 x"}, + {"eval with trailing subst", "eval nmap $(id)"}, + {"stacked wrappers", "sudo env FOO=1 timeout 30 nohup command /usr/bin/nmap -p 80 x"}, + {"nested payload depth 2", `bash -c "sh -c 'nmap -p 80 x'"`}, + {"nested payload depth 3", `bash -c "sh -c \"eval 'nmap -p 80 x'\""`}, + {"bad nested payload does not block later call", `bash -c "if then"; nmap -p 80 x`}, + } + + for _, action := range []string{"deny", "ask"} { + for _, tc := range nmapShouldMatch { + t.Run(action+"/match/"+tc.name, func(t *testing.T) { + dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd)) + if !ok || dec.Action != action { + t.Errorf("%s [\"nmap\"] on %q: got (%+v, %v), want match with action %q", action, tc.cmd, dec, ok, action) + } + }) + } + } + + nmapShouldNotMatch := []struct { + name string + cmd string + }{ + {"argument to echo", "echo nmap"}, + {"prefix of other binary", "nmapx"}, + {"argument in pipeline", "echo x | grep nmap"}, + {"command -v lookup", "command -v nmap"}, + {"command -V lookup", "command -V nmap"}, + {"sudo -l list", "sudo -l nmap"}, + {"sudo -e edit", "sudo -e nmap"}, + {"env no command", "env FOO=1"}, + {"ionice pid mode", "ionice -p 1234"}, + {"taskset pid mode", "taskset -p 1234"}, + {"chrt pid mode", "chrt -p 1234"}, + {"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"}, + {"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"}, + {"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"}, + {"shell script mode with -x", "bash -x nmap"}, + {"shell script file", "bash nmap"}, + {"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"}, + {"find -exec echo nmap", `find . -exec echo nmap \;`}, + {"parallel echo with nmap input", "parallel echo ::: nmap"}, + {"parallel no command ::: echo nmap quoted", `parallel ::: "echo nmap"`}, + {"parallel echo nmap ::: x", "parallel echo nmap ::: x"}, + {"parallel --link echo nmap ::: x", "parallel --link echo nmap ::: x"}, + {"parallel :::: file input", "parallel :::: nmap"}, + {"parallel :::+ separator", "parallel :::+ nmap"}, + {"chroot without command", "chroot /"}, + {"busybox list mode", "busybox --list"}, + {"eval opaque leading arg", "eval $CMD nmap"}, + {"opaque command token", "$CMD -p 80 x"}, + {"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`}, + {"unparsable single quote", "nmap 'unterminated"}, + {"unparsable subst", "nmap $("}, + {"empty command", ""}, + } + + for _, action := range []string{"deny", "ask"} { + for _, tc := range nmapShouldNotMatch { + t.Run(action+"/nomatch/"+tc.name, func(t *testing.T) { + if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd)); ok { + t.Errorf("%s [\"nmap\"] on %q unexpectedly matched: %+v", action, tc.cmd, dec) + } + }) + } + } + + // Non-Bash tool never matches argv rules. + if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok { + t.Errorf("non-Bash tool matched deny rule: %+v", dec) + } +} + +func TestArgvDenyMultiTokenAndPathRules(t *testing.T) { + cases := []struct { + name string + pattern string + cmd string + want bool + }{ + {"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true}, + {"git config via command", `["git","config"]`, "command git config --list", true}, + {"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true}, + {"git config opaque subcommand", `["git","config"]`, "git $SUB --list", false}, + {"git status does not match git config", `["git","config"]`, "git status", false}, + {"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true}, + {"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false}, + {"exact path rule does not match other path", `["/usr/bin/nmap"]`, "/opt/bin/nmap -p 80 x", false}, + {"builtin wrapper matches echo", `["echo"]`, "builtin -- echo hi", true}, + {"xargs with no command does not invent echo", `["echo"]`, "xargs -n 1", false}, + {"wrapper itself can still be denied", `["sudo"]`, "sudo nmap -p 80 x", true}, + {"shell itself can still be denied", `["bash"]`, "bash -c 'echo hi'", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, got := matchSingleArgvRule("deny", tc.pattern, "Bash", bashInput(tc.cmd)) + if got != tc.want { + t.Errorf("deny %s on %q = %v, want %v", tc.pattern, tc.cmd, got, tc.want) + } + }) + } +} + +func TestArgvAllowRemainsStrict(t *testing.T) { + cases := []struct { + cmd string + want bool + }{ + {"nmap -p 80 x", true}, + {"command nmap x", false}, + {"nmap x; true", false}, + {"bash -c 'nmap x'", false}, + {"/usr/bin/nmap x", false}, + {"sudo nmap x", false}, + {"env FOO=1 nmap x", false}, + {"nmap $(id)", false}, + } + for _, tc := range cases { + t.Run(tc.cmd, func(t *testing.T) { + _, got := matchSingleArgvRule("allow", `["nmap"]`, "Bash", bashInput(tc.cmd)) + if got != tc.want { + t.Errorf("allow [\"nmap\"] on %q = %v, want %v", tc.cmd, got, tc.want) + } + }) + } +} + +func TestArgvCompoundMalformedInputDoesNotPanic(t *testing.T) { + inputs := [][]byte{ + nil, + []byte(``), + []byte(`not json`), + []byte(`{}`), + bashInput(`nmap 'unterminated`), + bashInput(`nmap $(`), + bashInput(`if then fi; (( (`), + bashInput(`bash -c "unterminated`), + bashInput(`eval "((("`), + } + for _, action := range []string{"deny", "ask", "allow"} { + for _, in := range inputs { + if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", in); ok { + t.Errorf("%s matched malformed input %q: %+v", action, string(in), dec) + } + } + } +} + +func TestArgvPriorityPreservedWithCompoundDeny(t *testing.T) { + ic := New(nil) + ic.SetRulesForTest([]db.InterceptRule{ + {ID: 1, Name: "allow simple nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"}, + {ID: 2, Name: "deny compound nmap", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"}, + }) + + // Simple command hits the higher-priority allow rule. + dec, ok := ic.Match("Bash", bashInput("nmap -p 80 x")) + if !ok || dec.Action != "allow" || dec.RuleID != 1 { + t.Fatalf("simple nmap: got (%+v, %v), want allow rule 1", dec, ok) + } + // Compound command fails the strict allow rule and falls through to the deny rule. + dec, ok = ic.Match("Bash", bashInput("nmap -p 80 x; true")) + if !ok || dec.Action != "deny" || dec.RuleID != 2 { + t.Fatalf("compound nmap: got (%+v, %v), want deny rule 2", dec, ok) + } +} diff --git a/intercept/argv_test.go b/intercept/argv_test.go index 82f09ba..4efbc8e 100644 --- a/intercept/argv_test.go +++ b/intercept/argv_test.go @@ -214,20 +214,20 @@ func TestParseArgvPattern(t *testing.T) { func TestArgvAllowBelowDeny(t *testing.T) { ic := New(nil) ic.SetRulesForTest([]db.InterceptRule{ - {ID: 1, Name: "no force push", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex", + {ID: 1, Name: "no force flag", Enabled: true, Priority: 50, MatchTarget: "tool_input", MatchType: "regex", Pattern: `--force`, Action: "deny"}, - {ID: 2, Name: "argv allow git push", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv", - Pattern: `["git","push"]`, Action: "allow"}, + {ID: 2, Name: "argv allow nmap", Enabled: true, Priority: -1000, MatchTarget: "tool_input", MatchType: "argv", + Pattern: `["nmap"]`, Action: "allow"}, }) - dec, ok := ic.Match("Bash", []byte(`{"command":"git push --force"}`)) + dec, ok := ic.Match("Bash", []byte(`{"command":"nmap --force 10.0.0.1"}`)) if !ok || dec.Action != "deny" || dec.RuleID != 1 { - t.Fatalf("force push: %+v %v, want the deny rule", dec, ok) + t.Fatalf("force flag: %+v %v, want the deny rule", dec, ok) } - dec, ok = ic.Match("Bash", []byte(`{"command":"git push origin"}`)) + dec, ok = ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1"}`)) if !ok || dec.Action != "allow" || dec.RuleID != 2 { - t.Fatalf("push: %+v %v, want the argv allow", dec, ok) + t.Fatalf("nmap: %+v %v, want the argv allow", dec, ok) } - if _, ok := ic.Match("Bash", []byte(`{"command":"git push; id"}`)); ok { + if _, ok := ic.Match("Bash", []byte(`{"command":"nmap 10.0.0.1; id"}`)); ok { t.Fatal("a compound command matched the argv rule") } if _, ok := compileRule(db.InterceptRule{MatchType: "argv", Pattern: `["-x"]`}); ok { diff --git a/intercept/default_tools_test.go b/intercept/default_tools_test.go new file mode 100644 index 0000000..4a8d8ef --- /dev/null +++ b/intercept/default_tools_test.go @@ -0,0 +1,48 @@ +package intercept + +import "testing" + +// TestDefaultEnabledToolsCoverExecutors pins the tools that must be gated when no +// intercept_enabled_tools setting has been saved. ExecuteExtraTool and Monitor +// dispatch MCP / deferred tools and background commands, so leaving them out let +// those calls bypass every rule. +func TestDefaultEnabledToolsCoverExecutors(t *testing.T) { + got := map[string]bool{} + for _, name := range defaultEnabledTools { + got[name] = true + } + for _, want := range []string{"Bash", "Write", "Edit", "MultiEdit", "ExecuteExtraTool", "Monitor"} { + if !got[want] { + t.Errorf("defaultEnabledTools must include %q", want) + } + } + for _, readOnly := range []string{"list_assets", "traffic_search", "Read"} { + if got[readOnly] { + t.Errorf("defaultEnabledTools must not gate the read-only tool %q by default", readOnly) + } + } +} + +// TestEnabledToolsFromSettingNeverDisablesTheGate: an unset or malformed setting +// must keep the defaults, not turn the rule system off. +func TestEnabledToolsFromSettingNeverDisablesTheGate(t *testing.T) { + for _, tc := range []struct { + name string + val string + ok bool + }{ + {"unset", "", false}, + {"malformed", "{not json", true}, + {"wrong shape", `"Bash"`, true}, + } { + got := enabledToolsFromSetting(tc.val, tc.ok) + if !got["Bash"] || !got["ExecuteExtraTool"] || !got["Monitor"] { + t.Errorf("%s: enabled tools %v, want the defaults", tc.name, got) + } + } + // A valid explicit list replaces the defaults. + got := enabledToolsFromSetting(`["Bash"]`, true) + if !got["Bash"] || got["WebFetch"] { + t.Fatalf("explicit list: %v, want only Bash", got) + } +} diff --git a/intercept/intercept.go b/intercept/intercept.go index 70bbf90..c9078e9 100644 --- a/intercept/intercept.go +++ b/intercept/intercept.go @@ -211,6 +211,9 @@ type Interceptor struct { // upstreamProxy reports whether target traffic leaves through an upstream // egress proxy (nil = no). Injected by the server layer. upstreamProxy func() bool + // toolProxy reports whether one tool's own configuration routes its traffic + // through a proxy (nil = no). Injected by the server layer. + toolProxy func(string) bool // derivedExempt lists the endpoints of the platform's own services (nil = // none). Injected by the server layer. See SetDerivedExemptions. derivedExempt func() []string @@ -234,6 +237,15 @@ func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) { i.mu.Unlock() } +// SetToolProxyCheck installs the function that reports whether a tool sends its +// own traffic through a proxy. The proxy then chooses the address it connects +// to, so a target approval for that call is name-only. Passing nil disables it. +func (i *Interceptor) SetToolProxyCheck(f func(string) bool) { + i.mu.Lock() + i.toolProxy = f + i.mu.Unlock() +} + // SetReviewer installs the LLM fallback judge callback. Passing nil disables it. func (i *Interceptor) SetReviewer(r Reviewer) { i.mu.Lock() @@ -254,6 +266,10 @@ var defaultEnabledTools = []string{ "Bash", "WebFetch", "web_search", "shell_open", "shell_send", "Write", "Edit", "MultiEdit", + // ExecuteExtraTool dispatches MCP and deferred tools, and Monitor starts a + // background command; both execute third-party or shell commands, so they + // belong in the default gate with the rest. + "ExecuteExtraTool", "Monitor", } // New creates an Interceptor backed by d. The rule cache is lazy-loaded on @@ -293,27 +309,32 @@ func (i *Interceptor) loadLocked() error { // Load enabled-tools set from settings, falling back to hard-coded defaults. val, ok, _ := i.db.GetSetting("intercept_enabled_tools") - if !ok { - m := make(map[string]bool, len(defaultEnabledTools)) - for _, n := range defaultEnabledTools { - m[n] = true - } - i.enabledTools = m - } else { - var names []string - if json.Unmarshal([]byte(val), &names) != nil { - i.enabledTools = map[string]bool{} - } else { - m := make(map[string]bool, len(names)) - for _, n := range names { - m[n] = true - } - i.enabledTools = m - } - } + i.enabledTools = enabledToolsFromSetting(val, ok) return nil } +// enabledToolsFromSetting maps the stored intercept_enabled_tools value to the +// gate's set. A malformed value must not silently disable the gate, so it falls +// back to the same defaults as an unset setting. +func enabledToolsFromSetting(val string, ok bool) map[string]bool { + m := make(map[string]bool, len(defaultEnabledTools)) + for _, n := range defaultEnabledTools { + m[n] = true + } + if !ok { + return m + } + var names []string + if json.Unmarshal([]byte(val), &names) != nil { + return m + } + m = make(map[string]bool, len(names)) + for _, n := range names { + m[n] = true + } + return m +} + func (i *Interceptor) rules() ([]compiledRule, error) { i.mu.RLock() if i.cached != nil { @@ -369,7 +390,7 @@ func (i *Interceptor) GetEnabledTools() ([]string, error) { } var names []string if err := json.Unmarshal([]byte(val), &names); err != nil { - return []string{}, nil + return nil, fmt.Errorf("intercept_enabled_tools is not valid JSON: %w", err) } return names, nil } @@ -753,12 +774,20 @@ func (i *Interceptor) SetRulesForTest(rules []db.InterceptRule) { func ruleMatches(r compiledRule, toolName string, input []byte) bool { if r.MatchType == "argv" { // Bash only, on the parsed command; match_target is always tool_input. - // The denylist neutralises allow rules only: an argv deny or ask rule - // for a denylisted program still matches. - if r.Action == "allow" && CheckArgvAllow(r.argv) != nil { - return false + // Allow rules stay strictly limited to a single simple command with + // exact derived prefix and denylist enforcement. Deny and ask rules + // walk every call in a compound Bash command, stripping known wrappers + // and recursing into eval / shell -c payloads. + if r.Action == "allow" { + if CheckArgvAllow(r.argv) != nil { + return false + } + return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input) } - return r.MatchTarget == "tool_input" && argvRuleMatches(r.argv, toolName, input) + if r.Action == "deny" || r.Action == "ask" { + return r.MatchTarget == "tool_input" && argvCompoundMatches(r.argv, toolName, input) + } + return false } var subject string switch r.MatchTarget { diff --git a/intercept/target_exempt.go b/intercept/target_exempt.go index ea1b552..d9e1202 100644 --- a/intercept/target_exempt.go +++ b/intercept/target_exempt.go @@ -165,6 +165,18 @@ func (i *Interceptor) loadExemptions() (exemptions, error) { return ex, nil } +// IsNonPublicAddr reports whether addr is private (RFC1918, fc00::/7 unique +// local), loopback, link-local (including 169.254.169.254 and fe80::/10), +// unspecified, multicast, or a known instance-metadata address. +// Invalid addresses are treated as non-public (fail closed). +func IsNonPublicAddr(addr netip.Addr) bool { + if !addr.IsValid() { + return true + } + addr = addr.Unmap().WithZone("") + return addr.IsPrivate() || ValidateExemptionHost(addr.String()) != nil +} + // voidsExemption reports whether one resolved address voids a stored // exemption on a name: a private address (10/8, 172.16/12, 192.168/16, the // unique local range fc00::/7), or one that is never exempt as a literal @@ -175,6 +187,5 @@ func voidsExemption(ip string) bool { if err != nil { return true } - a = a.Unmap().WithZone("") - return a.IsPrivate() || ValidateExemptionHost(a.String()) != nil + return IsNonPublicAddr(a) } diff --git a/intercept/target_gate.go b/intercept/target_gate.go index de7b8e2..bd2a475 100644 --- a/intercept/target_gate.go +++ b/intercept/target_gate.go @@ -208,11 +208,13 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) { i.mu.RLock() proxied := i.upstreamProxy + toolProxy := i.toolProxy i.mu.RUnlock() - // Behind the upstream proxy the proxy chooses the address it connects to, so - // every pin is name-only for this call, whatever the pin row says: the proxy - // can be turned on after a pin was approved. - nameOnly := proxied != nil && proxied() + // Behind a proxy the proxy chooses the address it connects to, so every pin + // is name-only for this call, whatever the pin row says: the proxy can be + // turned on after a pin was approved. The recording proxy, the global egress + // proxy and a custom tool's own proxy all count. + nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool)) var unpinned []TargetRequest var uses []func() diff --git a/intercept/target_gate_test.go b/intercept/target_gate_test.go index a4d4376..8665121 100644 --- a/intercept/target_gate_test.go +++ b/intercept/target_gate_test.go @@ -975,6 +975,31 @@ func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) { g.passes("name-only pin, no proxy", g.fetch(appURL)) } +// A custom tool that carries its own proxy cannot enforce an approved IP, so +// its pins are name-only at call time, the same as behind the upstream proxy. +func TestToolProxyMakesPinsNameOnlyAtCallTime(t *testing.T) { + g := newGate(t) + proxied := false + g.ic.SetToolProxyCheck(func(string) bool { return proxied }) + const tool = "my_http_tool" + const input = `{"url":"https://app.example.com/login"}` + g.res.set("app.example.com", "203.0.113.7") + g.pin("app.example.com", 443, "203.0.113.7") + + // The address changes. A direct call asks. + g.res.set("app.example.com", "198.51.100.99") + g.expire() + g.requests("changed address, direct tool", g.check(tool, input)) + + // The same pin covers the name for the proxied tool, and the first-use row + // records that the connection was not bound. + proxied = true + g.passes("changed address, proxied tool", g.check(tool, input)) + if got := g.store.outcomes(); len(got) != 1 || got[0] != "allowed/pin_match" || !g.store.logged[0].Audit.Targets[0].NameOnlyEffective { + t.Fatalf("rows %v, target %+v; want a name-only first use", got, g.store.logged[0].Audit.Targets[0]) + } +} + // The first call that a pin version covers is logged once per process. func TestPinFirstUseLoggedOncePerVersion(t *testing.T) { g := newGate(t) diff --git a/llmrec/capture.go b/llmrec/capture.go index 555d6ff..f639934 100644 --- a/llmrec/capture.go +++ b/llmrec/capture.go @@ -35,8 +35,17 @@ type Capture struct { type attempt struct { status int body strings.Builder + full bool // true once body hit maxAttemptBody; further reads are not stored } +// maxAttemptBody is the captured size of one HTTP attempt. The stream still +// reaches the caller in full; only the in-memory mirror stops. +const maxAttemptBody = 1 << 20 // 1 MiB + +// maxCaptureAttempts is how many HTTP attempts one Capture keeps. Further +// attempts pass through unread into the mirror. +const maxCaptureAttempts = 8 + // NewCapture returns a context carrying a fresh Capture, plus the Capture itself. func NewCapture(ctx context.Context) (context.Context, *Capture) { c := &Capture{} @@ -74,8 +83,12 @@ func (c *Capture) TeeResponse(status int, rc io.ReadCloser) io.ReadCloser { if c == nil || rc == nil { return rc } - a := &attempt{status: status} c.mu.Lock() + if len(c.attempts) >= maxCaptureAttempts { + c.mu.Unlock() + return rc + } + a := &attempt{status: status} c.attempts = append(c.attempts, a) c.mu.Unlock() return &teeBody{rc: rc, c: c, a: a} @@ -153,7 +166,15 @@ func (t *teeBody) Read(p []byte) (int, error) { n, err := t.rc.Read(p) if n > 0 { t.c.mu.Lock() - t.a.body.Write(p[:n]) + if !t.a.full { + remain := maxAttemptBody - t.a.body.Len() + if n > remain { + t.a.body.Write(p[:remain]) + t.a.full = true + } else { + t.a.body.Write(p[:n]) + } + } t.c.mu.Unlock() } return n, err diff --git a/llmrec/capture_test.go b/llmrec/capture_test.go index 3386202..7ac5cc0 100644 --- a/llmrec/capture_test.go +++ b/llmrec/capture_test.go @@ -95,6 +95,30 @@ func TestCaptureRetriedAttemptsAreAllKept(t *testing.T) { } } +func TestCaptureCapsAttemptBodyAndCount(t *testing.T) { + _, c := NewCapture(context.Background()) + payload := strings.Repeat("a", maxAttemptBody+4096) + body := c.TeeResponse(200, io.NopCloser(strings.NewReader(payload))) + got, err := io.ReadAll(body) + if err != nil { + t.Fatalf("read: %v", err) + } + if len(got) != len(payload) { + t.Fatalf("tee truncated the caller stream: %d want %d", len(got), len(payload)) + } + if n := len(c.RawResponse()); n != maxAttemptBody { + t.Fatalf("captured %d bytes, want cap %d", n, maxAttemptBody) + } + + for i := 1; i < maxCaptureAttempts+3; i++ { + rc := c.TeeResponse(200, io.NopCloser(strings.NewReader("x"))) + _, _ = io.ReadAll(rc) + } + if n := len(c.Attempts()); n != maxCaptureAttempts { + t.Fatalf("attempts %d, want %d", n, maxCaptureAttempts) + } +} + func TestCaptureEmptyWhenNoHTTPHappened(t *testing.T) { _, c := NewCapture(context.Background()) if c.RawRequest() != "" || c.RawResponse() != "" { diff --git a/mcphttp/client.go b/mcphttp/client.go index 25cbb61..f5893a3 100644 --- a/mcphttp/client.go +++ b/mcphttp/client.go @@ -17,6 +17,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "net/url" "strings" @@ -31,6 +32,10 @@ import ( const protocolVersion = "2025-11-25" const legacySSEProtocolVersion = "2024-11-05" +// mcpMaxRPCBytes is the largest JSON-RPC response (JSON body or SSE data +// payload) the client will buffer. A remote MCP server is untrusted. +const mcpMaxRPCBytes = 8 << 20 + // ToolName mirrors mcp.ToolName so remote tools share the mcp__server__tool scheme. func ToolName(server, name string) string { return "mcp__" + server + "__" + name } @@ -97,6 +102,66 @@ func normalizeHeaders(headers map[string]string) (map[string]string, error) { return out, nil } +// originKey returns the scheme, host and effective port of u, in a form two +// URLs can be compared with. Empty means u is not an absolute http(s) URL with +// a host. +func originKey(u *url.URL) string { + if u == nil { + return "" + } + scheme := strings.ToLower(u.Scheme) + var port string + switch scheme { + case "http": + port = "80" + case "https": + port = "443" + default: + return "" + } + host := strings.ToLower(u.Hostname()) + if host == "" { + return "" + } + if p := u.Port(); p != "" { + port = p + } + return scheme + "://" + net.JoinHostPort(host, port) +} + +// sameOrigin reports whether u has the same scheme, host and effective port as +// base. +func sameOrigin(base, u *url.URL) bool { + key := originKey(base) + return key != "" && key == originKey(u) +} + +// redirectPolicy refuses a redirect that leaves the origin of the configured +// endpoint, so a remote MCP server cannot retarget authenticated requests. +func redirectPolicy(base *url.URL) func(*http.Request, []*http.Request) error { + return func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("mcp: stopped after 10 redirects") + } + if !sameOrigin(base, req.URL) { + return fmt.Errorf("mcp: refusing a redirect to another origin: %s", req.URL.Redacted()) + } + return nil + } +} + +// parseMCPURL parses and validates a configured MCP endpoint URL. +func parseMCPURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + return nil, fmt.Errorf("mcp url: %w", err) + } + if originKey(u) == "" { + return nil, fmt.Errorf("mcp url must be an absolute http or https URL with a host: %q", raw) + } + return u, nil +} + // New connects to a remote MCP endpoint and performs the initialize handshake. // headers are sent on every request (Authorization, custom API keys, …). // When insecure is true, TLS certificate verification is skipped so servers that @@ -113,7 +178,11 @@ func New(ctx context.Context, server, url string, headers map[string]string, ins if timeoutSeconds > 0 { timeout = time.Duration(timeoutSeconds) * time.Second } - hc := &http.Client{Timeout: timeout} + base, err := parseMCPURL(url) + if err != nil { + return nil, err + } + hc := &http.Client{Timeout: timeout, CheckRedirect: redirectPolicy(base)} if insecure { hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} } @@ -138,7 +207,11 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin if err != nil { return nil, err } - hc := &http.Client{} // the SSE stream is intentionally long-lived. + base, err := parseMCPURL(sseURL) + if err != nil { + return nil, err + } + hc := &http.Client{CheckRedirect: redirectPolicy(base)} // the SSE stream is intentionally long-lived. if insecure { hc.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} } @@ -163,7 +236,7 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin return nil, fmt.Errorf("mcp sse http %d: %s", resp.StatusCode, readSnippet(resp.Body)) } reader := bufio.NewReader(resp.Body) - endpoint, err := readSSEEndpoint(reader, sseURL) + endpoint, err := readSSEEndpoint(reader, base) if err != nil { resp.Body.Close() cancel() @@ -191,7 +264,11 @@ func NewSSE(ctx context.Context, server, sseURL string, headers map[string]strin return c, nil } -func readSSEEndpoint(r *bufio.Reader, base string) (string, error) { +// readSSEEndpoint reads the message endpoint announced by the SSE stream. The +// endpoint must stay on the origin of the configured SSE URL: the POSTs that +// follow carry the operator's headers, and a remote server must not be able to +// retarget them. +func readSSEEndpoint(r *bufio.Reader, base *url.URL) (string, error) { for { line, err := r.ReadString('\n') if err != nil { @@ -209,14 +286,17 @@ func readSSEEndpoint(r *bufio.Reader, base string) (string, error) { if err != nil { return "", fmt.Errorf("mcp sse endpoint URL: %w", err) } - if !u.IsAbs() { - b, err := url.Parse(base) - if err != nil { - return "", err - } - candidate = b.ResolveReference(u).String() + if u.User != nil { + return "", errors.New("mcp sse endpoint must not carry userinfo") } - return candidate, nil + abs := u + if !u.IsAbs() { + abs = base.ResolveReference(u) + } + if !sameOrigin(base, abs) { + return "", fmt.Errorf("mcp sse endpoint %q is not on the configured origin", abs.Redacted()) + } + return abs.String(), nil } } @@ -352,10 +432,14 @@ func (c *Client) wrap(rt remoteTool) actool.CoreTool { if err := json.Unmarshal(raw, &res); err != nil { return actool.Errorf("Error: bad MCP response: " + err.Error()), nil } - var text string + var b strings.Builder for _, blk := range res.Content { - text += blk.Text + b.WriteString(blk.Text) + if b.Len() > mcpMaxRPCBytes { + break + } } + text := b.String() // Consistent with built-in/custom tools: oversized output goes through Capture — // truncated at the session's MaxOutputChars (default 30000), and when // ToolOutputDir is configured the full output spills to disk leaving only the @@ -510,8 +594,21 @@ func (c *Client) roundTrip(ctx context.Context, body rpcRequest, expectResp bool if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { return parseSSE(resp.Body, body.ID) } + return decodeRPC(resp.Body) +} + +// decodeRPC reads one JSON-RPC response, refusing a body larger than +// mcpMaxRPCBytes so a remote server cannot force an unbounded allocation. +func decodeRPC(r io.Reader) (*rpcResponse, error) { + data, err := io.ReadAll(io.LimitReader(r, mcpMaxRPCBytes+1)) + if err != nil { + return nil, fmt.Errorf("mcp: read json response: %w", err) + } + if len(data) > mcpMaxRPCBytes { + return nil, fmt.Errorf("mcp: json response exceeds %d bytes", mcpMaxRPCBytes) + } var out rpcResponse - if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + if err := json.Unmarshal(data, &out); err != nil { return nil, fmt.Errorf("mcp: decode json response: %w", err) } return &out, nil @@ -602,6 +699,9 @@ func parseSSE(r io.Reader, wantID int) (*rpcResponse, error) { } if strings.HasPrefix(line, "data:") { dataBuf.WriteString(strings.TrimSpace(line[len("data:"):])) + if dataBuf.Len() > mcpMaxRPCBytes { + return nil, fmt.Errorf("mcp: sse payload exceeds %d bytes", mcpMaxRPCBytes) + } } } if resp, ok := flush(); ok { diff --git a/mcphttp/client_sse_test.go b/mcphttp/client_sse_test.go index b470f9c..8e525ad 100644 --- a/mcphttp/client_sse_test.go +++ b/mcphttp/client_sse_test.go @@ -1,11 +1,13 @@ package mcphttp import ( + "bufio" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" + "net/url" "strings" "sync" "testing" @@ -105,3 +107,134 @@ func TestLegacySSEClientDiscoverAndCall(t *testing.T) { t.Fatalf("Call() = %q, %v", got, err) } } + +func TestReadSSEEndpointSameOrigin(t *testing.T) { + base, err := url.Parse("https://mcp.example.com:8443/sse") + if err != nil { + t.Fatal(err) + } + read := func(line string) (string, error) { + stream := "event: endpoint\ndata: " + line + "\n\n" + return readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base) + } + for _, line := range []string{ + "/message?sessionId=1", + "https://mcp.example.com:8443/message", + "HTTPS://MCP.EXAMPLE.COM:8443/message", + "//mcp.example.com:8443/message", + } { + got, err := read(line) + if err != nil { + t.Errorf("%q: %v", line, err) + continue + } + u, err := url.Parse(got) + if err != nil || !sameOrigin(base, u) { + t.Errorf("%q: resolved to %q, not the configured origin", line, got) + } + } + for _, line := range []string{ + "https://evil.example/message", + "http://mcp.example.com:8443/message", + "https://mcp.example.com:444/message", + "//evil.example/message", + "http://user:pass@mcp.example.com:8443/message", + "ftp://mcp.example.com/message", + } { + if got, err := read(line); err == nil { + t.Errorf("%q: accepted as %q, want a refusal", line, got) + } + } +} + +func TestReadSSEEndpointDefaultPort(t *testing.T) { + base, err := url.Parse("https://mcp.example.com/sse") + if err != nil { + t.Fatal(err) + } + stream := "data: https://mcp.example.com:443/message\n\n" + if _, err := readSSEEndpoint(bufio.NewReader(strings.NewReader(stream)), base); err != nil { + t.Fatalf("explicit default port refused: %v", err) + } +} + +func TestParseMCPURL(t *testing.T) { + for _, raw := range []string{"ftp://x/y", "not-a-url", "http:///nohost", ""} { + if _, err := parseMCPURL(raw); err == nil { + t.Errorf("%q accepted, want a refusal", raw) + } + } + for _, raw := range []string{"http://x/y", "https://x:8443/y"} { + if _, err := parseMCPURL(raw); err != nil { + t.Errorf("%q refused: %v", raw, err) + } + } +} + +func TestLegacySSERefusesCrossOriginEndpoint(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "event: endpoint\ndata: http://evil.invalid/message\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer srv.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := NewSSE(ctx, "test", srv.URL+"/sse", nil, false); err == nil { + t.Fatal("cross-origin SSE endpoint accepted") + } +} + +func TestMCPClientRefusesCrossOriginRedirect(t *testing.T) { + var hits int + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits++ + })) + defer target.Close() + src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+"/steal", http.StatusFound) + })) + defer src.Close() + + base, err := url.Parse(src.URL + "/sse") + if err != nil { + t.Fatal(err) + } + hc := &http.Client{CheckRedirect: redirectPolicy(base)} + resp, err := hc.Get(src.URL + "/sse") + if err == nil { + resp.Body.Close() + t.Fatal("cross-origin redirect accepted") + } + if hits != 0 { + t.Fatalf("redirect target was reached %d times", hits) + } +} + +func TestMCPClientAllowsSameOriginRedirect(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/sse2", http.StatusFound) + }) + mux.HandleFunc("/sse2", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + base, err := url.Parse(srv.URL + "/sse") + if err != nil { + t.Fatal(err) + } + hc := &http.Client{CheckRedirect: redirectPolicy(base)} + resp, err := hc.Get(srv.URL + "/sse") + if err != nil { + t.Fatalf("same-origin redirect refused: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("status %d", resp.StatusCode) + } +} diff --git a/mcphttp/client_test.go b/mcphttp/client_test.go index 12e7810..194f407 100644 --- a/mcphttp/client_test.go +++ b/mcphttp/client_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "strings" "testing" "time" ) @@ -233,3 +234,28 @@ func TestStreamableClientVersionRejectionForms(t *testing.T) { }) } } + +func TestDecodeRPCCapsBody(t *testing.T) { + ok := `{"jsonrpc":"2.0","id":1,"result":{}}` + got, err := decodeRPC(strings.NewReader(ok)) + if err != nil || got == nil || got.ID != 1 { + t.Fatalf("small body: got=%+v err=%v", got, err) + } + if _, err := decodeRPC(strings.NewReader(strings.Repeat("x", mcpMaxRPCBytes+1))); err == nil { + t.Fatal("oversize body must fail") + } +} + +func TestParseSSECapsPayload(t *testing.T) { + chunk := strings.Repeat("a", 64*1024) + var b strings.Builder + for b.Len() <= mcpMaxRPCBytes { + b.WriteString("data: ") + b.WriteString(chunk) + b.WriteByte('\n') + } + b.WriteByte('\n') + if _, err := parseSSE(strings.NewReader(b.String()), 1); err == nil { + t.Fatal("oversize SSE payload must fail") + } +} diff --git a/server/assembly.go b/server/assembly.go index 24bff8b..b2ae7d6 100644 --- a/server/assembly.go +++ b/server/assembly.go @@ -44,7 +44,7 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor for _, n := range names { nameSet[n] = true } - if allReg, err := skill.LoadDir(skillDir); err == nil && allReg != nil { + if allReg, err := loadSkillsConfined(skillDir); err == nil && allReg != nil { reg = skill.NewRegistry() for _, s := range allReg.List() { // match by directory name (Base of Dir), not by skill display Name diff --git a/server/auth.go b/server/auth.go index 814b9d1..2d51550 100644 --- a/server/auth.go +++ b/server/auth.go @@ -283,11 +283,11 @@ func extractToken(r *http.Request) string { } // requireAuth wraps h with JWT validation. -// /api/auth/* and /api/health are exempt. +// /api/auth/*, /api/health and /api/ready are exempt. func (s *Server) requireAuth(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := r.URL.Path - if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" { + if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" || p == "/api/ready" { h.ServeHTTP(w, r) return } diff --git a/server/conversations.go b/server/conversations.go index 7c0d916..cb810ae 100644 --- a/server/conversations.go +++ b/server/conversations.go @@ -311,16 +311,16 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request) return } q := r.URL.Query() - limit := atoiDefault(q.Get("limit"), 200) s.chatMu.Lock() running := s.chatBusy[s.convBusyKey(c.ID)] s.chatMu.Unlock() // Incremental tail: ?since=N returns steps after id N (ASC) — used by the live - // poll and the post-send fetch. A generous cap so a burst is never dropped. + // poll and the post-send fetch. Capped so a huge limit cannot materialise the + // whole transcript in one response. if sv := q.Get("since"); sv != "" { since, _ := strconv.ParseInt(sv, 10, 64) - items, cursor, err := pg.ConvActivityList(c.ID, since, max(limit, 1000)) + items, cursor, err := pg.ConvActivityList(c.ID, since, 1000) if err != nil { writeErr(w, 500, err.Error()) return @@ -333,7 +333,7 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request) // the page of older steps ending before id N. hasMore lets the client stop // loading earlier history once the top of the thread is reached. before, _ := strconv.ParseInt(q.Get("before"), 10, 64) - items, hasMore, err := pg.ConvActivityPage(c.ID, before, limit) + items, hasMore, err := pg.ConvActivityPage(c.ID, before, convMessageLimit(q.Get("limit"), 200, 200)) if err != nil { writeErr(w, 500, err.Error()) return @@ -345,6 +345,19 @@ func (s *Server) pgConversationMessages(w http.ResponseWriter, r *http.Request) writeJSON(w, 200, map[string]any{"items": activityDTOs(items), "cursor": cursor, "running": running, "hasMore": hasMore}) } +// convMessageLimit clamps a page size. Missing or invalid values use def; the +// result is at most cap so a huge query cannot materialise the whole transcript. +func convMessageLimit(raw string, maxN, def int) int { + n := atoiDefault(raw, def) + if n < 1 { + n = def + } + if n > maxN { + n = maxN + } + return n +} + // pgConversationMsgDetail lazily returns one step's full detail blob. func (s *Server) pgConversationMsgDetail(w http.ResponseWriter, r *http.Request) { pg, c, ok := s.convByID(w, r) diff --git a/server/conversations_limit_test.go b/server/conversations_limit_test.go new file mode 100644 index 0000000..7813a7d --- /dev/null +++ b/server/conversations_limit_test.go @@ -0,0 +1,21 @@ +package server + +import "testing" + +func TestConvMessageLimit(t *testing.T) { + if got := convMessageLimit("", 200, 200); got != 200 { + t.Fatalf("default: %d", got) + } + if got := convMessageLimit("50", 200, 200); got != 50 { + t.Fatalf("50: %d", got) + } + if got := convMessageLimit("2147483646", 200, 200); got != 200 { + t.Fatalf("huge history: %d", got) + } + if got := convMessageLimit("2147483646", 1000, 1000); got != 1000 { + t.Fatalf("huge since: %d", got) + } + if got := convMessageLimit("-1", 200, 200); got != 200 { + t.Fatalf("negative: %d", got) + } +} diff --git a/server/engine.go b/server/engine.go index bc8c6f4..999af5d 100644 --- a/server/engine.go +++ b/server/engine.go @@ -1182,6 +1182,27 @@ func (e *Engine) runWorkerStep(ctx context.Context, t *Task, name string, worker return e.runIntent(ctx, t, name, worker, intent, token, "", "") } +// intentWorkContext resolves the cached per-task exec context and returns a +// per-intent child context with the rotated LLM profile pin attached (#85, +// #376). Attaching the pin after execContextFor ensures a cached e.execCtx +// does not drop it; attaching it after the paused/deleting check ensures a +// rolled-back claim never advances the rotation counter. +func (e *Engine) intentWorkContext(ctx context.Context, t *Task) (ectx, workCtx context.Context, workCancel context.CancelCauseFunc, ok bool) { + ectx = e.clockCtx(e.execContextFor(ctx, t.ID), t, false) // cancellable by Pause; carries the task deadline + if ectx.Err() != nil || e.IsDeleting(t.ID) { + return ectx, nil, nil, false + } + // per-work child context so the planner's kill_work can stop just this work. + workCtx, workCancel = context.WithCancelCause(ectx) + // Per-intent LLM rotation (#85): each claimed worker intent runs on the + // next chain head. The pin travels through the run context into the + // provider resolver; non-worker roles and failover keep the active head. + if head, pinned := t.nextRotatedProfile(); pinned { + workCtx = withLLMProfilePin(workCtx, head) + } + return ectx, workCtx, workCancel, true +} + // runIntent executes and fully settles one already-claimed (state=running) intent. // Both the pool worker loop (via runWorkerStep) and the human-message handler (via // runDetachedIntent, a dedicated goroutine outside the worker pool) call it, so the @@ -1194,25 +1215,17 @@ func (e *Engine) runWorkerStep(ctx context.Context, t *Task, name string, worker // while the worker is busy, and every intent state write below is fenced on it, // so a worker whose claim was taken over cannot overwrite the new claimer. func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *agent.Worker, intent *db.Node, token, requestID, message string) bool { - // Per-intent LLM rotation (#85): each claimed worker intent runs on the - // next chain head. The pin travels through the run context into the - // provider resolver; non-worker roles and failover keep the active head. - if head, ok := t.nextRotatedProfile(); ok { - ctx = withLLMProfilePin(ctx, head) - } hasChatMessage := message != "" e.stampFirstRun(t) // first real execution → stamp first_run_at + compute the deadline (only for tasks with a timeout) e.touch(t.ID) emit := func(r db.Activity) { e.emitActivity(t, r) } - ectx := e.clockCtx(e.execContextFor(ctx, t.ID), t, false) // cancellable by Pause; carries the task deadline - if ectx.Err() != nil || e.IsDeleting(t.ID) { + ectx, workCtx, workCancel, ok := e.intentWorkContext(ctx, t) + if !ok { if err := t.Store.SettleIntentClaim(intent.ID, token, "open"); err != nil { log.Printf("[worker %s] task %s intent #%d claim rollback failed: %v", name, t.ID, intent.ID, err) } return true } - // per-work child context so the planner's kill_work can stop just this work. - workCtx, workCancel := context.WithCancelCause(ectx) e.registerWork(intent.ID, workCancel) stopHeartbeat := startClaimHeartbeat(t.Store, db.IntentClaimHeartbeatInterval, name, intent.ID, token, workCancel) // wrap the guard hooks so steer_work can inject a mid-run course-correction diff --git a/server/intercept_argv_test.go b/server/intercept_argv_test.go index acab9e9..5e28c7f 100644 --- a/server/intercept_argv_test.go +++ b/server/intercept_argv_test.go @@ -7,7 +7,7 @@ import ( ) func TestValidateArgvRuleReq(t *testing.T) { - base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["git","push"]`, Action: "allow"} + base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "allow"} if err := validateInterceptRuleReq(base); err != nil { t.Fatalf("valid argv rule refused: %v", err) } @@ -15,7 +15,7 @@ func TestValidateArgvRuleReq(t *testing.T) { "tool_name target": func(r *interceptRuleReq) { r.MatchTarget = "tool_name" }, "empty pattern": func(r *interceptRuleReq) { r.Pattern = "" }, "empty token": func(r *interceptRuleReq) { r.Pattern = `["git",""]` }, - "flag token": func(r *interceptRuleReq) { r.Pattern = `["git","-C"]` }, + "flag token": func(r *interceptRuleReq) { r.Pattern = `["nmap","-C"]` }, "metacharacter": func(r *interceptRuleReq) { r.Pattern = `["nmap;id"]` }, "nine tokens": func(r *interceptRuleReq) { r.Pattern = `["a","b","c","d","e","f","g","h","i"]` }, "not an array": func(r *interceptRuleReq) { r.Pattern = `git push` }, @@ -31,7 +31,7 @@ func TestValidateArgvRuleReq(t *testing.T) { // The manual rule form refuses an argv allow rule for a denylisted program, // with the message of the "always allow" endpoint; deny and ask stay creatable. func TestValidateArgvAllowDenylist(t *testing.T) { - for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`} { + for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`, `["git","push"]`, `["cmake"]`} { req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"} tokens, _ := intercept.ParseArgvPattern(pattern) want := intercept.CheckArgvAllow(tokens) @@ -45,7 +45,7 @@ func TestValidateArgvAllowDenylist(t *testing.T) { } } } - for _, pattern := range []string{`["nmap"]`, `["git","push"]`} { + for _, pattern := range []string{`["nmap"]`, `["curl"]`} { req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"} if err := validateInterceptRuleReq(req); err != nil { t.Errorf("allow %s refused: %v", pattern, err) diff --git a/server/llm_key_endpoint_test.go b/server/llm_key_endpoint_test.go index 6e59826..114aee5 100644 --- a/server/llm_key_endpoint_test.go +++ b/server/llm_key_endpoint_test.go @@ -130,6 +130,7 @@ func TestStoredProfileKeyOnlyForStoredEndpoint(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + s.allowLoopbackModels = true s.cfgMu.Lock() s.llmCfg = agent.Config{} // no global key to fall back on s.cfgMu.Unlock() diff --git a/server/llm_models_ssrf_test.go b/server/llm_models_ssrf_test.go new file mode 100644 index 0000000..61ba038 --- /dev/null +++ b/server/llm_models_ssrf_test.go @@ -0,0 +1,920 @@ +package server + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Autumn-27/artex/agent" +) + +func dialTestServerForHosts(routes map[string]string, fallback func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) { + return func(ctx context.Context, network, addr string) (net.Conn, error) { + if target, ok := routes[strings.ToLower(addr)]; ok { + return (&net.Dialer{}).DialContext(ctx, network, target) + } + host, _, err := net.SplitHostPort(addr) + if err == nil { + if target, ok := routes[strings.ToLower(host)]; ok { + return (&net.Dialer{}).DialContext(ctx, network, target) + } + } + return fallback(ctx, network, addr) + } +} + +// newTestTLSServer starts an HTTPS httptest server with a leaf certificate +// valid for dnsNames and returns the server and a CertPool trusting it. +func newTestTLSServer(t *testing.T, dnsNames []string, h http.Handler) (*httptest.Server, *x509.CertPool) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: dnsNames[0]}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + DNSNames: dnsNames, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + pool := x509.NewCertPool() + pool.AddCert(cert) + + srv := httptest.NewUnstartedServer(h) + srv.TLS = &tls.Config{ + Certificates: []tls.Certificate{{ + Certificate: [][]byte{der}, + PrivateKey: key, + }}, + } + srv.StartTLS() + t.Cleanup(srv.Close) + return srv, pool +} + +func TestLLMModelsRefusesLoopbackBeforeRequest(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("internal secret body")) + })) + t.Cleanup(srv.Close) + + // Strict production default: no test seams set. + s := &Server{} + for _, tc := range []struct { + name string + provider string + apiKey string + }{ + {"openai", "openai", "sk-test"}, + {"anthropic", "anthropic", "sk-test"}, + {"ollama_keyless", "ollama", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": tc.provider, + "base_url": srv.URL, + "api_key": tc.apiKey, + }) + if hits.Load() != 0 { + t.Fatalf("loopback server was contacted (%d hits)", hits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false, got %v", resp) + } + errMsg, _ := resp["error"].(string) + if errMsg == "" { + t.Fatalf("expected non-empty refusal error, got %v", resp) + } + if strings.Contains(errMsg, "127.0.0.1") || strings.Contains(errMsg, "internal secret") { + t.Fatalf("error leaked address or body: %q", errMsg) + } + }) + } +} + +func TestLLMModelsDefaultOllamaAllowedWithoutSeam(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + + // 1. Caller-supplied DefaultOllamaBaseURL ("http://127.0.0.1:11434/v1") must + // still be refused with no test seams and no allow-list entry. + bare := &Server{} + supplied := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": agent.DefaultOllamaBaseURL, + "api_key": "", + }) + if supplied["ok"] != false { + t.Fatalf("caller-supplied %s must be refused, got %v", agent.DefaultOllamaBaseURL, supplied) + } + if errMsg, _ := supplied["error"].(string); !strings.Contains(errMsg, "not allowed") || strings.Contains(errMsg, "127.0.0.1") { + t.Fatalf("unexpected refusal for caller-supplied ollama URL: %q", errMsg) + } + + // 2. Empty base_url with provider="ollama" uses the code-owned default and + // must NOT be refused by URL validation or dial control even with no test seam. + var ollamaHits atomic.Int32 + fakeOllama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ollamaHits.Add(1) + if r.URL.Path != "/v1/models" { + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"llama3.2"}]}`)) + })) + t.Cleanup(fakeOllama.Close) + + // Verify the production guard allows dialing only 127.0.0.1:11434 (not other loopback ports). + s := &Server{} + s.modelDialContext = dialTestServerForHosts( + map[string]string{"127.0.0.1:11434": fakeOllama.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "", + "api_key": "", + }) + if ollamaHits.Load() != 1 { + t.Fatalf("expected default ollama endpoint to be contacted once, got %d", ollamaHits.Load()) + } + if resp["ok"] != true { + t.Fatalf("expected ok=true for default ollama without allowLoopbackModels, got %v", resp) + } + rawModels, _ := resp["models"].([]any) + if len(rawModels) != 1 || rawModels[0] != "llama3.2" { + t.Fatalf("unexpected models: %v", rawModels) + } + + // Also verify a completely bare Server (zero seams at all) does not refuse + // {"provider":"ollama","base_url":""} at validation or dial Control. + bareResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "", + "api_key": "", + }) + if bareResp["ok"] == false { + errMsg, _ := bareResp["error"].(string) + if strings.Contains(errMsg, "not allowed") { + t.Fatalf("bare Server refused code-owned default Ollama URL: %q", errMsg) + } + } +} + +func TestLLMModelsPrivateEndpointsAllowList(t *testing.T) { + var allowedHits atomic.Int32 + allowedSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + allowedHits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"local-llama"}]}`)) + })) + t.Cleanup(allowedSrv.Close) + + var otherPortHits atomic.Int32 + otherPortSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + otherPortHits.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"wrong-port"}]}`)) + })) + t.Cleanup(otherPortSrv.Close) + + // 1. No allow-list entry -> refused with bare Server (zero test seams). + t.Setenv(LLMPrivateEndpointsEnv, "") + bare := &Server{} + noEntry := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": allowedSrv.URL, + "api_key": "", + }) + if allowedHits.Load() != 0 || noEntry["ok"] != false { + t.Fatalf("expected refusal with empty %s, hits=%d resp=%v", LLMPrivateEndpointsEnv, allowedHits.Load(), noEntry) + } + + // 2. Allow-listed exact host:port works end-to-end with bare Server (real production dialer + guard). + t.Setenv(LLMPrivateEndpointsEnv, allowedSrv.Listener.Addr().String()+",host.docker.internal:11434") + okResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": allowedSrv.URL, + "api_key": "", + }) + if allowedHits.Load() != 1 || okResp["ok"] != true { + t.Fatalf("allow-listed endpoint should work, hits=%d resp=%v", allowedHits.Load(), okResp) + } + rawModels, _ := okResp["models"].([]any) + if len(rawModels) != 1 || rawModels[0] != "local-llama" { + t.Fatalf("unexpected models from allow-listed endpoint: %v", rawModels) + } + + // 3. Same host on a different port stays refused. + diffPort := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": otherPortSrv.URL, + "api_key": "", + }) + if otherPortHits.Load() != 0 || diffPort["ok"] != false { + t.Fatalf("same host on another port must be refused, hits=%d resp=%v", otherPortHits.Load(), diffPort) + } + + // 4. Allow-listed hostname resolving to RFC1918 works on its exact port, + // stays refused on another port, and still validates scheme & redirects. + var dockerHits atomic.Int32 + dockerSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + dockerHits.Add(1) + if r.URL.Path == "/redirect/v1/models" { + http.Redirect(w, r, otherPortSrv.URL+"/secret", http.StatusFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"docker-qwen"}]}`)) + })) + t.Cleanup(dockerSrv.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "host.docker.internal" { + return []netip.Addr{netip.MustParseAddr("192.168.65.254")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"host.docker.internal:11434": dockerSrv.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + dockerOK := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "http://host.docker.internal:11434", + "api_key": "", + }) + if dockerHits.Load() != 1 || dockerOK["ok"] != true { + t.Fatalf("allow-listed docker host should work, hits=%d resp=%v", dockerHits.Load(), dockerOK) + } + + dockerWrongPort := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "http://host.docker.internal:8080", + "api_key": "", + }) + if dockerWrongPort["ok"] != false { + t.Fatalf("docker host on wrong port must be refused: %v", dockerWrongPort) + } + + dockerBadScheme := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "ftp://host.docker.internal:11434", + "api_key": "", + }) + if dockerBadScheme["ok"] != false { + t.Fatalf("disallowed scheme on allow-listed host must be refused: %v", dockerBadScheme) + } + + dockerBadRedirect := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "ollama", + "base_url": "http://host.docker.internal:11434/redirect", + "api_key": "", + }) + if otherPortHits.Load() != 0 || dockerBadRedirect["ok"] != false { + t.Fatalf("redirect from allow-listed host to non-listed loopback port must be refused, hits=%d resp=%v", otherPortHits.Load(), dockerBadRedirect) + } + + // 5. Cloud metadata remains refused even if mistakenly added to the env var. + t.Setenv(LLMPrivateEndpointsEnv, "169.254.169.254:80,[fd00:ec2::254]:80") + for _, metaURL := range []string{"http://169.254.169.254/latest/meta-data/", "http://[fd00:ec2::254]/latest/meta-data/"} { + metaResp := postJSON(t, bare.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": metaURL, + "api_key": "sk-test", + }) + if metaResp["ok"] != false { + t.Fatalf("metadata URL %s must stay refused even if listed: %v", metaURL, metaResp) + } + } +} + +func TestLLMModelsRefusesMetadataAndRestrictedAddresses(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + s := &Server{} + for _, tc := range []struct { + name string + baseURL string + noLeak string + }{ + {"aws_metadata", "http://169.254.169.254/latest/meta-data/", "169.254.169.254"}, + {"rfc1918_10", "http://10.0.0.1/v1", "10.0.0.1"}, + {"rfc1918_172", "http://172.16.0.1/v1", "172.16.0.1"}, + {"rfc1918_192", "http://192.168.1.1/v1", "192.168.1.1"}, + {"unique_local_v6", "http://[fc00::1]/v1", "fc00::1"}, + {"unique_local_fd", "http://[fd12:3456::1]/v1", "fd12:3456::1"}, + {"unspecified_v4", "http://0.0.0.0/v1", "0.0.0.0"}, + {"unspecified_v6", "http://[::]/v1", "::"}, + {"loopback_v6", "http://[::1]:8080/v1", "::1"}, + {"link_local_v6", "http://[fe80::1]/v1", "fe80::1"}, + {"v4_mapped_loopback", "http://[::ffff:127.0.0.1]/v1", "127.0.0.1"}, + {"v4_mapped_metadata", "http://[::ffff:169.254.169.254]/v1", "169.254.169.254"}, + {"aws_imds_v6", "http://[fd00:ec2::254]/latest/meta-data/", "fd00:ec2::254"}, + {"alibaba_metadata", "http://100.100.100.200/latest/meta-data/", "100.100.100.200"}, + {"decimal_loopback", "http://2130706433/v1", "127.0.0.1"}, + {"hex_metadata", "http://0xa9.254.0xa9fe/latest/meta-data/", "169.254.169.254"}, + {"localhost", "http://localhost:8080/v1", "127.0.0.1"}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": tc.baseURL, + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("expected ok=false for %s, got %v", tc.baseURL, resp) + } + errMsg, _ := resp["error"].(string) + if errMsg == "" { + t.Fatalf("expected error message for %s", tc.baseURL) + } + if tc.noLeak != "" && strings.Contains(errMsg, tc.noLeak) { + t.Fatalf("error leaked address %q: %q", tc.noLeak, errMsg) + } + }) + } + + // Resolved DNS addresses must be checked and must never leak into the error. + for _, tc := range []struct { + name string + addrs []netip.Addr + noLeak string + }{ + {"dns_private", []netip.Addr{netip.MustParseAddr("10.23.45.67")}, "10.23.45.67"}, + {"dns_metadata", []netip.Addr{netip.MustParseAddr("169.254.169.254")}, "169.254.169.254"}, + {"dns_unique_local", []netip.Addr{netip.MustParseAddr("fd00::42")}, "fd00::42"}, + {"dns_mixed_public_and_loopback", []netip.Addr{netip.MustParseAddr("93.184.216.34"), netip.MustParseAddr("127.0.0.1")}, "127.0.0.1"}, + } { + t.Run(tc.name, func(t *testing.T) { + rs := &Server{ + modelLookupIP: func(_ context.Context, _ string) ([]netip.Addr, error) { + return tc.addrs, nil + }, + } + resp := postJSON(t, rs.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://internal.example/v1", + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("expected ok=false, got %v", resp) + } + errMsg, _ := resp["error"].(string) + if errMsg == "" || strings.Contains(errMsg, tc.noLeak) { + t.Fatalf("unexpected error %q (must be non-empty and not contain %q)", errMsg, tc.noLeak) + } + }) + } +} + +func TestLLMModelsRefusesDisallowedSchemes(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + s := &Server{} + for _, raw := range []string{ + "file:///etc/passwd", + "ftp://api.example.com/v1", + "gopher://api.example.com:70/1", + "javascript:alert(1)", + } { + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": raw, + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("scheme %q was not refused: %v", raw, resp) + } + if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "http or https") { + t.Fatalf("scheme %q: expected http/https refusal, got %q", raw, errMsg) + } + } +} + +func TestLLMModelsRefusesRestrictedProxyAndTargetThroughProxy(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + var proxyHits atomic.Int32 + proxySrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyHits.Add(1) + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"data":[{"id":"proxied"}]}`)) + })) + t.Cleanup(proxySrv.Close) + + // 1. Loopback proxy is refused before any request is sent. + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "api.public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + if host == "private-proxy.example" { + return []netip.Addr{netip.MustParseAddr("10.99.0.1")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + for _, tc := range []struct { + name string + proxy string + noLeak string + }{ + {"loopback_proxy", proxySrv.URL, "127.0.0.1"}, + {"metadata_proxy", "http://169.254.169.254:80", "169.254.169.254"}, + {"socks5_proxy", "socks5://api.public.example:1080", ""}, + {"dns_private_proxy", "http://private-proxy.example:3128", "10.99.0.1"}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://api.public.example/v1", + "proxy": tc.proxy, + "api_key": "sk-test", + }) + if proxyHits.Load() != 0 { + t.Fatalf("proxy was contacted (%d hits)", proxyHits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false, got %v", resp) + } + errMsg, _ := resp["error"].(string) + if errMsg == "" || (tc.noLeak != "" && strings.Contains(errMsg, tc.noLeak)) { + t.Fatalf("unexpected error %q (must not leak %q)", errMsg, tc.noLeak) + } + }) + } + + // 2. Valid public proxy + refused target: target must be rejected before the proxy is contacted. + s2 := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "proxy.public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s2.modelDialContext = dialTestServerForHosts( + map[string]string{"proxy.public.example": proxySrv.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s2).blockDial}).DialContext, + ) + resp := postJSON(t, s2.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://169.254.169.254/latest/meta-data/", + "proxy": "http://proxy.public.example:8080", + "api_key": "sk-test", + }) + if proxyHits.Load() != 0 { + t.Fatalf("proxy was contacted for refused target (%d hits)", proxyHits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false, got %v", resp) + } + if errMsg, _ := resp["error"].(string); strings.Contains(errMsg, "169.254.169.254") { + t.Fatalf("error leaked metadata address: %q", errMsg) + } + + // 3. Valid public proxy + public target that returns 302 to 127.0.0.1: + // the proxy must see the first request only, never the redirect target. + var proxyReqs []string + redirProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyReqs = append(proxyReqs, r.URL.String()) + http.Redirect(w, r, "http://127.0.0.1:9999/secret", http.StatusFound) + })) + t.Cleanup(redirProxy.Close) + + s3 := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + switch host { + case "proxy.public.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil + case "api.public.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + default: + return nil, &net.DNSError{Err: "no such host", Name: host} + } + }, + } + s3.modelDialContext = dialTestServerForHosts( + map[string]string{"proxy.public.example": redirProxy.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s3).blockDial}).DialContext, + ) + resp3 := postJSON(t, s3.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://api.public.example/v1", + "proxy": "http://proxy.public.example:8080", + "api_key": "sk-test", + }) + if len(proxyReqs) != 1 || proxyReqs[0] != "http://api.public.example/v1/models" { + t.Fatalf("proxy received unexpected requests: %v", proxyReqs) + } + if resp3["ok"] != false { + t.Fatalf("expected ok=false for proxied redirect to loopback, got %v", resp3) + } + if errMsg, _ := resp3["error"].(string); errMsg == "" || strings.Contains(errMsg, "127.0.0.1") { + t.Fatalf("unexpected error %q (must not leak 127.0.0.1)", errMsg) + } +} + +func TestLLMModelsRefusesRedirectToLoopbackAndRestrictedHost(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + var targetHits atomic.Int32 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + targetHits.Add(1) + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("loopback secret")) + })) + t.Cleanup(target.Close) + + for _, tc := range []struct { + name string + location string + noLeak string + }{ + {"redirect_to_loopback", target.URL + "/secret", "127.0.0.1"}, + {"redirect_to_metadata", "http://169.254.169.254/latest/meta-data/", "169.254.169.254"}, + {"redirect_to_private_dns", "http://internal.example/secret", "10.44.55.66"}, + } { + t.Run(tc.name, func(t *testing.T) { + targetHits.Store(0) + var redirHits atomic.Int32 + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + redirHits.Add(1) + http.Redirect(w, r, tc.location, http.StatusFound) + })) + t.Cleanup(redirector.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + switch host { + case "public.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + case "internal.example": + return []netip.Addr{netip.MustParseAddr("10.44.55.66")}, nil + default: + return nil, &net.DNSError{Err: "no such host", Name: host} + } + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"public.example": redirector.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://public.example/v1", + "api_key": "sk-test", + }) + if redirHits.Load() != 1 { + t.Fatalf("expected redirector to be hit once, got %d", redirHits.Load()) + } + if targetHits.Load() != 0 { + t.Fatalf("redirect target on loopback was contacted (%d hits)", targetHits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false, got %v", resp) + } + errMsg, _ := resp["error"].(string) + if errMsg == "" { + t.Fatalf("expected refusal error, got %v", resp) + } + if strings.Contains(errMsg, tc.noLeak) || strings.Contains(errMsg, "loopback secret") { + t.Fatalf("error leaked address or body: %q", errMsg) + } + }) + } +} + +func TestLLMModelsRedirectSchemePolicyAndCap(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + + t.Run("http_to_https_same_host_allowed", func(t *testing.T) { + httpsSrv, pool := newTestTLSServer(t, []string{"public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"upgraded-model"}]}`)) + })) + httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "https://public.example/v1/models", http.StatusFound) + })) + t.Cleanup(httpSrv.Close) + + s := &Server{ + modelRootCAs: pool, + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{ + "public.example:80": httpSrv.Listener.Addr().String(), + "public.example:443": httpsSrv.Listener.Addr().String(), + }, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://public.example/v1", + "api_key": "sk-test", + }) + if resp["ok"] != true { + t.Fatalf("expected same-host http->https upgrade to succeed, got %v", resp) + } + rawModels, _ := resp["models"].([]any) + if len(rawModels) != 1 || rawModels[0] != "upgraded-model" { + t.Fatalf("unexpected models after upgrade: %v", rawModels) + } + }) + + t.Run("https_to_http_downgrade_refused", func(t *testing.T) { + var httpHits atomic.Int32 + httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + httpHits.Add(1) + _, _ = w.Write([]byte(`{"data":[{"id":"downgraded"}]}`)) + })) + t.Cleanup(httpSrv.Close) + + httpsSrv, pool := newTestTLSServer(t, []string{"public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://public.example/v1/models", http.StatusFound) + })) + + s := &Server{ + modelRootCAs: pool, + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{ + "public.example:80": httpSrv.Listener.Addr().String(), + "public.example:443": httpsSrv.Listener.Addr().String(), + }, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "https://public.example/v1", + "api_key": "sk-test", + }) + if httpHits.Load() != 0 { + t.Fatalf("downgraded HTTP endpoint was contacted (%d hits)", httpHits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false on https->http downgrade, got %v", resp) + } + if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") { + t.Fatalf("expected scheme refusal error, got %q", errMsg) + } + }) + + t.Run("http_to_https_cross_host_refused", func(t *testing.T) { + var otherHits atomic.Int32 + httpsOther, pool := newTestTLSServer(t, []string{"other.public.example"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + otherHits.Add(1) + _, _ = w.Write([]byte(`{"data":[{"id":"other"}]}`)) + })) + httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "https://other.public.example/v1/models", http.StatusFound) + })) + t.Cleanup(httpSrv.Close) + + s := &Server{ + modelRootCAs: pool, + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + switch host { + case "public.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + case "other.public.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.35")}, nil + default: + return nil, &net.DNSError{Err: "no such host", Name: host} + } + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{ + "public.example:80": httpSrv.Listener.Addr().String(), + "other.public.example:443": httpsOther.Listener.Addr().String(), + }, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://public.example/v1", + "api_key": "sk-test", + }) + if otherHits.Load() != 0 { + t.Fatalf("cross-host HTTPS redirect target was contacted (%d hits)", otherHits.Load()) + } + if resp["ok"] != false { + t.Fatalf("expected ok=false on cross-host scheme change, got %v", resp) + } + if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") { + t.Fatalf("expected scheme refusal error, got %q", errMsg) + } + }) + + t.Run("http_to_file_refused", func(t *testing.T) { + httpSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "file:///etc/passwd", http.StatusFound) + })) + t.Cleanup(httpSrv.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"public.example": httpSrv.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://public.example/v1", + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("expected ok=false on file:// redirect, got %v", resp) + } + if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "scheme") { + t.Fatalf("expected scheme refusal error, got %q", errMsg) + } + }) + + t.Run("too_many_redirects", func(t *testing.T) { + var hops atomic.Int32 + looper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := hops.Add(1) + http.Redirect(w, r, "/v1/models?hop="+string(rune('0'+n)), http.StatusFound) + })) + t.Cleanup(looper.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"public.example": looper.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://public.example/v1", + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("expected ok=false on redirect loop, got %v", resp) + } + if errMsg, _ := resp["error"].(string); !strings.Contains(errMsg, "too many redirects") { + t.Fatalf("expected too many redirects error, got %q", errMsg) + } + if hops.Load() > int32(maxModelRedirects) { + t.Fatalf("followed %d redirects, cap is %d", hops.Load(), maxModelRedirects) + } + }) +} + +func TestLLMModelsChecksEveryCandidateURL(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + var flip atomic.Bool + var seenPaths []string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seenPaths = append(seenPaths, r.URL.Path) + if r.URL.Path == "/anthropic/v1/models" { + // Flip DNS to a private address before candidate 2 is tried. + flip.Store(true) + w.WriteHeader(http.StatusNotFound) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"should-not-reach"}]}`)) + })) + t.Cleanup(upstream.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host != "rebind.example" { + return nil, &net.DNSError{Err: "no such host", Name: host} + } + if flip.Load() { + return []netip.Addr{netip.MustParseAddr("10.77.88.99")}, nil + } + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"rebind.example": upstream.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "anthropic", + "base_url": "http://rebind.example/anthropic", + "api_key": "sk-test", + }) + if resp["ok"] != false { + t.Fatalf("expected ok=false when second candidate resolves to private IP, got %v", resp) + } + if len(seenPaths) != 1 || seenPaths[0] != "/anthropic/v1/models" { + t.Fatalf("expected only first candidate to be sent, got %v", seenPaths) + } + if errMsg, _ := resp["error"].(string); errMsg == "" || strings.Contains(errMsg, "10.77.88.99") { + t.Fatalf("unexpected error %q (must not leak resolved IP)", errMsg) + } +} + +func TestLLMModelsPublicEndpointWorks(t *testing.T) { + t.Setenv(LLMPrivateEndpointsEnv, "") + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/models" { + // Also verify a safe same-scheme redirect to a public host succeeds. + http.Redirect(w, r, "http://api.public.example/v2/models", http.StatusFound) + return + } + if r.URL.Path != "/v2/models" { + w.WriteHeader(http.StatusNotFound) + return + } + if r.Header.Get("Authorization") != "Bearer sk-public" { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"gpt-4o"},{"id":"o3"}]}`)) + })) + t.Cleanup(upstream.Close) + + s := &Server{ + modelLookupIP: func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "api.public.example" { + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host} + }, + } + s.modelDialContext = dialTestServerForHosts( + map[string]string{"api.public.example": upstream.Listener.Addr().String()}, + (&net.Dialer{Control: newModelURLGuard(s).blockDial}).DialContext, + ) + + resp := postJSON(t, s.pgListModels, "/api/llm/models", map[string]any{ + "provider": "openai", + "base_url": "http://api.public.example/v1", + "api_key": "sk-public", + }) + if resp["ok"] != true { + t.Fatalf("expected ok=true for normal public endpoint, got %v", resp) + } + rawModels, _ := resp["models"].([]any) + if len(rawModels) != 2 || rawModels[0] != "gpt-4o" || rawModels[1] != "o3" { + t.Fatalf("unexpected models: %v", rawModels) + } +} diff --git a/server/llm_ollama_test.go b/server/llm_ollama_test.go index 655a410..51bf868 100644 --- a/server/llm_ollama_test.go +++ b/server/llm_ollama_test.go @@ -202,6 +202,7 @@ func TestOllamaListModels(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) + s.allowLoopbackModels = true call := func(baseURL string) (bool, []string) { body, _ := json.Marshal(map[string]any{"provider": "ollama", "base_url": baseURL, "api_key": ""}) diff --git a/server/manager.go b/server/manager.go index f314626..650625e 100644 --- a/server/manager.go +++ b/server/manager.go @@ -430,8 +430,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) { log.Printf("[llmusage] create table: %v", err) } m := &Manager{dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg)} - // Behind the global egress proxy a target approval is name-only. - m.interceptor.SetUpstreamProxyCheck(func() bool { return m.GlobalProxy() != "" }) + // Behind any proxy in the path (the recording proxy, the global egress proxy, + // or a custom tool's own proxy) the proxy chooses the address, so a target + // approval is name-only. + m.interceptor.SetUpstreamProxyCheck(func() bool { return m.ProxyAddr() != "" }) + m.interceptor.SetToolProxyCheck(m.toolUsesProxy) // The platform's own endpoints need no target approval. m.interceptor.SetDerivedExemptions(m.targetGateEndpoints) if proxyAddr != "" { @@ -832,6 +835,36 @@ func (m *Manager) ProxyAddr() string { return m.globalProxy } +// toolUsesProxy reports whether a custom tool's own configuration sends its +// traffic through a proxy. That call cannot enforce an approved IP, so the +// target gate treats its pins as name-only. A recording-proxy tool is also +// covered by ProxyAddr() when capture is on; the per-tool check covers a +// tool-specific proxy while capture is off. +func (m *Manager) toolUsesProxy(key string) bool { + if m.pg == nil { + return false + } + t, err := m.pg.GetTool(key) + if err != nil { + // A failed read cannot prove the call is direct; treat it as proxied. + return true + } + if t == nil || t.Kind != "http" { + return false + } + var spec struct { + Proxy string `json:"proxy"` + UseRecordingProxy bool `json:"use_recording_proxy"` + } + if json.Unmarshal(t.Exec, &spec) != nil { + return false + } + if strings.TrimSpace(spec.Proxy) != "" { + return true + } + return spec.UseRecordingProxy && m.ProxyAddr() != "" +} + // ProxyCACert returns the CA cert path agents must trust to verify HTTPS through // the egress proxy. Non-empty ONLY when traffic capture is on (the MITM re-signs // certs): the global proxy used directly (capture off) is a plain forwarder that diff --git a/server/manager_tool_proxy_test.go b/server/manager_tool_proxy_test.go new file mode 100644 index 0000000..af79b30 --- /dev/null +++ b/server/manager_tool_proxy_test.go @@ -0,0 +1,86 @@ +package server + +import ( + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/traffic" +) + +// ProxyAddr is the one source of truth for "is there a proxy in the path": +// the recording proxy while capture is on, the global proxy otherwise. +func TestProxyAddrCoversRecordingAndGlobal(t *testing.T) { + m := &Manager{} + if got := m.ProxyAddr(); got != "" { + t.Fatalf("empty manager ProxyAddr = %q", got) + } + m.globalProxy = "http://127.0.0.1:9" + if got := m.ProxyAddr(); got != m.globalProxy { + t.Fatalf("global ProxyAddr = %q", got) + } + + tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer tr.Close() + m.traffic = tr + m.trafficOn = true + if got := m.ProxyAddr(); got == "" { + t.Fatal("recording proxy not returned by ProxyAddr") + } +} + +// A custom http tool with its own proxy cannot enforce an approved IP; a +// recording-proxy tool counts only when a proxy address is actually in the path. +func TestToolUsesProxy(t *testing.T) { + g := newGateServer(t) + pg := g.m.pg + suffix := fmt.Sprintf("_%d", time.Now().UnixNano()) + add := func(key, kind string, exec map[string]any) string { + t.Helper() + key += suffix + raw, err := json.Marshal(exec) + if err != nil { + t.Fatal(err) + } + if err := pg.CreateCustomTool(&db.Tool{Key: key, Kind: kind, Enabled: true, Exec: raw}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = pg.DeleteCustomTool(key) }) + return key + } + + proxied := add("t_proxy_http", "http", map[string]any{ + "url": "http://example.com/", "proxy": "http://127.0.0.1:9"}) + direct := add("t_direct_http", "http", map[string]any{"url": "http://example.com/"}) + recording := add("t_rec_http", "http", map[string]any{ + "url": "http://example.com/", "use_recording_proxy": true}) + command := add("t_proxy_cmd", "command", map[string]any{ + "command": "curl http://example.com/", "proxy": "http://127.0.0.1:9"}) + + if !g.m.toolUsesProxy(proxied) { + t.Fatal("per-tool proxy not detected") + } + if g.m.toolUsesProxy(direct) { + t.Fatal("direct http tool reported as proxied") + } + if g.m.toolUsesProxy(recording) { + t.Fatal("recording tool reported as proxied with capture off and no global proxy") + } + if g.m.toolUsesProxy(command) { + t.Fatal("command tool reported as proxied") + } + if g.m.toolUsesProxy("t_missing" + suffix) { + t.Fatal("missing tool reported as proxied") + } + + // With a proxy address in the path, the recording flag counts. + g.m.globalProxy = "http://127.0.0.1:9" + if !g.m.toolUsesProxy(recording) { + t.Fatal("recording tool not proxied with a global proxy") + } +} diff --git a/server/pathconfine.go b/server/pathconfine.go new file mode 100644 index 0000000..2bbcaf9 --- /dev/null +++ b/server/pathconfine.go @@ -0,0 +1,360 @@ +package server + +import ( + "errors" + "os" + "path/filepath" + "strings" + "syscall" + + "github.com/Autumn-27/norma/skill" +) + +var errPathEscape = errors.New("invalid path") + +// confinedPath holds the canonicalized result of resolving a user-supplied +// relative path inside a root directory. +type confinedPath struct { + realRoot string // canonical root directory after symlink evaluation + realPath string // resolved target path (deepest existing ancestor resolved + non-existent remainder) + entryPath string // resolved parent + final segment (differs from realPath when final segment is a symlink) + exists bool // whether the target itself exists on disk (and, if a symlink, its target exists) +} + +// isWithinRoot reports whether target is equal to or strictly beneath realRoot. +// Both paths must be cleaned and canonicalized in the same coordinate space. +func isWithinRoot(realRoot, target string) bool { + realRoot = filepath.Clean(realRoot) + target = filepath.Clean(target) + if target == realRoot { + return true + } + rel, err := filepath.Rel(realRoot, target) + if err != nil { + return false + } + if rel == "." { + return true + } + if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return false + } + return true +} + +// resolveRealRoot returns the cleaned, symlink-evaluated absolute path of root. +func resolveRealRoot(root string) (string, error) { + absRoot, err := filepath.Abs(root) + if err != nil { + return "", err + } + realRoot, err := filepath.EvalSymlinks(absRoot) + if err != nil { + return "", err + } + return filepath.Clean(realRoot), nil +} + +// splitRelSegments validates and splits a relative path into individual safe +// path segments. It rejects NUL bytes, volume prefixes, ".." segments, and +// (unless trimLeadingSlash is true) leading separators. +func splitRelSegments(rel string, trimLeadingSlash bool) ([]string, error) { + if strings.ContainsRune(rel, 0) { + return nil, errPathEscape + } + rel = strings.TrimSpace(rel) + // Reject Windows drive-letter prefixes (e.g. "C:foo" or "C:/foo"). + if filepath.VolumeName(rel) != "" { + return nil, errPathEscape + } + // Normalize backslashes so "..\foo" is caught uniformly across platforms. + slashed := strings.ReplaceAll(rel, "\\", "/") + if trimLeadingSlash { + slashed = strings.TrimLeft(slashed, "/") + } else if strings.HasPrefix(slashed, "/") { + return nil, errPathEscape + } + if slashed == "" || slashed == "." { + return nil, nil + } + rawSegs := strings.Split(slashed, "/") + segs := make([]string, 0, len(rawSegs)) + for _, seg := range rawSegs { + if seg == "" || seg == "." { + continue + } + if seg == ".." { + return nil, errPathEscape + } + segs = append(segs, seg) + } + return segs, nil +} + +func isNotDirErr(err error) bool { + return errors.Is(err, syscall.ENOTDIR) +} + +// resolveWithinRoot resolves rel beneath root, walking each path component so +// that symlinks in any component are evaluated and verified to stay within root. +// +// For paths that do not exist yet (write, upload, mkdir), the deepest existing +// ancestor is resolved via Lstat + EvalSymlinks, then the remaining non-existent +// components are re-joined and checked against realRoot. +// +// Broken symlinks, symlink loops, ".." segments, and any symlink whose target +// escapes root return errPathEscape. Symlinks whose resolved target stays inside +// root are permitted. +func resolveWithinRoot(root, rel string, trimLeadingSlash bool) (confinedPath, error) { + realRoot, err := resolveRealRoot(root) + if err != nil { + return confinedPath{}, err + } + segs, err := splitRelSegments(rel, trimLeadingSlash) + if err != nil { + return confinedPath{}, err + } + if len(segs) == 0 { + return confinedPath{ + realRoot: realRoot, + realPath: realRoot, + entryPath: realRoot, + exists: true, + }, nil + } + + cur := realRoot + for i, seg := range segs { + candidate := filepath.Join(cur, seg) + fi, err := os.Lstat(candidate) + if err != nil { + if errors.Is(err, os.ErrNotExist) || isNotDirErr(err) { + // cur is the deepest existing ancestor (already verified within realRoot). + // Re-join the remaining non-existent segments and verify confinement. + rem := make([]string, 0, 1+len(segs)-i) + rem = append(rem, cur) + rem = append(rem, segs[i:]...) + full := filepath.Clean(filepath.Join(rem...)) + if !isWithinRoot(realRoot, full) { + return confinedPath{}, errPathEscape + } + return confinedPath{ + realRoot: realRoot, + realPath: full, + entryPath: full, + exists: false, + }, nil + } + return confinedPath{}, errPathEscape + } + + if fi.Mode()&os.ModeSymlink != 0 { + target, evalErr := filepath.EvalSymlinks(candidate) + if evalErr != nil { + // Broken symlink, symlink loop, or unreadable symlink target. + return confinedPath{}, errPathEscape + } + target = filepath.Clean(target) + if !isWithinRoot(realRoot, target) { + return confinedPath{}, errPathEscape + } + if i == len(segs)-1 { + return confinedPath{ + realRoot: realRoot, + realPath: target, + entryPath: candidate, + exists: true, + }, nil + } + cur = target + continue + } + + cur = candidate + } + + if !isWithinRoot(realRoot, cur) { + return confinedPath{}, errPathEscape + } + return confinedPath{ + realRoot: realRoot, + realPath: cur, + entryPath: cur, + exists: true, + }, nil +} + +// resolveSkillDir resolves / and ensures it does not escape skillDir. +// If skillDir itself does not exist yet, it returns (confinedPath{exists: false}, nil) +// so read/delete handlers can return 404 rather than 400. +func resolveSkillDir(skillDir, name string) (confinedPath, error) { + cp, err := resolveWithinRoot(skillDir, name, false) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return confinedPath{exists: false}, nil + } + return confinedPath{}, errPathEscape + } + return cp, nil +} + +// resolveSkillFile resolves //, confining both the +// skill directory under skillDir and the file under that skill's directory. +func resolveSkillFile(skillDir, name, relFile string) (skillExists bool, cp confinedPath, err error) { + dirCP, err := resolveSkillDir(skillDir, name) + if err != nil { + return false, confinedPath{}, err + } + if !dirCP.exists { + return false, confinedPath{}, nil + } + fi, statErr := os.Stat(dirCP.realPath) + if statErr != nil || !fi.IsDir() { + return false, confinedPath{}, nil + } + fileCP, err := resolveWithinRoot(dirCP.realPath, relFile, false) + if err != nil { + return true, confinedPath{}, errPathEscape + } + return true, fileCP, nil +} + +// loadSkillsConfined loads skills from dir using skill.LoadDir while refusing +// to follow symlinks whose real target leaves dir (or leaves its skill +// subdirectory for //SKILL.md). +func loadSkillsConfined(dir string) (*skill.Registry, error) { + realRoot, err := resolveRealRoot(dir) + if err != nil { + return nil, err + } + entries, err := os.ReadDir(realRoot) + if err != nil { + return nil, err + } + + type safeEntry struct { + isDir bool + entryName string + sourcePath string + } + + hasUnsafe := false + var safe []safeEntry + + for _, e := range entries { + name := e.Name() + switch { + case e.IsDir(): + // os.ReadDir reports e.IsDir() == false for symlinks, so / + // is a real directory under realRoot. Verify its SKILL.md stays inside it. + skillRoot := filepath.Join(realRoot, name) + cp, rerr := resolveWithinRoot(skillRoot, "SKILL.md", false) + if rerr != nil { + hasUnsafe = true + continue + } + if !cp.exists { + continue + } + if fi, serr := os.Stat(cp.realPath); serr != nil || fi.IsDir() { + continue + } + safe = append(safe, safeEntry{ + isDir: true, + entryName: name, + sourcePath: cp.realPath, + }) + case strings.HasSuffix(name, ".md"): + cp, rerr := resolveWithinRoot(realRoot, name, false) + if rerr != nil { + hasUnsafe = true + continue + } + if !cp.exists { + continue + } + if fi, serr := os.Stat(cp.realPath); serr != nil || fi.IsDir() { + continue + } + safe = append(safe, safeEntry{ + isDir: false, + entryName: name, + sourcePath: cp.realPath, + }) + } + } + + // Fast path: every skill file candidate in dir is safely confined. + if !hasUnsafe { + return skill.LoadDir(dir) + } + + // Safe fallback: stage only verified files into a temporary directory so + // skill.LoadDir never opens or reads escaping/broken/looping symlinks, then + // restore each Skill.Dir to match dir. + if len(safe) == 0 { + return skill.NewRegistry(), nil + } + tmp, err := os.MkdirTemp("", "artex-skills-*") + if err != nil { + return nil, err + } + defer os.RemoveAll(tmp) + + for _, item := range safe { + data, rerr := os.ReadFile(item.sourcePath) + if rerr != nil { + continue + } + if item.isDir { + sub := filepath.Join(tmp, item.entryName) + if err := os.MkdirAll(sub, 0o755); err != nil { + continue + } + _ = os.WriteFile(filepath.Join(sub, "SKILL.md"), data, 0o600) + } else { + _ = os.WriteFile(filepath.Join(tmp, item.entryName), data, 0o600) + } + } + + loaded, err := skill.LoadDir(tmp) + if err != nil { + return nil, err + } + out := skill.NewRegistry() + for _, sk := range loaded.List() { + if sk.Dir == tmp { + sk.Dir = dir + } else if rel, relErr := filepath.Rel(tmp, sk.Dir); relErr == nil && rel != "." { + sk.Dir = filepath.Join(dir, rel) + } + out.Add(sk) + } + return out, nil +} + +// safeFSErr formats a filesystem error without leaking absolute paths. +func safeFSErr(err error) string { + if err == nil { + return "" + } + var pe *os.PathError + if errors.As(err, &pe) && pe.Err != nil { + if pe.Op != "" { + return pe.Op + ": " + pe.Err.Error() + } + return pe.Err.Error() + } + var le *os.LinkError + if errors.As(err, &le) && le.Err != nil { + if le.Op != "" { + return le.Op + ": " + le.Err.Error() + } + return le.Err.Error() + } + var se *os.SyscallError + if errors.As(err, &se) && se.Err != nil { + return se.Err.Error() + } + return "filesystem error" +} diff --git a/server/platform_tools.go b/server/platform_tools.go index 65bebf9..eadd40e 100644 --- a/server/platform_tools.go +++ b/server/platform_tools.go @@ -98,12 +98,16 @@ func (s *Server) toolCreateSkill() actool.CoreTool { if strings.TrimSpace(a.Description) == "" { return actool.Errorf("description is required"), nil } - path := filepath.Join(s.skillDir, a.Name) - if _, err := os.Stat(path); err == nil { + dirCP, err := resolveSkillDir(s.skillDir, a.Name) + if err != nil { + return actool.Errorf("invalid skill path"), nil + } + if dirCP.exists { return actool.Errorf("skill already exists: " + a.Name), nil } + path := filepath.Join(s.skillDir, a.Name) if err := os.MkdirAll(path, 0o755); err != nil { - return actool.Errorf(err.Error()), nil + return actool.Errorf(safeFSErr(err)), nil } var b strings.Builder b.WriteString("---\n") @@ -117,7 +121,7 @@ func (s *Server) toolCreateSkill() actool.CoreTool { } if err := os.WriteFile(filepath.Join(path, "SKILL.md"), []byte(b.String()), 0o644); err != nil { _ = os.RemoveAll(path) - return actool.Errorf(err.Error()), nil + return actool.Errorf(safeFSErr(err)), nil } return actool.Text("skill created: " + a.Name), nil }) @@ -137,10 +141,6 @@ func (s *Server) toolUpdateSkillFile() actool.CoreTool { if !validSkillName(a.Name) { return actool.Errorf("invalid skill name"), nil } - skillPath := filepath.Join(s.skillDir, a.Name) - if _, err := os.Stat(skillPath); os.IsNotExist(err) { - return actool.Errorf("skill does not exist: " + a.Name), nil - } rel := strings.TrimSpace(a.File) if rel == "" { rel = "SKILL.md" @@ -149,12 +149,21 @@ func (s *Server) toolUpdateSkillFile() actool.CoreTool { if msg != "" { return actool.Errorf("illegal path: " + msg), nil } - full := filepath.Join(skillPath, clean) - if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { - return actool.Errorf(err.Error()), nil + skillExists, cp, err := resolveSkillFile(s.skillDir, a.Name, clean) + if err != nil { + return actool.Errorf("illegal path: invalid path"), nil } - if err := os.WriteFile(full, []byte(a.Content), 0o644); err != nil { - return actool.Errorf(err.Error()), nil + if !skillExists { + return actool.Errorf("skill does not exist: " + a.Name), nil + } + if cp.realPath == cp.realRoot { + return actool.Errorf("illegal path: invalid path"), nil + } + if err := os.MkdirAll(filepath.Dir(cp.realPath), 0o755); err != nil { + return actool.Errorf(safeFSErr(err)), nil + } + if err := os.WriteFile(cp.realPath, []byte(a.Content), 0o644); err != nil { + return actool.Errorf(safeFSErr(err)), nil } return actool.Text("skill file written: " + a.Name + "/" + clean), nil }) diff --git a/server/ready.go b/server/ready.go new file mode 100644 index 0000000..a628fbc --- /dev/null +++ b/server/ready.go @@ -0,0 +1,80 @@ +package server + +import ( + "context" + "errors" + "net/http" + "sync" + "time" +) + +const ( + readyCacheTTL = time.Second + readyPingTimeout = time.Second +) + +var errNoPostgres = errors.New("PostgreSQL is not configured") + +type readyCache struct { + mu sync.Mutex + checked time.Time + ready bool + pending chan struct{} +} + +func (c *readyCache) check(ctx context.Context, ping func(context.Context) error) bool { + if ctx.Err() != nil { + return false + } + + c.mu.Lock() + if !c.checked.IsZero() && time.Since(c.checked) < readyCacheTTL { + ready := c.ready + c.mu.Unlock() + return ready + } + if done := c.pending; done != nil { + c.mu.Unlock() + select { + case <-done: + c.mu.Lock() + ready := c.ready + c.mu.Unlock() + return ready + case <-ctx.Done(): + return false + } + } + done := make(chan struct{}) + c.pending = done + c.mu.Unlock() + + pingCtx, cancel := context.WithTimeout(context.Background(), readyPingTimeout) + err := ping(pingCtx) + cancel() + + c.mu.Lock() + c.ready = err == nil + c.checked = time.Now() + c.pending = nil + close(done) + ready := c.ready + c.mu.Unlock() + return ready +} + +// ready reports PostgreSQL reachability without exposing connection details. +// Its cached ping is bounded to one second and never runs application work. +func (s *Server) ready(w http.ResponseWriter, r *http.Request) { + ready := s.readyPG.check(r.Context(), func(ctx context.Context) error { + if s.m == nil || s.m.pg == nil { + return errNoPostgres + } + return s.m.pg.PingContext(ctx) + }) + status := http.StatusServiceUnavailable + if ready { + status = http.StatusOK + } + writeJSON(w, status, map[string]bool{"ready": ready}) +} diff --git a/server/ready_test.go b/server/ready_test.go new file mode 100644 index 0000000..9e6b135 --- /dev/null +++ b/server/ready_test.go @@ -0,0 +1,236 @@ +package server + +import ( + "context" + "database/sql" + "database/sql/driver" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Autumn-27/artex/db" +) + +type readyTestConnector struct { + ping func(context.Context) error +} + +func (c readyTestConnector) Connect(context.Context) (driver.Conn, error) { + return readyTestConn{ping: c.ping}, nil +} + +func (c readyTestConnector) Driver() driver.Driver { return readyTestDriver{} } + +type readyTestDriver struct{} + +func (readyTestDriver) Open(string) (driver.Conn, error) { + return nil, errors.New("ready test driver must be opened through its connector") +} + +type readyTestConn struct { + ping func(context.Context) error +} + +func (readyTestConn) Prepare(string) (driver.Stmt, error) { + return nil, errors.New("not supported") +} +func (readyTestConn) Close() error { return nil } +func (readyTestConn) Begin() (driver.Tx, error) { return nil, errors.New("not supported") } +func (c readyTestConn) Ping(ctx context.Context) error { + return c.ping(ctx) +} + +func newReadyServer(t *testing.T, ping func(context.Context) error) (*Server, *sql.DB) { + t.Helper() + sqlDB := sql.OpenDB(readyTestConnector{ping: ping}) + t.Cleanup(func() { _ = sqlDB.Close() }) + return &Server{m: &Manager{pg: &db.DB{DB: sqlDB}}}, sqlDB +} + +func readyRequest(h http.Handler, method, path string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(method, path, nil)) + return rec +} + +func assertReadyResponse(t *testing.T, rec *httptest.ResponseRecorder, status int, ready bool) { + t.Helper() + if rec.Code != status { + t.Fatalf("status = %d, want %d; body=%s", rec.Code, status, rec.Body.String()) + } + var body map[string]bool + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode body %q: %v", rec.Body.String(), err) + } + if len(body) != 1 || body["ready"] != ready { + t.Fatalf("body = %s, want only ready:%t", rec.Body.String(), ready) + } +} + +func TestReadyRouteAvailabilityAndCompatibility(t *testing.T) { + var calls atomic.Int32 + s, _ := newReadyServer(t, func(context.Context) error { + calls.Add(1) + return nil + }) + h := s.Handler() + + assertReadyResponse(t, readyRequest(h, http.MethodGet, "/api/ready"), http.StatusOK, true) + if got := readyRequest(h, http.MethodGet, "/api/health"); got.Code != http.StatusOK || strings.TrimSpace(got.Body.String()) != `{"ok":true}` { + t.Fatalf("unauthenticated health = %d %s, want 200 {\"ok\":true}", got.Code, got.Body.String()) + } + if got := readyRequest(h, http.MethodGet, "/api/stats"); got.Code != http.StatusUnauthorized { + t.Fatalf("unauthenticated stats = %d, want %d", got.Code, http.StatusUnauthorized) + } + if got := calls.Load(); got != 1 { + t.Fatalf("database ping count = %d after readiness and liveness requests, want 1", got) + } +} + +func TestReadyOutageRecoveryAndErrorRedaction(t *testing.T) { + var calls atomic.Int32 + var available atomic.Bool + s, _ := newReadyServer(t, func(context.Context) error { + calls.Add(1) + if !available.Load() { + return errors.New("secret PostgreSQL connection details") + } + return nil + }) + h := s.Handler() + + first := readyRequest(h, http.MethodGet, "/api/ready") + assertReadyResponse(t, first, http.StatusServiceUnavailable, false) + if strings.Contains(first.Body.String(), "secret") { + t.Fatalf("readiness response exposed database error: %s", first.Body.String()) + } + + available.Store(true) + s.readyPG.mu.Lock() + s.readyPG.checked = time.Now().Add(-2 * readyCacheTTL) + s.readyPG.mu.Unlock() + assertReadyResponse(t, readyRequest(h, http.MethodGet, "/api/ready"), http.StatusOK, true) + if got := calls.Load(); got != 2 { + t.Fatalf("database ping count = %d, want outage and recovery checks", got) + } +} + +func TestReadyClosedDatabaseReturnsUnavailable(t *testing.T) { + s, sqlDB := newReadyServer(t, func(context.Context) error { return nil }) + if err := sqlDB.Close(); err != nil { + t.Fatal(err) + } + assertReadyResponse(t, readyRequest(s.Handler(), http.MethodGet, "/api/ready"), http.StatusServiceUnavailable, false) +} + +func TestReadyPingTimeout(t *testing.T) { + var cache readyCache + started := make(chan struct{}) + start := time.Now() + ready := cache.check(context.Background(), func(ctx context.Context) error { + close(started) + <-ctx.Done() + return ctx.Err() + }) + if ready { + t.Fatal("timed-out ping reported ready") + } + <-started + if elapsed := time.Since(start); elapsed < readyPingTimeout || elapsed > 2*readyPingTimeout { + t.Fatalf("ping timeout elapsed %s, want about %s", elapsed, readyPingTimeout) + } +} + +type readyWaitContext struct { + context.Context + waiting chan struct{} + once sync.Once +} + +func (c *readyWaitContext) Done() <-chan struct{} { + c.once.Do(func() { close(c.waiting) }) + return c.Context.Done() +} + +func TestReadyCanceledWaiterDoesNotCancelSharedPing(t *testing.T) { + var cache readyCache + started := make(chan struct{}) + release := make(chan struct{}) + pingResult := make(chan bool, 1) + go func() { + pingResult <- cache.check(context.Background(), func(context.Context) error { + close(started) + <-release + return nil + }) + }() + <-started + + waitCtx, cancel := context.WithCancel(context.Background()) + waitingCtx := &readyWaitContext{Context: waitCtx, waiting: make(chan struct{})} + waiterResult := make(chan bool, 1) + go func() { waiterResult <- cache.check(waitingCtx, func(context.Context) error { return nil }) }() + <-waitingCtx.waiting + cancel() + select { + case ready := <-waiterResult: + if ready { + t.Fatal("canceled waiter reported ready") + } + case <-time.After(100 * time.Millisecond): + t.Fatal("canceled waiter did not return promptly") + } + + close(release) + if ready := <-pingResult; !ready { + t.Fatal("canceling a waiter canceled the shared ping") + } +} + +func TestReadyConcurrentRequestsShareOnePing(t *testing.T) { + var cache readyCache + var calls atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + ping := func(context.Context) error { + calls.Add(1) + close(started) + <-release + return nil + } + + const callers = 20 + results := make([]bool, callers) + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + results[0] = cache.check(context.Background(), ping) + }() + <-started + + for i := 1; i < callers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + results[i] = cache.check(context.Background(), ping) + }(i) + } + time.Sleep(25 * time.Millisecond) + close(release) + wg.Wait() + if got := calls.Load(); got != 1 { + t.Fatalf("database ping count = %d for %d callers, want 1", got, callers) + } + for i, ready := range results { + if !ready { + t.Errorf("caller %d reported not ready", i) + } + } +} diff --git a/server/server.go b/server/server.go index 7526c86..05ce563 100644 --- a/server/server.go +++ b/server/server.go @@ -2,6 +2,7 @@ package server import ( "context" + "crypto/x509" "encoding/base64" "encoding/json" "errors" @@ -66,6 +67,14 @@ type Server struct { authHashKey string authVersionKey string + // Test-only seams for pgListModels SSRF checks. All remain zero/nil in + // production (strict public-only default; only exact host:port entries in + // ARTEX_LLM_PRIVATE_ENDPOINTS may resolve to private addresses). + allowLoopbackModels bool + modelLookupIP func(ctx context.Context, host string) ([]netip.Addr, error) + modelDialContext func(ctx context.Context, network, addr string) (net.Conn, error) + modelRootCAs *x509.CertPool + loginLimit *loginLimiter // per-IP attempt limit on POST /api/auth/login pwdLimit *loginLimiter // attempt limit on POST /api/auth/change-password (IP + session token) trustedProxies []netip.Prefix // ARTEX_TRUSTED_PROXIES; see clientIP @@ -75,6 +84,8 @@ type Server struct { // free slots off the same snapshot and over-promote past the limit. concMu sync.Mutex + readyPG readyCache + cfgMu sync.Mutex chatAgent *agent.ChatAgent // conversational runner for the chat page; nil w/o LLM // llmProv is the fully-decorated global provider (recorder + failover chain) @@ -748,6 +759,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/auth/change-password", s.authChangePassword) mux.HandleFunc("GET /api/health", s.health) + mux.HandleFunc("GET /api/ready", s.ready) mux.HandleFunc("GET /api/stats", s.stats) mux.HandleFunc("GET /api/logs", s.getLogs) mux.HandleFunc("GET /api/logs/history", s.getLogsHistory) @@ -1050,7 +1062,14 @@ func (s *Server) Handler() http.Handler { api := cors(s.requireAuth(mux)) root := http.NewServeMux() root.Handle("/api/", api) - root.Handle("/", s.webuiHandler()) + webui := s.webuiHandler() + root.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + // Keep the operator console out of cross-origin frames and referrers. + w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'") + w.Header().Set("X-Frame-Options", "SAMEORIGIN") + w.Header().Set("Referrer-Policy", "same-origin") + webui.ServeHTTP(w, r) + }) return limitRequestBody(root) } @@ -3669,7 +3688,8 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) { } // getTrafficStream returns one page of a WebSocket/SSE exchange's messages in -// order (limit 1..200, default 50). +// order (limit 1..200, default 50). direction=c2s or s2c keeps one side of the +// conversation (plus the meta limit marker); any other non-empty value is a 400. func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) { tr := s.m.Traffic() if tr == nil { @@ -3684,7 +3704,12 @@ func (s *Server) getTrafficStream(w http.ResponseWriter, r *http.Request) { } offset, _ := strconv.Atoi(q.Get("offset")) limit, _ := strconv.Atoi(q.Get("limit")) - msgs, total, err := tr.StreamMessages(id, offset, limit) + direction := strings.ToLower(strings.TrimSpace(q.Get("direction"))) + msgs, total, err := tr.StreamMessagesByDirection(id, direction, offset, limit) + if errors.Is(err, traffic.ErrBadStreamDirection) { + writeErr(w, 400, err.Error()) + return + } if err != nil { writeErr(w, 500, err.Error()) return diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 0367e46..446ed5f 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -4,13 +4,16 @@ import ( "archive/zip" "bytes" "context" + "crypto/tls" "encoding/json" "errors" "fmt" "io" "log" "mime" + "net" "net/http" + "net/netip" "net/url" "os" "path" @@ -18,6 +21,8 @@ import ( "regexp" "strconv" "strings" + "sync" + "syscall" "text/template" "text/template/parse" "time" @@ -26,6 +31,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/notify" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/skill" @@ -1156,7 +1162,7 @@ type skillFileNode struct { func (s *Server) fsListSkills(w http.ResponseWriter, r *http.Request) { _ = os.MkdirAll(s.skillDir, 0o755) - allReg, _ := skill.LoadDir(s.skillDir) + allReg, _ := loadSkillsConfined(s.skillDir) metaByDir := map[string]skill.Skill{} if allReg != nil { for _, sk := range allReg.List() { @@ -1167,7 +1173,7 @@ func (s *Server) fsListSkills(w http.ResponseWriter, r *http.Request) { } entries, err := os.ReadDir(s.skillDir) if err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } // Usage is best-effort decoration: a ledger read failure leaves the counts at @@ -1275,13 +1281,18 @@ func (s *Server) fsCreateSkill(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, "description is required") return } - skillPath := filepath.Join(s.skillDir, body.Name) - if _, err := os.Stat(skillPath); err == nil { + dirCP, err := resolveSkillDir(s.skillDir, body.Name) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if dirCP.exists { writeErr(w, 409, "skill already exists") return } + skillPath := filepath.Join(s.skillDir, body.Name) if err := os.MkdirAll(skillPath, 0o755); err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } // Build a spec-compliant SKILL.md (agentskills.io format): @@ -1317,7 +1328,7 @@ func (s *Server) fsCreateSkill(w http.ResponseWriter, r *http.Request) { } if err := os.WriteFile(filepath.Join(skillPath, "SKILL.md"), []byte(sb.String()), 0o644); err != nil { _ = os.RemoveAll(skillPath) - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } // Verify with the real parser: a description containing ": " (or any value that @@ -1352,19 +1363,31 @@ func (s *Server) fsUpdateSkillMeta(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - skillMD := filepath.Join(s.skillDir, name, "SKILL.md") - raw, err := os.ReadFile(skillMD) + skillExists, cp, err := resolveSkillFile(s.skillDir, name, "SKILL.md") if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !skillExists || !cp.exists { writeErr(w, 404, "skill not found") return } + raw, err := os.ReadFile(cp.realPath) + if err != nil { + if os.IsNotExist(err) { + writeErr(w, 404, "skill not found") + return + } + writeErr(w, 500, safeFSErr(err)) + return + } updated, err := rewriteSkillFrontmatter(raw, body.MCPs, body.Description, body.License, body.Compatibility) if err != nil { writeErr(w, 400, err.Error()) return } - if err := os.WriteFile(skillMD, updated, 0o644); err != nil { - writeErr(w, 500, err.Error()) + if err := os.WriteFile(cp.realPath, updated, 0o644); err != nil { + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"ok": true}) @@ -1383,9 +1406,9 @@ func yamlScalar(s string) string { // verifySkillFile re-loads a written SKILL.md with the real skill parser and // asserts the name and the mcps list survived the round trip. func verifySkillFile(skillPath, wantName string, wantMCPs []string) error { - reg, err := skill.LoadDir(skillPath) + reg, err := loadSkillsConfined(skillPath) if err != nil { - return fmt.Errorf("load: %w", err) + return fmt.Errorf("load: %s", safeFSErr(err)) } for _, s := range reg.List() { if s.Dir == "" { @@ -1399,14 +1422,14 @@ func verifySkillFile(skillPath, wantName string, wantMCPs []string) error { } return nil } - return fmt.Errorf("no skill loaded from %s", skillPath) + return fmt.Errorf("no skill loaded from %s", filepath.Base(skillPath)) } // warnBrokenSkills logs skills whose parsed name does not match their directory // name: the signature of frontmatter that failed to parse and silently fell back // (fields empty, mcps gate lost). Best-effort, startup only. func warnBrokenSkills(dir string) { - reg, err := skill.LoadDir(dir) + reg, err := loadSkillsConfined(dir) if err != nil { return } @@ -1601,9 +1624,14 @@ func (s *Server) fsUploadSkill(w http.ResponseWriter, r *http.Request) { return } + dirCP, err := resolveSkillDir(s.skillDir, name) + if err != nil { + writeErr(w, 400, "invalid path") + return + } skillPath := filepath.Join(s.skillDir, name) overwrite := r.URL.Query().Get("overwrite") == "true" - if _, err := os.Stat(skillPath); err == nil && !overwrite { + if dirCP.exists && !overwrite { writeErr(w, 409, "skill already exists: "+name+" (retry after confirming if you want to overwrite)") return } @@ -1708,13 +1736,20 @@ func (s *Server) fsDeleteSkill(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, "invalid skill name") return } + dirCP, err := resolveSkillDir(s.skillDir, name) + if err != nil { + writeErr(w, 400, "invalid path") + return + } if err := pg.DeleteSkillVisibility(name); err != nil { writeErr(w, 500, err.Error()) return } - if err := os.RemoveAll(filepath.Join(s.skillDir, name)); err != nil { - writeErr(w, 500, err.Error()) - return + if dirCP.exists { + if err := os.RemoveAll(dirCP.entryPath); err != nil { + writeErr(w, 500, safeFSErr(err)) + return + } } writeJSON(w, 200, map[string]any{"deleted": name}) } @@ -1816,14 +1851,23 @@ func (s *Server) fsListFiles(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, "invalid skill name") return } - dirPath := filepath.Join(s.skillDir, name) - if _, err := os.Stat(dirPath); os.IsNotExist(err) { + dirCP, err := resolveSkillDir(s.skillDir, name) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !dirCP.exists { writeErr(w, 404, "skill not found") return } - files, err := walkSkillFiles(dirPath) + fi, err := os.Stat(dirCP.realPath) + if err != nil || !fi.IsDir() { + writeErr(w, 404, "skill not found") + return + } + files, err := walkSkillFiles(dirCP.realPath) if err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } if files == nil { @@ -1843,13 +1887,22 @@ func (s *Server) fsReadFile(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, errMsg) return } - data, err := os.ReadFile(filepath.Join(s.skillDir, name, file)) + skillExists, cp, err := resolveSkillFile(s.skillDir, name, file) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !skillExists || !cp.exists { + writeErr(w, 404, "file not found") + return + } + data, err := os.ReadFile(cp.realPath) if os.IsNotExist(err) { writeErr(w, 404, "file not found") return } if err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"content": string(data), "file": file}) @@ -1873,19 +1926,26 @@ func (s *Server) fsWriteFile(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - skillPath := filepath.Join(s.skillDir, name) - if _, err := os.Stat(skillPath); os.IsNotExist(err) { + skillExists, cp, err := resolveSkillFile(s.skillDir, name, file) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !skillExists { writeErr(w, 404, "skill not found") return } - fullPath := filepath.Join(skillPath, file) - // create parent subdirectory if needed (e.g. scripts/, references/, assets/) - if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil { - writeErr(w, 500, err.Error()) + if cp.realPath == cp.realRoot { + writeErr(w, 400, "invalid path") return } - if err := os.WriteFile(fullPath, []byte(body.Content), 0o644); err != nil { - writeErr(w, 500, err.Error()) + // create parent subdirectory if needed (e.g. scripts/, references/, assets/) + if err := os.MkdirAll(filepath.Dir(cp.realPath), 0o755); err != nil { + writeErr(w, 500, safeFSErr(err)) + return + } + if err := os.WriteFile(cp.realPath, []byte(body.Content), 0o644); err != nil { + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"ok": true}) @@ -1909,13 +1969,21 @@ func (s *Server) fsCreateDir(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, errMsg) return } - skillPath := filepath.Join(s.skillDir, name) - if _, err := os.Stat(skillPath); os.IsNotExist(err) { + skillExists, cp, err := resolveSkillFile(s.skillDir, name, dir) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !skillExists { writeErr(w, 404, "skill not found") return } - if err := os.MkdirAll(filepath.Join(skillPath, dir), 0o755); err != nil { - writeErr(w, 500, err.Error()) + if cp.realPath == cp.realRoot { + writeErr(w, 400, "invalid path") + return + } + if err := os.MkdirAll(cp.realPath, 0o755); err != nil { + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 201, map[string]any{"dir": dir}) @@ -1932,13 +2000,21 @@ func (s *Server) fsDeletePath(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, errMsg) return } - fullPath := filepath.Join(s.skillDir, name, file) - if _, err := os.Stat(fullPath); os.IsNotExist(err) { + skillExists, cp, err := resolveSkillFile(s.skillDir, name, file) + if err != nil { + writeErr(w, 400, "invalid path") + return + } + if !skillExists || !cp.exists { writeErr(w, 404, "not found") return } - if err := os.RemoveAll(fullPath); err != nil { - writeErr(w, 500, err.Error()) + if cp.realPath == cp.realRoot { + writeErr(w, 400, "invalid path") + return + } + if err := os.RemoveAll(cp.entryPath); err != nil { + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"deleted": file}) @@ -2236,6 +2312,224 @@ func (s *Server) pgLLMPoolReset(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, s.llmPoolStatus()) } +const maxModelRedirects = 5 + +// LLMPrivateEndpointsEnv is an opt-in comma-separated allow-list of exact +// host:port entries (for example "127.0.0.1:11434,host.docker.internal:11434") +// that POST /api/llm/models may contact on loopback or private addresses. +// Unset or empty enforces the strict public-only policy. +const LLMPrivateEndpointsEnv = "ARTEX_LLM_PRIVATE_ENDPOINTS" + +type modelURLRefusalError struct { + msg string +} + +func (e *modelURLRefusalError) Error() string { return e.msg } + +func normalizeModelHost(host string) (kind, normalized string, ok bool) { + host = strings.TrimSpace(host) + if host == "" { + return "", "", false + } + if addr, err := netip.ParseAddr(host); err == nil { + return intercept.TargetIP, addr.Unmap().WithZone("").String(), true + } + t, ok := intercept.NormalizeTarget(host) + if !ok || t.Kind == intercept.TargetCIDR || t.Host == "" { + return "", "", false + } + return t.Kind, t.Host, true +} + +func urlEffectivePort(u *url.URL) (int, bool) { + if p := u.Port(); p != "" { + n, err := strconv.Atoi(p) + if err != nil || n < 1 || n > 65535 { + return 0, false + } + return n, true + } + switch strings.ToLower(u.Scheme) { + case "http": + return 80, true + case "https": + return 443, true + default: + return 0, false + } +} + +func parsePrivateModelEndpoints(raw string) map[string]bool { + out := map[string]bool{} + for _, entry := range strings.Split(raw, ",") { + entry = strings.TrimSpace(entry) + if entry == "" { + continue + } + host, portStr, err := net.SplitHostPort(entry) + if err != nil { + continue + } + port, err := strconv.Atoi(portStr) + if err != nil || port < 1 || port > 65535 { + continue + } + _, normHost, ok := normalizeModelHost(host) + if !ok { + continue + } + out[net.JoinHostPort(normHost, strconv.Itoa(port))] = true + } + return out +} + +func sameRedirectHost(a, b *url.URL) bool { + ha := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(a.Hostname())), ".") + hb := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(b.Hostname())), ".") + return ha != "" && ha == hb +} + +func (s *Server) isBlockedModelAddr(addr netip.Addr, allowPrivate bool) bool { + if !addr.IsValid() { + return true + } + addr = addr.Unmap().WithZone("") + if s != nil && s.allowLoopbackModels && addr.IsLoopback() { + return false + } + if !intercept.IsNonPublicAddr(addr) { + return false + } + if allowPrivate { + // Allow-listed self-hosted endpoints may resolve to loopback or RFC1918 / + // unique-local private addresses, but never link-local, unspecified, + // multicast, or instance-metadata addresses (such as 169.254.169.254 or + // fd00:ec2::254). + if addr.IsLoopback() { + return false + } + if addr.IsPrivate() && intercept.ValidateExemptionHost(addr.String()) == nil { + return false + } + } + return true +} + +func (s *Server) lookupModelIPs(ctx context.Context, host string) ([]netip.Addr, error) { + if s != nil && s.modelLookupIP != nil { + return s.modelLookupIP(ctx, host) + } + return net.DefaultResolver.LookupNetIP(ctx, "ip", host) +} + +type modelURLGuard struct { + s *Server + privateEndpoints map[string]bool + mu sync.Mutex + allowedDialAddrs map[string]bool +} + +func newModelURLGuard(s *Server) *modelURLGuard { + return &modelURLGuard{ + s: s, + privateEndpoints: parsePrivateModelEndpoints(os.Getenv(LLMPrivateEndpointsEnv)), + } +} + +func (g *modelURLGuard) allowDialAddr(addr netip.Addr, port int) { + if !addr.IsValid() || port < 1 || port > 65535 { + return + } + key := net.JoinHostPort(addr.Unmap().WithZone("").String(), strconv.Itoa(port)) + g.mu.Lock() + if g.allowedDialAddrs == nil { + g.allowedDialAddrs = map[string]bool{} + } + g.allowedDialAddrs[key] = true + g.mu.Unlock() +} + +func (g *modelURLGuard) isAllowedDialAddr(addr netip.Addr, port string) bool { + key := net.JoinHostPort(addr.Unmap().WithZone("").String(), port) + g.mu.Lock() + ok := g.allowedDialAddrs[key] + g.mu.Unlock() + return ok +} + +func (g *modelURLGuard) blockDial(_, address string, _ syscall.RawConn) error { + host, port, err := net.SplitHostPort(address) + if err != nil { + return &modelURLRefusalError{msg: "target address is not allowed"} + } + addr, err := netip.ParseAddr(host) + if err != nil { + return &modelURLRefusalError{msg: "target address is not allowed"} + } + allowPrivate := g.isAllowedDialAddr(addr, port) + if g.s.isBlockedModelAddr(addr, allowPrivate) { + return &modelURLRefusalError{msg: "target address is not allowed"} + } + return nil +} + +// validateURL validates a base_url candidate, proxy URL, or redirect target for +// POST /api/llm/models. Only http and https URLs are permitted; hosts must +// resolve strictly to public addresses unless their exact host:port is listed +// in ARTEX_LLM_PRIVATE_ENDPOINTS. Errors never include resolved IP addresses. +func (g *modelURLGuard) validateURL(ctx context.Context, rawURL, role string) (*url.URL, error) { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)} + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL must use http or https", role)} + } + if u.Opaque != "" { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)} + } + port, ok := urlEffectivePort(u) + if !ok { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL", role)} + } + kind, normHost, ok := normalizeModelHost(u.Hostname()) + if !ok { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("invalid %s URL host", role)} + } + hostPort := net.JoinHostPort(normHost, strconv.Itoa(port)) + allowPrivate := g.privateEndpoints[hostPort] + + if kind == intercept.TargetIP { + addr, err := netip.ParseAddr(normHost) + if err != nil || g.s.isBlockedModelAddr(addr, allowPrivate) { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)} + } + if allowPrivate { + g.allowDialAddr(addr, port) + } + return u, nil + } + if !allowPrivate && !(g.s != nil && g.s.allowLoopbackModels) && (normHost == "localhost" || strings.HasSuffix(normHost, ".localhost")) { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)} + } + addrs, err := g.s.lookupModelIPs(ctx, normHost) + if err != nil || len(addrs) == 0 { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("failed to resolve %s host", role)} + } + for _, addr := range addrs { + if g.s.isBlockedModelAddr(addr, allowPrivate) { + return nil, &modelURLRefusalError{msg: fmt.Sprintf("%s URL host is not allowed", role)} + } + } + if allowPrivate { + for _, addr := range addrs { + g.allowDialAddr(addr, port) + } + } + return u, nil +} + // pgListModels fetches available models from the provider's API endpoint. // Supports OpenAI-format (GET /models), Anthropic-format (GET /v1/models) and // Ollama (keyless OpenAI-compatible GET /v1/models on the local server); for @@ -2285,7 +2579,9 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { return } - baseURL := strings.TrimRight(strings.TrimSpace(req.BaseURL), "/") + rawBaseURL := strings.TrimSpace(req.BaseURL) + baseURL := strings.TrimRight(rawBaseURL, "/") + defaultOllama := provider == "ollama" && rawBaseURL == "" // Candidate endpoints to try in order. Some Anthropic-compatible providers // (e.g. DeepSeek) implement /v1/messages under an /anthropic path but expose @@ -2349,19 +2645,98 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { } } - // Build HTTP client with optional proxy. - transport := &http.Transport{} + // Validate proxy and every candidate URL before sending any request. + // Pre-request validation is required in addition to the dial-time guard + // because a caller-supplied HTTP proxy fetches the target URL itself. + guard := newModelURLGuard(s) + var proxyURL *url.URL if p := strings.TrimSpace(req.Proxy); p != "" { - if pu, err := url.Parse(p); err == nil { - transport.Proxy = http.ProxyURL(pu) + var err error + proxyURL, err = guard.validateURL(r.Context(), p, "proxy") + if err != nil { + writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()}) + return } } - client := &http.Client{Transport: transport, Timeout: 30 * time.Second} + if defaultOllama { + // The built-in Ollama default is code-owned, not caller input: allow + // dialing its exact host:port without relaxing caller-supplied URLs. + if du, err := url.Parse(agent.DefaultOllamaBaseURL); err == nil { + if addr, err := netip.ParseAddr(du.Hostname()); err == nil { + if port, ok := urlEffectivePort(du); ok { + guard.allowDialAddr(addr, port) + } + } + } + } else { + for _, c := range candidates { + if _, err := guard.validateURL(r.Context(), c.url, "endpoint"); err != nil { + writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()}) + return + } + } + } + + // Build HTTP client with strict dial guard, redirect validation, and optional proxy. + var transport *http.Transport + if base, ok := http.DefaultTransport.(*http.Transport); ok { + transport = base.Clone() + } else { + transport = &http.Transport{} + } + transport.Proxy = nil + if proxyURL != nil { + transport.Proxy = http.ProxyURL(proxyURL) + } + if s.modelRootCAs != nil { + if transport.TLSClientConfig == nil { + transport.TLSClientConfig = &tls.Config{} + } else { + transport.TLSClientConfig = transport.TLSClientConfig.Clone() + } + transport.TLSClientConfig.RootCAs = s.modelRootCAs + } + dialCtx := (&net.Dialer{Timeout: 10 * time.Second, Control: guard.blockDial}).DialContext + if s.modelDialContext != nil { + dialCtx = s.modelDialContext + } + transport.DialContext = dialCtx + defer transport.CloseIdleConnections() + + client := &http.Client{ + Transport: transport, + Timeout: 30 * time.Second, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= maxModelRedirects { + return &modelURLRefusalError{msg: "too many redirects"} + } + if len(via) > 0 { + prev := via[len(via)-1].URL + prevScheme := strings.ToLower(prev.Scheme) + nextScheme := strings.ToLower(req.URL.Scheme) + if nextScheme != prevScheme { + if !(prevScheme == "http" && nextScheme == "https" && sameRedirectHost(prev, req.URL)) { + return &modelURLRefusalError{msg: "redirect scheme change is not allowed"} + } + } + } + if _, err := guard.validateURL(req.Context(), req.URL.String(), "redirect"); err != nil { + return err + } + return nil + }, + } // Try each candidate; return the first that yields a non-empty model list. var lastErr string emptyOK := false - for _, c := range candidates { + for i, c := range candidates { + if i > 0 && !defaultOllama { + if _, err := guard.validateURL(r.Context(), c.url, "endpoint"); err != nil { + writeJSON(w, 200, map[string]any{"ok": false, "error": err.Error()}) + return + } + } httpReq, err := http.NewRequestWithContext(r.Context(), http.MethodGet, c.url, nil) if err != nil { lastErr = "failed to build request: " + err.Error() @@ -2370,6 +2745,11 @@ func (s *Server) pgListModels(w http.ResponseWriter, r *http.Request) { httpReq.Header = c.hdr resp, err := client.Do(httpReq) if err != nil { + var refusal *modelURLRefusalError + if errors.As(err, &refusal) { + writeJSON(w, 200, map[string]any{"ok": false, "error": refusal.Error()}) + return + } lastErr = "request failed: " + err.Error() continue } diff --git a/server/symlink_confinement_test.go b/server/symlink_confinement_test.go new file mode 100644 index 0000000..e5ef654 --- /dev/null +++ b/server/symlink_confinement_test.go @@ -0,0 +1,1069 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "syscall" + "testing" +) + +// mustSymlink creates a symlink at newname pointing to oldname. On Windows +// without symlink privileges it skips the test so the package still builds and +// tests cleanly there. +func mustSymlink(t *testing.T, oldname, newname string) { + t.Helper() + if err := os.Symlink(oldname, newname); err != nil { + if runtime.GOOS == "windows" && isWindowsSymlinkPrivilegeErr(err) { + t.Skipf("skipping symlink test on Windows without symlink privileges: %v", err) + } + t.Fatalf("os.Symlink(%q, %q): %v", oldname, newname, err) + } +} + +func isWindowsSymlinkPrivilegeErr(err error) bool { + if errors.Is(err, os.ErrPermission) { + return true + } + var errno syscall.Errno + if errors.As(err, &errno) && errno == 1314 { // ERROR_PRIVILEGE_NOT_HELD + return true + } + return strings.Contains(strings.ToLower(err.Error()), "privilege") +} + +func assertNoAbsPathLeak(t *testing.T, body string, paths ...string) { + t.Helper() + for _, p := range paths { + if p == "" { + continue + } + if strings.Contains(body, p) { + t.Errorf("response body leaked absolute path %q: %s", p, body) + } + if real, err := filepath.EvalSymlinks(p); err == nil && real != "" && strings.Contains(body, real) { + t.Errorf("response body leaked resolved path %q: %s", real, body) + } + } +} + +// symlinkFixture sets up a root dir and a sibling outside dir with every +// required symlink scenario: +// - out-file: symlink to outside/secret.txt +// - out-dir: symlink to outside/dir (contains secret.txt) +// - in-file-rel: relative symlink to inside.txt +// - in-file-abs: absolute symlink to /inside.txt +// - in-dir-rel: relative symlink to subdir (contains nested.txt) +// - in-dir-abs: absolute symlink to /subdir +// - broken-out: dangling symlink to outside/missing.txt +// - broken-in: dangling symlink to missing-inside.txt +// - loop-a <-> loop-b: symlink loop +// - subdir/rel-escape-file: relative symlink with ".." escaping to outside/secret.txt +// - subdir/rel-escape-dir: relative symlink with ".." escaping to outside/dir +// - subdir/rel-inside: relative symlink with ".." staying inside (/inside.txt) +type symlinkFixture struct { + root string + outside string + outsideSecret string + outsideDir string +} + +func newSymlinkFixture(t *testing.T) symlinkFixture { + t.Helper() + base := t.TempDir() + root := filepath.Join(base, "root") + outside := filepath.Join(base, "outside") + outsideDir := filepath.Join(outside, "dir") + subdir := filepath.Join(root, "subdir") + + for _, d := range []string{root, outsideDir, subdir} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + outsideSecret := filepath.Join(outside, "secret.txt") + if err := os.WriteFile(outsideSecret, []byte("TOP_SECRET"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(outsideDir, "secret.txt"), []byte("DIR_SECRET"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "inside.txt"), []byte("INSIDE_OK"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(subdir, "nested.txt"), []byte("NESTED_OK"), 0o644); err != nil { + t.Fatal(err) + } + + mustSymlink(t, outsideSecret, filepath.Join(root, "out-file")) + mustSymlink(t, outsideDir, filepath.Join(root, "out-dir")) + mustSymlink(t, "inside.txt", filepath.Join(root, "in-file-rel")) + mustSymlink(t, filepath.Join(root, "inside.txt"), filepath.Join(root, "in-file-abs")) + mustSymlink(t, "subdir", filepath.Join(root, "in-dir-rel")) + mustSymlink(t, subdir, filepath.Join(root, "in-dir-abs")) + mustSymlink(t, filepath.Join(outside, "missing.txt"), filepath.Join(root, "broken-out")) + mustSymlink(t, "missing-inside.txt", filepath.Join(root, "broken-in")) + mustSymlink(t, "loop-b", filepath.Join(root, "loop-a")) + mustSymlink(t, "loop-a", filepath.Join(root, "loop-b")) + mustSymlink(t, filepath.Join("..", "..", "outside", "secret.txt"), filepath.Join(subdir, "rel-escape-file")) + mustSymlink(t, filepath.Join("..", "..", "outside", "dir"), filepath.Join(subdir, "rel-escape-dir")) + mustSymlink(t, filepath.Join("..", "inside.txt"), filepath.Join(subdir, "rel-inside")) + + return symlinkFixture{ + root: root, + outside: outside, + outsideSecret: outsideSecret, + outsideDir: outsideDir, + } +} + +func newTestWorkspaceServer(root string) *Server { + return &Server{m: &Manager{dir: root}} +} + +func doJSONReq(t *testing.T, method, target string, payload any, h http.HandlerFunc) *httptest.ResponseRecorder { + t.Helper() + var body bytes.Buffer + if payload != nil { + if err := json.NewEncoder(&body).Encode(payload); err != nil { + t.Fatal(err) + } + } + req := httptest.NewRequest(method, target, &body) + req.Header.Set("Content-Type", "application/json") + rr := httptest.NewRecorder() + h(rr, req) + return rr +} + +func doUploadReq(t *testing.T, s *Server, dirPath, filename, content string) *httptest.ResponseRecorder { + t.Helper() + var body bytes.Buffer + mw := multipart.NewWriter(&body) + fw, err := mw.CreateFormFile("file", filename) + if err != nil { + t.Fatal(err) + } + if _, err := fw.Write([]byte(content)); err != nil { + t.Fatal(err) + } + if err := mw.Close(); err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(http.MethodPost, "/api/workspace/upload?path="+url.QueryEscape(dirPath), &body) + req.Header.Set("Content-Type", mw.FormDataContentType()) + rr := httptest.NewRecorder() + s.wsUpload(rr, req) + return rr +} + +func TestWorkspaceListSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"child of symlink to outside dir", "out-dir/sub"}, + {"broken symlink outside", "broken-out"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-dir"}, + {"outside symlink plus dotdot", "out-dir/.."}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-dir"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/list?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsList(rr, req) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsList(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + for _, okPath := range []string{"in-dir-rel", "in-dir-abs"} { + t.Run("allow_"+okPath, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/list?path="+url.QueryEscape(okPath), nil) + rr := httptest.NewRecorder() + s.wsList(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("wsList(%q) = %d (%s), want 200", okPath, rr.Code, rr.Body.String()) + } + if !strings.Contains(rr.Body.String(), "nested.txt") { + t.Fatalf("wsList(%q) missing nested.txt: %s", okPath, rr.Body.String()) + } + }) + } +} + +func TestWorkspaceReadSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"file under symlink to outside dir", "out-dir/secret.txt"}, + {"broken symlink outside", "broken-out"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-file"}, + {"outside symlink plus dotdot", "out-dir/../secret.txt"}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside/secret.txt"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-file"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/read?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsRead(rr, req) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsRead(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + if strings.Contains(rr.Body.String(), "SECRET") { + t.Fatalf("wsRead(%q) leaked outside content: %s", tc.path, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + allowCases := []struct { + path string + want string + }{ + {"in-file-rel", "INSIDE_OK"}, + {"in-file-abs", "INSIDE_OK"}, + {"in-dir-rel/nested.txt", "NESTED_OK"}, + {"in-dir-abs/nested.txt", "NESTED_OK"}, + {"subdir/rel-inside", "INSIDE_OK"}, + } + for _, tc := range allowCases { + t.Run("allow_"+tc.path, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/read?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsRead(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("wsRead(%q) = %d (%s), want 200", tc.path, rr.Code, rr.Body.String()) + } + if !strings.Contains(rr.Body.String(), tc.want) { + t.Fatalf("wsRead(%q) = %s, want %q", tc.path, rr.Body.String(), tc.want) + } + }) + } +} + +func TestWorkspaceWriteSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"existing file under outside dir symlink", "out-dir/secret.txt"}, + {"nonexistent file under outside dir symlink", "out-dir/newsub/pwn.txt"}, + {"broken symlink outside", "broken-out"}, + {"nonexistent child under broken symlink", "broken-out/pwn.txt"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-file"}, + {"outside symlink plus dotdot", "out-dir/../pwn.txt"}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside/pwn.txt"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-file"}, + {"nonexistent under relative dotdot escape dir", "subdir/rel-escape-dir/pwn.txt"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + rr := doJSONReq(t, http.MethodPost, "/api/workspace/write", + map[string]string{"path": tc.path, "content": "OVERWRITTEN"}, s.wsWrite) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsWrite(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + // Verify outside files were not touched or created. + if got, _ := os.ReadFile(f.outsideSecret); string(got) != "TOP_SECRET" { + t.Fatalf("outside secret modified: %q", got) + } + if got, _ := os.ReadFile(filepath.Join(f.outsideDir, "secret.txt")); string(got) != "DIR_SECRET" { + t.Fatalf("outside dir secret modified: %q", got) + } + for _, untouched := range []string{ + filepath.Join(f.outside, "missing.txt"), + filepath.Join(f.outside, "pwn.txt"), + filepath.Join(f.outsideDir, "newsub", "pwn.txt"), + filepath.Join(f.outsideDir, "pwn.txt"), + } { + if _, err := os.Lstat(untouched); !os.IsNotExist(err) { + t.Fatalf("outside path should not exist: %s", untouched) + } + } + + // Symlink inside root staying inside must still work (existing file + nonexistent target under symlinked parent). + t.Run("allow_inside_file_symlink", func(t *testing.T) { + rr := doJSONReq(t, http.MethodPost, "/api/workspace/write", + map[string]string{"path": "in-file-rel", "content": "UPDATED"}, s.wsWrite) + if rr.Code != http.StatusOK { + t.Fatalf("wsWrite(in-file-rel) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.root, "inside.txt")); string(got) != "UPDATED" { + t.Fatalf("inside.txt = %q, want UPDATED", got) + } + }) + t.Run("allow_nonexistent_under_inside_symlink_parent", func(t *testing.T) { + rr := doJSONReq(t, http.MethodPost, "/api/workspace/write", + map[string]string{"path": "in-dir-rel/fresh/created.txt", "content": "FRESH"}, s.wsWrite) + if rr.Code != http.StatusOK { + t.Fatalf("wsWrite(in-dir-rel/fresh/created.txt) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.root, "subdir", "fresh", "created.txt")); string(got) != "FRESH" { + t.Fatalf("created.txt = %q, want FRESH", got) + } + }) +} + +func TestWorkspaceMkdirSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"nonexistent dir under outside symlink parent", "out-dir/escaped-dir/nested"}, + {"broken symlink outside", "broken-out"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-dir/newdir"}, + {"outside symlink plus dotdot", "out-dir/../newdir"}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside/newdir"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-dir/newdir"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + rr := doJSONReq(t, http.MethodPost, "/api/workspace/mkdir", + map[string]string{"path": tc.path}, s.wsMkdir) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsMkdir(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + for _, untouched := range []string{ + filepath.Join(f.outsideDir, "escaped-dir"), + filepath.Join(f.outside, "missing.txt"), + filepath.Join(f.outside, "newdir"), + } { + if _, err := os.Lstat(untouched); !os.IsNotExist(err) { + t.Fatalf("outside dir should not have been created: %s", untouched) + } + } + + t.Run("allow_inside_dir_symlink_and_nonexistent_child", func(t *testing.T) { + rr := doJSONReq(t, http.MethodPost, "/api/workspace/mkdir", + map[string]string{"path": "in-dir-rel/newchild/deep"}, s.wsMkdir) + if rr.Code != http.StatusOK { + t.Fatalf("wsMkdir(in-dir-rel/newchild/deep) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if fi, err := os.Stat(filepath.Join(f.root, "subdir", "newchild", "deep")); err != nil || !fi.IsDir() { + t.Fatalf("expected created directory inside root: err=%v", err) + } + }) +} + +func TestWorkspaceDeleteSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + mustSymlink(t, ".", filepath.Join(f.root, "root-link")) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"file under symlink to outside dir", "out-dir/secret.txt"}, + {"broken symlink outside", "broken-out"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-file"}, + {"outside symlink plus dotdot", "out-dir/../secret.txt"}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside/secret.txt"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-file"}, + {"symlink to root itself", "root-link"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodDelete, "/api/workspace/delete?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsDelete(rr, req) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsDelete(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + if _, err := os.Stat(f.outsideSecret); err != nil { + t.Fatalf("outside secret was deleted: %v", err) + } + if _, err := os.Stat(filepath.Join(f.outsideDir, "secret.txt")); err != nil { + t.Fatalf("outside dir secret was deleted: %v", err) + } + + // Deleting an in-root symlink removes the symlink itself and preserves its target. + t.Run("allow_delete_inside_symlink", func(t *testing.T) { + req := httptest.NewRequest(http.MethodDelete, "/api/workspace/delete?path=in-file-rel", nil) + rr := httptest.NewRecorder() + s.wsDelete(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("wsDelete(in-file-rel) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if _, err := os.Lstat(filepath.Join(f.root, "in-file-rel")); !os.IsNotExist(err) { + t.Fatalf("in-file-rel symlink should have been removed") + } + if _, err := os.Stat(filepath.Join(f.root, "inside.txt")); err != nil { + t.Fatalf("inside.txt target should still exist: %v", err) + } + }) + + // Deleting a file through an inside directory symlink works. + t.Run("allow_delete_through_inside_dir_symlink", func(t *testing.T) { + req := httptest.NewRequest(http.MethodDelete, "/api/workspace/delete?path=in-dir-rel/nested.txt", nil) + rr := httptest.NewRecorder() + s.wsDelete(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("wsDelete(in-dir-rel/nested.txt) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if _, err := os.Stat(filepath.Join(f.root, "subdir", "nested.txt")); !os.IsNotExist(err) { + t.Fatalf("nested.txt should have been deleted") + } + }) +} + +func TestWorkspaceDownloadSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + path string + }{ + {"symlink to outside file", "out-file"}, + {"symlink to outside dir", "out-dir"}, + {"file under symlink to outside dir", "out-dir/secret.txt"}, + {"broken symlink outside", "broken-out"}, + {"broken symlink inside", "broken-in"}, + {"symlink loop", "loop-a"}, + {"dotdot plus outside symlink", "subdir/../out-file"}, + {"outside symlink plus dotdot", "out-dir/../secret.txt"}, + {"inside symlink plus dotdot escape", "in-dir-rel/../../outside/secret.txt"}, + {"relative symlink with dotdot escape", "subdir/rel-escape-file"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/download?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsDownload(rr, req) + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsDownload(%q) = %d (%s), want 400", tc.path, rr.Code, rr.Body.String()) + } + if strings.Contains(rr.Body.String(), "SECRET") { + t.Fatalf("wsDownload(%q) leaked outside content", tc.path) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + for _, tc := range []struct{ path, want string }{ + {"in-file-rel", "INSIDE_OK"}, + {"in-file-abs", "INSIDE_OK"}, + {"in-dir-rel/nested.txt", "NESTED_OK"}, + } { + t.Run("allow_"+tc.path, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/api/workspace/download?path="+url.QueryEscape(tc.path), nil) + rr := httptest.NewRecorder() + s.wsDownload(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("wsDownload(%q) = %d (%s), want 200", tc.path, rr.Code, rr.Body.String()) + } + if rr.Body.String() != tc.want { + t.Fatalf("wsDownload(%q) body = %q, want %q", tc.path, rr.Body.String(), tc.want) + } + }) + } +} + +func TestWorkspaceUploadSymlinkConfinement(t *testing.T) { + f := newSymlinkFixture(t) + s := newTestWorkspaceServer(f.root) + + rejectCases := []struct { + name string + dirPath string + filename string + }{ + {"filename is symlink to outside file", "", "out-file"}, + {"target dir is symlink to outside dir (new file)", "out-dir", "newfile.txt"}, + {"target dir is nonexistent under outside symlink", "out-dir/missing", "newfile.txt"}, + {"filename is symlink to outside dir", "", "out-dir"}, + {"filename is broken symlink outside", "", "broken-out"}, + {"filename is broken symlink inside", "", "broken-in"}, + {"target dir is broken symlink", "broken-out", "newfile.txt"}, + {"target dir is symlink loop", "loop-a", "newfile.txt"}, + {"filename is symlink loop", "", "loop-a"}, + {"dotdot plus outside symlink dir", "subdir/../out-dir", "newfile.txt"}, + {"inside symlink dir plus dotdot escape", "in-dir-rel/../../outside", "newfile.txt"}, + {"relative symlink with dotdot escape dir", "subdir/rel-escape-dir", "newfile.txt"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + rr := doUploadReq(t, s, tc.dirPath, tc.filename, "UPLOADED_EVIL") + if rr.Code != http.StatusBadRequest { + t.Fatalf("wsUpload(dir=%q, file=%q) = %d (%s), want 400", tc.dirPath, tc.filename, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.root, f.outside) + }) + } + + if got, _ := os.ReadFile(f.outsideSecret); string(got) != "TOP_SECRET" { + t.Fatalf("outside secret modified by upload: %q", got) + } + for _, untouched := range []string{ + filepath.Join(f.outsideDir, "newfile.txt"), + filepath.Join(f.outside, "missing.txt"), + filepath.Join(f.outside, "newfile.txt"), + } { + if _, err := os.Lstat(untouched); !os.IsNotExist(err) { + t.Fatalf("upload created file outside root: %s", untouched) + } + } + + // Non-existent target under inside symlinked parent must succeed. + t.Run("allow_new_file_under_inside_symlink_dir", func(t *testing.T) { + rr := doUploadReq(t, s, "in-dir-rel", "fresh-upload.txt", "HELLO_UPLOAD") + if rr.Code != http.StatusOK { + t.Fatalf("wsUpload(in-dir-rel, fresh-upload.txt) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.root, "subdir", "fresh-upload.txt")); string(got) != "HELLO_UPLOAD" { + t.Fatalf("uploaded file = %q, want HELLO_UPLOAD", got) + } + }) + t.Run("allow_overwrite_inside_file_symlink", func(t *testing.T) { + rr := doUploadReq(t, s, "", "in-file-rel", "VIA_LINK") + if rr.Code != http.StatusOK { + t.Fatalf("wsUpload('', in-file-rel) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.root, "inside.txt")); string(got) != "VIA_LINK" { + t.Fatalf("inside.txt = %q, want VIA_LINK", got) + } + }) +} + +// skillFixture builds a skillDir with a "demo" skill containing the same +// symlink matrix, plus an escaping skill directory symlink "evil-skill" and +// a sibling "other-skill". +type skillFixture struct { + skillDir string + skillRoot string + outside string + outsideSecret string + outsideDir string +} + +func newSkillFixture(t *testing.T) skillFixture { + t.Helper() + base := t.TempDir() + skillDir := filepath.Join(base, "skills") + skillRoot := filepath.Join(skillDir, "demo") + otherSkill := filepath.Join(skillDir, "other") + refs := filepath.Join(skillRoot, "references") + outside := filepath.Join(base, "outside") + outsideDir := filepath.Join(outside, "dir") + + for _, d := range []string{refs, otherSkill, outsideDir} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + outsideSecret := filepath.Join(outside, "secret.txt") + if err := os.WriteFile(outsideSecret, []byte("---\nname: leaked\ndescription: secret\n---\nTOP_SECRET\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(outsideDir, "secret.txt"), []byte("DIR_SECRET"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(skillRoot, "SKILL.md"), []byte("---\nname: demo\ndescription: demo skill\n---\nDEMO_BODY\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(refs, "doc.md"), []byte("REF_DOC"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(otherSkill, "SKILL.md"), []byte("---\nname: other\ndescription: other\n---\nOTHER_SECRET\n"), 0o644); err != nil { + t.Fatal(err) + } + + mustSymlink(t, outsideSecret, filepath.Join(skillRoot, "out-file.md")) + mustSymlink(t, outsideDir, filepath.Join(skillRoot, "out-dir")) + mustSymlink(t, "SKILL.md", filepath.Join(skillRoot, "in-file-rel.md")) + mustSymlink(t, filepath.Join(skillRoot, "SKILL.md"), filepath.Join(skillRoot, "in-file-abs.md")) + mustSymlink(t, "references", filepath.Join(skillRoot, "in-dir-rel")) + mustSymlink(t, refs, filepath.Join(skillRoot, "in-dir-abs")) + mustSymlink(t, filepath.Join(outside, "missing.md"), filepath.Join(skillRoot, "broken-out.md")) + mustSymlink(t, "missing-inside.md", filepath.Join(skillRoot, "broken-in.md")) + mustSymlink(t, "loop-b", filepath.Join(skillRoot, "loop-a")) + mustSymlink(t, "loop-a", filepath.Join(skillRoot, "loop-b")) + mustSymlink(t, filepath.Join("..", "..", "..", "outside", "secret.txt"), filepath.Join(refs, "rel-escape-file.md")) + mustSymlink(t, filepath.Join("..", "..", "..", "outside", "dir"), filepath.Join(refs, "rel-escape-dir")) + mustSymlink(t, filepath.Join("..", "SKILL.md"), filepath.Join(refs, "rel-inside.md")) + mustSymlink(t, filepath.Join("..", "other", "SKILL.md"), filepath.Join(skillRoot, "cross-skill.md")) + // Skill directory itself is a symlink pointing outside skillDir. + mustSymlink(t, outsideDir, filepath.Join(skillDir, "evil-skill")) + // Skill directory itself is a symlink staying inside skillDir. + mustSymlink(t, "demo", filepath.Join(skillDir, "alias-skill")) + + return skillFixture{ + skillDir: skillDir, + skillRoot: skillRoot, + outside: outside, + outsideSecret: outsideSecret, + outsideDir: outsideDir, + } +} + +func skillReq(method, name, file string, body any) *http.Request { + var buf bytes.Buffer + if body != nil { + _ = json.NewEncoder(&buf).Encode(body) + } + req := httptest.NewRequest(method, "/api/skills/"+name+"/files/"+file, &buf) + req.SetPathValue("name", name) + if file != "" { + req.SetPathValue("file", file) + } + req.Header.Set("Content-Type", "application/json") + return req +} + +func TestSkillReadFileSymlinkConfinement(t *testing.T) { + f := newSkillFixture(t) + s := &Server{skillDir: f.skillDir} + + rejectCases := []struct { + name string + skill string + file string + }{ + {"symlink to outside file", "demo", "out-file.md"}, + {"symlink to outside dir", "demo", "out-dir"}, + {"file under symlink to outside dir", "demo", "out-dir/secret.txt"}, + {"cross-skill symlink", "demo", "cross-skill.md"}, + {"escaping skill dir symlink", "evil-skill", "secret.txt"}, + {"broken symlink outside", "demo", "broken-out.md"}, + {"broken symlink inside", "demo", "broken-in.md"}, + {"symlink loop", "demo", "loop-a"}, + {"dotdot plus symlink in request", "demo", "references/../out-file.md"}, + {"inside symlink plus dotdot in request", "demo", "in-dir-rel/../../outside/secret.txt"}, + {"relative symlink with dotdot escape", "demo", "references/rel-escape-file.md"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsReadFile(rr, skillReq(http.MethodGet, tc.skill, tc.file, nil)) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsReadFile(%q, %q) = %d (%s), want 400", tc.skill, tc.file, rr.Code, rr.Body.String()) + } + if strings.Contains(rr.Body.String(), "SECRET") { + t.Fatalf("fsReadFile(%q, %q) leaked secret content", tc.skill, tc.file) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + }) + } + + allowCases := []struct { + skill string + file string + want string + }{ + {"demo", "in-file-rel.md", "DEMO_BODY"}, + {"demo", "in-file-abs.md", "DEMO_BODY"}, + {"demo", "in-dir-rel/doc.md", "REF_DOC"}, + {"demo", "in-dir-abs/doc.md", "REF_DOC"}, + {"demo", "references/rel-inside.md", "DEMO_BODY"}, + {"alias-skill", "SKILL.md", "DEMO_BODY"}, + } + for _, tc := range allowCases { + t.Run("allow_"+tc.skill+"/"+tc.file, func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsReadFile(rr, skillReq(http.MethodGet, tc.skill, tc.file, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("fsReadFile(%q, %q) = %d (%s), want 200", tc.skill, tc.file, rr.Code, rr.Body.String()) + } + if !strings.Contains(rr.Body.String(), tc.want) { + t.Fatalf("fsReadFile(%q, %q) = %s, want %q", tc.skill, tc.file, rr.Body.String(), tc.want) + } + }) + } +} + +func TestSkillWriteFileSymlinkConfinement(t *testing.T) { + f := newSkillFixture(t) + s := &Server{skillDir: f.skillDir} + + rejectCases := []struct { + name string + skill string + file string + }{ + {"symlink to outside file", "demo", "out-file.md"}, + {"symlink to outside dir", "demo", "out-dir"}, + {"existing file under outside dir symlink", "demo", "out-dir/secret.txt"}, + {"nonexistent file under outside dir symlink", "demo", "out-dir/newsub/pwn.md"}, + {"escaping skill dir symlink", "evil-skill", "pwn.md"}, + {"cross-skill symlink", "demo", "cross-skill.md"}, + {"broken symlink outside", "demo", "broken-out.md"}, + {"nonexistent child under broken symlink", "demo", "broken-out.md/pwn.md"}, + {"broken symlink inside", "demo", "broken-in.md"}, + {"symlink loop", "demo", "loop-a"}, + {"dotdot plus symlink in request", "demo", "references/../out-file.md"}, + {"relative symlink with dotdot escape", "demo", "references/rel-escape-file.md"}, + {"nonexistent under relative dotdot escape dir", "demo", "references/rel-escape-dir/pwn.md"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsWriteFile(rr, skillReq(http.MethodPut, tc.skill, tc.file, map[string]string{"content": "OVERWRITTEN"})) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsWriteFile(%q, %q) = %d (%s), want 400", tc.skill, tc.file, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + }) + } + + if got, _ := os.ReadFile(f.outsideSecret); !strings.Contains(string(got), "TOP_SECRET") { + t.Fatalf("outside secret modified: %q", got) + } + for _, untouched := range []string{ + filepath.Join(f.outside, "missing.md"), + filepath.Join(f.outsideDir, "newsub", "pwn.md"), + filepath.Join(f.outsideDir, "pwn.md"), + } { + if _, err := os.Lstat(untouched); !os.IsNotExist(err) { + t.Fatalf("outside path should not exist: %s", untouched) + } + } + + t.Run("allow_inside_file_symlink", func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsWriteFile(rr, skillReq(http.MethodPut, "demo", "in-file-rel.md", map[string]string{"content": "UPDATED_SKILL"})) + if rr.Code != http.StatusOK { + t.Fatalf("fsWriteFile(in-file-rel.md) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.skillRoot, "SKILL.md")); string(got) != "UPDATED_SKILL" { + t.Fatalf("SKILL.md = %q, want UPDATED_SKILL", got) + } + }) + t.Run("allow_nonexistent_under_inside_symlink_parent", func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsWriteFile(rr, skillReq(http.MethodPut, "demo", "in-dir-rel/fresh/note.md", map[string]string{"content": "NEW_NOTE"})) + if rr.Code != http.StatusOK { + t.Fatalf("fsWriteFile(in-dir-rel/fresh/note.md) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if got, _ := os.ReadFile(filepath.Join(f.skillRoot, "references", "fresh", "note.md")); string(got) != "NEW_NOTE" { + t.Fatalf("note.md = %q, want NEW_NOTE", got) + } + }) +} + +func TestSkillCreateDirSymlinkConfinement(t *testing.T) { + f := newSkillFixture(t) + s := &Server{skillDir: f.skillDir} + + rejectCases := []struct { + name string + skill string + dir string + }{ + {"symlink to outside file", "demo", "out-file.md"}, + {"symlink to outside dir", "demo", "out-dir"}, + {"nonexistent dir under outside dir symlink", "demo", "out-dir/escaped/nested"}, + {"escaping skill dir symlink", "evil-skill", "newdir"}, + {"broken symlink outside", "demo", "broken-out.md"}, + {"broken symlink inside", "demo", "broken-in.md"}, + {"symlink loop", "demo", "loop-a"}, + {"dotdot plus symlink in request", "demo", "references/../out-dir/newdir"}, + {"relative symlink with dotdot escape", "demo", "references/rel-escape-dir/newdir"}, + } + for _, tc := range rejectCases { + t.Run("reject_"+tc.name, func(t *testing.T) { + req := skillReq(http.MethodPost, tc.skill, "", map[string]string{"path": tc.dir}) + rr := httptest.NewRecorder() + s.fsCreateDir(rr, req) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsCreateDir(%q, %q) = %d (%s), want 400", tc.skill, tc.dir, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + }) + } + + for _, untouched := range []string{ + filepath.Join(f.outsideDir, "escaped"), + filepath.Join(f.outsideDir, "newdir"), + filepath.Join(f.outside, "missing.md"), + } { + if _, err := os.Lstat(untouched); !os.IsNotExist(err) { + t.Fatalf("outside dir should not have been created: %s", untouched) + } + } + + t.Run("allow_nonexistent_dir_under_inside_symlink_parent", func(t *testing.T) { + req := skillReq(http.MethodPost, "demo", "", map[string]string{"path": "in-dir-rel/sub/deep"}) + rr := httptest.NewRecorder() + s.fsCreateDir(rr, req) + if rr.Code != http.StatusCreated { + t.Fatalf("fsCreateDir(in-dir-rel/sub/deep) = %d (%s), want 201", rr.Code, rr.Body.String()) + } + if fi, err := os.Stat(filepath.Join(f.skillRoot, "references", "sub", "deep")); err != nil || !fi.IsDir() { + t.Fatalf("expected dir created inside skill: err=%v", err) + } + }) +} + +func TestSkillDeleteAndMetaAndListSymlinkConfinement(t *testing.T) { + f := newSkillFixture(t) + s := &Server{skillDir: f.skillDir} + + // fsDeletePath rejections + for _, tc := range []struct{ name, skill, file string }{ + {"outside file", "demo", "out-file.md"}, + {"outside dir", "demo", "out-dir"}, + {"child of outside dir", "demo", "out-dir/secret.txt"}, + {"broken outside", "demo", "broken-out.md"}, + {"broken inside", "demo", "broken-in.md"}, + {"loop", "demo", "loop-a"}, + {"dotdot plus symlink", "demo", "references/../out-file.md"}, + {"relative dotdot escape", "demo", "references/rel-escape-file.md"}, + {"escaping skill dir", "evil-skill", "secret.txt"}, + } { + t.Run("delete_reject_"+tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsDeletePath(rr, skillReq(http.MethodDelete, tc.skill, tc.file, nil)) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsDeletePath(%q, %q) = %d (%s), want 400", tc.skill, tc.file, rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + }) + } + if _, err := os.Stat(f.outsideSecret); err != nil { + t.Fatalf("outside secret deleted: %v", err) + } + + // fsDeletePath on inside symlink removes symlink and preserves target. + t.Run("delete_allow_inside_symlink", func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsDeletePath(rr, skillReq(http.MethodDelete, "demo", "in-file-rel.md", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("fsDeletePath(in-file-rel.md) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if _, err := os.Lstat(filepath.Join(f.skillRoot, "in-file-rel.md")); !os.IsNotExist(err) { + t.Fatalf("in-file-rel.md should be removed") + } + if _, err := os.Stat(filepath.Join(f.skillRoot, "SKILL.md")); err != nil { + t.Fatalf("SKILL.md target should be preserved: %v", err) + } + }) + + // fsListFiles rejects escaping skill dir symlink and allows inside alias. + t.Run("list_files_reject_escaping_skill_dir", func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsListFiles(rr, skillReq(http.MethodGet, "evil-skill", "", nil)) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsListFiles(evil-skill) = %d (%s), want 400", rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + }) + t.Run("list_files_allow_inside_alias", func(t *testing.T) { + rr := httptest.NewRecorder() + s.fsListFiles(rr, skillReq(http.MethodGet, "alias-skill", "", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("fsListFiles(alias-skill) = %d (%s), want 200", rr.Code, rr.Body.String()) + } + }) + + // fsUpdateSkillMeta rejects escaping SKILL.md symlink. + t.Run("update_meta_reject_escaping_skill_md", func(t *testing.T) { + badSkill := filepath.Join(f.skillDir, "meta-escape") + if err := os.MkdirAll(badSkill, 0o755); err != nil { + t.Fatal(err) + } + mustSymlink(t, f.outsideSecret, filepath.Join(badSkill, "SKILL.md")) + + desc := "pwned" + rr := httptest.NewRecorder() + s.fsUpdateSkillMeta(rr, skillReq(http.MethodPut, "meta-escape", "", map[string]any{"description": desc})) + if rr.Code != http.StatusBadRequest { + t.Fatalf("fsUpdateSkillMeta(meta-escape) = %d (%s), want 400", rr.Code, rr.Body.String()) + } + assertNoAbsPathLeak(t, rr.Body.String(), f.skillDir, f.outside) + if got, _ := os.ReadFile(f.outsideSecret); !strings.Contains(string(got), "TOP_SECRET") { + t.Fatalf("outside secret overwritten via fsUpdateSkillMeta: %q", got) + } + }) + + // toolUpdateSkillFile rejects escaping symlinks and allows inside symlinks. + t.Run("tool_update_skill_file_confinement", func(t *testing.T) { + tl := s.toolUpdateSkillFile() + for _, badFile := range []string{"out-file.md", "out-dir/new.md", "broken-out.md", "loop-a", "references/rel-escape-file.md"} { + in, _ := json.Marshal(map[string]string{"name": "demo", "file": badFile, "content": "EVIL"}) + res, err := tl.Call(context.Background(), in, nil) + if err != nil { + t.Fatalf("toolUpdateSkillFile(%q) returned err: %v", badFile, err) + } + if !res.IsError { + t.Fatalf("toolUpdateSkillFile(%q) should fail, got %+v", badFile, res) + } + assertNoAbsPathLeak(t, res.Flatten(), f.skillDir, f.outside) + } + in, _ := json.Marshal(map[string]string{"name": "demo", "file": "in-dir-rel/tool-ok.md", "content": "TOOL_OK"}) + res, err := tl.Call(context.Background(), in, nil) + if err != nil || res.IsError { + t.Fatalf("toolUpdateSkillFile(in-dir-rel/tool-ok.md) failed: err=%v res=%+v", err, res) + } + if got, _ := os.ReadFile(filepath.Join(f.skillRoot, "references", "tool-ok.md")); string(got) != "TOOL_OK" { + t.Fatalf("tool-ok.md = %q, want TOOL_OK", got) + } + }) +} + +func TestSkillLoaderSymlinkConfinement(t *testing.T) { + base := t.TempDir() + skillDir := filepath.Join(base, "skills") + outside := filepath.Join(base, "outside") + if err := os.MkdirAll(skillDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(outside, 0o755); err != nil { + t.Fatal(err) + } + outsideMD := filepath.Join(outside, "secret.md") + if err := os.WriteFile(outsideMD, []byte("---\nname: leaked\ndescription: secret desc\n---\nSECRET_INSTRUCTIONS\n"), 0o644); err != nil { + t.Fatal(err) + } + + // 1. Valid regular skill. + goodDir := filepath.Join(skillDir, "good-skill") + if err := os.MkdirAll(goodDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(goodDir, "SKILL.md"), []byte("---\nname: good-skill\ndescription: ok\n---\nGOOD_BODY\n"), 0o644); err != nil { + t.Fatal(err) + } + + // 2. Skill whose SKILL.md is an in-skill symlink staying inside its directory. + inLinkDir := filepath.Join(skillDir, "inlink-skill") + if err := os.MkdirAll(inLinkDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inLinkDir, "real.md"), []byte("---\nname: inlink-skill\ndescription: inside link\n---\nINLINK_BODY\n"), 0o644); err != nil { + t.Fatal(err) + } + mustSymlink(t, "real.md", filepath.Join(inLinkDir, "SKILL.md")) + + // 3. Skill whose SKILL.md is a symlink pointing outside skillDir. + evilDir := filepath.Join(skillDir, "evil-skill") + if err := os.MkdirAll(evilDir, 0o755); err != nil { + t.Fatal(err) + } + mustSymlink(t, outsideMD, filepath.Join(evilDir, "SKILL.md")) + + // 4. Skill whose SKILL.md is a relative ".." symlink escaping outside skillDir. + relEscapeDir := filepath.Join(skillDir, "rel-escape-skill") + if err := os.MkdirAll(relEscapeDir, 0o755); err != nil { + t.Fatal(err) + } + mustSymlink(t, filepath.Join("..", "..", "outside", "secret.md"), filepath.Join(relEscapeDir, "SKILL.md")) + + // 5. Skill whose SKILL.md is a broken symlink. + brokenDir := filepath.Join(skillDir, "broken-skill") + if err := os.MkdirAll(brokenDir, 0o755); err != nil { + t.Fatal(err) + } + mustSymlink(t, filepath.Join(outside, "missing.md"), filepath.Join(brokenDir, "SKILL.md")) + + // 6. Skill whose SKILL.md is a symlink loop. + loopDir := filepath.Join(skillDir, "loop-skill") + if err := os.MkdirAll(loopDir, 0o755); err != nil { + t.Fatal(err) + } + mustSymlink(t, "loop-b.md", filepath.Join(loopDir, "SKILL.md")) + mustSymlink(t, "SKILL.md", filepath.Join(loopDir, "loop-b.md")) + + // 7. Bare .md symlink at top level pointing outside. + mustSymlink(t, outsideMD, filepath.Join(skillDir, "bare-evil.md")) + + reg, err := loadSkillsConfined(skillDir) + if err != nil { + t.Fatalf("loadSkillsConfined: %v", err) + } + + // Valid skills (regular + in-skill symlink) must still load with original Dir restored. + good, ok := reg.Get("good-skill") + if !ok || !strings.Contains(good.Instructions, "GOOD_BODY") { + t.Fatalf("good-skill not loaded properly: ok=%v skill=%+v", ok, good) + } + if good.Dir != goodDir { + t.Fatalf("good-skill Dir = %q, want %q", good.Dir, goodDir) + } + inlink, ok := reg.Get("inlink-skill") + if !ok || !strings.Contains(inlink.Instructions, "INLINK_BODY") { + t.Fatalf("inlink-skill not loaded properly: ok=%v skill=%+v", ok, inlink) + } + if inlink.Dir != inLinkDir { + t.Fatalf("inlink-skill Dir = %q, want %q", inlink.Dir, inLinkDir) + } + + // Escaping, broken, and looping skills must NOT be loaded. + for _, sk := range reg.List() { + if strings.Contains(sk.Instructions, "SECRET_INSTRUCTIONS") || sk.Name == "leaked" || sk.Name == "evil-skill" || sk.Name == "rel-escape-skill" || sk.Name == "broken-skill" || sk.Name == "loop-skill" || sk.Name == "bare-evil" { + t.Fatalf("unsafe skill leaked into registry: %+v", sk) + } + } + + // fsListSkills must not expose metadata from escaping SKILL.md symlinks. + s := &Server{skillDir: skillDir, m: &Manager{}} + req := httptest.NewRequest(http.MethodGet, "/api/skills", nil) + rr := httptest.NewRecorder() + s.fsListSkills(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("fsListSkills = %d (%s), want 200", rr.Code, rr.Body.String()) + } + if strings.Contains(rr.Body.String(), "secret desc") || strings.Contains(rr.Body.String(), "SECRET_INSTRUCTIONS") { + t.Fatalf("fsListSkills leaked outside skill metadata: %s", rr.Body.String()) + } +} diff --git a/server/task_llm_rotation_test.go b/server/task_llm_rotation_test.go index b590dd4..f0b0aed 100644 --- a/server/task_llm_rotation_test.go +++ b/server/task_llm_rotation_test.go @@ -3,12 +3,14 @@ package server import ( "context" "fmt" + "iter" "net/http" "net/http/httptest" "sync" "testing" "time" + "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/norma/llm" ) @@ -211,3 +213,180 @@ func TestNextRotatedProfileRoundRobin(t *testing.T) { t.Fatal("disabled rotation must not assign a pin") } } + +type pinCapture struct { + id int64 + ok bool +} + +type pinCaptureProvider struct { + mu sync.Mutex + seen []pinCapture +} + +func (p *pinCaptureProvider) record(ctx context.Context) { + id, ok := llmProfilePinFrom(ctx) + p.mu.Lock() + p.seen = append(p.seen, pinCapture{id: id, ok: ok}) + p.mu.Unlock() +} + +func (p *pinCaptureProvider) Stream(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + p.record(ctx) + return func(yield func(llm.StreamEvent, error) bool) { + if !yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "done"}, nil) { + return + } + if !yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil) { + return + } + yield(llm.StreamEvent{Type: llm.SEMessageStop}, nil) + } +} + +func (p *pinCaptureProvider) Complete(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.record(ctx) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("done")}}, "end_turn", llm.Usage{}, nil +} + +// Regression test for #376 (DB-free): warming e.execContextFor first (as the +// planner does) must not drop the per-intent LLM profile pin on subsequent +// worker intents, and a paused/deleting rollback must not advance rotation. +func TestIntentWorkContextRotatesWithCachedExecCtx(t *testing.T) { + const ( + taskID = "77" + profileA = int64(101) + profileB = int64(202) + ) + e := NewEngine(nil) + tk := &Task{ID: taskID, LLMProfileIDs: []int64{profileA, profileB}, LLMRotate: true} + + // Warm the per-task cached execCtx, simulating the planner running first. + warm := e.execContextFor(context.Background(), taskID) + if warm == nil || warm.Err() != nil { + t.Fatalf("warm execContextFor returned invalid ctx: %v", warm) + } + + // A paused task must roll back without advancing the rotation counter. + e.Pause(taskID, agent.AbortPausedByUser) + if _, _, _, ok := e.intentWorkContext(context.Background(), tk); ok { + t.Fatal("paused task unexpectedly yielded a work context") + } + e.Resume(tk) + // Re-warm cached execCtx after resume (again simulating planner before worker). + _ = e.execContextFor(context.Background(), taskID) + + // A deleting task must also roll back without advancing the rotation counter. + e.BeginDelete(taskID) + if _, _, _, ok := e.intentWorkContext(context.Background(), tk); ok { + t.Fatal("deleting task unexpectedly yielded a work context") + } + e.AbortDelete(taskID, false) + + // Two consecutive claimed intents must carry distinct rotated pins (A then B). + _, workA, cancelA, ok := e.intentWorkContext(context.Background(), tk) + if !ok { + t.Fatal("first intentWorkContext failed") + } + defer cancelA(nil) + gotA, okA := llmProfilePinFrom(workA) + if !okA || gotA != profileA { + t.Fatalf("first workCtx pin = (%d, %v), want (%d, true)", gotA, okA, profileA) + } + + _, workB, cancelB, ok := e.intentWorkContext(context.Background(), tk) + if !ok { + t.Fatal("second intentWorkContext failed") + } + defer cancelB(nil) + gotB, okB := llmProfilePinFrom(workB) + if !okB || gotB != profileB { + t.Fatalf("second workCtx pin = (%d, %v), want (%d, true)", gotB, okB, profileB) + } + if gotA == gotB { + t.Fatalf("expected distinct pinned profile IDs, both were %d", gotA) + } +} + +// Regression test for #376 (end-to-end through runIntent): warm execContextFor +// first (simulating the planner running before workers), then run two intents +// through runIntent and assert the two work contexts carry distinct pinned +// profile IDs (A then B). +func TestRunIntentRotatesPinnedProfileWithCachedExecCtx(t *testing.T) { + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Skipf("postgres unavailable: %v", err) + } + defer m.Close() + + ids := make([]int64, 0, 2) + for i := 0; i < 2; i++ { + id, err := m.pg.SaveProfile(&db.LLMProfile{ + Name: fmt.Sprintf("runintent-rotate-%d-%d", time.Now().UnixNano(), i), + Format: "openai", + BaseURL: "http://127.0.0.1:1/v1", + Model: "test", + APIKey: "test-key", + }) + if err != nil { + t.Fatal(err) + } + ids = append(ids, id) + defer m.pg.DeleteProfile(id) + } + + on := true + task, err := m.CreateTaskWithOptions("runIntent rotation", "verify pin survives cached execCtx", db.TaskCreateOptions{ + LLMProfileIDs: ids, + LLMRotate: &on, + }) + if err != nil { + t.Fatal(err) + } + defer m.DeleteTask(task.ID, DeleteTaskOptions{}) + + e := NewEngine(m) + // Warm the per-task cached execCtx before any worker intent runs. + _ = e.execContextFor(context.Background(), task.ID) + + // Verify paused rollback through runIntent does not advance rotation. + if _, err := task.Store.AddIntent(map[string]any{"summary": "rolled back while paused"}, 1, nil, "planner"); err != nil { + t.Fatal(err) + } + pausedIntent, pausedToken := e.claimNext(task, "work#0") + if pausedIntent == nil { + t.Fatal("failed to claim intent for paused rollback check") + } + e.Pause(task.ID, agent.AbortPausedByUser) + probe := &pinCaptureProvider{} + worker := agent.NewWorker(probe, "test-model", m.dir, nil, 0, 2) + e.runIntent(context.Background(), task, "work#0", worker, pausedIntent, pausedToken, "", "") + if len(probe.seen) != 0 { + t.Fatalf("paused runIntent called provider %d times, want 0", len(probe.seen)) + } + e.Resume(task) + // Re-warm cached execCtx after resume (simulating planner before workers). + _ = e.execContextFor(context.Background(), task.ID) + + // Run two intents through runIntent and assert distinct pins: ids[0] then ids[1]. + if _, err := task.Store.AddIntent(map[string]any{"summary": "rotate intent 2"}, 1, nil, "planner"); err != nil { + t.Fatal(err) + } + for i, wantID := range ids { + name := fmt.Sprintf("work#%d", i+1) + intent, token := e.claimNext(task, name) + if intent == nil { + t.Fatalf("intent %d not claimed", i+1) + } + p := &pinCaptureProvider{} + w := agent.NewWorker(p, "test-model", m.dir, nil, 0, 2) + e.runIntent(context.Background(), task, name, w, intent, token, "", "") + if len(p.seen) == 0 { + t.Fatalf("intent %d: provider was not called", i+1) + } + got := p.seen[0] + if !got.ok || got.id != wantID { + t.Fatalf("intent %d: workCtx pin = (%d, %v), want (%d, true)", i+1, got.id, got.ok, wantID) + } + } +} diff --git a/server/traffic_stream_test.go b/server/traffic_stream_test.go index 5e03f70..4e3f1cd 100644 --- a/server/traffic_stream_test.go +++ b/server/traffic_stream_test.go @@ -2,6 +2,7 @@ package server import ( "encoding/json" + "fmt" "testing" ) @@ -87,3 +88,65 @@ VALUES('1-0001',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'we t.Fatalf("exchange = %d %s", w.Code, w.Body) } } + +func TestTrafficStreamRouteDirection(t *testing.T) { + s, request := ingestServer(t) + db := s.m.Traffic().DB() + if _, err := db.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path) +VALUES('1-0002',1,'ws.example.com','GET','/ws','wss://ws.example.com/ws',101,'websocket',0,0,'')`); err != nil { + t.Fatal(err) + } + // seq 1 c2s, 2 s2c, 3 c2s, 4 s2c, 5 meta. + for i, dir := range []string{"c2s", "s2c", "c2s", "s2c", "meta"} { + kind := 1 + if dir == "meta" { + kind = 0 + } + if _, err := db.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload) VALUES('1-0002',?,1,?,?,1,'x')`, i+1, dir, kind); err != nil { + t.Fatal(err) + } + } + + type page struct { + Items []struct { + Seq int64 `json:"seq"` + Direction string `json:"direction"` + } `json:"items"` + Total int `json:"total"` + } + get := func(query string) page { + t.Helper() + w := request("GET", "/api/traffic/stream?exchange=1-0002"+query, "") + if w.Code != 200 { + t.Fatalf("GET %s = %d %s", query, w.Code, w.Body) + } + var p page + if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { + t.Fatal(err) + } + return p + } + seqs := func(p page) []int64 { + out := []int64{} + for _, it := range p.Items { + out = append(out, it.Seq) + } + return out + } + + if p := get(""); p.Total != 5 || len(p.Items) != 5 { + t.Fatalf("unfiltered = %+v", p) + } + if p := get("&direction=c2s"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[1 3 5]" { + t.Fatalf("c2s = total %d seqs %v, want 3 and [1 3 5]", p.Total, seqs(p)) + } + if p := get("&direction=S2C"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[2 4 5]" { + t.Fatalf("S2C = total %d seqs %v, want 3 and [2 4 5]", p.Total, seqs(p)) + } + if p := get("&direction=s2c&offset=1&limit=1"); p.Total != 3 || fmt.Sprint(seqs(p)) != "[4]" { + t.Fatalf("s2c offset=1 limit=1 = total %d seqs %v, want 3 and [4]", p.Total, seqs(p)) + } + if w := request("GET", "/api/traffic/stream?exchange=1-0002&direction=meta", ""); w.Code != 400 { + t.Fatalf("direction=meta = %d %s, want 400", w.Code, w.Body) + } +} diff --git a/server/webui_headers_test.go b/server/webui_headers_test.go new file mode 100644 index 0000000..55096ad --- /dev/null +++ b/server/webui_headers_test.go @@ -0,0 +1,39 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestConsoleBrowserProtections(t *testing.T) { + handler := (&Server{}).Handler() + headers := map[string]string{ + "Content-Security-Policy": "frame-ancestors 'self'", + "X-Frame-Options": "SAMEORIGIN", + "Referrer-Policy": "same-origin", + } + + for _, path := range []string{"/", "/settings/"} { + res := httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil)) + sent := res.Result().Header + for name, want := range headers { + if got := sent.Get(name); got != want { + t.Errorf("%s: %s = %q, want %q", path, name, got, want) + } + } + } + + res := httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/health", nil)) + if res.Code != http.StatusOK { + t.Fatalf("health: status = %d, want %d", res.Code, http.StatusOK) + } + sent := res.Result().Header + for name := range headers { + if got := sent.Get(name); got != "" { + t.Errorf("health: unexpected %s = %q", name, got) + } + } +} diff --git a/server/workspace.go b/server/workspace.go index 0307343..e8389ba 100644 --- a/server/workspace.go +++ b/server/workspace.go @@ -23,23 +23,68 @@ const ( maxWorkspaceUpload = 512 << 20 // 512 MiB per upload request ) +// wsResolveConfined maps a user-supplied relative path to a canonicalized path +// inside the work dir, resolving symlinks in every component and rejecting any +// traversal, broken symlink, symlink loop, or target that escapes s.m.dir. +func (s *Server) wsResolveConfined(rel string) (confinedPath, bool) { + cp, err := resolveWithinRoot(s.m.dir, rel, true) + if err != nil { + return confinedPath{}, false + } + if workspacePathDenied(cp.realRoot, cp.realPath) { + return confinedPath{}, false + } + return cp, true +} + +// workspaceDeniedPrefixes are platform-internal subtrees under the data dir +// that the workspace file manager must not expose. traffic/_ca holds the +// capture proxy CA private key; traffic/_index holds the SQLite exchange index. +var workspaceDeniedPrefixes = []string{"traffic/_ca", "traffic/_index"} + +// workspacePathDenied reports whether realPath lands in a platform-internal +// subtree. It compares the canonicalized path relative to the real root, so a +// symlink alias cannot reach a denied directory. Segments are lower-cased and +// trailing dots/spaces are trimmed because Windows resolves those spellings to +// the same directory. +func workspacePathDenied(realRoot, realPath string) bool { + rel, err := filepath.Rel(realRoot, realPath) + if err != nil { + return true // fail closed + } + rel = filepath.ToSlash(rel) + if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") { + return true // outside the root: fail closed + } + segs := strings.Split(rel, "/") + for i, seg := range segs { + segs[i] = strings.ToLower(strings.TrimRight(seg, ". ")) + } + rel = strings.Join(segs, "/") + for _, prefix := range workspaceDeniedPrefixes { + if rel == prefix || strings.HasPrefix(rel, prefix+"/") { + return true + } + } + return false +} + // wsResolve maps a user-supplied relative path to an absolute path INSIDE the work -// dir. It returns ok=false if the path would escape the root. filepath.Clean on a -// rooted copy collapses any ".." so nothing can climb above the root. +// dir. It returns ok=false if the path would escape the root (including via symlinks). func (s *Server) wsResolve(rel string) (string, bool) { - base := filepath.Clean(s.m.dir) - rel = strings.TrimPrefix(strings.TrimSpace(rel), "/") - clean := filepath.Clean("/" + rel) // e.g. "/a/../../etc" → "/etc" (still rooted at "/") - abs := filepath.Clean(filepath.Join(base, clean)) - if abs != base && !strings.HasPrefix(abs, base+string(os.PathSeparator)) { + cp, ok := s.wsResolveConfined(rel) + if !ok { return "", false } - return abs, true + return cp.realPath, true } // wsRel renders an absolute path back as a workspace-relative path (forward slashes). func (s *Server) wsRel(abs string) string { - base := filepath.Clean(s.m.dir) + base, err := resolveRealRoot(s.m.dir) + if err != nil { + base = filepath.Clean(s.m.dir) + } rel, err := filepath.Rel(base, abs) if err != nil || rel == "." { return "" @@ -57,11 +102,12 @@ type wsEntry struct { // GET /api/workspace/list?path= func (s *Server) wsList(w http.ResponseWriter, r *http.Request) { - abs, ok := s.wsResolve(r.URL.Query().Get("path")) + cp, ok := s.wsResolveConfined(r.URL.Query().Get("path")) if !ok { writeErr(w, 400, "invalid path") return } + abs := cp.realPath fi, err := os.Stat(abs) if err != nil { writeErr(w, 404, "path does not exist") @@ -73,7 +119,7 @@ func (s *Server) wsList(w http.ResponseWriter, r *http.Request) { } ents, err := os.ReadDir(abs) if err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } out := make([]wsEntry, 0, len(ents)) @@ -103,11 +149,12 @@ func (s *Server) wsList(w http.ResponseWriter, r *http.Request) { // GET /api/workspace/read?path= — inline text for view/edit. Binary or oversize // files return {binary:true}/{too_large:true} with no content (use download instead). func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) { - abs, ok := s.wsResolve(r.URL.Query().Get("path")) + cp, ok := s.wsResolveConfined(r.URL.Query().Get("path")) if !ok { writeErr(w, 400, "invalid path") return } + abs := cp.realPath fi, err := os.Stat(abs) if err != nil { writeErr(w, 404, "file does not exist") @@ -123,7 +170,7 @@ func (s *Server) wsRead(w http.ResponseWriter, r *http.Request) { } data, err := os.ReadFile(abs) if err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) { @@ -143,21 +190,22 @@ func (s *Server) wsWrite(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - abs, ok := s.wsResolve(req.Path) - if !ok || abs == filepath.Clean(s.m.dir) { + cp, ok := s.wsResolveConfined(req.Path) + if !ok || cp.realPath == cp.realRoot { writeErr(w, 400, "invalid path") return } + abs := cp.realPath if fi, err := os.Stat(abs); err == nil && fi.IsDir() { writeErr(w, 400, "target is a directory") return } if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } if err := os.WriteFile(abs, []byte(req.Content), 0o644); err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(abs)}) @@ -172,13 +220,14 @@ func (s *Server) wsMkdir(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, err.Error()) return } - abs, ok := s.wsResolve(req.Path) - if !ok || abs == filepath.Clean(s.m.dir) { + cp, ok := s.wsResolveConfined(req.Path) + if !ok || cp.realPath == cp.realRoot { writeErr(w, 400, "invalid path") return } + abs := cp.realPath if err := os.MkdirAll(abs, 0o755); err != nil { - writeErr(w, 500, err.Error()) + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"ok": true, "path": s.wsRel(abs)}) @@ -187,21 +236,21 @@ func (s *Server) wsMkdir(w http.ResponseWriter, r *http.Request) { // DELETE /api/workspace/delete?path= — removes a file or a directory tree // (confined to the work dir; the root itself can't be deleted). func (s *Server) wsDelete(w http.ResponseWriter, r *http.Request) { - abs, ok := s.wsResolve(r.URL.Query().Get("path")) + cp, ok := s.wsResolveConfined(r.URL.Query().Get("path")) if !ok { writeErr(w, 400, "invalid path") return } - if abs == filepath.Clean(s.m.dir) { + if cp.realPath == cp.realRoot { writeErr(w, 400, "cannot delete the workspace root directory") return } - if _, err := os.Stat(abs); err != nil { + if !cp.exists { writeErr(w, 404, "path does not exist") return } - if err := os.RemoveAll(abs); err != nil { - writeErr(w, 500, err.Error()) + if err := os.RemoveAll(cp.entryPath); err != nil { + writeErr(w, 500, safeFSErr(err)) return } writeJSON(w, 200, map[string]any{"ok": true}) @@ -209,17 +258,18 @@ func (s *Server) wsDelete(w http.ResponseWriter, r *http.Request) { // GET /api/workspace/download?path= — stream a file as an attachment. func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) { - abs, ok := s.wsResolve(r.URL.Query().Get("path")) + cp, ok := s.wsResolveConfined(r.URL.Query().Get("path")) if !ok { writeErr(w, 400, "invalid path") return } + abs := cp.realPath fi, err := os.Stat(abs) if err != nil || fi.IsDir() { writeErr(w, 404, "file does not exist") return } - name := filepath.Base(abs) + name := filepath.Base(cp.entryPath) // RFC 5987 filename* keeps non-ASCII names intact; plain filename is the fallback. w.Header().Set("Content-Disposition", "attachment; filename=\""+sanitizeFilename(name)+"\"; filename*=UTF-8''"+url.PathEscape(name)) http.ServeFile(w, r, abs) @@ -227,12 +277,12 @@ func (s *Server) wsDownload(w http.ResponseWriter, r *http.Request) { // POST /api/workspace/upload?path= — multipart form field "file" (one or more). func (s *Server) wsUpload(w http.ResponseWriter, r *http.Request) { - dirAbs, ok := s.wsResolve(r.URL.Query().Get("path")) + dir, ok := s.wsResolveConfined(r.URL.Query().Get("path")) if !ok { writeErr(w, 400, "invalid path") return } - if fi, err := os.Stat(dirAbs); err != nil || !fi.IsDir() { + if fi, err := os.Stat(dir.realPath); err != nil || !fi.IsDir() { writeErr(w, 400, "target directory does not exist") return } @@ -246,18 +296,24 @@ func (s *Server) wsUpload(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, "missing upload file (form field file)") return } + dirRel := s.wsRel(dir.realPath) saved := 0 for _, hdr := range files { name := filepath.Base(hdr.Filename) // strip any path component if name == "" || name == "." || name == ".." { continue } - destAbs, okd := s.wsResolve(filepath.Join(s.wsRel(dirAbs), name)) - if !okd { - continue + destRel := name + if dirRel != "" { + destRel = dirRel + "/" + name } - if err := saveUpload(hdr, destAbs); err != nil { - writeErr(w, 500, err.Error()) + dest, okd := s.wsResolveConfined(destRel) + if !okd || dest.realPath == dest.realRoot { + writeErr(w, 400, "invalid path") + return + } + if err := saveUpload(hdr, dest.realPath); err != nil { + writeErr(w, 500, safeFSErr(err)) return } saved++ diff --git a/server/workspace_deny_test.go b/server/workspace_deny_test.go new file mode 100644 index 0000000..70e08fd --- /dev/null +++ b/server/workspace_deny_test.go @@ -0,0 +1,68 @@ +package server + +import ( + "os" + "path/filepath" + "testing" +) + +func TestWorkspaceDeniesPlatformPaths(t *testing.T) { + dir := t.TempDir() + for _, p := range []string{"traffic/_ca", "traffic/_index", "traffic/host", "other"} { + if err := os.MkdirAll(filepath.Join(dir, p), 0o755); err != nil { + t.Fatal(err) + } + } + key := filepath.Join(dir, "traffic", "_ca", "mitmproxy-ca.pem") + if err := os.WriteFile(key, []byte("key"), 0o600); err != nil { + t.Fatal(err) + } + s := &Server{m: &Manager{dir: dir}} + + for _, rel := range []string{ + "traffic/_ca", + "traffic/_ca/mitmproxy-ca.pem", + "traffic/_index", + "traffic/_index/index.sqlite", + "TRAFFIC/_CA/mitmproxy-ca.pem", + "traffic/_ca.", + "traffic/_ca./mitmproxy-ca.pem", + } { + if _, ok := s.wsResolveConfined(rel); ok { + t.Errorf("%q resolved, want a refusal", rel) + } + } + + for _, rel := range []string{"", "traffic", "traffic/host", "traffic/_caX", "other"} { + if _, ok := s.wsResolveConfined(rel); !ok { + t.Errorf("%q refused, want a resolution", rel) + } + } + + link := filepath.Join(dir, "alias") + if err := os.Symlink(filepath.Join(dir, "traffic", "_ca"), link); err == nil { + if _, ok := s.wsResolveConfined("alias/mitmproxy-ca.pem"); ok { + t.Error("symlink alias to traffic/_ca resolved") + } + } +} + +func TestWorkspacePathDenied(t *testing.T) { + root := filepath.Clean("/data") + for _, tc := range []struct { + path string + want bool + }{ + {"/data/traffic/_ca", true}, + {"/data/traffic/_ca/x", true}, + {"/data/traffic/_index/index.sqlite", true}, + {"/data/traffic/_caX", false}, + {"/data/traffic", false}, + {"/data/other", false}, + {"/elsewhere/traffic/_ca", true}, // outside the root: fail closed + } { + if got := workspacePathDenied(root, filepath.FromSlash(tc.path)); got != tc.want { + t.Errorf("workspacePathDenied(%q) = %v, want %v", tc.path, got, tc.want) + } + } +} diff --git a/traffic/stream.go b/traffic/stream.go index d58c5a0..c70a3bc 100644 --- a/traffic/stream.go +++ b/traffic/stream.go @@ -528,6 +528,37 @@ type StreamMessage struct { // most streamPreview (4 KiB); a longer one lives in the blob store and the row // carries its hash for the rest (traffic_blob, GET /api/traffic/blob). func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]StreamMessage, int, error) { + return t.StreamMessagesByDirection(exchangeID, "", offset, limit) +} + +// ErrBadStreamDirection is returned by StreamMessagesByDirection for a +// direction other than "", "c2s" or "s2c". +var ErrBadStreamDirection = errors.New(`direction must be "c2s", "s2c" or empty`) + +// streamDirectionFilter returns the SQL condition (after exchange_id=?) and its +// argument for a direction filter. A filtered page keeps the 'meta' limit +// marker, so a reader never misses that messages were dropped. +func streamDirectionFilter(direction string) (cond string, args []any, err error) { + switch direction { + case "": + return "", nil, nil + case "c2s", "s2c": + return ` AND direction IN (?, 'meta')`, []any{direction}, nil + default: + return "", nil, ErrBadStreamDirection + } +} + +// StreamMessagesByDirection is StreamMessages restricted to one direction: +// "c2s" (client to server), "s2c" (server to client), or "" for both. total +// counts only the matching rows, so offset pages through the filtered list. +// The 'meta' row (messages dropped past the recorder's limits) is kept in a +// filtered page. Seq stays the message's position in the whole stream. +func (t *Traffic) StreamMessagesByDirection(exchangeID, direction string, offset, limit int) ([]StreamMessage, int, error) { + cond, dirArgs, err := streamDirectionFilter(direction) + if err != nil { + return nil, 0, err + } if limit <= 0 { limit = 50 } @@ -538,11 +569,12 @@ func (t *Traffic) StreamMessages(exchangeID string, offset, limit int) ([]Stream offset = 0 } var total int - if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`, exchangeID).Scan(&total); err != nil { + args := append([]any{exchangeID}, dirArgs...) + if err := t.db.QueryRow(`SELECT COUNT(*) FROM stream_messages WHERE exchange_id=?`+cond, args...).Scan(&total); err != nil { return nil, 0, err } rows, err := t.db.Query(`SELECT seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated -FROM stream_messages WHERE exchange_id=? ORDER BY seq LIMIT ? OFFSET ?`, exchangeID, limit, offset) +FROM stream_messages WHERE exchange_id=?`+cond+` ORDER BY seq LIMIT ? OFFSET ?`, append(args, limit, offset)...) if err != nil { return nil, 0, err } diff --git a/traffic/stream_direction_test.go b/traffic/stream_direction_test.go new file mode 100644 index 0000000..897e6b7 --- /dev/null +++ b/traffic/stream_direction_test.go @@ -0,0 +1,114 @@ +package traffic + +import ( + "errors" + "strings" + "testing" + + "github.com/gorilla/websocket" +) + +// directionStream records c2s "q0","q1",... and s2c "a0","a1",... interleaved +// (q0 a0 q1 a1 ...) on one WebSocket exchange and returns its id. +func directionStream(t *testing.T, pairs int) (*Traffic, string) { + t.Helper() + tr, s, f := unitStream(t, "direction.test") + for i := 0; i < pairs; i++ { + addWS(f, true, websocket.TextMessage, []byte("q"+string(rune('0'+i)))) + addWS(f, false, websocket.TextMessage, []byte("a"+string(rune('0'+i)))) + } + s.WebSocketMessage(f) + s.WebSocketEnd(f) + return tr, onlyExchange(t, tr) +} + +func TestStreamMessagesByDirection(t *testing.T) { + tr, id := directionStream(t, 3) + + all, total, err := tr.StreamMessagesByDirection(id, "", 0, 50) + if err != nil || total != 6 || len(all) != 6 { + t.Fatalf("unfiltered: %d of %d, err %v; want 6 of 6", len(all), total, err) + } + + for _, tc := range []struct { + dir string + payloads []string + seqs []int64 + }{ + {"c2s", []string{"q0", "q1", "q2"}, []int64{1, 3, 5}}, + {"s2c", []string{"a0", "a1", "a2"}, []int64{2, 4, 6}}, + } { + msgs, total, err := tr.StreamMessagesByDirection(id, tc.dir, 0, 50) + if err != nil || total != 3 || len(msgs) != 3 { + t.Fatalf("%s: %d of %d, err %v; want 3 of 3", tc.dir, len(msgs), total, err) + } + for i, m := range msgs { + // Seq stays the position in the whole stream, so a filtered row + // can be matched against the unfiltered conversation. + if m.Direction != tc.dir || m.Payload != tc.payloads[i] || m.Seq != tc.seqs[i] { + t.Fatalf("%s message %d = %+v, want payload %q seq %d", tc.dir, i, m, tc.payloads[i], tc.seqs[i]) + } + } + // offset and total apply to the filtered list. + page, total, err := tr.StreamMessagesByDirection(id, tc.dir, 1, 1) + if err != nil || total != 3 || len(page) != 1 || page[0].Payload != tc.payloads[1] { + t.Fatalf("%s offset=1 limit=1: %+v total %d err %v; want %q", tc.dir, page, total, err, tc.payloads[1]) + } + } + + // StreamMessages is the unfiltered form. + if msgs, total, err := tr.StreamMessages(id, 0, 50); err != nil || total != 6 || len(msgs) != 6 { + t.Fatalf("StreamMessages: %d of %d, err %v", len(msgs), total, err) + } +} + +func TestStreamMessagesByDirectionRejectsUnknown(t *testing.T) { + tr, id := directionStream(t, 1) + for _, dir := range []string{"meta", "both", "C2S", "c2s' OR 1=1 --"} { + if _, _, err := tr.StreamMessagesByDirection(id, dir, 0, 50); !errors.Is(err, ErrBadStreamDirection) { + t.Fatalf("direction %q: err %v, want ErrBadStreamDirection", dir, err) + } + } +} + +// A filtered page keeps the meta row, so dropped messages are never hidden. +func TestStreamMessagesByDirectionKeepsMetaRow(t *testing.T) { + tr, s, f := unitStream(t, "direction-meta.test") + for i := 0; i < maxStreamMessages+4; i++ { + addWS(f, i%2 == 0, websocket.TextMessage, []byte("m")) + } + s.WebSocketMessage(f) + s.WebSocketEnd(f) + id := onlyExchange(t, tr) + + _, total, err := tr.StreamMessagesByDirection(id, "s2c", 0, 1) + if err != nil || total != maxStreamMessages/2+1 { + t.Fatalf("s2c total %d err %v, want %d messages and the meta row", total, err, maxStreamMessages/2+1) + } + last, _, err := tr.StreamMessagesByDirection(id, "s2c", total-1, 1) + if err != nil || len(last) != 1 || last[0].Type != "meta" { + t.Fatalf("last s2c row %+v err %v, want the meta row", last, err) + } +} + +func TestTrafficMessagesToolDirection(t *testing.T) { + tr, id := directionStream(t, 2) + + out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"s2c"}`) + if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"a0"`) || !strings.Contains(out, `"a1"`) || strings.Contains(out, `"q0"`) { + t.Fatalf("s2c output:\n%s", out) + } + out = toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":" C2S "}`) + if !strings.HasPrefix(out, "[messages 1-2 of 2]") || !strings.Contains(out, `"q1"`) || strings.Contains(out, `"a1"`) { + t.Fatalf("c2s output (case and spaces normalized):\n%s", out) + } + if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`"}`); !strings.HasPrefix(out, "[messages 1-4 of 4]") { + t.Fatalf("no direction output:\n%s", out) + } + if out := toolText(t, tr, "traffic_messages", `{"id":"`+id+`","direction":"sideways"}`); !strings.Contains(out, "direction must be") { + t.Fatalf("bad direction output:\n%s", out) + } + if out := toolText(t, tr, "traffic_messages", `{"id":"nope","direction":"c2s"}`); !strings.Contains(out, "No c2s stream messages") { + t.Fatalf("empty filtered output:\n%s", out) + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index b865de5..4c5b65d 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -2353,13 +2353,14 @@ func (t *Traffic) Tools() []actool.CoreTool { messages := actool.Build(actool.Spec{ Name: "traffic_messages", - Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Returns 20 messages by default, at most 50; use offset to page.", + Description: "List the messages of one captured WebSocket or SSE (Server-Sent Events) record in order: direction (c2s client→server, s2c server→client), type (text/binary/event, or meta when the recorder dropped messages past its limits), size and a preview of at most 1KB (binary as hex). A payload stored as a blob carries its hash; read the rest with traffic_blob. Set direction to c2s or s2c to list only one side of the conversation (the meta row is kept). Returns 20 messages by default, at most 50; use offset to page.", Schema: map[string]any{ "type": "object", "properties": map[string]any{ - "id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"}, - "offset": map[string]any{"type": "integer", "description": "number of messages to skip, default 0"}, - "limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"}, + "id": map[string]any{"type": "string", "description": "the record id from traffic_search (a WebSocket status-101 or SSE record)"}, + "direction": map[string]any{"type": "string", "enum": []any{"c2s", "s2c"}, "description": "only messages in this direction: c2s (client→server) or s2c (server→client); omit for both"}, + "offset": map[string]any{"type": "integer", "description": "number of messages to skip within the (filtered) list, default 0"}, + "limit": map[string]any{"type": "integer", "description": "messages to return, default 20, max 50"}, }, "required": []any{"id"}, }, @@ -2367,9 +2368,10 @@ func (t *Traffic) Tools() []actool.CoreTool { Permissions: allow, Run: func(_ context.Context, in json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { var a struct { - ID string - Offset int - Limit int + ID string + Direction string + Offset int + Limit int } _ = json.Unmarshal(in, &a) if strings.TrimSpace(a.ID) == "" { @@ -2384,11 +2386,15 @@ func (t *Traffic) Tools() []actool.CoreTool { if a.Offset < 0 { a.Offset = 0 } - msgs, total, err := t.StreamMessages(a.ID, a.Offset, a.Limit) + a.Direction = strings.ToLower(strings.TrimSpace(a.Direction)) + msgs, total, err := t.StreamMessagesByDirection(a.ID, a.Direction, a.Offset, a.Limit) if err != nil { return actool.Errorf(err.Error()), nil } if total == 0 { + if a.Direction != "" { + return actool.Text(fmt.Sprintf("No %s stream messages recorded for this id (not a WebSocket/SSE record, or no message was sent in that direction).", a.Direction)), nil + } return actool.Text("No stream messages recorded for this id (not a WebSocket/SSE record, or no message was exchanged)."), nil } type liteMsg struct { diff --git a/web/package.json b/web/package.json index 4c823af..f5265be 100644 --- a/web/package.json +++ b/web/package.json @@ -15,7 +15,8 @@ "generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts", "test:polling": "node --test scripts/polling.test.mjs", "test:replay": "node --test scripts/replay.test.mjs", - "test:upload": "node --test scripts/upload.test.mjs" + "test:upload": "node --test scripts/upload.test.mjs", + "test:i18n": "node scripts/check-i18n.mjs" }, "lint-staged": { "*.{js,ts,jsx,tsx}": [ diff --git a/web/scripts/check-i18n.mjs b/web/scripts/check-i18n.mjs new file mode 100644 index 0000000..149308b --- /dev/null +++ b/web/scripts/check-i18n.mjs @@ -0,0 +1,64 @@ +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +// Every literal t("...") / t('...') key must exist in the locale dictionary +// with the same {placeholders}. Dynamic keys (variables, template literals +// with ${}) are skipped: there is nothing to compare them against. +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const dict = JSON.parse(readFileSync(join(root, "src/i18n/locales/tr.json"), "utf8")); + +const files = []; +function walk(dir) { + for (const name of readdirSync(dir)) { + const p = join(dir, name); + const st = statSync(p); + if (st.isDirectory()) walk(p); + else if (/\.(ts|tsx)$/.test(name)) files.push(p); + } +} +walk(join(root, "src")); + +const calls = new Map(); // key -> first file that uses it +const literalCall = /(?:^|[^\w$.])t\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/gm; +for (const file of files) { + const src = readFileSync(file, "utf8"); + for (const m of src.matchAll(literalCall)) { + const key = + m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : m[2].replace(/\\(['\\])/g, "$1"); + if (!calls.has(key)) calls.set(key, file.slice(root.length + 1)); + } +} + +function placeholders(s) { + return [...s.matchAll(/\{(\w+)\}/g)] + .map((m) => m[1]) + .sort() + .join(","); +} + +const missing = []; +const mismatch = []; +for (const [key, file] of calls) { + if (!Object.prototype.hasOwnProperty.call(dict, key)) { + missing.push(`${file}: ${JSON.stringify(key)}`); + continue; + } + if (placeholders(dict[key]) !== placeholders(key)) { + mismatch.push(`${JSON.stringify(key)}: source {${placeholders(key)}} dict {${placeholders(dict[key])}}`); + } +} + +if (missing.length || mismatch.length) { + if (missing.length) { + console.error(`Missing tr.json entries (${missing.length}):\n${missing.join("\n")}`); + } + if (mismatch.length) { + console.error(`Placeholder mismatches (${mismatch.length}):\n${mismatch.join("\n")}`); + } + process.exit(1); +} + +console.log( + `i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} tr.json entries`, +); diff --git a/web/scripts/upload.test.mjs b/web/scripts/upload.test.mjs index 733184e..8826bca 100644 --- a/web/scripts/upload.test.mjs +++ b/web/scripts/upload.test.mjs @@ -21,6 +21,9 @@ function setup(mock = false) { require(name) { if (name === "@/lib/mock/enabled") return { MOCK: mock }; if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") }; + // English passthrough: assertions below match the source (English) messages. + if (name === "@/i18n") + return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m)) }; throw new Error("Unexpected import: " + name); }, FormData: class { diff --git a/web/src/app/(auth)/login/page.tsx b/web/src/app/(auth)/login/page.tsx index 1ec20b3..9d8d4c1 100644 --- a/web/src/app/(auth)/login/page.tsx +++ b/web/src/app/(auth)/login/page.tsx @@ -11,6 +11,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { t } from "@/i18n"; import { api } from "@/lib/api"; import { auth } from "@/lib/auth"; @@ -55,14 +56,14 @@ export default function LoginPage() { .then(({ initialized }) => { if (!initialized) router.replace("/setup"); }) - .catch(() => setError("Unable to connect to the backend service")) + .catch(() => setError(t("Unable to connect to the backend service"))) .finally(() => setChecking(false)); }, [router]); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (!agreed) { - setError("Please read and agree to the Terms of Use first"); + setError(t("Please read and agree to the Terms of Use first")); return; } setLoading(true); @@ -72,7 +73,7 @@ export default function LoginPage() { auth.setToken(token); window.location.replace("/function/tasks"); } catch { - setError("Incorrect username or password"); + setError(t("Incorrect username or password")); } finally { setLoading(false); } @@ -80,12 +81,16 @@ export default function LoginPage() { if (checking) { return ( -
- Checking login state… + // Prerendered in the build-time locale; the reader's locale may differ for this brief state. +
+ {t("Checking login state…")}
); } + // Keep the agreement sentence whole: the link text is placed through a placeholder so the word order can follow the locale. + const [agreeBefore, agreeAfter = ""] = t("I have read and agree to {terms}").split("{terms}"); + return (
{/* Left panel */} @@ -103,22 +108,24 @@ export default function LoginPage() {
-

Sign in

-

Welcome back — enter your password to continue using ARTEX

+

{t("Sign in")}

+

+ {t("Welcome back — enter your password to continue using ARTEX")} +

- +
- + setPassword(e.target.value)} - placeholder="Enter your password" + placeholder={t("Enter your password")} autoFocus autoComplete="current-password" /> @@ -131,19 +138,20 @@ export default function LoginPage() { className="mt-0.5" />
{error &&

{error}

}
@@ -156,9 +164,9 @@ export default function LoginPage() {
- ARTEX Terms of Use and Disclaimer + {t("ARTEX Terms of Use and Disclaimer")}

- Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in + {t("Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in")}

@@ -169,11 +177,14 @@ export default function LoginPage() { className="max-h-[60vh] space-y-5 overflow-y-auto px-6 py-5 text-sm leading-relaxed text-muted-foreground" >

- This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX - project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks. + {t( + 'This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks.', + )} {" "} - Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement. + {t( + "Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement.", + )}

@@ -182,12 +193,12 @@ export default function LoginPage() { 1 - Article 1 · Definitions and Open-Source License + {t("Article 1 · Definitions and Open-Source License")}

- This software (ARTEX) is an open-source program released under the GNU Affero General Public License - v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under - the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file. + {t( + "This software (ARTEX) is an open-source program released under the GNU Affero General Public License v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file.", + )}

@@ -196,10 +207,12 @@ export default function LoginPage() { 2 - Article 2 · Permitted Scope of Use + {t("Article 2 · Permitted Scope of Use")}

- This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf. + {t( + "This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf.", + )}

@@ -209,15 +222,29 @@ export default function LoginPage() { 3 - Article 3 · Prohibited Conduct + {t("Article 3 · Prohibited Conduct")}
  • - Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted; + {t( + "Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted;", + )} +
  • +
  • + {t( + "Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;", + )} +
  • +
  • + {t( + "Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;", + )} +
  • +
  • + {t( + "Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.", + )}
  • -
  • Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;
  • -
  • Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;
  • -
  • Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.
@@ -226,11 +253,12 @@ export default function LoginPage() { 4 - Article 4 · Intellectual Property + {t("Article 4 · Intellectual Property")}

- The copyright and related intellectual property of this software belong to the project authors and contributors, who grant - you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication. + {t( + "The copyright and related intellectual property of this software belong to the project authors and contributors, who grant you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication.", + )}

@@ -239,10 +267,12 @@ export default function LoginPage() { 5 - Article 5 · Data and Privacy + {t("Article 5 · Data and Privacy")}

- This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear. + {t( + "This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear.", + )}

@@ -251,13 +281,17 @@ export default function LoginPage() { 6 - Article 6 · Compliance and Legal Liability + {t("Article 6 · Compliance and Legal Liability")}

- You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction). + {t( + "You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).", + )} {" "} - All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors. + {t( + "All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.", + )}

@@ -267,11 +301,12 @@ export default function LoginPage() { 7 - Article 7 · Disclaimer and Limitation of Liability + {t("Article 7 · Disclaimer and Limitation of Liability")}

- This software is provided on an "AS IS" and "AS - AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software's authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes. + {t( + 'This software is provided on an "AS IS" and "AS AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software\'s authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes.', + )}

@@ -280,17 +315,19 @@ export default function LoginPage() { 8 - Article 8 · Changes to the Terms and Final Interpretation + {t("Article 8 · Changes to the Terms and Final Interpretation")}

- The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect. + {t( + "The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect.", + )}

- {readToEnd ? "You have read all the terms" : "Scroll the terms to the bottom to confirm"} + {readToEnd ? t("You have read all the terms") : t("Scroll the terms to the bottom to confirm")}

diff --git a/web/src/app/(auth)/setup/page.tsx b/web/src/app/(auth)/setup/page.tsx index 0df08a7..152bca3 100644 --- a/web/src/app/(auth)/setup/page.tsx +++ b/web/src/app/(auth)/setup/page.tsx @@ -7,6 +7,7 @@ import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { t } from "@/i18n"; import { api } from "@/lib/api"; import { auth } from "@/lib/auth"; @@ -29,7 +30,7 @@ export default function SetupPage() { if (initialized) router.replace("/login"); }) .catch((err) => { - setError(err instanceof Error ? err.message : "Unable to connect to the backend service"); + setError(err instanceof Error ? err.message : t("Unable to connect to the backend service")); setUnavailable(true); }) .finally(() => setChecking(false)); @@ -38,11 +39,11 @@ export default function SetupPage() { async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (password !== confirm) { - setError("The two passwords do not match"); + setError(t("The two passwords do not match")); return; } if (password.length < 12) { - setError("Password must be at least 12 characters"); + setError(t("Password must be at least 12 characters")); return; } setLoading(true); @@ -52,7 +53,7 @@ export default function SetupPage() { auth.setToken(token); router.replace("/function/tasks"); } catch (err) { - setError(err instanceof Error ? err.message : "Initialization failed"); + setError(err instanceof Error ? err.message : t("Initialization failed")); } finally { setLoading(false); } @@ -77,52 +78,56 @@ export default function SetupPage() {
-

{unavailable ? "Cannot confirm initialization state" : "Set initial password"}

+

{unavailable ? t("Cannot confirm initialization state") : t("Set initial password")}

{unavailable - ? "The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again." - : "First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)"} + ? t( + "The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again.", + ) + : t( + "First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)", + )}

{unavailable ? (
{error &&

{error}

}
) : (
- + setSetupToken(e.target.value)} - placeholder="Printed in the server log at startup" + placeholder={t("Printed in the server log at startup")} autoFocus autoComplete="off" />
- + setPassword(e.target.value)} - placeholder="At least 12 characters" + placeholder={t("At least 12 characters")} autoComplete="new-password" />
- + setConfirm(e.target.value)} - placeholder="Enter the password again" + placeholder={t("Enter the password again")} autoComplete="new-password" />
@@ -132,7 +137,7 @@ export default function SetupPage() { className="w-full" disabled={loading || !setupToken.trim() || !password || !confirm} > - {loading ? "Saving..." : "Set password and sign in"} + {loading ? t("Saving...") : t("Set password and sign in")}
)} diff --git a/web/src/app/(external)/page.tsx b/web/src/app/(external)/page.tsx index bf37db5..5a64de8 100644 --- a/web/src/app/(external)/page.tsx +++ b/web/src/app/(external)/page.tsx @@ -1,6 +1,8 @@ import { redirect } from "next/navigation"; +import { t } from "@/i18n"; + export default function Home() { redirect("/function/tasks"); - return <>Coming Soon; + return <>{t("Coming Soon")}; } diff --git a/web/src/app/(main)/_components/main-content.tsx b/web/src/app/(main)/_components/main-content.tsx index 129f265..05bc8ed 100644 --- a/web/src/app/(main)/_components/main-content.tsx +++ b/web/src/app/(main)/_components/main-content.tsx @@ -9,6 +9,7 @@ import { X } from "lucide-react"; import { Separator } from "@/components/ui/separator"; import { SidebarTrigger } from "@/components/ui/sidebar"; import { useCurrentUser } from "@/hooks/use-current-user"; +import { t } from "@/i18n"; import { api } from "@/lib/api"; import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client"; import { cn } from "@/lib/utils"; @@ -57,11 +58,11 @@ export function MainContent({ children }: { children: ReactNode }) { const updateBanner = latest ? (
- ARTEX {latest} is available. See the release notes. + {t("ARTEX {version} is available. See the release notes.", { version: latest })}
{version && ( - Version · {version} + {t("Version · {version}", { version })} )} diff --git a/web/src/app/(main)/_components/sidebar/account-switcher.tsx b/web/src/app/(main)/_components/sidebar/account-switcher.tsx index 54daaf9..3edc039 100644 --- a/web/src/app/(main)/_components/sidebar/account-switcher.tsx +++ b/web/src/app/(main)/_components/sidebar/account-switcher.tsx @@ -12,6 +12,7 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { t } from "@/i18n"; import { auth } from "@/lib/auth"; import { cn, getInitials } from "@/lib/utils"; @@ -64,7 +65,7 @@ export function AccountSwitcher({
{user.name} - {user.role} + {t(user.role)}
setPwOpen(true)}> - Change password + {t("Change password")} - Sign out + {t("Sign out")} diff --git a/web/src/app/(main)/_components/sidebar/change-password-dialog.tsx b/web/src/app/(main)/_components/sidebar/change-password-dialog.tsx index 5233e84..2d0102f 100644 --- a/web/src/app/(main)/_components/sidebar/change-password-dialog.tsx +++ b/web/src/app/(main)/_components/sidebar/change-password-dialog.tsx @@ -15,6 +15,7 @@ import { } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { t } from "@/i18n"; import { api } from "@/lib/api"; export function ChangePasswordDialog({ @@ -41,37 +42,44 @@ export function ChangePasswordDialog({ function submit(e: React.FormEvent) { e.preventDefault(); if (!oldPassword || !newPassword) { - toast.error("Fill in the current password and the new password"); + toast.error(t("Fill in the current password and the new password")); return; } if (newPassword !== confirmPassword) { - toast.error("The two new passwords do not match"); + toast.error(t("The two new passwords do not match")); return; } setSaving(true); api .changePassword(oldPassword, newPassword) .then(() => { - toast.success("Password changed"); + toast.success(t("Password changed")); onOpenChange(false); }) - .catch((err) => toast.error(`Change failed: ${(err as Error).message}`)) + .catch((err) => toast.error(t("Change failed: {error}", { error: (err as Error).message }))) .finally(() => setSaving(false)); } + // The username stays bold; it is placed through a placeholder so the sentence is translated whole. + const [descBefore, descAfter = ""] = t( + "The username is fixed as {username}. Enter the current password to verify; login tokens issued before the change stay valid until they expire.", + ).split("{username}"); + return (
- Change password + {t("Change password")} - The username is fixed as ARTEX. Enter the current password to verify; login tokens issued before the change stay valid until they expire. + {descBefore} + ARTEX + {descAfter}
- +
- +
- + diff --git a/web/src/app/(main)/_components/sidebar/layout-controls.tsx b/web/src/app/(main)/_components/sidebar/layout-controls.tsx index 28091b4..cc3c2f7 100644 --- a/web/src/app/(main)/_components/sidebar/layout-controls.tsx +++ b/web/src/app/(main)/_components/sidebar/layout-controls.tsx @@ -21,6 +21,7 @@ import { persistPreference } from "@/lib/preferences/preferences-storage"; import { THEME_PRESET_OPTIONS, type ThemeMode, type ThemePreset } from "@/lib/preferences/theme"; import { applyThemePreset } from "@/lib/preferences/theme-utils"; import { usePreferencesStore } from "@/stores/preferences/preferences-provider"; +import { type Locale, LOCALES, locale, setLocale, t } from "@/i18n"; export function LayoutControls() { const themeMode = usePreferencesStore((s) => s.themeMode); @@ -106,15 +107,33 @@ export function LayoutControls() {
-

Preferences

-

Customize your dashboard layout preferences.

+

{t("Preferences")}

+

{t("Customize your dashboard layout preferences.")}

- + + v && setLocale(v as Locale)} + > + {LOCALES.map((l) => ( + + {l.label} + + ))} + +
+ +
+ - + @@ -154,7 +173,7 @@ export function LayoutControls() {
- + - - Light + + {t("Light")} - - Dark + + {t("Dark")} - - System + + {t("System")}
- + - - Centered + + {t("Centered")} - - Full Width + + {t("Full Width")}
- + - - Sticky + + {t("Sticky")} - - Scroll + + {t("Scroll")}
- + - - Inset + + {t("Inset")} - - Sidebar + + {t("Sidebar")} - - Floating + + {t("Floating")}
- + - - Icon + + {t("Icon")} - - OffCanvas + + {t("OffCanvas")}
diff --git a/web/src/app/(main)/_components/sidebar/nav-documents.tsx b/web/src/app/(main)/_components/sidebar/nav-documents.tsx index 730aa4f..bf74086 100644 --- a/web/src/app/(main)/_components/sidebar/nav-documents.tsx +++ b/web/src/app/(main)/_components/sidebar/nav-documents.tsx @@ -18,6 +18,7 @@ import { SidebarMenuItem, useSidebar, } from "@/components/ui/sidebar"; +import { t } from "@/i18n"; export function NavDocuments({ items, @@ -32,7 +33,7 @@ export function NavDocuments({ return ( - Documents + {t("Documents")} {items.map((item) => ( @@ -46,7 +47,7 @@ export function NavDocuments({ - More + {t("More")} - Open + {t("Open")} - Share + {t("Share")} - Delete + {t("Delete")} @@ -74,7 +75,7 @@ export function NavDocuments({ - More + {t("More")} diff --git a/web/src/app/(main)/_components/sidebar/nav-main.tsx b/web/src/app/(main)/_components/sidebar/nav-main.tsx index 2b5125d..e99c835 100644 --- a/web/src/app/(main)/_components/sidebar/nav-main.tsx +++ b/web/src/app/(main)/_components/sidebar/nav-main.tsx @@ -29,6 +29,7 @@ import { SidebarMenuSubItem, useSidebar, } from "@/components/ui/sidebar"; +import { t } from "@/i18n"; import { cn } from "@/lib/utils"; import type { NavBadge, @@ -321,7 +322,7 @@ function NavItemBadge({ badge }: { badge?: NavBadge }) { badge === "soon" && "border-muted-foreground text-muted-foreground", )} > - {badge} + {t(badge)} ); } diff --git a/web/src/app/(main)/_components/sidebar/nav-user.tsx b/web/src/app/(main)/_components/sidebar/nav-user.tsx index 56cbc65..840274c 100644 --- a/web/src/app/(main)/_components/sidebar/nav-user.tsx +++ b/web/src/app/(main)/_components/sidebar/nav-user.tsx @@ -14,6 +14,7 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar"; +import { t } from "@/i18n"; import { auth } from "@/lib/auth"; import { getInitials } from "@/lib/utils"; @@ -79,12 +80,12 @@ export function NavUser({ setPwOpen(true)}> - Change password + {t("Change password")} - Sign out + {t("Sign out")} diff --git a/web/src/app/(main)/_components/sidebar/search-dialog.tsx b/web/src/app/(main)/_components/sidebar/search-dialog.tsx index d07251d..fd8059a 100644 --- a/web/src/app/(main)/_components/sidebar/search-dialog.tsx +++ b/web/src/app/(main)/_components/sidebar/search-dialog.tsx @@ -17,6 +17,7 @@ import { CommandList, CommandSeparator, } from "@/components/ui/command"; +import { t } from "@/i18n"; import type { NavMainItem } from "@/navigation/sidebar/sidebar-items"; import { sidebarItems } from "@/navigation/sidebar/sidebar-items"; @@ -33,7 +34,7 @@ type SearchItem = { const sidebarGroupLabels = new Set(sidebarItems.flatMap((group) => (group.label ? [group.label] : []))); function getSubItemGroup(groupLabel: string | undefined, itemTitle: string) { - return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? "Other") : itemTitle; + return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? t("Other")) : itemTitle; } const searchItems: SearchItem[] = sidebarItems.flatMap((group) => @@ -52,7 +53,7 @@ const searchItems: SearchItem[] = sidebarItems.flatMap((group) => return [ { id: item.id, - group: group.label ?? "Other", + group: group.label ?? t("Other"), label: item.title, url: item.url, icon: item.icon, @@ -138,16 +139,16 @@ export function SearchDialog() { className="px-0! font-normal text-muted-foreground hover:no-underline" > - Search + {t("Search")} ⌘J - + - No results found. + {t("No results found.")} {query ? renderGroups(searchItems) : renderGroups(recommendations)} diff --git a/web/src/app/(main)/_components/sidebar/sidebar-support-card.tsx b/web/src/app/(main)/_components/sidebar/sidebar-support-card.tsx index 5d41598..6b05655 100644 --- a/web/src/app/(main)/_components/sidebar/sidebar-support-card.tsx +++ b/web/src/app/(main)/_components/sidebar/sidebar-support-card.tsx @@ -4,24 +4,27 @@ import { siX } from "simple-icons"; import { SimpleIcon } from "@/components/simple-icon"; import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { t } from "@/i18n"; export function SidebarSupportCard() { + // The X link sits inside the sentence through a placeholder so the word order can follow the locale. + const [before, after = ""] = t("Open an issue or do reach out to me on {x}.").split("{x}"); return ( - Looking for something more? + {t("Looking for something more?")} - Open an issue or do reach out to me on  + {before.trimEnd()}  - . + {after} diff --git a/web/src/app/(main)/_components/sidebar/theme-switcher.tsx b/web/src/app/(main)/_components/sidebar/theme-switcher.tsx index a95a83a..b8217cb 100644 --- a/web/src/app/(main)/_components/sidebar/theme-switcher.tsx +++ b/web/src/app/(main)/_components/sidebar/theme-switcher.tsx @@ -3,11 +3,18 @@ import { Monitor, Moon, Sun } from "lucide-react"; import { Button } from "@/components/ui/button"; +import { t } from "@/i18n"; import { persistPreference } from "@/lib/preferences/preferences-storage"; import { usePreferencesStore } from "@/stores/preferences/preferences-provider"; const THEME_CYCLE = ["light", "dark", "system"] as const; +const THEME_LABELS: Record<(typeof THEME_CYCLE)[number], string> = { + light: t("Light"), + dark: t("Dark"), + system: t("System"), +}; + export function ThemeSwitcher() { const themeMode = usePreferencesStore((s) => s.themeMode); const setThemeMode = usePreferencesStore((s) => s.setThemeMode); @@ -21,7 +28,7 @@ export function ThemeSwitcher() { }; return ( - @@ -234,7 +235,7 @@ function Composer({ variant="ghost" onClick={() => fileInputRef.current?.click()} disabled={disabled || uploading} - title="Upload files" + title={t("Upload files")} > {uploading ? : } @@ -250,14 +251,14 @@ function Composer({ onKeyDown={onKeyDown} /> {running && allowBtw && isBtwCommand(value) && ( - )} {running ? ( // while a run is in flight the send button becomes a stop button — // aborts just this session (the trigger queue keeps going). - ) : ( @@ -265,8 +266,8 @@ function Composer({ size="icon" onClick={onSend} disabled={disabled || (!value.trim() && atts.length === 0)} - title="Send message" - aria-label="Send message" + title={t("Send message")} + aria-label={t("Send message")} > @@ -294,7 +295,11 @@ function LLMProfileRow({ const [open, setOpen] = React.useState(false); const activeDefault = profiles.find((p) => p.is_default); const current = selected != null ? profiles.find((p) => Number(p.id) === selected) : null; - const label = current ? current.name : `Default${activeDefault ? ` (${activeDefault.name})` : ""}`; + const label = current + ? current.name + : activeDefault + ? t("Default ({name})", { name: activeDefault.name }) + : t("Default"); return (
@@ -309,12 +314,12 @@ function LLMProfileRow({ disabled={disabled} className="flex shrink-0 items-center gap-0.5 text-primary text-xs hover:underline disabled:pointer-events-none disabled:opacity-40" > - Change + {t("Change")} -

Select an LLM profile

+

{t("Select an LLM profile")}

{/* default option */} )}
) : ( @@ -1417,7 +1444,7 @@ export default function ChatPage() { disabled={filteredConversations.length === 0} > - Select + {t("Select")}
))} @@ -1430,7 +1457,7 @@ export default function ChatPage() {
{filteredConversations.length === 0 && (

- {agentFilter === null ? "No conversations yet" : "No conversations for this agent"} + {agentFilter === null ? t("No conversations yet") : t("No conversations for this agent")}

)} {pinnedConversations.map((c) => ( @@ -1496,7 +1523,7 @@ export default function ChatPage() { className="mt-1 w-full" onClick={() => setVisibleConversationCount((count) => count + CONVERSATION_LIST_PAGE)} > - Load more + {t("Load more")} )}
@@ -1517,7 +1544,7 @@ export default function ChatPage() { /> ) : sourceRequested ? (
- {convsLoaded ? "The conversation has been deleted" : "Loading the conversation…"} + {convsLoaded ? t("The conversation has been deleted") : t("Loading the conversation…")}
) : ( - Delete {selectedConversationCount} selected conversations? - Conversation messages and execution records will be deleted with them. This action cannot be undone. + + {t("Delete {count} selected conversations?", { count: selectedConversationCount })} + + + {t("Conversation messages and execution records will be deleted with them. This action cannot be undone.")} + - Cancel + {t("Cancel")} {bulkDeleting && } - {bulkDeleting ? "Deleting" : "Confirm delete"} + {bulkDeleting ? t("Deleting") : t("Confirm delete")} diff --git a/web/src/app/(main)/dashboard/page.tsx b/web/src/app/(main)/dashboard/page.tsx index e2dc053..de514cf 100644 --- a/web/src/app/(main)/dashboard/page.tsx +++ b/web/src/app/(main)/dashboard/page.tsx @@ -40,14 +40,15 @@ import type { UsageStats, } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { t } from "@/i18n"; import { setVisibleInterval } from "@/lib/polling"; // ── chart constants ─────────────────────────────────────────────────────────── const dailyTrendConfig = { - input: { label: "Input", color: "hsl(217 91% 60%)" }, - output: { label: "Output", color: "hsl(263 70% 60%)" }, - cacheRead: { label: "Cache read", color: "hsl(160 60% 45%)" }, + input: { label: t("Input"), color: "hsl(217 91% 60%)" }, + output: { label: t("Output"), color: "hsl(263 70% 60%)" }, + cacheRead: { label: t("Cache read"), color: "hsl(160 60% 45%)" }, } satisfies ChartConfig; // ── helpers ────────────────────────────────────────────────────────────────── @@ -56,12 +57,12 @@ function fmtRel(ts?: string | number): string { if (!ts) return "—"; const ms = Date.now() - (typeof ts === "number" ? ts * 1000 : Date.parse(ts as string)); const s = Math.floor(ms / 1000); - if (s < 60) return `${s}s ago`; + if (s < 60) return t("{n}s ago", { n: s }); const m = Math.floor(s / 60); - if (m < 60) return `${m}m ago`; + if (m < 60) return t("{n}m ago", { n: m }); const h = Math.floor(m / 60); - if (h < 24) return `${h}h ago`; - return `${Math.floor(h / 24)}d ago`; + if (h < 24) return t("{n}h ago", { n: h }); + return t("{n}d ago", { n: Math.floor(h / 24) }); } function fmtTokens(n: number): string { @@ -71,12 +72,12 @@ function fmtTokens(n: number): string { } const ASSET_TYPE_LABELS: Record = { - root_domain: "Root domain", + root_domain: t("Root domain"), ip: "IP", - subdomain: "Subdomain", - app: "App", - service: "Service", - endpoint: "Endpoint", + subdomain: t("Subdomain"), + app: t("App"), + service: t("Service"), + endpoint: t("Endpoint"), }; const ASSET_COLORS: Record = { @@ -473,9 +474,9 @@ export default function DashboardPage() { // activity kind label function kindLabel(a: Activity): string { - if (a.kind === "tool_use") return a.tool ?? "tool_use"; - if (a.kind === "tool_result") return "tool_result"; - return a.kind; + if (a.kind === "tool_use") return a.tool ?? t("tool_use"); + if (a.kind === "tool_result") return t("tool_result"); + return t(a.kind); } function workerColor(w: string): string { @@ -497,8 +498,8 @@ export default function DashboardPage() { {/* ── Header ── */}
-

Overview

-

System-wide status · live refresh

+

{t("Overview")}

+

{t("System-wide status · live refresh")}

@@ -508,7 +509,7 @@ export default function DashboardPage() {
- Active tasks + {t("Active tasks")}
{tasksByStatus.running ?? 0} @@ -516,10 +517,16 @@ export default function DashboardPage() {
- {(tasksByStatus.running ?? 0) > 0 && Exploring {tasksByStatus.running}} - {(tasksByStatus.paused ?? 0) > 0 && Paused {tasksByStatus.paused}} - {(tasksByStatus.done ?? 0) > 0 && Completed {tasksByStatus.done}} - {tasks.length === 0 && No tasks} + {(tasksByStatus.running ?? 0) > 0 && ( + {t("Exploring {count}", { count: tasksByStatus.running })} + )} + {(tasksByStatus.paused ?? 0) > 0 && ( + {t("Paused {count}", { count: tasksByStatus.paused })} + )} + {(tasksByStatus.done ?? 0) > 0 && ( + {t("Completed {count}", { count: tasksByStatus.done })} + )} + {tasks.length === 0 && {t("No tasks")}}
@@ -527,15 +534,15 @@ export default function DashboardPage() {
- Confirmed findings + {t("Confirmed findings")}
{findings.length}
- Critical {findingsBySev.critical} - High {findingsBySev.high} - Medium {findingsBySev.medium} - Low {findingsBySev.low} + {t("Critical {count}", { count: findingsBySev.critical })} + {t("High {count}", { count: findingsBySev.high })} + {t("Medium {count}", { count: findingsBySev.medium })} + {t("Low {count}", { count: findingsBySev.low })}
@@ -543,18 +550,18 @@ export default function DashboardPage() {
- Asset nodes + {t("Asset nodes")}
{totalAssets}
- Shared across tasks + {t("Shared across tasks")}
{/* Traffic exchanges */}
- Traffic exchanges + {t("Traffic exchanges")}
{traffic.length}
@@ -562,10 +569,10 @@ export default function DashboardPage() { {settings?.traffic_capture ? ( <> - Recording + {t("Recording")} ) : ( - Capture is off + {t("Capture is off")} )}
@@ -574,15 +581,18 @@ export default function DashboardPage() {
- Token usage + {t("Token usage")}
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
- In {fmtTokens(displayedTokens.input)} (incl. cache {fmtTokens(displayedTokens.cacheRead)}) · Out{" "} - {fmtTokens(displayedTokens.output)} + {t("In {input} (incl. cache {cache}) · Out {output}", { + input: fmtTokens(displayedTokens.input), + cache: fmtTokens(displayedTokens.cacheRead), + output: fmtTokens(displayedTokens.output), + })}
@@ -593,13 +603,13 @@ export default function DashboardPage() {
- LLM token usage + {t("LLM token usage")} {/* Data source toggle: old = activity stats (includes historical tasks), new = the llm_usage metering ledger (more accurate, only covers data since it was enabled) */}
{( [ - { v: "old", label: "Old" }, - { v: "new", label: "New" }, + { v: "old", label: t("Old") }, + { v: "new", label: t("New") }, ] as const ).map(({ v, label }) => ( {llmProfiles.map((p) => { const key = Number(p.id); @@ -667,7 +681,7 @@ export default function DashboardPage() { : "bg-emerald-500/20 text-emerald-400", )} > - Default + {t("Default")} )} @@ -682,11 +696,13 @@ export default function DashboardPage() {
{/* Total */}
-
Total (input+output)
+
{t("Total (input+output)")}
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
-
{displayedTokens.taskCount} tasks
+
+ {t("{count} tasks", { count: displayedTokens.taskCount })} +
{/* Per-type bars */} @@ -696,19 +712,19 @@ export default function DashboardPage() { const total = displayedTokens.input + displayedTokens.output; return [ { - label: "Input (uncached)", + label: t("Input (uncached)"), value: displayedTokens.input - displayedTokens.cacheRead, barColor: dailyTrendConfig.input.color!, text: "text-blue-400", }, { - label: "Cache hits", + label: t("Cache hits"), value: displayedTokens.cacheRead, barColor: dailyTrendConfig.cacheRead.color!, text: "text-emerald-400", }, { - label: "Output", + label: t("Output"), value: displayedTokens.output, barColor: dailyTrendConfig.output.color!, text: "text-violet-400", @@ -740,7 +756,7 @@ export default function DashboardPage() { const hitPct = denominator > 0 ? Math.round((displayedTokens.cacheRead / denominator) * 100) : 0; return (
- Cache hit rate + {t("Cache hit rate")} 50 ? "text-emerald-400" : "text-amber-400")} > @@ -768,11 +784,11 @@ export default function DashboardPage() {
{( [ - { days: 7, label: "7d" }, - { days: 30, label: "30d" }, - { days: 90, label: "3mo" }, - { days: 180, label: "6mo" }, - { days: 365, label: "1y" }, + { days: 7, label: t("7d") }, + { days: 30, label: t("30d") }, + { days: 90, label: t("3mo") }, + { days: 180, label: t("6mo") }, + { days: 365, label: t("1y") }, ] as const ).map(({ days, label }) => (
) : ( @@ -852,17 +868,17 @@ export default function DashboardPage() {
- Activity feed + {t("Activity feed")}
- {activity.filter((a) => a.kind !== "usage").length} events + {t("{count} events", { count: activity.filter((a) => a.kind !== "usage").length })} - View tasks + {t("View tasks")}
@@ -873,7 +889,7 @@ export default function DashboardPage() { if (count === 0) return null; return ( - {kind} {count} + {t(kind)} {count} ); })} @@ -881,7 +897,7 @@ export default function DashboardPage() {
{recentActivity.length === 0 ? ( -
No activity records
+
{t("No activity records")}
) : ( recentActivity.map((a) => (
@@ -899,7 +915,7 @@ export default function DashboardPage() {
- {a.kind} + {t(a.kind)}
{fmtRel(a.ts)}
@@ -914,19 +930,19 @@ export default function DashboardPage() {
- Findings + {t("Findings")}
- All + {t("All")}
{recentFindings.length === 0 ? ( -
No findings
+
{t("No findings")}
) : ( recentFindings.map((f) => (
@@ -959,15 +975,15 @@ export default function DashboardPage() {
- Tasks + {t("Tasks")}
- {tasks.length} tasks + {t("{count} tasks", { count: tasks.length })} - All + {t("All")}
@@ -979,7 +995,7 @@ export default function DashboardPage() { key={h} className="px-4 py-2 text-left text-[9px] font-semibold uppercase tracking-widest text-muted-foreground first:pl-4" > - {h} + {t(h)} ))} @@ -988,7 +1004,7 @@ export default function DashboardPage() { {sortedTasks.length === 0 ? ( - No tasks + {t("No tasks")} ) : ( @@ -1046,12 +1062,12 @@ export default function DashboardPage() {
{/* Asset distribution */} - - Asset distribution + + {t("Asset distribution")} {assetByType.length === 0 ? ( -
No asset data
+
{t("No asset data")}
) : (
{assetByType.map(([type, count]) => ( @@ -1071,18 +1087,20 @@ export default function DashboardPage() {
)} -
{totalAssets} nodes in total
+
+ {t("{count} nodes in total", { count: totalAssets })} +
{/* Traffic status codes */} - - Traffic status codes + + {t("Traffic status codes")} {/* bar chart */} {trafficByCodes.length === 0 ? ( -
No traffic data
+
{t("No traffic data")}
) : ( <>
@@ -1099,7 +1117,7 @@ export default function DashboardPage() {
-
Recent requests
+
{t("Recent requests")}
{recentTraffic.map((e) => (
@@ -1128,11 +1146,11 @@ export default function DashboardPage() { {/* System status & pending approvals */} - System status + {t("System status")}
-
LLM config
+
{t("LLM config")}
- {stats?.llm_configured ? "Configured" : "Not configured"} + {stats?.llm_configured ? t("Configured") : t("Not configured")}
-
Traffic capture
+
{t("Traffic capture")}
- {settings?.traffic_capture ? "On" : "Off"} + {settings?.traffic_capture ? t("On") : t("Off")}
{activeProfile && (
-
Active model
+
{t("Active model")}
{activeProfile.model}
)} @@ -1172,7 +1190,9 @@ export default function DashboardPage() { {/* pending approvals */} {pendingCount > 0 && (
-
Pending approvals ({pendingCount})
+
+ {t("Pending approvals ({count})", { count: pendingCount })} +
{pending.slice(0, 3).map((p) => ( - {pendingCount - 3} more… + {t("{count} more…", { count: pendingCount - 3 })} )}
@@ -1202,7 +1222,7 @@ export default function DashboardPage() { {pendingCount === 0 && (
- No pending interception approvals + {t("No pending interception approvals")}
)} diff --git a/web/src/app/(main)/function/assets/page.tsx b/web/src/app/(main)/function/assets/page.tsx index 6d70f91..bbbe6f9 100644 --- a/web/src/app/(main)/function/assets/page.tsx +++ b/web/src/app/(main)/function/assets/page.tsx @@ -63,6 +63,7 @@ import { parseCompanyScopeText } from "@/lib/company-scope"; import { httpHref } from "@/lib/http-href"; import type { Asset, Company, CompanyScopeRule } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { t } from "@/i18n"; const METHOD_COLOR: Record = { GET: "bg-emerald-100 text-emerald-700", @@ -99,13 +100,13 @@ function statusTone(code: number) { const PAGE_SIZES = [25, 50, 100, 200]; const TABS: { key: string; label: string; icon: LucideIcon }[] = [ - { key: "company", label: "Companies", icon: BuildingIcon }, - { key: "root_domain", label: "Root domains", icon: GlobeIcon }, + { key: "company", label: t("Companies"), icon: BuildingIcon }, + { key: "root_domain", label: t("Root domains"), icon: GlobeIcon }, { key: "ip", label: "IP", icon: NetworkIcon }, - { key: "subdomain", label: "Subdomains", icon: GlobeIcon }, - { key: "app", label: "Apps", icon: SmartphoneIcon }, - { key: "service", label: "Services", icon: LayoutTemplateIcon }, - { key: "endpoint", label: "Endpoints", icon: LinkIcon }, + { key: "subdomain", label: t("Subdomains"), icon: GlobeIcon }, + { key: "app", label: t("Apps"), icon: SmartphoneIcon }, + { key: "service", label: t("Services"), icon: LayoutTemplateIcon }, + { key: "endpoint", label: t("Endpoints"), icon: LinkIcon }, ]; export default function AssetsPage() { @@ -193,11 +194,11 @@ export default function AssetsPage() { setDeleting(true); try { const res = await api.deleteAssets(deleteIds); - toast.success(`Deleted ${res.deleted} assets`); + toast.success(t("Deleted {count} assets", { count: res.deleted })); setSelected(new Set()); refresh(); } catch (e) { - toast.error("Delete failed: " + String((e as Error)?.message ?? e)); + toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { setDeleting(false); setDeleteOpen(false); @@ -211,12 +212,12 @@ export default function AssetsPage() { const res = await api.deleteCompany(companyDeleteTarget.id, companyDeleteAssets); const msg = companyDeleteAssets && res.assets_deleted > 0 - ? `Company deleted, along with ${res.assets_deleted} assets` - : "Company deleted"; + ? t("Company deleted, along with {count} assets", { count: res.assets_deleted }) + : t("Company deleted"); toast.success(msg); refresh(); } catch (e) { - toast.error("Delete failed: " + String((e as Error)?.message ?? e)); + toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { setCompanyDeleting(false); setCompanyDeleteTarget(null); @@ -317,19 +318,19 @@ export default function AssetsPage() {
-

Assets

+

{t("Assets")}

- - {totalAssets} assets in total + + {t("{count} assets in total", { count: totalAssets })} {selected.size > 0 && ( )}
@@ -355,10 +356,10 @@ export default function AssetsPage() { - Company - Assets - Asset scope - Actions + {t("Company")} + {t("Assets")} + {t("Asset scope")} + {t("Actions")} @@ -381,7 +382,7 @@ export default function AssetsPage() { ))} ) : ( - No scope set + {t("No scope set")} )} @@ -396,7 +397,7 @@ export default function AssetsPage() { setCompanyDeleteTarget(c); setCompanyDeleteAssets(false); }} - aria-label={`Delete company ${c.name}`} + aria-label={t("Delete company {name}", { name: c.name })} > @@ -407,7 +408,9 @@ export default function AssetsPage() { {companies.length === 0 && ( - No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets. + {t( + 'No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets.', + )} )} @@ -440,7 +443,7 @@ export default function AssetsPage() { {a.domain} {a.icp || "—"} - {companyName(a.company_id) || Unassigned} + {companyName(a.company_id) || {t("Unassigned")}} @@ -495,7 +498,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => openDelete([a.id])} - aria-label={`Delete asset ${a.ip || a.id}`} + aria-label={t("Delete asset {name}", { name: a.ip || a.id })} > @@ -537,7 +540,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => openDelete([a.id])} - aria-label={`Delete asset ${a.domain || a.id}`} + aria-label={t("Delete asset {name}", { name: a.domain || a.id })} > @@ -577,7 +580,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => openDelete([a.id])} - aria-label={`Delete asset ${a.app_name || a.id}`} + aria-label={t("Delete asset {name}", { name: a.app_name || a.id })} > @@ -657,7 +660,7 @@ export default function AssetsPage() { ) : ( (a.auth ?? []).map((authItem, i) => { const item = authItem as Record; - const label = item.type || item.username || "Auth"; + const label = item.type || item.username || t("Auth"); return ( @@ -673,7 +676,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => openDelete([a.id])} - aria-label={`Delete asset ${a.url || a.id}`} + aria-label={t("Delete asset {name}", { name: a.url || a.id })} > @@ -725,7 +728,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => openDelete([a.id])} - aria-label={`Delete asset ${a.url || a.id}`} + aria-label={t("Delete asset {name}", { name: a.url || a.id })} > @@ -739,14 +742,15 @@ export default function AssetsPage() { - Confirm delete + {t("Confirm delete")} - This will permanently delete {deleteIds.length}{" "} - asset records. This action cannot be undone. + {t("This will permanently delete {count} asset records. This action cannot be undone.", { + count: deleteIds.length, + })} - Cancel + {t("Cancel")} { e.preventDefault(); @@ -755,7 +759,7 @@ export default function AssetsPage() { disabled={deleting} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > - {deleting ? "Deleting…" : "Confirm delete"} + {deleting ? t("Deleting…") : t("Confirm delete")} @@ -772,10 +776,14 @@ export default function AssetsPage() { > - Delete company · {companyDeleteTarget?.name} + {t("Delete company · {name}", { name: companyDeleteTarget?.name ?? "" })}
-

This will permanently delete the company and its asset scope configuration. This action cannot be undone.

+

+ {t( + "This will permanently delete the company and its asset scope configuration. This action cannot be undone.", + )} +

- Cancel + {t("Cancel")} { e.preventDefault(); @@ -803,7 +813,7 @@ export default function AssetsPage() { disabled={companyDeleting} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > - {companyDeleting ? "Deleting…" : "Confirm delete"} + {companyDeleting ? t("Deleting…") : t("Confirm delete")}
@@ -861,7 +871,7 @@ function AssetCard({ /> ) : ( - {c} + {c && t(c)} ), )} @@ -872,7 +882,7 @@ function AssetCard({ ) : ( - {loaded ? "No data." : "Loading…"} + {loaded ? t("No data.") : t("Loading…")} )} @@ -889,7 +899,7 @@ function AssetCard({ {PAGE_SIZES.map((n) => ( - {n} / page + {t("{count} / page", { count: n })} ))} @@ -989,11 +999,11 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) { const submit = async () => { if (!name.trim()) { - toast.error("Please enter a company name"); + toast.error(t("Please enter a company name")); return; } if (parsedScope.errors.length > 0) { - toast.error("Please fix the invalid asset scope"); + toast.error(t("Please fix the invalid asset scope")); return; } setBusy(true); @@ -1001,14 +1011,15 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) { const res = await api.createCompany(name.trim(), parsedScope.rules); const added = res.scope_added ?? 0; const invalid = res.scope_invalid ?? 0; - if (invalid > 0) toast.warning(`Company created, ${added} scopes added; ${invalid} invalid lines`); - else toast.success(`Company created, ${added} scopes added`); + if (invalid > 0) + toast.warning(t("Company created, {added} scopes added; {invalid} invalid lines", { added, invalid })); + else toast.success(t("Company created, {added} scopes added", { added })); setOpen(false); onSaved(); } catch (e) { const msg = String((e as Error)?.message ?? e); - if (/:\s*409$/.test(msg)) toast.error("Company already exists; try a different name"); - else toast.error(`Save failed: ${msg}`); + if (/:\s*409$/.test(msg)) toast.error(t("Company already exists; try a different name")); + else toast.error(t("Save failed: {error}", { error: msg })); } finally { setBusy(false); } @@ -1018,21 +1029,25 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) { - Add company - Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets. + {t("Add company")} + + {t( + "Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets.", + )} +
- Company name + {t("Company name")} setName(e.target.value)} /> @@ -1042,10 +1057,10 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
@@ -1073,20 +1088,20 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () = const submit = async () => { if (parsedScope.errors.length > 0) { - toast.error("Please fix the invalid asset scope"); + toast.error(t("Please fix the invalid asset scope")); return; } setBusy(true); try { const res = await api.updateCompanyScope(company.id, parsedScope.rules, reason); const errCount = res.invalid ?? 0; - if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`); - else toast.success(`Scope updated, ${res.added} entries in total`); + if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount })); + else toast.success(t("Scope updated, {count} entries in total", { count: res.added })); showScopeWarnings(res.warnings); setOpen(false); onSaved(); } catch (e) { - toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`); + toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { setBusy(false); } @@ -1096,14 +1111,16 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () = - Edit asset scope · {company.name} + {t("Edit asset scope · {name}", { name: company.name })} - Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints. + {t( + "Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints.", + )} @@ -1114,10 +1131,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () = parsed={parsedScope} /> - Attribution basis (optional) + {t("Attribution basis (optional)")} setReason(e.target.value)} /> @@ -1125,10 +1142,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () = @@ -1152,24 +1169,24 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: () const submit = async () => { if (parsedScope.rules.length === 0) { - toast.error("Please enter the scopes to append"); + toast.error(t("Please enter the scopes to append")); return; } if (parsedScope.errors.length > 0) { - toast.error("Please fix the invalid asset scope"); + toast.error(t("Please fix the invalid asset scope")); return; } setBusy(true); try { const res = await api.addCompanyScope(company.id, parsedScope.rules, reason); const errCount = res.invalid ?? 0; - if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`); - else toast.success(`Appended ${res.added} scopes`); + if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount })); + else toast.success(t("Appended {count} scopes", { count: res.added })); showScopeWarnings(res.warnings); setOpen(false); onSaved(); } catch (e) { - toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`); + toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { setBusy(false); } @@ -1179,13 +1196,17 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: () - Append asset scope · {company.name} - New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints. + {t("Append asset scope · {name}", { name: company.name })} + + {t( + "New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints.", + )} + - Attribution basis (optional) + {t("Attribution basis (optional)")} setReason(e.target.value)} /> @@ -1206,10 +1227,10 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: () diff --git a/web/src/app/(main)/function/commands/page.tsx b/web/src/app/(main)/function/commands/page.tsx index e12a06e..9f7d7c2 100644 --- a/web/src/app/(main)/function/commands/page.tsx +++ b/web/src/app/(main)/function/commands/page.tsx @@ -15,9 +15,10 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { api } from "@/lib/api"; import type { CommandRecord, ToolStat } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { intlLocale, t } from "@/i18n"; function fmtTime(ts: string) { - return new Date(ts).toLocaleString("zh-CN", { + return new Date(ts).toLocaleString(intlLocale, { month: "2-digit", day: "2-digit", hour: "2-digit", @@ -130,7 +131,7 @@ export default function CommandsPage() {
-

Tool executions

+

{t("Tool executions")}

{total}
@@ -140,14 +141,14 @@ export default function CommandsPage() {
setQuery(e.target.value)} className="h-8 pl-8" />
setTaskFilter(e.target.value.replace(/\D/g, ""))} @@ -159,7 +160,7 @@ export default function CommandsPage() { {PAGE_SIZES.map((n) => ( - {n} / page + {t("{count} / page", { count: n })} ))} @@ -167,7 +168,7 @@ export default function CommandsPage() {
@@ -205,12 +206,12 @@ export default function CommandsPage() {
- Time - Task - Worker - Tool - Input - Status + {t("Time")} + {t("Task")} + {t("Worker")} + {t("Tool")} + {t("Input")} + {t("Status")} @@ -223,7 +224,7 @@ export default function CommandsPage() { ) : commands.length === 0 ? ( - No tool execution records yet + {t("No tool execution records yet")} ) : ( @@ -255,11 +256,11 @@ export default function CommandsPage() { {cmd.is_error ? ( - Failed + {t("Failed")} ) : ( - Success + {t("Success")} )} @@ -276,21 +277,20 @@ export default function CommandsPage() { - Tool call stats + {t("Tool call stats")} - {taskFilter || queryQ ? "All records under the current filters" : "All tool execution records"} + {taskFilter || queryQ ? t("All records under the current filters") : t("All tool execution records")} {stats.length > 0 && ( - <> + {" · "} - {stats.length} tools ·{" "} - {statsTotal} calls + {t("{tools} tools · {calls} calls", { tools: stats.length, calls: statsTotal })} {statsErrors > 0 && ( <> - {" · Failed "} - {statsErrors} + {" · "} + {t("Failed {count}", { count: statsErrors })} )} - + )} @@ -300,7 +300,7 @@ export default function CommandsPage() { ) : stats.length === 0 ? ( -
No stats data
+
{t("No stats data")}
) : (
{stats.map((s) => ( @@ -309,7 +309,9 @@ export default function CommandsPage() {
{s.tool} {s.errors > 0 && ( - Failed {s.errors} + + {t("Failed {count}", { count: s.errors })} + )}
@@ -337,7 +339,7 @@ export default function CommandsPage() { {selected && ( <> - Tool execution details + {t("Tool execution details")} {fmtTime(selected.created_at)}
@@ -351,18 +353,18 @@ export default function CommandsPage() { {selected.is_error ? ( - Failed + {t("Failed")} ) : ( - Success + {t("Success")} )}
-
Input
+
{t("Input")}
                       {toolInput(selected.command)}
@@ -370,7 +372,7 @@ export default function CommandsPage() {
                   
-
Output
+
{t("Output")}
-                      {selected.output || "(empty)"}
+                      {selected.output || t("(empty)")}
                     
diff --git a/web/src/app/(main)/function/findings/_components/asset-tree.tsx b/web/src/app/(main)/function/findings/_components/asset-tree.tsx index 13f636e..13433e0 100644 --- a/web/src/app/(main)/function/findings/_components/asset-tree.tsx +++ b/web/src/app/(main)/function/findings/_components/asset-tree.tsx @@ -20,6 +20,7 @@ import { Button } from "@/components/ui/button"; import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group"; import type { FindingAssetKind, FindingAssetNode } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { t } from "@/i18n"; // Icons reuse the assets page's type mapping, so the same asset kind looks the same in both places. const KIND_ICON: Record = { @@ -34,14 +35,14 @@ const KIND_ICON: Record = { }; const KIND_LABEL: Record = { - company: "Company", - root_domain: "Root domain", - subdomain: "Subdomain", + company: t("Company"), + root_domain: t("Root domain"), + subdomain: t("Subdomain"), ip: "IP", - app: "App", - service: "Service", - endpoint: "Endpoint", - none: "Unlinked", + app: t("App"), + service: t("Service"), + endpoint: t("Endpoint"), + none: t("Unlinked"), }; // TreeNode is the tree assembled from the node array. The backend already sorts by "most findings under the same parent first", @@ -233,9 +234,9 @@ export function AssetTree({ [isExpanded], ); - let emptyHint = "No findings are linked to assets under the current filters."; - if (loading) emptyHint = "Loading…"; - else if (searching) emptyHint = "No matching assets."; + let emptyHint = t("No findings are linked to assets under the current filters."); + if (loading) emptyHint = t("Loading…"); + else if (searching) emptyHint = t("No matching assets."); const rows: React.ReactNode[] = []; const pushRows = (list: TreeNode[]) => { @@ -264,8 +265,8 @@ export function AssetTree({ type="search" value={keyword} onChange={(event) => setKeyword(event.target.value)} - placeholder="Filter assets" - aria-label="Filter assets" + placeholder={t("Filter assets")} + aria-label={t("Filter assets")} />
@@ -343,7 +346,7 @@ function AssetTreeRow({ type="button" onClick={onToggle} className="flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground" - aria-label={open ? "Collapse" : "Expand"} + aria-label={open ? t("Collapse") : t("Expand")} aria-expanded={open} > @@ -362,16 +365,16 @@ function AssetTreeRow({ {node.critical > 0 && ( - + {node.critical} )} {node.high > 0 && ( - + {node.high} )} - + {node.total} diff --git a/web/src/app/(main)/function/findings/_components/findings-table.tsx b/web/src/app/(main)/function/findings/_components/findings-table.tsx index 56b7b5b..7eab950 100644 --- a/web/src/app/(main)/function/findings/_components/findings-table.tsx +++ b/web/src/app/(main)/function/findings/_components/findings-table.tsx @@ -46,6 +46,7 @@ import type { VerificationStatus, } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { intlLocale, t } from "@/i18n"; export const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"]; @@ -78,11 +79,11 @@ export const FINDING_REPORT_STATES: FindingReportState[] = [ ]; export const REPORT_STATE_META: Record = { - none: { label: "Not submitted", tone: "slate" }, - submitted: { label: "Submitted", tone: "amber" }, - accepted: { label: "Accepted", tone: "green" }, - rejected: { label: "Rejected", tone: "red" }, - duplicate: { label: "Duplicate report", tone: "neutral" }, + none: { label: t("Not submitted"), tone: "slate" }, + submitted: { label: t("Submitted"), tone: "amber" }, + accepted: { label: t("Accepted"), tone: "green" }, + rejected: { label: t("Rejected"), tone: "red" }, + duplicate: { label: t("Duplicate report"), tone: "neutral" }, }; export function ReportStateBadge({ state }: { state?: FindingReportState }) { @@ -102,11 +103,11 @@ export function ReportStateBadge({ state }: { state?: FindingReportState }) { // Verification outcome → label/tone, on the same tone tokens StatusBadge uses. export const VERIFICATION_META: Record = { - verified: { label: "Verified", tone: "green" }, - unverified: { label: "Unverified", tone: "slate" }, - blocked: { label: "Blocked", tone: "amber" }, - not_assessed: { label: "Not assessed", tone: "red" }, - false_positive: { label: "False positive", tone: "neutral" }, + verified: { label: t("Verified"), tone: "green" }, + unverified: { label: t("Unverified"), tone: "slate" }, + blocked: { label: t("Blocked"), tone: "amber" }, + not_assessed: { label: t("Not assessed"), tone: "red" }, + false_positive: { label: t("False positive"), tone: "neutral" }, }; // VerificationBadge shows the automated verification outcome ("Verified L3" when a @@ -155,7 +156,7 @@ export function isSameFinding(left: Finding, right: Finding): boolean { } export function fmtTime(ts: string) { - return new Date(ts).toLocaleString("zh-CN", { + return new Date(ts).toLocaleString(intlLocale, { month: "2-digit", day: "2-digit", hour: "2-digit", @@ -208,7 +209,7 @@ export function FindingsTable({ activeRetests, onDeepen, onDelete, - selectAllLabel = "Select all on this page", + selectAllLabel = t("Select all on this page"), }: FindingsTableProps) { const selectableIds = items.map((finding) => finding.finding_id).filter((id): id is string => Boolean(id)); const selectedCount = selectableIds.filter((id) => selectedIds.has(id)).length; @@ -232,14 +233,14 @@ export function FindingsTable({ /> - Severity - Vulnerability - Asset - Status - Report - Task - Time - Actions + {t("Severity")} + {t("Vulnerability")} + {t("Asset")} + {t("Status")} + {t("Report")} + {t("Task")} + {t("Time")} + {t("Actions")} @@ -266,7 +267,7 @@ export function FindingsTable({ onToggleSelected(f.finding_id as string, c === true)} - aria-label="Select this vulnerability" + aria-label={t("Select this vulnerability")} /> )} @@ -285,16 +286,16 @@ export function FindingsTable({ href={`/function/findings/detail?id=${f.finding_id}`} onClick={(e) => e.stopPropagation()} className="truncate font-medium hover:text-primary hover:underline" - title="View finding details" + title={t("View finding details")} > - {f.name || f.vulnclass || "Uncategorized"} + {f.name || f.vulnclass || t("Uncategorized")} ) : ( - {f.name || f.vulnclass || "Uncategorized"} + {f.name || f.vulnclass || t("Uncategorized")} )} {f.summary}
- Traffic evidence: {f.traffic_count ?? 0} + {t("Traffic evidence: {count}", { count: f.traffic_count ?? 0 })}
@@ -378,22 +379,27 @@ export function FindingsTable({
{retest ? ( ) : null} {!retest && f.finding_id && !f.inherited ? ( - ) : null} {f.finding_id && f.task_id && ( )} {f.finding_id && ( @@ -403,25 +409,24 @@ export function FindingsTable({ size="icon" variant="ghost" className="size-7 text-muted-foreground hover:text-destructive" - aria-label="Delete vulnerability" + aria-label={t("Delete vulnerability")} > - Delete this vulnerability? - - " - - {f.name || f.vulnclass || f.summary || `#${f.finding_id}`} - - " will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone. + {t("Delete this vulnerability?")} + + {t( + '"{name}" will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone.', + { name: f.name || f.vulnclass || f.summary || `#${f.finding_id}` }, + )} - Cancel - onDelete(f)}>Delete + {t("Cancel")} + onDelete(f)}>{t("Delete")} @@ -439,23 +444,23 @@ export function FindingsTable({ {f.finding_id && edit && (
- + onEditChange((s) => (s ? { ...s, name: e.target.value } : s))} - placeholder="Readable title; falls back to category when empty" + placeholder={t("Readable title; falls back to category when empty")} />
- + onEditChange((s) => (s ? { ...s, vulnclass: e.target.value } : s))} - placeholder="e.g. SQL Injection" + placeholder={t("e.g. SQL Injection")} />
- +
)}
- Evidence + {t("Evidence")} {f.vulnclass && ( - · Type: + · {t("Type:")} {f.vulnclass} )} {f.param_id && {f.param_id}} {f.assets && f.assets.length > 0 && ( - · Assets: + · {t("Assets:")} {f.assets.map((a) => ( {a.label} @@ -508,12 +513,12 @@ export function FindingsTable({
- Detailed report + {t("Detailed report")} {reports[rowKey]?.status === "done" && reports[rowKey]?.text.trim() && ( @@ -522,11 +527,11 @@ export function FindingsTable({ {(() => { const rep = reports[rowKey]; if (!rep || rep.status === "loading") - return

Loading…

; + return

{t("Loading…")}

; if (rep.status === "error") - return

Failed to load the report.

; + return

{t("Failed to load the report.")}

; if (!rep.text.trim()) - return

No detailed report yet.

; + return

{t("No detailed report yet.")}

; return ( // break-words inherits into paragraphs/lists; pre additionally gets // whitespace-pre-wrap so code blocks wrap too — otherwise long code lines/URLs @@ -548,7 +553,7 @@ export function FindingsTable({ {items.length === 0 && ( - No matching findings. + {t("No matching findings.")} )} diff --git a/web/src/app/(main)/function/findings/detail/lineage.tsx b/web/src/app/(main)/function/findings/detail/lineage.tsx index 97b4438..982e12b 100644 --- a/web/src/app/(main)/function/findings/detail/lineage.tsx +++ b/web/src/app/(main)/function/findings/detail/lineage.tsx @@ -5,6 +5,7 @@ import * as React from "react"; import { ExplorationGraph } from "@/components/exploration-graph"; import { api } from "@/lib/api"; import type { Edge, TaskNode } from "@/lib/types"; +import { t } from "@/i18n"; // FindingLineageView renders the exploration sub-graph from the task's initial // node down to this finding's node — the same exploration graph canvas as the task graph, @@ -35,7 +36,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) { if (loaded && nodes.length === 0) { return (

- No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted). + {t("No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted).")}

); } @@ -45,7 +46,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) { nodes={nodes} edges={edges} className="h-[68vh]" - emptyHint={loaded ? "No lineage" : "Loading…"} + emptyHint={loaded ? t("No lineage") : t("Loading…")} /> ); } diff --git a/web/src/app/(main)/function/findings/detail/page.tsx b/web/src/app/(main)/function/findings/detail/page.tsx index d33e516..2950054 100644 --- a/web/src/app/(main)/function/findings/detail/page.tsx +++ b/web/src/app/(main)/function/findings/detail/page.tsx @@ -24,6 +24,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { api } from "@/lib/api"; import { statusMeta } from "@/lib/status"; import type { Finding, FindingReportState, FindingStatus, Severity } from "@/lib/types"; +import { intlLocale, t } from "@/i18n"; import { FINDING_REPORT_STATES, @@ -47,7 +48,7 @@ const FINDING_STATUSES: FindingStatus[] = [ ]; function fmtTime(ts: string) { - return new Date(ts).toLocaleString("zh-CN"); + return new Date(ts).toLocaleString(intlLocale); } // FieldRow is one label/value line in the right-hand status panel. @@ -91,10 +92,10 @@ function FindingDetailInner() { try { const updated = await api.setFindingSeverity(id, next); setFinding(updated); - toast.success(`Severity changed to "${statusMeta("severity", next).label}"`); + toast.success(t('Severity changed to "{label}"', { label: statusMeta("severity", next).label })); } catch (e) { setFinding((cur) => (cur ? { ...cur, severity: prev } : cur)); - toast.error("Update failed: " + (e as Error).message); + toast.error(t("Update failed: {error}", { error: (e as Error).message })); } }, [finding, id], @@ -108,10 +109,10 @@ function FindingDetailInner() { try { const updated = await api.setFindingStatus(id, next); setFinding(updated); - toast.success(`Status changed to "${statusMeta("finding", next).label}"`); + toast.success(t('Status changed to "{label}"', { label: statusMeta("finding", next).label })); } catch (e) { setFinding((cur) => (cur ? { ...cur, status: prev } : cur)); - toast.error("Update failed: " + (e as Error).message); + toast.error(t("Update failed: {error}", { error: (e as Error).message })); } }, [finding, id], @@ -125,10 +126,10 @@ function FindingDetailInner() { try { const updated = await api.setFindingReportState(id, next); setFinding(updated); - toast.success(`Report stage changed to "${REPORT_STATE_META[next].label}"`); + toast.success(t('Report stage changed to "{label}"', { label: REPORT_STATE_META[next].label })); } catch (e) { setFinding((cur) => (cur ? { ...cur, report_state: prev } : cur)); - toast.error("Update failed: " + (e as Error).message); + toast.error(t("Update failed: {error}", { error: (e as Error).message })); } }, [finding, id], @@ -137,11 +138,11 @@ function FindingDetailInner() { if (!finding) { return (
-

{loaded ? `Finding ${id} not found` : "Loading…"}

+

{loaded ? t("Finding {id} not found", { id }) : t("Loading…")}

{loaded && ( )} @@ -149,7 +150,7 @@ function FindingDetailInner() { ); } - const title = finding.name || finding.vulnclass || "Uncategorized"; + const title = finding.name || finding.vulnclass || t("Uncategorized"); return ( @@ -173,12 +174,12 @@ function FindingDetailInner() { {finding.inherited && finding.source_task_id && ( - Source task #{finding.source_task_id} · read-only + {t("Source task #{id} · read-only", { id: finding.source_task_id })} )}
- Overview - Exploration graph + {t("Overview")} + {t("Exploration graph")} @@ -191,16 +192,16 @@ function FindingDetailInner() {
- Digest + {t("Digest")} -

{finding.summary || "(no digest)"}

+

{finding.summary || t("(no digest)")}

- Evidence / PoC + {t("Evidence / PoC")} {finding.evidence ? ( @@ -208,14 +209,14 @@ function FindingDetailInner() { {finding.evidence} ) : ( -

(no evidence)

+

{t("(no evidence)")}

)}
{finding.counterevidence?.trim() && ( - Counterevidence + {t("Counterevidence")}

{finding.counterevidence}

@@ -225,7 +226,7 @@ function FindingDetailInner() { {finding.confidence_rationale?.trim() && ( - Confidence rationale + {t("Confidence rationale")}

{finding.confidence_rationale}

@@ -242,19 +243,21 @@ function FindingDetailInner() { {/* Below evidence: detailed report (rendered Markdown) */} - Detailed report - {finding.report && } + {t("Detailed report")} + {finding.report && } {finding.report_stale ? ( - Traffic evidence has changed; the detailed report is pending an update. + + {t("Traffic evidence has changed; the detailed report is pending an update.")} + ) : null} {finding.report ? ( ) : ( -

No detailed report yet.

+

{t("No detailed report yet.")}

)}
@@ -263,18 +266,18 @@ function FindingDetailInner() { {/* Right column: status panel */} - Status + {t("Status")} {/* Vulnerability ID */} - + #{finding.id} {/* Severity */} - + {finding.inherited ? ( ) : ( @@ -296,7 +299,7 @@ function FindingDetailInner() { {/* Triage status */} - + {finding.inherited ? ( ) : ( @@ -317,7 +320,7 @@ function FindingDetailInner() { )} - + {finding.inherited ? ( ) : ( @@ -343,7 +346,7 @@ function FindingDetailInner() { {/* Verification: automated outcome; the note explains any state other than verified */} {finding.verification_status && ( - + {finding.verification_status !== "verified" && finding.verification_note?.trim() && (

@@ -354,7 +357,7 @@ function FindingDetailInner() { )} {/* Vulnerability type */} - + {finding.vulnclass ? ( {finding.vulnclass} ) : ( @@ -363,7 +366,7 @@ function FindingDetailInner() { {/* Assets */} - + {finding.assets && finding.assets.length > 0 ? (

{finding.assets.map((a) => ( @@ -382,7 +385,7 @@ function FindingDetailInner() { {/* Task */} - + {finding.task_id ? ( ) : ( - — (task deleted) + {t("— (task deleted)")} )} {/* Found at */} - + {fmtTime(finding.ts)} diff --git a/web/src/app/(main)/function/findings/page.tsx b/web/src/app/(main)/function/findings/page.tsx index 25eb1c1..bd1dfd1 100644 --- a/web/src/app/(main)/function/findings/page.tsx +++ b/web/src/app/(main)/function/findings/page.tsx @@ -73,6 +73,7 @@ import { VERIFICATION_STATUSES, } from "./_components/findings-table"; import { setVisibleInterval } from "@/lib/polling"; +import { t } from "@/i18n"; const FINDING_LIST_PREFERENCE_KEY = "artex_finding_list_preferences"; @@ -201,7 +202,7 @@ export default function FindingsPage() { setActiveRetests(Object.fromEntries(rows.map((item) => [item.finding_id, item]))); failed = false; } catch (error) { - if (!disposed && !failed) toast.error(`Failed to load retest status: ${(error as Error).message}`); + if (!disposed && !failed) toast.error(t("Failed to load retest status: {error}", { error: (error as Error).message })); failed = true; } finally { if (!disposed) timer = setTimeout(() => void refreshRetests(), 3000); @@ -324,9 +325,9 @@ export default function FindingsPage() { ids: [...selectedIds], }); setExportOpen(false); - toast.success("Export download started"); + toast.success(t("Export download started")); } catch (e) { - toast.error(`Export failed: ${(e as Error).message}`); + toast.error(t("Export failed: {error}", { error: (e as Error).message })); } finally { setExporting(false); } @@ -420,7 +421,7 @@ export default function FindingsPage() { } catch (e) { if (request !== assetTreeRequest.current || activeFilterFingerprint.current !== requestFilter) return; setAssetTree((current) => ({ ...current, loading: false })); - toast.error(`Failed to load the asset tree: ${(e as Error).message}`); + toast.error(t("Failed to load the asset tree: {error}", { error: (e as Error).message })); } }, [filterFingerprint, reportState, severity, status, verificationStatus, vulnclass, task, query, sort]); @@ -669,7 +670,7 @@ export default function FindingsPage() { setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: next } : x))); try { await api.setFindingStatus(f.finding_id, next); - toast.success(`Marked as "${statusMeta("finding", next).label}"`); + toast.success(t('Marked as "{label}"', { label: statusMeta("finding", next).label })); // refresh stat cards (pending count) and drop the row if it no longer matches the status filter api .findingStats() @@ -685,7 +686,7 @@ export default function FindingsPage() { refreshAfterMutation(f); } catch (e) { setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: prev } : x))); - toast.error(`Update failed: ${(e as Error).message}`); + toast.error(t("Update failed: {error}", { error: (e as Error).message })); } }, [refreshAfterMutation, setFindings, status], @@ -698,7 +699,7 @@ export default function FindingsPage() { setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: next } : x))); try { await api.setFindingReportState(f.finding_id, next); - toast.success(`Report stage set to "${REPORT_STATE_META[next].label}"`); + toast.success(t('Report stage set to "{label}"', { label: REPORT_STATE_META[next].label })); api .findingStats() .then(setStats) @@ -713,7 +714,7 @@ export default function FindingsPage() { refreshAfterMutation(f); } catch (e) { setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: prev } : x))); - toast.error(`Update failed: ${(e as Error).message}`); + toast.error(t("Update failed: {error}", { error: (e as Error).message })); } }, [refreshAfterMutation, reportState, setFindings], @@ -729,9 +730,7 @@ export default function FindingsPage() { const r = await api.bulkSetFindingStatus([...selectedIds], next); setSelectedIds(new Set()); const label = statusMeta("finding", next).label; - toast.success( - r.updated === 1 ? `Marked 1 finding as "${label}"` : `Marked ${r.updated} findings as "${label}"`, - ); + toast.success(t('Marked {count} findings as "{label}"', { count: r.updated, label })); void loadFlat(); if (view === "asset") void loadAssetTree(); api @@ -741,7 +740,7 @@ export default function FindingsPage() { // The list reload remains valid even if the aggregate refresh fails. }); } catch (e) { - toast.error(`Bulk update failed: ${(e as Error).message}`); + toast.error(t("Bulk update failed: {error}", { error: (e as Error).message })); } finally { setBulkBusy(false); } @@ -757,11 +756,7 @@ export default function FindingsPage() { const r = await api.bulkSetFindingReportState([...selectedIds], next); setSelectedIds(new Set()); const label = REPORT_STATE_META[next].label; - toast.success( - r.updated === 1 - ? `Set report stage of 1 finding to "${label}"` - : `Set report stage of ${r.updated} findings to "${label}"`, - ); + toast.success(t('Set report stage of {count} findings to "{label}"', { count: r.updated, label })); void loadFlat(); if (view === "asset") void loadAssetTree(); api @@ -771,7 +766,7 @@ export default function FindingsPage() { // The list reload remains valid even if the aggregate refresh fails. }); } catch (e) { - toast.error(`Bulk update failed: ${(e as Error).message}`); + toast.error(t("Bulk update failed: {error}", { error: (e as Error).message })); } finally { setBulkBusy(false); } @@ -828,7 +823,7 @@ export default function FindingsPage() { : x, ), ); - toast.success("Saved"); + toast.success(t("Saved")); api .findingStats() .then(setStats) @@ -837,7 +832,7 @@ export default function FindingsPage() { }); refreshAfterMutation(f); } catch (e) { - toast.error(`Save failed: ${(e as Error).message}`); + toast.error(t("Save failed: {error}", { error: (e as Error).message })); } finally { setSaving(false); } @@ -861,7 +856,7 @@ export default function FindingsPage() { setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) })); const rowKey = findingRowKey(f); setExpanded((cur) => (cur === rowKey ? null : cur)); - toast.success("Vulnerability deleted"); + toast.success(t("Vulnerability deleted")); api .findingStats() .then(setStats) @@ -870,7 +865,7 @@ export default function FindingsPage() { }); refreshAfterMutation(f, true); } catch (e) { - toast.error(`Delete failed: ${(e as Error).message}`); + toast.error(t("Delete failed: {error}", { error: (e as Error).message })); } }, [refreshAfterMutation, setFindings], @@ -888,28 +883,28 @@ export default function FindingsPage() { const result = await api.deepenFinding(deepenFinding.finding_id, deepenDescription.trim()); toast.success( result.queued - ? `Deepen intent #${result.intent_id} has entered the task queue` - : `Created high-priority worker intent #${result.intent_id}`, + ? t("Deepen intent #{id} has entered the task queue", { id: result.intent_id }) + : t("Created high-priority worker intent #{id}", { id: result.intent_id }), ); refreshAfterMutation(deepenFinding); setDeepenFinding(null); setDeepenDescription(""); } catch (error) { - toast.error(`Submit failed: ${(error as Error).message}`); + toast.error(t("Submit failed: {error}", { error: (error as Error).message })); } finally { setDeepening(false); } } const statCards = [ - { label: "Total findings", value: stats.total, icon: BugIcon }, - { label: "Pending", value: stats.pending, tone: "text-amber-500", icon: ClockIcon }, - { label: "Submitted", value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon }, - { label: "Accepted", value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon }, - { label: "Critical", value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon }, - { label: "High", value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon }, - { label: "Medium", value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon }, - { label: "Low", value: stats.low, tone: "text-slate-500", icon: InfoIcon }, + { label: t("Total findings"), value: stats.total, icon: BugIcon }, + { label: t("Pending"), value: stats.pending, tone: "text-amber-500", icon: ClockIcon }, + { label: t("Submitted"), value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon }, + { label: t("Accepted"), value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon }, + { label: t("Critical"), value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon }, + { label: t("High"), value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon }, + { label: t("Medium"), value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon }, + { label: t("Low"), value: stats.low, tone: "text-slate-500", icon: InfoIcon }, ]; // The "current filter" count in the export dialog: both views share the same filters, only the counting source differs. @@ -949,7 +944,7 @@ export default function FindingsPage() {
) : ( <> - +
-

Findings

-

Cross-task vulnerability overview

+

{t("Findings")}

+

{t("Cross-task vulnerability overview")}

setView(v as FindingView)}> - All findings - By task - By asset + {t("All findings")} + {t("By task")} + {t("By asset")}
@@ -1006,8 +1001,8 @@ export default function FindingsPage() { type="search" value={search} onChange={(event) => setSearch(event.target.value)} - placeholder="Search findings" - aria-label="Search findings" + placeholder={t("Search findings")} + aria-label={t("Search findings")} />