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/languages/golang/CHANGELOG.md b/languages/golang/CHANGELOG.md index 6833efd306..47c5d66cf9 100644 --- a/languages/golang/CHANGELOG.md +++ b/languages/golang/CHANGELOG.md @@ -22,6 +22,27 @@ 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 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. 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 + `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. + +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..9b6eec0636 100644 --- a/languages/golang/encrypt/README.md +++ b/languages/golang/encrypt/README.md @@ -584,9 +584,35 @@ 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`. 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 three 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. + +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 +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 15b9dc9313..f2c8be1a5d 100644 --- a/languages/golang/encrypt/errors.go +++ b/languages/golang/encrypt/errors.go @@ -34,9 +34,33 @@ 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 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. + // + // 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 // 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..db6810b698 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", "The keyset is disabled, or the access token lacks the scope"}, + } + 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..0d752bc42e 100644 --- a/languages/golang/encrypt/json_fields_test.go +++ b/languages/golang/encrypt/json_fields_test.go @@ -499,14 +499,28 @@ 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) { - t.Errorf("%s: Selector opened the entry, or not as ErrForbidden: %v", whose, err) - } - 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/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..4b5b22ca79 --- /dev/null +++ b/languages/golang/encrypt/refusal.go @@ -0,0 +1,105 @@ +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 three causes, and its answer +// 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. 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 +// 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, 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. 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, and so does a keyset disabled since it was loaded. "+ + refusalCauseNotGiven, + 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; " + + "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. " + + 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. +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..380036b035 --- /dev/null +++ b/languages/golang/encrypt/refusal_test.go @@ -0,0 +1,113 @@ +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 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. 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() + 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", "disabled since it was loaded"}, + }, + { + 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{"keyset the value was sealed under is disabled", "scope to retrieve keys", "Cipher.Scope", "Cipher.Bind", "context field", "ErrNotFound"}, + }, + } + 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 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) + } + } + 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..3bd2d6466c 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,19 @@ 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. 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 fcb8a30742..6cac4542f6 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 + /// its 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("keyset is disabled"), "{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..2d6f94acd8 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,83 @@ 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: ". 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!( + "{} 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(), + } +} + +/// The help for a data-key request ZeroKMS failed, by the request kind. +/// +/// 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. 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 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." + } + 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 +124,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 +239,45 @@ 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: 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 this keyset, or the keyset is disabled.") + 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(#[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 +291,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 +420,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 +442,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 +555,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 +567,122 @@ 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" 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 does not exist, is not granted to this client, or the client is unknown", + 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#"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("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. 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; + 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("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 /// they are, so a renamed key breaks the callers that read it. #[test] @@ -645,10 +876,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 +898,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 +921,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 +934,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 +945,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))); } } 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.