Skip to content

feat(openapi): support multiple security schemes, scopes, and components.securitySchemes - #219

Merged
Kilerd merged 2 commits into
mainfrom
feat/openapi-security-schemes
Dec 3, 2026
Merged

Kilerd merged 2 commits into
mainfrom
feat/openapi-security-schemes

Conversation

@Kilerd

@Kilerd Kilerd commented Dec 3, 2026 •

Copy link
Copy Markdown
Owner

Motivation

#[api(security = "...")] previously only allowed a single security scheme name with empty scopes, and Gotcha offered no builder API to declare components.securitySchemes or 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:

  • Declaring OR alternatives, compound AND requirements (all(...)), per-scheme scopes, explicit public overrides (none → []), and optional anonymous access (optional → {}) on #[api].
  • Declaring reusable components.securitySchemes on Gotcha, GotchaRouter, and GotchaApp via SecuritySchemeBuilder or raw oas::SecurityScheme.
  • Validating security scheme definitions and verifying that referenced schemes exist in 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):

  1. Applications using #[api(security = "...")] without declaring the scheme in components.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 from components.securitySchemes fails assembly/fallible export with an error (when OpenAPI endpoints are enabled, when no .openapi(..) transforms are registered, or on export) and panics in into_openapi() / openapi_document().
  2. Compile-time scheme name validation: #[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.
  3. Operable::security field type changed from Option<&'static str> to Option<&'static [SecurityAlternative]> (gotcha::openapi::SecurityAlternative, containing &'static [OperationSecurity]). Both OperationSecurity and SecurityAlternative are #[non_exhaustive] and constructed with const fn constructors (OperationSecurity::scheme, OperationSecurity::new, SecurityAlternative::all, SecurityAlternative::OPTIONAL). Callers constructing Operable { .. } struct literals manually must update the security field.
  4. Applications declaring schemes inside .openapi(..) transforms (including OAuth2 clientCredentials / password under oas 0.3): Transform-declared schemes keep working without blocking startup — shape issues (such as oas 0.3 clientCredentials/password) log a tracing::warn! instead of failing, and disabled docs never invoke .openapi(..) transforms (logging a tracing::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.md and MIGRATION.md:

  • Breaking API or behavioral changes bump the 0.x minor version (0.2 → 0.3, 0.3 → 0.4, 0.4 → 0.5), documented under ### Breaking in CHANGELOG.md with a migration section in MIGRATION.md.
  • Patch releases (0.5.1, 0.5.2, 0.5.3) carry only backward-compatible additions and fixes.
  • Since 0.5.2, gotcha, gotcha_core, and gotcha_macro are published in lockstep with exact =x.y.z inter-crate dependencies.

Shipping this PR corresponds to a 0.5.3 → 0.6.0 minor release across all three crates together. Crate versions are intentionally unchanged in this PR.

Design and Tradeoffs

Public API

  1. #[api(security ...)] syntax

    • Unset (omitted): Operable::security = None → omits security on the operation so it inherits top-level OpenAPIV3.security.
    • Backward-compatible shorthand: #[api(security = "bearerAuth")] → [{"bearerAuth": []}].
    • Explicit public override: #[api(security(none))] → "security": [] (overrides top-level security).
    • Optional anonymous access: #[api(security(optional))] → [{}], or combined with alternatives #[api(security("bearerAuth", optional))] → [{"bearerAuth": []}, {}].
    • Multi-scheme OR list with optional scopes and compound AND groups:
      #[api(security(
          "bearerAuth",
          "oauth2" = ["read:items", "write:items"],
          all("bearerAuth", "apiKey"),
          optional
      ))]
    • Using string literals for scheme names supports valid OpenAPI keys containing - or . (e.g. "bearer-auth", "v1.api_key") and never collides with the unquoted all, optional, or none keywords.
  2. components.securitySchemes declaration

    • Added SecuritySchemeBuilder (http_bearer, http_basic, http, api_key_header, api_key_cookie, api_key_query, oauth2, open_id_connect, .bearer_format(..), .description(..), into_inner(), plus From conversions with oas::SecurityScheme), re-exported from gotcha::openapi, gotcha, and gotcha::prelude. Named SecuritySchemeBuilder to avoid colliding with gotcha::oas::SecurityScheme when both gotcha::prelude::* and gotcha::oas::* are imported.
    • Added .security_scheme(name, scheme) on Gotcha and GotchaRouter (accepting impl Into<oas::SecurityScheme>), plus default method GotchaApp::security_schemes().
    • nest and merge inherit child .security_scheme(..) declarations with the parent winning on key collisions (emitting a tracing::warn! if the child declared a different definition under the same key). On GotchaApp, application-level security_schemes() wins over router-level .security_scheme(..) inside routes().
    • components is emitted even when an app declares security schemes and has no component schemas.
  3. Fallible export

    • Added Gotcha::try_into_openapi(), GotchaRouter::try_into_openapi(), and GotchaApp::try_openapi_document() returning GotchaResult<OpenAPIV3>.

Key Tradeoffs

  1. Compile-time syntax validation vs. assembly/startup reference validation

    • Compile-time (gotcha_macro): Rejects malformed syntax, empty security() / all(), invalid scheme name characters, empty/duplicate scopes, duplicate scheme keys within all(...), mixing none with other items, unknown keywords, duplicate security attributes, and order-independent duplicate requirements (all("a", "b") vs all("b", "a"), ["r", "w"] vs ["w", "r"], duplicate optional).
    • Assembly / startup time (gotcha):
      • Builder-declared .security_scheme(..) entries are always strictly validated against OpenAPI 3.1/3.2 constraints (including rejecting OAuth2 clientCredentials/password under oas 0.3).
      • When documentation endpoints are enabled (or exporting via try_into_openapi / into_openapi), all operation and top-level security references must exist in the final components.securitySchemes; schemes added or modified in .openapi(..) transforms satisfy presence checks and log a tracing::warn! on shape issues instead of blocking startup so 0.5 applications keep working.
      • When documentation endpoints are disabled, .openapi(..) transforms are unconditionally never run: missing schemes fail startup immediately if no transforms are registered, and log a tracing::warn! (suggesting .security_scheme(..)) if transforms are present.
  2. Operable::security representation (Option<&'static [SecurityAlternative]>) and 1.0 extensibility

    • Captures the complete OpenAPI Operation.security model (None = inherit, Some(&[]) = [], Some(&[SecurityAlternative::OPTIONAL]) = [{}], OR of AND requirements with scopes) in one const-constructible field.
    • OperationSecurity and SecurityAlternative are #[non_exhaustive], and #[api] emits const fn constructor calls (OperationSecurity::new, SecurityAlternative::all, SecurityAlternative::OPTIONAL) rather than struct literals so future fields can be added without breaking compatibility.
  3. OAuth2 flow validation on oas 0.3

    • oas 0.3's OauthFlow has a non-optional authorization_url: String that always serializes, which violates the official OpenAPI 3.1 and 3.2 schemas for clientCredentials and password flows ('authorizationUrl' was unexpected). Rather than silently emitting invalid documents from the new builder API (or coupling this PR to a breaking oas 0.4 upgrade), .security_scheme(..) strictly rejects clientCredentials, password, empty OauthFlows, implicit with tokenUrl, and authorizationCode without tokenUrl (and non-bearer HTTP bearerFormat), while transform-declared schemes emit a tracing::warn! to preserve 0.5 compatibility.

Testing

  • Macro unit tests in gotcha_macro/src/route.rs covering shorthand, OR, scopes, all(...), none, optional, and order-independent duplicate rejection.
  • Unit tests in gotcha/src/openapi/security.rs covering SecuritySchemeBuilder, SecurityAlternative, declared-scheme validation (including OAuth2 flow rules and bearerFormat), and document security validation.
  • Trybuild pass test (gotcha/tests/pass/openapi/security_schemes.rs) covering all syntax forms, macro_rules! fragment forwarding, manual static Operable built with const fn constructors, and gotcha::prelude::* + gotcha::oas::* import compatibility.
  • 16 trybuild compile-fail tests (gotcha/tests/fail/security/*.rs) covering all malformed, empty, invalid, and order-independent duplicate forms.
  • Integration tests in gotcha/tests/openapi_security.rs:
    • Full OpenAPI document snapshot (gotcha/tests/fixtures/openapi_security.json) validated against the official OpenAPI 3.2.0 JSON Schema (gotcha/tests/fixtures/openapi_3_2_schema.json) via jsonschema, plus a negative control proving raw oas 0.3 clientCredentials fails the official schema.
    • OpenAPI 3.1.0 + security integration test validating OpenApiVersion::V3_1 output (with post-transform $self stripping and all security forms preserved) against the official OpenAPI 3.1.0 JSON Schema (gotcha/tests/fixtures/openapi_3_1_schema.json).
    • Backward-compatible shorthand, .openapi(..) transform declarations, unconditional no-transform guarantee when docs are disabled, none ([]) and optional ([{}]) overriding global security, and components-only emission.
    • Startup (bind, into_router, GotchaApp::build_router) and export (try_into_openapi, into_openapi) failure checks for undeclared schemes (both with and without .with_openapi()).
    • Strict rejection of invalid builder schemes (clientCredentials, password, bad name) alongside non-blocking acceptance of transform-declared schemes (clientCredentials, apiKey in path).
    • nest/merge inheritance, parent precedence, and builder/trait/served /openapi.json byte-for-byte parity.
  • Warning log tests in gotcha/tests/openapi_security_logs.rs (single global subscriber) verifying WARN output for both transform-declared clientCredentials and disabled docs with registered transforms (while asserting 0 transform invocations).
  • Updated README.md (with compiled doctest), CHANGELOG.md (### Breaking + ### Added), and MIGRATION.md.

Known Limitations

  • OAuth2 clientCredentials and password flows are rejected by .security_scheme(..) under oas 0.3: Because oas 0.3.0's OauthFlow unconditionally serializes authorizationUrl, 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 a tracing::warn!). First-class support requires upgrading oas to 0.4+ (where authorization_url is optional).
  • Disabled docs with .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 a tracing::warn! instead of failing startup (and transform-only top-level spec.security is checked when docs are enabled or exported).
  • callbacks and webhooks are not traversed: validate_document_security checks paths operations (all 8 HTTP methods) and top-level spec.security; security requirements injected solely inside callbacks or webhooks by custom .openapi(..) transforms are not checked.
  • SecuritySchemeBuilder::bearer_format panics on non-HTTP-Bearer schemes: Calling .bearer_format(..) on a non-bearer builder (such as http_basic() or api_key_header(..)) panics immediately instead of returning a Result, and builder validation likewise rejects raw oas::SecurityScheme values setting bearerFormat on non-bearer HTTP schemes.

@Kilerd
Kilerd force-pushed the feat/openapi-security-schemes branch 2 times, most recently from 51491e1 to dede749 Compare December 3, 2026 12:18
@Kilerd
Kilerd force-pushed the feat/openapi-security-schemes branch from dede749 to 8159577 Compare December 3, 2026 12:27
@Kilerd
Kilerd merged commit 624764e into main Dec 3, 2026
13 checks passed
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.

1 participant