Repository navigation
feat(openapi): support multiple security schemes, scopes, and components.securitySchemes - #219
Merged
Merged
Conversation
Kilerd
force-pushed
the
feat/openapi-security-schemes
branch
2 times, most recently
from
December 3, 2026 12:18
51491e1 to
dede749
Compare
Kilerd
force-pushed
the
feat/openapi-security-schemes
branch
from
December 3, 2026 12:27
dede749 to
8159577
Compare
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Motivation
#[api(security = "...")]previously only allowed a single security scheme name with empty scopes, and Gotcha offered no builder API to declarecomponents.securitySchemesor catch typos where an operation references an undeclared scheme. Applications accepting multiple authentication mechanisms (for example, Bearer JWT or API key / session cookie), compound AND requirements, explicit public overrides ([]), optional authentication ([{}]), or OAuth2/OIDC scopes previously had to hand-edit the OpenAPI document in.openapi(..)callbacks.This PR adds first-class support for:
all(...)), per-scheme scopes, explicit public overrides (none→[]), and optional anonymous access (optional→{}) on#[api].components.securitySchemesonGotcha,GotchaRouter, andGotchaAppviaSecuritySchemeBuilderor rawoas::SecurityScheme.components.securitySchemes.Breaking Changes and Versioning Impact
This PR introduces breaking changes affecting four groups of existing applications (see
MIGRATION.md#unreleased-security-schemes-and-operable-security):#[api(security = "...")]without declaring the scheme incomponents.securitySchemes: OpenAPI security validation now runs on router assembly (run,bind,into_router,build_router) and export (try_into_openapi,try_openapi_document,into_openapi,openapi_document). Referencing a scheme missing fromcomponents.securitySchemesfails assembly/fallible export with an error (when OpenAPI endpoints are enabled, when no.openapi(..)transforms are registered, or on export) and panics ininto_openapi()/openapi_document().#[api(security ...)]now rejects scheme names outside OpenAPI's Components Object key alphabet (^[A-Za-z0-9._-]+$). Previously accepted names containing spaces or slashes now fail to compile.Operable::securityfield type changed fromOption<&'static str>toOption<&'static [SecurityAlternative]>(gotcha::openapi::SecurityAlternative, containing&'static [OperationSecurity]). BothOperationSecurityandSecurityAlternativeare#[non_exhaustive]and constructed withconst fnconstructors (OperationSecurity::scheme,OperationSecurity::new,SecurityAlternative::all,SecurityAlternative::OPTIONAL). Callers constructingOperable { .. }struct literals manually must update thesecurityfield..openapi(..)transforms (including OAuth2clientCredentials/passwordunderoas 0.3): Transform-declared schemes keep working without blocking startup — shape issues (such asoas 0.3clientCredentials/password) log atracing::warn!instead of failing, and disabled docs never invoke.openapi(..)transforms (logging atracing::warn!when an operation references a scheme missing from.security_scheme(..)). Move supported schemes to.security_scheme(..)for startup validation even when docs are disabled.0.x Versioning Convention (no version bump in this PR)
Per Gotcha's established 0.x convention in
CHANGELOG.mdandMIGRATION.md:0.2 → 0.3,0.3 → 0.4,0.4 → 0.5), documented under### BreakinginCHANGELOG.mdwith a migration section inMIGRATION.md.0.5.1,0.5.2,0.5.3) carry only backward-compatible additions and fixes.0.5.2,gotcha,gotcha_core, andgotcha_macroare published in lockstep with exact=x.y.zinter-crate dependencies.Shipping this PR corresponds to a
0.5.3 → 0.6.0minor release across all three crates together. Crate versions are intentionally unchanged in this PR.Design and Tradeoffs
Public API
#[api(security ...)]syntaxOperable::security = None→ omitssecurityon the operation so it inherits top-levelOpenAPIV3.security.#[api(security = "bearerAuth")]→[{"bearerAuth": []}].#[api(security(none))]→"security": [](overrides top-levelsecurity).#[api(security(optional))]→[{}], or combined with alternatives#[api(security("bearerAuth", optional))]→[{"bearerAuth": []}, {}].-or.(e.g."bearer-auth","v1.api_key") and never collides with the unquotedall,optional, ornonekeywords.components.securitySchemesdeclarationSecuritySchemeBuilder(http_bearer,http_basic,http,api_key_header,api_key_cookie,api_key_query,oauth2,open_id_connect,.bearer_format(..),.description(..),into_inner(), plusFromconversions withoas::SecurityScheme), re-exported fromgotcha::openapi,gotcha, andgotcha::prelude. NamedSecuritySchemeBuilderto avoid colliding withgotcha::oas::SecuritySchemewhen bothgotcha::prelude::*andgotcha::oas::*are imported..security_scheme(name, scheme)onGotchaandGotchaRouter(acceptingimpl Into<oas::SecurityScheme>), plus default methodGotchaApp::security_schemes().nestandmergeinherit child.security_scheme(..)declarations with the parent winning on key collisions (emitting atracing::warn!if the child declared a different definition under the same key). OnGotchaApp, application-levelsecurity_schemes()wins over router-level.security_scheme(..)insideroutes().componentsis emitted even when an app declares security schemes and has no component schemas.Fallible export
Gotcha::try_into_openapi(),GotchaRouter::try_into_openapi(), andGotchaApp::try_openapi_document()returningGotchaResult<OpenAPIV3>.Key Tradeoffs
Compile-time syntax validation vs. assembly/startup reference validation
gotcha_macro): Rejects malformed syntax, emptysecurity()/all(), invalid scheme name characters, empty/duplicate scopes, duplicate scheme keys withinall(...), mixingnonewith other items, unknown keywords, duplicatesecurityattributes, and order-independent duplicate requirements (all("a", "b")vsall("b", "a"),["r", "w"]vs["w", "r"], duplicateoptional).gotcha):.security_scheme(..)entries are always strictly validated against OpenAPI 3.1/3.2 constraints (including rejecting OAuth2clientCredentials/passwordunderoas 0.3).try_into_openapi/into_openapi), all operation and top-levelsecurityreferences must exist in the finalcomponents.securitySchemes; schemes added or modified in.openapi(..)transforms satisfy presence checks and log atracing::warn!on shape issues instead of blocking startup so 0.5 applications keep working..openapi(..)transforms are unconditionally never run: missing schemes fail startup immediately if no transforms are registered, and log atracing::warn!(suggesting.security_scheme(..)) if transforms are present.Operable::securityrepresentation (Option<&'static [SecurityAlternative]>) and 1.0 extensibilityOperation.securitymodel (None= inherit,Some(&[])=[],Some(&[SecurityAlternative::OPTIONAL])=[{}], OR of AND requirements with scopes) in oneconst-constructible field.OperationSecurityandSecurityAlternativeare#[non_exhaustive], and#[api]emitsconst fnconstructor calls (OperationSecurity::new,SecurityAlternative::all,SecurityAlternative::OPTIONAL) rather than struct literals so future fields can be added without breaking compatibility.OAuth2 flow validation on
oas 0.3oas 0.3'sOauthFlowhas a non-optionalauthorization_url: Stringthat always serializes, which violates the official OpenAPI 3.1 and 3.2 schemas forclientCredentialsandpasswordflows ('authorizationUrl' was unexpected). Rather than silently emitting invalid documents from the new builder API (or coupling this PR to a breakingoas 0.4upgrade),.security_scheme(..)strictly rejectsclientCredentials,password, emptyOauthFlows,implicitwithtokenUrl, andauthorizationCodewithouttokenUrl(and non-bearer HTTPbearerFormat), while transform-declared schemes emit atracing::warn!to preserve 0.5 compatibility.Testing
gotcha_macro/src/route.rscovering shorthand, OR, scopes,all(...),none,optional, and order-independent duplicate rejection.gotcha/src/openapi/security.rscoveringSecuritySchemeBuilder,SecurityAlternative, declared-scheme validation (including OAuth2 flow rules andbearerFormat), and document security validation.gotcha/tests/pass/openapi/security_schemes.rs) covering all syntax forms,macro_rules!fragment forwarding, manualstaticOperablebuilt withconst fnconstructors, andgotcha::prelude::*+gotcha::oas::*import compatibility.gotcha/tests/fail/security/*.rs) covering all malformed, empty, invalid, and order-independent duplicate forms.gotcha/tests/openapi_security.rs:gotcha/tests/fixtures/openapi_security.json) validated against the official OpenAPI 3.2.0 JSON Schema (gotcha/tests/fixtures/openapi_3_2_schema.json) viajsonschema, plus a negative control proving rawoas 0.3clientCredentialsfails the official schema.OpenApiVersion::V3_1output (with post-transform$selfstripping and all security forms preserved) against the official OpenAPI 3.1.0 JSON Schema (gotcha/tests/fixtures/openapi_3_1_schema.json)..openapi(..)transform declarations, unconditional no-transform guarantee when docs are disabled,none([]) andoptional([{}]) overriding global security, andcomponents-only emission.bind,into_router,GotchaApp::build_router) and export (try_into_openapi,into_openapi) failure checks for undeclared schemes (both with and without.with_openapi()).clientCredentials,password,bad name) alongside non-blocking acceptance of transform-declared schemes (clientCredentials,apiKeyinpath).nest/mergeinheritance, parent precedence, and builder/trait/served/openapi.jsonbyte-for-byte parity.gotcha/tests/openapi_security_logs.rs(single global subscriber) verifyingWARNoutput for both transform-declaredclientCredentialsand disabled docs with registered transforms (while asserting 0 transform invocations).README.md(with compiled doctest),CHANGELOG.md(### Breaking+### Added), andMIGRATION.md.Known Limitations
clientCredentialsandpasswordflows are rejected by.security_scheme(..)underoas 0.3: Becauseoas 0.3.0'sOauthFlowunconditionally serializesauthorizationUrl, those two flows cannot produce valid OpenAPI 3.1/3.2 documents and are rejected on the builder API (transform-declared schemes still work with atracing::warn!). First-class support requires upgradingoasto0.4+(whereauthorization_urlis optional)..openapi(..)transforms defer reference checks to warning: When OpenAPI endpoints are disabled and transforms are registered,.openapi(..)transforms are never run at startup, so operations referencing schemes missing from.security_scheme(..)log atracing::warn!instead of failing startup (and transform-only top-levelspec.securityis checked when docs are enabled or exported).callbacksandwebhooksare not traversed:validate_document_securitycheckspathsoperations (all 8 HTTP methods) and top-levelspec.security; security requirements injected solely insidecallbacksorwebhooksby custom.openapi(..)transforms are not checked.SecuritySchemeBuilder::bearer_formatpanics on non-HTTP-Bearer schemes: Calling.bearer_format(..)on a non-bearer builder (such ashttp_basic()orapi_key_header(..)) panics immediately instead of returning aResult, and builder validation likewise rejects rawoas::SecuritySchemevalues settingbearerFormaton non-bearer HTTP schemes.