Repository navigation
fix(api): return actionable statuses for failed registry imports - #615
trentoliphant wants to merge 8 commits into
Conversation
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
left a comment
There was a problem hiding this comment.
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:
PullOptions.RejectUnverifiableLayersis 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 onmainand 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 thatExtractBundleignores 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.gogoes with it.displayRepoRefcannot affect any response.remote.NewRepositoryruns first inresolveBundleManifestand rejects any@in the host segment with an invalid-reference error (probed: bothuser:pw@host/repoanduser@host/repofail 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 andTestDisplayRepoRef.
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:
ImportEnvironmentininternal/api/handlers/registry_browse.gohas 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} ErrorResponseplusmake swaggerwould 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.
| // 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| // 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Removed in fdf1356, with TestDisplayRepoRef. The messages use the repository reference as given.
| } | ||
| var upstreamErr *service.UpstreamError | ||
| if errors.As(err, &upstreamErr) { | ||
| slog.Warn("upstream service refused the request", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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].
| // UpstreamStatus is the HTTP status the upstream answered with. | ||
| UpstreamStatus int | ||
| // Op is the server-side operation that was refused, for logs. | ||
| Op string |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // fails under a different operation and is not. | ||
| var copyErr *oras.CopyError | ||
| if errors.As(err, ©Err) && copyErr.Origin == oras.CopyErrorOriginSource && | ||
| copyErr.Op == "FetchReference" && errors.Is(copyErr.Err, errdef.ErrNotFound) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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]>
|
Thanks @tylerpotts. All of it is in
One thing I kept that you may want to rule on: Verified at |
Summary
POST /api/v1/registries/:id/importanswered500 {"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
500 {"error":"Internal server error"}422 {"error":"not a Nebi artifact"}422 {"error":"invalid bundle: <reason>"}404 {"error":"repository or tag not found: <host>/<repo>:<tag>"}502 {"error":"registry refused access to <host>/<repo>","upstream_status":401}<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:
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 addsservice.UnprocessableError.upstream_status.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:
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.Basicchallenge 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: sentinelsErrNotNebiArtifact,ErrInvalidBundle,ErrReferenceNotFound;InvalidBundleError(with the fixedReason) andRegistryAccessError(with the status and the spec-defined error codes). Classification reads the registry client's typederrcode.ErrorResponseanderrdef.ErrNotFoundviaerrors.As/errors.Is; there is no error-text matching.Error()strings of bundle errors are byte-identical tomain; the typed wrappers only addIs/Asbehavior.nebi importoutput is unchanged.internal/service:NotFoundError(matches the existingErrNotFoundundererrors.Is),UnprocessableError,UpstreamError(message and upstream status only), andclassifyBundlePullError, which also writes the WARN line.internal/api/handlers:handleServiceErrormaps the new types.ErrorResponsegains an optionalupstream_status(omitempty);erroris unchanged, so the envelope stays backward compatible.ImportEnvironmentnow has swagger annotations for 201/400/404/422/502/500.internal/swagger: regenerated withmake swaggerfor the new field and the endpoint.Testing
internal/api/handlers/registry_import_test.godrivesPOST /registries/:id/importend 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:Basic/Bearercredentials: 502, nothing leaked to body or log;Basicchallenge: 502 withupstream_status401;internal/oci: every rejection has a safeReason;PullBundleandExtractBundlereturn the right typed error for each case, including the anonymousBasicchallenge (with the client's error still in the chain);ExtractBundlereports a zero-size layer as an invalid bundle; a refusal keeps only spec-defined error codes.messages_test.gopins the exactError()strings the CLI prints; it passes onmainoncepushRawArtifactis copied along fromerrors_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.fdf1356:go test -tags=e2e -racepasses oninternal/oci,internal/service,internal/api/...andcmd/nebi;go vet -tags=e2eis clean;make swaggerleaves no further diff.golangci-lintwas last run atf775150, not on the review commit.The issue's repro, against a locally built binary (team mode,
quay.io):main@8b9fdd3)prometheus/busybox:latest{"error":"Internal server error"}500{"error":"not a Nebi artifact"}422nebi-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}502prometheus/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"}404Zero-size layers
A layer that declares size 0 with the digest of non-empty content can never verify.
ExtractBundlealready rejected it while copying; that rejection is now anInvalidBundleError, 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 addedPullOptions.RejectUnverifiableLayersto reject both; it was removed in review as out of scope for #614.Not in this PR
/repositories,/tags) still return their existing generic 500s.errorfield for a failed import, so it picks up the new messages without changes.🤖 Generated with Claude Code