Repository navigation
feat: report invalid fields of write requests - #378
Conversation
TODO: replace the pin by foca==0.22.0 (`foca>=0.22.0,<0.23`) and the base image by elixircloud/foca:0.22.0-py3.13 once FOCA 0.22.0 is released. Until then, the app is built on FOCA's dev head (98bdf2d) and its development image of that commit, for the invalid fields of 400 responses (elixir-cloud-aai/foca#586). The release workflow refuses these pins (scripts/check_release_pins.py). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Raise FOCA's InvalidFieldsProblem for invalid fields of write requests, including the registry's own checks: URLs and their schemes, links, timestamps, environments, unregistered service types, identifiers that can't be stored in roles, and import addresses. Each field gets a JSON Pointer or parameter name, a stable code and a message that never quotes the value. All invalid fields of a registration are reported together. Document the codes in the API additions (FieldError, InvalidRequestError) and in the docs, and update the tests for FOCA 0.22's value-free validation messages (validation_reasons off). Closes #317 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check identifiers of PUT /services/{serviceId} before anything is
stored, so that an unusable serviceId is reported together with the
invalid fields of the body (not only after a rollback). Name fields of
fetched service info with unpaired surrogates in imports, name fields
by their dotted keys in descriptions (e.g., of self listings), and name
the setting service_info.service.id for unusable identifiers of the
registry's own entry.
Pin the details of FOCA's URL reasons in tests, compare the documented
codes with the spec's x-extensible-enum, and say that FOCA's schema
validation reports most invalid timestamps first.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check identifiers of PUT /services/{serviceId} for roles only when the
request creates the service, so that stored services with identifiers
that can't be stored in roles (e.g., from before roles) can still be
updated. Report invalid strings of types of pending services with their
fields too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The unit tests of the controllers run without API routing, which the checks of identifiers for roles need (cf. tests/test_field_errors.py). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresDefine the stable invalid-field codes and the exception data structure that carries field errors from registry checks.
APISpecify the invalid-request response schemas and use them for bad-request responses, including the service-import URL error.
Uses of the APIWire invalid-field reporting into registration, rename, listing, import, verification, and service-type request flows.
Convert registry exceptions carrying field errors into FOCA invalid-request responses.
ImplementationImplement value-safe field-error construction and aggregate URL, link, timestamp, environment, and identifier checks.
ConfigurationDocument the configured validation-reason behavior and keep the FOCA exception settings explicit.
DocumentationExplain the invalid-field response format, codes, value disclosure behavior, and upgrade impact.
TestsTest field-error behavior across request validation, registry checks, imports, renames, verification, and documented codes.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #378 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 27 27
Lines 3265 3341 +76
=========================================
+ Hits 3265 3341 +76 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Takes dev's FOCA 0.22.0 pins (#382): `foca>=0.22.0,<0.23` in `pyproject.toml`, the release image `elixircloud/foca:0.22.0-py3.13` by digest in the `Dockerfile` and its `uv.lock`, replacing the temporary pins of FOCA's dev head. The 0.22.0 image has no zlib1g findings. Keeps dev's `exceptions.validation_reasons: true`: `detail` stays the reason of the rejection, i.e., the validator's message for the schema validation and the locations and messages of the invalid fields for the registry's own checks. The docs (Errors in `api.md`, `upgrading.md`, the 1.0.0rc2 notes) and the comment in `config.yaml` say so. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `exceptions.validation_reasons` (set by #382), `detail` is the reason of the rejection: the validator's message, which may quote the value, for the schema validation, and the locations and messages of the invalid fields for the registry's own checks. The tests assumed FOCA 0.22's default instead. - `invalid_fields()` checks that `errors` doesn't quote the values, and no longer what `detail` says. - Tests of the own checks check that no part of the response quotes the values, and the `detail` of all fields of a registration. - Tests of non-JSON bodies, unpaired surrogates and large values keep dev's checks of the reason. - `tests/test_validation_reasons.py` covers both settings, also `validation_reasons: false`, for the schema validation and the own checks. - The spec (`InvalidRequestError`) and `reject()` describe both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`test_release_after_expiry()` undid its patch with `monkeypatch.undo()`, which also undoes the patches of the fixtures: the mocked identity provider and the blocked network. Its next request then fetched from the fictitious provider and got `401` whenever its token wasn't cached (e.g., a new second since the last request), as in CI. The patch now lives in `monkeypatch.context()`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `exceptions.validation_reasons`, the `detail` of rejected invitation labels quotes them, and FOCA logs that reason at `DEBUG`; the labels section said they were never returned. The Errors section promised all invalid fields together, though conflicts found first (e.g., the limit of unused types) and the first invalid part of import addresses are reported on their own. `scheme-not-allowed` also applies to the `url` of verifications. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cloud_registry/exceptions.py" line_range="268-290" />
<code_context>
+def reject(exc: HTTPException) -> Response:
</code_context>
<issue_to_address>
**Permissions endpoint errors**
The issue asks for invalid-field reporting on all write endpoints. The new `reject()` adapter is used for several write paths, but permissions endpoints remain plain 400 responses without field errors, as the PR description notes.
</issue_to_address>
### Comment 2
<location path="cloud_registry/ga4gh/registry/self_listing.py" line_range="222-226" />
<code_context>
+ check_id(service_id)
+ except InvalidService as exc:
+ # names the setting, as listings have no request body to point to
+ raise InvalidService(
+ "The identifier of the service info (`service_info.service.id`) "
+ "can't be used for services: it must not contain commas or line "
+ "breaks, and must not be too long."
+ ) from exc
return service_id
</code_context>
<issue_to_address>
**Misleading self-listing identifier error**
When the configured `service_info.service.id` contains an unpaired surrogate, `check_id()` can reject `service_info.service.id` for an unpaired surrogate, but this handler replaces that reason with a message about commas, line breaks, and length. The deployment administrator sees an inaccurate explanation for the invalid setting.
Preserve or distinguish the original failure reason when rewriting the self-listing identifier error.
</issue_to_address>
### Comment 3
<location path="tests/test_service_import.py" line_range="321" />
<code_context>
- """Strings that can't be stored are invalid."""
+ """Strings that can't be stored are invalid, naming the field."""
serve(b'{"id": "x", "name": "\\ud800"}')
assert post(client).status_code == 400
serve(
- json.dumps({**INFO, "name": "\ud800"}).encode(),
</code_context>
<issue_to_address>
**Incomplete info masks surrogate handling**
When the first served document is missing required service-info fields, when the served service info contains only `id` and a surrogate-bearing `name`, `test_surrogates` checks only that the import returns 400. Missing required service-info fields can cause that response, so the assertion still passes if the surrogate check stops rejecting the name.
Use otherwise-valid service info for the first case and assert that the rejection identifies `name`.
</issue_to_address>Linked issues
#317 feat: report invalid fields of registrations · 2 of 3 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Report every invalid field on all write endpoints, including the registry's own checks. | 🟡 Partly met | The change reports fields for registrations, imports, renames, and verifications, but permissions endpoints still return plain 400 responses without errors. |
| 2 | Document the codes in the API specification and docs, next to the conflict codes. | ✅ Met | The FieldError and InvalidRequestError schemas and the Errors documentation describe the codes. |
| 3 | Add tests for each code. | ✅ Met | Tests cover the app's field-error codes and check that the codes are documented. |
Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: cloud_registry/exceptions.py:290, cloud_registry/ga4gh/registry/self_listing.py:226, tests/test_service_import.py:321
A `service_info.service.id` with unpaired surrogates was refused with the message about commas, line breaks and length. The message now gives the reason that applies. The import test of surrogates in the fetched `name` uses otherwise valid service info and checks that the field is named, so that missing fields can't pass it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Linked issues
#317 feat: report invalid fields of registrations · 2 of 3 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Report every invalid field on all write endpoints, including fields rejected by the registry's own checks. | 🟡 Partly met | The change adds field errors for registrations, renames, imports, and verifications, but the PR notes that permission endpoints still return plain 400 responses. |
| 2 | Document the codes in the API specification and the docs, next to the existing conflict codes. | ✅ Met | The specification adds InvalidRequestError and FieldError, and the API docs list the codes. |
| 3 | Add tests for each code. | ✅ Met | The tests cover the registry's field-error codes and check that the documented codes match the specification. |
Summary
Closes #317
Write requests with invalid fields now get a
400that lists every invalid field inerrors. Each entry has a JSON Pointer (pointer) or a parameter name (parameter), a stablecodeand a readabledetail. That message never quotes the rejected value. The format is FOCA 0.22's (InvalidFieldsProblem, problem type andcodeinvalid-request). It also covers the registry's own checks:invalid-urlscheme-not-allowedinvalid-valueinvalid-formatunregistered-typeunusable-idserviceIdofPUT /services/{serviceId}andidof renames that can't be stored in rolesnot-service-info-url,path-not-normalized,too-longserviceInfoUrlof importsReserved IDs are reported by FOCA's schema validation, as
pattern-mismatch. All invalid fields of a registration are reported together, including an unregistered type and an unusableserviceId. The body's fields come before the parameters.detailandexceptions.validation_reasons: the app keepsexceptions.validation_reasons: true, which #382 set. Sodetailis still the reason for the rejection:'#/url': Must not contain user info.. It quotes no values.With
validation_reasons: false,detailnames the fields by location and code (Invalid fields: #/url (invalid-url)), and no part of the response quotes values.tests/test_validation_reasons.pytests both settings. The docs, the spec and the comment inconfig.yamldescribe both.cloud_registry/exceptions.py:InvalidFieldscarriesfield_errors, andreject()raises them as FOCA'sInvalidFieldsProblem.service.py:url_errors,link_errors,date_time_errors,environment_errors.unusable_id_errors()inrename.py.service_info.service.idis named for the registry's own entry.dev, so the PR now builds on the released FOCA 0.22.0.pyproject.tomlhasfoca>=0.22.0,<0.23, theDockerfileuseselixircloud/foca:0.22.0-py3.13by digest, anduv.lockmatches; all three are identical todevafter build: bump FOCA to 0.22.0 #382. The temporary dev pins and their TODOs are gone.additions.openapi.yamlhas the new schemasInvalidRequestErrorandFieldError, next toConflictError, with all codes (x-extensible-enum).api.md(Errors, with a table of codes and thedetailof both settings),configuration.md,access-control.md,upgrading.md(From 1.0.0rc1, "Invalid fields"),releases/1.0.0rc2.md(Breaking changes).tests/test_field_errors.pyand the existing modules test each code.invalid_fields()checks thaterrorsdoesn't quote the rejected values. Tests of the own checks also check the whole response.test_release_after_expiryusedmonkeypatch.undo(), which also undid the fixtures' mocks of the identity provider. It failed in CI with401whenever its token wasn't in FOCA's userinfo cache. It now usesmonkeypatch.context().How it was verified
coverage run --source cloud_registry,scripts -m pytestwith Helm 3.22.1 (chart tests included): 2394 passed, 11 skipped, coverage 100%.pre-commit run --all-files: all hooks passed (ruff, ruff-format, mypy, semgrep, gitleaks, actionlint, ast-grep, ast-grep-test, file checks).gitleaks-allreported matches only in local caches inside the clone (.cache/,.venv/), none in repository files.mkdocs build --strict: OK.python scripts/check_release_pins.py: OK.Scan imagefailure (zlib1g CVE-2026-76844, CVE-2026-85091) came from the dated FOCA dev base image. The 0.22.0 image has no such findings (devscans clean), and cloud-registry has no zlib1g Trivy ignores to remove (.trivyignore.yamlis empty).Test (mongomock)failure was not a hang. That job took 21 min with 1 failure, the flaky invitation test fixed here. Its usual duration ondevis about 12 min.73873b2(run 42660853490) and, after the Sourcery fixes, on16a62eb(run 42665600457): CI passed, Lint, Test (mongomock) 23m05s, Test (MongoDB 7.0) 14m18s, Chart, Docs, Smoke test, Scan image, Release readiness, PR title, CodeQL, Read the Docs.Lane
Full review: this changes validation behaviour. Reviewed with
adversarial-reviewerandquality-reviewerongit diff origin/dev...HEAD.Declined review findings
_url_errordepends on their wording (quality, medium; earlier round): FOCA'sInvalidURLhas no structured reason yet. I kept the parsing and addedtest_url_errors_details, which pins the code and detail of every FOCA reason, so a rewording in FOCA fails the tests.serviceIdis not reported if an earlier check raises on its own (adversarial, low; earlier round), e.g. for a type with unpaired surrogates, or a missing url or type. FOCA rejects such bodies before the app, so this can't happen for requests.check()validates the URL more than once (quality, low; earlier round): left as it is. Merging the checks would mean a larger rewrite ofservice_key(), with no change in behaviour.server.py(nestedtry,check(errors=...)) could move intoRegisterService. No change in behaviour; left for a refactor, as the PR is needed for a deployment today.test_codes_documentedchecks the docs with regexes over prose. It checks the table rows that start with each code and the spec'sx-extensible-enum. That is enough to catch a missing code.exceptions.py(FOCA doesn't export them);unusable_id_errorslives inrename.py; a few overlapping tests and oldtest_check_*names; the sharedBadRequestresponse referencesInvalidRequestError, whoseerrors/codeare optional; the sentence on FOCA's logs inapi.md(FOCA's logging is tested ondev'stest_validation_error_logs_bounded). These are cosmetic or not behavioural.self_listing._new_entry_idrewording a surrogate failure only concerns the deployment's own config.detailquotes them withvalidation_reasons: true. The Errors section claimed all invalid fields are always reported together. Thescheme-not-alloweddocs didn't list verifications. All three are corrected indocs/access-control.md,docs/api.mdand the spec. The adversarial probe found no rejected value inerrors, in the own checks'detail, or inINFOlogs.Sourcery
Three threads, all resolved: the self-listing ID message now gives the right reason, and the import surrogate test now uses otherwise valid info (both fixed in
16a62eb). The permissions endpoints are FOCA's API, so answered there; see the follow-ups.Follow-ups (not blocking this PR)
400s, withouterrors: their checks aren't field checks of the body. They could get field errors in a later issue.InvalidURL, so that the registry doesn't need to parse messages. Also,namespace_subjects._read_only_appcould useFoca.use_config().🤖 Generated with Claude Code