Conversation
lakhansamani
added a commit
that referenced
this pull request
Nov 26, 2026
- Revoke: a memory-store miss (already revoked/rotated) is a typed NotFound, not a masked 500; add a shared memerr.ErrNotFound sentinel and memory_store.IsNotFound (also accepts redis.Nil); log masked misses at warn - InviteMembers: skip an invitee lost to a concurrent create instead of failing mid-loop - Use errors.Is for redis.Nil in SSO/SAML state reads - Mark the OpenFGA 'render DSL returned nil' error internal; fix comments - Document conflict-probe placement and the committed-but-errored edge case - Tests: double revoke, invite race, signup email race (verification on), create-org and add-member races, cross-backend IsNotFound
…icts (#356) Mark memory-store (Redis/in-memory), OpenFGA internal faults, JWT signing, SMTP and SMS errors at their provider boundary with a new internalerr marker, so every transport masks them with an error_id like storage errors. Mask JWKS key-render errors. Map backend uniqueness conflicts on signup, invite, create organization and add member to typed errors via a post-failure probe instead of a masked 500.
- Revoke: a memory-store miss (already revoked/rotated) is a typed NotFound, not a masked 500; add a shared memerr.ErrNotFound sentinel and memory_store.IsNotFound (also accepts redis.Nil); log masked misses at warn - InviteMembers: skip an invitee lost to a concurrent create instead of failing mid-loop - Use errors.Is for redis.Nil in SSO/SAML state reads - Mark the OpenFGA 'render DSL returned nil' error internal; fix comments - Document conflict-probe placement and the committed-but-errored edge case - Tests: double revoke, invite race, signup email race (verification on), create-org and add-member races, cross-backend IsNotFound
The DB-backed memory store mapped every storage error to the miss sentinel, so a database outage surfaced as "token not found" and was logged at warn. Map only storage.IsNotFound to memerr.ErrNotFound and return other errors unchanged. Report expired OAuth state as a miss, matching in-memory/Redis.
cmd/root.go type-asserted the memory store against an anonymous interface whose Client() return type could never match the Redis backend's Client() redis.RedisClient, so distributed rate limiting never received the Redis client and every replica limited in memory. The memory-store error boundary would also hide Client(). Add memory_store.RedisClient, which looks through the boundary and asserts the real method, and use it for wiring.
lakhansamani
force-pushed
the
fix/356-mask-remaining-errors
branch
from
November 26, 2026 10:44
3297f39 to
198c5d5
Compare
This was referenced Nov 26, 2026
Merged
lakhansamani
added a commit
that referenced
this pull request
Nov 27, 2026
* test(e2e): smoke coverage for 2.4.9 fixes Black-box release smoke tests against the real binary for the 2.4.9 fixes: - GHSA-rpv7-grw6-r2jv: a wrong-password login to an unverified account arms an MFA session that skip_mfa_setup, lock_mfa, totp/email OTP setup and webauthn registration options must all reject on GraphQL, REST and gRPC; the emailed OTP (read from an in-test SMTP sink) still completes login via verify_otp. - #922: restart on the same DB with a role removed from --roles; login, validate_jwt_token on an old token and the refresh grant stop honouring it. - #924/#932: a fake Redis that errors after the startup PING; revoke returns a masked internal error with an error_id on every surface, and that id is logged next to the original error. - #927: admin users sort/filter return identical ordered results on GraphQL, REST and gRPC. startServer gains a startServerWithLog variant that returns the log path. * test(e2e): smoke coverage for 2.4.7 and 2.4.8 fixes Black-box, against the real binary: - GHSA-p7g3-2258-8wmp: org A's SCIM PATCH of a shared user's userName, emails, phoneNumbers (and a mixed PatchOp) is refused with 400/mutability and writes nothing; the reset cannot reach the attacker's mailbox; case-only and single-org changes still sync. - #904: RS256/ES256 tokens carry a kid equal to the RFC 7638 thumbprint of a JWKS key that verifies them, including a pre-rotation token after a primary-to-secondary rotation; HS256 tokens have no kid. - #913: client_id on access tokens and azp == aud on ID tokens from the authorization_code, refresh_token and client_credentials grants. - #903: list_permissions with cap+1 grants returns cap results and truncated=true on GraphQL, REST and gRPC; under the cap, false. * test(e2e): opt-in make smoke-db for SereneDB, SurrealDB and SQL Server `make smoke-db DB=serenedb|surrealdb|sqlserver` starts the database in Docker and runs TestReleaseSmokeDB against the real binary: signup, login, session, refresh grant, admin users list, forgot_password and resend_verify_email twice with the superseding link redeemed, and MFA enrollment twice plus a concurrent burst. The repeated forgot_password fails with INTERNAL on SQL Server without the 2.4.7 conflict-target fix. Skipped unless SMOKE_DB_ARGS is set, so `make smoke` stays SQLite-only and needs no Docker. * test(e2e): build the smoke binary once; unique smoke-db run ids; review nits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #356
Follow-up to #924. That PR masked storage-layer errors on every transport. This one closes the remaining gaps from the issue.
1. Infrastructure provider errors are masked like storage errors
There is a new leaf package,
internal/internalerr:Wrap(source, err),Is,Source. It is the non-storage counterpart ofstorage.Error, and it is transparent toerrors.Is/errors.Asand to the error message.service.MaskInternalErrornow masksstorage.IsStorageError(err) || internalerr.Is(err), unless the error is a typedservice.Error. Each masked error is logged witherror_idand a newerror_sourcefield. GraphQL, gRPCErrorMap(and through it REST and MCP), andpublicErrorMessageall pick this up without further changes.Errors are marked where they leave the provider, not where they reach the client. Untyped errors that nobody marked keep their text, so the many deliberate user-facing messages (
unauthorized,invalid token,unsupported provider: x, …) are unchanged.errorBoundarydecorator applied inmemory_store.New, same pattern as storage, with a compile-time interface assertion. Before this, errors from all three backends reached clients verbatim (the DB-backed store's misses are plain errors, not storage errors). Misses are now distinguishable from faults: the in-memory and DB backends return a sharedmemerr.ErrNotFoundsentinel (same"not found"text), andmemory_store.IsNotFoundalso acceptsredis.Nil. A masked miss is logged at warn, not error. The DB-backed store now returns the sentinel only when the storage layer reports not-found (storage.IsNotFound). Any other storage error is returned as-is, so a database outage stays a masked 500 logged at error, never "token not found" at warn. Expired OAuth state is a miss on the DB store too (it was"state expired"), matching in-memory and Redis.opErrmarks errors where OpenFGA itself returnedserverErrors.InternalError(datastore and unexpected faults). Marshal/render failures, including "render DSL returned nil", are marked too. Validation errors (unknown type/relation, invalid tuple, invalid DSL) are not marked: admins need to see them. OpenFGA already replaces anInternalError's text with a generic "Internal Server Error", so the gain here is not hiding text. It is theerror_idcorrelation, and no longer passing OpenFGA's non-standard gRPC status (code 4000) straight throughErrorMapto clients.signJWTToken(bad algorithm, unparseable private key, signer failure), the session fingerprintEncryptAES, and admin session-ID generation. Token validation errors are not marked, because they are user-facing.SendEmail: template and SMTP dial/auth/send errors.errorBoundaryinsms.New. A nil provider (SMS not configured) stays nil.publicErrorMessagewith sourcejwks.2. Audit of client-reachable error text in
internal/http_handlersThere are 61
err.Error()/%w|%v|%suses oferr, plus every response helper that takes a dynamic description (rejectExchange,registrationError,redirectErrorToRP,ssoFail,samlFail,samlIDPFail,utils.HandleRedirectORJsonResponse).Categories: (a) safe (static text, or derived from validated input, or never sent to the client). (b) could carry storage, provider or internal text.
oauth_callback.goprocess*UserInfo(fmt.Errorf("…: %s", err.Error()), Google/GitHub/Facebook/LinkedIn/Apple/Discord/Twitter/Microsoft/Twitch/Roblox)oauth_callback_failedoauth_sso.godiscovery / token / id_token / JWKS%wssoFailcodessaml_sp.goreplay-check / cert / ACS / entity-ID%wsamlFail/ "connection misconfigured"oauth_sso.go:234,saml_sp.go:323err != goredis.Nilerrors.Is. A direct comparison is always true through the new wrapper.register_client.go:166validateRegistrationRedirectURIredirect_uripublic_error.go:18jwks.go:52,59publicErrorMessage(internalerr.Wrap("jwks", err))graphql.go:80svcErr.Error()verify_email.go:89,119,198publicErrorMessage(#924). Line 198 (CreateAuthToken) is now actually masked because signing and memory-store errors are markedoauth_login.go:96GetOAuthConfigpublicErrorMessage; current messages are static plus the provider name from the URLoauth_callback.go:521,oauth_sso.go:307publicErrorMessagetoken_exchange.gorejectExchange/badTokenExchangeRequestdescsauthorize.go+consent.goredirectErrorToRP/validateAuthorizeRequestresponse_typesaml_idp.gosamlIssuanceDenyReasonscim/*mapServiceErrorverify_email.go:208Outside
http_handlers: MCP forwardsgwConn.Invokeerrors, which already passed throughErrorMap. Itsinvalid arguments: …text comes from protojson decoding of the caller's own input (a)._test_endpointdeliberately returns the admin-supplied webhook's transport error and response body to the super-admin as a diagnostic (a; left as-is).3. Backend "already exists" no longer becomes a 500
Every backend's
AddUserrejects a duplicate email or phone with its own error. After #924 that is a masked 500. I did not string-match 13 backends. Instead,internal/service/conflict.gore-queries storage after a failed create. If the identifier is now taken, the service returns a typed error. If the probe lookup itself fails, the original error stays masked, so an outage is never reported as a conflict.InvalidArgument("signup failed. please check your credentials or try a different method"), the phone pre-check's wording. A lost race on the email itself with email verification on returns the existing anti-enumeration success message.AddUser): an invitee created concurrently is skipped (continue), exactly as the pre-check skips emails that already exist. The request is not failed after earlier invitees were already created and emailed.AddOrganization) and add org member (AddOrgMembership):AlreadyExists(409).Existing pre-checks are unchanged. The not-found contract is untouched (
storage.IsNotFoundis unaffected by the new wrapper).Accepted, pre-existing phone-existence signal. An email signup with a phone number that is already taken now gets the same
InvalidArgumentthe phone-only signup pre-check already returns for a taken phone. Before this PR it was a masked 500 (and before #924, the raw "user with given phone number already exists"). That pre-check already reveals whether a phone is registered, so nothing new is exposed. Email existence stays hidden behind the anti-enumeration message when verification is on, including in the race window.Accepted edge case. A write that was applied but still reported an error (e.g. a Cassandra/DynamoDB timeout after the write landed) is probed as "taken" and reported as a conflict, although the row is the request's own. That outcome is recoverable (the resource does exist), whereas trusting the ambiguous write error would report a 500 for the same state. This is documented in
conflict.go.4. Double revoke is not a 500
Revoketreats a memory-store miss on the refresh-token entry (already revoked, rotated or expired) like the existing empty-entry case: typedNotFound("token not found"). Without this, the new wrapper would have turned every double revoke into a masked 500 with an ERROR log. Genuine store faults (including a database outage behind the DB-backed store) still return the masked internal error. (The RFC 7009/oauth/revokeHTTP endpoint has its own handler, which already answers 200 for an unknown or invalid token, and it is unchanged.)Also fixes: distributed rate limiting never used Redis
Pre-existing bug, which the new memory-store wrapper would also have hidden.
cmd/root.gotype-asserted the memory store against an anonymous interface whoseClient()return type could never match the Redis backend'sClient() redis.RedisClient. The assertion always failed, even on the raw Redis provider, so the rate limiter never received the Redis client. Every replica silently enforced a per-process in-memory limit, so the effective limit was N times the configured one.New
memory_store.RedisClient(p)looks through the error boundary, asserts the backend's real method, and returns the client (goredis.Cmdable), or nil for the in-memory and DB stores.cmd/root.gouses it to wire the limiter. Tests:TestRedisClient_ReachesRateLimiter(Redis-gated: the limiter is the Redis implementation and its Eval-based check runs against Redis) andTestRedisClient_NilWithoutRedis.Tests
Each test was confirmed to fail with the fix disabled.
service:TestMaskInternalError_InfraProviders. Memory-store, OpenFGA, token, email and SMS errors are masked and logged witherror_id,error_sourceand level error. A typed error wrapping one keeps its message; plain untyped errors are untouched.grpcsrv/interceptors:TestErrorMap_MasksInfraProviderErrors(includes an OpenFGAInternalErrorthat carries its own gRPC status).TestErrorMap_DeliberateUntypedMessageUnchanged.http_handlers:TestGraphQLErrorPresenter_MasksInfraProviderError(Redis dial error),TestPublicErrorMessage_InfraProviderError,TestJWKsHandler_MasksKeyError.memory_store.TestNew_MarksErrorsInternal,openfga.TestOpErr(internal error marked, validation error not),token.TestSignJWTToken_KeyErrorIsInternal,email.TestSendEmail_SMTPErrorIsInternal(real SMTP dial failure),sms.TestErrorBoundary_MarksErrorsInternal,sms.TestNew_UnconfiguredStaysNil.memory_store.TestIsNotFound_UniformAcrossBackendsandTestNew_MarksErrorsInternalrun against in-memory, DB, and Redis (run locally withTEST_ENABLE_REDIS=1against a throwaway redis:7 container).service/conflict_test.go):TestInviteMembers_RaceSkipsEmail,TestInviteMembers_AddUserOutageStaysInternal,TestSignUp_EmailRaceKeepsAntiEnumerationAnswer(verification on; the race answer equals the pre-check answer exactly),TestCreateOrganization_RaceIsAlreadyExists,TestAddOrgMember_RaceIsAlreadyExists.db.TestDBStore_OutageIsNotAMiss,db.TestDBStore_StorageNotFoundIsAMiss,db.TestDBStore_ExpiredStateIsAMiss.service.TestRevoke_StorageOutageIsInternalcovers revoke during a storage outage through the real memory-store wrapper: masked internal, not NotFound.service.TestRevoke_SessionMissIsNotFound.TestIsNotFound_UniformAcrossBackendsnow also covers session and MFA-session expiry on all three backends.TestSignup_PhoneConflictOnEmailSignup,TestRevoke_Twice.Verification (run locally on this branch)
go build ./...: okgo vet ./...: okmake test(SQLite): ok, all packages passmake lint(golangci-lint v2.15.0 + prettier): 0 issuesmake smoke: ok (boots the real binary; GraphQL/REST/gRPC/MCP)TEST_ENABLE_REDIS=1 go test ./internal/memory_store/...: ok (throwaway redis:7 on :6380)No storage provider was modified (only callers and the service layer), so no non-SQL storage backend run was needed. The memory-store sentinel change was additionally run against Redis. The conflict probes use the existing
GetUserByEmail/GetUserByPhoneNumber/GetOrganizationByName/GetOrgMembershipgetters on every backend.Not changed (deliberate)
ParseJWTTokenpublic-key parse failures are not marked. They surface through validation paths that already convert them tounauthorized.UpdateOrganization) keeps its pre-check only. There is no post-failure probe for that race.