From a95c279df86eb3462f5a90cb46b15c2babf04afb Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 04:43:15 +1100 Subject: [PATCH 1/4] fix(golang): say which cause a ZeroKMS refusal has, and name the keyset A refused data key has two causes. The value is opened under another context, or the client has no grant for its keyset. ZeroKMS answers both with HTTP 403, and the error had an empty Help. A keyset that ZeroKMS does not find was not named in the message. Its Help never said that the keyset may exist but not be granted to this client. ZeroKMS's answer does not say which cause it is. So stack-kms gives RetrieveKeyError::RequestFailed a help for each request kind. For a 403, the help names both causes. The Go client has more facts. A read through a Cipher loads its keyset first, so the client has access to it. The cause is then the context. The Help names the keyset, and the number of scope and binding parts. It never names their values, because they are context values. A read through the Client gets a Help that names both causes. stack-kms has the keyset that a load asked for. LoadKeysetError's Forbidden and KeysetNotFound now store it and name it in the message. The payload includes it as keyset_name or keyset_id. The codes, the Go error values, and their errors.Is matches are the same. Refs #1893 Refs #1897 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 17 + languages/golang/encrypt/README.md | 22 +- languages/golang/encrypt/errors.go | 17 +- languages/golang/encrypt/guest/src/status.rs | 4 +- languages/golang/encrypt/guest/tests/leak.rs | 11 +- languages/golang/encrypt/guest_test.go | 33 ++ languages/golang/encrypt/json.go | 2 +- languages/golang/encrypt/json_fields_test.go | 8 +- languages/golang/encrypt/records.go | 12 +- languages/golang/encrypt/refusal.go | 91 ++++++ languages/golang/encrypt/refusal_test.go | 111 +++++++ packages/stack-encrypt/src/cipher.rs | 2 +- packages/stack-encrypt/tests/keysets.rs | 7 +- packages/stack-kms/CHANGELOG.md | 27 ++ packages/stack-kms/src/client.rs | 89 +++++- packages/stack-kms/src/errors.rs | 312 ++++++++++++++++--- 16 files changed, 705 insertions(+), 60 deletions(-) create mode 100644 languages/golang/encrypt/refusal.go create mode 100644 languages/golang/encrypt/refusal_test.go diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 6833efd306..bf10245776 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,23 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. `[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to one. `stashgen` does not yet map a Go type to it. +### Changed + +- A data key that ZeroKMS refuses (`ErrForbidden`, code + `stack_kms::retrieve_key_failed`) now has a `Help` (#1893). Through a + `*Cipher`, the `Help` says that the context differs. It names the + cipher's keyset, and says how many scope and binding parts the cipher + adds. Through the `*Client`, it names both causes: another context, or no + grant for the value's keyset. Before, the `Help` was empty. +- A keyset that ZeroKMS does not find (`ErrNotFound`, code + `stack_kms::keyset_not_found`) is named in the error's message, and in + its `Fields` as `keyset_name` or `keyset_id` (#1897). The `Help` now says + that the keyset may exist but not be granted to this client. A keyset + that ZeroKMS refuses to load (`stack_kms::load_keyset_forbidden`) is + named in the message and the `Help` too. + +The error values, codes, and `errors.Is` matches are the same as before. + ## [0.1.0-rc.7] - 2026-11-25 ### Upgrading from rc.6 diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 6e67a1e8a8..7df8347483 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -584,9 +584,25 @@ if errors.As(err, &d) { ``` `Field` and `Reason` name the field and the problem (`field_missing`, -`unknown_key`, ...) on a refused plan, record or value. An error the client -raises itself carries no `Diagnostic`: a closed client, a guest that did not -return, `ErrMemoryLock`, and an argument refused before it reached the engine. +`unknown_key`, ...) on a refused plan, record, or value. An error the client +raises itself has no `Diagnostic`: a closed client, a guest that did not +return, `ErrMemoryLock`, or a refused argument. + +ZeroKMS refuses a data key (`ErrForbidden`, code +`stack_kms::retrieve_key_failed`) for one of two causes. The value is opened +under another context, or the client has no grant for the value's keyset. +ZeroKMS gives the same answer for both, so the `Help` says which cause it is +where the call knows: + +- Through a `*Cipher`, the cause is the context, because the cipher loaded + its keyset first. The `Help` names the keyset, and says how many scope and + binding parts the cipher adds. +- Through the `*Client`, the `Help` names both causes. + +A keyset that ZeroKMS does not find (`ErrNotFound`, code +`stack_kms::keyset_not_found`) is named in the `Message`, and in `Fields` as +`keyset_name` or `keyset_id`. ZeroKMS gives the same answer for a keyset +that exists but is not granted to this client. What an error may contain is fixed. It may carry keyset ids and names, field names, counts, index kinds, ZeroKMS request kinds and HTTP statuses. It never diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 15b9dc9313..4c8617eaf3 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -34,9 +34,24 @@ var ( // ErrForbidden is ZeroKMS refusing the request (HTTP 403): the token is // valid but not permitted, or a data key's bound context did not match // the one presented — the production form of a wrong-AAD open. + // + // ZeroKMS refuses a data key (code "stack_kms::retrieve_key_failed") + // with one answer for two causes: the value is opened under another + // context, or the client has no grant for the value's keyset. The + // [Diagnostic]'s Help says which one it is where the call knows. On a + // read through a [Cipher], which loaded its keyset first, the cause is + // the context: the Help names the keyset and how many scope and binding + // parts the cipher adds, never their values. On a read through the + // [Client], the Help names both causes. A keyset ZeroKMS refuses to + // load, such as a disabled one, is "stack_kms::load_keyset_forbidden", + // and its message names the keyset. ErrForbidden = guest.ErrForbidden // ErrNotFound is ZeroKMS reporting a missing resource (HTTP 404): an - // unknown keyset name or id, or a data key that does not exist. + // unknown keyset name or id, or a data key that does not exist. ZeroKMS + // also answers 404 for a keyset that exists but is not granted to this + // client. The message of "stack_kms::keyset_not_found" names the + // keyset, and its Diagnostic's Fields hold it as "keyset_name" or + // "keyset_id" (neither for the default keyset). ErrNotFound = guest.ErrNotFound // ErrConflict is ZeroKMS reporting a resource conflict (HTTP 409). ErrConflict = guest.ErrConflict diff --git a/languages/golang/encrypt/guest/src/status.rs b/languages/golang/encrypt/guest/src/status.rs index 570dd9e5b3..6ce28a5a65 100644 --- a/languages/golang/encrypt/guest/src/status.rs +++ b/languages/golang/encrypt/guest/src/status.rs @@ -235,8 +235,8 @@ fn status_for_kms(error: &stack_kms::Error) -> u32 { }, stack_kms::Error::LoadKeyset(e) => match e { LoadKeysetError::Unauthorized(_) => STATUS_KMS_UNAUTHORIZED, - LoadKeysetError::Forbidden(_) => STATUS_KMS_FORBIDDEN, - LoadKeysetError::KeysetNotFound(_) => STATUS_KMS_NOT_FOUND, + LoadKeysetError::Forbidden { .. } => STATUS_KMS_FORBIDDEN, + LoadKeysetError::KeysetNotFound { .. } => STATUS_KMS_NOT_FOUND, LoadKeysetError::RequestFailed(e) => status_for_kind(&e.kind), LoadKeysetError::InvalidKeyMaterial(_) => STATUS_KMS_OTHER, }, diff --git a/languages/golang/encrypt/guest/tests/leak.rs b/languages/golang/encrypt/guest/tests/leak.rs index b782a2e795..2f973f852e 100644 --- a/languages/golang/encrypt/guest/tests/leak.rs +++ b/languages/golang/encrypt/guest/tests/leak.rs @@ -114,7 +114,7 @@ impl IndexKeySource for Failing { ) -> Result<(Uuid, stack_kms::IndexKey), stack_kms::Error> { match keyset_id { None => self.0.load_index_key(None).await, - Some(_) => Err(LoadKeysetError::KeysetNotFound(vitur(404)).into()), + keyset => Err(LoadKeysetError::from_request(keyset, vitur(404)).into()), } } } @@ -875,11 +875,20 @@ fn a_keyset_not_found_carries_its_help_and_request_kind() { Some("stack_kms::keyset_not_found") ); assert!(text(get(&error, "help")).is_some_and(|help| help.contains("client is unknown"))); + assert!(text(get(&error, "help")).is_some_and(|help| help.contains("not granted"))); + // The keyset the selection named reaches the host, in the message and + // the fields. + assert!( + text(get(&error, "message")).is_some_and(|message| message.contains(r#""tenant""#)), + "{:?}", + text(get(&error, "message")) + ); let fields = get(&error, "fields").expect("fields"); assert_eq!( text(get(fields, "request_kind")).as_deref(), Some("NotFound") ); + assert_eq!(text(get(fields, "keyset_name")).as_deref(), Some("tenant")); let Some(Tree::Array(causes)) = get(&error, "causes") else { panic!("causes"); }; diff --git a/languages/golang/encrypt/guest_test.go b/languages/golang/encrypt/guest_test.go index 32c87ccb67..b1cf1f1f9c 100644 --- a/languages/golang/encrypt/guest_test.go +++ b/languages/golang/encrypt/guest_test.go @@ -262,6 +262,39 @@ func TestTransportOutcomesMapToErrors(t *testing.T) { }) } +// A keyset load ZeroKMS refuses or does not find names the keyset it asked +// for, here the client's default keyset that NewClient loads, and its Help +// says what to check, a grant among it. +func TestAFailedKeysetLoadNamesTheKeyset(t *testing.T) { + guestOrSkip(t) + cases := []struct { + name string + status int + want error + code string + message, help string + }{ + {"404", http.StatusNotFound, ErrNotFound, "stack_kms::keyset_not_found", "Keyset not found: the client is unknown, or has no default keyset", "exists but is not granted to this client"}, + {"403", http.StatusForbidden, ErrForbidden, "stack_kms::load_keyset_forbidden", "the client's default keyset", "Grant the keyset to this client"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + stub := newStub(t, tc.status, "", "missing") + _, err := NewClient(context.Background(), testConfig(stub.URL)...) + if !errors.Is(err, tc.want) { + t.Fatalf("NewClient: %v, want %v", err, tc.want) + } + d := wantDiagnostic(t, err, tc.code) + if !strings.Contains(d.Message, tc.message) { + t.Errorf("Message = %q, want it to contain %q", d.Message, tc.message) + } + if !strings.Contains(d.Help, tc.help) { + t.Errorf("Help = %q, want it to contain %q", d.Help, tc.help) + } + }) + } +} + func TestRoundTripperFailureIsTransport(t *testing.T) { guestOrSkip(t) cfg := testConfig("http://zerokms.invalid") diff --git a/languages/golang/encrypt/json.go b/languages/golang/encrypt/json.go index 20d6e110ac..47cf32de02 100644 --- a/languages/golang/encrypt/json.go +++ b/languages/golang/encrypt/json.go @@ -121,7 +121,7 @@ func (cph *Cipher) jsonOpen(ctx context.Context, plan *record.Plan, field string return inst.call(ctx, inst.jsonOpen, buf(encodedRows), buf(encodedPlan), buf([]byte(field)), buf(encodedRequest), buf(opts)) }) if err != nil { - return nil, err + return nil, cph.explainRefusal(err) } // The output is plaintext: wiped once it is decoded into the caller's // values. diff --git a/languages/golang/encrypt/json_fields_test.go b/languages/golang/encrypt/json_fields_test.go index 9312d57a95..480c1f0e37 100644 --- a/languages/golang/encrypt/json_fields_test.go +++ b/languages/golang/encrypt/json_fields_test.go @@ -499,9 +499,15 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { "no binding": scoped.cipher, "another row": scoped.cipher.Bind(uint64(10)), } { - if _, err := selectorRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { + _, err := selectorRead(other, document) + if !errors.Is(err, encrypt.ErrForbidden) { t.Errorf("%s: Selector opened the entry, or not as ErrForbidden: %v", whose, err) } + // The read went through a cipher, so the Help says how + // many parts it adds, as a record's open does. + if d := (*encrypt.Diagnostic)(nil); errors.As(err, &d) && !strings.Contains(d.Help, "binding part") { + t.Errorf("%s: Selector's Help = %q, want the cipher's parts", whose, d.Help) + } if _, err := subtreeRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { t.Errorf("%s: Subtree opened the row, or not as ErrForbidden: %v", whose, err) } diff --git a/languages/golang/encrypt/records.go b/languages/golang/encrypt/records.go index 6072b2e995..8326019ed8 100644 --- a/languages/golang/encrypt/records.go +++ b/languages/golang/encrypt/records.go @@ -123,7 +123,11 @@ func (cph *Cipher) Open(ctx context.Context, plan *record.Plan, records []record } opts := cph.dataKeyCall() opts.context = cph.context - return cph.client.open(ctx, opts, p, records) + opened, err := cph.client.open(ctx, opts, p, records) + if err != nil { + return nil, cph.explainRefusal(err) + } + return opened, nil } // derive derives one index term for one value of a field, under the plan's @@ -262,7 +266,11 @@ func (c *Client) openAny(ctx context.Context, audit auditFacts, plan *record.Pla if err := plan.Validate(); err != nil { return nil, fmt.Errorf("%w: %v", ErrEncoding, err) } - return c.open(ctx, callOptions{keyset: anyKeyset{}, audit: audit}, plan, records) + opened, err := c.open(ctx, callOptions{keyset: anyKeyset{}, audit: audit}, plan, records) + if err != nil { + return nil, explainClientRefusal(err) + } + return opened, nil } // plan is the declaration's plan with this cipher's extension, checked. A diff --git a/languages/golang/encrypt/refusal.go b/languages/golang/encrypt/refusal.go new file mode 100644 index 0000000000..14ca3daf7b --- /dev/null +++ b/languages/golang/encrypt/refusal.go @@ -0,0 +1,91 @@ +package encrypt + +import ( + "errors" + "fmt" +) + +// codeRetrieveKeyFailed is the code of a data-key request that ZeroKMS +// failed. With ErrForbidden, ZeroKMS refused the data key. +const codeRetrieveKeyFailed = "stack_kms::retrieve_key_failed" + +// ZeroKMS refuses a data key with HTTP 403 for two causes, and its answer +// does not say which: the value is opened under another context than it was +// sealed under, or the client has no grant for the value's keyset. The guest +// gives a Help that names both. The call knows more, so these say which one +// it was where they can. +// +// A Help never names a scope's or a binding's value, or a context label: +// those are context values, which a Diagnostic never carries. It names how +// many parts there are, and the keyset, whose name or id it may carry. + +// explainRefusal gives err the Help for a data key ZeroKMS refused on a +// call through this cipher. The cipher loaded its keyset before it asked for +// a key, so the client has access to the keyset, and the context is what +// differs. Any other error is returned as it is. +func (cph *Cipher) explainRefusal(err error) error { + return withRefusalHelp(err, fmt.Sprintf( + "ZeroKMS refused the data key, because the value was sealed under another context than this cipher opens it under. "+ + "The client loaded this cipher's keyset (%s), so it has access to that keyset. "+ + "This cipher adds %s and %s to the context. "+ + "Open the value through a cipher with the same Cipher.Scope and Cipher.Bind parts as the cipher that encrypted it. "+ + "A row whose context field was changed after it was written fails the same way.", + describeKeyset(cph.keyset), countParts(len(cph.extension), "scope"), countParts(len(cph.bindings), "binding"))) +} + +// clientRefusalHelp is the Help for a data key ZeroKMS refused on a call +// through the Client, which opens each value under the keyset that sealed +// it without loading that keyset first. +const clientRefusalHelp = "ZeroKMS refused the data key. The Client opens a value only under the context stored with it, so one of these is the cause: " + + "the value was encrypted through a cipher with Cipher.Scope or Cipher.Bind parts, which only a cipher with the same parts opens; " + + "this client has no grant for the keyset the value was sealed under; " + + "or the row's context field was changed after it was written. " + + "Open a scoped or bound value through a cipher like the one that encrypted it, and check the keyset's grants in ZeroKMS." + +// explainClientRefusal gives err the Help for a data key ZeroKMS refused on +// a call through the Client. Any other error is returned as it is. +func explainClientRefusal(err error) error { + return withRefusalHelp(err, clientRefusalHelp) +} + +// withRefusalHelp sets help on the Diagnostic of err when err is a data key +// ZeroKMS refused, and returns err. The Diagnostic is the one the guest made +// for this call, so no other caller holds it. +func withRefusalHelp(err error, help string) error { + if !errors.Is(err, ErrForbidden) { + return err + } + var d *Diagnostic + if errors.As(err, &d) && d.Code == codeRetrieveKeyFailed { + d.Help = help + } + return err +} + +// describeKeyset names the keyset a selector selects, as a Help says it. +// Keyset names and ids are details a Diagnostic may carry. +func describeKeyset(sel KeysetSelector) string { + switch s := sel.(type) { + case KeysetName: + return fmt.Sprintf("keyset %q", string(s)) + case KeysetID: + return "keyset " + s.String() + case defaultKeyset: + return "the client's default keyset" + default: + return "its keyset" + } +} + +// countParts says how many parts of a kind there are: "no scope parts", +// "1 scope part", "2 scope parts". +func countParts(n int, kind string) string { + switch n { + case 0: + return "no " + kind + " parts" + case 1: + return "1 " + kind + " part" + default: + return fmt.Sprintf("%d %s parts", n, kind) + } +} diff --git a/languages/golang/encrypt/refusal_test.go b/languages/golang/encrypt/refusal_test.go new file mode 100644 index 0000000000..f81ccc0065 --- /dev/null +++ b/languages/golang/encrypt/refusal_test.go @@ -0,0 +1,111 @@ +package encrypt_test + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/cipherstash/stack/languages/golang/encrypt" + "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" +) + +// A data key ZeroKMS refuses is ErrForbidden with the code +// stack_kms::retrieve_key_failed, whatever the cause. The Help says which +// cause it is where the call knows: a cipher loaded its keyset first, so for +// a cipher the context is what differs; the Client did not, so its Help names +// both causes. Neither names a scope's value. +func TestARefusedDataKeySaysWhichCause(t *testing.T) { + c := deterministicClient(t) + ctx := context.Background() + cipher := c.Keyset(encrypt.KeysetName("tenant-a")) + rows, err := testusers.Encrypt(ctx, cipher.Scope("scope-value-7"), people[:1]) + if err != nil { + t.Fatal(err) + } + defaultRows, err := testusers.Encrypt(ctx, c.DefaultKeyset().Scope("scope-value-7"), people[:1]) + if err != nil { + t.Fatal(err) + } + + cases := []struct { + name string + rows []testusers.EncryptedUser + with encrypt.Decrypter + want []string + }{ + { + name: "a cipher with another scope", + with: cipher.Scope("scope-value-8"), + want: []string{`keyset "tenant-a"`, "1 scope part and no binding parts", "Cipher.Scope", "Cipher.Bind", "context field"}, + }, + { + name: "a cipher with no scope", + with: cipher, + want: []string{`keyset "tenant-a"`, "no scope parts and no binding parts", "Cipher.Scope"}, + }, + { + name: "a cipher with a binding", + with: cipher.Scope("scope-value-7").Bind(int64(1)), + want: []string{"1 scope part and 1 binding part", "Cipher.Bind"}, + }, + { + name: "the default keyset's cipher", + rows: defaultRows, + with: c.DefaultKeyset().Scope("scope-value-7", "scope-value-8"), + want: []string{"the client's default keyset", "2 scope parts"}, + }, + { + name: "the Client", + with: c, + want: []string{"no grant for the keyset", "Cipher.Scope", "Cipher.Bind", "context field"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sealed := rows + if tc.rows != nil { + sealed = tc.rows + } + _, err := testusers.Decrypt(ctx, tc.with, sealed) + if !errors.Is(err, encrypt.ErrForbidden) { + t.Fatalf("Decrypt: %v, want ErrForbidden", err) + } + var d *encrypt.Diagnostic + if !errors.As(err, &d) { + t.Fatalf("Decrypt: %v, want a Diagnostic", err) + } + if d.Code != "stack_kms::retrieve_key_failed" { + t.Errorf("Code = %q, want stack_kms::retrieve_key_failed", d.Code) + } + for _, want := range tc.want { + if !strings.Contains(d.Help, want) { + t.Errorf("Help = %q, want it to contain %q", d.Help, want) + } + } + if strings.Contains(d.Help, "scope-value") || strings.Contains(err.Error(), "scope-value") { + t.Errorf("a scope's value is in the error: %v; Help %q", err, d.Help) + } + }) + } +} + +// A cipher's own Help is given only to a refused data key: other failures +// keep the Help the guest gave them. +func TestOnlyARefusedDataKeyGetsTheCipherHelp(t *testing.T) { + c := deterministicClient(t) + ctx := context.Background() + cipher := c.Keyset(encrypt.KeysetName("tenant-a")) + rows, err := testusers.Encrypt(ctx, cipher, people[:1]) + if err != nil { + t.Fatal(err) + } + _, err = testusers.Decrypt(ctx, c.Keyset(encrypt.KeysetName("tenant-b")), rows) + if !errors.Is(err, encrypt.ErrForeignKeyset) { + t.Fatalf("Decrypt: %v, want ErrForeignKeyset", err) + } + var d *encrypt.Diagnostic + if errors.As(err, &d) && strings.Contains(d.Help, "scope part") { + t.Errorf("a foreign keyset got the refusal's Help: %q", d.Help) + } +} diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index b6d2c0fe75..8847edb77a 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -994,7 +994,7 @@ fn is_keyset_not_found(error: &Error) -> bool { matches!( error, Error::Kms(stack_kms::Error::LoadKeyset( - stack_kms::LoadKeysetError::KeysetNotFound(_) + stack_kms::LoadKeysetError::KeysetNotFound { .. } )) ) } diff --git a/packages/stack-encrypt/tests/keysets.rs b/packages/stack-encrypt/tests/keysets.rs index ca2b84be7b..fe4b403c29 100644 --- a/packages/stack-encrypt/tests/keysets.rs +++ b/packages/stack-encrypt/tests/keysets.rs @@ -158,7 +158,8 @@ impl IndexKeySource for Observed { } Refusal::Unreachable => (ViturRequestErrorKind::SendRequest, "no answer"), }; - Err(stack_kms::Error::from(LoadKeysetError::from( + Err(stack_kms::Error::from(LoadKeysetError::from_request( + keyset_id.clone(), ViturRequestError::new(kind, message, std::io::Error::other(message)), ))) } @@ -411,7 +412,7 @@ async fn a_refused_name_is_zerokms_answer_and_leaves_the_keyset_cached_by_id() { matches!( error, Error::Kms(stack_kms::Error::LoadKeyset( - LoadKeysetError::KeysetNotFound(_) + LoadKeysetError::KeysetNotFound { .. } )) ), "ZeroKMS's not-found reaches the caller as it is, got {error:?}" @@ -475,7 +476,7 @@ async fn an_answer_in_flight_does_not_rebind_a_name_zerokms_has_since_refused() matches!( refused, Err(Error::Kms(stack_kms::Error::LoadKeyset( - LoadKeysetError::KeysetNotFound(_) + LoadKeysetError::KeysetNotFound { .. } ))) ), "the later lookup was refused, got {refused:?}" diff --git a/packages/stack-kms/CHANGELOG.md b/packages/stack-kms/CHANGELOG.md index be1e491a27..e68440352a 100644 --- a/packages/stack-kms/CHANGELOG.md +++ b/packages/stack-kms/CHANGELOG.md @@ -23,6 +23,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `zerokms_keyset::Error` is `#[non_exhaustive]`, so a `match` on the field of `InvalidKeyMaterialError` needs a `_` arm. +- `LoadKeysetError::Forbidden` and `LoadKeysetError::KeysetNotFound` are + struct variants. Each holds the keyset the load asked for, `keyset: + Option` (`None` is the client's default keyset), and + ZeroKMS's answer as `source`. Their messages name that keyset (#1897). + `From for LoadKeysetError` is replaced by + `LoadKeysetError::from_request(keyset, error)`. To migrate: + + - Match `LoadKeysetError::KeysetNotFound { .. }` and + `LoadKeysetError::Forbidden { .. }` in place of + `KeysetNotFound(_)` and `Forbidden(_)`. + - In a key source of your own, replace `LoadKeysetError::from(error)` + with `LoadKeysetError::from_request(keyset_id, error)`, where + `keyset_id` is the keyset that `load_index_key` was asked for. + + The codes are the same: `stack_kms::keyset_not_found` and + `stack_kms::load_keyset_forbidden`. + ### Features - The `wasm-simd` feature. On wasm32 it re-encrypts key material with wasm @@ -31,6 +48,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- `RetrieveKeyError::RequestFailed` has a help for each request kind (#1893). + Before, it had none. A refused data key (HTTP 403) has two causes: the + value is opened under another context, or the client has no grant for its + keyset. ZeroKMS gives the same answer for both, so the help names + both. + The code is the same: `stack_kms::retrieve_key_failed`. +- The help of `LoadKeysetError::KeysetNotFound` says that ZeroKMS also + answers 404 for a keyset that exists but is not granted to this client + (#1897). The payload of a refused or missing keyset includes the keyset + that the load asked for, as `keyset_name` or `keyset_id`. - A batch now yields to the async runtime every 64 keys while it derives data keys. On tokio, the yield reschedules the task. In a wasm guest, it hands control back to the host. The host cannot preempt the guest. diff --git a/packages/stack-kms/src/client.rs b/packages/stack-kms/src/client.rs index fcb8a30742..5153bd3a97 100644 --- a/packages/stack-kms/src/client.rs +++ b/packages/stack-kms/src/client.rs @@ -338,15 +338,21 @@ impl Client { keyset_id: Option, access_token: &str, ) -> Result<(Keyset, IndexKey), LoadKeysetError> { + // Kept for the error: a refusal and a missing keyset name the + // keyset the load asked for. let req = LoadKeysetRequest { client_id: client_key.key_id, - keyset_id, + keyset_id: keyset_id.clone(), }; let LoadKeysetResponse { keyset, partial_index_key, - } = self.connection.send(req, access_token).await?; + } = self + .connection + .send(req, access_token) + .await + .map_err(|error| LoadKeysetError::from_request(keyset_id, error))?; let index_key = IndexKey::from_key_material(client_key, &partial_index_key.key_material)?; @@ -1184,6 +1190,85 @@ mod tests { "expected RequestFailed(SendRequest), got: {err:?}" ); } + + /// A data key ZeroKMS refuses (HTTP 403) carries a help that names + /// both causes, keeping its code. + #[tokio::test] + async fn retrieve_keys_gives_a_refused_data_key_its_help() { + use miette::Diagnostic; + let client_key = random_client_key(); + let client = build_client(|builder| { + builder.add_failed_response::(vitur_error( + ViturRequestErrorKind::Forbidden, + )) + }); + + let err = client + .retrieve_keys( + vec![RetrieveKeyPayload::new(Iv::default(), "a", &[1])], + &client_key, + None, + "token", + None, + ) + .await + .expect_err("a refused request must surface"); + + assert_eq!( + err.code().map(|code| code.to_string()).as_deref(), + Some("stack_kms::retrieve_key_failed") + ); + let help = err.help().map(|help| help.to_string()).unwrap_or_default(); + assert!(help.contains("another context"), "{help}"); + assert!(help.contains("no grant for the keyset"), "{help}"); + } + + /// A keyset load ZeroKMS answers with 404 or 403 names the keyset it + /// asked for, by name or by id, in the message. + #[tokio::test] + async fn load_keyset_names_the_keyset_it_asked_for() { + let client_key = random_client_key(); + let named = Some(IdentifiedBy::Name(zerokms_protocol::Name::new_untrusted( + "tenant-42", + ))); + let by_id = Some(IdentifiedBy::Uuid(uuid!( + "11111111-1111-1111-1111-111111111111" + ))); + for (kind, keyset, shown) in [ + ( + ViturRequestErrorKind::NotFound, + named.clone(), + r#"keyset name "tenant-42""#, + ), + ( + ViturRequestErrorKind::NotFound, + by_id, + "keyset id 11111111-1111-1111-1111-111111111111", + ), + ( + ViturRequestErrorKind::Forbidden, + named, + r#"keyset name "tenant-42""#, + ), + ] { + let expected = format!("{kind:?}"); + let client = build_client(|builder| { + builder.add_failed_response::(vitur_error(kind)) + }); + let err = client + .load_keyset(&client_key, keyset, "token") + .await + .expect_err("a failed load must surface"); + let message = err.to_string(); + assert!(message.contains(shown), "{expected}: {message}"); + assert!(!message.contains("boom"), "{expected}: {message}"); + match err { + LoadKeysetError::KeysetNotFound { .. } => assert_eq!(expected, "NotFound"), + LoadKeysetError::Forbidden { .. } => assert_eq!(expected, "Forbidden"), + other => panic!("{expected}: {other:?}"), + } + } + } } #[tokio::test] diff --git a/packages/stack-kms/src/errors.rs b/packages/stack-kms/src/errors.rs index 22c317f98d..d3dce6e727 100644 --- a/packages/stack-kms/src/errors.rs +++ b/packages/stack-kms/src/errors.rs @@ -2,7 +2,7 @@ use miette::Diagnostic; use stack_auth::diagnostic::{payload, ErrorPayload}; use thiserror::Error; use vitaminc::random::RandomError; -use zerokms_protocol::{ViturRequestError, ViturRequestErrorKind}; +use zerokms_protocol::{IdentifiedBy, ViturRequestError, ViturRequestErrorKind}; /// The fields a failed ZeroKMS request contributes: the request kind /// (`NotFound`, `SendRequest`, ...), and nothing from the response body. @@ -28,6 +28,77 @@ fn request_kind(kind: &ViturRequestErrorKind) -> &'static str { } } +/// The fields a failed keyset load contributes: its request kind, and the +/// keyset it asked for, as `keyset_id` or `keyset_name`, or neither for the +/// client's default keyset. Keyset ids and names are details the +/// [`ErrorPayload`] policy allows. +fn keyset_request_payload( + keyset: Option<&IdentifiedBy>, + error: &ViturRequestError, +) -> serde_json::Map { + let mut fields = request_payload(error); + let named = match keyset { + Some(IdentifiedBy::Uuid(id)) => Some(("keyset_id", id.to_string())), + Some(IdentifiedBy::Name(name)) => Some(("keyset_name", name.to_string())), + None => None, + }; + fields.extend(named.map(|(key, value)| (key.to_owned(), value.into()))); + fields +} + +/// The keyset a load asked for, as a message names it: `name "tenant-42"`, +/// `id 6a70bd18-...`, or the client's default keyset. A name is quoted with +/// Rust's escapes, so a name that ZeroKMS would not issue still prints on +/// one line. +fn requested_keyset(keyset: Option<&IdentifiedBy>) -> String { + match keyset { + Some(IdentifiedBy::Uuid(id)) => format!("keyset id {id}"), + Some(IdentifiedBy::Name(name)) => format!("keyset name {:?}", &**name), + None => "the client's default keyset".into(), + } +} + +/// What a keyset-not-found message says after "Keyset not found: ". A keyset +/// asked for by id or name may exist and not be granted to this client. The +/// default keyset is missing when the client is unknown or has none. +fn not_found(keyset: Option<&IdentifiedBy>) -> String { + match keyset { + Some(_) => format!( + "{}, or it is not granted to this client", + requested_keyset(keyset) + ), + None => "the client is unknown, or has no default keyset".into(), + } +} + +/// The help for a data-key request ZeroKMS failed, by the request kind. +/// ZeroKMS answers a refused data key with HTTP 403 whatever the reason, +/// and nothing in its answer says which reason it was. So the help for a +/// 403 names both causes. A binding that knows more about the call, such as +/// whether it loaded the keyset first, may replace it with the one cause. +fn retrieve_help(kind: &ViturRequestErrorKind) -> &'static str { + match kind { + ViturRequestErrorKind::Forbidden => { + "ZeroKMS refused the data key. Either the value is opened under another context than the one it was sealed under, or this client has no grant for the keyset the value was sealed under. Open the value under the context it was sealed with, and check the keyset's grants in ZeroKMS." + } + ViturRequestErrorKind::Unauthorized => { + "ZeroKMS refused the access token. Refresh the credential and retry." + } + ViturRequestErrorKind::NotFound => { + "ZeroKMS found no keyset or data key for the value. Check that the keyset the value was sealed under exists in this workspace, and is granted to this client." + } + ViturRequestErrorKind::PrepareRequest | ViturRequestErrorKind::SendRequest => { + "The request did not reach ZeroKMS. Check the network and the ZeroKMS endpoint, and retry." + } + ViturRequestErrorKind::Conflict + | ViturRequestErrorKind::FailureResponse + | ViturRequestErrorKind::ParseResponse + | ViturRequestErrorKind::Other => { + "ZeroKMS failed the request, or sent a response the client could not read. Retry, and report the error if it persists." + } + } +} + /// The fields of a key-count mismatch. fn count_payload(expected: usize, received: usize) -> serde_json::Map { payload([("expected", expected.into()), ("received", received.into())]) @@ -47,9 +118,13 @@ impl ErrorPayload for InvalidKeyMaterialError {} #[derive(Diagnostic, Error, Debug)] pub enum RetrieveKeyError { // `ViturRequestError`'s Display is its kind and a static message; the - // response it carries stays behind `source()`. + // response it carries stays behind `source()`. The help is the request + // kind's (see `retrieve_help`). #[error("Failed to send request: {0}")] - #[diagnostic(code(stack_kms::retrieve_key_failed))] + #[diagnostic( + code(stack_kms::retrieve_key_failed), + help("{}", retrieve_help(&.0.kind)) + )] RequestFailed(#[from] ViturRequestError), #[error("Received an invalid number of keys from request. Expected {expected} but received {received}")] #[diagnostic(code(stack_kms::retrieved_key_count))] @@ -158,24 +233,42 @@ pub enum LoadKeysetError { help("ZeroKMS refused the access token. Refresh the credential and retry.") )] Unauthorized(#[source] ViturRequestError), - #[error("Request forbidden due to insufficient permissions")] + /// ZeroKMS refused to load the keyset. The message and help name the + /// keyset the load asked for: a keyset id or name is a detail the + /// [`ErrorPayload`] policy allows. + #[error("Request forbidden due to insufficient permissions: {}", requested_keyset(.keyset.as_ref()))] #[diagnostic( code(stack_kms::load_keyset_forbidden), - help("The client is not granted this keyset, or the keyset is disabled.") + help("The client is not granted {}, or the keyset is disabled. Grant the keyset to this client in ZeroKMS, or enable it.", requested_keyset(.keyset.as_ref())) )] - Forbidden(#[source] ViturRequestError), + Forbidden { + /// The keyset the load asked for. `None` is the client's default. + keyset: Option, + /// ZeroKMS's answer. + #[source] + source: ViturRequestError, + }, // `load-keyset` uniquely takes a caller-supplied keyset id or name, so a // server 404 is an expected, user-actionable outcome — e.g. a typo'd // name — not an "unexpected error". Note the server also responds 404 - // when the *client* is unknown or has no default keyset, so a 404 does - // not prove the named keyset is missing: inspect `source()` for the - // server's response body before treating this as "create the keyset". - #[error("Keyset not found (or the client is unknown or has no default keyset)")] + // when the keyset exists but is not granted to this client, and when the + // *client* is unknown or has no default keyset, so a 404 does not prove + // the named keyset is missing: inspect `source()` for the server's + // response body before treating this as "create the keyset". + /// ZeroKMS has no keyset this client may load under the id or name the + /// load asked for. The message names the keyset. + #[error("Keyset not found: {}", not_found(.keyset.as_ref()))] #[diagnostic( code(stack_kms::keyset_not_found), - help("ZeroKMS answers 404 when no keyset has this id or name, and also when the client is unknown or has no default keyset. Check the client ID and the keyset's name before creating a keyset.") + help("ZeroKMS answers 404 when no keyset has this id or name, when the keyset exists but is not granted to this client, and when the client is unknown or has no default keyset. Check the keyset's name, the client ID, and the keyset's grants in ZeroKMS before creating a keyset.") )] - KeysetNotFound(#[source] ViturRequestError), + KeysetNotFound { + /// The keyset the load asked for. `None` is the client's default. + keyset: Option, + /// ZeroKMS's answer. + #[source] + source: ViturRequestError, + }, #[error(transparent)] #[diagnostic(transparent)] InvalidKeyMaterial(#[from] InvalidKeyMaterialError), @@ -189,22 +282,31 @@ pub enum LoadKeysetError { impl ErrorPayload for LoadKeysetError { fn payload(&self) -> serde_json::Map { match self { - Self::Unauthorized(error) - | Self::Forbidden(error) - | Self::KeysetNotFound(error) - | Self::RequestFailed(error) => request_payload(error), + Self::Unauthorized(error) | Self::RequestFailed(error) => request_payload(error), + Self::Forbidden { keyset, source } | Self::KeysetNotFound { keyset, source } => { + keyset_request_payload(keyset.as_ref(), source) + } Self::InvalidKeyMaterial(error) => error.payload(), } } } -impl From for LoadKeysetError { - fn from(err: ViturRequestError) -> Self { - match err.kind { - ViturRequestErrorKind::Forbidden => Self::Forbidden(err), - ViturRequestErrorKind::Unauthorized => Self::Unauthorized(err), - ViturRequestErrorKind::NotFound => Self::KeysetNotFound(err), - _ => Self::RequestFailed(err), +impl LoadKeysetError { + /// The error for a failed request to load `keyset` (`None` is the + /// client's default keyset), by the request's kind. A refusal and a + /// missing keyset name the keyset they are about. + pub fn from_request(keyset: Option, error: ViturRequestError) -> Self { + match error.kind { + ViturRequestErrorKind::Forbidden => Self::Forbidden { + keyset, + source: error, + }, + ViturRequestErrorKind::Unauthorized => Self::Unauthorized(error), + ViturRequestErrorKind::NotFound => Self::KeysetNotFound { + keyset, + source: error, + }, + _ => Self::RequestFailed(error), } } } @@ -309,11 +411,13 @@ mod codes { LoadKeysetError::Unauthorized(_) => { LoadKeysetError::Unauthorized(vitur(ViturRequestErrorKind::Unauthorized)) }, - LoadKeysetError::Forbidden(_) => { - LoadKeysetError::Forbidden(vitur(ViturRequestErrorKind::Forbidden)) + LoadKeysetError::Forbidden { .. } => LoadKeysetError::Forbidden { + keyset: None, + source: vitur(ViturRequestErrorKind::Forbidden), }, - LoadKeysetError::KeysetNotFound(_) => { - LoadKeysetError::KeysetNotFound(vitur(ViturRequestErrorKind::NotFound)) + LoadKeysetError::KeysetNotFound { .. } => LoadKeysetError::KeysetNotFound { + keyset: None, + source: vitur(ViturRequestErrorKind::NotFound), }, LoadKeysetError::InvalidKeyMaterial(_) => { LoadKeysetError::InvalidKeyMaterial(material()) @@ -329,9 +433,10 @@ mod codes { Error::RetrieveKey(_) => { Error::RetrieveKey(RetrieveKeyError::FailedRetrieval("no key".into())) }, - Error::LoadKeyset(_) => Error::LoadKeyset(LoadKeysetError::KeysetNotFound(vitur( - ViturRequestErrorKind::NotFound, - ))), + Error::LoadKeyset(_) => Error::LoadKeyset(LoadKeysetError::from_request( + None, + vitur(ViturRequestErrorKind::NotFound), + )), Error::Auth(_) => { Error::Auth(stack_auth::AuthError::TokenExpired(stack_auth::TokenExpired)) }, @@ -441,9 +546,10 @@ mod codes { /// carried: the detail behind `source()` stays out of the payload too. #[test] fn a_request_failure_gives_the_kind_and_not_the_response() { - let error = Error::LoadKeyset(LoadKeysetError::KeysetNotFound(vitur( - ViturRequestErrorKind::NotFound, - ))); + let error = Error::LoadKeyset(LoadKeysetError::from_request( + None, + vitur(ViturRequestErrorKind::NotFound), + )); let fields = error.payload(); assert_eq!(fields["request_kind"], "NotFound"); assert!(!format!("{fields:?}").contains("detail"), "{fields:?}"); @@ -452,6 +558,118 @@ mod codes { .is_some_and(|help| help.to_string().contains("client is unknown"))); } + fn name(name: &str) -> Option { + Some(IdentifiedBy::Name(zerokms_protocol::Name::new_untrusted( + name, + ))) + } + + const ID: uuid::Uuid = uuid::uuid!("6a70bd18-99ac-4650-b104-37eec3a15b09"); + + fn help_of(error: &dyn Diagnostic) -> String { + error + .help() + .map(|help| help.to_string()) + .unwrap_or_default() + } + + /// A keyset ZeroKMS did not find is named in the message and the + /// payload, by name or by id, and the help says that a keyset which + /// exists but is not granted to this client is answered the same way. + #[test] + fn a_keyset_not_found_names_the_keyset_and_says_it_may_not_be_granted() { + let cases = [ + ( + name("tenant-42"), + r#"Keyset not found: keyset name "tenant-42", or it is not granted to this client"#, + Some(("keyset_name", "tenant-42")), + ), + ( + Some(IdentifiedBy::Uuid(ID)), + "Keyset not found: keyset id 6a70bd18-99ac-4650-b104-37eec3a15b09, or it is not granted to this client", + Some(("keyset_id", "6a70bd18-99ac-4650-b104-37eec3a15b09")), + ), + ( + None, + "Keyset not found: the client is unknown, or has no default keyset", + None, + ), + ]; + for (keyset, message, field) in cases { + let error = + LoadKeysetError::from_request(keyset, vitur(ViturRequestErrorKind::NotFound)); + assert!(matches!(error, LoadKeysetError::KeysetNotFound { .. })); + assert_eq!(error.to_string(), message); + assert_eq!( + error.code().map(|code| code.to_string()).as_deref(), + Some("stack_kms::keyset_not_found") + ); + let help = help_of(&error); + assert!(help.contains("not granted to this client"), "{help}"); + let fields = error.payload(); + assert_eq!(fields["request_kind"], "NotFound"); + match field { + Some((key, value)) => assert_eq!(fields[key], value, "{fields:?}"), + None => assert!( + !fields.contains_key("keyset_id") && !fields.contains_key("keyset_name"), + "{fields:?}" + ), + } + } + } + + /// A refused keyset load names the keyset in its message and help. + #[test] + fn a_refused_keyset_load_names_the_keyset() { + let error = LoadKeysetError::from_request( + name("tenant-42"), + vitur(ViturRequestErrorKind::Forbidden), + ); + assert!(matches!(error, LoadKeysetError::Forbidden { .. })); + assert_eq!( + error.to_string(), + r#"Request forbidden due to insufficient permissions: keyset name "tenant-42""# + ); + assert_eq!( + help_of(&error), + r#"The client is not granted keyset name "tenant-42", or the keyset is disabled. Grant the keyset to this client in ZeroKMS, or enable it."# + ); + assert_eq!(error.payload()["keyset_name"], "tenant-42"); + let default = LoadKeysetError::from_request(None, vitur(ViturRequestErrorKind::Forbidden)); + assert!( + help_of(&default).starts_with("The client is not granted the client's default keyset"), + "{}", + help_of(&default) + ); + } + + /// Every request kind a data-key request can fail with has a help, and + /// a refusal (HTTP 403) names both of its causes: another context, and + /// a keyset with no grant for this client. + #[test] + fn every_data_key_request_failure_has_a_help() { + use ViturRequestErrorKind as K; + for kind in [ + K::PrepareRequest, + K::SendRequest, + K::NotFound, + K::Conflict, + K::FailureResponse, + K::ParseResponse, + K::Unauthorized, + K::Forbidden, + K::Other, + ] { + let shown = format!("{kind:?}"); + let help = help_of(&RetrieveKeyError::RequestFailed(vitur(kind))); + assert!(!help.is_empty(), "{shown} has no help"); + assert!(!help.contains("detail"), "{shown}: {help}"); + } + let help = help_of(&RetrieveKeyError::RequestFailed(vitur(K::Forbidden))); + assert!(help.contains("another context"), "{help}"); + assert!(help.contains("no grant for the keyset"), "{help}"); + } + /// Every structured field this crate adds. A binding passes these on as /// they are, so a renamed key breaks the callers that read it. #[test] @@ -645,10 +863,20 @@ mod load_keyset_error_from_vitur_request_error { use super::vitur_error_mapping_support::*; use super::*; + /// A failed load of the keyset named "tenant-42". + fn load(error: ViturRequestError) -> LoadKeysetError { + LoadKeysetError::from_request( + Some(IdentifiedBy::Name(zerokms_protocol::Name::new_untrusted( + "tenant-42", + ))), + error, + ) + } + #[test] fn forbidden_maps_to_forbidden_keeping_the_source() { - let mapped = LoadKeysetError::from(err(ViturRequestErrorKind::Forbidden)); - assert!(matches!(mapped, LoadKeysetError::Forbidden(_))); + let mapped = load(err(ViturRequestErrorKind::Forbidden)); + assert!(matches!(mapped, LoadKeysetError::Forbidden { .. })); assert!( std::error::Error::source(&mapped).is_some(), "the server response (e.g. 'Keyset disabled') must stay reachable" @@ -657,15 +885,15 @@ mod load_keyset_error_from_vitur_request_error { #[test] fn unauthorized_maps_to_unauthorized_keeping_the_source() { - let mapped = LoadKeysetError::from(err(ViturRequestErrorKind::Unauthorized)); + let mapped = load(err(ViturRequestErrorKind::Unauthorized)); assert!(matches!(mapped, LoadKeysetError::Unauthorized(_))); assert!(std::error::Error::source(&mapped).is_some()); } #[test] fn not_found_maps_to_keyset_not_found() { - let mapped = LoadKeysetError::from(err(ViturRequestErrorKind::NotFound)); - assert!(matches!(mapped, LoadKeysetError::KeysetNotFound(_))); + let mapped = load(err(ViturRequestErrorKind::NotFound)); + assert!(matches!(mapped, LoadKeysetError::KeysetNotFound { .. })); assert!(std::error::Error::source(&mapped).is_some()); } @@ -680,7 +908,7 @@ mod load_keyset_error_from_vitur_request_error { ViturRequestErrorKind::ParseResponse, ViturRequestErrorKind::Other, ], - LoadKeysetError::from, + load, |mapped, name| matches!(mapped, LoadKeysetError::RequestFailed(e) if format!("{:?}", e.kind) == name), ); } @@ -693,7 +921,7 @@ mod load_keyset_error_from_vitur_request_error { ViturRequestErrorKind::NotFound, ViturRequestErrorKind::SendRequest, ] { - let mapped = LoadKeysetError::from(err(kind)); + let mapped = load(err(kind)); let shown = mapped.to_string(); assert!( !shown.contains(SOURCE_DETAIL), @@ -704,9 +932,7 @@ mod load_keyset_error_from_vitur_request_error { #[test] fn request_failed_display_names_the_kind_and_message() { - assert_request_failed_display(&LoadKeysetError::from(err( - ViturRequestErrorKind::SendRequest, - ))); + assert_request_failed_display(&load(err(ViturRequestErrorKind::SendRequest))); } } From 5629cd4fd01cfe97ee2c236e28541e82188dd501 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 05:42:16 +1100 Subject: [PATCH 2/4] fix(golang): name the causes ZeroKMS answers 403 for, not a missing grant ZeroKMS answers a client with no grant for a keyset with 404, not 403. Its retrieve_data_key and load_keyset look up the client's grant first. A 403 means another context, a disabled keyset, or a token without the scope to retrieve keys. So the helps that named a missing grant for a 403 sent a developer to the wrong fix. The helps now name those three causes. The 404 help names the grant. Through a cipher, the Help says the context is the likely cause, and that a keyset disabled since it was loaded fails the same way. A keyset named by id or name is also not found when the client is unknown, and the message now says so. The JSON field test now requires a Diagnostic on all three JSON reads, and checks each one's Help. Refs #1893 Refs #1897 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 14 ++--- languages/golang/encrypt/README.md | 28 ++++++---- languages/golang/encrypt/errors.go | 20 +++---- languages/golang/encrypt/guest_test.go | 2 +- languages/golang/encrypt/json_fields_test.go | 36 ++++++++----- languages/golang/encrypt/refusal.go | 29 ++++++----- languages/golang/encrypt/refusal_test.go | 10 ++-- packages/stack-kms/CHANGELOG.md | 21 ++++---- packages/stack-kms/src/client.rs | 4 +- packages/stack-kms/src/errors.rs | 55 ++++++++++++-------- 10 files changed, 129 insertions(+), 90 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index bf10245776..91b9eba9dc 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -26,14 +26,16 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. - A data key that ZeroKMS refuses (`ErrForbidden`, code `stack_kms::retrieve_key_failed`) now has a `Help` (#1893). Through a - `*Cipher`, the `Help` says that the context differs. It names the - cipher's keyset, and says how many scope and binding parts the cipher - adds. Through the `*Client`, it names both causes: another context, or no - grant for the value's keyset. Before, the `Help` was empty. + `*Cipher`, the `Help` says that the context is the likely cause. It + names the cipher's keyset, and says how many scope and binding parts the + cipher adds. Through the `*Client`, it names every cause: another + context, a disabled keyset, or a token without the scope to retrieve + keys. Before, the `Help` was empty. - A keyset that ZeroKMS does not find (`ErrNotFound`, code `stack_kms::keyset_not_found`) is named in the error's message, and in - its `Fields` as `keyset_name` or `keyset_id` (#1897). The `Help` now says - that the keyset may exist but not be granted to this client. A keyset + its `Fields` as `keyset_name` or `keyset_id` (#1897). The message and the + `Help` now say that the keyset may not be granted to this client, or + that the client may be unknown. A keyset that ZeroKMS refuses to load (`stack_kms::load_keyset_forbidden`) is named in the message and the `Help` too. diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 7df8347483..57aee7ded4 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -585,24 +585,30 @@ if errors.As(err, &d) { `Field` and `Reason` name the field and the problem (`field_missing`, `unknown_key`, ...) on a refused plan, record, or value. An error the client -raises itself has no `Diagnostic`: a closed client, a guest that did not -return, `ErrMemoryLock`, or a refused argument. +raises itself has no `Diagnostic`. These are a closed client, a guest that +did not return, `ErrMemoryLock`, and an argument refused before it reached +the engine. ZeroKMS refuses a data key (`ErrForbidden`, code -`stack_kms::retrieve_key_failed`) for one of two causes. The value is opened -under another context, or the client has no grant for the value's keyset. -ZeroKMS gives the same answer for both, so the `Help` says which cause it is -where the call knows: +`stack_kms::retrieve_key_failed`) for one of three causes: -- Through a `*Cipher`, the cause is the context, because the cipher loaded - its keyset first. The `Help` names the keyset, and says how many scope and - binding parts the cipher adds. -- Through the `*Client`, the `Help` names both causes. +- the value is opened under another context; +- the keyset is disabled; +- the access token lacks the scope to retrieve keys. + +ZeroKMS gives the same answer for all three, so the `Help` says which cause +is likely where the call knows: + +- Through a `*Cipher`, the likely cause is the context, because the cipher + loaded its keyset first. The `Help` names the keyset, and says how many + scope and binding parts the cipher adds. +- Through the `*Client`, the `Help` names every cause. A keyset that ZeroKMS does not find (`ErrNotFound`, code `stack_kms::keyset_not_found`) is named in the `Message`, and in `Fields` as `keyset_name` or `keyset_id`. ZeroKMS gives the same answer for a keyset -that exists but is not granted to this client. +that exists but is not granted to this client, and for a client it does +not know. What an error may contain is fixed. It may carry keyset ids and names, field names, counts, index kinds, ZeroKMS request kinds and HTTP statuses. It never diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 4c8617eaf3..512e0b221c 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -36,15 +36,17 @@ var ( // the one presented — the production form of a wrong-AAD open. // // ZeroKMS refuses a data key (code "stack_kms::retrieve_key_failed") - // with one answer for two causes: the value is opened under another - // context, or the client has no grant for the value's keyset. The - // [Diagnostic]'s Help says which one it is where the call knows. On a - // read through a [Cipher], which loaded its keyset first, the cause is - // the context: the Help names the keyset and how many scope and binding - // parts the cipher adds, never their values. On a read through the - // [Client], the Help names both causes. A keyset ZeroKMS refuses to - // load, such as a disabled one, is "stack_kms::load_keyset_forbidden", - // and its message names the keyset. + // with one answer for three causes: the value is opened under another + // context, the keyset is disabled, or the token lacks the scope to + // retrieve keys. The [Diagnostic]'s Help says which cause is likely + // where the call knows. On a read through a [Cipher], which loaded its + // keyset first, the likely cause is the context: the Help names the + // keyset and how many scope and binding parts the cipher adds, never + // their values. On a read through the [Client], the Help names every + // cause. A keyset ZeroKMS refuses to load, a disabled one or one asked + // for with a token that lacks the scope, is + // "stack_kms::load_keyset_forbidden", and its message names the keyset. + // A keyset that is not granted to this client is [ErrNotFound]. ErrForbidden = guest.ErrForbidden // ErrNotFound is ZeroKMS reporting a missing resource (HTTP 404): an // unknown keyset name or id, or a data key that does not exist. ZeroKMS diff --git a/languages/golang/encrypt/guest_test.go b/languages/golang/encrypt/guest_test.go index b1cf1f1f9c..db6810b698 100644 --- a/languages/golang/encrypt/guest_test.go +++ b/languages/golang/encrypt/guest_test.go @@ -275,7 +275,7 @@ func TestAFailedKeysetLoadNamesTheKeyset(t *testing.T) { message, help string }{ {"404", http.StatusNotFound, ErrNotFound, "stack_kms::keyset_not_found", "Keyset not found: the client is unknown, or has no default keyset", "exists but is not granted to this client"}, - {"403", http.StatusForbidden, ErrForbidden, "stack_kms::load_keyset_forbidden", "the client's default keyset", "Grant the keyset to this client"}, + {"403", http.StatusForbidden, ErrForbidden, "stack_kms::load_keyset_forbidden", "the client's default keyset", "The keyset is disabled, or the access token lacks the scope"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/languages/golang/encrypt/json_fields_test.go b/languages/golang/encrypt/json_fields_test.go index 480c1f0e37..0d752bc42e 100644 --- a/languages/golang/encrypt/json_fields_test.go +++ b/languages/golang/encrypt/json_fields_test.go @@ -499,20 +499,28 @@ func TestACustomersDocumentReadsThroughACipherWithABinding(t *testing.T) { "no binding": scoped.cipher, "another row": scoped.cipher.Bind(uint64(10)), } { - _, err := selectorRead(other, document) - if !errors.Is(err, encrypt.ErrForbidden) { - t.Errorf("%s: Selector opened the entry, or not as ErrForbidden: %v", whose, err) - } - // The read went through a cipher, so the Help says how - // many parts it adds, as a record's open does. - if d := (*encrypt.Diagnostic)(nil); errors.As(err, &d) && !strings.Contains(d.Help, "binding part") { - t.Errorf("%s: Selector's Help = %q, want the cipher's parts", whose, d.Help) - } - if _, err := subtreeRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { - t.Errorf("%s: Subtree opened the row, or not as ErrForbidden: %v", whose, err) - } - if _, err := childrenRead(other, document); !errors.Is(err, encrypt.ErrForbidden) { - t.Errorf("%s: Children opened the child, or not as ErrForbidden: %v", whose, err) + _, selectorErr := selectorRead(other, document) + _, subtreeErr := subtreeRead(other, document) + _, childrenErr := childrenRead(other, document) + for read, err := range map[string]error{ + "Selector": selectorErr, + "Subtree": subtreeErr, + "Children": childrenErr, + } { + if !errors.Is(err, encrypt.ErrForbidden) { + t.Errorf("%s: %s opened the value, or not as ErrForbidden: %v", whose, read, err) + continue + } + // The read went through a cipher, so the Help says how + // many parts it adds, as a record's open does. + var d *encrypt.Diagnostic + if !errors.As(err, &d) { + t.Errorf("%s: %s's error has no Diagnostic: %v", whose, read, err) + continue + } + if !strings.Contains(d.Help, "binding part") { + t.Errorf("%s: %s's Help = %q, want the cipher's parts", whose, read, d.Help) + } } } diff --git a/languages/golang/encrypt/refusal.go b/languages/golang/encrypt/refusal.go index 14ca3daf7b..e3aa4d57ab 100644 --- a/languages/golang/encrypt/refusal.go +++ b/languages/golang/encrypt/refusal.go @@ -9,11 +9,12 @@ import ( // failed. With ErrForbidden, ZeroKMS refused the data key. const codeRetrieveKeyFailed = "stack_kms::retrieve_key_failed" -// ZeroKMS refuses a data key with HTTP 403 for two causes, and its answer +// ZeroKMS refuses a data key with HTTP 403 for three causes, and its answer // does not say which: the value is opened under another context than it was -// sealed under, or the client has no grant for the value's keyset. The guest -// gives a Help that names both. The call knows more, so these say which one -// it was where they can. +// sealed under, the keyset is disabled, or the access token lacks the scope +// to retrieve keys. A client with no grant for the keyset is answered 404, +// which is ErrNotFound. The guest gives a Help that names all three. The +// call knows more, so these say which cause is likely where they can. // // A Help never names a scope's or a binding's value, or a context label: // those are context values, which a Diagnostic never carries. It names how @@ -21,15 +22,17 @@ const codeRetrieveKeyFailed = "stack_kms::retrieve_key_failed" // explainRefusal gives err the Help for a data key ZeroKMS refused on a // call through this cipher. The cipher loaded its keyset before it asked for -// a key, so the client has access to the keyset, and the context is what -// differs. Any other error is returned as it is. +// a key, and ZeroKMS refuses that load for a disabled keyset or a token +// without the scope. So the context is the likely cause. The keyset may +// still have been disabled since the load, because the guest caches it. +// Any other error is returned as it is. func (cph *Cipher) explainRefusal(err error) error { return withRefusalHelp(err, fmt.Sprintf( - "ZeroKMS refused the data key, because the value was sealed under another context than this cipher opens it under. "+ - "The client loaded this cipher's keyset (%s), so it has access to that keyset. "+ + "ZeroKMS refused the data key. This cipher loaded its keyset (%s), so the keyset was enabled when it was loaded. "+ + "The likely cause is that the value was sealed under another context than this cipher opens it under. "+ "This cipher adds %s and %s to the context. "+ "Open the value through a cipher with the same Cipher.Scope and Cipher.Bind parts as the cipher that encrypted it. "+ - "A row whose context field was changed after it was written fails the same way.", + "A row whose context field was changed after it was written fails the same way, and so does a keyset disabled since it was loaded.", describeKeyset(cph.keyset), countParts(len(cph.extension), "scope"), countParts(len(cph.bindings), "binding"))) } @@ -38,9 +41,11 @@ func (cph *Cipher) explainRefusal(err error) error { // it without loading that keyset first. const clientRefusalHelp = "ZeroKMS refused the data key. The Client opens a value only under the context stored with it, so one of these is the cause: " + "the value was encrypted through a cipher with Cipher.Scope or Cipher.Bind parts, which only a cipher with the same parts opens; " + - "this client has no grant for the keyset the value was sealed under; " + - "or the row's context field was changed after it was written. " + - "Open a scoped or bound value through a cipher like the one that encrypted it, and check the keyset's grants in ZeroKMS." + "the row's context field was changed after it was written; " + + "the keyset the value was sealed under is disabled; " + + "or the access token lacks the scope to retrieve keys. " + + "Open a scoped or bound value through a cipher like the one that encrypted it. " + + "A keyset that is not granted to this client gives ErrNotFound, not this error." // explainClientRefusal gives err the Help for a data key ZeroKMS refused on // a call through the Client. Any other error is returned as it is. diff --git a/languages/golang/encrypt/refusal_test.go b/languages/golang/encrypt/refusal_test.go index f81ccc0065..01b2518e58 100644 --- a/languages/golang/encrypt/refusal_test.go +++ b/languages/golang/encrypt/refusal_test.go @@ -12,9 +12,9 @@ import ( // A data key ZeroKMS refuses is ErrForbidden with the code // stack_kms::retrieve_key_failed, whatever the cause. The Help says which -// cause it is where the call knows: a cipher loaded its keyset first, so for -// a cipher the context is what differs; the Client did not, so its Help names -// both causes. Neither names a scope's value. +// cause is likely where the call knows: a cipher loaded its keyset first, so +// for a cipher the context is the likely cause; the Client did not, so its +// Help names every cause. Neither names a scope's value. func TestARefusedDataKeySaysWhichCause(t *testing.T) { c := deterministicClient(t) ctx := context.Background() @@ -37,7 +37,7 @@ func TestARefusedDataKeySaysWhichCause(t *testing.T) { { name: "a cipher with another scope", with: cipher.Scope("scope-value-8"), - want: []string{`keyset "tenant-a"`, "1 scope part and no binding parts", "Cipher.Scope", "Cipher.Bind", "context field"}, + want: []string{`keyset "tenant-a"`, "1 scope part and no binding parts", "Cipher.Scope", "Cipher.Bind", "context field", "disabled since it was loaded"}, }, { name: "a cipher with no scope", @@ -58,7 +58,7 @@ func TestARefusedDataKeySaysWhichCause(t *testing.T) { { name: "the Client", with: c, - want: []string{"no grant for the keyset", "Cipher.Scope", "Cipher.Bind", "context field"}, + want: []string{"keyset the value was sealed under is disabled", "scope to retrieve keys", "Cipher.Scope", "Cipher.Bind", "context field", "ErrNotFound"}, }, } for _, tc := range cases { diff --git a/packages/stack-kms/CHANGELOG.md b/packages/stack-kms/CHANGELOG.md index e68440352a..3bd2d6466c 100644 --- a/packages/stack-kms/CHANGELOG.md +++ b/packages/stack-kms/CHANGELOG.md @@ -49,15 +49,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - `RetrieveKeyError::RequestFailed` has a help for each request kind (#1893). - Before, it had none. A refused data key (HTTP 403) has two causes: the - value is opened under another context, or the client has no grant for its - keyset. ZeroKMS gives the same answer for both, so the help names - both. - The code is the same: `stack_kms::retrieve_key_failed`. -- The help of `LoadKeysetError::KeysetNotFound` says that ZeroKMS also - answers 404 for a keyset that exists but is not granted to this client - (#1897). The payload of a refused or missing keyset includes the keyset - that the load asked for, as `keyset_name` or `keyset_id`. + Before, it had none. ZeroKMS refuses a data key (HTTP 403) for three + causes: another context, a disabled keyset, or a token without the scope + to retrieve keys. Its answer does not say which, so the help names + all three. A missing grant is answered 404, and its help says so. The + code is the same: `stack_kms::retrieve_key_failed`. +- The message and help of `LoadKeysetError::KeysetNotFound` say that ZeroKMS + also answers 404 for a keyset not granted to this client, or an unknown + client (#1897). The help of `LoadKeysetError::Forbidden` names its + causes: a disabled keyset, or a token without the scope to use keys. + Before, it named a missing grant. ZeroKMS answers a missing grant with 404. The + payload of a refused or missing keyset includes the keyset that the load + asked for, as `keyset_name` or `keyset_id`. - A batch now yields to the async runtime every 64 keys while it derives data keys. On tokio, the yield reschedules the task. In a wasm guest, it hands control back to the host. The host cannot preempt the guest. diff --git a/packages/stack-kms/src/client.rs b/packages/stack-kms/src/client.rs index 5153bd3a97..6cac4542f6 100644 --- a/packages/stack-kms/src/client.rs +++ b/packages/stack-kms/src/client.rs @@ -1192,7 +1192,7 @@ mod tests { } /// A data key ZeroKMS refuses (HTTP 403) carries a help that names - /// both causes, keeping its code. + /// its causes, keeping its code. #[tokio::test] async fn retrieve_keys_gives_a_refused_data_key_its_help() { use miette::Diagnostic; @@ -1220,7 +1220,7 @@ mod tests { ); let help = err.help().map(|help| help.to_string()).unwrap_or_default(); assert!(help.contains("another context"), "{help}"); - assert!(help.contains("no grant for the keyset"), "{help}"); + assert!(help.contains("keyset is disabled"), "{help}"); } /// A keyset load ZeroKMS answers with 404 or 403 names the keyset it diff --git a/packages/stack-kms/src/errors.rs b/packages/stack-kms/src/errors.rs index d3dce6e727..2d6f94acd8 100644 --- a/packages/stack-kms/src/errors.rs +++ b/packages/stack-kms/src/errors.rs @@ -58,13 +58,15 @@ fn requested_keyset(keyset: Option<&IdentifiedBy>) -> String { } } -/// What a keyset-not-found message says after "Keyset not found: ". A keyset -/// asked for by id or name may exist and not be granted to this client. The -/// default keyset is missing when the client is unknown or has none. +/// What a keyset-not-found message says after "Keyset not found: ". ZeroKMS +/// looks a keyset up through the client's grant of it, so a keyset asked +/// for by id or name is also not found when it is not granted to this +/// client, and when the client is unknown. The default keyset is missing +/// when the client is unknown or has none. fn not_found(keyset: Option<&IdentifiedBy>) -> String { match keyset { Some(_) => format!( - "{}, or it is not granted to this client", + "{} does not exist, is not granted to this client, or the client is unknown", requested_keyset(keyset) ), None => "the client is unknown, or has no default keyset".into(), @@ -72,20 +74,24 @@ fn not_found(keyset: Option<&IdentifiedBy>) -> String { } /// The help for a data-key request ZeroKMS failed, by the request kind. -/// ZeroKMS answers a refused data key with HTTP 403 whatever the reason, -/// and nothing in its answer says which reason it was. So the help for a -/// 403 names both causes. A binding that knows more about the call, such as -/// whether it loaded the keyset first, may replace it with the one cause. +/// +/// ZeroKMS answers a data-key request with HTTP 403 for three causes, and +/// its answer does not say which: the value is opened under another context +/// than the one it was sealed under, the keyset is disabled, or the access +/// token lacks the scope to retrieve keys. So the help for a 403 names all +/// three. A client with no grant for the keyset is answered 404, not 403. +/// A binding that knows more about the call, such as whether it loaded the +/// keyset first, may replace the help with the likely cause. fn retrieve_help(kind: &ViturRequestErrorKind) -> &'static str { match kind { ViturRequestErrorKind::Forbidden => { - "ZeroKMS refused the data key. Either the value is opened under another context than the one it was sealed under, or this client has no grant for the keyset the value was sealed under. Open the value under the context it was sealed with, and check the keyset's grants in ZeroKMS." + "ZeroKMS refused the data key. The value is opened under another context than the one it was sealed under, the keyset is disabled, or the access token lacks the scope to retrieve keys. Open the value under the context it was sealed with." } ViturRequestErrorKind::Unauthorized => { "ZeroKMS refused the access token. Refresh the credential and retry." } ViturRequestErrorKind::NotFound => { - "ZeroKMS found no keyset or data key for the value. Check that the keyset the value was sealed under exists in this workspace, and is granted to this client." + "ZeroKMS found no grant of the value's keyset to this client, or does not know the client. Check the keyset's grants in ZeroKMS, and the client ID." } ViturRequestErrorKind::PrepareRequest | ViturRequestErrorKind::SendRequest => { "The request did not reach ZeroKMS. Check the network and the ZeroKMS endpoint, and retry." @@ -233,13 +239,16 @@ pub enum LoadKeysetError { help("ZeroKMS refused the access token. Refresh the credential and retry.") )] Unauthorized(#[source] ViturRequestError), - /// ZeroKMS refused to load the keyset. The message and help name the - /// keyset the load asked for: a keyset id or name is a detail the + /// ZeroKMS refused to load the keyset: it answers 403 for a disabled + /// keyset, and for an access token without the scope to use keys. A + /// keyset not granted to this client is answered 404, as + /// [`KeysetNotFound`](Self::KeysetNotFound). The message and help name + /// the keyset the load asked for: a keyset id or name is a detail the /// [`ErrorPayload`] policy allows. #[error("Request forbidden due to insufficient permissions: {}", requested_keyset(.keyset.as_ref()))] #[diagnostic( code(stack_kms::load_keyset_forbidden), - help("The client is not granted {}, or the keyset is disabled. Grant the keyset to this client in ZeroKMS, or enable it.", requested_keyset(.keyset.as_ref())) + help("ZeroKMS refused to load {}. The keyset is disabled, or the access token lacks the scope to use keys. Enable the keyset in ZeroKMS, or use a credential with that scope.", requested_keyset(.keyset.as_ref())) )] Forbidden { /// The keyset the load asked for. `None` is the client's default. @@ -581,12 +590,12 @@ mod codes { let cases = [ ( name("tenant-42"), - r#"Keyset not found: keyset name "tenant-42", or it is not granted to this client"#, + r#"Keyset not found: keyset name "tenant-42" does not exist, is not granted to this client, or the client is unknown"#, Some(("keyset_name", "tenant-42")), ), ( Some(IdentifiedBy::Uuid(ID)), - "Keyset not found: keyset id 6a70bd18-99ac-4650-b104-37eec3a15b09, or it is not granted to this client", + "Keyset not found: keyset id 6a70bd18-99ac-4650-b104-37eec3a15b09 does not exist, is not granted to this client, or the client is unknown", Some(("keyset_id", "6a70bd18-99ac-4650-b104-37eec3a15b09")), ), ( @@ -632,20 +641,20 @@ mod codes { ); assert_eq!( help_of(&error), - r#"The client is not granted keyset name "tenant-42", or the keyset is disabled. Grant the keyset to this client in ZeroKMS, or enable it."# + r#"ZeroKMS refused to load keyset name "tenant-42". The keyset is disabled, or the access token lacks the scope to use keys. Enable the keyset in ZeroKMS, or use a credential with that scope."# ); assert_eq!(error.payload()["keyset_name"], "tenant-42"); let default = LoadKeysetError::from_request(None, vitur(ViturRequestErrorKind::Forbidden)); assert!( - help_of(&default).starts_with("The client is not granted the client's default keyset"), + help_of(&default).starts_with("ZeroKMS refused to load the client's default keyset."), "{}", help_of(&default) ); } - /// Every request kind a data-key request can fail with has a help, and - /// a refusal (HTTP 403) names both of its causes: another context, and - /// a keyset with no grant for this client. + /// Every request kind a data-key request can fail with has a help. A + /// refusal (HTTP 403) names its three causes, and does not name a + /// missing grant, which ZeroKMS answers with 404. A 404 names the grant. #[test] fn every_data_key_request_failure_has_a_help() { use ViturRequestErrorKind as K; @@ -667,7 +676,11 @@ mod codes { } let help = help_of(&RetrieveKeyError::RequestFailed(vitur(K::Forbidden))); assert!(help.contains("another context"), "{help}"); - assert!(help.contains("no grant for the keyset"), "{help}"); + assert!(help.contains("keyset is disabled"), "{help}"); + assert!(help.contains("scope to retrieve keys"), "{help}"); + assert!(!help.contains("grant"), "{help}"); + let help = help_of(&RetrieveKeyError::RequestFailed(vitur(K::NotFound))); + assert!(help.contains("no grant"), "{help}"); } /// Every structured field this crate adds. A binding passes these on as From 4c065ac1d82860e006421248f1812b21f59932c1 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 17:10:24 +1100 Subject: [PATCH 3/4] docs(golang): say that ZeroKMS leaves a refusal's cause out by design ZeroKMS refuses a data key with one answer for three causes, and does not say which applies. That is intentional: a refusal that named its cause would tell an attacker which part of a request to change. The Help of every refused data key, through a Cipher or the Client, now ends by saying so, and tells the reader to contact CipherStash Support for the exact cause. The ErrForbidden doc comment, the encrypt README's Errors section and the changelog say the same. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- languages/golang/CHANGELOG.md | 4 +++- languages/golang/encrypt/README.md | 4 ++++ languages/golang/encrypt/errors.go | 11 +++++++++-- languages/golang/encrypt/refusal.go | 17 +++++++++++++---- languages/golang/encrypt/refusal_test.go | 6 ++++-- 5 files changed, 33 insertions(+), 9 deletions(-) diff --git a/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 91b9eba9dc..47c5d66cf9 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -30,7 +30,9 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit. names the cipher's keyset, and says how many scope and binding parts the cipher adds. Through the `*Client`, it names every cause: another context, a disabled keyset, or a token without the scope to retrieve - keys. Before, the `Help` was empty. + keys. Before, the `Help` was empty. Both say that ZeroKMS does not say + which cause applies, by design, and that CipherStash Support can find + the exact cause. - A keyset that ZeroKMS does not find (`ErrNotFound`, code `stack_kms::keyset_not_found`) is named in the error's message, and in its `Fields` as `keyset_name` or `keyset_id` (#1897). The message and the diff --git a/languages/golang/encrypt/README.md b/languages/golang/encrypt/README.md index 57aee7ded4..9b6eec0636 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -604,6 +604,10 @@ is likely where the call knows: scope and binding parts the cipher adds. - Through the `*Client`, the `Help` names every cause. +ZeroKMS does not say which cause applies, by design. A refusal that named +its cause would tell an attacker which part of a request to change. To find +the exact cause of a refusal, contact CipherStash Support. + A keyset that ZeroKMS does not find (`ErrNotFound`, code `stack_kms::keyset_not_found`) is named in the `Message`, and in `Fields` as `keyset_name` or `keyset_id`. ZeroKMS gives the same answer for a keyset diff --git a/languages/golang/encrypt/errors.go b/languages/golang/encrypt/errors.go index 512e0b221c..f2c8be1a5d 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -43,8 +43,15 @@ var ( // keyset first, the likely cause is the context: the Help names the // keyset and how many scope and binding parts the cipher adds, never // their values. On a read through the [Client], the Help names every - // cause. A keyset ZeroKMS refuses to load, a disabled one or one asked - // for with a token that lacks the scope, is + // cause. + // + // ZeroKMS does not say which cause applies, by design: a refusal that + // named its cause would tell an attacker which part of a request to + // change. To find the exact cause of a refusal, contact CipherStash + // Support. + // + // A keyset ZeroKMS refuses to load, a disabled one or one asked for + // with a token that lacks the scope, is // "stack_kms::load_keyset_forbidden", and its message names the keyset. // A keyset that is not granted to this client is [ErrNotFound]. ErrForbidden = guest.ErrForbidden diff --git a/languages/golang/encrypt/refusal.go b/languages/golang/encrypt/refusal.go index e3aa4d57ab..4b5b22ca79 100644 --- a/languages/golang/encrypt/refusal.go +++ b/languages/golang/encrypt/refusal.go @@ -13,8 +13,9 @@ const codeRetrieveKeyFailed = "stack_kms::retrieve_key_failed" // does not say which: the value is opened under another context than it was // sealed under, the keyset is disabled, or the access token lacks the scope // to retrieve keys. A client with no grant for the keyset is answered 404, -// which is ErrNotFound. The guest gives a Help that names all three. The -// call knows more, so these say which cause is likely where they can. +// which is ErrNotFound. ZeroKMS leaves the cause out by design, so a Help +// cannot name it. The guest gives a Help that names all three. The call +// knows more, so these say which cause is likely where they can. // // A Help never names a scope's or a binding's value, or a context label: // those are context values, which a Diagnostic never carries. It names how @@ -32,7 +33,8 @@ func (cph *Cipher) explainRefusal(err error) error { "The likely cause is that the value was sealed under another context than this cipher opens it under. "+ "This cipher adds %s and %s to the context. "+ "Open the value through a cipher with the same Cipher.Scope and Cipher.Bind parts as the cipher that encrypted it. "+ - "A row whose context field was changed after it was written fails the same way, and so does a keyset disabled since it was loaded.", + "A row whose context field was changed after it was written fails the same way, and so does a keyset disabled since it was loaded. "+ + refusalCauseNotGiven, describeKeyset(cph.keyset), countParts(len(cph.extension), "scope"), countParts(len(cph.bindings), "binding"))) } @@ -45,7 +47,14 @@ const clientRefusalHelp = "ZeroKMS refused the data key. The Client opens a valu "the keyset the value was sealed under is disabled; " + "or the access token lacks the scope to retrieve keys. " + "Open a scoped or bound value through a cipher like the one that encrypted it. " + - "A keyset that is not granted to this client gives ErrNotFound, not this error." + "A keyset that is not granted to this client gives ErrNotFound, not this error. " + + refusalCauseNotGiven + +// refusalCauseNotGiven ends every Help for a refused data key. ZeroKMS +// does not say which cause applies on purpose: a refusal that named its +// cause would tell an attacker which part of a request to change. +const refusalCauseNotGiven = "ZeroKMS does not say which cause applies, by design. " + + "To find the exact cause, contact CipherStash Support." // explainClientRefusal gives err the Help for a data key ZeroKMS refused on // a call through the Client. Any other error is returned as it is. diff --git a/languages/golang/encrypt/refusal_test.go b/languages/golang/encrypt/refusal_test.go index 01b2518e58..380036b035 100644 --- a/languages/golang/encrypt/refusal_test.go +++ b/languages/golang/encrypt/refusal_test.go @@ -14,7 +14,9 @@ import ( // stack_kms::retrieve_key_failed, whatever the cause. The Help says which // cause is likely where the call knows: a cipher loaded its keyset first, so // for a cipher the context is the likely cause; the Client did not, so its -// Help names every cause. Neither names a scope's value. +// Help names every cause. ZeroKMS does not say which cause applies, by +// design, so every Help says so and points to CipherStash Support. Neither +// names a scope's value. func TestARefusedDataKeySaysWhichCause(t *testing.T) { c := deterministicClient(t) ctx := context.Background() @@ -78,7 +80,7 @@ func TestARefusedDataKeySaysWhichCause(t *testing.T) { if d.Code != "stack_kms::retrieve_key_failed" { t.Errorf("Code = %q, want stack_kms::retrieve_key_failed", d.Code) } - for _, want := range tc.want { + for _, want := range append(tc.want, "does not say which cause applies, by design", "contact CipherStash Support") { if !strings.Contains(d.Help, want) { t.Errorf("Help = %q, want it to contain %q", d.Help, want) } From 84e89ed003928748a8389f0dcb67252e23277fd6 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Fri, 27 Nov 2026 17:20:28 +1100 Subject: [PATCH 4/4] docs(skills): say a refused data key does not name its cause Step 4 of the stash-zerokms runbook said the 403 for a disabled keyset says so. A refused data key does not say which cause applies, by design, so the step now lists the possible causes and points to CipherStash Support for the exact one. Adds a stash patch changeset, because skills ship in the stash npm package. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CtEQzxj55RUn35dkbhdwQk --- .changeset/stash-zerokms-refusal-cause.md | 5 +++++ skills/stash-zerokms/SKILL.md | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 .changeset/stash-zerokms-refusal-cause.md diff --git a/.changeset/stash-zerokms-refusal-cause.md b/.changeset/stash-zerokms-refusal-cause.md new file mode 100644 index 0000000000..782128a165 --- /dev/null +++ b/.changeset/stash-zerokms-refusal-cause.md @@ -0,0 +1,5 @@ +--- +'stash': patch +--- + +The `stash-zerokms` skill no longer says that a refused data key's 403 names a disabled keyset. ZeroKMS does not say which cause applies, by design. The skill now lists the possible causes and says that CipherStash Support can find the exact cause of a refusal. diff --git a/skills/stash-zerokms/SKILL.md b/skills/stash-zerokms/SKILL.md index dfee7d5f6d..ef5bdf733e 100644 --- a/skills/stash-zerokms/SKILL.md +++ b/skills/stash-zerokms/SKILL.md @@ -259,7 +259,12 @@ each step's failure explains everything after it: check which keyset each client *defaults* to — a writer and a reader that both omit `config.keyset` can still be on different keysets if their clients were created against different ones. -4. **Is the keyset disabled?** The 403 message says so explicitly. +4. **Is the keyset disabled?** A refused data key (`403`) does not say + which cause applies, by design. A refusal that + named its cause would tell an attacker which part of a request to + change. The cause may be a disabled keyset, another context, or a token + without the scope to retrieve keys. To find the exact cause of a + refusal, contact CipherStash Support. 5. **Only decrypt of specific values failing, for specific callers?** That's lock context (gate 2), not keyset access — check that the decrypt call carries the same lock context the value was encrypted with.