You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Judge the scopes of a security requirement alike for the client and the server - #6016
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.
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.
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.
Added render cases and generated snapshots for security-roles and security-roles-30. The generated routes include API-key, bearer, and OAuth security requirements.
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: 5
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title clearly describes the main change: applying consistent security-scope validation to client and server generation.
Linked Issues check
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
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
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.
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
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.
⚠️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.
…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
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
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes: #5849
Summary by CodeRabbit