From dd45f6effd50a931aed3c113bb50e4d869acdab3 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Mon, 23 Nov 2026 19:33:21 -0500 Subject: [PATCH] prepare bounded primary object credentials Read the selected environment or credential-file forms and construct the real shared S3 client without I/O, persistent state or startup selection. Refuse ambiguous, empty, multiline, nonregular and oversized sources without disclosing credentials or paths. Keep credentials separate from maintenance and replica fingerprints. Record remaining delayed-PUT erasure qualification and native PostgreSQL recovery decisions in the existing design/plan; do not select a protocol or consume unmerged shared APIs. Cover successful mixed sources, refusal/redaction and startup fences with executable checks. Co-Authored-By: GPT 6.1 Sol --- AGENTS.md | 7 + DESIGN.md | 16 ++ IMPLEMENTATION_PLAN.md | 22 +++ docs/ASSURANCE-CASE.md | 8 + docs/STRONG-CRYPTO.md | 1 + .../specs/2026-11-23-tenancy-design.md | 19 ++- internal/app/replica_objects.go | 65 ++++++++ internal/app/replica_objects_test.go | 143 ++++++++++++++++++ 8 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 internal/app/replica_objects.go create mode 100644 internal/app/replica_objects_test.go diff --git a/AGENTS.md b/AGENTS.md index a8e05648..fceda8fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -369,6 +369,13 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che startup or invent object/PG-backup adapters. Verify `TestReplica*`, `TestBackendSeam*`, `TestObjectKeys*`, `TestStoreIdentitySingleMode*`, both backend suites and the golden. +- Primary-object credential preparation (`internal/app/replica_objects.go`) reads only the + selected environment/_FILE forms, rejects ambiguous/empty/multiline/oversized inputs and + nonregular files, and reports setting names only. Credentials never enter replica fields, + SQL, local key files or printable client state. Its concrete shared-client constructor does + no I/O and is not wired into startup. Verify `TestReplicaObject*` in normal/FIPS profiles + plus existing object/replica/golden tests. See the tenancy plan for remaining erasure gates. + - `internal/storage/migrations/0008_frozen_contract_columns.sql` exposes the frozen audit and idempotency-key schema on databases created by the earlier implementation migrations. diff --git a/DESIGN.md b/DESIGN.md index 17bfe4de..55b0a112 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1014,3 +1014,19 @@ Object/part reads preserve exact stored wire bytes, including when the provider object with gzip metadata. The shared client's identity-encoding GET prevents transparent HTTP decoding from changing ciphertext, lengths or hashes; an actual compressed-byte fixture pins product-level GET/HEAD agreement. No provider metadata authorizes content transformation. + + +### Primary-object credentials and remaining erasure qualification + +`app.newReplicaObjectClient` prepares the actual shared client without I/O from the already +validated endpoint/bucket/region and environment/_FILE credentials. The credential reader +rejects ambiguous forms, empty/multiline or over-64-KiB values and nonregular files, accepts +one trailing file LF/CRLF, and reports no credential or path in errors. Credentials stay out +of replica fields and persisted settings. This entry point remains separate from maintenance +and all startup paths; tests preserve the multi refusal and standalone golden. + +N3 session-lock ownership and context cancellation do not establish the fate of a previously +issued remote PUT after lock loss. Complete GC/purge/runtime integration requires a selected +and qualified delayed-writer erasure fence before deletion/readiness claims. The shared +conditional API does not choose a product ledger/protocol. Store controls/age and selected +provider proof, native-PG recovery transport and final assembly remain launch prerequisites. diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index aa2cb156..b7c2a1b3 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2308,3 +2308,25 @@ age metadata, requested from the existing shared-client owner. Parts/finalizatio binding, age-gated orphans/probe cleanup, provider/latency/erasure evidence, native-PG recovery and final mode-binding/runtime/lifecycle assembly remain prerequisites. Startup stays refused; no volume fallback, private client, unselected provider/transport or version pruning. + + +### Tenancy PR 5b-2: primary-object credential preparation + +Prepared the actual shared S3 client from the selected environment credentials or their +`_FILE` alternatives, separately from maintenance/shared-fingerprint input. Both forms set +(including empty values) refuse; inputs are one nonempty line, at most 64 KiB. Operator-owned +regular credential files may end with one LF/CRLF; bounded reads, source/type failures and +client validation errors disclose setting names only. Construction makes no network request, +local key/store or SQL write. No normal config loader or startup path invokes it. + +The base shared client is pinned to merged #77 (`79823f9`); published #78's exclusive-create, +ETag and age additions remain unmerged and are not consumed. Complete Backend/Temporary, +store-ID/probes, request/GC/purge integration and provider evidence remain unbuilt. + +Before binding GC/purge/runtime, qualify the fate of an already-issued remote PUT after the +writer loses its PG session lock or context. Lock loss/cancellation alone cannot prove that +remote write finished before erasure. The selected Notes resolution and delayed-write test +must be recorded here before erasure-readiness claims; consuming wire-only conditional APIs +does not select Messages' ledger/protocol. Preserve access fences while this is unresolved. +Native encrypted PG base-backup/WAL tool/transport, destination/retention and restore/drill +remain spec open question 3. Startup remains refused; existing single-mode behavior stays. diff --git a/docs/ASSURANCE-CASE.md b/docs/ASSURANCE-CASE.md index e7ad2dc5..51931b09 100644 --- a/docs/ASSURANCE-CASE.md +++ b/docs/ASSURANCE-CASE.md @@ -202,3 +202,11 @@ tail removal. Native independent PG pools prove one physical PUT/claim under the continued N3 availability while the provider blocks. This is product-adapter boundary evidence, not real-provider qualification or a complete object/GC/runtime implementation. Upstream client gate clearance, exclusive controls, provider age and native recovery remain prerequisites. + + +Primary-object client preparation has a separate environment/_FILE credential boundary. +`TestReplicaObject*` covers bounded values/files, source ambiguity, nonregular/missing paths, +multiline/empty refusal and secret-safe errors/formatting. Construction writes no shared +settings or local store and does not enable startup. Actual delayed PUT completion after a +lost PG lock remains unqualified; neither a canceled context nor the published wire API is +erasure proof. Runtime/GC/purge/provider and native-PG recovery gates remain explicit. diff --git a/docs/STRONG-CRYPTO.md b/docs/STRONG-CRYPTO.md index ac1bbc4f..d2e7f0f8 100644 --- a/docs/STRONG-CRYPTO.md +++ b/docs/STRONG-CRYPTO.md @@ -34,6 +34,7 @@ delete accounts. Nothing in this guide rewrites a stored key. | Directory webhook (HMAC-SHA256) | 32 random bytes minted by KySignOn | A new secret below 16 bytes is refused by the admin SSO form, KySignOn pairing and `apply-setup`; `syncauth` refuses to verify with one. A short secret stored before this check is kept as is and authenticates nothing until replaced. Pairing requires an HTTPS issuer. | | KyRecovery capsules | Sealed by `ky-primitives/recoveryclient` to the pinned fixed-suite public key, HTTPS only | No size is selectable. | | SFTP blob mirror (`ky-primitives/offsite`) | Pinned SHA-256 host key; password or PEM key | Host, client and certificate-authority keys must be RSA-2048+, ECDSA P-256+ or Ed25519, and a matching pin never exempts a short key. RSA client signatures use SHA-2 only; negotiation uses `golang.org/x/crypto/ssh`'s supported set. See [mirror](DEPLOYMENT.md#ciphertext-blob-mirror). | +| Primary S3 object client (hosted preparation only) | HTTPS only, shared SigV4 HMAC-SHA256 client; explicit environment/_FILE credentials | Credential length is provider-owned, not a content-encryption key size. One nonempty line up to 64 KiB; ambiguous sources refuse. No ambient credential chain, plaintext endpoint or startup enablement. | | S3 blob mirror | HTTPS to AWS, SigV4 (HMAC-SHA256) | A custom `s3_endpoint` may be plain HTTP outside the profile. | | SMB blob mirror | NTLM (MD4, HMAC-MD5, RC4) | An explicit legacy choice ([SMB](DEPLOYMENT.md#smb-compatibility-choice)); refused under the profile. | | Generated tokens | Session tokens 256 random bits and device secrets 192, stored as SHA-256 hashes; CSRF tokens HMAC-SHA256 under a key derived from `pairing.key` | Not operator-supplied. | diff --git a/docs/superpowers/specs/2026-11-23-tenancy-design.md b/docs/superpowers/specs/2026-11-23-tenancy-design.md index 4c4ba3f7..43b7fc0b 100644 --- a/docs/superpowers/specs/2026-11-23-tenancy-design.md +++ b/docs/superpowers/specs/2026-11-23-tenancy-design.md @@ -1570,4 +1570,21 @@ client, volume fallback, automatic pruning or hosted/native-backup readiness is The object preparation consumes the shared client's encoded-byte GET correction: identity encoding preserves opaque gzip-labelled bytes and GET/HEAD size agreement. A regression fails against the earlier published client and passes after the upstream correction. This does not -make the separately prepared/unpublished conditional-PUT/timestamp follow-up available. +make the separately published but unmerged conditional-PUT/timestamp follow-up a merged dependency. + + +### PR 5b-2 as built: credential/client preparation (startup still refused) + +`app.newReplicaObjectClient` consumes the selected environment/_FILE credential forms through +one bounded, setting-name-only reader and the actual shared client's constructor. One form +per key, one nonempty line, at most64KiB; regular files may have one trailing LF/CRLF. +Credentials never enter shared fingerprints/settings or local keys. Construction performs no +network or database I/O and is not called by ordinary startup or maintenance loading. +Tests cover direct/file/mixed sources, ambiguity/empty/size/multiline/path/type refusal, +secret-safe errors/formatting, shared-field separation and unchanged startup refusals. + +Base #77 is merged and pinned to79823f9; published #78 remains unmerged/not consumed. Before +complete GC/purge/runtime binding, Notes must select and qualify delayed remote-PUT fate +after PG-lock loss; cancellation alone is no completion proof. Shared conditional operations +do not select a Notes ledger/protocol. Keep this and native-PG recovery open question3 as +explicit remaining gates, alongside store controls/age/provider proof and lifecycle E2E. diff --git a/internal/app/replica_objects.go b/internal/app/replica_objects.go new file mode 100644 index 00000000..d06bd303 --- /dev/null +++ b/internal/app/replica_objects.go @@ -0,0 +1,65 @@ +package app + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + + shareds3 "github.com/Busnes-app/ky-primitives/s3" +) + +// newReplicaObjectClient prepares the selected primary-object client without network I/O. +// It is separate from maintenance/fingerprint input: credentials are per replica and never +// belong in shared settings. Startup remains refused until every hosted prerequisite exists. +func newReplicaObjectClient(in replicaInputs) (*shareds3.Client, error) { + access, err := replicaObjectCredential("KYNOTES_BLOB_S3_ACCESS_KEY") + if err != nil { + return nil, err + } + secret, err := replicaObjectCredential("KYNOTES_BLOB_S3_SECRET") + if err != nil { + return nil, err + } + client, err := shareds3.New(shareds3.Config{ + Endpoint: in.BlobEndpoint, Bucket: in.BlobBucket, Region: in.BlobRegion, + AccessKey: access, SecretKey: secret, + }) + if err != nil { + return nil, errors.New("replicas: invalid primary object-store configuration") + } + return client, nil +} + +// These paths are operator configuration. Refuse nonregular files before opening them (in +// particular FIFOs/devices); keep the read bounded even if a regular file grows while read. +// Errors name only the setting, never its value, path or an underlying filesystem error. +func replicaObjectCredential(name string) (string, error) { + const maxBytes = 64 << 10 + value, direct := os.LookupEnv(name) + path, file := os.LookupEnv(name + "_FILE") + if direct && file { + return "", fmt.Errorf("replicas: set only one of %s and %s_FILE", name, name) + } + if file { + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() { + return "", fmt.Errorf("replicas: %s_FILE must name a readable regular file", name) + } + f, err := os.Open(path) + if err != nil { + return "", fmt.Errorf("replicas: %s_FILE cannot be read", name) + } + raw, readErr := io.ReadAll(io.LimitReader(f, maxBytes+1)) + closeErr := f.Close() + if readErr != nil || closeErr != nil || len(raw) > maxBytes { + return "", fmt.Errorf("replicas: %s_FILE cannot be read within the credential limit", name) + } + value = strings.TrimSuffix(strings.TrimSuffix(string(raw), "\n"), "\r") + } + if value == "" || len(value) > maxBytes || strings.ContainsAny(value, "\x00\r\n") { + return "", fmt.Errorf("replicas: %s requires one nonempty credential of at most 64 KiB", name) + } + return value, nil +} diff --git a/internal/app/replica_objects_test.go b/internal/app/replica_objects_test.go new file mode 100644 index 00000000..4405fda5 --- /dev/null +++ b/internal/app/replica_objects_test.go @@ -0,0 +1,143 @@ +package app + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/Busnes-app/kynotes-server/internal/config" +) + +func unsetObjectCredential(t *testing.T, name string) { + t.Helper() + for _, key := range []string{name, name + "_FILE"} { + t.Setenv(key, "") // Register restoration of any inherited operator configuration. + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } +} + +func TestReplicaObjectCredentialInputsAreBoundedAndRedacted(t *testing.T) { + const name = "KYNOTES_BLOB_S3_SECRET" + const secret = "private-credential-DO-NOT-DISCLOSE" + for _, tc := range []struct { + name, contents string + file, invalid bool + }{ + {"environment", secret, false, false}, + {"file", secret, true, false}, + {"file-newline", secret + "\n", true, false}, + {"file-crlf", secret + "\r\n", true, false}, + {"empty-environment", "", false, true}, + {"empty-file", "", true, true}, + {"multiline-environment", secret + "\nother", false, true}, + {"multiline-file", secret + "\nother", true, true}, + {"nul-file", secret + "\x00", true, true}, + {"oversized-environment", strings.Repeat("s", (64<<10)+1), false, true}, + {"oversized-file", strings.Repeat("s", (64<<10)+1), true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + unsetObjectCredential(t, name) + path := filepath.Join(t.TempDir(), "path-"+secret) + if tc.file { + if err := os.WriteFile(path, []byte(tc.contents), 0600); err != nil { + t.Fatal(err) + } + t.Setenv(name+"_FILE", path) + } else { + t.Setenv(name, tc.contents) + } + got, err := replicaObjectCredential(name) + if tc.invalid { + if err == nil || got != "" || !strings.Contains(err.Error(), name) || strings.Contains(err.Error(), secret) || strings.Contains(err.Error(), path) { + t.Fatal("credential boundary failed or disclosed input") + } + } else if err != nil || got != secret { + t.Fatal("valid credential was not preserved") + } + }) + } + for _, kind := range []string{"missing", "missing-file", "directory", "both", "both-empty"} { + t.Run(kind, func(t *testing.T) { + unsetObjectCredential(t, name) + switch kind { + case "missing-file": + t.Setenv(name+"_FILE", filepath.Join(t.TempDir(), secret)) + case "directory": + t.Setenv(name+"_FILE", t.TempDir()) + case "both", "both-empty": + value := secret + if kind == "both-empty" { + value = "" + } + t.Setenv(name, value) + t.Setenv(name+"_FILE", secret) + } + got, err := replicaObjectCredential(name) + if err == nil || got != "" || strings.Contains(err.Error(), secret) { + t.Fatal("invalid credential source accepted or disclosed") + } + }) + } +} + +func TestReplicaObjectClientPreparationKeepsKeysOutOfSharedState(t *testing.T) { + replicaEnvironment(t) + const access, secret = "access-DO-NOT-DISCLOSE", "secret-DO-NOT-DISCLOSE" + for _, name := range []string{"KYNOTES_BLOB_S3_ACCESS_KEY", "KYNOTES_BLOB_S3_SECRET"} { + unsetObjectCredential(t, name) + } + t.Setenv("KYNOTES_BLOB_S3_ACCESS_KEY", access) + path := filepath.Join(t.TempDir(), "object-secret") + if err := os.WriteFile(path, []byte(secret+"\n"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("KYNOTES_BLOB_S3_SECRET_FILE", path) + c := config.Defaults() + c.DataDir = filepath.Join(t.TempDir(), "not-created") + c, in, err := readReplicaInputs(c) + if err != nil { + t.Fatal(err) + } + before := replicaFields(c, in) + client, err := newReplicaObjectClient(in) + if err != nil || client == nil { + t.Fatalf("client preparation: %v", err) + } + encoded, err := json.Marshal(client) + if err != nil { + t.Fatal(err) + } + for _, output := range []string{string(encoded), fmt.Sprintf("%v %#v", client, client), fmt.Sprint(replicaFields(c, in))} { + if strings.Contains(output, access) || strings.Contains(output, secret) || strings.Contains(output, path) { + t.Fatal("object credential escaped its boundary") + } + } + if !reflect.DeepEqual(before, replicaFields(c, in)) { + t.Fatal("credentials changed shared fingerprint inputs") + } + if _, err := os.Stat(c.DataDir); !os.IsNotExist(err) { + t.Fatal("client preparation wrote a local store") + } + for _, mode := range []string{"single", "multi"} { + t.Setenv("KYNOTES_TENANCY", mode) + if _, err := config.Load(filepath.Join(c.DataDir, "config.yaml")); err == nil { + t.Fatal("preparation enabled unsupported configuration") + } + } + for _, bad := range []replicaInputs{ + {BlobEndpoint: "http://" + secret, BlobBucket: "notes", BlobRegion: "eu"}, + {BlobEndpoint: "https://objects.example", BlobBucket: "bad/" + secret, BlobRegion: "eu"}, + {BlobEndpoint: "https://objects.example", BlobBucket: "notes", BlobRegion: "bad/" + secret}, + } { + client, err := newReplicaObjectClient(bad) + if err == nil || client != nil || strings.Contains(err.Error(), secret) { + t.Fatal("invalid object configuration accepted or disclosed") + } + } +}