Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(secret-server): redeem runner-bound secret credentials (#3024)

Jiaqiang Wong8d6f80f5ef6e
diff --git a/apps/secret-server/README.md b/apps/secret-server/README.md
index ece8e0aad..3d181e50b 100644
--- a/apps/secret-server/README.md
+++ b/apps/secret-server/README.md
@@ -4,10 +4,8 @@ The internal encryption package protects secret values and routing policy with p
## Scope
-This Go module contains `internal/encryption`, `internal/server`,
-`internal/attest` ([runner attestation](#runner-attestation)), and a Secret
-Server skeleton with database initialization and a migration command. Write and
-fetch business endpoints and deployment resources are not yet implemented.
+This Go module runs Secret Server with database initialization, a migration
+command, and the authenticated fetch endpoint.
The existing API encryption service and stored values remain unchanged.
## Server skeleton
@@ -21,7 +19,8 @@ environment key provider is rejected in production.
The write route group validates Google ID tokens and permits only verified emails
on the allowlist. The fetch route checks Runner proof in `fetch` and `all` roles.
-The current business handlers are placeholders that return 404 after authentication.
+The fetch endpoint redeems credentials. The reserved write routes return 404
+after successful write authentication until their handlers are wired.
`/health` is liveness and `/ready` checks database connectivity. Startup also
performs an encryption round trip.
@@ -55,7 +54,9 @@ exposing secret values; it does not use envconfig or validator.
For a local run, supply a persistent development key, database URL, and dev token
through the environment, then run `make run:apps:secret-server`. The role defaults
to `write`; set `SECRET_SERVER_ROLE=fetch` to select fetch. The local target defaults
-to the `dev` attestor. Do not commit or print the key or token.
+to the `dev` attestor. For `fetch` and `all`, set
+`SECRET_SERVER_INTROSPECTION_URL` to the full credential introspection URL.
+Do not commit or print the key or token.
The local database must use the same key across restarts.
@@ -73,7 +74,7 @@ Routing metadata follows the [headers map contract](https://github.com/boxlite-a
## Server configuration and write authentication
The service configuration and write authentication middleware are available for
-the server skeleton. Google mode validates token signature, audience, expiry,
+the server runtime. Google mode validates token signature, audience, expiry,
issuer, verified email, and the caller allowlist. Dev mode uses an exact bearer
token and is permitted only in local and dev environments.
@@ -241,7 +242,7 @@ Invalid attestation configuration prevents startup before the listener opens.
| `Verify` result | Meaning | Fetch route answer |
| --- | --- | --- |
-| `runnerID, nil` | Proof valid | Continue to the fetch handler (currently a 404 placeholder) |
+| `runnerID, nil` | Proof valid | Continue to credential introspection |
| `errors.Is(err, attest.ErrInvalidProof)` | Missing, ambiguous, or rejected proof | 401 `attestation_failed` |
| any other error | Google signing keys unreachable | 503; the runner retries |
@@ -324,3 +325,121 @@ Verifying real Google tokens is planned for staging.
This is a new contract with no equivalent on the base branch. Full-revert defect
proof is not applicable; positive, negative, and boundary tests exercise the new code.
+
+## Fetching authorized secrets
+
+The `internal/fetch` handler implements
+[credential redemption](https://github.com/boxlite-ai/boxlite/issues/2724).
+It depends on the single-value database foundation in #2612, including the
+existing attestation and encryption packages. Migration 2 extends access-log
+results while preserving version-1 data. There is no secret version in grants,
+responses or audit rows; decryption always uses AAD version 1.
+
+For `fetch` and `all`, startup constructs the handler after database
+initialization, using the configured cipher and Runner verifier. Set the full
+internal endpoint, for example:
+
+```sh
+export SECRET_SERVER_INTROSPECTION_URL=https://api-internal/internal/v1/credentials/introspect
+```
+
+For fetch-enabled roles, startup rejects a missing URL or a URL without an
+endpoint path before opening the database pool. The runtime
+mounts `POST /internal/v1/secrets/fetch` separately from write-caller authentication.
+The `write` role leaves fetch disabled and does not require this URL.
+
+A runner posts `{"credential":"bxsc_..."}` with its attestation proof header.
+The handler verifies identity before contacting the API, then sends
+`{"token":"bxsc_...","runner_id":"..."}`. The API owns atomic consumption
+and runner binding (BUI-1385); the client makes one request with a three-second
+limit and never follows redirects, retries or caches authorization.
+The MVP API route has no caller authentication and must remain internal-only.
+Introspection requires HTTPS, except for literal loopback IPs used by local tests.
+Hostnames such as `localhost` do not qualify for the plaintext exception.
+
+```text
+proof -> consuming introspection -> check all organizations and box scopes
+ -> decrypt all values -> audit -> complete response
+```
+
+An active reply must contain credential, organization, runner and box IDs,
+an unexpired RFC3339 expiry and unique secret grants. The returned runner must
+match the verified identity. Missing or disabled rows reject the entire request;
+box-scoped secrets must match both organization and box. Decryption reconstructs
+AAD from stored IDs, hosts and headers. A late failure returns no partial values.
+
+Success is `{"box_id":"...","secrets":[{"name":"...","value":"...",
+"hosts":["..."],"headers":{"Authorization":"Bearer {value}"},
+"placeholder":"..."}]}`. Empty grants return `secrets: []`.
+Every response carries `Cache-Control: no-store`; errors use RFC 9457 with `code`.
+
+| Failure | HTTP / code | Audit result |
+| --- | --- | --- |
+| Invalid proof | 401 / `attestation_failed` | `attestation_failed` |
+| Verifier outage | 503 / `attestation_unavailable` | `attestation_unavailable` |
+| Inactive credential | 401 / `credential_invalid` | `credential_invalid` |
+| Runner mismatch | 401 / `credential_invalid` | `runner_mismatch` |
+| Organization or box mismatch | 401 / `credential_invalid` | `scope_mismatch` |
+| Missing or disabled secret | 409 / `secret_unavailable` | `not_found` / `disabled` |
+| API failure or malformed answer | 503 / `api_unavailable` | `api_unavailable` |
+| Storage failure or resource limit | 503 / `store_unavailable` | `store_unavailable` |
+| Decryption failure | 503 / `decrypt_failed` | `decrypt_failed` |
+
+Disabled errors include the authorized name; a deleted secret has no name to
+return. Inactive reasons are known only to the API. Attestation failures never
+consume credentials; failures after successful introspection leave them consumed.
+
+Resource bounds are 4 KiB request bodies, 64 KiB API replies, 64 grants,
+65,565 bytes of ciphertext (64 KiB plaintext plus 29 bytes of envelope overhead),
+64 KiB wrapped keys, 2 MiB per serialized stored row, 12 MiB of serialized rows
+per grant set, 8 MiB success JSON and 16 concurrent fetch operations. The row
+budget accommodates the write endpoint's 1 MiB JSON request after PostgreSQL
+reformats metadata and hex encodes the envelope. A single SQL statement checks
+row and grant-set sizes before returning payloads.
+
+Audit attempts use a separate 100 ms context for the complete outcome, with at
+most 16 concurrent audit operations. Each batch uses one atomic SQL insert, so
+a failed row cannot leave a partially persisted batch. Success records one row per secret; empty
+success and failure record one row. Unknown identifiers remain null.
+Audit failures preserve the response outcome, emit a fixed error log and increment
+`Handler.AuditFailures()` for telemetry collection. Credentials, proofs, values,
+templates, placeholders and raw upstream errors are never logged.
+
+Tests use a consuming HTTP fake for the API and real envelope encryption.
+They cover identity ordering, replay, concurrent consumption, ownership, late
+failures, redirect refusal, timeout, limits and audit failures. The PostgreSQL
+integration target includes real fetch queries, audit constraints and schema
+upgrade preservation; staging integration with the real API remains pending.
+It also combines the production local/dev attestation selector with HTTP and
+PostgreSQL to check allowed organization/box access, rejected foreign ownership,
+and missing-proof rejection before API contact. This does not exercise real GCP
+tokens or replace staging identity verification.
+
+### Credential API contract integration
+
+`make test:apps:secret-server:credential-api` runs the actual service, controller
+and migration as merged by API PR #2769 at commit
+`bc78b36e5dc241bb3d2d7f8522f4f6f546833b40`, with the Secret Server command on a loopback listener and real
+PostgreSQL. The harness reads these files from Git into a temporary directory;
+it does not change the API checkout or implement a second credential service.
+
+Prerequisites: the merged commit must be available locally (`git fetch origin
+main`), Node.js, installed apps dependencies (`make _ensure-apps-deps`),
+Go, and a disposable PostgreSQL instance allowing database creation.
+
+```sh
+SECRET_TEST_DATABASE_URL=postgresql://boxlite:[email protected]:25432/boxlite \
+ make test:apps:secret-server:credential-api
+```
+
+`NODE_PATH` may point to an existing apps dependency installation; otherwise the
+target uses this worktree's `apps/node_modules`. The harness creates a temporary
+API schema and a separate secret database, then removes both. Its loopback-only
+issuance fixture invokes the real service; it is not a production API endpoint.
+
+The test verifies that missing proof and wrong Runner identity leave the
+credential usable. It also checks redemption of a 64 KiB value with a 920 KiB
+placeholder, replay rejection, and persisted audit outcomes. A missing or skipped
+Go test fails the harness. It covers Secret Server startup and the API contract
+in an isolated Nest application. Full API startup, ingress, deployment, and GCP
+attestation require separate validation.
diff --git a/apps/secret-server/cmd/secret-server/credential_api_test.go b/apps/secret-server/cmd/secret-server/credential_api_test.go
new file mode 100644
index 000000000..24254e7eb
--- /dev/null
+++ b/apps/secret-server/cmd/secret-server/credential_api_test.go
@@ -0,0 +1,132 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/attest"
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestCredentialAPIIntegration(t *testing.T) {
+ endpoint := os.Getenv("SECRET_TEST_CREDENTIAL_API_URL")
+ if endpoint == "" {
+ t.Skip("run make test:apps:secret-server:credential-api")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ dsn := runtimeDatabase(t, ctx)
+ t.Setenv("SECRET_SERVER_ROLE", "all")
+ t.Setenv("SECRET_SERVER_ATTESTORS", "dev")
+ t.Setenv("SECRET_SERVER_INTROSPECTION_URL", endpoint+"/internal/v1/credentials/introspect")
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ runtime := startRuntime(t, ctx)
+ fetchURL := "http://" + runtime.awaitAddress(t, ctx) + "/internal/v1/secrets/fetch"
+
+ provider, err := encryption.NewEnvKeyProvider(os.Getenv("SECRET_MASTER_KEY_ID"), os.Getenv("SECRET_MASTER_KEY_BASE64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cipher, err := encryption.NewCipher(provider)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const first = "22222222-2222-2222-2222-222222222222"
+ const org = "11111111-1111-1111-1111-111111111111"
+ hosts := []string{"api.example.com"}
+ templates := map[string]string{"Authorization": "Bearer {value}"}
+ placeholder := strings.Repeat("p", 920<<10)
+ want := "plaintext-marker-" + strings.Repeat("a", 65536-len("plaintext-marker-"))
+ envelope, err := cipher.Encrypt(ctx, encryption.SecretContext{
+ OrganizationID: org, SecretID: first, Version: 1, Hosts: hosts, Headers: templates,
+ }, []byte(want))
+ if err != nil {
+ t.Fatal(err)
+ }
+ headers, err := json.Marshal(templates)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = pool.Exec(ctx, `INSERT INTO secret(id,organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by)
+ VALUES($1,$2,'org',$3,$3,$4,$5,$6,$7,$8,$9,'test')`, first, org, "KEY_2", envelope.Ciphertext, envelope.WrappedDEK.Ciphertext, envelope.WrappedDEK.KeyID, hosts, headers, placeholder)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client := &http.Client{Timeout: 5 * time.Second}
+ binding, _ := json.Marshal(map[string]any{"runnerId": "runner-a", "boxId": "box-a", "organizationId": org, "secretIds": []string{first}})
+ response, err := client.Post(endpoint+"/__test/issue", "application/json", bytes.NewReader(binding))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var issued struct {
+ Token string `json:"token"`
+ }
+ err = json.NewDecoder(response.Body).Decode(&issued)
+ response.Body.Close()
+ if err != nil || response.StatusCode != 200 || !strings.HasPrefix(issued.Token, "bxsc_") {
+ t.Fatal("production API did not issue credential")
+ }
+ body, _ := json.Marshal(map[string]string{"credential": issued.Token})
+ for _, tc := range []struct {
+ name, runner string
+ status int
+ result string
+ }{
+ {"missing proof does not consume", "", 401, "attestation_failed"},
+ {"wrong runner does not consume", "runner-b", 401, "credential_invalid"},
+ {"redeem", "runner-a", 200, "ok"},
+ {"replay", "runner-a", 401, "credential_invalid"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, fetchURL, bytes.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.runner != "" {
+ request.Header.Set(attest.DevHeader, tc.runner)
+ }
+ response, err := client.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := io.ReadAll(response.Body)
+ response.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if response.StatusCode != tc.status {
+ t.Fatalf("status %d, want %d", response.StatusCode, tc.status)
+ }
+ if response.Header.Get("Cache-Control") != "no-store" {
+ t.Fatal("cacheable secret response")
+ }
+ if tc.status == 200 {
+ var result struct {
+ BoxID string `json:"box_id"`
+ Secrets []struct{ Value, Placeholder string } `json:"secrets"`
+ }
+ if json.Unmarshal(data, &result) != nil || result.BoxID != "box-a" || len(result.Secrets) != 1 || result.Secrets[0].Value != want || result.Secrets[0].Placeholder != placeholder {
+ t.Fatal("wrong decrypted secret response")
+ }
+ } else if bytes.Contains(data, []byte("plaintext-marker")) {
+ t.Fatal("denied request exposed plaintext")
+ }
+ var auditResult string
+ if err = pool.QueryRow(ctx, "SELECT result FROM secret_access_log ORDER BY id DESC LIMIT 1").Scan(&auditResult); err != nil || auditResult != tc.result {
+ t.Fatalf("audit %s, want %s: %v", auditResult, tc.result, err)
+ }
+ })
+ }
+}
diff --git a/apps/secret-server/cmd/secret-server/runtime_integration_test.go b/apps/secret-server/cmd/secret-server/runtime_integration_test.go
index 9cb3d3e7c..61371d8c3 100644
--- a/apps/secret-server/cmd/secret-server/runtime_integration_test.go
+++ b/apps/secret-server/cmd/secret-server/runtime_integration_test.go
@@ -6,6 +6,7 @@ import (
"errors"
"net"
"net/http"
+ "net/http/httptest"
"os"
"strings"
"testing"
@@ -119,20 +120,80 @@ func TestFetchRuntimeRequiresAttestation(t *testing.T) {
}
t.Setenv("SECRET_SERVER_ATTESTORS", "dev")
- s := startRuntime(t, ctx)
- address := s.awaitAddress(t, ctx)
- for _, path := range []string{"/internal/v1/fetch", "/internal/v1/fetch/child"} {
- if got := runtimeStatus(t, address, path, ""); got != http.StatusUnauthorized {
- t.Errorf("%s without Runner proof returned %d, want 401", path, got)
+ t.Setenv("SECRET_SERVER_INTROSPECTION_URL", "http://api.invalid/internal/v1/credentials/introspect")
+ err = runWithListener(ctx, nil, func(_, _ string) (net.Listener, error) { return nil, listenCalled })
+ if errors.Is(err, listenCalled) || err == nil || !strings.Contains(err.Error(), "SECRET_SERVER_INTROSPECTION_URL") {
+ t.Fatalf("invalid introspection URL returned %v, want startup rejection before listen", err)
+ }
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ t.Error("request without valid proof or credential reached introspection")
+ w.WriteHeader(500)
+ }))
+ defer api.Close()
+ t.Setenv("SECRET_SERVER_INTROSPECTION_URL", api.URL+"/introspect")
+ address := startRuntime(t, ctx).awaitAddress(t, ctx)
+ for _, tc := range []struct {
+ path, proof string
+ status int
+ }{
+ {"/internal/v1/secrets/fetch", "", 401},
+ {"/internal/v1/secrets/fetch", "test-runner", 401},
+ {"/internal/v1/secrets/fetch/child", "test-runner", 404},
+ } {
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://"+address+tc.path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.proof != "" {
+ req.Header.Set(attest.DevHeader, tc.proof)
+ }
+ resp, err := (&http.Client{Timeout: 3 * time.Second}).Do(req)
+ if err != nil {
+ t.Fatal(err)
}
- if got := runtimeStatus(t, address, path, "test-runner"); got != http.StatusNotFound {
- t.Errorf("%s with Runner proof returned %d, want placeholder 404", path, got)
+ resp.Body.Close()
+ if resp.StatusCode != tc.status {
+ t.Errorf("%s returned %d, want %d", tc.path, resp.StatusCode, tc.status)
}
}
})
}
}
+func TestFetchStartupRejectsInvalidEndpoint(t *testing.T) {
+ for _, tc := range []struct{ role, endpoint string }{
+ {"fetch", ""},
+ {"all", "https://api.invalid"},
+ {"all", "https://api.invalid/"},
+ } {
+ t.Run(tc.role+"/"+tc.endpoint, func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ dsn := runtimeDatabase(t, ctx)
+ t.Setenv("SECRET_SERVER_ROLE", tc.role)
+ t.Setenv("SECRET_SERVER_ATTESTORS", "dev")
+ t.Setenv("SECRET_SERVER_INTROSPECTION_URL", tc.endpoint)
+ err := runWithListener(ctx, nil, func(_, _ string) (net.Listener, error) {
+ t.Error("invalid config reached listener")
+ return nil, errors.New("listener reached")
+ })
+ if err == nil || !strings.Contains(err.Error(), "SECRET_SERVER_INTROSPECTION_URL") {
+ t.Errorf("startup error = %v, want introspection URL error", err)
+ }
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ var initialized bool
+ err = pool.QueryRow(ctx, "SELECT to_regclass('goose_db_version') IS NOT NULL OR to_regclass('key_verification_canary') IS NOT NULL").Scan(&initialized)
+ if err != nil || initialized {
+ t.Fatalf("invalid config initialized database: initialized=%t err=%v", initialized, err)
+ }
+ })
+ }
+}
+
func TestFetchRuntimeRequiresGCPRunnerRegistry(t *testing.T) {
for _, role := range []string{"fetch", "all"} {
t.Run(role, func(t *testing.T) {
@@ -141,6 +202,7 @@ func TestFetchRuntimeRequiresGCPRunnerRegistry(t *testing.T) {
runtimeDatabase(t, ctx)
t.Setenv("SECRET_SERVER_ROLE", role)
t.Setenv("SECRET_SERVER_ATTESTORS", "gcp_iit")
+ t.Setenv("SECRET_SERVER_INTROSPECTION_URL", "https://api.invalid/internal/v1/credentials/introspect")
t.Setenv("SECRET_SERVER_AUDIENCE", "https://secret.example.invalid")
t.Setenv("SECRET_SERVER_GCP_PROJECT", "test-project")
t.Setenv("SECRET_SERVER_RUNNER_SERVICE_ACCOUNT", "[email protected]")
diff --git a/apps/secret-server/internal/database/database.go b/apps/secret-server/internal/database/database.go
index 744e8865a..4db912f81 100644
--- a/apps/secret-server/internal/database/database.go
+++ b/apps/secret-server/internal/database/database.go
@@ -20,7 +20,7 @@ import (
//go:embed migrations/*.sql
var migrationFiles embed.FS
-const schemaVersion = 1
+const schemaVersion = 2
type boundedSessionLocker struct{ lock.SessionLocker }
diff --git a/apps/secret-server/internal/database/database_test.go b/apps/secret-server/internal/database/database_test.go
index 5634775c9..59d057d0a 100644
--- a/apps/secret-server/internal/database/database_test.go
+++ b/apps/secret-server/internal/database/database_test.go
@@ -13,12 +13,14 @@ import (
"strings"
"sync"
"testing"
+ "testing/fstest"
"time"
"github.com/boxlite-ai/secret-server/internal/encryption"
"github.com/boxlite-ai/secret-server/internal/testdb"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/jackc/pgx/v5/stdlib"
"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock"
)
@@ -75,6 +77,42 @@ func TestIntegration(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(admin.Close)
+ t.Run("upgrade populated version one", func(t *testing.T) {
+ _, dsn := testdb.Create(t, ctx, admin, url, false)
+ legacyPool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer legacyPool.Close()
+ initial, err := migrationFiles.ReadFile("migrations/00001_initial.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ bridge := stdlib.OpenDBFromPool(legacyPool)
+ provider, err := goose.NewProvider(goose.DialectPostgres, bridge, fstest.MapFS{"00001_initial.sql": &fstest.MapFile{Data: initial}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = provider.Up(ctx); err != nil {
+ t.Fatal(err)
+ }
+ bridge.Close()
+ if _, err = legacyPool.Exec(ctx, "INSERT INTO secret_access_log(result) VALUES ($1)", "ok"); err != nil {
+ t.Fatal(err)
+ }
+ if err = Migrate(ctx, legacyPool); err != nil {
+ t.Fatal(err)
+ }
+ var count int
+ if err = legacyPool.QueryRow(ctx, "SELECT count(*) FROM secret_access_log WHERE result=$1", "ok").Scan(&count); err != nil || count != 1 {
+ t.Fatalf("preserved rows %d %v", count, err)
+ }
+ for _, result := range []string{"api_unavailable", "scope_mismatch", "store_unavailable", "attestation_unavailable"} {
+ if _, err = legacyPool.Exec(ctx, "INSERT INTO secret_access_log(result) VALUES ($1)", result); err != nil {
+ t.Fatal(err)
+ }
+ }
+ })
t.Run("temporary database URL supports pool options", func(t *testing.T) {
parsed, err := urlpkg.Parse(url)
if err != nil {
@@ -289,7 +327,7 @@ func TestIntegration(t *testing.T) {
if err := Migrate(ctx, pool); err != nil {
t.Fatal(err)
}
- if _, err := pool.Exec(ctx, `INSERT INTO goose_db_version (version_id, is_applied) VALUES (2, true)`); err != nil {
+ if _, err := pool.Exec(ctx, `INSERT INTO goose_db_version (version_id, is_applied) VALUES (3, true)`); err != nil {
t.Fatal(err)
}
if err := Migrate(ctx, pool); err != nil {
diff --git a/apps/secret-server/internal/database/migrations/00002_fetch_audit_results.sql b/apps/secret-server/internal/database/migrations/00002_fetch_audit_results.sql
new file mode 100644
index 000000000..bf67e3bb4
--- /dev/null
+++ b/apps/secret-server/internal/database/migrations/00002_fetch_audit_results.sql
@@ -0,0 +1,6 @@
+-- +goose Up
+ALTER TABLE secret_access_log DROP CONSTRAINT secret_access_log_result_check;
+ALTER TABLE secret_access_log ADD CONSTRAINT secret_access_log_result_check CHECK (result IN
+ ('ok', 'attestation_failed', 'credential_invalid', 'runner_mismatch',
+ 'not_found', 'disabled', 'decrypt_failed', 'api_unavailable',
+ 'scope_mismatch', 'store_unavailable', 'attestation_unavailable'));
diff --git a/apps/secret-server/internal/fetch/client.go b/apps/secret-server/internal/fetch/client.go
new file mode 100644
index 000000000..36d3b6b24
--- /dev/null
+++ b/apps/secret-server/internal/fetch/client.go
@@ -0,0 +1,105 @@
+package fetch
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+type grant struct {
+ SecretID string `json:"secret_id"`
+}
+type authorization struct {
+ Active bool `json:"active"`
+ CredentialID string `json:"credential_id"`
+ RunnerID string `json:"runner_id"`
+ BoxID string `json:"box_id"`
+ OrganizationID string `json:"organization_id"`
+ Grants []grant `json:"grants"`
+ ExpiresAt time.Time `json:"expires_at"`
+}
+
+type apiClient struct {
+ endpoint string
+ http http.Client
+}
+
+// ValidateIntrospectionURL checks the endpoint without connecting to the API.
+func ValidateIntrospectionURL(endpoint string) error {
+ u, err := url.Parse(endpoint)
+ if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
+ return errors.New("invalid introspection endpoint")
+ }
+ if strings.Trim(u.Path, "/") == "" {
+ return errors.New("introspection URL requires an endpoint path")
+ }
+ if ip, _ := netip.ParseAddr(u.Hostname()); u.Scheme == "http" && !ip.IsLoopback() {
+ return errors.New("introspection requires HTTPS outside literal loopback")
+ }
+ return nil
+}
+
+func newClient(endpoint string) (*apiClient, error) {
+ if err := ValidateIntrospectionURL(endpoint); err != nil {
+ return nil, err
+ }
+ return &apiClient{endpoint: endpoint, http: http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+
+func (c *apiClient) consume(ctx context.Context, token, runner string) (authorization, error) {
+ var a authorization
+ body, _ := json.Marshal(map[string]string{"token": token, "runner_id": runner})
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
+ if err != nil {
+ return a, err
+ }
+ // POST has no idempotency key; Go's transport must not replay consumption.
+ req.GetBody = nil
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return a, errors.New("introspection transport failed")
+ }
+ defer resp.Body.Close()
+ data, err := io.ReadAll(io.LimitReader(resp.Body, 65537))
+ if err != nil || len(data) > 65536 || resp.StatusCode != 200 {
+ return a, errors.New("introspection response failed")
+ }
+ var active struct {
+ Active *bool `json:"active"`
+ }
+ if json.Unmarshal(data, &active) != nil || active.Active == nil || json.Unmarshal(data, &a) != nil {
+ return authorization{}, errors.New("invalid introspection response")
+ }
+ if !a.Active {
+ return authorization{}, nil
+ }
+ if !uuid(a.CredentialID) || !uuid(a.OrganizationID) || a.RunnerID == "" || len(a.RunnerID) > 256 || a.BoxID == "" || len(a.BoxID) > 64 || !a.ExpiresAt.After(time.Now()) || a.Grants == nil || len(a.Grants) > 64 {
+ return authorization{}, errors.New("incomplete authorization")
+ }
+ seen := make(map[string]bool, len(a.Grants))
+ for i, g := range a.Grants {
+ id := strings.ToLower(g.SecretID)
+ if !uuid(id) || seen[id] {
+ return authorization{}, errors.New("invalid grant")
+ }
+ seen[id] = true
+ a.Grants[i].SecretID = id
+ }
+ a.OrganizationID = strings.ToLower(a.OrganizationID)
+ return a, nil
+}
+
+func uuid(s string) bool {
+ var id pgtype.UUID
+ return len(s) == 36 && s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-' && id.Scan(s) == nil && id.Valid
+}
diff --git a/apps/secret-server/internal/fetch/client_test.go b/apps/secret-server/internal/fetch/client_test.go
new file mode 100644
index 000000000..cf301c389
--- /dev/null
+++ b/apps/secret-server/internal/fetch/client_test.go
@@ -0,0 +1,100 @@
+package fetch
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestClientRejectsInvalidResponses(t *testing.T) {
+ for _, body := range []string{`{}`, `null`, `{"active":null}`, `{"active":"true"}`, `{"active":true}`, `{"active":false} {}`, strings.Repeat(" ", 65537)} {
+ t.Run(body[:min(len(body), 30)], func(t *testing.T) {
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, body) }))
+ defer s.Close()
+ c, _ := newClient(s.URL + "/introspect")
+ if _, err := c.consume(context.Background(), "x", "r"); err == nil {
+ t.Fatal("invalid reply accepted")
+ }
+ })
+ }
+ for _, mutate := range []func(*authorization){func(a *authorization) { a.CredentialID = "bad" }, func(a *authorization) { a.OrganizationID = "bad" }, func(a *authorization) { a.ExpiresAt = time.Now().Add(-time.Second) }, func(a *authorization) { a.Grants = nil }, func(a *authorization) { a.Grants = []grant{{first}, {first}} }, func(a *authorization) { a.Grants = []grant{{"bad"}} }, func(a *authorization) { a.Grants = make([]grant, 65) }, func(a *authorization) { a.BoxID = "" }} {
+ a := active()
+ mutate(&a)
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(a) }))
+ c, _ := newClient(s.URL + "/introspect")
+ _, err := c.consume(context.Background(), "x", "r")
+ s.Close()
+ if err == nil {
+ t.Fatal("invalid active reply accepted")
+ }
+ }
+}
+func TestClientNoRetriesRedirectsAndTimeout(t *testing.T) {
+ for _, status := range []int{500, 301, 302, 307, 308} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ calls := 0
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.Header().Set("Location", "/redirect")
+ w.WriteHeader(status)
+ }))
+ defer s.Close()
+ c, _ := newClient(s.URL + "/introspect")
+ if _, err := c.consume(context.Background(), "x", "r"); err == nil || calls != 1 {
+ t.Fatalf("calls %d error %v", calls, err)
+ }
+ })
+ }
+ var calls atomic.Int32
+ release := make(chan struct{})
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); <-release }))
+ defer func() { close(release); s.Close() }()
+ c, _ := newClient(s.URL + "/introspect")
+ if c.http.Timeout != 3*time.Second {
+ t.Fatal("wrong timeout")
+ }
+ c.http.Timeout = 20 * time.Millisecond
+ if _, err := c.consume(context.Background(), "x", "r"); err == nil || calls.Load() != 1 {
+ t.Fatalf("timeout calls %d, err %v", calls.Load(), err)
+ }
+}
+func TestEndpointValidation(t *testing.T) {
+ for _, endpoint := range []string{"", ":bad", "file:///x", "http://user:pass@host", "https://host/?token=x", "https://host/#fragment"} {
+ if _, err := newClient(endpoint); err == nil {
+ t.Fatal("accepted", endpoint)
+ }
+ }
+}
+
+func TestEndpointTransportSecurity(t *testing.T) {
+ for _, endpoint := range []string{"http://api-internal/introspect", "http://192.0.2.1/introspect", "http://[2001:db8::1]/introspect", "http://localhost/introspect", "http://127.0.0.1.example.com/introspect"} {
+ if _, err := newClient(endpoint); err == nil {
+ t.Errorf("accepted plaintext endpoint %s", endpoint)
+ }
+ }
+ for _, endpoint := range []string{"https://api-internal/introspect", "http://127.0.0.1/introspect", "http://[::1]/introspect"} {
+ if _, err := newClient(endpoint); err != nil {
+ t.Errorf("rejected secure or literal loopback endpoint %s: %v", endpoint, err)
+ }
+ }
+}
+
+func TestResponseSizeBoundary(t *testing.T) {
+ for _, size := range []int{65536, 65537} {
+ body := `{"active":false}`
+ body += strings.Repeat(" ", size-len(body))
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, body) }))
+ c, _ := newClient(s.URL + "/introspect")
+ _, err := c.consume(context.Background(), "x", "r")
+ s.Close()
+ if (err == nil) != (size == 65536) {
+ t.Fatalf("size %d error %v", size, err)
+ }
+ }
+}
diff --git a/apps/secret-server/internal/fetch/handler.go b/apps/secret-server/internal/fetch/handler.go
new file mode 100644
index 000000000..edab345a9
--- /dev/null
+++ b/apps/secret-server/internal/fetch/handler.go
@@ -0,0 +1,211 @@
+// Package fetch redeems runner-bound credentials for authorized secret values.
+package fetch
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "sync/atomic"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/attest"
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+// Handler is mounted at /internal/v1/secrets/fetch only for the fetch and all roles.
+// The caller owns the pool, startup key verification and verifier configuration.
+type Handler struct {
+ verifier attest.Verifier
+ cipher *encryption.Cipher
+ api *apiClient
+ store store
+ logger *slog.Logger
+ slots, auditSlots chan struct{}
+ auditFailures atomic.Uint64
+}
+
+// New validates dependencies and the full internal introspection endpoint URL.
+func New(pool *pgxpool.Pool, cipher *encryption.Cipher, verifier attest.Verifier, endpoint string, logger *slog.Logger) (*Handler, error) {
+ if pool == nil || cipher == nil || verifier == nil || logger == nil {
+ return nil, errors.New("fetch dependencies are required")
+ }
+ client, err := newClient(endpoint)
+ if err != nil {
+ return nil, err
+ }
+ return &Handler{verifier: verifier, cipher: cipher, api: client, store: postgres{pool}, logger: logger, slots: make(chan struct{}, 16), auditSlots: make(chan struct{}, 16)}, nil
+}
+
+// AuditFailures is a monotonic counter for failed or admission-rejected audit rows.
+func (h *Handler) AuditFailures() uint64 { return h.auditFailures.Load() }
+
+type value struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ Hosts []string `json:"hosts"`
+ Headers map[string]string `json:"headers"`
+ Placeholder string `json:"placeholder"`
+}
+
+func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ a := audit{Result: "credential_invalid"}
+ start := time.Now()
+ defer func() {
+ h.logger.Info("secret fetch", "runner_id", a.RunnerID, "credential_id", a.CredentialID, "box_id", a.BoxID, "result", a.Result, "latency", time.Since(start))
+ }()
+ fail := func(status int, code, result, name string) {
+ a.Result = result
+ h.record(r.Context(), a)
+ problem(w, status, code, name)
+ }
+ if r.URL.Path != "/internal/v1/secrets/fetch" {
+ fail(404, "not_found", "credential_invalid", "")
+ return
+ }
+ if r.Method != http.MethodPost {
+ w.Header().Set("Allow", "POST")
+ fail(405, "method_not_allowed", "credential_invalid", "")
+ return
+ }
+ select {
+ case h.slots <- struct{}{}:
+ defer func() { <-h.slots }()
+ default:
+ fail(503, "store_unavailable", "store_unavailable", "")
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+ runner, err := h.verifier.Verify(ctx, r.Header)
+ if err != nil || runner == "" {
+ if err != nil && !errors.Is(err, attest.ErrInvalidProof) {
+ fail(503, "attestation_unavailable", "attestation_unavailable", "")
+ } else {
+ fail(401, "attestation_failed", "attestation_failed", "")
+ }
+ return
+ }
+ a.RunnerID = string(runner)
+ var request struct {
+ Credential string `json:"credential"`
+ }
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
+ decoder.DisallowUnknownFields()
+ if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF || request.Credential == "" {
+ fail(401, "credential_invalid", "credential_invalid", "")
+ return
+ }
+ auth, err := h.api.consume(ctx, request.Credential, string(runner))
+ if err != nil {
+ fail(503, "api_unavailable", "api_unavailable", "")
+ return
+ }
+ if !auth.Active {
+ fail(401, "credential_invalid", "credential_invalid", "")
+ return
+ }
+ a.CredentialID = auth.CredentialID
+ a.BoxID = auth.BoxID
+ if auth.RunnerID != string(runner) {
+ fail(401, "credential_invalid", "runner_mismatch", "")
+ return
+ }
+ ids := make([]string, len(auth.Grants))
+ for i, g := range auth.Grants {
+ ids[i] = g.SecretID
+ }
+ secrets, err := h.store.load(ctx, ids)
+ if err != nil {
+ fail(503, "store_unavailable", "store_unavailable", "")
+ return
+ }
+ for _, id := range ids {
+ a.SecretID = id
+ s, ok := secrets[id]
+ if !ok {
+ fail(409, "secret_unavailable", "not_found", "")
+ return
+ }
+ if s.OrganizationID != auth.OrganizationID || (s.Scope == "org" && s.BoxID != nil) || (s.Scope == "box" && (s.BoxID == nil || *s.BoxID != auth.BoxID)) || (s.Scope != "org" && s.Scope != "box") {
+ fail(401, "credential_invalid", "scope_mismatch", "")
+ return
+ }
+ if s.DisabledAt != nil {
+ fail(409, "secret_unavailable", "disabled", s.Name)
+ return
+ }
+ }
+ response := struct {
+ BoxID string `json:"box_id"`
+ Secrets []value `json:"secrets"`
+ }{auth.BoxID, make([]value, 0, len(ids))}
+ for _, id := range ids {
+ a.SecretID = id
+ s := secrets[id]
+ envelope, err := s.envelope()
+ if err != nil {
+ fail(503, "decrypt_failed", "decrypt_failed", "")
+ return
+ }
+ plaintext, err := h.cipher.Decrypt(ctx, encryption.SecretContext{OrganizationID: s.OrganizationID, SecretID: s.ID, Version: 1, Hosts: s.Hosts, Headers: s.Headers}, envelope)
+ if err != nil {
+ fail(503, "decrypt_failed", "decrypt_failed", "")
+ return
+ }
+ response.Secrets = append(response.Secrets, value{s.Name, string(plaintext), s.Hosts, s.Headers, s.Placeholder})
+ clear(plaintext)
+ }
+ body, err := json.Marshal(response)
+ if err != nil || len(body) > 8<<20 || ctx.Err() != nil {
+ fail(503, "store_unavailable", "store_unavailable", "")
+ return
+ }
+ a.Result = "ok"
+ a.SecretID = ""
+ entries := make([]audit, 0, max(1, len(ids)))
+ if len(ids) == 0 {
+ entries = append(entries, a)
+ }
+ for _, id := range ids {
+ a.SecretID = id
+ entries = append(entries, a)
+ }
+ h.record(ctx, entries...)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write(body)
+}
+
+func (h *Handler) record(ctx context.Context, entries ...audit) {
+ select {
+ case h.auditSlots <- struct{}{}:
+ defer func() { <-h.auditSlots }()
+ default:
+ h.auditFailure(len(entries))
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 100*time.Millisecond)
+ defer cancel()
+ if h.store.record(ctx, entries...) != nil {
+ h.auditFailure(len(entries))
+ }
+}
+func (h *Handler) auditFailure(count int) {
+ h.auditFailures.Add(uint64(count))
+ h.logger.Error("secret fetch audit write failed")
+}
+func problem(w http.ResponseWriter, status int, code, name string) {
+ w.Header().Set("Content-Type", "application/problem+json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(struct {
+ Type string `json:"type"`
+ Title string `json:"title"`
+ Status int `json:"status"`
+ Code string `json:"code"`
+ Name string `json:"name,omitempty"`
+ }{"about:blank", http.StatusText(status), status, code, name})
+}
diff --git a/apps/secret-server/internal/fetch/handler_test.go b/apps/secret-server/internal/fetch/handler_test.go
new file mode 100644
index 000000000..4f777b2b2
--- /dev/null
+++ b/apps/secret-server/internal/fetch/handler_test.go
@@ -0,0 +1,398 @@
+package fetch
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/attest"
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+)
+
+const org = "11111111-1111-1111-1111-111111111111"
+const first = "22222222-2222-2222-2222-222222222222"
+const second = "33333333-3333-3333-3333-333333333333"
+const credential = "44444444-4444-4444-4444-444444444444"
+
+type verifierFunc func(context.Context, http.Header) (attest.RunnerID, error)
+
+func (f verifierFunc) Verify(c context.Context, h http.Header) (attest.RunnerID, error) {
+ return f(c, h)
+}
+
+type memoryStore struct {
+ rows map[string]secret
+ audits []audit
+ loadErr, auditErr error
+ mu sync.Mutex
+ loads int
+}
+
+func (s *memoryStore) load(context.Context, []string) (map[string]secret, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.loads++
+ return s.rows, s.loadErr
+}
+func (s *memoryStore) record(ctx context.Context, entries ...audit) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.audits = append(s.audits, entries...)
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ return s.auditErr
+}
+func active() authorization {
+ return authorization{true, credential, "runner-a", "box-a", org, []grant{{first}, {second}}, time.Now().Add(time.Minute)}
+}
+func cipherForTest(t *testing.T) *encryption.Cipher {
+ t.Helper()
+ p, e := encryption.NewEnvKeyProvider("env:test", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)))
+ if e != nil {
+ t.Fatal(e)
+ }
+ c, e := encryption.NewCipher(p)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return c
+}
+func encrypted(t *testing.T, c *encryption.Cipher, id string) secret {
+ t.Helper()
+ s := secret{ID: id, OrganizationID: org, Scope: "org", Name: "KEY_" + id[:1], Hosts: []string{"api.example.com"}, Headers: map[string]string{"Authorization": "Bearer {value}"}, Placeholder: "placeholder-marker"}
+ e, err := c.Encrypt(context.Background(), encryption.SecretContext{OrganizationID: org, SecretID: id, Version: 1, Hosts: s.Hosts, Headers: s.Headers}, []byte("plaintext-marker-"+id))
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.Ciphertext = `\x` + hex.EncodeToString(e.Ciphertext)
+ s.EncryptedDEK = `\x` + hex.EncodeToString(e.WrappedDEK.Ciphertext)
+ s.KeyID = e.WrappedDEK.KeyID
+ return s
+}
+func setup(t *testing.T, serve http.HandlerFunc) (*Handler, *memoryStore, *bytes.Buffer) {
+ t.Helper()
+ api := httptest.NewServer(serve)
+ t.Cleanup(api.Close)
+ client, e := newClient(api.URL + "/internal/v1/credentials/introspect")
+ if e != nil {
+ t.Fatal(e)
+ }
+ c := cipherForTest(t)
+ s := &memoryStore{rows: map[string]secret{first: encrypted(t, c, first), second: encrypted(t, c, second)}}
+ log := new(bytes.Buffer)
+ v := verifierFunc(func(_ context.Context, h http.Header) (attest.RunnerID, error) {
+ if h.Get("X-Proof") != "proof-marker" {
+ return "", attest.ErrInvalidProof
+ }
+ return "runner-a", nil
+ })
+ return &Handler{verifier: v, cipher: c, api: client, store: s, logger: slog.New(slog.NewTextHandler(log, nil)), slots: make(chan struct{}, 16), auditSlots: make(chan struct{}, 16)}, s, log
+}
+func call(h http.Handler, body string, proof bool) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", "/internal/v1/secrets/fetch", strings.NewReader(body))
+ if proof {
+ r.Header.Set("X-Proof", "proof-marker")
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ return w
+}
+
+const requestBody = `{"credential":"credential-marker"}`
+
+func TestFetchOutcomes(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ mutate func(*Handler, *memoryStore, *authorization)
+ status int
+ code, result string
+ }{
+ {"success", func(*Handler, *memoryStore, *authorization) {}, 200, "", "ok"},
+ {"empty", func(_ *Handler, _ *memoryStore, a *authorization) { a.Grants = []grant{} }, 200, "", "ok"},
+ {"inactive", func(_ *Handler, _ *memoryStore, a *authorization) { *a = authorization{} }, 401, "credential_invalid", "credential_invalid"},
+ {"runner", func(_ *Handler, _ *memoryStore, a *authorization) { a.RunnerID = "other" }, 401, "credential_invalid", "runner_mismatch"},
+ {"org", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ r.OrganizationID = first
+ s.rows[second] = r
+ }, 401, "credential_invalid", "scope_mismatch"},
+ {"box", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ r.Scope = "box"
+ box := "other"
+ r.BoxID = &box
+ s.rows[second] = r
+ }, 401, "credential_invalid", "scope_mismatch"},
+ {"allowed_box", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ r.Scope = "box"
+ box := "box-a"
+ r.BoxID = &box
+ s.rows[second] = r
+ }, 200, "", "ok"},
+ {"missing", func(_ *Handler, s *memoryStore, _ *authorization) { delete(s.rows, second) }, 409, "secret_unavailable", "not_found"},
+ {"disabled", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ now := "now"
+ r.DisabledAt = &now
+ s.rows[second] = r
+ }, 409, "secret_unavailable", "disabled"},
+ {"tampered_second", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ r.Hosts = []string{"evil.example.com"}
+ s.rows[second] = r
+ }, 503, "decrypt_failed", "decrypt_failed"},
+ {"bad_envelope", func(_ *Handler, s *memoryStore, _ *authorization) {
+ r := s.rows[second]
+ r.Ciphertext = "invalid"
+ s.rows[second] = r
+ }, 503, "decrypt_failed", "decrypt_failed"},
+ {"database", func(_ *Handler, s *memoryStore, _ *authorization) { s.loadErr = errors.New("private-db-marker") }, 503, "store_unavailable", "store_unavailable"},
+ {"audit_failure", func(_ *Handler, s *memoryStore, _ *authorization) { s.auditErr = errors.New("private-db-marker") }, 200, "", "ok"},
+ {"proof_invalid", func(h *Handler, _ *memoryStore, _ *authorization) {
+ h.verifier = verifierFunc(func(context.Context, http.Header) (attest.RunnerID, error) { return "", attest.ErrInvalidProof })
+ }, 401, "attestation_failed", "attestation_failed"},
+ {"verifier_outage", func(h *Handler, _ *memoryStore, _ *authorization) {
+ h.verifier = verifierFunc(func(context.Context, http.Header) (attest.RunnerID, error) { return "", errors.New("proof-marker") })
+ }, 503, "attestation_unavailable", "attestation_unavailable"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ a := active()
+ calls := 0
+ h, s, logs := setup(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ var body map[string]string
+ if json.NewDecoder(r.Body).Decode(&body) != nil || body["token"] != "credential-marker" || body["runner_id"] != "runner-a" {
+ t.Error("invalid introspection request")
+ }
+ _ = json.NewEncoder(w).Encode(a)
+ })
+ tc.mutate(h, s, &a)
+ w := call(h, requestBody, true)
+ if w.Code != tc.status {
+ t.Fatalf("status %d: %s", w.Code, w.Body)
+ }
+ if w.Header().Get("Cache-Control") != "no-store" {
+ t.Error("cacheable response")
+ }
+ if tc.status != 200 {
+ var p map[string]any
+ _ = json.Unmarshal(w.Body.Bytes(), &p)
+ if p["code"] != tc.code {
+ t.Errorf("problem: %v", p)
+ }
+ if strings.Contains(w.Body.String(), "plaintext-marker") {
+ t.Fatal("partial plaintext")
+ }
+ } else {
+ var body struct {
+ Secrets []value `json:"secrets"`
+ }
+ if json.Unmarshal(w.Body.Bytes(), &body) != nil || len(body.Secrets) != len(a.Grants) {
+ t.Fatal("wrong response")
+ }
+ for _, v := range body.Secrets {
+ if !strings.HasPrefix(v.Value, "plaintext-marker-") {
+ t.Fatal("wrong plaintext")
+ }
+ }
+ }
+ if strings.Contains(w.Body.String(), "version") {
+ t.Error("version in response")
+ }
+ if len(s.audits) == 0 || s.audits[0].Result != tc.result {
+ t.Fatalf("audit: %+v", s.audits)
+ }
+ if tc.name == "proof_invalid" || tc.name == "verifier_outage" {
+ if calls != 0 || s.audits[0].RunnerID != "" {
+ t.Error("failed identity reached API")
+ }
+ }
+ if tc.name == "runner" && s.loads != 0 {
+ t.Error("runner mismatch reached storage")
+ }
+ if tc.name == "audit_failure" && h.AuditFailures() != 2 {
+ t.Error("missing audit counter")
+ }
+ for _, marker := range []string{"plaintext-marker", "credential-marker", "proof-marker", "placeholder-marker", "private-db-marker"} {
+ if strings.Contains(logs.String(), marker) {
+ t.Errorf("log leaked %s", marker)
+ }
+ }
+ })
+ }
+}
+func TestSingleUseAndFailureStillConsume(t *testing.T) {
+ for _, tamper := range []bool{false, true} {
+ t.Run(map[bool]string{false: "success", true: "decrypt_failure"}[tamper], func(t *testing.T) {
+ var used atomic.Bool
+ h, s, _ := setup(t, func(w http.ResponseWriter, r *http.Request) {
+ if used.Swap(true) {
+ _, _ = io.WriteString(w, `{"active":false}`)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(active())
+ })
+ if tamper {
+ r := s.rows[second]
+ r.Hosts = []string{"wrong"}
+ s.rows[second] = r
+ }
+ w := call(h, requestBody, true)
+ if (!tamper && w.Code != 200) || (tamper && w.Code != 503) {
+ t.Fatal(w.Code)
+ }
+ w = call(h, requestBody, true)
+ if w.Code != 401 {
+ t.Fatal("replay accepted", w.Code)
+ }
+ })
+ }
+}
+func TestMalformedRequestsAndMissingProof(t *testing.T) {
+ calls := 0
+ h, _, _ := setup(t, func(http.ResponseWriter, *http.Request) { calls++ })
+ for _, b := range []string{"", `{}`, `null`, `{"credential":"x","runner_id":"forged"}`, requestBody + `{}`, `{"credential":"` + strings.Repeat("x", 4096) + `"}`} {
+ if w := call(h, b, true); w.Code != 401 {
+ t.Errorf("invalid request accepted %d", w.Code)
+ }
+ }
+ if w := call(h, requestBody, false); w.Code != 401 {
+ t.Fatal(w.Code)
+ }
+ if calls != 0 {
+ t.Fatal("invalid input consumed credential")
+ }
+}
+func TestSaturationAndAuditAdmission(t *testing.T) {
+ h, s, _ := setup(t, func(http.ResponseWriter, *http.Request) { t.Error("API called") })
+ for range cap(h.slots) {
+ h.slots <- struct{}{}
+ }
+ if w := call(h, requestBody, true); w.Code != 503 || s.audits[0].Result != "store_unavailable" {
+ t.Fatal(w.Code)
+ }
+ for range cap(h.auditSlots) {
+ h.auditSlots <- struct{}{}
+ }
+ if w := call(h, requestBody, true); w.Code != 503 || h.AuditFailures() != 1 {
+ t.Fatal("unbounded audit admission")
+ }
+}
+func TestAuditSurvivesCancellation(t *testing.T) {
+ h, s, _ := setup(t, func(http.ResponseWriter, *http.Request) {})
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ h.record(ctx, audit{Result: "credential_invalid"})
+ if len(s.audits) != 1 || h.AuditFailures() != 0 {
+ t.Fatal("audit inherited cancellation")
+ }
+}
+
+func TestAllOwnershipChecksPrecedeDecrypt(t *testing.T) {
+ h, s, _ := setup(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(active()) })
+ r := s.rows[first]
+ r.Ciphertext = "invalid"
+ s.rows[first] = r
+ r = s.rows[second]
+ r.OrganizationID = first
+ s.rows[second] = r
+ w := call(h, requestBody, true)
+ if w.Code != 401 || s.audits[0].Result != "scope_mismatch" {
+ t.Fatalf("decrypted before checking all ownership: %d %+v", w.Code, s.audits)
+ }
+}
+func TestConcurrentSingleUse(t *testing.T) {
+ var used atomic.Bool
+ var calls atomic.Int32
+ h, s, _ := setup(t, func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if used.Swap(true) {
+ _, _ = io.WriteString(w, `{"active":false}`)
+ } else {
+ _ = json.NewEncoder(w).Encode(active())
+ }
+ })
+ h.logger = slog.New(slog.NewTextHandler(io.Discard, nil))
+ start := make(chan struct{})
+ results := make(chan int, 2)
+ for range 2 {
+ go func() { <-start; results <- call(h, requestBody, true).Code }()
+ }
+ close(start)
+ a, b := <-results, <-results
+ if !((a == 200 && b == 401) || (a == 401 && b == 200)) || calls.Load() != 2 {
+ t.Fatalf("concurrent results %d %d", a, b)
+ }
+ if len(s.audits) != 3 {
+ t.Fatalf("audit count %d", len(s.audits))
+ }
+}
+func TestRoutesAndConstructor(t *testing.T) {
+ h, _, _ := setup(t, func(http.ResponseWriter, *http.Request) { t.Error("API called") })
+ for _, tc := range []struct {
+ method, path string
+ status int
+ }{{"GET", "/internal/v1/secrets/fetch", 405}, {"POST", "/other", 404}} {
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
+ if w.Code != tc.status {
+ t.Fatal(w.Code)
+ }
+ }
+ if _, err := New(nil, h.cipher, h.verifier, "http://localhost", h.logger); err == nil {
+ t.Fatal("nil pool accepted")
+ }
+}
+
+func TestAggregateResponseLimit(t *testing.T) {
+ a := active()
+ a.Grants = nil
+ h, s, _ := setup(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(a) })
+ for i := range 64 {
+ id := fmt.Sprintf("%08x-0000-0000-0000-000000000000", i)
+ row := encrypted(t, h.cipher, id)
+ envelope, err := h.cipher.Encrypt(context.Background(), encryption.SecretContext{OrganizationID: org, SecretID: id, Version: 1, Hosts: row.Hosts, Headers: row.Headers}, bytes.Repeat([]byte{1}, 60000))
+ if err != nil {
+ t.Fatal(err)
+ }
+ row.Ciphertext = `\x` + hex.EncodeToString(envelope.Ciphertext)
+ row.EncryptedDEK = `\x` + hex.EncodeToString(envelope.WrappedDEK.Ciphertext)
+ s.rows[id] = row
+ a.Grants = append(a.Grants, grant{id})
+ }
+ w := call(h, requestBody, true)
+ if w.Code != 503 || strings.Contains(w.Body.String(), "value") || s.audits[0].Result != "store_unavailable" {
+ t.Fatalf("oversized response: %d %s", w.Code, w.Body)
+ }
+}
+func TestRequestSizeBoundary(t *testing.T) {
+ calls := 0
+ h, _, _ := setup(t, func(w http.ResponseWriter, r *http.Request) { calls++; _, _ = io.WriteString(w, `{"active":false}`) })
+ for _, size := range []int{4096, 4097} {
+ before := calls
+ body := requestBody + strings.Repeat(" ", size-len(requestBody))
+ w := call(h, body, true)
+ if w.Code != 401 {
+ t.Fatal(w.Code)
+ }
+ if (calls > before) != (size == 4096) {
+ t.Fatalf("size %d API calls %d", size, calls-before)
+ }
+ }
+}
diff --git a/apps/secret-server/internal/fetch/store.go b/apps/secret-server/internal/fetch/store.go
new file mode 100644
index 000000000..0ff253b84
--- /dev/null
+++ b/apps/secret-server/internal/fetch/store.go
@@ -0,0 +1,88 @@
+package fetch
+
+import (
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+type secret struct {
+ ID string `json:"id"`
+ OrganizationID string `json:"organization_id"`
+ Scope string `json:"scope"`
+ BoxID *string `json:"box_id"`
+ Name string `json:"name"`
+ Hosts []string `json:"hosts"`
+ Headers map[string]string `json:"headers"`
+ Placeholder string `json:"placeholder"`
+ DisabledAt *string `json:"disabled_at"`
+ Ciphertext string `json:"ciphertext"`
+ EncryptedDEK string `json:"encrypted_dek"`
+ KeyID string `json:"key_id"`
+}
+
+type audit struct{ CredentialID, RunnerID, BoxID, SecretID, Result string }
+type store interface {
+ load(context.Context, []string) (map[string]secret, error)
+ record(context.Context, ...audit) error
+}
+type postgres struct{ pool *pgxpool.Pool }
+
+func (p postgres) load(ctx context.Context, ids []string) (map[string]secret, error) {
+ // A 1 MiB write request fits after JSON reformatting and envelope hex encoding.
+ // Bound the entire grant set before transferring any payload to the service.
+ rows, err := p.pool.Query(ctx, `WITH checked AS MATERIALIZED (
+ SELECT CASE WHEN octet_length(ciphertext)<=65565 AND octet_length(encrypted_dek)<=65536
+ AND octet_length(row_to_json(s)::text)<=2097152 THEN row_to_json(s) END AS payload
+ FROM secret s WHERE id=ANY($1::uuid[]))
+ SELECT CASE WHEN count(payload) OVER () = count(*) OVER ()
+ AND sum(octet_length(payload::text)) OVER ()<=12582912 THEN payload END FROM checked`, ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ result := make(map[string]secret, len(ids))
+ for rows.Next() {
+ var data []byte
+ if err := rows.Scan(&data); err != nil {
+ return nil, err
+ }
+ if len(data) == 0 {
+ return nil, errors.New("stored secret exceeds size limit")
+ }
+ var s secret
+ if err := json.Unmarshal(data, &s); err != nil {
+ return nil, err
+ }
+ result[s.ID] = s
+ }
+ return result, rows.Err()
+}
+func (p postgres) record(ctx context.Context, entries ...audit) error {
+ body, _ := json.Marshal(entries)
+ _, err := p.pool.Exec(ctx, `INSERT INTO secret_access_log (credential_id,runner_id,box_id,secret_id,result)
+ SELECT NULLIF(a->>'CredentialID','')::uuid,NULLIF(a->>'RunnerID',''),NULLIF(a->>'BoxID',''),
+ NULLIF(a->>'SecretID','')::uuid,a->>'Result' FROM jsonb_array_elements($1::jsonb) a`, body)
+ return err
+}
+func (s secret) envelope() (encryption.Envelope, error) {
+ var e encryption.Envelope
+ decode := func(s string) ([]byte, error) {
+ if len(s) < 2 || s[:2] != `\x` {
+ return nil, errors.New("invalid stored envelope")
+ }
+ return hex.DecodeString(s[2:])
+ }
+ var err error
+ e.Ciphertext, err = decode(s.Ciphertext)
+ if err != nil {
+ return e, err
+ }
+ e.WrappedDEK.KeyID = s.KeyID
+ e.WrappedDEK.Ciphertext, err = decode(s.EncryptedDEK)
+ return e, err
+}
diff --git a/apps/secret-server/internal/fetch/store_test.go b/apps/secret-server/internal/fetch/store_test.go
new file mode 100644
index 000000000..139c86213
--- /dev/null
+++ b/apps/secret-server/internal/fetch/store_test.go
@@ -0,0 +1,250 @@
+package fetch
+
+import (
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/attest"
+
+ "github.com/boxlite-ai/secret-server/internal/database"
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/boxlite-ai/secret-server/internal/testdb"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestIntegration(t *testing.T) {
+ dsn := os.Getenv("SECRET_TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("set SECRET_TEST_DATABASE_URL")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ admin, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(admin.Close)
+ _, dsn = testdb.Create(t, ctx, admin, dsn, false)
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ if err = database.Migrate(ctx, pool); err != nil {
+ t.Fatal(err)
+ }
+ c := cipherForTest(t)
+ insert := func(s secret) {
+ t.Helper()
+ e, err := s.envelope()
+ if err != nil {
+ t.Fatal(err)
+ }
+ headers, _ := json.Marshal(s.Headers)
+ _, err = pool.Exec(ctx, `INSERT INTO secret(id,organization_id,scope,box_id,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by)
+ VALUES($1,$2,$3,$4,$5,$5,$6,$7,$8,$9,$10,$11,'test')`, s.ID, s.OrganizationID, s.Scope, s.BoxID, s.Name, e.Ciphertext, e.WrappedDEK.Ciphertext, e.WrappedDEK.KeyID, s.Hosts, headers, s.Placeholder)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ insert(encrypted(t, c, first))
+ insert(encrypted(t, c, second))
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(active()) }))
+ defer api.Close()
+ v := verifierFunc(func(context.Context, http.Header) (attest.RunnerID, error) { return "runner-a", nil })
+ h, err := New(pool, c, v, api.URL+"/introspect", slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(h)
+ defer server.Close()
+ resp, err := http.Post(server.URL+"/internal/v1/secrets/fetch", "application/json", strings.NewReader(requestBody))
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != 200 || !strings.Contains(string(data), "plaintext-marker") {
+ t.Fatalf("fetch %d %s", resp.StatusCode, data)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM secret_access_log WHERE result='ok'").Scan(&count); err != nil || count != 2 {
+ t.Fatalf("audit count %d %v", count, err)
+ }
+ t.Run("audit batch is atomic", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, `CREATE FUNCTION reject_second_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.secret_id = '33333333-3333-3333-3333-333333333333'::uuid THEN RAISE EXCEPTION 'rejected audit'; END IF; RETURN NEW; END $$`); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, err := pool.Exec(ctx, "DROP FUNCTION reject_second_audit() CASCADE")
+ if err != nil {
+ t.Error(err)
+ }
+ })
+ if _, err := pool.Exec(ctx, "CREATE TRIGGER reject_second_audit BEFORE INSERT ON secret_access_log FOR EACH ROW EXECUTE FUNCTION reject_second_audit()"); err != nil {
+ t.Fatal(err)
+ }
+ before := h.AuditFailures()
+ h.record(ctx, audit{SecretID: first, Result: "ok"}, audit{SecretID: second, Result: "ok"})
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM secret_access_log WHERE result='ok'").Scan(&count); err != nil || count != 2 {
+ t.Fatalf("partial audit batch persisted: count=%d error=%v", count, err)
+ }
+ if got := h.AuditFailures() - before; got != 2 {
+ t.Fatalf("failed audit rows=%d, want 2", got)
+ }
+ })
+ for _, result := range []string{"api_unavailable", "scope_mismatch", "store_unavailable", "attestation_unavailable"} {
+ if err := h.store.record(ctx, audit{Result: result}); err != nil {
+ t.Fatal(result, err)
+ }
+ }
+ t.Run("real attestation and database ownership boundaries", func(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ selector, err := attest.New(attest.Config{Attestors: []string{"dev"}, Environment: "local", Registry: `{}`}, nil, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i, tc := range []struct {
+ name, organization, box string
+ status int
+ result string
+ }{
+ {"organization allowed", org, "", 200, "ok"},
+ {"box allowed", org, "box-a", 200, "ok"},
+ {"foreign organization", second, "", 401, "scope_mismatch"},
+ {"foreign box", org, "box-b", 401, "scope_mismatch"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ id := fmt.Sprintf("55555555-5555-5555-5555-%012d", i)
+ row := encrypted(t, c, id)
+ row.Name = fmt.Sprintf("BOUNDARY_%d", i)
+ row.OrganizationID = tc.organization
+ envelope, err := c.Encrypt(ctx, encryption.SecretContext{OrganizationID: row.OrganizationID, SecretID: id, Version: 1, Hosts: row.Hosts, Headers: row.Headers}, []byte("plaintext-marker"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ row.Ciphertext = `\x` + hex.EncodeToString(envelope.Ciphertext)
+ row.EncryptedDEK = `\x` + hex.EncodeToString(envelope.WrappedDEK.Ciphertext)
+ if tc.box != "" {
+ row.Scope = "box"
+ row.BoxID = &tc.box
+ }
+ insert(row)
+ auth := active()
+ auth.Grants = []grant{{id}}
+ var calls atomic.Int32
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ var request map[string]string
+ if json.NewDecoder(r.Body).Decode(&request) != nil || request["runner_id"] != "runner-a" {
+ t.Error("API did not receive attested runner")
+ }
+ _ = json.NewEncoder(w).Encode(auth)
+ }))
+ defer api.Close()
+ handler, err := New(pool, c, selector, api.URL+"/introspect", logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := httptest.NewServer(handler)
+ defer server.Close()
+ for _, proof := range []bool{false, true} {
+ req, err := http.NewRequest(http.MethodPost, server.URL+"/internal/v1/secrets/fetch", strings.NewReader(requestBody))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if proof {
+ req.Header.Set(attest.DevHeader, "runner-a")
+ }
+ response, err := server.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(response.Body)
+ response.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ status, result := tc.status, tc.result
+ if !proof {
+ status, result = 401, "attestation_failed"
+ if calls.Load() != 0 {
+ t.Fatal("missing proof reached API")
+ }
+ }
+ if response.StatusCode != status {
+ t.Fatalf("status %d, want %d: %s", response.StatusCode, status, body)
+ }
+ if status != 200 && strings.Contains(string(body), "plaintext-marker") {
+ t.Fatal("denied request exposed plaintext")
+ }
+ var stored string
+ if err := pool.QueryRow(ctx, "SELECT result FROM secret_access_log ORDER BY id DESC LIMIT 1").Scan(&stored); err != nil || stored != result {
+ t.Fatalf("audit %s, want %s: %v", stored, result, err)
+ }
+ }
+ if calls.Load() != 1 {
+ t.Fatal("unexpected consumption calls", calls.Load())
+ }
+ })
+ }
+ })
+ if err := h.store.record(ctx, audit{Result: "invalid-result"}); err == nil {
+ t.Fatal("invalid audit result accepted")
+ }
+ t.Run("grant set exceeds read budget", func(t *testing.T) {
+ var ids []string
+ err := pool.QueryRow(ctx, `WITH inserted AS (
+ INSERT INTO secret(organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by)
+ SELECT organization_id,scope,'BUDGET_'||n,'BUDGET_'||n,ciphertext,encrypted_dek,key_id,hosts,headers,repeat('p',1048576),created_by
+ FROM secret CROSS JOIN generate_series(1,12) n WHERE id=$1 RETURNING id
+ ) SELECT array_agg(id::text) FROM inserted`, first).Scan(&ids)
+ if err != nil || len(ids) != 12 {
+ t.Fatalf("create budget fixture: rows=%d error=%v", len(ids), err)
+ }
+ if _, err := h.store.load(ctx, ids[:1]); err != nil {
+ t.Fatalf("individual row did not fit: %v", err)
+ }
+ if rows, err := h.store.load(ctx, ids); err == nil || len(rows) != 0 {
+ t.Fatalf("oversized grant set was not rejected: rows=%d error=%v", len(rows), err)
+ }
+ })
+ _, err = pool.Exec(ctx, "UPDATE secret SET disabled_at=now() WHERE id=$1", second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if w := call(h, requestBody, true); w.Code != 409 || strings.Contains(w.Body.String(), "plaintext-marker") {
+ t.Fatal("disabled secret exposed", w.Code)
+ }
+ // Wrapping fields are mutable for KMS rewrapping; a large wrapping field must
+ // be suppressed before it crosses the database boundary.
+ _, err = pool.Exec(ctx, "UPDATE secret SET encrypted_dek=decode(repeat('ab',131073),'hex') WHERE id=$1", first)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = h.store.load(ctx, []string{first}); err == nil {
+ t.Fatal("oversized row accepted")
+ }
+ if w := call(h, requestBody, true); w.Code != 503 {
+ t.Fatal("oversized row not classified", w.Code)
+ }
+ _, err = pool.Exec(ctx, "DELETE FROM secret WHERE id=$1", second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rows, err := h.store.load(ctx, []string{second})
+ if err != nil || len(rows) != 0 {
+ t.Fatal("absence not distinguished", err)
+ }
+}
diff --git a/apps/secret-server/internal/server/auth_test.go b/apps/secret-server/internal/server/auth_test.go
index 58d69381b..aa38803be 100644
--- a/apps/secret-server/internal/server/auth_test.go
+++ b/apps/secret-server/internal/server/auth_test.go
@@ -40,10 +40,10 @@ func TestFetchRouteVerifierOutage(t *testing.T) {
return "", errors.New("signing-key service unavailable")
})
mux := http.NewServeMux()
- mux.Handle("/internal/v1/fetch", fetchAuth(verifier, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ mux.Handle("/internal/v1/secrets/fetch", fetchAuth(verifier, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
called = true
})))
- request := httptest.NewRequest(http.MethodPost, "/internal/v1/fetch", nil)
+ request := httptest.NewRequest(http.MethodPost, "/internal/v1/secrets/fetch", nil)
request.Header.Set(attest.GCPIITHeader, proof)
response := httptest.NewRecorder()
mux.ServeHTTP(response, request)
diff --git a/apps/secret-server/internal/server/config.go b/apps/secret-server/internal/server/config.go
index 51996d145..50bc8fd1f 100644
--- a/apps/secret-server/internal/server/config.go
+++ b/apps/secret-server/internal/server/config.go
@@ -19,6 +19,7 @@ type Config struct {
Port string
ShutdownTimeout time.Duration
RunnerAttestation attest.Config
+ IntrospectionURL string
}
func LoadConfig() (Config, error) {
@@ -77,6 +78,7 @@ func LoadConfig() (Config, error) {
return c, errors.New("invalid SECRET_SERVER_AUTH_MODE")
}
if c.Role == "fetch" || c.Role == "all" {
+ c.IntrospectionURL = os.Getenv("SECRET_SERVER_INTROSPECTION_URL")
c.RunnerAttestation = attest.Config{
Environment: c.Environment,
Registry: os.Getenv("SECRET_SERVER_RUNNER_REGISTRY"),
diff --git a/apps/secret-server/internal/server/routes_test.go b/apps/secret-server/internal/server/routes_test.go
index ce0b5f97c..a5d06be69 100644
--- a/apps/secret-server/internal/server/routes_test.go
+++ b/apps/secret-server/internal/server/routes_test.go
@@ -11,7 +11,6 @@ import (
"strings"
"testing"
- "github.com/boxlite-ai/secret-server/internal/attest"
"github.com/jackc/pgx/v5/pgconn"
)
@@ -19,17 +18,12 @@ func TestRoutes(t *testing.T) {
for _, role := range []string{"write", "fetch", "all"} {
t.Run(role, func(t *testing.T) {
pingErr := error(nil)
- var runnerVerifier attest.Verifier
+ fetchHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
wantFetch := http.StatusNotFound
if role == "fetch" || role == "all" {
- selector, err := attest.New(attest.Config{Attestors: []string{attest.DevName}, Environment: "local"}, nil, slog.Default())
- if err != nil {
- t.Fatal(err)
- }
- runnerVerifier = selector
- wantFetch = http.StatusUnauthorized
+ wantFetch = http.StatusNoContent
}
- handler := routes(Config{Role: role, AuthMode: "dev", DevToken: "secret"}, func(context.Context) error { return pingErr }, nil, runnerVerifier)
+ handler := routes(Config{Role: role, AuthMode: "dev", DevToken: "secret"}, func(context.Context) error { return pingErr }, nil, fetchHandler)
request := func(path, token string) int {
r := httptest.NewRequest(http.MethodGet, path, nil)
if token != "" {
@@ -52,10 +46,10 @@ func TestRoutes(t *testing.T) {
if got := request("/health", ""); got != 200 {
t.Fatalf("liveness depends on db: %d", got)
}
- if got := request("/internal/v1/fetch", ""); got != wantFetch {
- t.Fatalf("unimplemented fetch: %d", got)
+ if got := request("/internal/v1/secrets/fetch", ""); got != wantFetch {
+ t.Fatalf("fetch route: %d", got)
}
- if got := request("/internal/v1/fetch/child", ""); got != wantFetch {
+ if got := request("/internal/v1/secrets/fetch/child", ""); got != http.StatusNotFound {
t.Fatalf("fetch subtree: %d", got)
}
want := 401
diff --git a/apps/secret-server/internal/server/server.go b/apps/secret-server/internal/server/server.go
index e05058999..fc311b4f4 100644
--- a/apps/secret-server/internal/server/server.go
+++ b/apps/secret-server/internal/server/server.go
@@ -16,6 +16,7 @@ import (
"github.com/boxlite-ai/secret-server/internal/attest"
"github.com/boxlite-ai/secret-server/internal/database"
"github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/boxlite-ai/secret-server/internal/fetch"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"google.golang.org/api/idtoken"
@@ -71,6 +72,9 @@ func newServer(ctx context.Context, c Config, deps startupDependencies) (*Server
return nil, errors.New("invalid runner attestation configuration (check SECRET_SERVER_ATTESTORS, SECRET_SERVER_RUNNER_REGISTRY and gcp_iit settings)")
}
runnerVerifier = selector
+ if err := fetch.ValidateIntrospectionURL(c.IntrospectionURL); err != nil {
+ return nil, fmt.Errorf("invalid SECRET_SERVER_INTROSPECTION_URL: %w", err)
+ }
}
provider, err := encryption.NewEnvKeyProvider(c.KeyID, c.Key)
if err != nil {
@@ -113,13 +117,22 @@ func newServer(ctx context.Context, c Config, deps startupDependencies) (*Server
db.Close()
return nil, errors.New("database initialization failed")
}
+ var fetchHandler http.Handler
+ if runnerVerifier != nil {
+ handler, err := fetch.New(db, cipher, runnerVerifier, c.IntrospectionURL, slog.Default())
+ if err != nil {
+ db.Close()
+ return nil, fmt.Errorf("invalid SECRET_SERVER_INTROSPECTION_URL: %w", err)
+ }
+ fetchHandler = handler
+ }
validator, err := deps.newValidator(ctx)
if err != nil {
db.Close()
return nil, errors.New("token validator initialization failed")
}
s := &Server{config: c, db: db}
- s.http = &http.Server{Addr: net.JoinHostPort("", c.Port), Handler: routes(c, db.Ping, validator.Validate, runnerVerifier), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second}
+ s.http = &http.Server{Addr: net.JoinHostPort("", c.Port), Handler: routes(c, db.Ping, validator.Validate, fetchHandler), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second}
return s, nil
}
@@ -148,17 +161,15 @@ func databaseError(err error) error {
}
}
-func routes(c Config, ping func(context.Context) error, validate validateToken, runnerVerifier attest.Verifier) http.Handler {
+func routes(c Config, ping func(context.Context) error, validate validateToken, fetchHandler http.Handler) http.Handler {
mux := http.NewServeMux()
- // Endpoint implementations are supplied by their respective follow-up work.
- // The fetch path is reserved separately so the write middleware never handles it.
+ // Reserve fetch paths so they never fall through to the write middleware.
notFound := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { problem(w, http.StatusNotFound, "not_found") })
- var fetch http.Handler = notFound
- if runnerVerifier != nil {
- fetch = fetchAuth(runnerVerifier, fetch)
+ if fetchHandler == nil || (c.Role != "fetch" && c.Role != "all") {
+ fetchHandler = notFound
}
- mux.Handle("/internal/v1/fetch", fetch)
- mux.Handle("/internal/v1/fetch/", fetch)
+ mux.Handle("/internal/v1/secrets/fetch", fetchHandler)
+ mux.Handle("/internal/v1/secrets/fetch/", notFound)
if c.Role == "write" || c.Role == "all" {
mux.Handle("/internal/v1/", writeAuth(c, validate, notFound))
}
diff --git a/apps/secret-server/tests/credential-api.cjs b/apps/secret-server/tests/credential-api.cjs
new file mode 100644
index 000000000..24caf4747
--- /dev/null
+++ b/apps/secret-server/tests/credential-api.cjs
@@ -0,0 +1,103 @@
+// Run the actual credential service/controller/migration from the pinned API PR.
+// No API production files are copied into the Secret Server implementation.
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { execFileSync, spawn } = require('node:child_process')
+const { randomUUID } = require('node:crypto')
+require('reflect-metadata')
+const ts = require('typescript')
+const { Test } = require('@nestjs/testing')
+const { DataSource } = require('typeorm')
+const express = require('express')
+
+const apiCommit = 'bc78b36e5dc241bb3d2d7f8522f4f6f546833b40'
+const repository = path.resolve(__dirname, '../../..')
+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'boxlite-credential-api-'))
+const schema = `credential_fetch_${randomUUID().replaceAll('-', '')}`
+let database, app
+
+function source(relative) {
+ const input = execFileSync('git', ['show', `${apiCommit}:apps/api/src/${relative}.ts`], {
+ cwd: repository, encoding: 'utf8', maxBuffer: 1024 * 1024,
+ })
+ const output = ts.transpileModule(input, { compilerOptions: {
+ module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022,
+ experimentalDecorators: true, emitDecoratorMetadata: true,
+ }}).outputText
+ const destination = path.join(temporary, relative + '.js')
+ fs.mkdirSync(path.dirname(destination), { recursive: true })
+ fs.writeFileSync(destination, output)
+ return require(destination)
+}
+
+async function main() {
+ if (!process.env.SECRET_TEST_DATABASE_URL) throw new Error('SECRET_TEST_DATABASE_URL is required')
+ const { SecretCredentialService } = source('box/services/secret-credential.service')
+ const { SecretCredentialController } = source('box/controllers/secret-credential.controller')
+ const { AddSecretCredential1794873600000 } = source('migrations/pre-deploy/1794873600000-add-secret-credential-migration')
+ database = await new DataSource({ type: 'postgres', url: process.env.SECRET_TEST_DATABASE_URL,
+ extra: { options: `-c search_path=${schema}`, connectionTimeoutMillis: 5000 },
+ }).initialize()
+ await database.query(`CREATE SCHEMA "${schema}"`)
+ await database.query(`CREATE TABLE box (
+ id varchar(64) PRIMARY KEY, "runnerId" varchar(64) NOT NULL, "organizationId" uuid NOT NULL,
+ state text NOT NULL DEFAULT 'stopped', "desiredState" text NOT NULL DEFAULT 'stopped'
+ )`)
+ const runner = database.createQueryRunner()
+ try { await new AddSecretCredential1794873600000().up(runner) }
+ finally { await runner.release() }
+ const service = new SecretCredentialService(database)
+ const module = await Test.createTestingModule({
+ controllers: [SecretCredentialController],
+ providers: [{ provide: SecretCredentialService, useValue: service }],
+ }).compile()
+ app = module.createNestApplication({ logger: false })
+ // Test-only issuance uses the production service; it is not an API route proposal.
+ // Keep the fixture parser inside a router so Nest still registers its own
+ // application-wide JSON parser for the production introspection controller.
+ const issuance = express.Router()
+ issuance.use(express.json())
+ issuance.post('/', async (req, res) => {
+ try {
+ const { boxId, runnerId, organizationId } = req.body
+ await database.query('INSERT INTO box(id, "runnerId", "organizationId") VALUES($1, $2, $3) ON CONFLICT DO NOTHING', [boxId, runnerId, organizationId])
+ res.json(await service.issue(req.body))
+ } catch { res.status(500).json({ error: 'test credential issuance failed' }) }
+ })
+ app.use('/__test/issue', issuance)
+ await app.listen(0, '127.0.0.1')
+ const apiURL = await app.getUrl()
+ let passed = false
+ const exit = await new Promise((resolve, reject) => {
+ const child = spawn('make', ['test:apps:secret-server', 'GOTEST_FILTER=-run=TestCredentialAPIIntegration -json -count=1 -timeout=60s'], {
+ cwd: repository, stdio: ['ignore', 'pipe', 'inherit'],
+ env: { ...process.env, SECRET_TEST_CREDENTIAL_API_URL: apiURL },
+ })
+ let pending = ''
+ child.stdout.on('data', (chunk) => {
+ pending += chunk.toString()
+ const lines = pending.split('\n'); pending = lines.pop()
+ for (const line of lines) {
+ let event
+ try { event = JSON.parse(line) } catch { continue }
+ if (event.Output) process.stdout.write(event.Output)
+ if (event.Test === 'TestCredentialAPIIntegration' && event.Action === 'pass') passed = true
+ }
+ })
+ child.once('error', reject)
+ child.once('close', (code) => resolve(code ?? 1))
+ })
+ if (exit !== 0 || !passed) throw new Error('Go credential integration test failed or did not run')
+ console.log(`Credential API integration verified against ${apiCommit}`)
+}
+
+main().catch((error) => { console.error(error.message); process.exitCode = 1 }).finally(async () => {
+ try {
+ await app?.close()
+ if (database?.isInitialized) {
+ await database.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
+ await database.destroy()
+ }
+ } finally { fs.rmSync(temporary, { recursive: true, force: true }) }
+})
diff --git a/make/help.mk b/make/help.mk
index c6f4dc612..4b21d21d5 100644
--- a/make/help.mk
+++ b/make/help.mk
@@ -123,6 +123,7 @@ help:
@echo " make test:apps:github-ci-runner - Run standalone Listener boundary tests"
@echo " make test:apps:proxy - Run proxy unit tests (FILTER=<pattern>)"
@echo " make test:apps:secret-server - Run Secret Server Go tests with the race detector"
+ @echo " make test:apps:secret-server:credential-api - Test the pinned credential API with Secret Server"
@echo " make test:apps:secret-server:integration - Test Secret Server against PostgreSQL (set SECRET_TEST_DATABASE_URL)"
@echo " make test:apps:mdeploy - Type-check and test deployment scripts"
@echo " make test:apps:mbuild - Type-check and test image publication scripts"
diff --git a/make/test.mk b/make/test.mk
index b39d5828c..3fa04d1af 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -829,8 +829,8 @@ PHONY_TARGETS += run\:apps\:secret-server
run\:apps\:secret-server:
@cd apps/secret-server && ENVIRONMENT=local SECRET_SERVER_ROLE=$${SECRET_SERVER_ROLE:-write} SECRET_SERVER_AUTH_MODE=dev SECRET_SERVER_ATTESTORS=$${SECRET_SERVER_ATTESTORS:-dev} GOWORK=off go run ./cmd/secret-server
-SECRET_SERVER_INTEGRATION_PACKAGES := ./internal/database ./internal/server ./internal/testdb ./cmd/secret-server
-SECRET_SERVER_INTEGRATION_TESTS := ^Test(Integration|MigrateSIGTERM|StartupRejectsWrongPersistentKey|PostgresStartupAndReadiness|WrongKeyDoesNotStartServer|RunRejectsOccupiedPort|StartupClosesPoolWhenValidatorConstructionFails|RunBoundsDatabaseCleanup|FetchRuntimeRequiresAttestation|FetchRuntimeRequiresGCPRunnerRegistry|StartupWaitsForMigrationLock|CreateOverridesDatabaseQuery)$$
+SECRET_SERVER_INTEGRATION_PACKAGES := ./internal/database ./internal/fetch ./internal/server ./internal/testdb ./cmd/secret-server
+SECRET_SERVER_INTEGRATION_TESTS := ^Test(Integration|MigrateSIGTERM|StartupRejectsWrongPersistentKey|PostgresStartupAndReadiness|WrongKeyDoesNotStartServer|RunRejectsOccupiedPort|StartupClosesPoolWhenValidatorConstructionFails|RunBoundsDatabaseCleanup|FetchRuntimeRequiresAttestation|FetchRuntimeRequiresGCPRunnerRegistry|FetchStartupRejectsInvalidEndpoint|StartupWaitsForMigrationLock|CreateOverridesDatabaseQuery)$$
PHONY_TARGETS += _require-secret-test-database test\:apps\:secret-server\:integration
_require-secret-test-database:
@test -n "$$SECRET_TEST_DATABASE_URL" || { echo "Set SECRET_TEST_DATABASE_URL to a disposable PostgreSQL server before running Secret Server integration tests." >&2; exit 1; }
@@ -838,6 +838,11 @@ _require-secret-test-database:
test\:apps\:secret-server\:integration: _require-secret-test-database
@cd apps/secret-server && GOWORK=off go test -race -count=1 $(SECRET_SERVER_INTEGRATION_PACKAGES) -run '$(SECRET_SERVER_INTEGRATION_TESTS)'
+PHONY_TARGETS += test\:apps\:secret-server\:credential-api
+test\:apps\:secret-server\:credential-api:
+ @NODE_PATH="$${NODE_PATH:-$(PROJECT_ROOT)/apps/node_modules}" node apps/secret-server/tests/credential-api.cjs
+
+
test\:apps: _ensure-apps-deps dev\:go
@echo "🧪 Running apps workspace test matrix..."
@$(MAKE) test:apps:infra