diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99825ad2..14dadc42 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,44 @@ jobs: GODEBUG: fips140=on run: make test + # Provider qualification (tenancy spec, primary object storage) against the disposable + # signature-checking, versioned S3 server the suite's other apps use, behind a verified + # TLS proxy in the test. Normal and strong-key profiles. + object-store: + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + - name: Start disposable versioned S3 server + run: | + printf '%s' '{"identities":[{"name":"kynotes-ci","credentials":[{"accessKey":"kynotes-ci","secretKey":"kynotes-ci-fixture-secret"}],"actions":["Admin","Read","Write","List","Tagging"]}]}' > "$RUNNER_TEMP/s3.json" + docker run -d --name s3 --memory=512m --memory-swap=512m --cpus=1 --pids-limit=256 \ + -p 127.0.0.1:8333:8333 -v "$RUNNER_TEMP/s3.json:/etc/s3.json:ro" \ + chrislusf/seaweedfs:4.52@sha256:57877e32bb90073b37dc109b438ba66e84fd5ed9ced5f5c04f56444ef243ce59 \ + server -dir=/data -s3 -s3.port=8333 -s3.config=/etc/s3.json + for _ in $(seq 60); do curl -s -o /dev/null http://127.0.0.1:8333 && break; sleep 1; done + for _ in $(seq 30); do + docker exec s3 sh -c 'echo "s3.bucket.create -name kynotes" | weed shell' >/dev/null || true + docker exec s3 sh -c 'echo "s3.bucket.versioning -name kynotes -enable" | weed shell' | grep -q 'set to Enabled' && exit 0 + sleep 1 + done + docker logs s3; exit 1 + - name: Qualify the provider + env: + KY_TEST_S3_ENDPOINT: http://127.0.0.1:8333 + KY_TEST_S3_BUCKET: kynotes + KY_TEST_S3_ACCESS_KEY: kynotes-ci + KY_TEST_S3_SECRET_KEY: kynotes-ci-fixture-secret + run: | + go test -race -count=1 -timeout 5m -run '^TestProviderQualification' ./internal/blobstore + GODEBUG=fips140=on go test -race -count=1 -timeout 5m -run '^TestProviderQualification' ./internal/blobstore + # The suites that open a store, again with every storage.Open on a schema in a real # PostgreSQL (KYNOTES_TEST_DATABASE_URL; tenancy spec PR 2). Left out: internal/backup and # cmd/kynotes-server, whose capsules and offline data-directory commands work on the SQLite file @@ -233,7 +271,7 @@ jobs: # The required check and release-image.yml's REQUIRED name: green only if every leg passed. test: - needs: [race, fips, checks, postgres] + needs: [race, fips, checks, postgres, object-store] if: (always()) && github.event.pull_request.draft != true runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/AGENTS.md b/AGENTS.md index 8cb3abfb..050f0e79 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -327,6 +327,9 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che No customer/everyday account or password/DSN argv path exists there. Startup bootstrap preparation seeds only staff accounts, rechecks under N3, refuses everyday variables and audits; the single bootstrap/CLI paths retain their original behavior. + `qualify-object-store` runs `blobstore.QualifyProvider` with the replica object environment and + credential reader; verify `TestProviderQualificationOnVersionedS3` (CI `object-store`) and + `TestQualifyObjectStoreRefusesIncompleteInput`. It proves no SigV4 request-age refusal. `accept-replica-config --confirm-stopped` loads the complete app-owned field map through a separate read-only maintenance loader, requires the retained salt key and fixed mode/staff/ region, and atomically audits changed names only. Stop every replica first. Normal config diff --git a/cmd/kynotes-server/main.go b/cmd/kynotes-server/main.go index 9e827985..93f41ab3 100644 --- a/cmd/kynotes-server/main.go +++ b/cmd/kynotes-server/main.go @@ -57,6 +57,15 @@ func main() { os.Exit(1) } return + case "qualify-object-store": + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + e := app.QualifyObjectStore(ctx, os.Stdout) + cancel() + if e != nil { + fmt.Fprintln(os.Stderr, e) + os.Exit(1) + } + return case "prepare-postgres-restore": if e := preparePostgresRestoreCommand(os.Args[2:], os.Stdout); e != nil { fmt.Fprintln(os.Stderr, e) diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index e833ae37..c4d2090e 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1658,6 +1658,31 @@ Unproven: that a selected provider honors request age and commits no PUT past th (provider qualification), and clock skew between provider and database beyond a few minutes. +### Provider qualification as built (startup still refused) + +`blobstore.QualifyProvider`, run by `kynotes-server qualify-object-store` with the replica's +own object environment and bounded `_FILE`/direct credential reader (PR 5b-2), checks the +provider behaviors the object runtime relies on, under a fresh `qualify//` prefix it +deletes again on success and failure: + +- **Signatures:** a request signed with a wrong secret is refused, not answered `404`. +- **Conditional writes:** a second `If-None-Match: *` PUT is refused (`412`) and the object + keeps its first bytes (blob writes and the store ID rely on this). +- **Age metadata:** `LastModified` is present and within 5 minutes of this host's clock, since + the orphan sweep ages objects by provider time. +- **Versions and erasure:** an overwrite and a delete, then a prefix delete, leave no version or + delete marker. Versioning on or off is reported; both qualify, because Delete and Purge remove + every version. + +It needs only read, write, list and delete in the bucket. `TestProviderQualificationOnVersionedS3` +runs it against the suite's signature-checking, versioned SeaweedFS fixture behind a verified TLS +proxy (CI job `object-store`, normal and FIPS), and makes the proxy lie in one way at a time; +each lie fails at its own step. **Not qualified here:** SigV4 request-age refusal (a request +signed more than 15 minutes earlier) and so the late-PUT window's provider bound, because the +shared client exposes no signer clock; that needs a ky-primitives option. Credential scope +(that the key reaches only this bucket) is the operator's IAM policy and is not probed. The +chosen hosted provider must pass this command before multi startup is enabled. + ### Phase 6 host maintenance as built (startup still refused) Multi-mode `user add --admin` uses bounded stdin derived credentials and an exact existing PG diff --git a/internal/app/qualify_object_store_test.go b/internal/app/qualify_object_store_test.go new file mode 100644 index 00000000..30f8ae41 --- /dev/null +++ b/internal/app/qualify_object_store_test.go @@ -0,0 +1,35 @@ +package app + +import ( + "io" + "strings" + "testing" +) + +// qualify-object-store needs the full object-store environment, one credential form per key, +// and an HTTPS endpoint; it never echoes a credential. +func TestQualifyObjectStoreRefusesIncompleteInput(t *testing.T) { + base := map[string]string{"KYNOTES_BLOB_S3_ENDPOINT": "https://s3.invalid", "KYNOTES_BLOB_S3_BUCKET": "b", "KYNOTES_BLOB_S3_REGION": "r", "KYNOTES_BLOB_S3_ACCESS_KEY": "AKIDSECRETVALUE", "KYNOTES_BLOB_S3_SECRET": "very-secret-value"} + for _, c := range []struct{ drop, set, value, want string }{ + {drop: "KYNOTES_BLOB_S3_ENDPOINT", want: "KYNOTES_BLOB_S3_ENDPOINT is required"}, + {drop: "KYNOTES_BLOB_S3_SECRET", want: "KYNOTES_BLOB_S3_SECRET requires"}, + {set: "KYNOTES_BLOB_S3_SECRET_FILE", value: "/nonexistent", want: "set only one"}, + {set: "KYNOTES_BLOB_S3_ENDPOINT", value: "http://s3.invalid", want: "invalid object-store configuration"}, + } { + t.Run(c.want, func(t *testing.T) { + for k, v := range base { + t.Setenv(k, v) + } + if c.drop != "" { + t.Setenv(c.drop, "") + } + if c.set != "" { + t.Setenv(c.set, c.value) + } + err := QualifyObjectStore(t.Context(), io.Discard) + if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "very-secret") || strings.Contains(err.Error(), "AKIDSECRET") { + t.Errorf("%+v: %v", c, err) + } + }) + } +} diff --git a/internal/app/replica_objects.go b/internal/app/replica_objects.go index d06bd303..3eac06e8 100644 --- a/internal/app/replica_objects.go +++ b/internal/app/replica_objects.go @@ -1,13 +1,17 @@ package app import ( + "context" "errors" "fmt" "io" "os" "strings" + "time" shareds3 "github.com/Busnes-app/ky-primitives/s3" + + "github.com/Busnes-app/kynotes-server/internal/blobstore" ) // newReplicaObjectClient prepares the selected primary-object client without network I/O. @@ -63,3 +67,32 @@ func replicaObjectCredential(name string) (string, error) { } return value, nil } + +// QualifyObjectStore runs blobstore.QualifyProvider against the configured primary object +// store, with the replica's own bounded credential reader, and reports what it proved. +func QualifyObjectStore(ctx context.Context, out io.Writer) error { + var in replicaInputs + for name, dst := range map[string]*string{"KYNOTES_BLOB_S3_ENDPOINT": &in.BlobEndpoint, "KYNOTES_BLOB_S3_BUCKET": &in.BlobBucket, "KYNOTES_BLOB_S3_REGION": &in.BlobRegion} { + if *dst = os.Getenv(name); *dst == "" { + return fmt.Errorf("qualify: %s is required", name) + } + } + access, err := replicaObjectCredential("KYNOTES_BLOB_S3_ACCESS_KEY") + if err != nil { + return err + } + secret, err := replicaObjectCredential("KYNOTES_BLOB_S3_SECRET") + if err != nil { + return err + } + q, err := blobstore.QualifyProvider(ctx, shareds3.Config{Endpoint: in.BlobEndpoint, Bucket: in.BlobBucket, Region: in.BlobRegion, AccessKey: access, SecretKey: secret}, time.Now) + if err != nil { + return err + } + versions := "off: Delete and Purge remove the only copy" + if q.Versioned { + versions = "on: Delete and Purge removed every version and marker" + } + _, err = fmt.Fprintf(out, "Object store qualified: signatures checked, exclusive create refused, LastModified present (skew %s), prefix erasure complete; versioning %s. Not proven here: SigV4 request-age refusal and the late-PUT bound.\n", q.Skew.Round(time.Second), versions) + return err +} diff --git a/internal/blobstore/AGENTS.md b/internal/blobstore/AGENTS.md index 09b301e7..ce3f7de7 100644 --- a/internal/blobstore/AGENTS.md +++ b/internal/blobstore/AGENTS.md @@ -48,6 +48,12 @@ Own opaque blob streams, single-volume compatibility and the tenancy blob seam. - New shared-client dependencies must point to its reviewed upstream implementation, with no copied signing/transport or invented client contract. Provider qualification is separate from the local TLS S3 wire fixture. +- `QualifyProvider` (CLI `qualify-object-store`) proves on a throwaway `qualify//` + prefix, removed on every exit: signatures verified, If-None-Match: * refused and not + replacing, LastModified present within `MaxProviderSkew`, prefix erasure leaving no version + or marker. Versioning is reported, not required. Each check has a lying-proxy case in + `TestProviderQualificationOnVersionedS3` (CI `object-store` job, SeaweedFS, both profiles); + keep one per check. SigV4 request-age refusal is not proven: the shared client has no clock option. ## Work Guidance diff --git a/internal/blobstore/qualify.go b/internal/blobstore/qualify.go new file mode 100644 index 00000000..d414efb2 --- /dev/null +++ b/internal/blobstore/qualify.go @@ -0,0 +1,96 @@ +package blobstore + +import ( + "context" + "crypto/rand" + "errors" + "fmt" + "io" + "strings" + "time" + + shareds3 "github.com/Busnes-app/ky-primitives/s3" +) + +// MaxProviderSkew bounds the provider clock against ours. The orphan sweep ages objects by +// provider LastModified (an hour); a larger skew would let it delete a fresh upload. +const MaxProviderSkew = 5 * time.Minute + +// Qualification is what QualifyProvider proved about a bucket. Versioned is informational: +// either way Delete and Purge must leave no version or delete marker behind. +type Qualification struct { + Versioned bool + Skew time.Duration +} + +// QualifyProvider checks, under a fresh qualify// prefix it removes again, the +// provider behavior multi mode relies on: signatures are verified, If-None-Match: * never +// replaces an object, LastModified is present and within MaxProviderSkew, and a prefix delete +// leaves no version or marker. It needs only the bucket's own read, write, list and delete. +// It does not prove SigV4 request-age refusal or the late-PUT bound (spec, provider +// qualification); those need a signer clock the shared client does not expose. +func QualifyProvider(ctx context.Context, cfg shareds3.Config, now func() time.Time) (Qualification, error) { + var q Qualification + c, err := shareds3.New(cfg) + if err != nil { + return q, errors.New("qualify: invalid object-store configuration") + } + prefix := "qualify/" + strings.ToLower(rand.Text()) + "/" + key := prefix + "exclusive" + fail := func(step string, err error) (Qualification, error) { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute) + defer cancel() + return q, errors.Join(fmt.Errorf("qualify: %s: %w", step, err), c.DeletePrefix(cleanup, prefix)) + } + + bad := cfg + bad.SecretKey += "-wrong" + if wrong, err := shareds3.New(bad); err == nil { + if _, err := wrong.Head(ctx, key, ""); err == nil || errors.Is(err, shareds3.ErrNotFound) { + return fail("signatures", errors.New("a request signed with a wrong secret was answered")) + } + } + if _, err := c.PutIfAbsent(ctx, key, strings.NewReader("first"), 5); err != nil { + return fail("exclusive create", err) + } + if _, err := c.PutIfAbsent(ctx, key, strings.NewReader("other"), 5); !errors.Is(err, shareds3.ErrAlreadyExists) { + return fail("exclusive create", fmt.Errorf("a second If-None-Match: * PUT was not refused (%v)", err)) + } + body, obj, err := c.Get(ctx, key, "") + if err != nil { + return fail("exclusive create", err) + } + got, err := io.ReadAll(io.LimitReader(body, 16)) + body.Close() + if err != nil || string(got) != "first" { + return fail("exclusive create", errors.New("the refused PUT replaced the object")) + } + if obj.LastModified.IsZero() { + return fail("age metadata", errors.New("no LastModified")) + } + q.Skew = now().Sub(obj.LastModified) + if q.Skew > MaxProviderSkew || q.Skew < -MaxProviderSkew { + return fail("age metadata", fmt.Errorf("provider clock differs by %s", q.Skew.Round(time.Second))) + } + if _, err := c.Put(ctx, key, strings.NewReader("second"), 6); err != nil { + return fail("versions", err) + } + if _, err := c.Delete(ctx, key, ""); err != nil { + return fail("versions", err) + } + page, err := c.ListObjectVersions(ctx, prefix, shareds3.VersionCursor{}) + if err != nil { + return fail("versions", err) + } + q.Versioned = len(page.Objects) > 0 + if err := c.DeletePrefix(ctx, prefix); err != nil { + return fail("erasure", err) + } + if page, err = c.ListObjectVersions(ctx, prefix, shareds3.VersionCursor{}); err != nil { + return fail("erasure", err) + } + if len(page.Objects) > 0 { + return fail("erasure", fmt.Errorf("%d versions or markers survived the prefix delete", len(page.Objects))) + } + return q, nil +} diff --git a/internal/blobstore/qualify_test.go b/internal/blobstore/qualify_test.go new file mode 100644 index 00000000..e779b96a --- /dev/null +++ b/internal/blobstore/qualify_test.go @@ -0,0 +1,115 @@ +package blobstore + +import ( + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "strings" + "sync/atomic" + "testing" + "time" + + shareds3 "github.com/Busnes-app/ky-primitives/s3" +) + +// The disposable signature-checking, versioned S3 server CI starts (KY_TEST_S3_*), behind a +// verified TLS proxy that can make it lie in one way at a time. +func versionedS3(t *testing.T) (shareds3.Config, *atomic.Value) { + t.Helper() + endpoint := os.Getenv("KY_TEST_S3_ENDPOINT") + if endpoint == "" { + t.Skip("set KY_TEST_S3_* for the disposable versioned S3 server") + } + u, err := url.Parse(endpoint) + if err != nil || u.Scheme != "http" || !net.ParseIP(u.Hostname()).IsLoopback() { + t.Fatal("the qualification fixture must be loopback HTTP, never a live store") + } + var lie atomic.Value + lie.Store("") + proxy := httputil.NewSingleHostReverseProxy(u) + forward := proxy.ServeHTTP + proxy.ModifyResponse = func(resp *http.Response) error { + r := resp.Request + switch lie.Load() { + case "conditional": // accepts an If-None-Match: * PUT on an existing key + if r.Method == http.MethodPut && resp.StatusCode == http.StatusPreconditionFailed { + resp.StatusCode = http.StatusOK + } + case "age": + resp.Header.Del("Last-Modified") + case "replaced": // refuses the second PUT, yet serves its bytes + if r.Method == http.MethodGet && r.URL.RawQuery == "" && resp.StatusCode == http.StatusOK { + resp.Body.Close() + resp.Body = io.NopCloser(strings.NewReader("other")) + } + case "unsigned": // answers a bad signature as if it had checked nothing + if resp.StatusCode == http.StatusForbidden { + resp.StatusCode = http.StatusNotFound + } + } + return nil + } + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if lie.Load() == "erasure" && r.Method == http.MethodDelete && r.URL.Query().Has("versionId") { + w.WriteHeader(http.StatusNoContent) // claims to delete a version it keeps + return + } + forward(w, r) + })) + t.Cleanup(srv.Close) + cfg := shareds3.Config{Endpoint: srv.URL, Bucket: os.Getenv("KY_TEST_S3_BUCKET"), Region: "us-east-1", AccessKey: os.Getenv("KY_TEST_S3_ACCESS_KEY"), SecretKey: os.Getenv("KY_TEST_S3_SECRET_KEY"), HTTP: srv.Client()} + t.Cleanup(func() { + lie.Store("") + c, err := shareds3.New(cfg) + if err == nil { + err = c.DeletePrefix(context.Background(), "qualify/") + } + if err != nil { + t.Error("fixture cleanup", err) + } + }) + return cfg, &lie +} + +// The real versioned server qualifies and leaves nothing behind; each provider behavior +// multi mode relies on, broken alone, fails qualification at its own step. +func TestProviderQualificationOnVersionedS3(t *testing.T) { + cfg, lie := versionedS3(t) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute) + defer cancel() + q, err := QualifyProvider(ctx, cfg, time.Now) + if err != nil || !q.Versioned { + t.Fatalf("honest versioned server: %+v %v", q, err) + } + c, _ := shareds3.New(cfg) + if page, err := c.ListObjectVersions(ctx, "qualify/", shareds3.VersionCursor{}); err != nil || len(page.Objects) != 0 { + t.Fatalf("qualification left %d objects: %v", len(page.Objects), err) + } + for lying, want := range map[string]string{"conditional": "exclusive create: a second", "replaced": "exclusive create: the refused PUT", "age": "age metadata: no LastModified", "erasure": "erasure:", "unsigned": "signatures: a request signed with a wrong secret"} { + lie.Store(lying) + if _, err := QualifyProvider(ctx, cfg, time.Now); err == nil || !strings.Contains(err.Error(), "qualify: "+want) { + t.Errorf("a provider lying about %s: %v", lying, err) + } + lie.Store("") + if err := c.DeletePrefix(ctx, "qualify/"); err != nil { + t.Fatal(err) + } + } + skewed := func() time.Time { return time.Now().Add(MaxProviderSkew + time.Minute) } + if _, err := QualifyProvider(ctx, cfg, skewed); err == nil || !strings.Contains(err.Error(), "provider clock differs") { + t.Errorf("a skewed clock qualified: %v", err) + } + wrong := cfg + wrong.SecretKey = "not-the-secret" + if _, err := QualifyProvider(ctx, wrong, time.Now); err == nil { + t.Error("wrong credentials qualified") + } + if page, err := c.ListObjectVersions(ctx, "qualify/", shareds3.VersionCursor{}); err != nil || len(page.Objects) != 0 { + t.Fatalf("a failed qualification left %d objects: %v", len(page.Objects), err) + } +}