-
-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: de-dup JWT verification, DB lifecycle, and keypair generation #59
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
PenguinzTech
wants to merge
1
commit into
feature/manager-security-hardening
Choose a base branch
from
chore/dedup-reusable-code
base: feature/manager-security-hardening
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
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
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,81 @@ | ||
| """Shared Squawk JWT verification (single implementation for dns-server). | ||
|
|
||
| Centralizes the ES256/RS256 verification contract used by every dns-server | ||
| authorization path (selective_router, resilience): | ||
|
|
||
| - asymmetric algorithms only (ES256/RS256) — HS256/none rejected, blocking | ||
| the public-key-as-HMAC algorithm-confusion attack | ||
| - issuer + audience validated; exp/iat/tenant required | ||
| - fail closed: no public key configured, or missing/empty tenant → reject | ||
|
|
||
| Callers pass their configured public key and act on the returned payload; | ||
| authorization (zone visibility/team rules) stays with the caller. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from typing import Optional | ||
|
|
||
| import jwt as pyjwt | ||
| from jwt.exceptions import ( | ||
| DecodeError, | ||
| ExpiredSignatureError, | ||
| InvalidAudienceError, | ||
| InvalidIssuerError, | ||
| InvalidSignatureError, | ||
| InvalidTokenError, | ||
| MissingRequiredClaimError, | ||
| ) | ||
|
|
||
| from app.config import JWT_AUDIENCE, JWT_ISSUER | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def verify_squawk_jwt(token: str, public_key: Optional[str]) -> Optional[dict]: | ||
| """Verify a Squawk user JWT; return its payload or None (fail closed). | ||
|
|
||
| Args: | ||
| token: The presented bearer token. | ||
| public_key: PEM public key to verify with (caller's configured key). | ||
|
|
||
| Returns: | ||
| The verified payload dict, or None on any failure — unconfigured key, | ||
| bad signature/alg, expired, wrong iss/aud, missing/empty tenant. | ||
| """ | ||
| if not public_key: | ||
| logger.error("JWT_PUBLIC_KEY not configured; denying access") | ||
| return None | ||
|
|
||
| if not token: | ||
| return None | ||
|
|
||
| try: | ||
| payload = pyjwt.decode( | ||
| token, | ||
| public_key, | ||
| algorithms=['ES256', 'RS256'], | ||
| audience=JWT_AUDIENCE, | ||
| issuer=JWT_ISSUER, | ||
| options={'require': ['exp', 'iat', 'tenant']}, | ||
| ) | ||
| except (InvalidSignatureError, ExpiredSignatureError, DecodeError) as e: | ||
| logger.warning(f"Invalid JWT token: {e}") | ||
| return None | ||
| except (InvalidAudienceError, InvalidIssuerError, MissingRequiredClaimError) as e: | ||
| logger.warning(f"JWT claim validation failed: {e}") | ||
| return None | ||
| except InvalidTokenError as e: | ||
| logger.warning(f"Invalid token: {e}") | ||
| return None | ||
| except Exception as e: | ||
| logger.error(f"Token validation error: {e}") | ||
| return None | ||
|
|
||
| # Fail closed: tenant claim must be present and non-empty | ||
| if not payload.get('tenant'): | ||
| logger.debug("Access denied: token missing or empty tenant claim") | ||
| return None | ||
|
|
||
| return payload | ||
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nitpick: The
tokenparameter type could be relaxed toOptional[str]to match the usage.The function already treats a missing/empty token as valid input and returns early, so the signature should reflect that by using
token: Optional[str]. This will better match the actual contract and prevent unnecessary type-checker issues when callers pass an optional token.