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): add encrypted storage foundations (#2612)

Jiaqiang Wong5caa12428d11
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 69b2e3746..c3a7cad58 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -601,6 +601,45 @@ jobs:
disable_search: true
fail_ci_if_error: true
+ secret-server-postgres:
+ name: Secret Server PostgreSQL integration
+ needs: changes
+ if: ${{ needs.changes.outputs.go == 'true' }}
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ id-token: write
+ services:
+ postgres:
+ image: postgres:17-alpine
+ env:
+ POSTGRES_USER: boxlite
+ POSTGRES_PASSWORD: boxlite
+ POSTGRES_DB: boxlite
+ ports:
+ - 5432/tcp
+ options: >-
+ --health-cmd "pg_isready -U boxlite -d boxlite"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 12
+ steps:
+ - uses: actions/checkout@v5
+ - uses: ./.github/actions/setup-go
+ - name: Run Secret Server PostgreSQL integration tests
+ env:
+ SECRET_TEST_DATABASE_URL: postgresql://boxlite:[email protected]:${{ job.services.postgres.ports[5432] }}/boxlite
+ run: make coverage:apps:secret-server:integration
+ - name: Upload Secret Server integration coverage to Codecov
+ uses: codecov/codecov-action@v5
+ with:
+ files: target/coverage/secret-server-integration.out
+ flags: go
+ use_oidc: true
+ disable_search: true
+ fail_ci_if_error: true
+
# Go SDK unit tests
go:
name: Go Tests (${{ matrix.platform.target }})
@@ -649,7 +688,7 @@ jobs:
BOXLITE_REQUIRE_NESTED_RUNTIME_TESTS: '1'
run: |
mkdir -p target/coverage/full-go
- for module in go-sdk gvproxy runner image-service; do
+ for module in go-sdk gvproxy runner image-service secret-server; do
cp "target/coverage/$module.out" "target/coverage/full-go/$module.out"
done
sudo chmod a+rw /dev/kvm
@@ -657,7 +696,7 @@ jobs:
make coverage:go GOTEST_FILTER='-count=1 -run NestedVirtualization'
# Both passes instrument this checkout with the same atomic mode.
# Keep the complete suite's blocks as well as the hardware pass.
- for module in go-sdk gvproxy runner image-service; do
+ for module in go-sdk gvproxy runner image-service secret-server; do
report="target/coverage/$module.out"
full="target/coverage/full-go/$module.out"
if [[ "$(head -n 1 "$report")" != 'mode: atomic' || "$(head -n 1 "$full")" != 'mode: atomic' ]]; then
@@ -981,7 +1020,7 @@ jobs:
# NOTE: keep `needs` in sync with the jobs above when adding/removing jobs.
test-conclusion:
name: Test (conclusion)
- needs: [changes, infra, rust, python, node, go, setup, api, dashboard, plugins, guest_artifacts, coverage-empty]
+ needs: [changes, infra, rust, python, node, go, secret-server-postgres, setup, api, dashboard, plugins, guest_artifacts, coverage-empty]
if: ${{ !cancelled() }}
runs-on: ubuntu-latest
permissions: {}
diff --git a/apps/infra/deployment/nested-runtime-coverage.test.ts b/apps/infra/deployment/nested-runtime-coverage.test.ts
index f97611e72..780828040 100644
--- a/apps/infra/deployment/nested-runtime-coverage.test.ts
+++ b/apps/infra/deployment/nested-runtime-coverage.test.ts
@@ -15,7 +15,7 @@ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
const workflow: any = loadYaml(readFileSync(join(root, '.github/workflows/test.yml'), 'utf8'))
const steps = workflow.jobs.go.steps
const qualify = steps.find((step: any) => step.id === 'nested-runtime-coverage')
-const modules = ['go-sdk', 'gvproxy', 'runner', 'image-service']
+const modules = ['go-sdk', 'gvproxy', 'runner', 'image-service', 'secret-server']
test('nested metadata qualification runs after full coverage and only on Linux x64', () => {
assert.ok(qualify)
@@ -52,7 +52,7 @@ fi
[[ "$1" == 'coverage:go' ]]
[[ "$2" == 'GOTEST_FILTER=-count=1 -run NestedVirtualization' ]]
[[ "$BOXLITE_REQUIRE_NESTED_RUNTIME_TESTS" == '1' ]]
-for module in go-sdk gvproxy runner image-service; do
+for module in go-sdk gvproxy runner image-service secret-server; do
printf 'mode: %s\\nexample/%s/source.go:2.1,2.2 1 5\\n' "$NESTED_TEST_FOCUSED_MODE" "$module" > "target/coverage/$module.out"
done
`, { mode: 0o755 })
diff --git a/apps/secret-server/README.md b/apps/secret-server/README.md
index f8b02fb6d..f5de061bc 100644
--- a/apps/secret-server/README.md
+++ b/apps/secret-server/README.md
@@ -4,9 +4,9 @@ The internal encryption package protects secret values and routing policy with p
## Scope
-This Go module contains `internal/encryption`, `internal/server`, and
-`internal/attest` ([runner attestation](#runner-attestation)). It has no server
-entry point, HTTP endpoints, persistence, or deployment resources yet.
+This Go module contains encryption, runner attestation, server configuration,
+write authentication, database initialization, and a migration command. The
+HTTP server entry point, routes, and deployment resources are not yet included.
The existing API encryption service and stored values remain unchanged.
Design: [envelope encryption and KeyProvider](https://github.com/boxlite-ai/boxlite/issues/2495).
@@ -132,6 +132,26 @@ A future change will add a rewrap API or a keyring provider that routes by key I
The envelope format allows rewrapping a DEK without changing the value ciphertext,
but KMS, provider routing, and migration jobs are not implemented here.
+## Database migrations
+
+Set `DATABASE_URL` to the separate PostgreSQL database and run
+`secret-server migrate`. The command applies embedded goose migrations under a
+PostgreSQL session lock, with a two-minute deadline. Run it with an account that
+can create schema objects. Migrations are forward-only; deployed application
+versions must tolerate compatible schema changes. The database must use UTF-8
+server encoding. SIGINT and SIGTERM cancel a running migration.
+
+Before serving requests, the future service must call `database.Initialize`.
+It applies migrations and verifies a durable encrypted canary under a separate
+transaction advisory lock. If the canary is absent but secrets exist, it first
+decrypts an existing secret using AAD version 1.
+
+A wrong key or corrupt ciphertext fails readiness.
+Each secret stores one immutable encrypted value; replace a value by deleting and
+creating a secret with a new ID. Online rotation and version history are not supported.
+
+Canary enrollment uses a read-committed transaction even when the database has a
+different default isolation level.
## Runner attestation
Design: [runner attestation with gcp_iit](https://github.com/boxlite-ai/boxlite/issues/2623).
@@ -192,13 +212,23 @@ Run from the repository root with Go 1.25.4 or newer:
```sh
make test:apps:secret-server
+make test:apps:secret-server:integration
+make coverage:apps:secret-server:integration
make lint:apps:secret-server
make fmt:apps:secret-server
make test:apps:secret-server GOTEST_FILTER='-fuzz=FuzzDecryptEnvelope -fuzztime=5s -parallel=2'
```
-The test target runs with the race detector and `GOWORK=off`, so it needs no VM,
-native SDK library, Node installation, cloud permissions, or external Go modules.
+The unit test target runs with the race detector and `GOWORK=off`. The integration
+target requires infra-local PostgreSQL and permission to create a temporary database.
+It defaults to port 25432; override `SECRET_TEST_DATABASE_URL` when needed. It
+creates a uniquely named database and drops it after the test.
+The coverage target runs the same tests and writes `target/coverage/secret-server-integration.out`.
+Database and command tests share the temporary database setup and cleanup helper.
+It also checks that SIGTERM cancels the migration command while it waits for a lock.
+CI runs the same integration target against a PostgreSQL 17 service on Ubuntu,
+including on draft PRs when Go-related files change. This checks database behavior;
+the infra-local BoxLite VM still needs separate local verification.
The Nx test target delegates to the same make target for workspace test discovery.
Nx caching is disabled for this target because the workspace default inputs exclude
Go test files. Every invocation reaches Go, whose own test cache tracks test changes.
@@ -213,6 +243,14 @@ explicit context checkpoints after cryptographic operations to verify that no
result is released. These checkpoints avoid timing-dependent sleeps.
Fuzzing covers malformed envelope decoding; it is not a cryptographic proof.
+On Linux, CI preserves the full-suite report when it adds nested runtime coverage.
+Database rollback and migration lock cleanup have bounded waits; a connection
+with a failed migration unlock is discarded.
+
+The test helper verifies the database name before tests run, even if the URL includes
+database query parameters. Canary enrollment reads back the persisted ciphertext.
+The test database URL also accepts pgxpool options such as `pool_max_conns`.
+
Go reports statement coverage; Codecov also distinguishes partially covered source
lines, so a passing statement percentage does not imply passing patch coverage.
The uint32 framing overflow guards remain in place; tests do not allocate multi-GiB
diff --git a/apps/secret-server/cmd/secret-server/main.go b/apps/secret-server/cmd/secret-server/main.go
new file mode 100644
index 000000000..de863c634
--- /dev/null
+++ b/apps/secret-server/cmd/secret-server/main.go
@@ -0,0 +1,40 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/database"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func run(ctx context.Context, args []string) error {
+ if len(args) != 1 || args[0] != "migrate" {
+ return fmt.Errorf("usage: secret-server migrate")
+ }
+ url := os.Getenv("DATABASE_URL")
+ if url == "" {
+ return fmt.Errorf("DATABASE_URL is required")
+ }
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
+ defer cancel()
+ pool, err := pgxpool.New(ctx, url)
+ if err != nil {
+ return fmt.Errorf("configure database: invalid DATABASE_URL")
+ }
+ defer pool.Close()
+ return database.Migrate(ctx, pool)
+}
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ if err := run(ctx, os.Args[1:]); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/apps/secret-server/cmd/secret-server/main_test.go b/apps/secret-server/cmd/secret-server/main_test.go
new file mode 100644
index 000000000..35b28d968
--- /dev/null
+++ b/apps/secret-server/cmd/secret-server/main_test.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "context"
+ "net/url"
+ "os"
+ "os/exec"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/testdb"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/pressly/goose/v3/lock"
+)
+
+func TestRunRejectsInvalidArgumentsAndMissingDatabase(t *testing.T) {
+ t.Setenv("DATABASE_URL", "")
+ for _, args := range [][]string{nil, {"unknown"}, {"migrate", "extra"}} {
+ if err := run(context.Background(), args); err == nil || !strings.Contains(err.Error(), "usage") {
+ t.Errorf("run(%v) = %v; want usage error", args, err)
+ }
+ }
+ if err := run(context.Background(), []string{"migrate"}); err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
+ t.Errorf("missing database: %v", err)
+ }
+}
+
+func TestMigrateUsesDatabaseURL(t *testing.T) {
+ t.Setenv("DATABASE_URL", ":invalid:")
+ err := run(context.Background(), []string{"migrate"})
+ if err == nil || !strings.Contains(err.Error(), "configure database") {
+ t.Fatalf("run with DATABASE_URL = %v, want database configuration error", err)
+ }
+}
+
+func TestMigrateRedactsDatabaseURL(t *testing.T) {
+ if os.Getenv("SECRET_TEST_REDACTION_CHILD") == "1" {
+ os.Args = []string{"secret-server", "migrate"}
+ main()
+ return
+ }
+ const password = "redaction-test-password"
+ cmd := exec.Command(os.Args[0], "-test.run=^TestMigrateRedactsDatabaseURL$")
+ cmd.Env = append(os.Environ(), "SECRET_TEST_REDACTION_CHILD=1", "DATABASE_URL=postgresql://user@localhost/db?password="+password+"&sslmode=invalid")
+ output, err := cmd.CombinedOutput()
+ if strings.Contains(string(output), password) {
+ t.Fatalf("database password leaked in command output: %s", output)
+ }
+ if err == nil || !strings.Contains(string(output), "DATABASE_URL") {
+ t.Fatalf("expected DATABASE_URL configuration error, got %v: %s", err, output)
+ }
+}
+
+func TestMigrateSIGTERM(t *testing.T) {
+ if os.Getenv("SECRET_TEST_SIGNAL_CHILD") == "1" {
+ os.Args = []string{"secret-server", "migrate"}
+ main()
+ return
+ }
+ dsn := os.Getenv("SECRET_TEST_DATABASE_URL")
+ if dsn == "" {
+ t.Skip("set SECRET_TEST_DATABASE_URL for signal integration test")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ admin, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(admin.Close)
+ name, databaseURL := testdb.Create(t, ctx, admin, dsn, false)
+ u, err := url.Parse(databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := u.Query()
+ q.Set("application_name", "secret-signal-test")
+ u.RawQuery = q.Encode()
+ pool, err := pgxpool.New(ctx, u.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ held, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Release()
+ if _, err := held.Exec(ctx, "SELECT pg_advisory_lock($1)", lock.DefaultLockID); err != nil {
+ t.Fatal(err)
+ }
+ defer held.Exec(context.Background(), "SELECT pg_advisory_unlock($1)", lock.DefaultLockID)
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMigrateSIGTERM$")
+ cmd.Env = append(os.Environ(), "SECRET_TEST_SIGNAL_CHILD=1", "DATABASE_URL="+u.String())
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if cmd.ProcessState == nil {
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ }
+ }()
+ for {
+ var waiting bool
+ err := admin.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname=$1 AND application_name=$2 AND query LIKE '%pg_try_advisory_lock%')", name, "secret-signal-test").Scan(&waiting)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if waiting {
+ break
+ }
+ select {
+ case <-ctx.Done():
+ t.Fatal("child did not reach migration lock")
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
+ t.Fatal(err)
+ }
+ err = cmd.Wait()
+ exitErr, ok := err.(*exec.ExitError)
+ if !ok || exitErr.ProcessState.Sys().(syscall.WaitStatus).Signaled() {
+ t.Fatalf("SIGTERM terminated process without graceful cancellation: %v", err)
+ }
+}
diff --git a/apps/secret-server/go.mod b/apps/secret-server/go.mod
index c052c7a7c..da226536f 100644
--- a/apps/secret-server/go.mod
+++ b/apps/secret-server/go.mod
@@ -2,6 +2,23 @@ module github.com/boxlite-ai/secret-server
go 1.25.4
+require (
+ github.com/jackc/pgx/v5 v5.7.6
+ github.com/pressly/goose/v3 v3.26.0
+)
+
+require (
+ github.com/jackc/pgpassfile v1.0.0 // indirect
+ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
+ github.com/jackc/puddle/v2 v2.2.2 // indirect
+ github.com/mfridman/interpolate v0.0.2 // indirect
+ github.com/sethvargo/go-retry v0.3.0 // indirect
+ go.uber.org/multierr v1.11.0 // indirect
+ golang.org/x/crypto v0.41.0 // indirect
+ golang.org/x/sync v0.16.0 // indirect
+ golang.org/x/text v0.28.0 // indirect
+)
+
require google.golang.org/api v0.247.0
require (
@@ -16,14 +33,12 @@ require (
github.com/googleapis/gax-go/v2 v2.15.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
- go.opentelemetry.io/otel v1.36.0 // indirect
- go.opentelemetry.io/otel/metric v1.36.0 // indirect
- go.opentelemetry.io/otel/trace v1.36.0 // indirect
- golang.org/x/crypto v0.41.0 // indirect
+ go.opentelemetry.io/otel v1.37.0 // indirect
+ go.opentelemetry.io/otel/metric v1.37.0 // indirect
+ go.opentelemetry.io/otel/trace v1.37.0 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/sys v0.35.0 // indirect
- golang.org/x/text v0.28.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250804133106-a7a43d27e69b // indirect
google.golang.org/grpc v1.74.2 // indirect
google.golang.org/protobuf v1.36.7 // indirect
diff --git a/apps/secret-server/go.sum b/apps/secret-server/go.sum
index aaad3ffc4..8580019b1 100644
--- a/apps/secret-server/go.sum
+++ b/apps/secret-server/go.sum
@@ -4,8 +4,11 @@ cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIi
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
cloud.google.com/go/compute/metadata v0.8.0 h1:HxMRIbao8w17ZX6wBnjhcDkW6lTFpgcaobyVfZWqRLA=
cloud.google.com/go/compute/metadata v0.8.0/go.mod h1:sYOGTp851OV9bOFJ9CH7elVvyzopvWQFNNghtDQ/Biw=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
@@ -25,28 +28,55 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU
github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA=
github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo=
github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc=
+github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
+github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
+github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
+github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
+github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
+github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
+github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
+github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
-github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/pressly/goose/v3 v3.26.0 h1:KJakav68jdH0WDvoAcj8+n61WqOIaPGgH0bJWS6jpmM=
+github.com/pressly/goose/v3 v3.26.0/go.mod h1:4hC1KrritdCxtuFsqgs1R4AU5bWtTAf+cnWvfhf2DNY=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
+github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
+github.com/stretchr/testify v1.11.0 h1:ib4sjIrwZKxE5u/Japgo/7SJV3PvgjGiRNAvTVGqQl8=
+github.com/stretchr/testify v1.11.0/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
-go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg=
-go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E=
-go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE=
-go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs=
+go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
+go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
+go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
+go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs=
go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY=
go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis=
go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4=
-go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w=
-go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA=
+go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
+go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
+golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
+golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
@@ -67,5 +97,15 @@ google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4=
google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM=
google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
+modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
+modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
diff --git a/apps/secret-server/internal/database/canary.go b/apps/secret-server/internal/database/canary.go
new file mode 100644
index 000000000..cf92b2cce
--- /dev/null
+++ b/apps/secret-server/internal/database/canary.go
@@ -0,0 +1,98 @@
+package database
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+var canaryContext = encryption.SecretContext{
+ OrganizationID: "00000000-0000-0000-0000-000000000000",
+ SecretID: "00000000-0000-0000-0000-000000000000",
+ Version: 1, Hosts: []string{"canary"}, Headers: map[string]string{"X-Canary": "canary"},
+}
+
+// Reserve a stable lock distinct from goose's session lock for canary enrollment.
+const canaryLock int64 = 0x626f786c69746501
+const canaryValue = "boxlite secret server key verification v1"
+
+// VerifyKey checks durable ciphertext, creating it on first enrollment.
+func VerifyKey(ctx context.Context, pool *pgxpool.Pool, cipher *encryption.Cipher) error {
+ if cipher == nil {
+ return errors.New("verify key: cipher is nil")
+ }
+ tx, err := pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
+ if err != nil {
+ return fmt.Errorf("begin key verification: %w", err)
+ }
+ defer func() {
+ cleanup, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ _ = tx.Rollback(cleanup)
+ }()
+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", canaryLock); err != nil {
+ return fmt.Errorf("lock key verification: %w", err)
+ }
+ var envelope encryption.Envelope
+ err = tx.QueryRow(ctx, "SELECT ciphertext, encrypted_dek, key_id FROM key_verification_canary WHERE id = 1").Scan(&envelope.Ciphertext, &envelope.WrappedDEK.Ciphertext, &envelope.WrappedDEK.KeyID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ if err := verifyExistingSecret(ctx, tx, cipher); err != nil {
+ return err
+ }
+ envelope, err = cipher.Encrypt(ctx, canaryContext, []byte(canaryValue))
+ if err != nil {
+ return fmt.Errorf("encrypt key canary: %w", err)
+ }
+ _, err = tx.Exec(ctx, "INSERT INTO key_verification_canary (id, ciphertext, encrypted_dek, key_id) VALUES (1, $1, $2, $3)", envelope.Ciphertext, envelope.WrappedDEK.Ciphertext, envelope.WrappedDEK.KeyID)
+ if err != nil {
+ return fmt.Errorf("insert key canary: %w", err)
+ }
+ err = tx.QueryRow(ctx, "SELECT ciphertext, encrypted_dek, key_id FROM key_verification_canary WHERE id = 1").Scan(&envelope.Ciphertext, &envelope.WrappedDEK.Ciphertext, &envelope.WrappedDEK.KeyID)
+ }
+ if err != nil {
+ return fmt.Errorf("read key canary: %w", err)
+ }
+ plaintext, err := cipher.Decrypt(ctx, canaryContext, envelope)
+ if err != nil {
+ return fmt.Errorf("decrypt key canary: %w", err)
+ }
+ defer clear(plaintext)
+ if !bytes.Equal(plaintext, []byte(canaryValue)) {
+ return errors.New("key canary plaintext mismatch")
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return fmt.Errorf("commit key verification: %w", err)
+ }
+ return nil
+}
+
+func verifyExistingSecret(ctx context.Context, tx pgx.Tx, cipher *encryption.Cipher) error {
+ identity := encryption.SecretContext{Version: 1}
+ var headers []byte
+ var envelope encryption.Envelope
+ err := tx.QueryRow(ctx, `SELECT organization_id::text, id::text, hosts, headers,
+ ciphertext, encrypted_dek, key_id FROM secret LIMIT 1`).
+ Scan(&identity.OrganizationID, &identity.SecretID, &identity.Hosts, &headers, &envelope.Ciphertext, &envelope.WrappedDEK.Ciphertext, &envelope.WrappedDEK.KeyID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("read existing secret for key verification: %w", err)
+ }
+ if err := json.Unmarshal(headers, &identity.Headers); err != nil {
+ return fmt.Errorf("decode existing secret headers: %w", err)
+ }
+ plaintext, err := cipher.Decrypt(ctx, identity, envelope)
+ clear(plaintext)
+ if err != nil {
+ return fmt.Errorf("verify existing secret key: %w", err)
+ }
+ return nil
+}
diff --git a/apps/secret-server/internal/database/cleanup_test.go b/apps/secret-server/internal/database/cleanup_test.go
new file mode 100644
index 000000000..473bd6101
--- /dev/null
+++ b/apps/secret-server/internal/database/cleanup_test.go
@@ -0,0 +1,169 @@
+package database
+
+import (
+ "context"
+ "errors"
+ "net"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/boxlite-ai/secret-server/internal/testdb"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/pressly/goose/v3/lock"
+)
+
+// discardReads simulates a server that accepts writes but stops responding.
+type discardReads struct {
+ net.Conn
+ discard *atomic.Bool
+}
+
+func (c discardReads) Read(p []byte) (int, error) {
+ for {
+ n, err := c.Conn.Read(p)
+ if err != nil || !c.discard.Load() {
+ return n, err
+ }
+ }
+}
+
+type disconnectingProvider struct {
+ discard *atomic.Bool
+ cancel context.CancelFunc
+}
+
+func (p disconnectingProvider) Wrap(context.Context, []byte, []byte) (encryption.WrappedDEK, error) {
+ p.discard.Store(true)
+ p.cancel()
+ return encryption.WrappedDEK{}, encryption.ErrProviderUnavailable
+}
+
+func (disconnectingProvider) Unwrap(context.Context, encryption.WrappedDEK, []byte) ([]byte, error) {
+ return nil, encryption.ErrProviderUnavailable
+}
+
+func testRollbackCleanup(t *testing.T, ctx context.Context, admin *pgxpool.Pool, url string) {
+ _, dsn := testdb.Create(t, ctx, admin, url, false)
+ config, err := pgxpool.ParseConfig(dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config.MaxConns = 1
+ var discard atomic.Bool
+ var socket net.Conn
+ config.ConnConfig.DialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) {
+ conn, err := (&net.Dialer{}).DialContext(ctx, network, addr)
+ if err == nil {
+ socket = conn
+ return discardReads{Conn: conn, discard: &discard}, nil
+ }
+ return nil, err
+ }
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ if err := Migrate(ctx, pool); err != nil {
+ t.Fatal(err)
+ }
+ op, cancel := context.WithCancel(ctx)
+ defer cancel()
+ cipher, err := encryption.NewCipher(disconnectingProvider{discard: &discard, cancel: cancel})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Prevent a broken implementation from hanging the test indefinitely.
+ timer := time.AfterFunc(5*time.Second, func() { _ = socket.Close() })
+ defer timer.Stop()
+ start := time.Now()
+ err = VerifyKey(op, pool, cipher)
+ if elapsed := time.Since(start); elapsed > 3*time.Second {
+ t.Fatalf("rollback blocked for %v after cancellation: %v", elapsed, err)
+ }
+ if !errors.Is(err, encryption.ErrProviderUnavailable) {
+ t.Fatalf("VerifyKey: %v", err)
+ }
+}
+
+func testMigrationUnlockCleanup(t *testing.T, ctx context.Context, admin *pgxpool.Pool, url string) {
+ _, dsn := testdb.Create(t, ctx, admin, url, false)
+ setup, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(setup.Close)
+ _, err = setup.Exec(ctx, `CREATE SCHEMA unlock_probe; CREATE FUNCTION unlock_probe.pg_advisory_unlock(bigint) RETURNS boolean LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(5); RETURN pg_catalog.pg_advisory_unlock($1); END $$`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, err := pgxpool.ParseConfig(dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config.ConnConfig.RuntimeParams["search_path"] = "unlock_probe,public,pg_catalog"
+ config.ConnConfig.RuntimeParams["application_name"] = "secret-unlock-test"
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ op, cancel := context.WithCancel(ctx)
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { done <- Migrate(op, pool) }()
+ wait, stop := context.WithTimeout(ctx, 15*time.Second)
+ defer stop()
+ for {
+ var active bool
+ err := setup.QueryRow(wait, `SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND application_name='secret-unlock-test' AND wait_event='PgSleep')`).Scan(&active)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if active {
+ break
+ }
+ select {
+ case <-wait.Done():
+ t.Fatal("unlock did not start")
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ cancel()
+ select {
+ case err := <-done:
+ if err == nil || !strings.Contains(err.Error(), "unlock") {
+ t.Fatalf("expected unlock error, got %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ err := <-done
+ t.Fatalf("migration unlock blocked after cancellation: %v", err)
+ }
+ check, err := setup.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer check.Release()
+ deadline := time.NewTimer(5 * time.Second)
+ defer deadline.Stop()
+ for {
+ var acquired bool
+ if err := check.QueryRow(ctx, "SELECT pg_try_advisory_lock($1)", lock.DefaultLockID).Scan(&acquired); err != nil {
+ t.Fatal(err)
+ }
+ if acquired {
+ break
+ }
+ select {
+ case <-deadline.C:
+ t.Fatal("failed unlock left the migration lock held")
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ if _, err := check.Exec(ctx, "SELECT pg_advisory_unlock($1)", lock.DefaultLockID); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/apps/secret-server/internal/database/database.go b/apps/secret-server/internal/database/database.go
new file mode 100644
index 000000000..744e8865a
--- /dev/null
+++ b/apps/secret-server/internal/database/database.go
@@ -0,0 +1,83 @@
+// Package database owns Secret Server schema initialization and key verification.
+package database
+
+import (
+ "context"
+ "database/sql"
+ "embed"
+ "fmt"
+ "io/fs"
+ "log"
+ "time"
+
+ "github.com/boxlite-ai/secret-server/internal/encryption"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/jackc/pgx/v5/stdlib"
+ "github.com/pressly/goose/v3"
+ "github.com/pressly/goose/v3/lock"
+)
+
+//go:embed migrations/*.sql
+var migrationFiles embed.FS
+
+const schemaVersion = 1
+
+type boundedSessionLocker struct{ lock.SessionLocker }
+
+func (l boundedSessionLocker) SessionUnlock(ctx context.Context, conn *sql.Conn) error {
+ cleanup, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+ if err := l.SessionLocker.SessionUnlock(cleanup, conn); err != nil {
+ // A failed unlock can leave a session lock held: never return it to the pool.
+ _ = conn.Raw(func(raw any) error {
+ if pg, ok := raw.(*stdlib.Conn); ok {
+ closed, stop := context.WithTimeout(context.Background(), time.Second)
+ defer stop()
+ _ = pg.Conn().Close(closed)
+ }
+ return nil
+ })
+ return err
+ }
+ return nil
+}
+
+// Initialize applies the schema and verifies the configured key before readiness.
+func Initialize(ctx context.Context, pool *pgxpool.Pool, cipher *encryption.Cipher) error {
+ if err := Migrate(ctx, pool); err != nil {
+ return err
+ }
+ return VerifyKey(ctx, pool, cipher)
+}
+
+// Migrate serializes embedded migrations with a PostgreSQL session lock.
+func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
+ db := stdlib.OpenDBFromPool(pool)
+ defer db.Close()
+ files, err := fs.Sub(migrationFiles, "migrations")
+ if err != nil {
+ return fmt.Errorf("open migrations: %w", err)
+ }
+ locker, err := lock.NewPostgresSessionLocker()
+ if err != nil {
+ return fmt.Errorf("create migration lock: %w", err)
+ }
+ provider, err := goose.NewProvider(goose.DialectPostgres, db, files, goose.WithSessionLocker(boundedSessionLocker{locker}))
+ if err != nil {
+ return fmt.Errorf("create migration provider: %w", err)
+ }
+ if _, err := provider.Up(ctx); err != nil {
+ return fmt.Errorf("apply migrations: %w", err)
+ }
+ version, err := provider.GetDBVersion(ctx)
+ if err != nil {
+ return fmt.Errorf("read schema version: %w", err)
+ }
+ if version < schemaVersion {
+ return fmt.Errorf("schema version %d is behind expected %d", version, schemaVersion)
+ }
+ if version > schemaVersion {
+ log.Printf("warning: schema version %d is ahead of binary version %d", version, schemaVersion)
+ }
+ return nil
+}
diff --git a/apps/secret-server/internal/database/database_test.go b/apps/secret-server/internal/database/database_test.go
new file mode 100644
index 000000000..5634775c9
--- /dev/null
+++ b/apps/secret-server/internal/database/database_test.go
@@ -0,0 +1,703 @@
+package database
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io/fs"
+ urlpkg "net/url"
+ "os"
+ "os/exec"
+ "strings"
+ "sync"
+ "testing"
+ "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/pressly/goose/v3"
+ "github.com/pressly/goose/v3/lock"
+)
+
+func TestSchemaVersionMatchesEmbeddedMigrations(t *testing.T) {
+ paths, err := fs.Glob(migrationFiles, "migrations/*.sql")
+ if err != nil || len(paths) == 0 {
+ t.Fatalf("embedded migrations: %v, %v", paths, err)
+ }
+ var latest int64
+ for _, path := range paths {
+ version, err := goose.NumericComponent(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if version > latest {
+ latest = version
+ }
+ }
+ if latest != schemaVersion {
+ t.Fatalf("latest embedded migration = %d, schemaVersion = %d", latest, schemaVersion)
+ }
+}
+
+func TestNormalizeName(t *testing.T) {
+ for _, tc := range []struct {
+ input, want string
+ valid bool
+ }{
+ {"open-ai", "OPEN_AI", true}, {"AZ09_", "AZ09_", true}, {"café", "CAF_", true}, {"", "", false},
+ {strings.Repeat("a", 64), strings.Repeat("A", 64), true}, {strings.Repeat("a", 65), "", false},
+ {"\xff", "", false}, {"a\x00b", "", false},
+ } {
+ got, err := NormalizeName(tc.input)
+ if (err == nil) != tc.valid || got != tc.want {
+ t.Errorf("NormalizeName(%q) = %q, %v", tc.input, got, err)
+ }
+ }
+}
+
+func TestIntegration(t *testing.T) {
+ url := os.Getenv("SECRET_TEST_DATABASE_URL")
+ if url == "" {
+ t.Skip("set SECRET_TEST_DATABASE_URL to run PostgreSQL integration tests")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ config, err := pgxpool.ParseConfig(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ admin, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(admin.Close)
+ t.Run("temporary database URL supports pool options", func(t *testing.T) {
+ parsed, err := urlpkg.Parse(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := parsed.Query()
+ query.Set("pool_max_conns", "8")
+ parsed.RawQuery = query.Encode()
+ name, dsn := testdb.Create(t, ctx, admin, parsed.String(), false)
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ var actual string
+ if err := pool.QueryRow(ctx, "SELECT current_database()").Scan(&actual); err != nil || actual != name {
+ t.Fatalf("connected to %q, %v; want temporary database %q", actual, err, name)
+ }
+ if pool.Config().MaxConns != 8 {
+ t.Fatalf("maximum pool connections = %d; want 8", pool.Config().MaxConns)
+ }
+ })
+ t.Run("temporary database URL ignores conflicting query parameters", func(t *testing.T) {
+ for _, param := range []string{"dbname", "database"} {
+ t.Run(param, func(t *testing.T) {
+ parsed, err := urlpkg.Parse(url)
+ if err != nil {
+ t.Fatal(err)
+ }
+ query := parsed.Query()
+ query.Set(param, config.ConnConfig.Database)
+ parsed.RawQuery = query.Encode()
+ name, dsn := testdb.Create(t, ctx, admin, parsed.String(), false)
+ connection, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer connection.Close()
+ var actual string
+ if err := connection.QueryRow(ctx, "SELECT current_database()").Scan(&actual); err != nil {
+ t.Fatal(err)
+ }
+ if actual != name {
+ t.Fatalf("connected to %q; want temporary database %q", actual, name)
+ }
+ })
+ }
+ })
+ t.Run("canary enrollment verifies persisted value", func(t *testing.T) {
+ for _, action := range []string{"skip", "corrupt"} {
+ t.Run(action, func(t *testing.T) {
+ _, dsn := testdb.Create(t, ctx, admin, url, false)
+ p, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Close()
+ if err := Migrate(ctx, p); err != nil {
+ t.Fatal(err)
+ }
+ body := "RETURN NULL;"
+ if action == "corrupt" {
+ body = "NEW.ciphertext := decode('00','hex'); RETURN NEW;"
+ }
+ _, err = p.Exec(ctx, "CREATE FUNCTION alter_canary() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN "+body+" END $$; CREATE TRIGGER alter_canary BEFORE INSERT ON key_verification_canary FOR EACH ROW EXECUTE FUNCTION alter_canary()")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := VerifyKey(ctx, p, testCipher(t, 1)); err == nil {
+ t.Fatal("enrollment succeeded without a valid persisted canary")
+ }
+ var count int
+ if err := p.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary after failed enrollment = %d, %v; want 0", count, err)
+ }
+ })
+ }
+ })
+ t.Run("rollback and unlock cleanup are bounded", func(t *testing.T) {
+ t.Run("rollback", func(t *testing.T) { testRollbackCleanup(t, ctx, admin, url) })
+ t.Run("migration unlock", func(t *testing.T) { testMigrationUnlockCleanup(t, ctx, admin, url) })
+ })
+ t.Run("initialize migrates and enrolls key", func(t *testing.T) {
+ name, _ := testdb.Create(t, ctx, admin, url, false)
+ initConfig := config.Copy()
+ initConfig.ConnConfig.Database = name
+ initPool, err := pgxpool.NewWithConfig(ctx, initConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer initPool.Close()
+ canceled, cancel := context.WithCancel(ctx)
+ cancel()
+ if err := Initialize(canceled, initPool, nil); err == nil || !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled initialization = %v; want canceled migration", err)
+ }
+ var relation *string
+ if err := initPool.QueryRow(ctx, "SELECT to_regclass('key_verification_canary')::text").Scan(&relation); err != nil || relation != nil {
+ t.Fatalf("canary table after canceled migration = %v, %v; want absent", relation, err)
+ }
+ cipher := testCipher(t, 1)
+ if err := Initialize(ctx, initPool, cipher); err != nil {
+ t.Fatal(err)
+ }
+ var version int64
+ if err := initPool.QueryRow(ctx, "SELECT max(version_id) FROM goose_db_version WHERE is_applied").Scan(&version); err != nil || version != schemaVersion {
+ t.Fatalf("schema version = %d, %v; want %d", version, err, schemaVersion)
+ }
+ var count int
+ if err := initPool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 1 {
+ t.Fatalf("canary count = %d, %v; want 1", count, err)
+ }
+ if err := VerifyKey(ctx, initPool, cipher); err != nil {
+ t.Fatalf("verify enrolled canary: %v", err)
+ }
+ })
+ t.Run("reject non-UTF8 database", func(t *testing.T) {
+ name, _ := testdb.Create(t, ctx, admin, url, true)
+ asciiConfig := config.Copy()
+ asciiConfig.ConnConfig.Database = name
+ asciiPool, err := pgxpool.NewWithConfig(ctx, asciiConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer asciiPool.Close()
+ if err := Migrate(ctx, asciiPool); err == nil || !strings.Contains(err.Error(), "requires a UTF8 database") {
+ t.Fatalf("non-UTF8 database migration = %v; want encoding error", err)
+ }
+ })
+ name, _ := testdb.Create(t, ctx, admin, url, false)
+ config.ConnConfig.Database = name
+ pool, err := pgxpool.NewWithConfig(ctx, config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ if !t.Run("lock cancellation and migration failure", func(t *testing.T) {
+ held, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Release()
+ if _, err := held.Exec(ctx, `SELECT pg_advisory_lock($1)`, lock.DefaultLockID); err != nil {
+ t.Fatal(err)
+ }
+ blocked, stop := context.WithTimeout(ctx, 300*time.Millisecond)
+ err = Migrate(blocked, pool)
+ stop()
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Errorf("migration lock wait = %v; want context deadline exceeded", err)
+ }
+ if _, err := held.Exec(ctx, `SELECT pg_advisory_unlock($1)`, lock.DefaultLockID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, `CREATE TABLE secret (id integer)`); err != nil {
+ t.Fatal(err)
+ }
+ if err := Migrate(ctx, pool); err == nil {
+ t.Fatal("migration unexpectedly succeeded with a conflicting table")
+ }
+ if _, err := pool.Exec(ctx, `DROP TABLE secret`); err != nil {
+ t.Fatal(err)
+ }
+ }) {
+ return
+ }
+
+ if !t.Run("concurrent migrations and newer schema", func(t *testing.T) {
+ _, databaseURL := testdb.Create(t, ctx, admin, url, false)
+ concurrentPool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer concurrentPool.Close()
+ var existing *string
+ if err := concurrentPool.QueryRow(ctx, "SELECT to_regclass('goose_db_version')::text").Scan(&existing); err != nil {
+ t.Fatal(err)
+ }
+ if existing != nil {
+ t.Fatal("concurrent initialization did not start with an empty database")
+ }
+ var processes [2]*exec.Cmd
+ var output [2]bytes.Buffer
+ for i := range processes {
+ processes[i] = exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMigrationProcess$")
+ processes[i].Env = append(os.Environ(), "SECRET_MIGRATION_PROCESS_URL="+databaseURL)
+ processes[i].Stdout = &output[i]
+ processes[i].Stderr = &output[i]
+ if err := processes[i].Start(); err != nil {
+ t.Fatal(err)
+ }
+ process := processes[i]
+ t.Cleanup(func() {
+ if process.ProcessState == nil {
+ _ = process.Process.Kill()
+ _ = process.Wait()
+ }
+ })
+ }
+ for i, process := range processes {
+ if err := process.Wait(); err != nil {
+ t.Errorf("migration process %d: %v\n%s", i, err, output[i].String())
+ }
+ }
+ if t.Failed() {
+ return
+ }
+ var count int
+ if err := concurrentPool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 1 {
+ t.Fatalf("concurrent initialization canary count = %d, %v; want 1", count, err)
+ }
+ 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 {
+ t.Fatal(err)
+ }
+ if err := Migrate(ctx, pool); err != nil {
+ t.Fatalf("older binary with newer schema: %v", err)
+ }
+ }) {
+ return
+ }
+
+ cipher := testCipher(t, 1)
+ t.Run("canary lock timeout rolls back", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ guard, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer guard.Rollback(context.Background())
+ if _, err := guard.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", canaryLock); err != nil {
+ t.Fatal(err)
+ }
+ blocked, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
+ defer cancel()
+ err = VerifyKey(blocked, pool, cipher)
+ if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "lock key verification") {
+ t.Fatalf("canary lock wait = %v; want lock deadline exceeded", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after lock timeout = %d, %v", count, err)
+ }
+ })
+ t.Run("canary read failure is not enrollment", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "ALTER TABLE key_verification_canary RENAME TO unavailable_canary"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "ALTER TABLE unavailable_canary RENAME TO key_verification_canary"); err != nil {
+ t.Error(err)
+ }
+ })
+ err := VerifyKey(ctx, pool, cipher)
+ if err == nil || !strings.Contains(err.Error(), "read key canary") {
+ t.Fatalf("canary read failure = %v", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM unavailable_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after read failure = %d, %v", count, err)
+ }
+ })
+ t.Run("canary encryption failure rolls back", func(t *testing.T) {
+ unavailable, err := encryption.NewCipher(unavailableProvider{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = VerifyKey(ctx, pool, unavailable)
+ if !errors.Is(err, encryption.ErrProviderUnavailable) || !strings.Contains(err.Error(), "encrypt key canary") {
+ t.Fatalf("canary encryption failure = %v", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after encryption failure = %d, %v", count, err)
+ }
+ })
+ t.Run("key verification rejects invalid inputs", func(t *testing.T) {
+ if err := VerifyKey(ctx, pool, nil); err == nil || !strings.Contains(err.Error(), "cipher is nil") {
+ t.Fatalf("nil cipher = %v", err)
+ }
+ canceled, cancel := context.WithCancel(ctx)
+ cancel()
+ if err := VerifyKey(canceled, pool, cipher); err == nil || !strings.Contains(err.Error(), "begin key verification") || !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled key verification = %v", err)
+ }
+ })
+ t.Run("canary plaintext mismatch", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary WHERE id = 1"); err != nil {
+ t.Fatal(err)
+ }
+ envelope, err := cipher.Encrypt(ctx, canaryContext, []byte("different plaintext"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = pool.Exec(ctx, "INSERT INTO key_verification_canary (id, ciphertext, encrypted_dek, key_id) VALUES (1, $1, $2, $3)", envelope.Ciphertext, envelope.WrappedDEK.Ciphertext, envelope.WrappedDEK.KeyID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "DELETE FROM key_verification_canary WHERE id = 1"); err != nil {
+ t.Error(err)
+ }
+ })
+ if err := VerifyKey(ctx, pool, cipher); err == nil || !strings.Contains(err.Error(), "key canary plaintext mismatch") {
+ t.Fatalf("mismatched plaintext = %v", err)
+ }
+ })
+ if !t.Run("canary insertion failure identifies operation", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ _, err := pool.Exec(ctx, `CREATE FUNCTION reject_canary_insert() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected failure'; END $$`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Exec(context.Background(), "DROP FUNCTION reject_canary_insert()")
+ if _, err := pool.Exec(ctx, "CREATE TRIGGER reject_canary_insert BEFORE INSERT ON key_verification_canary FOR EACH ROW EXECUTE FUNCTION reject_canary_insert()"); err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Exec(context.Background(), "DROP TRIGGER reject_canary_insert ON key_verification_canary")
+ err = VerifyKey(ctx, pool, cipher)
+ if err == nil || !strings.Contains(err.Error(), "insert key canary") {
+ t.Fatalf("insertion error = %v", err)
+ }
+ }) {
+ return
+ }
+ t.Run("canary commit failure rolls back enrollment", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, `CREATE FUNCTION reject_canary_commit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'deferred failure'; END $$`); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "DROP FUNCTION reject_canary_commit() CASCADE"); err != nil {
+ t.Error(err)
+ }
+ })
+ if _, err := pool.Exec(ctx, `CREATE CONSTRAINT TRIGGER reject_canary_commit AFTER INSERT ON key_verification_canary DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_canary_commit()`); err != nil {
+ t.Fatal(err)
+ }
+ err := VerifyKey(ctx, pool, cipher)
+ if err == nil || !strings.Contains(err.Error(), "commit key verification") {
+ t.Fatalf("commit error = %v", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after failed commit = %d, %v; want 0", count, err)
+ }
+ })
+ t.Run("invalid existing secret headers prevent enrollment", func(t *testing.T) {
+ id := "20000000-0000-0000-0000-000000000006"
+ _, 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,'10000000-0000-0000-0000-000000000001','org','bad_headers','BAD_HEADERS','x','y','env:key',ARRAY['host'],'{"Authorization":123}','p','test')`, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "DELETE FROM secret WHERE id=$1", id); err != nil {
+ t.Error(err)
+ }
+ })
+ err = VerifyKey(ctx, pool, cipher)
+ if err == nil || !strings.Contains(err.Error(), "decode existing secret headers") {
+ t.Fatalf("invalid headers error = %v", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after invalid headers = %d, %v; want 0", count, err)
+ }
+ })
+ if !t.Run("concurrent canary enrollment with repeatable read default", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ guard, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer guard.Rollback(context.Background())
+ if _, err := guard.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", canaryLock); err != nil {
+ t.Fatal(err)
+ }
+ repeatable := config.Copy()
+ repeatable.ConnConfig.RuntimeParams["default_transaction_isolation"] = "repeatable read"
+ repeatable.ConnConfig.RuntimeParams["application_name"] = "secret-canary-isolation-test"
+ isolated, err := pgxpool.NewWithConfig(ctx, repeatable)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer isolated.Close()
+ workersCtx, stopWorkers := context.WithCancel(ctx)
+ defer stopWorkers()
+ results := make(chan error, 2)
+ for range 2 {
+ go func() { results <- VerifyKey(workersCtx, isolated, cipher) }()
+ }
+ for {
+ var count int
+ if err := admin.QueryRow(ctx, "SELECT count(*) FROM pg_stat_activity WHERE datname=$1 AND application_name=$2 AND wait_event='advisory'", name, "secret-canary-isolation-test").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count == 2 {
+ break
+ }
+ select {
+ case <-ctx.Done():
+ t.Fatal("canary transactions did not reach lock")
+ case <-time.After(20 * time.Millisecond):
+ }
+ }
+ if err := guard.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if err := <-results; err != nil {
+ t.Errorf("concurrent key verification: %v", err)
+ }
+ }
+ }) {
+ return
+ }
+ if !t.Run("canary verification and recovery", func(t *testing.T) {
+ var wg sync.WaitGroup
+ for range 2 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ errs2 := VerifyKey(ctx, pool, cipher)
+ if errs2 != nil {
+ t.Error(errs2)
+ }
+ }()
+ }
+ wg.Wait()
+ if err := VerifyKey(ctx, pool, testCipher(t, 2)); err == nil {
+ t.Error("different key accepted")
+ }
+ if _, err := pool.Exec(ctx, "UPDATE key_verification_canary SET ciphertext = decode('00','hex')"); err != nil {
+ t.Fatal(err)
+ }
+ if err := VerifyKey(ctx, pool, cipher); err == nil {
+ t.Error("corrupt canary accepted")
+ }
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ if err := VerifyKey(ctx, pool, cipher); err != nil {
+ t.Fatal(err)
+ }
+ }) {
+ return
+ }
+
+ t.Run("existing secret read failure prevents canary enrollment", func(t *testing.T) {
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ identity := encryption.SecretContext{OrganizationID: "10000000-0000-0000-0000-000000000001", SecretID: "20000000-0000-0000-0000-000000000005", Version: 1, Hosts: []string{"host"}, Headers: map[string]string{"Authorization": "Bearer {value}"}}
+ envelope, err := cipher.Encrypt(ctx, identity, []byte("existing secret"))
+ 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','existing','EXISTING',$3,$4,$5,ARRAY['host'],'{"Authorization":"Bearer {value}"}','p','test')`, identity.SecretID, identity.OrganizationID, envelope.Ciphertext, envelope.WrappedDEK.Ciphertext, envelope.WrappedDEK.KeyID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "DELETE FROM secret WHERE id=$1", identity.SecretID); err != nil {
+ t.Error(err)
+ }
+ })
+ if _, err := pool.Exec(ctx, "ALTER TABLE secret RENAME TO unavailable_secret"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if _, err := pool.Exec(context.Background(), "ALTER TABLE unavailable_secret RENAME TO secret"); err != nil {
+ t.Error(err)
+ }
+ })
+ err = VerifyKey(ctx, pool, cipher)
+ if err == nil || !strings.Contains(err.Error(), "read existing secret for key verification") {
+ t.Fatalf("existing secret read failure = %v", err)
+ }
+ var count int
+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM key_verification_canary").Scan(&count); err != nil || count != 0 {
+ t.Fatalf("canary count after read failure = %d, %v; want 0", count, err)
+ }
+ })
+
+ t.Run("single-value schema and key recovery", func(t *testing.T) {
+ org := "10000000-0000-0000-0000-000000000001"
+ id := "20000000-0000-0000-0000-000000000001"
+ identity := encryption.SecretContext{OrganizationID: org, SecretID: id, Version: 1, Hosts: []string{"host"}, Headers: map[string]string{"Authorization": "Bearer {value}"}}
+ envelope, err := cipher.Encrypt(ctx, identity, []byte("test secret"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherVersion := identity
+ otherVersion.Version = 2
+ if _, err := cipher.Decrypt(ctx, otherVersion, envelope); err == nil {
+ t.Fatal("ciphertext accepted a different AAD version")
+ }
+ normalized, err := NormalizeName("open-ai")
+ if err != nil {
+ t.Fatal(err)
+ }
+ insert := `INSERT INTO secret(id,organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by) VALUES ($1,$2,'org','open-ai',$3,$4,$5,$6,ARRAY['host'],'{"Authorization":"Bearer {value}"}','p','test')`
+ if _, err := pool.Exec(ctx, insert, id, org, normalized, envelope.Ciphertext, envelope.WrappedDEK.Ciphertext, envelope.WrappedDEK.KeyID); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct{ hosts, headers, placeholder, constraint string }{
+ {"{}", `{"A":"b"}`, "p", "secret_hosts_check"},
+ {"{host}", `{}`, "p", "secret_headers_check"},
+ {"{host}", `[]`, "p", "secret_headers_check"},
+ {"{host}", `{"A":"b"}`, "", "secret_placeholder_check"},
+ } {
+ _, err := pool.Exec(ctx, `INSERT INTO secret(organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by) VALUES ($1,'org','invalid','INVALID','x','y','env:key',$2::text[],$3::jsonb,$4,'test')`, org, tc.hosts, tc.headers, tc.placeholder)
+ var pgErr *pgconn.PgError
+ if !errors.As(err, &pgErr) || pgErr.Code != "23514" || pgErr.ConstraintName != tc.constraint {
+ t.Errorf("invalid secret: got %v; want check %s", err, tc.constraint)
+ }
+ }
+ if _, err := pool.Exec(ctx, `UPDATE secret SET ciphertext='other' WHERE id=$1`, id); err == nil {
+ t.Error("mutable ciphertext accepted")
+ }
+ if _, err := pool.Exec(ctx, "DELETE FROM key_verification_canary"); err != nil {
+ t.Fatal(err)
+ }
+ if err := VerifyKey(ctx, pool, testCipher(t, 2)); err == nil {
+ t.Error("wrong key recreated canary despite existing secret")
+ }
+ if err := VerifyKey(ctx, pool, cipher); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE secret SET hosts=ARRAY['other'] WHERE id=$1`, id); err == nil {
+ t.Error("mutable hosts accepted")
+ }
+ if _, err := pool.Exec(ctx, `UPDATE secret SET encrypted_dek='new', key_id='env:new' WHERE id=$1`, id); err != nil {
+ t.Error(err)
+ }
+ for _, tc := range []struct {
+ name, statement, code, constraint string
+ args []any
+ }{
+ {"duplicate normalized name", `INSERT INTO secret(organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by) VALUES ($1,'org','open_ai',$2,'x','y','env:key',ARRAY['host'],'{"A":"b"}','p','test')`, "23505", "secret_org_name_uq", []any{org, normalized}},
+ {"incorrect normalization", `INSERT INTO secret(organization_id,scope,name,name_normalized,ciphertext,encrypted_dek,key_id,hosts,headers,placeholder,created_by) VALUES ($1,'org','abc','OTHER','x','y','env:key',ARRAY['host'],'{"A":"b"}','p','test')`, "23514", "secret_check1", []any{org}},
+ } {
+ _, err := pool.Exec(ctx, tc.statement, tc.args...)
+ var pgErr *pgconn.PgError
+ if !errors.As(err, &pgErr) || pgErr.Code != tc.code || pgErr.ConstraintName != tc.constraint {
+ t.Errorf("%s: got %v, want SQLSTATE %s constraint %s", tc.name, err, tc.code, tc.constraint)
+ }
+ }
+ if _, err := pool.Exec(ctx, `DELETE FROM secret WHERE id=$1`, id); err != nil {
+ t.Fatal(err)
+ }
+ replacementID := "20000000-0000-0000-0000-000000000004"
+ replacementIdentity := identity
+ replacementIdentity.SecretID = replacementID
+ replacement, err := cipher.Encrypt(ctx, replacementIdentity, []byte("replacement secret"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, insert, replacementID, org, normalized, replacement.Ciphertext, replacement.WrappedDEK.Ciphertext, replacement.WrappedDEK.KeyID); err != nil {
+ t.Fatalf("recreate secret with a new ID: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `DELETE FROM secret WHERE id=$1`, replacementID); err != nil {
+ t.Fatal(err)
+ }
+ for i, box := range []string{"box-a", "box-b"} {
+ boxID := fmt.Sprintf("20000000-0000-0000-0000-%012d", i+2)
+ boxName, err := NormalizeName("café")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, 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,'box',$3,'café',$4,'x','y','env:key',ARRAY['host'],'{"A":"b"}','p','test')`, boxID, org, box, boxName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ })
+}
+
+type unavailableProvider struct{}
+
+func (unavailableProvider) Wrap(context.Context, []byte, []byte) (encryption.WrappedDEK, error) {
+ return encryption.WrappedDEK{}, encryption.ErrProviderUnavailable
+}
+
+func (unavailableProvider) Unwrap(context.Context, encryption.WrappedDEK, []byte) ([]byte, error) {
+ return nil, encryption.ErrProviderUnavailable
+}
+
+func testCipher(t *testing.T, key byte) *encryption.Cipher {
+ t.Helper()
+ provider, err := encryption.NewEnvKeyProvider("env:test", base64.StdEncoding.EncodeToString(bytesOf(key, 32)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ cipher, err := encryption.NewCipher(provider)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return cipher
+}
+
+func bytesOf(value byte, n int) []byte { return []byte(strings.Repeat(string([]byte{value}), n)) }
+
+func TestMigrationProcess(t *testing.T) {
+ dsn := os.Getenv("SECRET_MIGRATION_PROCESS_URL")
+ if dsn == "" {
+ t.Skip("integration subprocess only")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ if err := Initialize(ctx, pool, testCipher(t, 1)); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/apps/secret-server/internal/database/migrations/00001_initial.sql b/apps/secret-server/internal/database/migrations/00001_initial.sql
new file mode 100644
index 000000000..f2d8d5019
--- /dev/null
+++ b/apps/secret-server/internal/database/migrations/00001_initial.sql
@@ -0,0 +1,79 @@
+-- +goose Up
+-- +goose StatementBegin
+DO $$
+BEGIN
+ IF current_setting('server_encoding') <> 'UTF8' THEN
+ RAISE EXCEPTION 'Secret Server requires a UTF8 database';
+ END IF;
+END;
+$$;
+-- +goose StatementEnd
+
+CREATE TABLE secret (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ organization_id uuid NOT NULL,
+ scope text NOT NULL CHECK (scope IN ('org', 'box')),
+ box_id varchar(64),
+ name text NOT NULL CHECK (char_length(name) BETWEEN 1 AND 64),
+ name_normalized text NOT NULL CHECK (name_normalized ~ '^[A-Z0-9_]{1,64}$'),
+ ciphertext bytea NOT NULL,
+ encrypted_dek bytea NOT NULL,
+ key_id text NOT NULL CHECK (key_id <> '' AND length(key_id) <= 128),
+ hosts text[] NOT NULL CHECK (cardinality(hosts) > 0),
+ headers jsonb NOT NULL CHECK (jsonb_typeof(headers) = 'object' AND headers <> '{}'::jsonb),
+ placeholder text NOT NULL CHECK (placeholder <> ''),
+ disabled_at timestamptz,
+ created_by text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ CHECK ((scope = 'box') = (box_id IS NOT NULL)),
+ -- Keep this mapping consistent with database.NormalizeName.
+ CHECK (name_normalized = translate(
+ regexp_replace(name COLLATE "C", '[^A-Za-z0-9_]', '_', 'g'),
+ 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
+);
+CREATE UNIQUE INDEX secret_org_name_uq ON secret (organization_id, name_normalized) WHERE scope = 'org';
+CREATE UNIQUE INDEX secret_box_name_uq ON secret (box_id, name_normalized) WHERE scope = 'box';
+CREATE INDEX secret_org_idx ON secret (organization_id);
+
+CREATE INDEX secret_key_idx ON secret (key_id);
+
+-- +goose StatementBegin
+CREATE FUNCTION protect_secret_value() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ -- encrypted_dek and key_id remain mutable for future KMS rewrapping.
+ IF (NEW.id, NEW.organization_id, NEW.scope, NEW.box_id, NEW.name, NEW.name_normalized, NEW.ciphertext, NEW.hosts, NEW.headers,
+ NEW.placeholder, NEW.created_by, NEW.created_at)
+ IS DISTINCT FROM
+ (OLD.id, OLD.organization_id, OLD.scope, OLD.box_id, OLD.name, OLD.name_normalized, OLD.ciphertext, OLD.hosts, OLD.headers,
+ OLD.placeholder, OLD.created_by, OLD.created_at) THEN
+ RAISE EXCEPTION 'secret value is immutable';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+-- +goose StatementEnd
+CREATE TRIGGER secret_value_immutable BEFORE UPDATE ON secret
+ FOR EACH ROW EXECUTE FUNCTION protect_secret_value();
+
+CREATE TABLE key_verification_canary (
+ id smallint PRIMARY KEY CHECK (id = 1),
+ ciphertext bytea NOT NULL,
+ encrypted_dek bytea NOT NULL,
+ key_id text NOT NULL CHECK (key_id <> '' AND length(key_id) <= 128)
+);
+
+CREATE TABLE secret_access_log (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ occurred_at timestamptz NOT NULL DEFAULT now(),
+ credential_id uuid,
+ runner_id text,
+ box_id varchar(64),
+ secret_id uuid,
+ result text NOT NULL CHECK (result IN
+ ('ok', 'attestation_failed', 'credential_invalid', 'runner_mismatch',
+ 'not_found', 'disabled', 'decrypt_failed'))
+);
+CREATE INDEX secret_access_log_time_idx ON secret_access_log (occurred_at);
+CREATE INDEX secret_access_log_secret_idx ON secret_access_log (secret_id, occurred_at);
+CREATE INDEX secret_access_log_runner_idx ON secret_access_log (runner_id, occurred_at);
diff --git a/apps/secret-server/internal/database/normalize.go b/apps/secret-server/internal/database/normalize.go
new file mode 100644
index 000000000..413b7f32c
--- /dev/null
+++ b/apps/secret-server/internal/database/normalize.go
@@ -0,0 +1,27 @@
+package database
+
+import (
+ "errors"
+ "strings"
+ "unicode/utf8"
+)
+
+// NormalizeName validates a secret name and maps each Unicode scalar to an environment key.
+// Keep its mapping consistent with the name_normalized CHECK in 00001_initial.sql.
+func NormalizeName(name string) (string, error) {
+ if !utf8.ValidString(name) || utf8.RuneCountInString(name) < 1 || utf8.RuneCountInString(name) > 64 || strings.ContainsRune(name, 0) {
+ return "", errors.New("secret name must contain 1 to 64 valid non-NUL Unicode characters")
+ }
+ var result strings.Builder
+ for _, c := range name {
+ switch {
+ case c >= 'a' && c <= 'z':
+ result.WriteByte(byte(c - 'a' + 'A'))
+ case c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '_':
+ result.WriteByte(byte(c))
+ default:
+ result.WriteByte('_')
+ }
+ }
+ return result.String(), nil
+}
diff --git a/apps/secret-server/internal/testdb/testdb.go b/apps/secret-server/internal/testdb/testdb.go
new file mode 100644
index 000000000..85b13116c
--- /dev/null
+++ b/apps/secret-server/internal/testdb/testdb.go
@@ -0,0 +1,73 @@
+// Package testdb manages isolated PostgreSQL databases for integration tests.
+package testdb
+
+import (
+ "context"
+ "crypto/rand"
+ "fmt"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+// databaseURL selects the temporary database even if the original URL has database parameters.
+func databaseURL(dsn, name string) (string, error) {
+ u, err := url.Parse(dsn)
+ if err != nil {
+ return "", err
+ }
+ u.Path = "/" + name
+ query := u.Query()
+ query.Del("dbname")
+ query.Del("database")
+ u.RawQuery = query.Encode()
+ return u.String(), nil
+}
+
+// Create creates and verifies an isolated database and registers its cleanup.
+func Create(t *testing.T, ctx context.Context, admin *pgxpool.Pool, dsn string, ascii bool) (string, string) {
+ t.Helper()
+ var nonce [8]byte
+ if _, err := rand.Read(nonce[:]); err != nil {
+ t.Fatal(err)
+ }
+ name := fmt.Sprintf("secret_test_%x", nonce)
+ statement := "CREATE DATABASE " + pgx.Identifier{name}.Sanitize()
+ if ascii {
+ statement += " ENCODING 'SQL_ASCII' LC_COLLATE 'C' LC_CTYPE 'C' TEMPLATE template0"
+ }
+ if _, err := admin.Exec(ctx, statement); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if _, err := admin.Exec(cleanup, "DROP DATABASE "+pgx.Identifier{name}.Sanitize()); err != nil {
+ t.Errorf("drop test database: %v", err)
+ }
+ })
+ temporaryURL, err := databaseURL(dsn, name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, err := pgxpool.ParseConfig(temporaryURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn, err := pgx.ConnectConfig(ctx, config.ConnConfig)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close(context.Background())
+ var actual string
+ if err := conn.QueryRow(ctx, "SELECT current_database()").Scan(&actual); err != nil {
+ t.Fatal(err)
+ }
+ if actual != name {
+ t.Fatalf("connected to database %q; want %q", actual, name)
+ }
+ return name, temporaryURL
+}
diff --git a/codecov.yml b/codecov.yml
index d316279ba..3ae86dc01 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -42,6 +42,7 @@ flags:
carryforward: true
ignore:
+ - "apps/secret-server/internal/testdb/**" # Integration test fixtures
- "src/deps/**/vendor/**" # Third-party sources, not BoxLite's networking bridge
# Test sources themselves. A changed test file that matches none of these is one
# Codecov calls testable, which makes it reject the empty upload test.yml sends
diff --git a/make/coverage.mk b/make/coverage.mk
index 03095c30d..7c8446a8f 100644
--- a/make/coverage.mk
+++ b/make/coverage.mk
@@ -104,6 +104,11 @@ coverage\:go: dev\:go
-coverprofile="$(PROJECT_ROOT)/target/coverage/secret-server.out" $(GOTEST_FILTER) ./...) || rc=$$?; \
exit $$rc
+PHONY_TARGETS += coverage\:apps\:secret-server\:integration
+coverage\:apps\:secret-server\:integration:
+ @mkdir -p "$(PROJECT_ROOT)/target/coverage"
+ @cd apps/secret-server && SECRET_TEST_DATABASE_URL="$${SECRET_TEST_DATABASE_URL:-postgresql://boxlite:[email protected]:25432/boxlite}" GOWORK=off go test -race -count=1 -covermode=atomic -coverpkg=./... -coverprofile="$(PROJECT_ROOT)/target/coverage/secret-server-integration.out" ./internal/database ./cmd/secret-server -run '^Test(Integration|MigrateSIGTERM)$$'
+
# Native archive import/export does not boot a VM, but the production constructor still
# requires a supported host. The Linux native-binding job enables KVM first.
coverage\:go\:checkpoint: $(if $(CARGO_LLVM_COV),dev\:c,dev\:go)
diff --git a/make/help.mk b/make/help.mk
index 7a4263bf0..0404d6275 100644
--- a/make/help.mk
+++ b/make/help.mk
@@ -122,6 +122,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:integration - Test Secret Server against infra-local PostgreSQL"
@echo " make test:apps:mdeploy - Type-check and test deployment scripts"
@echo " make test:apps:mbuild - Type-check and test image publication scripts"
@echo " make test:e2e:drivers - Test acceptance-client argument handling"
@@ -150,6 +151,7 @@ help:
@echo " make coverage:report - Render collected Rust profiles as LCOV and HTML"
@echo " make coverage:bindings:external - Measure native SDK calls from C, Python and Node"
@echo " make coverage:go - Collect Go SDK, bridge, runner, image-service and Secret Server coverage"
+ @echo " make coverage:apps:secret-server:integration - Collect Secret Server PostgreSQL integration coverage"
@echo " make coverage:python - Collect Python SDK coverage"
@echo " make coverage:node - Collect Node.js SDK coverage"
@echo " make coverage:infra - Test infrastructure tooling and collect LCOV coverage"
diff --git a/make/test.mk b/make/test.mk
index c6630123a..31b8a9774 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -780,6 +780,10 @@ PHONY_TARGETS += test\:apps\:secret-server
test\:apps\:secret-server:
@cd apps/secret-server && GOWORK=off go test -race ./... $(GOTEST_FILTER)
+PHONY_TARGETS += test\:apps\:secret-server\:integration
+test\:apps\:secret-server\:integration:
+ @cd apps/secret-server && SECRET_TEST_DATABASE_URL="$${SECRET_TEST_DATABASE_URL:-postgresql://boxlite:[email protected]:25432/boxlite}" GOWORK=off go test -race -count=1 ./internal/database ./cmd/secret-server -run '^Test(Integration|MigrateSIGTERM)$$'
+
test\:apps: _ensure-apps-deps dev\:go
@echo "🧪 Running apps workspace test matrix..."
@$(MAKE) test:apps:infra