Skip to content

fix(api): return actionable statuses for failed registry imports - #615

Open
trentoliphant wants to merge 8 commits into
nebari-dev:mainfrom
trentoliphant:fix/614-typed-import-errors
Open

trentoliphant wants to merge 8 commits into
nebari-dev:mainfrom
trentoliphant:fix/614-typed-import-errors

Conversation

@trentoliphant

@trentoliphant trentoliphant commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

POST /api/v1/registries/:id/import answered 500 {"error":"Internal server error"} for failures the caller can act on, so an API client could not tell a bad artifact or a registry refusal from a broken server. The reason only appeared in the server log.

This classifies those failures in WorkspaceService.ImportFromRegistry, so local mode (oci.ExtractBundle) and team mode (oci.PullBundle) both get it.

Closes #614

Behavior

Failure Before After
Not a Nebi artifact 500 {"error":"Internal server error"} 422 {"error":"not a Nebi artifact"}
Malformed bundle 500 422 {"error":"invalid bundle: <reason>"}
Registry has no such repository or tag 500 404 {"error":"repository or tag not found: <host>/<repo>:<tag>"}
The pull is refused with 401/403 500 502 {"error":"registry refused access to <host>/<repo>","upstream_status":401}
Anything else 500 500, unchanged

<reason> is one of a fixed set: missing pixi.{toml,lock}, duplicate core layer, pixi.toml core layer has an unexpected title, pixi.lock core layer has an unexpected title, layer has an unknown media type, unsafe or colliding asset path, manifest is not valid JSON, zero-size layer has a non-empty digest (local mode only, see below).

Choices worth a look:

  • 422 rather than 400 for a bad artifact. ValidationError (400) is used for malformed request input. Here the request is well-formed and the thing it points at is the problem, so this adds service.UnprocessableError.
  • 502 rather than 401/403 for a registry refusal. A 401 or 403 from Nebi itself means "your Nebi session or permissions", and clients act on that. A refusal by the upstream registry is a different thing, so it is a 502 with the registry's own status in upstream_status.
  • Registries that answer 401 for a repository that does not exist (Quay does this for anonymous pulls) are reported as a refusal, because that is all the registry tells us.

What the response and the log may contain

Whoever controls the registry controls the manifest and the error bodies, and the registry client's errors carry full request URLs. So:

  • The 422 reason is fixed text. It never quotes the layer title, media type or asset path that triggered it.
  • The 404 and 502 messages are built from the repository reference the caller asked for, nothing else.
  • For a 502 the service logs one WARN line with the operation, host/repository, the upstream status and the registry's error codes. Only codes the distribution spec defines are logged (NAME_UNKNOWN, UNAUTHORIZED, DENIED, ...); a code the registry made up is dropped, and so are its message and detail. The codes let an operator tell a registry that answers 401 for a missing repository from one that refused the credentials. The registry client's error (request URLs, which can be signed, and the upstream error body, which can echo credentials) is not logged and not kept on the error value.

Which responses count

Classification reads only the typed errors the registry client already returns. Nothing changes at the HTTP layer: bundle pulls use the same clients as on main.

  • 404 is the registry client's own not-found for the manifest: either the tag does not resolve, or it resolves and the manifest it points at is gone, whether on the first fetch or on the one the local-mode extraction makes. A 404 from the token service arrives as a different error and stays a 500. So does a layer that 404s after the manifest was served: the reference exists, the registry is inconsistent.
  • 401/403 is an error response with that status anywhere in the pull, or a Basic challenge when no credentials are configured (which the registry client reports as "basic credential not found" rather than as an error response).

A 401 or 403 may have been answered by something the registry delegates to: its token service, or a host it redirected the request to, such as a blob storage backend. A manifest 404 may likewise have come from a host the registry redirected the manifest request to. These are attributed to the registry. The message names only the configured host/repository, never the URL that answered.

How

  • internal/oci: sentinels ErrNotNebiArtifact, ErrInvalidBundle, ErrReferenceNotFound; InvalidBundleError (with the fixed Reason) and RegistryAccessError (with the status and the spec-defined error codes). Classification reads the registry client's typed errcode.ErrorResponse and errdef.ErrNotFound via errors.As / errors.Is; there is no error-text matching.
  • Error() strings of bundle errors are byte-identical to main; the typed wrappers only add Is / As behavior. nebi import output is unchanged.
  • internal/service: NotFoundError (matches the existing ErrNotFound under errors.Is), UnprocessableError, UpstreamError (message and upstream status only), and classifyBundlePullError, which also writes the WARN line.
  • internal/api/handlers: handleServiceError maps the new types. ErrorResponse gains an optional upstream_status (omitempty); error is unchanged, so the envelope stays backward compatible.
  • ImportEnvironment now has swagger annotations for 201/400/404/422/502/500.
  • internal/swagger: regenerated with make swagger for the new field and the endpoint.

Testing

  • internal/api/handlers/registry_import_test.go drives POST /registries/:id/import end to end (route, service, OCI client) in both local mode (extract bundle) and team mode (pull bundle) against in-process registries, asserting status, exact body, and the captured server log:
    • refusals whose client error contains a signed token-service URL and JSON bodies echoing Basic / Bearer credentials: 502, nothing leaked to body or log;
    • manifests with credential-like text planted in titles, media types and asset paths: 422 with the fixed reason;
    • malformed manifest JSON and a non-Nebi artifact: 422; in local mode, a zero-size core or asset layer with a non-empty digest: 422;
    • a registry that answers an anonymous pull with a Basic challenge: 502 with upstream_status 401;
    • a manifest 404 from the registry, on tag resolution, on the manifest fetch after the tag resolved, or (local mode) on the second manifest fetch made during extraction, and after a token request that was redirected and succeeded: 404;
    • a token service answering 404, and a registry that serves the manifest but not its layers: 500.
  • internal/oci: every rejection has a safe Reason; PullBundle and ExtractBundle return the right typed error for each case, including the anonymous Basic challenge (with the client's error still in the chain); ExtractBundle reports a zero-size layer as an invalid bundle; a refusal keeps only spec-defined error codes. messages_test.go pins the exact Error() strings the CLI prints; it passes on main once pushRawArtifact is copied along from errors_test.go.
  • internal/service/workspace_import_errors_test.go: each mapping in both modes, plus that a failed import leaves no workspace or staging directory behind.
  • internal/api/handlers/helpers_test.go: status and exact JSON body for each service error type.
  • At fdf1356: go test -tags=e2e -race passes on internal/oci, internal/service, internal/api/... and cmd/nebi; go vet -tags=e2e is clean; make swagger leaves no further diff. golangci-lint was last run at f775150, not on the review commit.

The issue's repro, against a locally built binary (team mode, quay.io):

Request Before (main @ 8b9fdd3) After
prometheus/busybox:latest {"error":"Internal server error"} 500 {"error":"not a Nebi artifact"} 422
nebi-repro/does-not-exist:latest {"error":"Internal server error"} 500 {"error":"registry refused access to quay.io/nebi-repro/does-not-exist","upstream_status":401} 502
prometheus/busybox:nebi-repro-no-such-tag {"error":"Internal server error"} 500 {"error":"repository or tag not found: quay.io/prometheus/busybox:nebi-repro-no-such-tag"} 404

Zero-size layers

A layer that declares size 0 with the digest of non-empty content can never verify. ExtractBundle already rejected it while copying; that rejection is now an InvalidBundleError, so local mode answers 422 instead of 500.

Team mode is unchanged from main: such a core layer fails its fetch and is a 500, and such an asset layer is imported, because team mode never downloads assets. An earlier revision of this PR added PullOptions.RejectUnverifiableLayers to reject both; it was removed in review as out of scope for #614.

Not in this PR

  • Rejecting a zero-size layer with a non-empty digest in team mode (see above).
  • Other registry endpoints (/repositories, /tags) still return their existing generic 500s.
  • A bundle over the size cap still returns 500.
  • The pre-existing "unhandled service error" log line for 500s is unchanged; it still logs the underlying error.
  • The frontend already shows the error field for a failed import, so it picks up the new messages without changes.

🤖 Generated with Claude Code

trentoliphant and others added 7 commits October 2, 2026 23:58
PullBundle and ExtractBundle returned plain fmt.Errorf strings, so a
caller could only tell "this is not a Nebi bundle" from "the registry
said no" by matching message text.

Add sentinels that callers can test with errors.Is:

- ErrNotNebiArtifact: the reference is not a Nebi artifact;
- ErrInvalidBundle: every manifest rejection in classifyBundleManifest
  (missing/duplicate core layer, wrong core title, unknown media type,
  unsafe asset path);
- ErrReferenceNotFound: the registry has no such repository or tag.

Add RegistryStatus, which reads the HTTP status out of the registry
client's typed error response instead of the error text.

Messages are unchanged except that an unsafe asset path now reads
"invalid bundle: unsafe path: ..." and a missing reference names
"repository or tag not found".

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
POST /registries/:id/import answered a bare 500 "Internal server error"
for failures the caller can act on, so an API client could not tell a
bad artifact or a registry refusal from a broken server.

ImportFromRegistry now classifies a failed pull or extract, in both
local and team mode, and handleServiceError maps the result:

- not a Nebi artifact / invalid bundle -> 422 with the reason;
- repository or tag not found upstream -> 404 naming the reference;
- registry (or its token service) answered 401/403 -> 502 with
  "registry refused access to <host>/<repo>" and the registry's status
  in a new optional "upstream_status" field;
- anything else is still a logged 500.

The caller-facing message is built from the repository reference only.
The registry's response, request URLs and credentials are never echoed;
the underlying cause is logged server-side.

The error envelope stays backward compatible: "error" is unchanged and
"upstream_status" is omitted unless set. Swagger docs regenerated for
the new field.

Closes nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Follow-up to the typed registry-import errors:

- The 502 path logged the registry client's error verbatim. That error
  carries full request URLs (token-service and redirected blob URLs can
  hold signed query strings) and the upstream JSON error body, which can
  echo credentials. UpstreamError no longer carries the cause; the log
  records only the operation, "host/repository" and the upstream status.
- The 422 body returned the validation error text, which quotes layer
  titles, media types and asset paths the registry controls. Bundle
  rejections are now an oci.InvalidBundleError with a fixed Reason that
  quotes nothing from the manifest, and the API returns only that.
- A 404 from the token service was reported as "repository or tag not
  found", and responses from a host the registry redirected to were
  attributed to the registry. Not-found now requires the registry
  client's own not-found for the manifest request with no redirect to
  another host, and a 401/403 counts as a registry refusal only when it
  was answered by the registry or its token service
  (oci.RegistryAccessError). Everything else stays a 500.
- Malformed manifest JSON and a zero-size layer with a non-empty digest
  are now invalid bundles (422) instead of 500s.
- Error() strings of bundle errors are byte-identical to what they were
  before this branch, so `nebi import` output is unchanged; the typed
  wrappers expose the classification through errors.Is/As.

The import route is now tested end to end in both modes against
in-process registries, asserting status, body and captured server log.

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Follow-up to the registry-import error classification:

- Provenance was tracked in a redirect log shared by the whole pull, so
  a redirect on one request changed how an unrelated response was
  reported (a token request redirected to another host, then a manifest
  404 from the registry, came out as a 500). The log is gone. A small
  RoundTripper, originTransport, now looks at each request's own
  redirect chain: when a request was redirected to another host and
  that host answers 401, 403 or 404, it returns a transport error
  instead of the response. Classification no longer needs to know about
  redirects at all.
- A Basic challenge with no credentials configured makes the registry
  client return auth.ErrBasicCredentialNotFound rather than an error
  response. That is now a RegistryAccessError with status 401, with the
  client's error kept in the chain.
- PullBundle now rejects a zero-size layer with a non-empty digest
  (core or asset) as an invalid bundle before fetching anything, using
  the same check ExtractBundle makes while copying. ExtractBundle's
  message is unchanged.
- The pull client is now a copy of the client the other registry calls
  use, with a copy of its HTTP client and only the transport wrapped,
  so timeout, cookie jar, redirect policy, transport, headers and auth
  cache are inherited instead of being replaced by fresh literals.

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Tracking which host answered a response needed a transport wrapper and
a copied HTTP client, and changed errors and transport behaviour for
every caller of the bundle pull. Remove it:

- Bundle pulls use exactly the clients they use on main. No transport
  wrapper, no client copy, no HTTP-layer change.
- A failed pull is classified only from the error the registry client
  already returns. A 401 or 403 error response anywhere in the chain,
  or a Basic challenge with no credentials configured, is a
  RegistryAccessError; that covers the registry, its token service and
  a host it redirected to, and the error does not say which. A missing
  reference is the client's own not-found from tag resolution; a 404
  from the token service is a typed error response and does not match.

Unchanged: fixed 422 reasons, the sanitized WARN line, the zero-size
layer check in both entry points, and the pinned CLI messages.

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- When the tag resolves but fetching the manifest it points at returns
  404 (deleted in between, say), the pull now reports
  ErrReferenceNotFound, with the message and cause unchanged. A 404
  from the token service or for a layer is still not a missing
  reference.
- PullBundle's early rejection of a zero-size layer with a non-empty
  digest is now behind PullOptions.RejectUnverifiableLayers, which only
  the import service sets. `nebi import` does not set it, so its
  messages for such bundles are exactly what they were; a new test in
  cmd/nebi pins them for pixi.toml, pixi.lock and an asset layer.

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
ExtractBundle validates the manifest and then hands the pull to
oras.Copy, which fetches the manifest again. If the manifest is gone by
then, the copy fails with errdef.ErrNotFound for its source-side
FetchReference operation, and the import answered 500. That case is
now ErrReferenceNotFound, with the message and chain unchanged. A layer
that is not found fails under a different copy operation and stays
unclassified.

Refs nebari-dev#614

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@tylerpotts tylerpotts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. The core is right: typed errors originate in internal/oci, the service translates them, handleServiceError stays the one mapping point, and both modes share the classifier. The leak tests that assert on the captured server log are a nice touch. Verified at f775150: go test -tags=e2e -race green on oci, service, handlers and cmd/nebi; golangci-lint clean; I also ran the message-pinning tests against main @ 8b9fdd3 and they pass.

Requesting changes on scope only. Two pieces are independent of #614 and should come out of this PR:

  1. PullOptions.RejectUnverifiableLayers is a team-mode behavior change the issue never asked for. A bundle with a zero-size asset layer and a non-empty digest imports with 201 on main and now returns 422. Flipping the flag to false turns exactly two subtests red (registry_import_test.go:462-490) and nothing else, so it is cleanly separable. It is also an odd shape: a flag on a shared options struct that ExtractBundle ignores because it already enforces the rule unconditionally. In its own PR the better answer is probably to enforce it in both paths and accept the improved CLI message. cmd/nebi/import_messages_test.go goes with it.
  2. displayRepoRef cannot affect any response. remote.NewRepository runs first in resolveBundleManifest and rejects any @ in the host segment with an invalid-reference error (probed: both user:pw@host/repo and user@host/repo fail at construction). That error matches none of the typed cases, so the caller gets a 500 before the ref is ever displayed. Drop the helper and TestDisplayRepoRef.

I'd keep the fixed-Reason sanitization even though the issue literally asked for the invalid bundle: ... text. Once registry-controlled text goes into an API body, not echoing it is part of doing this correctly.

Non-blocking suggestions are inline. Two more that have no diff line to attach to:

  • ImportEnvironment in internal/api/handlers/registry_browse.go has no swagger annotations, so 201/400/404/422/502 are all undocumented. Pre-existing gap, but this PR is the one defining the status contract. @Failure 404/422/502 {object} ErrorResponse plus make swagger would close it.
  • Commit 1ef802d adds a transport wrapper that e2bd5e7 removes, so please squash on merge.

Small correction to the description: messages_test.go passes on main only with pushRawArtifact copied along from errors_test.go. The substance holds; the wording "unmodified" does not.

Comment thread internal/oci/browser.go Outdated
// anything, a bundle with a layer that declares Size 0 but whose
// digest is not that of empty content. ExtractBundle always rejects
// such a layer as it copies, so the option has no effect there.
RejectUnverifiableLayers bool

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scope: independent of #614 and a behavior change for team mode (201 on main becomes 422 for a zero-size asset layer). Please split this into its own PR. See the review summary for the mutation check that shows only two subtests depend on it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in fdf1356: the option, the PullBundle check, the service setting it, and cmd/nebi/import_messages_test.go.

Team mode is back to what main does for these bundles. I kept one piece: ExtractBundle already rejected such a layer, and that rejection is now an InvalidBundleError, so local mode answers 422 for it instead of 500. The handler subtests for it now run in local mode only. If you would rather that go to the follow-up as well, say so and I will take it out.

I have not opened the follow-up PR yet.

Comment thread internal/service/workspace_import.go Outdated

// displayRepoRef returns repoRef in a form safe to show to a caller: any
// userinfo embedded in the host part ("user:secret@host/repo") is dropped.
func displayRepoRef(repoRef string) string {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: this is unreachable. remote.NewRepository at browser.go:374 rejects a host segment containing @ before any request is made, and that error falls through classifyBundlePullError to the generic 500. Remove this and TestDisplayRepoRef.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in fdf1356, with TestDisplayRepoRef. The messages use the repository reference as given.

Comment thread internal/api/handlers/helpers.go Outdated
}
var upstreamErr *service.UpstreamError
if errors.As(err, &upstreamErr) {
slog.Warn("upstream service refused the request",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: classifyAccess already has the oras ErrorResponse, whose Errors[].Code values are distribution-spec tokens with exported constants (errcode.ErrorCodeNameUnknown, ErrorCodeDenied, ErrorCodeUnauthorized, ...). Logging only codes that match those constants is safe against a hostile registry and lets an operator tell Quay's "name unknown" 401 from a real credential refusal. Today nothing from resp.Errors reaches any log.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fdf1356. RegistryAccessError now carries Codes: the codes from the error response that match an errcode constant, in order, without repeats. Anything else, including the message and detail, is dropped. The WARN line logs them as registry_error_codes.

TestClassifyAccess_Codes covers a made-up code, a lower-case one and a repeat. The handler test for the token-service refusal checks the log has registry_error_codes=[UNAUTHORIZED].

Comment thread internal/service/errors.go Outdated
// UpstreamStatus is the HTTP status the upstream answered with.
UpstreamStatus int
// Op is the server-side operation that was refused, for logs.
Op string

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: Op and Target exist only so the handler can emit the WARN line. Elsewhere the service layer logs its own operational warnings (registry.go:78, workspace_worker.go:78). Logging in classifyBundlePullError would let this type shrink to Message + UpstreamStatus. Your call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took the suggestion in fdf1356. classifyBundlePullError logs the WARN line and UpstreamError is Message + UpstreamStatus. It also meant the error codes did not have to travel on the service error.

Comment thread internal/oci/browser.go
// fails under a different operation and is not.
var copyErr *oras.CopyError
if errors.As(err, &copyErr) && copyErr.Origin == oras.CopyErrorOriginSource &&
copyErr.Op == "FetchReference" && errors.Is(copyErr.Err, errdef.ErrNotFound) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this keys on an undocumented oras op name (copy.go:427 in v2.6.2). It fails safe on a rename (404 degrades to 500), so no change needed, but a comment citing the oras source line would help whoever bumps the dependency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in fdf1356: the comment cites copy.go:427 in oras-go v2.6.2 and says what happens on a rename.

// client error is full of things that must stay out of both the response
// and the log: a token-service URL with a signed query string, and JSON
// error bodies that echo the credentials the client presented.
func TestImport_RegistryRefusal_DoesNotLeak(t *testing.T) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Asserting on the captured log as well as the body is the right test for this. Good.

Address review on the typed import errors:

- Remove PullOptions.RejectUnverifiableLayers. It changed team-mode
  behaviour the issue did not ask for (a zero-size asset layer with a
  non-empty digest went from 201 to 422) and belongs in its own change.
  ExtractBundle still reports the layer it already rejected as an
  invalid bundle. The CLI message test that pinned the flag's effect
  goes with it.
- Remove displayRepoRef. A reference with userinfo in the host is
  rejected when the repository is constructed, before any error could
  display it, so the helper was unreachable.
- Log a registry refusal in the service, where it is classified, and
  include the registry's error codes. Only codes the distribution spec
  defines are kept, so the line carries nothing else the registry chose.
  UpstreamError shrinks to the message and the upstream status.
- Cite the oras source for the "FetchReference" op name the vanished
  manifest check keys on.
- Document the import endpoint's statuses in swagger.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trentoliphant

Copy link
Copy Markdown
Contributor Author

Thanks @tylerpotts. All of it is in fdf1356; the threads have the detail.

  • Scope: RejectUnverifiableLayers and displayRepoRef are out, with their tests.
  • Suggestions taken: spec-defined registry error codes in the WARN line, the log moved into the service so UpstreamError is two fields, the oras source citation, and swagger annotations on ImportEnvironment (201/400/404/422/502/500) with make swagger rerun.
  • Description: corrected. messages_test.go passes on main only with pushRawArtifact copied along, and the zero-size section now describes what is left.

One thing I kept that you may want to rule on: ExtractBundle's existing zero-size rejection is typed as an invalid bundle, so local mode returns 422 for it. Team mode is unchanged from main.

Verified at fdf1356: go test -tags=e2e -race passes on internal/oci, internal/service, internal/api/... and cmd/nebi; go vet -tags=e2e is clean. I did not rerun golangci-lint on this commit, so CI is the check for that. Squash on merge is fine with me.

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.

Registry import returns a bare 500 for an invalid bundle or an upstream auth failure

2 participants