Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions ctms/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
the client POSTs to /token again.
"""

import warnings
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from typing import Dict, Optional
from datetime import UTC, datetime, timedelta

import argon2
import jwt
Expand All @@ -24,7 +22,8 @@
pwd_context = argon2.PasswordHasher()


auth_info_context: ContextVar[dict] = ContextVar("auth_info_context", default={})
auth_info_context: ContextVar[dict] = ContextVar("auth_info_context")
auth_info_context.set({})


def verify_password(plain_password, hashed_password) -> bool:
Expand All @@ -42,11 +41,11 @@ def create_access_token(
data: dict,
expires_delta: timedelta,
secret_key: str,
now: Optional[datetime] = None,
now: datetime | None = None,
) -> str:
"""Create a JWT string to act as an OAuth2 access token."""
to_encode = data.copy()
expire = (now or datetime.now(timezone.utc)) + expires_delta
expire = (now or datetime.now(UTC)) + expires_delta
to_encode["exp"] = expire
encoded_jwt: str = jwt.encode(to_encode, secret_key, algorithm="HS256")
return encoded_jwt
Expand Down Expand Up @@ -97,8 +96,8 @@ def __init__(
self,
grant_type: str = Form(None, pattern="^(client_credentials|refresh_token)$"),
scope: str = Form(""),
client_id: Optional[str] = Form(None),
client_secret: Optional[str] = Form(None),
client_id: str | None = Form(None),
client_secret: str | None = Form(None),
):
self.grant_type = grant_type
self.scopes = scope.split()
Expand All @@ -121,18 +120,16 @@ class OAuth2ClientCredentials(OAuth2):
def __init__(
self,
tokenUrl: str,
scheme_name: Optional[str] = None,
scopes: Optional[Dict[str, str]] = None,
scheme_name: str | None = None,
scopes: dict[str, str] | None = None,
):
if not scopes:
scopes = {}
flows = OAuthFlowsModel(
clientCredentials={"tokenUrl": tokenUrl, "scopes": scopes}
)
flows = OAuthFlowsModel(clientCredentials={"tokenUrl": tokenUrl, "scopes": scopes})
super().__init__(flows=flows, scheme_name=scheme_name, auto_error=True)

async def __call__(self, request: Request) -> Optional[str]:
authorization: Optional[str] = request.headers.get("Authorization")
async def __call__(self, request: Request) -> str | None:
authorization: str | None = request.headers.get("Authorization")

# TODO: Try combining these lines after FastAPI 0.61.2 / mypy update
scheme_param = get_authorization_scheme_param(authorization)
Expand Down
24 changes: 6 additions & 18 deletions ctms/bin/client_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,7 @@ def print_new_credentials(
"""
)
else:
print(
"These credentials are currently disabled, and can not be used to get an OAuth2 access token."
)
print("These credentials are currently disabled, and can not be used to get an OAuth2 access token.")


def main(db, settings, test_args=None): # noqa: PLR0912
Expand All @@ -99,15 +97,9 @@ def main(db, settings, test_args=None): # noqa: PLR0912
parser = argparse.ArgumentParser(description="Create or update client credentials.")
parser.add_argument("name", help="short name of the client")
parser.add_argument("-e", "--email", help="contact email for the client")
parser.add_argument(
"--enable", action="store_true", help="enable a disabled client"
)
parser.add_argument(
"--disable", action="store_true", help="disable a new or enabled client"
)
parser.add_argument(
"--rotate-secret", action="store_true", help="generate a new secret key"
)
parser.add_argument("--enable", action="store_true", help="enable a disabled client")
parser.add_argument("--disable", action="store_true", help="disable a new or enabled client")
parser.add_argument("--rotate-secret", action="store_true", help="generate a new secret key")

args = parser.parse_args(args=test_args)
name = args.name
Expand All @@ -117,9 +109,7 @@ def main(db, settings, test_args=None): # noqa: PLR0912
rotate = args.rotate_secret

if not re.match(r"^[-_.a-zA-Z0-9]*$", name):
print(
f"name '{name}' should have only alphanumeric characters, '-', '_', or '.'"
)
print(f"name '{name}' should have only alphanumeric characters, '-', '_', or '.'")
return 1

if enable and disable:
Expand Down Expand Up @@ -168,9 +158,7 @@ def main(db, settings, test_args=None): # noqa: PLR0912
enabled = not disable
client_id, client_secret = create_client(db, client_id, email, enabled)
db.commit()
print_new_credentials(
client_id, client_secret, settings, sample_email=email, enabled=enabled
)
print_new_credentials(client_id, client_secret, settings, sample_email=email, enabled=enabled)
return 0


Expand Down
10 changes: 5 additions & 5 deletions ctms/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import Annotated, Optional
from typing import Annotated

from pydantic import AfterValidator, Field, PostgresDsn
from pydantic_settings import BaseSettings, SettingsConfigDict
Expand All @@ -13,7 +13,7 @@
PostgresDsnStr = Annotated[PostgresDsn, AfterValidator(str)]


@lru_cache()
@lru_cache
def get_version():
"""
Return contents of version.json.
Expand Down Expand Up @@ -49,11 +49,11 @@ class Settings(BaseSettings):
logging_level: LogLevel = LogLevel.INFO
sentry_debug: bool = False

fastapi_env: Optional[str] = Field(default=None, alias="FASTAPI_ENV")
sentry_dsn: Optional[AnyUrlString] = Field(default=None, alias="SENTRY_DSN")
fastapi_env: str | None = Field(default=None, alias="FASTAPI_ENV")
sentry_dsn: AnyUrlString | None = Field(default=None, alias="SENTRY_DSN")
host: str = Field(default="0.0.0.0", alias="HOST")
port: int = Field(default=8000, alias="PORT")

prometheus_pushgateway_url: Optional[str] = None
prometheus_pushgateway_url: str | None = None

model_config = SettingsConfigDict(env_prefix="ctms_")
Loading