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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stash-zerokms-refusal-cause.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions languages/golang/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 29 additions & 3 deletions languages/golang/encrypt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 25 additions & 1 deletion languages/golang/encrypt/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions languages/golang/encrypt/guest/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
11 changes: 10 additions & 1 deletion languages/golang/encrypt/guest/tests/leak.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
}
}
}
Expand Down Expand Up @@ -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");
};
Expand Down
33 changes: 33 additions & 0 deletions languages/golang/encrypt/guest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion languages/golang/encrypt/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 22 additions & 8 deletions languages/golang/encrypt/json_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
12 changes: 10 additions & 2 deletions languages/golang/encrypt/records.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
105 changes: 105 additions & 0 deletions languages/golang/encrypt/refusal.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading