Registry Mirror
Skip to content

Conversation

@lakhansamani

@lakhansamani lakhansamani commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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 of storage.Error, and it is transparent to errors.Is/errors.As and to the error message. service.MaskInternalError now masks storage.IsStorageError(err) || internalerr.Is(err), unless the error is a typed service.Error. Each masked error is logged with error_id and a new error_source field. GraphQL, gRPC ErrorMap (and through it REST and MCP), and publicErrorMessage all 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.

Boundary How it is marked
Memory store (Redis / in-memory / DB) errorBoundary decorator applied in memory_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 shared memerr.ErrNotFound sentinel (same "not found" text), and memory_store.IsNotFound also accepts redis.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.
OpenFGA engine opErr marks errors where OpenFGA itself returned serverErrors.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 an InternalError's text with a generic "Internal Server Error", so the gain here is not hiding text. It is the error_id correlation, and no longer passing OpenFGA's non-standard gRPC status (code 4000) straight through ErrorMap to clients.
Token signJWTToken (bad algorithm, unparseable private key, signer failure), the session fingerprint EncryptAES, and admin session-ID generation. Token validation errors are not marked, because they are user-facing.
Email SendEmail: template and SMTP dial/auth/send errors.
SMS errorBoundary in sms.New. A nil provider (SMS not configured) stays nil.
JWKS handler Public-key render errors were written raw to an unauthenticated endpoint. They now go through publicErrorMessage with source jwks.

2. Audit of client-reachable error text in internal/http_handlers

There are 61 err.Error() / %w|%v|%s uses of err, 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.

File / site Count Reaches client? Class Action
oauth_callback.go process*UserInfo (fmt.Errorf("…: %s", err.Error()), Google/GitHub/Facebook/LinkedIn/Apple/Discord/Twitter/Microsoft/Twitch/Roblox) 50 No. Logged only; client gets static oauth_callback_failed a none
oauth_sso.go discovery / token / id_token / JWKS %w 5 No. Client gets static ssoFail codes a none
saml_sp.go replay-check / cert / ACS / entity-ID %w 4 No. Client gets static samlFail / "connection misconfigured" a replay-check memory-store error is now also marked internal
oauth_sso.go:234, saml_sp.go:323 err != goredis.Nil 2 No (debug log only) a switched to errors.Is. A direct comparison is always true through the new wrapper.
register_client.go:166 validateRegistrationRedirectURI 1 Yes a static messages about the caller's own redirect_uri
public_error.go:18 1 Yes a the masking helper itself; returns only unmarked text
jwks.go:52,59 2 Yes (500 body, unauthenticated) b fixed: publicErrorMessage(internalerr.Wrap("jwks", err))
graphql.go:80 svcErr.Error() 1 Yes a typed service message
verify_email.go:89,119,198 3 Yes (JSON + redirect URL) b already routed through publicErrorMessage (#924). Line 198 (CreateAuthToken) is now actually masked because signing and memory-store errors are marked
oauth_login.go:96 GetOAuthConfig 1 Yes a/b already uses publicErrorMessage; current messages are static plus the provider name from the URL
oauth_callback.go:521, oauth_sso.go:307 2 Yes b already use publicErrorMessage
token_exchange.go rejectExchange / badTokenExchangeRequest descs all Yes a all string literals
authorize.go + consent.go redirectErrorToRP / validateAuthorizeRequest all Yes a literals, or the validated response_type
saml_idp.go samlIssuanceDenyReason all Yes a literals
scim/* mapServiceError all Yes a fixed SCIM messages; default is "internal error"
verify_email.go:208 1 No (comment) n/a n/a

Outside http_handlers: MCP forwards gwConn.Invoke errors, which already passed through ErrorMap. Its invalid arguments: … text comes from protojson decoding of the caller's own input (a). _test_endpoint deliberately 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 AddUser rejects 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.go re-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.

  • signup: an email signup carrying a phone number held by another account. This was reproducible, not just a race: the pre-check only covers the primary identifier. It now returns 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.
  • invite members (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.
  • create organization (AddOrganization) and add org member (AddOrgMembership): AlreadyExists (409).

Existing pre-checks are unchanged. The not-found contract is untouched (storage.IsNotFound is 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 InvalidArgument the 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

Revoke treats a memory-store miss on the refresh-token entry (already revoked, rotated or expired) like the existing empty-entry case: typed NotFound("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/revoke HTTP 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.go type-asserted the memory store against an anonymous interface whose Client() return type could never match the Redis backend's Client() 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.go uses it to wire the limiter. Tests: TestRedisClient_ReachesRateLimiter (Redis-gated: the limiter is the Redis implementation and its Eval-based check runs against Redis) and TestRedisClient_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 with error_id, error_source and level error. A typed error wrapping one keeps its message; plain untyped errors are untouched.
  • grpcsrv/interceptors: TestErrorMap_MasksInfraProviderErrors (includes an OpenFGA InternalError that carries its own gRPC status). TestErrorMap_DeliberateUntypedMessageUnchanged.
  • http_handlers: TestGraphQLErrorPresenter_MasksInfraProviderError (Redis dial error), TestPublicErrorMessage_InfraProviderError, TestJWKsHandler_MasksKeyError.
  • Boundaries: 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 misses: memory_store.TestIsNotFound_UniformAcrossBackends and TestNew_MarksErrorsInternal run against in-memory, DB, and Redis (run locally with TEST_ENABLE_REDIS=1 against a throwaway redis:7 container).
  • Conflicts (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-store outage vs miss: db.TestDBStore_OutageIsNotAMiss, db.TestDBStore_StorageNotFoundIsAMiss, db.TestDBStore_ExpiredStateIsAMiss. service.TestRevoke_StorageOutageIsInternal covers revoke during a storage outage through the real memory-store wrapper: masked internal, not NotFound. service.TestRevoke_SessionMissIsNotFound. TestIsNotFound_UniformAcrossBackends now also covers session and MFA-session expiry on all three backends.
  • Integration: TestSignup_PhoneConflictOnEmailSignup, TestRevoke_Twice.

Verification (run locally on this branch)

  • go build ./...: ok
  • go vet ./...: ok
  • make test (SQLite): ok, all packages pass
  • make lint (golangci-lint v2.15.0 + prettier): 0 issues
  • make 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/GetOrgMembership getters on every backend.

Not changed (deliberate)

  • ParseJWTToken public-key parse failures are not marked. They surface through validation paths that already convert them to unauthorized.
  • Organization rename (UpdateOrganization) keeps its pre-check only. There is no post-failure probe for that race.

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
lakhansamani force-pushed the fix/356-mask-remaining-errors branch from 3297f39 to 198c5d5 Compare November 26, 2026 10:44
@lakhansamani
lakhansamani merged commit 99b1356 into main Nov 26, 2026
4 checks passed
@lakhansamani
lakhansamani deleted the fix/356-mask-remaining-errors branch November 26, 2026 11:08
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Streamline error messages

1 participant