diff --git a/.github/mutation/mutants.json b/.github/mutation/mutants.json index 61a44b86..f24617c4 100644 --- a/.github/mutation/mutants.json +++ b/.github/mutation/mutants.json @@ -5658,5 +5658,77 @@ ], "run": "^(TestReentrantResolutionFailureHookReturns|TestReentrantResolutionFailureHookReturnsWhenMemoryFull)$", "why": "the failure is published on the in-flight resolution before OnResolutionFailure runs" + }, + { + "id": "server-ciba-inbox-skips-only-notfound", + "file": "server/backchannel_inbox.go", + "old": "return errors.Is(serverErr, storage.ErrBackchannelAuthenticationNotFound)", + "new": "return serverErr != nil", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestListBackchannelInteractionsReportsARefusedLookup$", + "why": "the CIBA inbox listing reports a lookup refused other than as not found, rather than skipping it" + }, + { + "id": "server-ciba-inbox-skips-notfound", + "file": "server/backchannel_inbox.go", + "old": "return errors.Is(serverErr, storage.ErrBackchannelAuthenticationNotFound)", + "new": "return serverErr == nil", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestListBackchannelInteractionsSkipsAGoneRequest$", + "why": "the CIBA inbox listing leaves out an entry whose request the store says is gone" + }, + { + "id": "server-ciba-inbox-skips-deregistered-client", + "file": "server/backchannel_inbox.go", + "old": "\tcase ErrorUnauthorizedClient:\n\t\treturn true", + "new": "\tcase ErrorUnauthorizedClient:\n\t\treturn false", + "module": "root", + "packages": [ + "./server" + ], + "run": "^TestBackchannelInboxSkipsADeregisteredClient$", + "why": "the CIBA inbox listing leaves out a request whose client is no longer registered" + }, + { + "id": "server-ciba-deny-clears-notfound", + "file": "server/backchannel_inbox.go", + "old": "errors.Is(failure, storage.ErrBackchannelAuthenticationNotFound)", + "new": "failure == nil", + "module": "root", + "packages": [ + "./server" + ], + "run": "^(TestStaleBackchannelEntry|TestDenyBackchannelInteractionsClearsAGoneRequest)$", + "why": "DenyBackchannelInteractions passes over and clears a request the store says is gone" + }, + { + "id": "memstore-ciba-lookup-wraps-notfound", + "file": "storage/memstore/backchannel_authentication_store.go", + "old": "fmt.Errorf(\"memstore: look up backchannel authentication: %w\", storage.ErrBackchannelAuthenticationNotFound)", + "new": "fmt.Errorf(\"memstore: look up backchannel authentication: %v\", storage.ErrBackchannelAuthenticationNotFound)", + "module": "root", + "packages": [ + "./storage/memstore" + ], + "run": "^TestBackchannelAuthenticationStoreReportsAnUnknownHandle$", + "why": "memstore wraps ErrBackchannelAuthenticationNotFound for a lookup of an unknown handle" + }, + { + "id": "memstore-ciba-decide-wraps-notfound", + "file": "storage/memstore/backchannel_authentication_store.go", + "old": "fmt.Errorf(\"memstore: decide backchannel authentication: %w\", storage.ErrBackchannelAuthenticationNotFound)", + "new": "fmt.Errorf(\"memstore: decide backchannel authentication: %v\", storage.ErrBackchannelAuthenticationNotFound)", + "module": "root", + "packages": [ + "./storage/memstore" + ], + "run": "^TestBackchannelAuthenticationStoreRefusesDecisionOnUnknownHandle$", + "why": "memstore wraps ErrBackchannelAuthenticationNotFound for a decision on an unknown handle" } ] diff --git a/UPGRADING.md b/UPGRADING.md index 44daeecd..01fbfbd8 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -50,6 +50,43 @@ that expire mid-resolution. little lifetime for how long its endpoints take to answer: ask the superior or RP to issue them for longer. +### A store of your own should report an unknown CIBA handle as not found (server, storage) + +**Affects:** a deployment with `Dependencies.BackchannelInbox` set that +calls `Server.ListBackchannelInteractions` or +`Server.DenyBackchannelInteractions`, with a +`storage.BackchannelAuthenticationStore` of its own. `memstore` and +`sqlstore` (from the release that wraps it) need nothing. + +**Why:** the listing left out every inbox entry whose request lookup +the store refused with anything but an outage, taking each for a +request that is gone. A store that refuses a lookup for another reason +with a plain error, or a request record the server can't read as its +own, was therefore hidden from the operator, and an account closure +could look finished while such an entry remained. A store now says a +request is gone by wrapping the new +`storage.ErrBackchannelAuthenticationNotFound`, and only such an entry +(or one whose client is no longer registered) is left out; any other is +reported. `DenyBackchannelInteractions` also passes over, and takes out +of the inbox, a request the store says is gone when it comes to deny +it. + +**What fails:** with a store that doesn't wrap it, an inbox entry whose +request the store no longer holds is no longer left out silently: +`ListBackchannelInteractions` still returns every other request, but +with an error for that entry, and `DenyBackchannelInteractions` reports +it in its error, until the entry expires. `LookupBackchannelInteraction` +and `CompleteBackchannelAuthentication` answer an unknown handle as +before. + +**What to change:** in `LookupBackchannelAuthentication`, and +`DecideBackchannelAuthentication`, wrap the sentinel for a handle the +store doesn't hold, and for nothing else (not an outage, not a request +already decided): +`fmt.Errorf("...: %w", storage.ErrBackchannelAuthenticationNotFound)`. +`storage.TestBackchannelAuthenticationStoreContract` checks it once you +do. + ## v0.85.0 ### Codes, refresh tokens and `auth_req_id`s are stored under digests covering the issuer (server, storage) diff --git a/docs/guides/ciba.md b/docs/guides/ciba.md index 5edbb327..976a0fa4 100644 --- a/docs/guides/ciba.md +++ b/docs/guides/ciba.md @@ -207,10 +207,16 @@ server. A request leaves the inbox once decided, or when it expires. Each request listed costs store reads, so pass the listing your request's context: once it ends, the listing reads no more and fails with the context's error, rather than returning part of the inbox. An -entry it can't read, one whose record won't decode or whose request a -store couldn't answer for, doesn't hide the rest: it returns what it -could read with an error for each entry it couldn't, so treat any error -as a possibly incomplete list. +entry whose request is gone is left out: the backchannel store says so +by wrapping `storage.ErrBackchannelAuthenticationNotFound`, as `memstore` +does, and `sqlstore` from the release that wraps it, or its client is +no longer registered. An entry it can't read, one whose record won't +decode or whose request a store couldn't answer for or refused any +other way, doesn't hide the rest: it returns what it could read with an +error for each entry it couldn't, so treat any error as a possibly +incomplete list. With a store that doesn't wrap the sentinel, an entry +left behind for a request the store no longer holds is reported this +way until it expires. The resolver also binds the request to that user: an `Authorize` for anyone else is a failed authentication (`access_denied`). That matters @@ -236,9 +242,10 @@ requests pending. To empty an inbox for good, have `BackchannelSubjects` stop resolving the user's hints first, then call it again until `ListBackchannelInteractions` lists nothing. A request already decided (one left listed because its removal from the inbox -failed) or expired is passed over and its entry removed; any other -refusal is reported in the error and the request stays listed. A -store says a request was already decided by wrapping +failed), expired, or gone from the store since it was listed is passed +over and its entry removed; any other refusal, or an entry the listing +couldn't read, is reported in the error and stays listed. A store says +a request was already decided by wrapping `storage.ErrBackchannelAuthenticationAlreadyDecided`, as `memstore` does, and `sqlstore` from the release that wraps it: with a store that doesn't, such an entry is reported each time until it expires. diff --git a/server/backchannel_authentication.go b/server/backchannel_authentication.go index a2f555d2..9a358a6d 100644 --- a/server/backchannel_authentication.go +++ b/server/backchannel_authentication.go @@ -793,8 +793,11 @@ func (s *Server) backchannelInteraction(client storage.RegisteredClient, params // decided or has expired (BackchannelAuthenticationStore's lookup doesn't // say); CompleteBackchannelAuthentication is what enforces both, so a // stale lookup can at most show a request that can no longer be -// completed. An unknown handle is an ErrorInvalidRequest *Error, and a -// request whose client is no longer registered ErrorUnauthorizedClient; +// completed. An unknown handle is an ErrorInvalidRequest *Error, which +// wraps the store's error (so errors.Is finds +// storage.ErrBackchannelAuthenticationNotFound with a store that wraps +// it), and a request whose client is no longer registered +// ErrorUnauthorizedClient; // a store or client repository that couldn't answer is // ErrorServerError. func (s *Server) LookupBackchannelInteraction(ctx context.Context, handle BackchannelAuthenticationHandle) (BackchannelInteractionRequest, error) { diff --git a/server/backchannel_inbox.go b/server/backchannel_inbox.go index f6603980..9449dbe5 100644 --- a/server/backchannel_inbox.go +++ b/server/backchannel_inbox.go @@ -244,12 +244,20 @@ func (s *Server) checkPendingBackchannelRequests(ctx context.Context, clientID f // ListBackchannelInteractions reads no more of them and fails with // ctx's error, rather than returning part of the inbox. // -// An entry it can't read (a record that won't decode, or a request the -// backchannel or client store couldn't answer for) doesn't hide the -// others: it returns every request it could read, with an error joining -// one for each entry it couldn't. So a non-nil error, with or without -// requests, means the list may be incomplete; when every request must -// be accounted for, as when closing an account, treat it as a failure. +// An entry whose request is gone is left out: one the backchannel store +// says it holds no such request for, by wrapping +// storage.ErrBackchannelAuthenticationNotFound, or one whose client is +// no longer registered. An entry it can't read otherwise (a record that +// won't decode, a request the backchannel or client store couldn't +// answer for, or a lookup the backchannel store refused with an error +// that doesn't wrap the sentinel) doesn't hide the others: it returns +// every request it could read, with an error joining one for each entry +// it couldn't. So a non-nil error, with or without requests, means the +// list may be incomplete; when every request must be accounted for, as +// when closing an account, treat it as a failure. (With a store that +// doesn't wrap the sentinel, an entry left behind for a request the +// store no longer holds is reported this way each time, until the +// entry expires.) // // ListBackchannelInteractions doesn't check who is asking: the // application must make sure the user is subject, as it does before @@ -264,7 +272,8 @@ func (s *Server) ListBackchannelInteractions(ctx context.Context, subject Subjec // listBackchannelInteractions returns the requests awaiting subject, // and, separately, the entries it couldn't read (an undecodable record, -// or a request the backchannel store couldn't answer for) joined into +// or a request the backchannel store couldn't answer for or refused +// other than as gone) joined into // unreadable, so one bad entry doesn't hide the others from // DenyBackchannelInteractions. err is for a listing that failed as a // whole, ctx ending before it finished among them. @@ -306,9 +315,10 @@ func (s *Server) listBackchannelInteractions(ctx context.Context, subject Subjec // pendingBackchannelInteraction rebuilds entry's request, reporting // false for one that isn't a live request of subject's at this server: -// written by another issuer, expired, gone from the backchannel store, -// from a client no longer registered, or bound to another subject than -// the one it's filed under. +// written by another issuer, expired, gone from the backchannel store +// (goneBackchannelRequest), from a client no longer registered, or bound +// to another subject than the one it's filed under. Any other failure to +// read the request is an error. func (s *Server) pendingBackchannelInteraction(ctx context.Context, subject SubjectID, entry storage.BackchannelInboxEntry) (PendingBackchannelInteraction, bool, error) { var record backchannelInboxRecord if err := decodeRecord(entry.Record, &record.Version, &record); err != nil { @@ -323,8 +333,7 @@ func (s *Server) pendingBackchannelInteraction(ctx context.Context, subject Subj } interaction, resolved, err := s.lookupBackchannelInteraction(ctx, handle) if err != nil { - var serverErr *Error - if errors.As(err, &serverErr) && (serverErr.Code() == ErrorInvalidRequest || serverErr.Code() == ErrorUnauthorizedClient) { + if goneBackchannelRequest(err) { return PendingBackchannelInteraction{}, false, nil } return PendingBackchannelInteraction{}, false, err @@ -337,6 +346,28 @@ func (s *Server) pendingBackchannelInteraction(ctx context.Context, subject Subj return PendingBackchannelInteraction{ID: backchannelInboxID(entry.HandleHash), Handle: handle, Interaction: interaction, ExpiresAt: entry.ExpiresAt}, true, nil } +// goneBackchannelRequest reports whether err, lookupBackchannelInteraction's +// refusal of a listed request, means the request is no longer one to +// list: the store says it holds no such request +// (storage.ErrBackchannelAuthenticationNotFound), or its client is no +// longer registered. Any other invalid_request, a refusal the store +// reported as a plain error or a request record the server can't read +// as its own, is an entry the listing couldn't read, not a request +// gone. +func goneBackchannelRequest(err error) bool { + var serverErr *Error + if !errors.As(err, &serverErr) { + return false + } + switch serverErr.Code() { + case ErrorUnauthorizedClient: + return true + case ErrorInvalidRequest: + return errors.Is(serverErr, storage.ErrBackchannelAuthenticationNotFound) + } + return false +} + // inboxWriteTimeout bounds each inbox write that doesn't end with its // caller's context, storeBackchannelRequest's filing and // unfileBackchannelRequest's removal: long enough for a store waiting on @@ -373,16 +404,20 @@ func (s *Server) unfileBackchannelRequest(ctx context.Context, handleHash [32]by // gets access_denied, a ping client is notified, and it leaves the // inbox. One already decided, by another call or instance, or by an // earlier call whose removal from the inbox failed, is passed over, not -// counted, and taken out of the inbox; so is one that has expired. A -// request counts as already decided only when the store says so by -// wrapping storage.ErrBackchannelAuthenticationAlreadyDecided: any other +// counted, and taken out of the inbox; so is one that has expired, and +// one gone from the store since it was listed. A request counts as +// already decided only when the store says so by wrapping +// storage.ErrBackchannelAuthenticationAlreadyDecided, and as gone only +// when it wraps storage.ErrBackchannelAuthenticationNotFound: any other // refusal, such as a store outage the store reports as a plain error, // is a failure for that request, which stays listed. Any failure, or an -// entry it can't read, doesn't stop it: it denies every other request, -// then returns how many it denied with every failure joined. What failed -// is still listed, so calling it again finishes the job. (With a store -// that doesn't wrap the sentinel, an entry left behind for a decided -// request is reported each time, until the request expires.) If ctx ends +// entry the listing couldn't read (see ListBackchannelInteractions), +// doesn't stop it: it denies every other request, then returns how many +// it denied with every failure joined; an entry it couldn't read isn't +// counted, and stays in the inbox. What failed is still listed, so +// calling it again finishes the job. (With a store that doesn't wrap +// the sentinels, an entry left behind for a decided or gone request is +// reported each time, until it expires.) If ctx ends // before the requests are all listed, it denies none of them and returns // ctx's error. // @@ -432,15 +467,18 @@ func (s *Server) DenyBackchannelInteractions(ctx context.Context, subject Subjec // staleBackchannelEntry reports whether failure, recordBackchannelDecision's // refusal of a listed request, means the request's inbox entry is stale: // the request has expired, which the server decides itself, or the store -// says it was already decided (storage.ErrBackchannelAuthenticationAlreadyDecided). -// Any other invalid_request may be a store outage reported as a plain -// error, so the entry is kept for the request still awaiting a decision. +// says it was already decided (storage.ErrBackchannelAuthenticationAlreadyDecided) +// or holds no such request any more +// (storage.ErrBackchannelAuthenticationNotFound). Any other +// invalid_request may be a store outage reported as a plain error, so +// the entry is kept for the request still awaiting a decision. func staleBackchannelEntry(failure *Error) bool { switch failure.Code() { case ErrorExpiredToken: return true case ErrorInvalidRequest: - return errors.Is(failure, storage.ErrBackchannelAuthenticationAlreadyDecided) + return errors.Is(failure, storage.ErrBackchannelAuthenticationAlreadyDecided) || + errors.Is(failure, storage.ErrBackchannelAuthenticationNotFound) } return false } diff --git a/server/backchannel_inbox_lookup_test.go b/server/backchannel_inbox_lookup_test.go new file mode 100644 index 00000000..70db9159 --- /dev/null +++ b/server/backchannel_inbox_lookup_test.go @@ -0,0 +1,126 @@ +package server_test + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "testing" + + "github.com/idfoundry/fapigo/server" + "github.com/idfoundry/fapigo/storage" + "github.com/idfoundry/fapigo/storage/memstore" +) + +// refusingLookupStore refuses every lookup of the requests whose handle +// hashes are in refused with lookupErr; with foreign set, it instead +// returns their request records rewritten as another issuer's. +type refusingLookupStore struct { + storage.BackchannelAuthenticationStore + refused map[[32]byte]bool + lookupErr error + foreign bool +} + +func (s *refusingLookupStore) LookupBackchannelAuthentication(ctx context.Context, handleHash [32]byte) (storage.LookedUpBackchannelAuthentication, error) { + found, err := s.BackchannelAuthenticationStore.LookupBackchannelAuthentication(ctx, handleHash) + if err != nil || !s.refused[handleHash] { + return found, err + } + if !s.foreign { + return storage.LookedUpBackchannelAuthentication{}, s.lookupErr + } + var record map[string]any + if err := json.Unmarshal(found.Request, &record); err != nil { + return storage.LookedUpBackchannelAuthentication{}, err + } + record["iss"] = "https://other-as.example" + found.Request, err = json.Marshal(record) + return found, err +} + +// refusingLookupHarness is an inbox harness holding two requests filed +// for user-1, whose backchannel store refuses lookups of the second +// (returned as refused) as store says, once refuse(true) is called, and +// answers them again after refuse(false). +func refusingLookupHarness(t *testing.T, store *refusingLookupStore) (h harness, kept, refused server.BackchannelInteractionRequired, refuse func(bool)) { + t.Helper() + store.BackchannelAuthenticationStore = memstore.NewBackchannelAuthenticationStore() + store.refused = map[[32]byte]bool{} + h = newHarnessWithBackchannelOptions(t, store, nil, func(d *server.Dependencies) { + d.BackchannelSubjects = hintSubjects{known: map[string]bool{"user-1": true}} + d.BackchannelInbox = memstore.NewBackchannelInbox() + }) + kept = beginFiled(t, h, "user-1") + refused = beginFiled(t, h, "user-1") + return h, kept, refused, func(on bool) { store.refused[sha256.Sum256([]byte(refused.Handle.String()))] = on } +} + +// listOnly checks ListBackchannelInteractions for user-1 at h lists only +// want, with an error exactly when wantErr is set. +func listOnly(t *testing.T, h harness, want server.BackchannelInteractionRequired, wantErr bool) { + t.Helper() + pending, err := h.server.ListBackchannelInteractions(context.Background(), mustSubjectID(t, "user-1")) + if (err != nil) != wantErr { + t.Fatalf("ListBackchannelInteractions error = %v, want an error: %v", err, wantErr) + } + if len(pending) != 1 || pending[0].Handle.String() != want.Handle.String() { + t.Fatalf("ListBackchannelInteractions = %d requests, want only the one whose lookup succeeds", len(pending)) + } +} + +// TestListBackchannelInteractionsSkipsAGoneRequest: an entry whose +// request the store says is gone (storage.ErrBackchannelAuthenticationNotFound) +// is left out without an error. +func TestListBackchannelInteractionsSkipsAGoneRequest(t *testing.T) { + h, kept, _, refuse := refusingLookupHarness(t, &refusingLookupStore{lookupErr: fmt.Errorf("db: %w", storage.ErrBackchannelAuthenticationNotFound)}) + refuse(true) + listOnly(t, h, kept, false) +} + +// TestListBackchannelInteractionsReportsARefusedLookup: an entry whose +// lookup the store refuses with an error that doesn't say the request is +// gone, or whose request record isn't this server's own, is reported, +// with the other requests still listed, rather than silently left out. +func TestListBackchannelInteractionsReportsARefusedLookup(t *testing.T) { + t.Run("plain error", func(t *testing.T) { + h, kept, _, refuse := refusingLookupHarness(t, &refusingLookupStore{lookupErr: errors.New("db: refused")}) + refuse(true) + listOnly(t, h, kept, true) + }) + t.Run("another issuer's request record", func(t *testing.T) { + h, kept, _, refuse := refusingLookupHarness(t, &refusingLookupStore{foreign: true}) + refuse(true) + listOnly(t, h, kept, true) + }) +} + +// TestDenyBackchannelInteractionsReportsARefusedLookup: an entry the +// listing couldn't read doesn't stop the other requests being denied; it +// isn't counted, is reported, and stays in the inbox. +func TestDenyBackchannelInteractionsReportsARefusedLookup(t *testing.T) { + h, _, refused, refuse := refusingLookupHarness(t, &refusingLookupStore{lookupErr: errors.New("db: refused")}) + refuse(true) + n, err := h.server.DenyBackchannelInteractions(context.Background(), mustSubjectID(t, "user-1"), "closed") + if err == nil || n != 1 { + t.Fatalf("DenyBackchannelInteractions = %d, %v, want 1 and an error for the unreadable entry", n, err) + } + refuse(false) + if left := inboxOf(t, h, "user-1"); len(left) != 1 || left[0].Handle.String() != refused.Handle.String() { + t.Errorf("inbox after the denial = %d requests, want only the unreadable one, still pending", len(left)) + } +} + +// TestDenyBackchannelInteractionsClearsAGoneRequest: a request the store +// says is gone (storage.ErrBackchannelAuthenticationNotFound) when it's +// denied is passed over, not counted, and its entry removed. +func TestDenyBackchannelInteractionsClearsAGoneRequest(t *testing.T) { + h := refusingDecideHarness(t, fmt.Errorf("db: %w", storage.ErrBackchannelAuthenticationNotFound)) + if n, err := h.server.DenyBackchannelInteractions(context.Background(), mustSubjectID(t, "user-1"), "closed"); err != nil || n != 0 { + t.Fatalf("DenyBackchannelInteractions(request gone) = %d, %v, want 0, nil", n, err) + } + if left := inboxOf(t, h, "user-1"); len(left) != 0 { + t.Errorf("inbox after the denial = %d requests, want the stale entry cleared", len(left)) + } +} diff --git a/server/backchannel_stale_entry_internal_test.go b/server/backchannel_stale_entry_internal_test.go index 9bc79479..a1fc56bd 100644 --- a/server/backchannel_stale_entry_internal_test.go +++ b/server/backchannel_stale_entry_internal_test.go @@ -10,10 +10,11 @@ import ( // TestStaleBackchannelEntry: a listed request's inbox entry is stale // when deciding it fails because it expired or because the store says -// it was already decided, and is kept for any other refusal, which may -// be an outage reported as a plain error. +// it was already decided or holds no such request, and is kept for any +// other refusal, which may be an outage reported as a plain error. func TestStaleBackchannelEntry(t *testing.T) { decided := fmt.Errorf("store: %w", storage.ErrBackchannelAuthenticationAlreadyDecided) + gone := fmt.Errorf("store: %w", storage.ErrBackchannelAuthenticationNotFound) for _, tc := range []struct { name string failure *Error @@ -21,11 +22,36 @@ func TestStaleBackchannelEntry(t *testing.T) { }{ {"expired", newError(ErrorExpiredToken, 400, "auth_req_id has expired", nil), true}, {"already decided", newError(ErrorInvalidRequest, 400, "already decided", decided), true}, + {"gone", newError(ErrorInvalidRequest, 400, "unknown", gone), true}, {"plain invalid_request", newError(ErrorInvalidRequest, 400, "refused", errors.New("store: refused")), false}, {"server_error", newError(ErrorServerError, 500, "store outage", decided), false}, + {"server_error, gone", newError(ErrorServerError, 500, "store outage", gone), false}, } { if got := staleBackchannelEntry(tc.failure); got != tc.want { t.Errorf("%s: staleBackchannelEntry = %v, want %v", tc.name, got, tc.want) } } } + +// TestGoneBackchannelRequest: a listed entry's request is gone, and the +// entry skipped, only when the lookup says its client is no longer +// registered or the store says it holds no such request; any other +// refusal, an outage, or an error that isn't the server's is not. +func TestGoneBackchannelRequest(t *testing.T) { + gone := fmt.Errorf("store: %w", storage.ErrBackchannelAuthenticationNotFound) + for _, tc := range []struct { + name string + err error + want bool + }{ + {"not a server error", gone, false}, + {"client no longer registered", newError(ErrorUnauthorizedClient, 400, "client is no longer registered", nil), true}, + {"not found", newError(ErrorInvalidRequest, 400, "backchannel authentication handle is unknown", gone), true}, + {"plain refusal", newError(ErrorInvalidRequest, 400, "backchannel authentication handle is unknown", errors.New("store: refused")), false}, + {"outage", newError(ErrorServerError, 500, "failed to look up the backchannel authentication request", gone), false}, + } { + if got := goneBackchannelRequest(tc.err); got != tc.want { + t.Errorf("%s: goneBackchannelRequest = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/storage/backchannel.go b/storage/backchannel.go index 1db77ce6..eaf5fcb5 100644 --- a/storage/backchannel.go +++ b/storage/backchannel.go @@ -234,6 +234,27 @@ func (e *BackchannelAuthenticationSlowDownError) Error() string { // request. var ErrBackchannelAuthenticationAlreadyDecided = errors.New("storage: backchannel authentication request already decided") +// ErrBackchannelAuthenticationNotFound is the error +// BackchannelAuthenticationStore.LookupBackchannelAuthentication, and +// DecideBackchannelAuthentication, wrap +// (fmt.Errorf("...: %w", storage.ErrBackchannelAuthenticationNotFound)) +// when the store holds no request under the handle: one never stored, +// or one gone since, expired and purged say. Never for an outage, and +// never for a request that is stored, decided or not. The server tells +// it apart with errors.Is: server.Server.ListBackchannelInteractions +// leaves out an inbox entry whose request the store says is gone, and +// server.Server.DenyBackchannelInteractions passes over such a request +// and takes its entry out of the inbox; any other refusal they report, +// so an entry the store can't answer for isn't hidden from the +// operator. +// +// Wrapping it is optional. A store that doesn't keeps working: an +// unknown handle is still refused, but ListBackchannelInteractions +// reports an entry whose request is gone as one it couldn't read, until +// the entry expires. TestBackchannelAuthenticationStoreContract checks +// a store that wraps it wraps it only for an unknown handle. +var ErrBackchannelAuthenticationNotFound = errors.New("storage: backchannel authentication request not found") + // BackchannelAuthenticationStore persists CIBA backchannel // authentication requests: creation, the out-of-band decision, and // client polling for that decision. @@ -253,7 +274,9 @@ type BackchannelAuthenticationStore interface { // validate a decision (e.g. that a narrowed authorization_details // grant is an acceptable subset of what was requested) against the // original request before calling DecideBackchannelAuthentication to - // record it. Returns a plain error if HandleHash is unknown. + // record it. Returns an error if HandleHash is unknown, which should + // wrap ErrBackchannelAuthenticationNotFound (optional; see its doc + // comment). LookupBackchannelAuthentication(ctx context.Context, handleHash [32]byte) (LookedUpBackchannelAuthentication, error) // DecideBackchannelAuthentication atomically records the terminal @@ -263,7 +286,8 @@ type BackchannelAuthenticationStore interface { // exactly one decision may ever be recorded, the same way // CompleteAuthorization's interaction handle is single-use — and // should wrap ErrBackchannelAuthenticationAlreadyDecided (optional; - // see its doc comment). For a + // see its doc comment). An unknown HandleHash fails too, and should + // wrap ErrBackchannelAuthenticationNotFound (optional). For a // request whose DeliveryMode is "ping", recording the decision also // exempts the client's next PollBackchannelAuthentication from the // PollInterval check: the ping notification is its signal to fetch diff --git a/storage/contract.go b/storage/contract.go index 7929b724..4dacd2b5 100644 --- a/storage/contract.go +++ b/storage/contract.go @@ -1303,7 +1303,9 @@ func testAccessTokenStoreLookupExpiredTokenStillReturnsIt(t *testing.T, factory // behavior against the guarantees BackchannelAuthenticationStore's // documentation promises: DecideBackchannelAuthentication is single-use, // and wraps ErrBackchannelAuthenticationAlreadyDecided for a second -// decision only, if it wraps it at all; +// decision only, if it wraps it at all; an unknown handle wraps +// ErrBackchannelAuthenticationNotFound, if the store wraps it at all, +// and an outage or a decided request doesn't; // PollBackchannelAuthentication is reusable for Pending/Denied/AuthenticationFailed // but single-use for the first Approved observation (mirroring // RedeemRefreshToken's and RedeemAuthorizationCode's contracts @@ -1318,6 +1320,9 @@ func TestBackchannelAuthenticationStoreContract(t *testing.T, factory func() Bac testBackchannelAuthenticationStoreLookupReturnsClientIDAndRequestWithoutConsuming(t, factory) }) t.Run("LookupUnknownHandleFails", func(t *testing.T) { testBackchannelAuthenticationStoreLookupUnknownHandleFails(t, factory) }) + t.Run("LookupUnknownHandleWrapsErrBackchannelAuthenticationNotFound", func(t *testing.T) { + testBackchannelAuthenticationStoreLookupUnknownHandleWrapsNotFound(t, factory) + }) t.Run("DecideThenPollReturnsApprovedFieldsRoundTripped", func(t *testing.T) { testBackchannelAuthenticationStoreDecideThenPollReturnsApprovedFieldsRoundTripped(t, factory) }) @@ -1336,6 +1341,12 @@ func TestBackchannelAuthenticationStoreContract(t *testing.T, factory func() Bac t.Run("DecideUnknownHandleIsNotAlreadyDecided", func(t *testing.T) { testBackchannelAuthenticationStoreDecideUnknownHandleIsNotAlreadyDecided(t, factory) }) + t.Run("DecideUnknownHandleWrapsErrBackchannelAuthenticationNotFound", func(t *testing.T) { + testBackchannelAuthenticationStoreDecideUnknownHandleWrapsNotFound(t, factory) + }) + t.Run("DecideAgainIsNotNotFound", func(t *testing.T) { + testBackchannelAuthenticationStoreDecideAgainIsNotNotFound(t, factory) + }) t.Run("ConcurrentDecideBackchannelAuthenticationHasExactlyOneWinner", func(t *testing.T) { testBackchannelAuthenticationStoreConcurrentDecideBackchannelAuthenticationHasExactlyOneWinner(t, factory) }) @@ -1415,6 +1426,24 @@ func testBackchannelAuthenticationStoreLookupUnknownHandleFails(t *testing.T, fa } } +// testBackchannelAuthenticationStoreLookupUnknownHandleWrapsNotFound: a +// store that reports an unknown handle with +// ErrBackchannelAuthenticationNotFound (optional) reports it that way, +// not as an outage. A store that doesn't wrap it skips this subtest: the +// lookup still fails (LookupUnknownHandleFails), and the server then +// reports an inbox entry whose request is gone rather than leaving it +// out. +func testBackchannelAuthenticationStoreLookupUnknownHandleWrapsNotFound(t *testing.T, factory func() BackchannelAuthenticationStore) { + store := factory() + _, err := store.LookupBackchannelAuthentication(context.Background(), sha256.Sum256([]byte("handle-never-stored"))) + if !errors.Is(err, ErrBackchannelAuthenticationNotFound) { + t.Skip("the store doesn't wrap ErrBackchannelAuthenticationNotFound") + } + if errors.Is(err, ErrStoreUnavailable) { + t.Fatalf("LookupBackchannelAuthentication(unknown handle) = %v, which also wraps ErrStoreUnavailable; an unknown request isn't an outage", err) + } +} + func testBackchannelAuthenticationStoreCreateThenPollReturnsPending(t *testing.T, factory func() BackchannelAuthenticationStore) { store := factory() ctx := context.Background() @@ -1593,6 +1622,48 @@ func testBackchannelAuthenticationStoreDecideUnknownHandleIsNotAlreadyDecided(t } } +// testBackchannelAuthenticationStoreDecideUnknownHandleWrapsNotFound: a +// store that reports deciding an unknown handle with +// ErrBackchannelAuthenticationNotFound (optional) reports it that way, +// not as an outage or an already-decided request. A store that doesn't +// wrap it skips this subtest. +func testBackchannelAuthenticationStoreDecideUnknownHandleWrapsNotFound(t *testing.T, factory func() BackchannelAuthenticationStore) { + store := factory() + _, err := store.DecideBackchannelAuthentication(context.Background(), DecideBackchannelAuthentication{ + HandleHash: sha256.Sum256([]byte("handle-never-stored")), Status: BackchannelAuthenticationDenied, + }) + if !errors.Is(err, ErrBackchannelAuthenticationNotFound) { + t.Skip("the store doesn't wrap ErrBackchannelAuthenticationNotFound") + } + if errors.Is(err, ErrStoreUnavailable) { + t.Fatalf("DecideBackchannelAuthentication(unknown handle) = %v, which also wraps ErrStoreUnavailable; an unknown request isn't an outage", err) + } +} + +// testBackchannelAuthenticationStoreDecideAgainIsNotNotFound: deciding a +// request already decided fails without wrapping +// ErrBackchannelAuthenticationNotFound: the request is still stored, and +// the server would otherwise take it for one gone. +func testBackchannelAuthenticationStoreDecideAgainIsNotNotFound(t *testing.T, factory func() BackchannelAuthenticationStore) { + store := factory() + ctx := context.Background() + record := newBackchannelAuthenticationRecord("auth-req-decided-found", "handle-decided-found") + if err := store.CreateBackchannelAuthentication(ctx, record); err != nil { + t.Fatalf("CreateBackchannelAuthentication: %v", err) + } + decision := DecideBackchannelAuthentication{HandleHash: record.HandleHash, Status: BackchannelAuthenticationDenied} + if _, err := store.DecideBackchannelAuthentication(ctx, decision); err != nil { + t.Fatalf("first DecideBackchannelAuthentication: %v", err) + } + _, err := store.DecideBackchannelAuthentication(ctx, decision) + switch { + case err == nil: + t.Fatal("second DecideBackchannelAuthentication = nil error, want error") + case errors.Is(err, ErrBackchannelAuthenticationNotFound): + t.Fatalf("second DecideBackchannelAuthentication = %v, which wraps ErrBackchannelAuthenticationNotFound; a decided request is still stored", err) + } +} + func testBackchannelAuthenticationStoreConcurrentDecideBackchannelAuthenticationHasExactlyOneWinner(t *testing.T, factory func() BackchannelAuthenticationStore) { store := factory() ctx := context.Background() diff --git a/storage/memstore/backchannel_authentication_store.go b/storage/memstore/backchannel_authentication_store.go index 11bae130..095d6bad 100644 --- a/storage/memstore/backchannel_authentication_store.go +++ b/storage/memstore/backchannel_authentication_store.go @@ -77,7 +77,7 @@ func (s *BackchannelAuthenticationStore) LookupBackchannelAuthentication(_ conte defer s.mu.Unlock() rec, ok := s.byHandleHash[handleHash] if !ok { - return storage.LookedUpBackchannelAuthentication{}, fmt.Errorf("memstore: no such backchannel authentication handle") + return storage.LookedUpBackchannelAuthentication{}, fmt.Errorf("memstore: look up backchannel authentication: %w", storage.ErrBackchannelAuthenticationNotFound) } return storage.LookedUpBackchannelAuthentication{ ClientID: rec.clientID, @@ -92,7 +92,7 @@ func (s *BackchannelAuthenticationStore) DecideBackchannelAuthentication(_ conte defer s.mu.Unlock() rec, ok := s.byHandleHash[decision.HandleHash] if !ok { - return storage.DecidedBackchannelAuthentication{}, fmt.Errorf("memstore: no such backchannel authentication handle") + return storage.DecidedBackchannelAuthentication{}, fmt.Errorf("memstore: decide backchannel authentication: %w", storage.ErrBackchannelAuthenticationNotFound) } if rec.status != storage.BackchannelAuthenticationPending { return storage.DecidedBackchannelAuthentication{}, fmt.Errorf("memstore: decide backchannel authentication: %w", storage.ErrBackchannelAuthenticationAlreadyDecided) diff --git a/storage/memstore/memstore_test.go b/storage/memstore/memstore_test.go index 2c4abdcd..4e2c0f61 100644 --- a/storage/memstore/memstore_test.go +++ b/storage/memstore/memstore_test.go @@ -241,13 +241,26 @@ func TestBackchannelAuthenticationStoreReportsAnAlreadyDecidedRequest(t *testing } // TestBackchannelAuthenticationStoreRefusesDecisionOnUnknownHandle: a -// decision for a handle no request was created with is refused. +// decision for a handle no request was created with is refused, wrapping +// storage.ErrBackchannelAuthenticationNotFound, so the contract's +// subtest for it runs rather than skips here. func TestBackchannelAuthenticationStoreRefusesDecisionOnUnknownHandle(t *testing.T) { store := NewBackchannelAuthenticationStore() if _, err := store.DecideBackchannelAuthentication(context.Background(), storage.DecideBackchannelAuthentication{ HandleHash: sha256.Sum256([]byte("no such handle")), Status: storage.BackchannelAuthenticationApproved, - }); err == nil { - t.Fatal("decision on an unknown handle = nil error, want refused") + }); !errors.Is(err, storage.ErrBackchannelAuthenticationNotFound) { + t.Fatalf("decision on an unknown handle = %v, want it refused wrapping ErrBackchannelAuthenticationNotFound", err) + } +} + +// TestBackchannelAuthenticationStoreReportsAnUnknownHandle pins that +// memstore wraps storage.ErrBackchannelAuthenticationNotFound for a +// lookup of a handle no request was created with, so the contract's +// subtest for it runs rather than skips here. +func TestBackchannelAuthenticationStoreReportsAnUnknownHandle(t *testing.T) { + store := NewBackchannelAuthenticationStore() + if _, err := store.LookupBackchannelAuthentication(context.Background(), sha256.Sum256([]byte("no such handle"))); !errors.Is(err, storage.ErrBackchannelAuthenticationNotFound) { + t.Fatalf("lookup of an unknown handle = %v, want it to wrap ErrBackchannelAuthenticationNotFound", err) } }