Skip to content

Judge the scopes of a security requirement alike for the client and the server - #6016

Merged
Koudai Aono (koxudaxi) merged 2 commits into
fix1-18from
fix1-19
Nov 3, 2026
Merged

Koudai Aono (koxudaxi) merged 2 commits into
fix1-18from
fix1-19

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Fixes: #5849

Summary by CodeRabbit

  • New Features
    • Generated clients and FastAPI services now support security requirements that use role names, OAuth2 scopes, and OpenID Connect scopes.
  • Bug Fixes
    • Security scopes are now checked against the relevant security scheme and OpenAPI version. Invalid or unsupported scope combinations produce a diagnostic instead of being accepted silently.
    • Accepted scopes are consistently sorted and deduplicated in generated client output.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Walkthrough

A shared validator now checks security requirement scopes by scheme and OpenAPI version. The client and FastAPI planners use it. Client and FastAPI render tests add role-based security cases, including OpenAPI 3.0.

Changes: Security scope validation

Layer / File(s) Summary
Shared validation and planner integration
src/datamodel_code_generator/_target_contract.py, src/datamodel_code_generator/_client/security.py, src/datamodel_code_generator/_fastapi/plan.py, docs/architecture.md
scope_problem validates OAuth2 and OpenID Connect scope tokens and checks the OpenAPI 3.0 rule for other schemes. Both planners use the shared validator. The client sorts and deduplicates accepted scopes.
Client render coverage
tests/api_generation/test_client_generation.py, tests/api_generation/test_client_generation.refs
Client render cases and snapshots now cover auth-roles and auth-roles-30.
FastAPI render coverage
tests/api_generation/test_fastapi_generation.py, tests/api_generation/test_fastapi_generation.refs, tests/data/expected/main/generation_platform/fastapi/packages/security-roles/...
Added render cases and generated snapshots for security-roles and security-roles-30. The generated routes include API-key, bearer, and OAuth security requirements.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Merge Risk: Low · previous review 551d2

Mergeable with a bounded diagnostic follow-up: malformed API-key or HTTP security scopes are rejected, but the error misleadingly requests OAuth scope tokens rather than an array of strings.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the main change: applying consistent security-scope validation to client and server generation.
Linked Issues check Passed Issue #5849 has three coding requirements. All three use one shared rule now.

(1) oauth2 and openIdConnect: scope values must be RFC 6749 scope tokens. The PR adds scope-token constants and `scope_pr…
Out of Scope Changes check Passed All changed areas connect to issue #5849 scope validation:
- _target_contract.py: adds the shared scope_problem rule and its constants. This is the core change.
- _client/security.py: replaces t…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Linked Issues check

Explanation

Issue #5849 has three coding requirements. All three use one shared rule now.

(1) oauth2 and openIdConnect: scope values must be RFC 6749 scope tokens. The PR adds scope-token constants and scope_problem in _target_contract.py. The client SecurityPlanner.binding (_client/security.py) and the FastAPI Planner.security (_fastapi/plan.py) both call scope_problem. The FastAPI planner reports a problem as F_SECURITY_INVALID. Both targets therefore reject "read write". The regex body is not visible in the summary. The summary states that absent or invalid scopes report an error. It does not state whether an empty scope array is accepted for OAuth schemes. This is a non-blocking uncertainty.

(2) apiKey and http under OpenAPI 3.1: role names are unrestricted. scope_problem returns no problem for these schemes. Both targets accept "Billing Admin". Fixtures auth-roles (client) and security-roles (FastAPI) cover this case.

(3) Non-OAuth schemes under OpenAPI 3.0.x: non-empty scopes are an error. scope_problem reports nonempty scopes for non-token schemes when openapi is 3.0. Fixtures auth-roles-30 and security-roles-30 cover this case.

Automated tests: the PR adds the four render cases to the client and FastAPI parameterized render tests and adds their snapshot references. The client and FastAPI snapshot files are not reviewable in full because some are excluded (see ignored_files). The summary supports the behavior, so no coding requirement is unmet.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to issue #5849 scope validation:

  • _target_contract.py: adds the shared scope_problem rule and its constants. This is the core change.
  • _client/security.py: replaces the local _scope_tuple and ASCII regex with scope_problem. It also retains the scheme catalogues and OpenAPI value. The sort and deduplication of accepted scopes is a small behavior detail tied to the same binding path.
  • _fastapi/plan.py: applies the same rule on the server side and adds the diagnostic.
  • docs/architecture.md: documents the scheme-dependent scope rule. This supports the change.
  • Test registrations and .refs entries: add the auth-roles, auth-roles-30, security-roles, and security-roles-30 cases.
  • Expected snapshot files under tests/data/expected/.../security-roles/: generated output for the new FastAPI test case. These are test artifacts that support the change. They do not add runtime behavior of their own.

No changed hunk is shown to be unrelated to #5849.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 5 functions across 12 files. (3 skipped: 3 unsupported.)

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between a7aeb1f3cec32a75ed8eb6e0012bd1dd2b7d5391 and 551d2861f828d4699c2e1dd30644f0102514ea00.

Files ignored due to path filters: 18
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/generation_platform/client/auth-errors.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/client/auth-roles-30.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/client/auth-roles.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/client/packages/auth-roles/pydantic_v2_BaseModel/client/_generated/security.py is excluded by !**/_generated/** and included by tests/**/*.py, tests/data/expected/**/*.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/_generated/__init__.py is excluded by !**/_generated/** and included by tests/**/*.py, tests/data/expected/**/*.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/_generated/contract.py is excluded by !**/_generated/** and included by tests/**/*.py, tests/data/expected/**/*.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/_generated/openapi.json is excluded by !**/_generated/**, !tests/data/**/*.json and included by none
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/_generated/openapi.py is excluded by !**/_generated/** and included by tests/**/*.py, tests/data/expected/**/*.py
  • tests/data/expected/main/generation_platform/fastapi/security-errors.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/fastapi/security-roles-30.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/generation_platform/fastapi/security-roles.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/generation_platform/client/auth-errors.yaml is excluded by !tests/data/**/*.yaml and included by none
  • tests/data/generation_platform/client/auth-roles-30.yaml is excluded by !tests/data/**/*.yaml and included by none
  • tests/data/generation_platform/client/auth-roles.yaml is excluded by !tests/data/**/*.yaml and included by none
  • tests/data/generation_platform/client/cases.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/generation_platform/fastapi/cases.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/generation_platform/fastapi/security-errors.yaml is excluded by !tests/data/**/*.yaml and included by none
Files selected for processing: 15
  • docs/architecture.md
  • src/datamodel_code_generator/_client/security.py
  • src/datamodel_code_generator/_fastapi/plan.py
  • src/datamodel_code_generator/_target_contract.py
  • tests/api_generation/test_client_generation.py
  • tests/api_generation/test_client_generation.refs
  • tests/api_generation/test_fastapi_generation.py
  • tests/api_generation/test_fastapi_generation.refs
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/__init__.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/application.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/main.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/routers/__init__.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/routers/default.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/security.py
  • tests/data/expected/main/generation_platform/fastapi/packages/security-roles/pydantic_v2_BaseModel/server/services.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 2, 2026 22:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T22:23:54.415041Z 551d286 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai coderabbitai 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.

  • Fix comments: Fix CodeRabbit comments on this PR

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@codspeed

codspeed Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 33.43%

2 warnings

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚠️ 52 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

❌ 52 regressed benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_simple_msgspec_unset_field_rendering 320.9 ms 586 ms -45.23%
❌ test_perf_client_calls[sync] 24.9 ms 44.1 ms -43.65%
❌ test_perf_client_calls[async] 28.1 ms 48.8 ms -42.46%
❌ test_perf_scalar_root_collapsed_builtin 133.3 ms 222.6 ms -40.09%
❌ test_perf_load_pyproject_config[mapping-None] 237.1 µs 387.2 µs -38.77%
❌ test_perf_ordinary_array_constraint_generation 1.3 s 2.1 s -38.63%
❌ test_perf_load_pyproject_config[config-None] 234.2 µs 380.1 µs -38.39%
❌ test_perf_load_pyproject_config[mapping-multiple] 247.4 µs 401.3 µs -38.34%
❌ test_perf_load_pyproject_config[config-multiple] 246.7 µs 397.7 µs -37.98%
❌ test_perf_large_models_single_module_stdout 1 s 1.7 s -37.61%
❌ test_perf_large_models_dataclass_builtin 950.4 ms 1,520.1 ms -37.48%
❌ test_perf_large_models_msgspec 1.3 s 2.2 s -37.25%
❌ test_perf_large_models_pydantic_v2_builtin_double_quotes 934.9 ms 1,475.3 ms -36.63%
❌ test_perf_local_reference_file_resolution 91.3 ms 144.1 ms -36.6%
❌ test_perf_large_models_typed_dict[legacy-requiredness] 798.5 ms 1,253.9 ms -36.32%
❌ test_perf_large_models_typed_dict[total-false-requiredness] 806.1 ms 1,264.1 ms -36.23%
❌ test_perf_false_reference_validation 187.8 ms 294 ms -36.12%
❌ test_perf_large_models_pydantic_v2_noformat 894.9 ms 1,400.2 ms -36.09%
❌ test_perf_large_models_pydantic_v2_builtin 892.8 ms 1,396.4 ms -36.07%
❌ test_perf_inherited_required_fields[required-derived-first] 490.3 ms 766.4 ms -36.02%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix1-19 (5261b51) with fix1-18 (fab8b62)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@codecov

codecov Bot commented Nov 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…he server

The client refused a scope with a space or a role name on a requirement, and the server wrote it into the route's
Security(...), because each target read the scopes its own way. One rule in the target contract decides for both,
by the type of the scheme: an oauth2 or openIdConnect scheme lists scope tokens (RFC 6749 section 3.3), and any
other scheme lists role names, which OpenAPI 3.1 leaves to the API and OpenAPI 3.0 does not allow (its array must be
empty).

Fixes: #5849
@koxudaxi
Koudai Aono (koxudaxi) merged commit 32ef084 into main Nov 3, 2026
28 of 29 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the fix1-19 branch November 3, 2026 04:47
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: Breaking changes detected

Reasoning: I read the whole diff and analysis context. The PR moves scope validation into a shared scope_problem helper in _target_contract.py, and both the client and FastAPI targets now use it. The rule is now: oauth2 and openIdConnect schemes must list RFC 6749 scope tokens; in OpenAPI 3.1 other schemes may list role names of any text; in OpenAPI 3.0 other schemes may list no scopes at all. Some inputs that are invalid under the spec but generated before now fail. First, OpenAPI 3.0 documents that list scopes for apiKey or http schemes now error in the client target (it used to accept valid tokens) and in the FastAPI target (it used to accept them unchecked). Second, the FastAPI target now emits F_SECURITY_INVALID for oauth2 or openIdConnect scopes that are not valid tokens, which it never checked before. The new security-errors and security-roles-30 snapshots show both errors. The client target's handling of OpenAPI 3.1 role names was loosened, which breaks nothing. The only removed code was a private helper and regex in _client/security.py, so there are no public API, CLI or template changes. The accepted cells in the behaviour diff gate cover integer multipleOf and exclusive bounds past 2**53. They compare against the last release, and this diff does not touch that code, so I did not count them for this PR.

Content for Release Notes

Error Handling Changes

  • OpenAPI 3.0 security requirements listing scopes for non-OAuth schemes now fail generation - The client and FastAPI targets now use a shared scope_problem check and report an error like lists scopes for scheme 'key', whose type takes none in OpenAPI 3.0 when an OpenAPI 3.0 document lists scopes or role names for an apiKey, http or any other scheme that is not oauth2 or openIdConnect. The client generator used to accept these documents when the entries were valid scope tokens, and the FastAPI generator used to accept them without checking. To fix this, use an empty scope array for these schemes in OpenAPI 3.0 documents, or move the document to OpenAPI 3.1, where role names of any text are allowed (Judge the scopes of a security requirement alike for the client and the server #6016)
  • FastAPI target now validates OAuth2 and OpenID Connect scope tokens - The FastAPI server generator now reports F_SECURITY_INVALID with requires valid scope tokens for scheme ... when a security requirement lists scopes for an oauth2 or openIdConnect scheme that are not valid RFC 6749 scope tokens, such as a scope containing a space like read write. It used to generate the server without checking these scopes (Judge the scopes of a security requirement alike for the client and the server #6016)

This analysis was produced by the release draft workflow

Koudai Aono (koxudaxi) added a commit that referenced this pull request Nov 3, 2026
…import a model of a module that a shared import names under an alias, give item counts only to fields that can hold an array, and watch a JSON file named like inline JSON (#6037)

Fixes for the unresolved review findings of #6013, #6014, #6016, #6032 and #6033.

The scan of regex syntax reads the two counts of a counted repetition and reports one whose minimum exceeds its maximum,
which the Rust engine rejects at import. Python's `re` reads such a repetition as text where whitespace or a verbose
comment is inside (`a{ 3 , 2 }`), so the model selects python-re; without whitespace both engines reject it, as before.

A model imported from its module because a shared import binds the module's name (`from .IPv4Address import
OrderedDict`) rebound `OrderedDict` where another shared import (`--external-ref-mapping common.json=collections`)
binds it too, and the field typed by the mapped type got the model. The import takes an alias then (`OrderedDict_1`):
`ReferenceImportTarget.reserve_name` keeps the resolver of the module from giving it the shared name, in the import it
adds and in the replay of the released names.

`scope_problem` names the shape of scopes that are not an array of strings before it judges tokens, so a scheme that
takes no scope tokens (`apiKey`, `http`) no longer reports "requires valid scope tokens" for `bearer: 42`.

The item counts that boolean `items` and `contains` imply belong to an array. A root model took them for every type
since the root read them as a property does, so `{"type": "string", "contains": true, "minContains": 2}` became
`min_length=2` and rejected the strings the schema accepts, as the property of that schema always did, and a root
that names a model (`{"$ref": "#/$defs/Names", "contains": true, "minContains": 2}`) got a `min_length` that Pydantic
cannot apply to a model, which raised at the first array. A field whose type is no array (a scalar, a mapping, `Any`)
takes none (`can_hold_array`), and neither does a root beside a model, as in 0.88.0; a custom type and a union with an
array keep them. An object property beside a model keeps them as in 0.88.0 (row `legacy-property-counts-beside-models`).
The behaviour diff against 0.88.0 accepts the property change of the new fixture.

The allowlist entries of the property maps of a type list that joins an array match the minProperties and
maxProperties change only (the constraint, default, required and constructor-order lines it makes), not any change of
that field.

A JSON option value that starts like inline JSON names a file where one exists, which the option reads first
(`json_file`, moved from `json_config` to `_config_fields`). `--watch` watches that file (`names_file`) in the watch
graph of a run and in the recovery of a failed plan; the resolver of the planned job is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Client and server generation disagree on the scope names a security requirement may list

1 participant