Skip to content

feat: report invalid fields of write requests - #378

Merged
uniqueg merged 10 commits into
devfrom
feat/field-errors
Nov 9, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/field-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #317

Write requests with invalid fields now get a 400 that lists every invalid field in errors. Each entry has a JSON Pointer (pointer) or a parameter name (parameter), a stable code and a readable detail. That message never quotes the rejected value. The format is FOCA 0.22's (InvalidFieldsProblem, problem type and code invalid-request). It also covers the registry's own checks:

Code Field
invalid-url URLs of registrations, verifications and imports
scheme-not-allowed URLs with schemes their field doesn't allow
invalid-value environments the deployment doesn't allow
invalid-format timestamps that aren't RFC 3339 date-times
unregistered-type unregistered types, when the user may not add them
unusable-id serviceId of PUT /services/{serviceId} and id of renames that can't be stored in roles
not-service-info-url, path-not-normalized, too-long serviceInfoUrl of imports

Reserved 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 unusable serviceId. The body's fields come before the parameters.

detail and exceptions.validation_reasons: the app keeps exceptions.validation_reasons: true, which #382 set. So detail is still the reason for the rejection:

  • For the schema validation, it is the validator's message, as up to FOCA 0.21. That message may quote the value.
  • For the registry's own checks, it is FOCA's description of the invalid fields: their locations and messages, e.g. '#/url': Must not contain user info.. It quotes no values.

With validation_reasons: false, detail names the fields by location and code (Invalid fields: #/url (invalid-url)), and no part of the response quotes values. tests/test_validation_reasons.py tests both settings. The docs, the spec and the comment in config.yaml describe both.

  • Code:
    • cloud_registry/exceptions.py: InvalidFields carries field_errors, and reject() raises them as FOCA's InvalidFieldsProblem.
    • Field-error helpers in service.py: url_errors, link_errors, date_time_errors, environment_errors.
    • unusable_id_errors() in rename.py.
    • Checks that don't come from requests keep descriptions that name the fields. These are sync, self listing and the fetched service info of imports. The setting service_info.service.id is named for the registry's own entry.
  • Build: merged dev, so the PR now builds on the released FOCA 0.22.0. pyproject.toml has foca>=0.22.0,<0.23, the Dockerfile uses elixircloud/foca:0.22.0-py3.13 by digest, and uv.lock matches; all three are identical to dev after build: bump FOCA to 0.22.0 #382. The temporary dev pins and their TODOs are gone.
  • Spec: additions.openapi.yaml has the new schemas InvalidRequestError and FieldError, next to ConflictError, with all codes (x-extensible-enum).
  • Docs: api.md (Errors, with a table of codes and the detail of both settings), configuration.md, access-control.md, upgrading.md (From 1.0.0rc1, "Invalid fields"), releases/1.0.0rc2.md (Breaking changes).
  • Tests:
    • tests/test_field_errors.py and the existing modules test each code.
    • The shared helper invalid_fields() checks that errors doesn't quote the rejected values. Tests of the own checks also check the whole response.
    • A test checks the documented codes against the spec and the docs.
    • Unrelated fix: test_release_after_expiry used monkeypatch.undo(), which also undid the fixtures' mocks of the identity provider. It failed in CI with 401 whenever its token wasn't in FOCA's userinfo cache. It now uses monkeypatch.context().

How it was verified

  • coverage run --source cloud_registry,scripts -m pytest with 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-all reported 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.
  • Tests against a real MongoDB were not run locally; CI runs them.
  • The earlier Scan image failure (zlib1g CVE-2026-76844, CVE-2026-85091) came from the dated FOCA dev base image. The 0.22.0 image has no such findings (dev scans clean), and cloud-registry has no zlib1g Trivy ignores to remove (.trivyignore.yaml is empty).
  • The earlier Test (mongomock) failure was not a hang. That job took 21 min with 1 failure, the flaky invitation test fixed here. Its usual duration on dev is about 12 min.
  • CI: all checks passed on 73873b2 (run 42660853490) and, after the Sourcery fixes, on 16a62eb (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-reviewer and quality-reviewer on git diff origin/dev...HEAD.

Declined review findings

  • The parsing of FOCA's URL messages in _url_error depends on their wording (quality, medium; earlier round): FOCA's InvalidURL has no structured reason yet. I kept the parsing and added test_url_errors_details, which pins the code and detail of every FOCA reason, so a rewording in FOCA fails the tests.
  • The unusable serviceId is 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 of service_key(), with no change in behaviour.
  • This round, quality (medium): the collection of errors in server.py (nested try, check(errors=...)) could move into RegisterService. No change in behaviour; left for a refactor, as the PR is needed for a deployment today.
  • This round, quality (medium): test_codes_documented checks the docs with regexes over prose. It checks the table rows that start with each code and the spec's x-extensible-enum. That is enough to catch a missing code.
  • This round, quality (low): the generic FOCA codes are mirrored in exceptions.py (FOCA doesn't export them); unusable_id_errors lives in rename.py; a few overlapping tests and old test_check_* names; the shared BadRequest response references InvalidRequestError, whose errors/code are optional; the sentence on FOCA's logs in api.md (FOCA's logging is tested on dev's test_validation_error_logs_bounded). These are cosmetic or not behavioural. self_listing._new_entry_id rewording a surrogate failure only concerns the deployment's own config.
  • Fixed this round (adversarial, medium + low): the labels docs claimed that rejected labels are never returned, but detail quotes them with validation_reasons: true. The Errors section claimed all invalid fields are always reported together. The scheme-not-allowed docs didn't list verifications. All three are corrected in docs/access-control.md, docs/api.md and the spec. The adversarial probe found no rejected value in errors, in the own checks' detail, or in INFO logs.

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)

  • Permissions endpoints still return plain 400s, without errors: their checks aren't field checks of the body. They could get field errors in a later issue.
  • FOCA: a structured reason or code on InvalidURL, so that the registry doesn't need to parse messages. Also, namespace_subjects._read_only_app could use Foca.use_config().

🤖 Generated with Claude Code

uniqueg and others added 5 commits November 7, 2026 21:21
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the stable invalid-field codes and the exception data structure that carries field errors from registry checks.

  • cloud_registry/exceptions.py L3-5, L15, L35-114

API

Specify the invalid-request response schemas and use them for bad-request responses, including the service-import URL error.

  • cloud_registry/api/additions.openapi.yaml L266-273, L1535-1543, L1677-1791 (+1 small edits)

Uses of the API

Wire invalid-field reporting into registration, rename, listing, import, verification, and service-type request flows.

  • cloud_registry/ga4gh/registry/rename.py L52-59, L136-143, L182-203 (+4 small edits)
  • cloud_registry/ga4gh/registry/self_listing.py L51-57, L224-238
  • cloud_registry/ga4gh/registry/server.py L282-288, L306-321, L385-395 (+8 small edits)
  • cloud_registry/ga4gh/registry/service_import.py L39-48, L184-230, L427-436 (+8 small edits)
  • cloud_registry/ga4gh/registry/service_types.py L172-190 (+3 small edits)
  • cloud_registry/ga4gh/registry/verification.py L32, L140-143, L150

Convert registry exceptions carrying field errors into FOCA invalid-request responses.

  • cloud_registry/exceptions.py L266-291

Implementation

Implement value-safe field-error construction and aggregate URL, link, timestamp, environment, and identifier checks.

  • cloud_registry/ga4gh/registry/service.py L154-251, L297-344, L352-375 (+15 small edits)
  • cloud_registry/utils.py L161

Configuration

Document the configured validation-reason behavior and keep the FOCA exception settings explicit.

  • cloud_registry/config.yaml L396-405

Documentation

Explain the invalid-field response format, codes, value disclosure behavior, and upgrade impact.

  • docs/access-control.md L358-365
  • docs/api.md L374-455 (+4 small edits)
  • docs/configuration.md L225-226, L332-333
  • docs/releases/1.0.0rc2.md L47-54
  • docs/upgrading.md L93-104

Tests

Test field-error behavior across request validation, registry checks, imports, renames, verification, and documented codes.

  • tests/conftest.py L130-165 (+3 small edits)
  • tests/ga4gh/registry/test_server.py L36-41
  • tests/ga4gh/registry/test_service.py L476-494, L590-683, L958-967 (+16 small edits)
  • tests/ga4gh/registry/test_verification.py L7, L206-213, L223-230
  • tests/test_access_control.py L543-566
  • tests/test_app.py L882-895, L2344-2354, L2362-2409 (+13 small edits)
  • tests/test_exceptions.py L11-15, L55-67
  • tests/test_field_errors.py L1-239
  • tests/test_invitations.py L490-494
  • tests/test_rename.py L29, L353-382
  • tests/test_self_listing.py L214, L231-257
  • tests/test_service_import.py L123-126, L198-224, L319-331 (+1 small edits)
  • tests/test_service_types.py L32-39 (+4 small edits)
  • tests/test_validation_reasons.py L1-38, L62-108
  • tests/test_verification.py L16-22, L294-306, L308 (removed lines)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4e38426) to head (16a62eb).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

uniqueg and others added 4 commits November 9, 2026 17:12
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]>
@uniqueg
uniqueg marked this pull request as ready for review November 9, 2026 17:19

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread cloud_registry/exceptions.py Resolved
Comment thread tests/test_service_import.py Resolved
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]>

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread cloud_registry/exceptions.py Resolved
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.

feat: report invalid fields of registrations

1 participant