Skip to content

✨ Implemented AuthManager + Policy Engine#856

Merged
yezz123 merged 14 commits into
yezz123:mainfrom
YuexiaW:feat/authmanager
May 20, 2026
Merged

✨ Implemented AuthManager + Policy Engine#856
yezz123 merged 14 commits into
yezz123:mainfrom
YuexiaW:feat/authmanager

Conversation

@YuexiaW
Copy link
Copy Markdown
Contributor

@YuexiaW YuexiaW commented May 19, 2026

Add login_type attribute to AuthXException and all its subclasses,
so that FastAPI exception handlers can differentiate errors by user type
(e.g., admin vs user token failures) and return type-specific responses.

Changes:

  • AuthXException.__init__ already accepted login_type parameter, but
    no raise site passed it; now all occurrences set it correctly.
  • Explicitly set login_type for RevokedTokenError, MissingTokenError,
    InsufficientScopeError in AuthX methods (_auth_required,
    websocket handler, scopes_required).
  • Set login_type for LoginTypeMismatchError and PolicyDeniedError
    in AuthManager (decode_token, _verify_login_type, authorize).
  • Wrap AuthX._decode_token() and verify_token() with an outer
    except AuthXException to inject self.login_type on exceptions from
    schema.py / token.py.
  • Make AuthManager inherit from _ErrorHandler so that it can directly
    use self.handle_errors(); add missing import Any in exceptions.py.

Why: This allows FastAPI users to write a global exception handler like:

@app.exception_handler(AuthXException)
async def authx_exception_handler(request, exc):
    # Different treatments are applied depending on the type.
    if exc.login_type == "admin":
        return JSONResponse({"error": "Admin auth failed"}, status=401)
    return JSONResponse({"error": "User auth failed"}, status=401)

yezz123 and others added 12 commits May 19, 2026 13:55
…ions

- Introduced `LoginTypeMismatchError` to handle token type mismatches with detailed initialization parameters.
- Added `PolicyDeniedError` for cases where access is denied due to policy evaluations.
- Created `PolicyEvaluationError` for handling errors during policy evaluations.
- Added new error messages for `LoginTypeMismatchError`, `PolicyDeniedError`, and `PolicyEvaluationError`.
- Updated the response content to include expected and actual types for login type mismatches.
- Registered new exception handlers for policy-related errors.
…andling in authentication methods for improved context management
- Introduced `PolicyEngine`, `PolicyRule`, `PolicyCondition`, and related classes to facilitate policy evaluation.
- Added methods for rule registration and evaluation, enhancing authorization capabilities.
- Included support for various policy operators and conditions to match actions and resources.
- Added `AuthManager` class to facilitate the management of multiple isolated AuthX contexts based on login types.
- Implemented methods for registering AuthX instances, creating access and refresh tokens, and handling errors within a FastAPI application.
- Enhanced token management with dependency factories for access and refresh tokens, ensuring better integration with FastAPI routes.
- Added `LoginTypeMismatchError`, `PolicyDeniedError`, and `PolicyEvaluationError` to the exceptions.
- Imported `AuthManager`, `PolicyCondition`, `PolicyContext`, `PolicyDecision`, `PolicyEngine`, and `PolicyRule` for enhanced policy management and authorization capabilities.
- Updated `__all__` to reflect the new additions for better module exports.
- Added tests for `LoginTypeMismatchError`, `PolicyDeniedError`, and `PolicyEvaluationError` to ensure proper error handling in the application.
- Introduced new test cases in `test_errors.py` to validate exception handlers for various error scenarios.
- Created `test_manager.py` and `test_policy.py` to cover the functionality of `AuthManager` and policy evaluation, including token creation and access control based on login types and policies.
- Introduced new documentation files for `AuthManager`, `PolicyEngine`, and related policy classes.
- Updated `exceptions.md` to include descriptions for `LoginTypeMismatchError`, `PolicyDeniedError`, and `PolicyEvaluationError`.
- Enhanced the `get-started` guide with examples on using `AuthManager` for managing multiple login types and implementing policy rules.
…erences

- Added links to the new documentation for `AuthManager` and policy management in the `get-started` section.
- Included references to `api/policy.md` and `api/manager.md` in the API documentation navigation.
- Added descriptions for the built-in `AuthManager` supporting multi-login-type applications.
- Included details on the pluggable policy engine for scopes, attributes, environment checks, and custom evaluators.
Add \`login_type\` attribute to \`AuthXException\` and all its subclasses,
so that FastAPI exception handlers can differentiate errors by user type
(e.g., admin vs user token failures) and return type-specific responses.

Changes:
- \`AuthXException.__init__\` already accepted \`login_type\` parameter, but
  no raise site passed it; now all occurrences set it correctly.
- Explicitly set \`login_type\` for \`RevokedTokenError\`, \`MissingTokenError\`,
  \`InsufficientScopeError\` in \`AuthX\` methods (\`_auth_required\`,
  websocket handler, \`scopes_required\`).
- Set \`login_type\` for \`LoginTypeMismatchError\` and \`PolicyDeniedError\`
  in \`AuthManager\` (\`decode_token\`, \`_verify_login_type\`, \`authorize\`).
- Wrap \`AuthX._decode_token()\` and \`verify_token()\` with an outer
  \`except AuthXException\` to inject \`self.login_type\` on exceptions from
  \`schema.py\` / \`token.py\`.
- Make \`AuthManager\` inherit from \`_ErrorHandler\` so that it can directly
  use \`self.handle_errors()\`; .

Why: This allows FastAPI users to write a global exception handler like:

\`\`\`python
@app.exception_handler(AuthXException)
async def authx_exception_handler(request, exc):
    # Different treatments are applied depending on the type.
    if exc.login_type == "admin":
        return JSONResponse({"error": "Admin auth failed"}, status=401)
    return JSONResponse({"error": "User auth failed"}, status=401)
\`\`\`
@vercel
Copy link
Copy Markdown

vercel Bot commented May 19, 2026

@YuexiaW is attempting to deploy a commit to the Yasser Tahiri's projects Team on Vercel.

A member of the Team first needs to authorize it.

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
Owner

@yezz123 yezz123 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@yezz123 yezz123 added enhancement New feature or request feature labels May 20, 2026
@yezz123 yezz123 changed the title feat: propagate login_type in all AuthXException raises ✨ Implemented AuthManager + Policy Engine May 20, 2026
@yezz123 yezz123 merged commit 053295b into yezz123:main May 20, 2026
9 of 18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants