Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions cmd/kynotes-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
25 changes: 25 additions & 0 deletions docs/superpowers/specs/2026-11-23-tenancy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<random>/` 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
Expand Down
35 changes: 35 additions & 0 deletions internal/app/qualify_object_store_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
33 changes: 33 additions & 0 deletions internal/app/replica_objects.go
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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
}
6 changes: 6 additions & 0 deletions internal/blobstore/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<random>/`
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

Expand Down
96 changes: 96 additions & 0 deletions internal/blobstore/qualify.go
Original file line number Diff line number Diff line change
@@ -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/<random>/ 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
}
Loading