Repository navigation
feat(api): Add typed Sentry error codes and auth challenges - #131253
sentry-junior[bot] wants to merge 3 commits into
Conversation
SentryAPIException bodies, {"detail": {"code", "message", "extra"}},
now set code, detailMessage and extra on SentryApiError and its
subclasses. message stays the error's own, and other bodies leave the
fields unset. KnownSentryErrorCode lists the backend's codes, and
SentryErrorCode allows any other string. isSentryErrorCode narrows by
code.
getSentryAuthChallenge classifies SSO, sudo, superuser, staff, 2FA,
disabled-member and email-verification responses as data. The
withAuthChallenges fetch wrapper calls an onAuthChallenge handler and
replays the request once when it returns retry. The SDK opens no UI
and never redirects, and without the wrapper nothing is retried.
Co-Authored-By: BYK <[email protected]>
Co-Authored-By: BYK <[email protected]> # Conflicts: # static/packages/api/build.mjs # static/packages/api/lib/sentry-errors.ts
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit c76cc5b. Configure here.
| */ | ||
| export type SentryAuthChallenge = ChallengeBase & | ||
| ( | ||
| | { code: "sso-required"; loginUrl?: string; organizationSlug?: string } |
There was a problem hiding this comment.
Shouldn't these come from the backend directly?
There was a problem hiding this comment.
Ideally, yes. Today they can't be: the OpenAPI spec this package is generated from doesn't describe SentryAPIException bodies at all. It has no list of codes and no extra fields, and none of these codes appear in the published spec. So for now KnownSentryErrorCode and the challenge fields are kept in sync by hand with src/sentry/api/exceptions.py.
To generate them, the backend would first have to publish them, for example as a spec component that lists each SentryAPIException subclass with its code, status and extra keys. That would be a backend PR, landing first since src/ and static/ deploy separately. The SDK would then build the union and SentryAuthChallenge from that component instead of these hand-written types. Want me to take that on as a follow-up, or keep the hand-maintained list for this PR?
There was a problem hiding this comment.
Now they do:
- feat(apidocs): Publish the SentryAPIException error body as a component #131285 publishes a
SentryApiErrorBodycomponent built from theSentryAPIExceptionclasses. It has onedetailvariant per code, with that code's status andextrakeys, and a test that keepsextra_keysin sync with each class's__init__. - feat(api): Generate error codes and challenge fields from the spec #131287 (stacked on it) generates
KnownSentryErrorCodeand the auth-challenge fields from that component, and runtime behavior stays the same.
The /client core passed no body to createApiError when an error's detail was not a string, so SentryAPIException responses never set code on /client errors. Pass the parsed body. Report the superuser-required orgSlug extra on the challenge, and do not let a failed cancel of the challenge body stop the replay.
…nt (#131285) Part of #131203. `SentryAPIException` subclasses answer with `{"detail": {"code", "message", "extra"}}`, but the OpenAPI spec doesn't describe that body. `@sentry/api` (#131253) keeps a hand-written list of the codes, which can drift from the backend. This adds a `SentryApiErrorBody` schema component so clients can generate from the spec instead. - **Built from the exception classes.** The postprocessing hook walks every imported `SentryAPIException` subclass with a code. Each one becomes a `detail` variant with its `code` (a one-value enum), its HTTP status in `x-sentry-status`, and the string keys its `extra` can carry. Two classes that share a code with different statuses fail the build. - **`extra` keys.** `SentryAPIException` gets an `extra_keys` class attribute, set where the keys are stable: `sso-required` (`loginUrl`, `organizationSlug`), `sudo-required` and `primary-email-verification-required` (`username`), `member-disabled-over-limit` (`next`), `parameter-validation-error` (`context`), and `superuser-required` (`orgSlug`, which only organization-scoped checks send). Each class's `extra_keys` must match the keywords its `__init__` passes to `super().__init__`, so a new key there has to be declared. - **Component only.** No operation references it. Any operation can return these errors, so listing them per operation wouldn't be accurate. The variants also include the Bitbucket webhook codes, since those classes are `SentryAPIException` subclasses too. `ImageTooLarge` and `FileTooLarge` send an empty code, so they're left out. Next: an `@sentry/api` PR that generates `KnownSentryErrorCode` and the auth-challenge fields from this component. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A9cddb8264df48e793bc61c15cd431e51 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <[email protected]>
…131287) Part of #131203. Stacked on #131346, and it includes #131253's commits until that PR merges. #131253 added `KnownSentryErrorCode` and the auth-challenge fields to `@sentry/api` as hand-written copies of the backend's `SentryAPIException` classes, which can drift. #131285 publishes those classes as the spec's `SentryApiErrorBody` component, and #131346 marks the auth challenges in it, so the SDK now generates from it: - A new build step, `scripts/generate-error-codes.mjs`, reads the component with `ts.factory` into `SENTRY_ERROR_EXTRA_KEYS`, a code → `extra` keys table, and `SENTRY_AUTH_CHALLENGE_CODES`, the codes marked with `x-sentry-auth-challenge`. The build fails if the component is missing, an `extra` key isn't a string, or a variant has no boolean `x-sentry-auth-challenge`. - `KnownSentryErrorCode` is the table's keys. `SentryAuthChallenge` covers the marked codes, and each carries its fields from the table: `loginUrl` and `organizationSlug` for SSO, `orgSlug` for superuser, `username` for sudo and email verification, and `next` for a disabled member. `getSentryAuthChallenge` returns the same objects as before. - No code lists are left in the SDK. The README's list of challenge codes is checked against the spec. The known codes now also include the three Bitbucket webhook codes the backend defines. Nothing is removed from the public exports. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A9cddb8264df48e793bc61c15cd431e51 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <[email protected]>
…131362) Part of #131203. Stacked on #131287. Merge order: #131346, then #131253, then #131287, then this PR. Some endpoints document a `code` enum in their own error responses instead of sending a `SentryAPIException` body. Today that's the Seer autofix 402 (`seer_out_of_credits`, `seer_out_of_quota`) and 409 (`scm_integration_required`, `repos_not_linked`, `run_in_flight`). Clients such as getsentry/toolkit hand-write those strings (getsentry/toolkit#2234), and `SentryApiError.code` stayed unset for them, because the code sits at the top level of the body. - **Known codes:** `scripts/generate-error-codes.mjs` also collects every string `code` enum value in documented non-2xx response bodies, including `oneOf`/`anyOf`/`allOf` members. It drops the ones `SentryApiErrorBody` already has and emits the rest as `SentryOperationErrorCode`, which `KnownSentryErrorCode` now includes. - **Top-level `code`:** when a body has no `SentryAPIException` `detail`, `SentryApiError.code` reads a non-empty top-level string `code`. `detailMessage` comes from a string `detail`, and `extra` is empty. Other fields, such as Seer's `denialReason`, stay on `body`. `SentryAPIException` bodies read exactly as before, and win when a body has both. - **README:** the "Error codes" section describes both body shapes and where the known codes come from. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A9cddb8264df48e793bc61c15cd431e51 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <[email protected]>
Part of #131203. Follow-up to #131253, which covers error codes and auth challenges. When a request uses a project's old slug, the project endpoints answer with a 302 to the same URL with the new slug. That body has `slug` and `detail.extra`, but no error `code`. `fetch` follows the redirect, so callers never see that body. They just get the renamed project's data back. `getSentryProjectRename(request, response)` reports the rename anyway: - **Followed redirect:** it compares the request URL with the final response URL. - **Unfollowed 302** (`redirect: "manual"` outside browsers): it reads the `Location` header. - **Result:** `{ organization, previousSlug, slug, url }`, but only when the redirect stays on the same origin and only the project segment of `/projects/{organization}/{project}/` changes. Everything else returns `undefined`. It's classification only and never redirects. The README's new "Renamed projects" section shows how to use it from a response interceptor. Browsers hide where an unfollowed redirect points, so in a browser only followed redirects are reported. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A9cddb8264df48e793bc61c15cd431e51 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A9cddb8264df48e793bc61c15cd431e51/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <[email protected]>

Part of #131203.
The backend's
SentryAPIExceptionerrors return{"detail": {"code", "message", "extra"}}. Until now, consumers of@sentry/apihad to dig that out oferror.bodythemselves.Error codes
SentryApiErrorand its subclasses, including/client'sApiError, now havecode,detailMessageandextra.messagedoesn't change; it stays the error's own message. Errors with any other body don't get the new keys.KnownSentryErrorCodelists the codes insrc/sentry/api/exceptions.pyand the otherSentryAPIExceptionsubclasses.SentryErrorCodealso accepts any other string.isSentryErrorCode(error, "sudo-required")narrows an error to one code.Auth challenges
getSentryAuthChallenge(error)turns the SSO, sudo, superuser, staff, 2FA, member-disabled and email-verification responses into a typedSentryAuthChallenge. Each carries its code's string fields:loginUrlandorganizationSlugfor SSO,orgSlugfor superuser,usernamefor sudo and email verification, andnextfor a disabled member.withAuthChallenges(fetch, { onAuthChallenge })wraps any fetch, for example the one given tocreateSentryClient,createBrowserFetchorcreateApiTransport.onAuthChallenge(challenge, request)."retry"sends the request once more, after the app has re-authenticated. Returning"fail"keeps the challenge response.Without the wrapper, behavior is the same as before, apart from the new fields. The README documents both, including how to map codes to your own copy.
Possible type break: a
SentryApiErrorsubclass that declares its owncodenow needsoverrideundernoImplicitOverride, and itscodehas to be a string.Project-rename classification is in #131258.
via @BYK.
--
View Session [Sentry]