Skip to content

fix: limit request body size - #119

Merged
uniqueg merged 6 commits into
devfrom
fix/request-size-limit
Oct 21, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/request-size-limit

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Limits the size of request bodies, which were read into memory without limit before the access token was checked. Unauthenticated clients could therefore exhaust the pod's memory (pre-release review finding, #114).

  • App:
    • New config option custom.max_content_length (default 1 MiB), set as Flask's MAX_CONTENT_LENGTH in a new create_app(). Bodies with a larger declared size get 413 before authentication and parsing.
    • A before_request hook also rejects chunked bodies larger than the limit with 413. Without it, Werkzeug silently truncated them.
    • 413 responses are problem details titled "Content Too Large".
  • API: the string lengths in the registration schemas of additions.openapi.yaml are limited (URLs 2048, names 1024, description 4096, others 256). The vendored GA4GH specs are unchanged.
  • Helm chart:
    • The ingress-nginx proxy-body-size annotation is derived from config.custom.max_content_length. Explicit annotations take precedence, and null removes it.
    • The values schema and the helper reject null, zero and non-numeric limits. config.custom: null now behaves like no custom config.
    • tmpSizeLimit (default 64Mi) for the /tmp emptyDirs of the app and MongoDB. All-zero quantities are rejected.
  • Docs: the limits are documented in the README and the deployment README.

Closes #114

Verification

  • coverage run --source=cloud_registry -m pytest (with helm on PATH): 572 passed, 100 % coverage
  • ruff check, ruff format --check, mypy: pass
  • helm lint --strict (default values, CI values, CI values with auth off) and helm template: pass
  • ast-grep scan: clean
  • Two rounds of adversarial and quality reviews; confirmed findings fixed

CI: all checks pass (tests on Python 3.10 and 3.12, Helm chart, Compose, static analysis, codecov, Read the Docs).

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Protect the application from oversized requests by enforcing configurable body and field limits across the app, API, and Helm deployment.

New Features:

  • Limit request bodies to a configurable maximum and reject oversized requests with 413 problem details before authentication and parsing.
  • Enforce maximum lengths for registration and verification string fields in the API schema.
  • Add configurable Helm limits for ingress request bodies and application and MongoDB temporary volumes.

Bug Fixes:

  • Prevent unauthenticated oversized or chunked requests from exhausting application memory.

Enhancements:

  • Make Helm ingress annotation overrides explicit, including support for removing chart-provided annotations, and treat null custom configuration as absent.

Deployment:

  • Configure ingress-nginx body limits from the application request-size setting and add default /tmp emptyDir size limits for application and MongoDB pods.

Documentation:

  • Document request body, registration field, ingress, and temporary-volume size limits in the user and deployment guides.

Tests:

  • Add coverage for declared and chunked request-size enforcement, field length validation, configuration handling, and Helm rendering and validation.

uniqueg and others added 5 commits October 21, 2026 03:00
Request bodies were read into memory without limit before the access
token was checked, so unauthenticated clients could exhaust the pod's
memory.

- Set Flask's MAX_CONTENT_LENGTH from the new config option
  `custom.max_content_length` (default 1 MiB), in a new `create_app()`
  used by `main()` and the tests. Werkzeug raises 413 when Connexion
  first accesses the request stream (building its request, outside the
  security decorator), so before authentication and parsing; declared
  sizes are rejected without reading the body, chunked bodies are read
  up to the limit only (and truncated, so larger JSON bodies are 400).
- Map RequestEntityTooLarge to problem details ("Content too large").
- Limit the length of strings in the registration schemas of
  `additions.openapi.yaml` (URLs 2048, names 1024, description 4096,
  other fields 256); the vendored GA4GH specifications are unchanged.
- Helm chart: default Ingress annotation
  `nginx.ingress.kubernetes.io/proxy-body-size: "1m"` (via
  `ingress.annotations`, removable with `null`), and `tmpSizeLimit`
  (default 64Mi) for the `/tmp` emptyDirs of the app and MongoDB.
- Document the limits in the README and the deployment README.

Closes #114

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bring in #118 (HTTP(S)-only URLs). Conflicts in the README and
`additions.openapi.yaml` are resolved by keeping both changes: the URL
rules and descriptions of #118, and the `maxLength` limits and request
size notes of this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Werkzeug reads bodies of unknown size (chunked) up to
MAX_CONTENT_LENGTH only and silently drops the rest, so a valid body
padded to the limit and followed by junk was registered. A
`before_request` hook now reads one byte more than the limit for
requests without `Content-Length` and returns 413 if the body is
larger; bodies of exactly the limit pass.

Also, from the reviews:
- Title 413 responses "Content Too Large" (RFC 9110).
- Keep the table of length limits in the README only, mention that
  they apply to verification bodies, and note that services stored
  with longer values can't be updated or verified unchanged.
- Tests: import the default limit, drop a redundant test, slim down
  the 413 tests and parametrize the length limits explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The ingress-nginx annotation `proxy-body-size` was hard-coded as "1m"
in the values, apart from the app's limit. The Ingress now sets it from
`config.custom.max_content_length` (in bytes, default 1048576);
annotations in `cloud_registry.ingress.annotations` still take
precedence, and `null` removes it.

Also, from the reviews:
- `tmpSizeLimit` accepts Kubernetes quantities (checked by a pattern)
  or numbers of bytes; empty strings and 0 are rejected. Numbers from
  values files (floats) are rendered as integers.
- Render the `emptyDir` volumes of both pods with one helper.
- Deployment README: describe the derived limit, and point to the
  documentation of other ingress controllers instead of naming their
  settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A null, zero or non-numeric `config.custom.max_content_length` gave
`proxy-body-size: "0"`, i.e., no limit in ingress-nginx, and
`config.custom: null` failed with a Go error.

- The values schema requires a positive integer, and the helper fails
  with a clear message otherwise (also without schema validation);
  floats from values files are accepted if they are integers.
- `config.custom: null` is like no custom config: the generated
  custom config and the default limit are kept.
- Define `tmpSizeLimit` once in the schema, and reject all-zero
  quantities (with `not`, as Go regular expressions have no
  lookahead).
- Note that `check_streamed_size` relies on the cached body, drop an
  unused argument of a test helper and re-wrap the deployment README.

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

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR adds defense-in-depth request-size controls from application configuration through ingress and pod temporary storage, ensuring oversized declared or chunked bodies are rejected before authentication with consistent 413 problem details. It also adds schema-level limits for registration data, validates Helm configuration and override behavior, and documents and tests the new limits.

Sequence diagram for request body size enforcement

sequenceDiagram
    participant Client
    participant App as Flask/Connexion App
    participant Auth as Access Token Check
    participant Parser as Request Parser

    Client->>App: HTTP request
    alt Content-Length exceeds MAX_CONTENT_LENGTH
        App-->>Client: 413 Content Too Large
    else Chunked body exceeds MAX_CONTENT_LENGTH
        App->>App: check_streamed_size()
        App-->>Client: 413 Content Too Large
    else Body within limit
        App->>Auth: Check access token
        Auth->>Parser: Parse request body
        Parser-->>Client: API response
    end
Loading

Entity relationship diagram for registration field limits

erDiagram
    SERVICE_REGISTRATION {
        string url_2048
        string name_1024
        string description_4096
        string version_256
    }
    ORGANIZATION {
        string name_1024
        string url_2048
    }
    SERVICE_TYPE {
        string group_256
        string artifact_256
        string version_256
    }
    SERVICE_REGISTRATION ||--o| ORGANIZATION : contains
    SERVICE_REGISTRATION ||--|| SERVICE_TYPE : has
Loading

File-Level Changes

Change Details Files
Enforce bounded request-body handling before authentication and parsing, including chunked requests, and return standardized 413 problem details.
  • Added configurable positive custom.max_content_length with a 1 MiB default.
  • Configured Flask/Werkzeug to reject oversized declared bodies without reading them.
  • Added a pre-request streamed-body check that reads at most one byte beyond the limit for unknown-length bodies.
  • Mapped oversized-body exceptions to 413 Content Too Large responses.
  • Added tests for declared and chunked bodies, authentication ordering, custom limits, and boundary behavior.
cloud_registry/app.py
cloud_registry/config.yaml
cloud_registry/exceptions.py
cloud_registry/service_models/custom_config.py
tests/conftest.py
tests/service_models/test_custom_config.py
tests/test_app.py
Constrain registration and verification string fields through OpenAPI schema validation.
  • Added maximum lengths for URLs, names, descriptions, and service type/version fields.
  • Covered registration and verification validation behavior with boundary tests.
  • Documented the limits and compatibility impact for previously stored services.
cloud_registry/api/additions.openapi.yaml
README.md
tests/test_app.py
tests/test_verification.py
Propagate the application body limit into Helm ingress configuration and harden chart value handling.
  • Derived the ingress-nginx proxy-body-size annotation from config.custom.max_content_length.
  • Preserved explicit annotation overrides and supported null removal.
  • Handled config.custom: null as absent custom configuration and rejected invalid body limits.
  • Extended chart schema and tests for defaults, overrides, nulls, zero, and non-numeric values.
deployment/templates/_helpers.tpl
deployment/templates/cloud-registry-configmap.yaml
deployment/templates/cloud-registry-ingress.yaml
deployment/values.schema.json
deployment/values.yaml
tests/test_chart.py
tests/test_config.py
Limit temporary storage used by the application and MongoDB pods.
  • Added configurable tmpSizeLimit values defaulting to 64Mi.
  • Applied optional Kubernetes emptyDir.sizeLimit values to both /tmp volumes.
  • Supported quantity strings, byte counts, and null removal while rejecting invalid or zero quantities.
  • Documented the eviction behavior and configuration.
deployment/templates/cloud-registry-deploy.yaml
deployment/templates/mongo-deploy.yaml
deployment/templates/_helpers.tpl
deployment/values.yaml
deployment/values.schema.json
deployment/README.md
tests/test_chart.py
tests/test_config.py

Assessment against linked issues

Issue Objective Addressed Explanation
#114 Enforce a configurable maximum request-body size in the Flask app, rejecting oversized requests with 413 before authentication or body parsing, including bodies without a declared length. ✅
#114 Set request string-length limits in the registration and verification schemas so oversized fields are rejected. ✅
#114 Add deployment safeguards by matching the app limit in the Helm Ingress configuration and limiting /tmp emptyDir storage. ✅

Possibly linked issues

  • fix: limit request body size #114: The PR implements the issue’s proposed app-level body limit, unauthenticated 413 behavior, ingress limit, and /tmp size limits.
  • #unknown: The PR directly adds schema string-length limits requested by the issue’s registration-limits finding.

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 Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (36adf9a) to head (4edc890).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #119   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            9         9           
  Lines          654       676   +22     
=========================================
+ Hits           654       676   +22     

☔ 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
uniqueg marked this pull request as ready for review October 21, 2026 01:51

@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 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="cloud_registry/app.py" line_range="28-29" />
<code_context>
+        werkzeug.exceptions.RequestEntityTooLarge: The body is larger than
+            the size limit.
+    """
+    if request.content_length is not None:
+        return  # checked by Werkzeug, by the declared size
+    limit = current_app.config["MAX_CONTENT_LENGTH"]
+    request.max_content_length = limit + 1
</code_context>
<issue_to_address>
**Declared bodies bypass limit on unread routes**

When a request declares a body larger than the limit but targets an operation that does not read its request stream, `check_streamed_size` returns for every request with `Content-Length`, relying on Werkzeug to reject the size only when the stream is accessed. A request to an operation that does not consume a body can therefore proceed without a 413 (and a protected operation can check authentication first), contrary to the documented rejection of oversized requests before authentication.

Reject a declared `request.content_length` above the configured limit in the hook before returning.
</issue_to_address>

### Comment 2
<location path="README.md" line_range="197-198" />
<code_context>
+| `description` | 4096 |
+| `version`, `environment`, `type.group`, `type.artifact`, `type.version` | 256 |
+
+Services stored before these limits were introduced may have longer values;
+they can't be updated or verified unchanged, only with the values shortened.
+
 See [Access control](#access-control) for the roles and [Verified
</code_context>
<issue_to_address>
**Over-limit services get verified**

When an admin sends an empty or null verification body for a legacy service with over-limit fields, `putServiceVerification` treats the empty or null body as verification of the stored record and writes `VERIFIED` without checking its field lengths, so an over-limit legacy service is verified unchanged despite the README restriction.

Validate the stored service against the new field limits before verification and reject it if any values exceed them.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and the new 64 MiB /tmp limits can cause Kubernetes to evict the app or MongoDB pod if temporary-file use exceeds the cap, creating an outage before the limit is reverted. The request and string limits also reject requests that previously worked, but those effects stop after a revert.

Blocking findings: cloud_registry/app.py:29, README.md:198


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

Comment thread cloud_registry/app.py Resolved
Comment thread README.md Resolved
From Sourcery's review: declared sizes (`Content-Length`) over the
limit were only rejected by Werkzeug when the request stream was read,
which Connexion does for the current operations but which isn't
guaranteed for operations that don't read their body. The
`before_request` hook now rejects them itself.

Also correct the README: services stored with longer values can be
verified unchanged (with an empty body), only not updated unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 8af16ac into dev Oct 21, 2026
11 checks passed
@uniqueg
uniqueg deleted the fix/request-size-limit branch October 21, 2026 02:04
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.

fix: limit request body size

1 participant