diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 320b606..d6dcef4 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..249338d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,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 b44fd9c..dc191b9 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..481aca9 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. 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..654b8eb 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 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/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/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/intercept/intercept.go b/intercept/intercept.go index 70bbf90..c765f02 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() 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..367a5a2 100644 --- a/mcphttp/client.go +++ b/mcphttp/client.go @@ -31,6 +31,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 } @@ -352,10 +356,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 +518,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 +623,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_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/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 5da030f..522682f 100644 --- a/server/server.go +++ b/server/server.go @@ -74,6 +74,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) @@ -745,6 +747,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) @@ -1047,7 +1050,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) } diff --git a/server/server_mgmt.go b/server/server_mgmt.go index 0367e46..a91e039 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -1156,7 +1156,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 +1167,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 +1275,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 +1322,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 +1357,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 +1400,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 +1416,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 +1618,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 +1730,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 +1845,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 +1881,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 +1920,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 +1963,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 +1994,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}) 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/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..8d87d2a 100644 --- a/server/workspace.go +++ b/server/workspace.go @@ -23,23 +23,33 @@ 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 + } + return cp, true +} + // 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 +67,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 +84,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 +114,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 +135,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 +155,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 +185,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 +201,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 +223,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 +242,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 +261,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/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")} />