-
Notifications
You must be signed in to change notification settings - Fork 982
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
Cookie-based auth #1521
Merged
Merged
Cookie-based auth #1521
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
2fc0d9d
Add single lint command for convenience.
dokterbob 12cd519
Allow and document passing arbitrary options to Cypress.
dokterbob dc34f2f
Cleanup of auth module.
dokterbob 91f078e
Remove deprecated ruff rule.
dokterbob 452c456
Bump ruff and use consistent version in CI.
dokterbob 6bf4119
Backend implementation of cookie auth.
dokterbob bc966d9
Only redirect to `/login` once auth config is available.
dokterbob 818197e
Expose cookie auth config to frontend.
dokterbob d615d10
Refactor of frontend auth, implement cookie authentication.
dokterbob 5ec8f10
Improved API error handling in frontend.
dokterbob b5c5b60
Move onErrorRetry logic to useAPI(), prevents infinite recursion.
dokterbob 84e88ad
Cleanup, improvement and cookie auth tests in password_* tests.
dokterbob 4f8bc3f
Re-enable user validation for `get_file()`. Closes #1101.
dokterbob 6655a5b
fix: conflicts with sticky session PR
willydouhard 10339cb
fix: ruff formatting
willydouhard a71f2e0
fix: test
willydouhard 6d82140
fix: ruff
willydouhard f19e4dd
fix: test
willydouhard f9d2538
fix: test
willydouhard 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 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 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 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 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,124 @@ | ||
import os | ||
from typing import Literal, Optional, cast | ||
|
||
from fastapi import Request, Response | ||
from fastapi.exceptions import HTTPException | ||
from fastapi.security.base import SecurityBase | ||
from fastapi.security.utils import get_authorization_scheme_param | ||
from starlette.status import HTTP_401_UNAUTHORIZED | ||
|
||
""" Module level cookie settings. """ | ||
_cookie_samesite = cast( | ||
Literal["lax", "strict", "none"], | ||
os.environ.get("CHAINLIT_COOKIE_SAMESITE", "lax"), | ||
) | ||
|
||
assert ( | ||
_cookie_samesite | ||
in [ | ||
"lax", | ||
"strict", | ||
"none", | ||
] | ||
), "Invalid value for CHAINLIT_COOKIE_SAMESITE. Must be one of 'lax', 'strict' or 'none'." | ||
_cookie_secure = _cookie_samesite == "none" | ||
|
||
_auth_cookie_lifetime = 60 * 60 # 1 hour | ||
_state_cookie_lifetime = 3 * 60 # 3m | ||
_auth_cookie_name = "access_token" | ||
_state_cookie_name = "oauth_state" | ||
|
||
|
||
class OAuth2PasswordBearerWithCookie(SecurityBase): | ||
""" | ||
OAuth2 password flow with cookie support with fallback to bearer token. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
tokenUrl: str, | ||
scheme_name: Optional[str] = None, | ||
auto_error: bool = True, | ||
): | ||
self.tokenUrl = tokenUrl | ||
self.scheme_name = scheme_name or self.__class__.__name__ | ||
self.auto_error = auto_error | ||
|
||
async def __call__(self, request: Request) -> Optional[str]: | ||
# First try to get the token from the cookie | ||
token = request.cookies.get(_auth_cookie_name) | ||
|
||
# If no cookie, try the Authorization header as fallback | ||
if not token: | ||
# TODO: Only bother to check if cookie auth is explicitly disabled. | ||
authorization = request.headers.get("Authorization") | ||
if authorization: | ||
scheme, token = get_authorization_scheme_param(authorization) | ||
if scheme.lower() != "bearer": | ||
if self.auto_error: | ||
raise HTTPException( | ||
status_code=HTTP_401_UNAUTHORIZED, | ||
detail="Invalid authentication credentials", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
else: | ||
return None | ||
else: | ||
if self.auto_error: | ||
raise HTTPException( | ||
status_code=HTTP_401_UNAUTHORIZED, | ||
detail="Not authenticated", | ||
headers={"WWW-Authenticate": "Bearer"}, | ||
) | ||
else: | ||
return None | ||
|
||
return token | ||
|
||
|
||
def set_auth_cookie(response: Response, token: str): | ||
""" | ||
Helper function to set the authentication cookie with secure parameters | ||
""" | ||
|
||
response.set_cookie( | ||
key=_auth_cookie_name, | ||
value=token, | ||
httponly=True, | ||
secure=_cookie_secure, | ||
samesite=_cookie_samesite, | ||
max_age=_auth_cookie_lifetime, | ||
path="/", # Why is path set here and not below? | ||
) | ||
|
||
|
||
def clear_auth_cookie(response: Response): | ||
""" | ||
Helper function to clear the authentication cookie | ||
""" | ||
response.delete_cookie(key=_auth_cookie_name, path="/") | ||
|
||
|
||
def set_oauth_state_cookie(response: Response, token: str): | ||
response.set_cookie( | ||
_state_cookie_name, | ||
token, | ||
httponly=True, | ||
samesite=_cookie_samesite, | ||
secure=_cookie_secure, | ||
max_age=_state_cookie_lifetime, | ||
) | ||
|
||
|
||
def validate_oauth_state_cookie(request: Request, state: str): | ||
"""Check the state from the oauth provider against the browser cookie.""" | ||
|
||
oauth_state = request.cookies.get(_state_cookie_name) | ||
|
||
if oauth_state != state: | ||
raise Exception("oauth state does not correspond") | ||
|
||
|
||
def clear_oauth_state_cookie(response: Response): | ||
"""Oauth complete, delete state token.""" | ||
response.delete_cookie(_state_cookie_name) # Do we set path here? |
This file contains 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,37 @@ | ||
import datetime | ||
import os | ||
from typing import Any, Dict, Optional | ||
|
||
import jwt as pyjwt | ||
|
||
from chainlit.config import config | ||
from chainlit.user import User | ||
|
||
|
||
def get_jwt_secret() -> Optional[str]: | ||
return os.environ.get("CHAINLIT_AUTH_SECRET") | ||
|
||
|
||
def create_jwt(data: User) -> str: | ||
to_encode: Dict[str, Any] = data.to_dict() | ||
to_encode.update( | ||
{ | ||
"exp": datetime.datetime.utcnow() | ||
+ datetime.timedelta(seconds=config.project.user_session_timeout), | ||
} | ||
) | ||
secret = get_jwt_secret() | ||
assert secret | ||
encoded_jwt = pyjwt.encode(to_encode, secret, algorithm="HS256") | ||
return encoded_jwt | ||
|
||
|
||
def decode_jwt(token: str) -> User: | ||
dict = pyjwt.decode( | ||
token, | ||
get_jwt_secret(), | ||
algorithms=["HS256"], | ||
options={"verify_signature": True}, | ||
) | ||
del dict["exp"] | ||
return User(**dict) |
This file contains 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 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.
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.
are we leaving this todo?