-
Notifications
You must be signed in to change notification settings - Fork 3
feat(spp_oauth): prepare spp_oauth for stable status with RS256 bridge module #114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gonzalesedwin1123
wants to merge
9
commits into
19.0
Choose a base branch
from
fix/spp-oauth-stable-prep
base: 19.0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
371aee6
fix(spp_oauth): fix placeholder config defaults and improve test cove…
gonzalesedwin1123 c95f9d0
feat(spp_api_v2_oauth): add RS256 JWT bridge module for API V2
gonzalesedwin1123 de347d3
refactor(spp_oauth,spp_api_v2_oauth): address staff engineer review f…
gonzalesedwin1123 dd735c8
fix(spp_api_v2_oauth): reword log messages to avoid semgrep credentia…
gonzalesedwin1123 05670eb
feat(spp_api_v2_oauth): dispatch RS256 tokens by iss to support exter…
kneckinator d7abecd
Merge branch '19.0' into fix/spp-oauth-stable-prep
kneckinator 41d6eb2
chore(spp_oauth): bump 19.0.2.0.0 → 19.0.2.1.0 + HISTORY entry
kneckinator 79d0920
fix(spp_api_v2_oauth): disable all claim checks on iss-routing decode
kneckinator 5e34973
feat(spp_api_v2_oauth): harden for Production/Stable promotion
kneckinator File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Large diffs are not rendered by default.
Oops, something went wrong.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| from . import models |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # pylint: disable=pointless-statement | ||
| { | ||
| "name": "OpenSPP API V2: OAuth RS256 Bridge", | ||
| "summary": "Bridges spp_api_v2 and spp_oauth to enable RS256 JWT authentication for the API.", | ||
| "category": "OpenSPP/Integration", | ||
| "version": "19.0.2.0.0", | ||
| "author": "OpenSPP.org", | ||
| "development_status": "Production/Stable", | ||
| "maintainers": ["jeremi", "gonzalesedwin1123"], | ||
| "external_dependencies": {"python": ["pyjwt>=2.4.0", "cryptography"]}, | ||
| "website": "https://github.com/OpenSPP/OpenSPP2", | ||
| "license": "LGPL-3", | ||
| "depends": [ | ||
| "spp_api_v2", | ||
| "spp_oauth", | ||
| ], | ||
| "data": [ | ||
| "security/ir.model.access.csv", | ||
| "views/oauth_issuer_views.xml", | ||
| "views/api_client_views.xml", | ||
| ], | ||
| "application": False, | ||
| "auto_install": ["spp_api_v2", "spp_oauth"], | ||
| "installable": True, | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| # Part of OpenSPP. See LICENSE file for full copyright and licensing details. | ||
| """Shared constants for the OAuth RS256 bridge module. | ||
|
|
||
| These must match the values used by spp_api_v2 in auth.py and oauth.py. | ||
| """ | ||
|
|
||
| JWT_AUDIENCE = "openspp" | ||
| JWT_ISSUER = "openspp-api-v2" | ||
|
|
||
| # Allowed clock skew (seconds) for RS256 verification. Absorbs normal NTP drift | ||
| # between OpenSPP and external IdPs. Applied to internal RS256 verification too | ||
| # for symmetry; harmless there since the issuer and verifier share a clock. | ||
| JWT_CLOCK_SKEW_LEEWAY_SECONDS = 30 |
Empty file.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,259 @@ | ||
| # Part of OpenSPP. See LICENSE file for full copyright and licensing details. | ||
| """RS256-aware authentication middleware for API V2. | ||
|
|
||
| Replaces get_authenticated_client via FastAPI dependency override. | ||
| Routes verification based on the JWT header `alg` and (for RS256) the `iss` | ||
| claim: | ||
|
|
||
| alg == HS256 -> delegated to spp_api_v2 (unchanged) | ||
| alg == RS256 -> iss == JWT_ISSUER -> spp_oauth public key | ||
| -> iss matches spp.oauth.issuer -> static PEM or JWKS for that record | ||
| -> otherwise -> 401 | ||
| other -> 401 | ||
| """ | ||
|
|
||
| import logging | ||
| from typing import Annotated | ||
|
|
||
| import jwt | ||
| from jwt.exceptions import PyJWKClientError | ||
|
|
||
| from odoo.api import Environment | ||
|
|
||
| from odoo.addons.fastapi.dependencies import odoo_env | ||
| from odoo.addons.spp_api_v2.middleware.auth import _validate_jwt_token | ||
| from odoo.addons.spp_oauth.tools import OpenSPPOAuthJWTException, get_public_key | ||
|
|
||
| from fastapi import Depends, HTTPException, status | ||
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | ||
|
|
||
| from ..constants import JWT_AUDIENCE, JWT_CLOCK_SKEW_LEEWAY_SECONDS, JWT_ISSUER | ||
| from ..tools.jwks_cache import get_jwks_client | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
| # Must match the original security object's configuration | ||
| security = HTTPBearer(auto_error=False) | ||
|
|
||
|
|
||
| def get_authenticated_client_rs256( | ||
| credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)], | ||
| env: Annotated[Environment, Depends(odoo_env)], | ||
| ): | ||
| """Validate JWT token (RS256 or HS256) and return authenticated API client. | ||
|
|
||
| This function replaces spp_api_v2's get_authenticated_client via | ||
| FastAPI dependency_overrides. It reads the JWT header's `alg` field | ||
| to route to the correct verification path; for RS256 it additionally | ||
| routes by the `iss` claim to support multiple trusted issuers. | ||
| """ | ||
| if not credentials: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Missing Authorization header", | ||
| headers={"WWW-Authenticate": "Bearer"}, | ||
| ) | ||
|
|
||
| token = credentials.credentials | ||
|
|
||
| try: | ||
| try: | ||
| header = jwt.get_unverified_header(token) | ||
| except jwt.exceptions.DecodeError as e: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token", | ||
| ) from e | ||
|
|
||
| alg = header.get("alg", "") | ||
|
|
||
| if alg == "RS256": | ||
| payload, issuer_rec = _validate_rs256_token_with_issuer(env, token) | ||
| elif alg == "HS256": | ||
| payload = _validate_jwt_token(env, token) | ||
| issuer_rec = None | ||
| else: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail=f"Unsupported token algorithm: {alg}", | ||
| ) | ||
|
|
||
| # Determine which claim holds the API client identifier. | ||
| claim_name = issuer_rec.client_claim if issuer_rec else "client_id" | ||
| client_id = payload.get(claim_name) | ||
| if not client_id: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail=f"Invalid token: missing {claim_name}", | ||
| ) | ||
|
|
||
| # SECURITY: Scope the client lookup by the resolved issuer record. | ||
| # Internal-path tokens (HS256 + internal RS256) only match clients with no | ||
| # oauth_issuer_id. External-issuer tokens only match clients explicitly | ||
| # linked to that issuer record. Without this, an external IdP that emits | ||
| # a claim value colliding with an internal client_id would authenticate | ||
| # as the internal client. | ||
| domain = [ | ||
| ("client_id", "=", client_id), | ||
| ("active", "=", True), | ||
| ] | ||
| if issuer_rec: | ||
| domain.append(("oauth_issuer_id", "=", issuer_rec.id)) | ||
| else: | ||
| domain.append(("oauth_issuer_id", "=", False)) | ||
|
|
||
| api_client = ( | ||
| env["spp.api.client"] # nosemgrep: odoo-sudo-without-context | ||
| .sudo() | ||
| .search(domain, limit=1) | ||
| ) | ||
|
|
||
| if not api_client: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Client not found or inactive", | ||
| ) | ||
|
|
||
| return api_client | ||
|
|
||
| except HTTPException: | ||
| raise | ||
| except Exception as e: | ||
| _logger.exception("Authentication error") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Authentication failed", | ||
| ) from e | ||
|
|
||
|
|
||
| def _validate_rs256_token_with_issuer(env: Environment, token: str): | ||
| """Validate an RS256-signed JWT and return (payload, issuer_record_or_None). | ||
|
|
||
| Routing by `iss`: | ||
| - iss == JWT_ISSUER ("openspp-api-v2") -> internal path, key from spp_oauth | ||
| - iss matches an active spp.oauth.issuer -> external path, key per record | ||
| - iss missing or not matched -> 401 | ||
| """ | ||
| # SECURITY: We read the iss claim BEFORE signature verification solely to | ||
| # decide which key to verify with. ALL claim checks (signature, exp, nbf, | ||
| # iat, aud, iss) are disabled here and are run authoritatively by the | ||
| # verifying jwt.decode() inside _validate_internal_rs256 / | ||
| # _validate_external_rs256 below. Disabling them here also keeps this routing | ||
| # step from producing misleading errors (e.g. an expired token would bubble | ||
| # up as a generic "Authentication failed" instead of "Token expired"). | ||
| try: | ||
| unverified = jwt.decode( | ||
| token, | ||
| options={ | ||
| "verify_signature": False, | ||
| "verify_exp": False, | ||
| "verify_nbf": False, | ||
| "verify_iat": False, | ||
| "verify_aud": False, | ||
| "verify_iss": False, | ||
| }, | ||
| ) | ||
| except jwt.exceptions.DecodeError as e: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token", | ||
| ) from e | ||
|
|
||
| iss = unverified.get("iss") | ||
|
|
||
| if iss == JWT_ISSUER: | ||
| return _validate_internal_rs256(env, token), None | ||
|
|
||
| if not iss: | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token: missing iss claim", | ||
| ) | ||
|
|
||
| issuer_rec = ( | ||
| env["spp.oauth.issuer"] # nosemgrep: odoo-sudo-without-context | ||
| .sudo() | ||
| .search([("issuer", "=", iss), ("active", "=", True)], limit=1) | ||
| ) | ||
| if not issuer_rec: | ||
| _logger.warning("RS256 token from unknown issuer: %s", iss) | ||
|
kneckinator marked this conversation as resolved.
Dismissed
|
||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Untrusted issuer", | ||
| ) | ||
|
|
||
| return _validate_external_rs256(issuer_rec, token), issuer_rec | ||
|
|
||
|
|
||
| def _validate_internal_rs256(env: Environment, token: str) -> dict: | ||
| """Verify a token signed by the internal openspp-api-v2 issuer.""" | ||
| try: | ||
| public_key = get_public_key(env) | ||
| except OpenSPPOAuthJWTException as e: | ||
| _logger.warning("RS256 verification failed: %s", e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="RS256 authentication not available", | ||
| ) from e | ||
|
|
||
| try: | ||
| return jwt.decode( | ||
| token, | ||
| public_key, | ||
| algorithms=["RS256"], | ||
| audience=JWT_AUDIENCE, | ||
| issuer=JWT_ISSUER, | ||
| leeway=JWT_CLOCK_SKEW_LEEWAY_SECONDS, | ||
| ) | ||
| except jwt.ExpiredSignatureError as e: | ||
| _logger.warning("Expired RS256 JWT credential") | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Token expired", | ||
| ) from e | ||
| except jwt.InvalidTokenError as e: | ||
| _logger.warning("RS256 JWT verification failed: %s", e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token", | ||
| ) from e | ||
|
|
||
|
|
||
| def _validate_external_rs256(issuer_rec, token: str) -> dict: | ||
| """Verify a token signed by an externally-trusted issuer record.""" | ||
| algorithms = issuer_rec.get_allowed_algorithms() | ||
|
|
||
| try: | ||
| if issuer_rec.key_source == "jwks_uri": | ||
| try: | ||
| signing_key = get_jwks_client(issuer_rec).get_signing_key_from_jwt(token) | ||
| except PyJWKClientError as e: | ||
| _logger.warning("JWKS key resolution failed for issuer %s: %s", issuer_rec.issuer, e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token", | ||
| ) from e | ||
| key = signing_key.key | ||
| else: | ||
| key = issuer_rec.public_key | ||
|
|
||
| return jwt.decode( | ||
| token, | ||
| key, | ||
| algorithms=algorithms, | ||
| audience=issuer_rec.audience, | ||
| issuer=issuer_rec.issuer, | ||
| leeway=JWT_CLOCK_SKEW_LEEWAY_SECONDS, | ||
| ) | ||
| except jwt.ExpiredSignatureError as e: | ||
| _logger.warning("Expired RS256 JWT from issuer %s", issuer_rec.issuer) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Token expired", | ||
| ) from e | ||
| except jwt.InvalidTokenError as e: | ||
| _logger.warning("RS256 JWT verification failed for issuer %s: %s", issuer_rec.issuer, e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_401_UNAUTHORIZED, | ||
| detail="Invalid token", | ||
| ) from e | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from . import api_client | ||
| from . import fastapi_endpoint | ||
| from . import oauth_issuer |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # Part of OpenSPP. See LICENSE file for full copyright and licensing details. | ||
| """Extends `spp.api.client` with a Trusted-Issuer link. | ||
|
|
||
| When set, the client can ONLY be reached by RS256 tokens issued by the linked | ||
| `spp.oauth.issuer` record. When unset, the client is "internal" and can be | ||
| reached by HS256 tokens (`spp_api_v2` /oauth/token) or by internal RS256 tokens | ||
| (/oauth/token/rs256 with `iss == openspp-api-v2`). The bridge middleware | ||
| (`auth_rs256.get_authenticated_client_rs256`) enforces this routing. | ||
|
|
||
| SECURITY: Without this field, an external IdP that happened to emit a claim | ||
| value matching an internal client's `client_id` would silently authenticate | ||
| as that internal client. | ||
| """ | ||
|
|
||
| from odoo import fields, models | ||
|
|
||
|
|
||
| class SppApiClient(models.Model): | ||
| _inherit = "spp.api.client" | ||
|
|
||
| oauth_issuer_id = fields.Many2one( | ||
| "spp.oauth.issuer", | ||
| string="Trusted OAuth Issuer", | ||
| ondelete="restrict", | ||
| help=( | ||
| "External Identity Provider whose RS256 tokens may authenticate as this " | ||
| "client. When set, ONLY tokens from the linked issuer can resolve to this " | ||
| "client; the client is not reachable via internal HS256 or internal RS256 " | ||
| "auth. Leave empty for clients used with the built-in /oauth/token and " | ||
| "/oauth/token/rs256 endpoints." | ||
| ), | ||
| ) |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # Part of OpenSPP. See LICENSE file for full copyright and licensing details. | ||
| import logging | ||
|
|
||
| from odoo import models | ||
|
|
||
| from fastapi import APIRouter | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class SppApiV2OAuthEndpoint(models.Model): | ||
| """Extends FastAPI endpoint to add RS256 auth and token generation for API V2.""" | ||
|
|
||
| _inherit = "fastapi.endpoint" | ||
|
|
||
| def _get_app_dependencies_overrides(self): | ||
| overrides = super()._get_app_dependencies_overrides() | ||
| if self.app == "api_v2": | ||
| from odoo.addons.spp_api_v2.middleware.auth import ( | ||
| get_authenticated_client, | ||
| ) | ||
|
|
||
| from ..middleware.auth_rs256 import get_authenticated_client_rs256 | ||
|
|
||
| overrides[get_authenticated_client] = get_authenticated_client_rs256 | ||
| return overrides | ||
|
|
||
| def _get_fastapi_routers(self) -> list[APIRouter]: | ||
| routers = super()._get_fastapi_routers() | ||
| if self.app == "api_v2": | ||
| from ..routers.oauth_rs256 import oauth_rs256_router | ||
|
|
||
| routers.append(oauth_rs256_router) | ||
| return routers |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.