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
1 change: 1 addition & 0 deletions src/authsome/auth/bundled_providers/notion.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"device_authorization_url": null,
"scopes": [],
"pkce": false,
"client_secret_handling": "basic",
"supports_device_code": false,
"supports_dcr": false
},
Expand Down
1 change: 1 addition & 0 deletions src/authsome/auth/bundled_providers/x.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"offline.access"
],
"pkce": true,
"client_secret_handling": "basic",
"supports_device_code": false,
"supports_dcr": false
},
Expand Down
31 changes: 20 additions & 11 deletions src/authsome/auth/flows/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,21 @@ async def revoke(
if not revocation_url:
return

def _do_revoke(token: str, token_type: str) -> None:
payload = {"token": token}
if client_id:
payload["client_id"] = client_id
if client_secret:
payload["client_secret"] = client_secret
use_basic = provider.oauth.client_secret_handling == "basic" if provider.oauth else False

def _do_revoke(token: str, token_type: str) -> None:
payload: dict[str, str] = {"token": token}
if not use_basic:
if client_id:
payload["client_id"] = client_id
if client_secret:
payload["client_secret"] = client_secret
try:
http_client.post(
revocation_url,
data=payload,
data=None if use_basic else payload,
json=payload if use_basic else None,
auth=(client_id or "", client_secret or "") if use_basic else None,
timeout=15,
)
except Exception as exc:
Expand Down Expand Up @@ -133,14 +137,19 @@ def refresh(
payload: dict[str, str] = {
"grant_type": "refresh_token",
"refresh_token": record.refresh_token,
"client_id": client_id,
}
if client_secret:
payload["client_secret"] = client_secret

use_basic = provider.oauth.client_secret_handling == "basic"
if not use_basic:
payload["client_id"] = client_id
if client_secret:
payload["client_secret"] = client_secret

resp = http_client.post(
provider.oauth.token_url,
data=payload,
data=None if use_basic else payload,
json=payload if use_basic else None,
auth=(client_id, client_secret or "") if use_basic else None,
headers={"Accept": "application/json"},
timeout=30,
)
Expand Down
23 changes: 16 additions & 7 deletions src/authsome/auth/flows/dcr_pkce.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,20 +232,29 @@ async def _exchange_code( # noqa: PLR0913
code_verifier: str,
) -> dict[str, Any]:
assert provider.oauth is not None
payload: dict[str, str] = {
body: dict[str, str] = {
"grant_type": "authorization_code",
"code": auth_code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"code_verifier": code_verifier,
}
if client_secret:
payload["client_secret"] = client_secret

use_basic = provider.oauth.client_secret_handling == "basic"
if not use_basic:
body["client_id"] = client_id
if client_secret:
body["client_secret"] = client_secret

resp = http_client.post(
provider.oauth.token_url,
data=None if use_basic else body,
json=body if use_basic else None,
auth=(client_id, client_secret or "") if use_basic else None,
headers={"Accept": "application/json"},
timeout=30,
)

try:
resp = http_client.post(
provider.oauth.token_url, data=payload, headers={"Accept": "application/json"}, timeout=30
)
resp.raise_for_status()
data = resp.json()
except http_client.RequestException as exc:
Expand Down
17 changes: 12 additions & 5 deletions src/authsome/auth/flows/device_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ async def poll_for_token( # noqa: PLR0912, PLR0913
deadline = time.monotonic() + effective_expires_in

use_json = provider.oauth.device_token_request == "json"
use_basic = provider.oauth.client_secret_handling == "basic"

while time.monotonic() < deadline:
await asyncio.sleep(poll_interval)
Expand All @@ -195,12 +196,18 @@ async def poll_for_token( # noqa: PLR0912, PLR0913
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device_code,
}
if client_id:
payload["client_id"] = client_id
if client_secret:
payload["client_secret"] = client_secret
if not use_basic:
if client_id:
payload["client_id"] = client_id
if client_secret:
payload["client_secret"] = client_secret
resp = requests.post(
provider.oauth.token_url, data=payload, headers={"Accept": "application/json"}, timeout=30
provider.oauth.token_url,
data=None if use_basic else payload,
json=payload if use_basic else None,
auth=(client_id or "", client_secret or "") if use_basic else None,
headers={"Accept": "application/json"},
timeout=30,
)
except requests.RequestException as exc:
logger.warning("Token poll request failed: {}, retrying...", exc)
Expand Down
26 changes: 16 additions & 10 deletions src/authsome/auth/flows/pkce.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,23 +143,29 @@ async def _exchange_code( # noqa: PLR0913
code_verifier: str,
) -> dict[str, Any]:
assert provider.oauth is not None
payload: dict[str, str] = {
body: dict[str, str] = {
"grant_type": "authorization_code",
"code": auth_code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"code_verifier": code_verifier,
}
if client_secret:
payload["client_secret"] = client_secret

use_basic = provider.oauth.client_secret_handling == "basic"
if not use_basic:
body["client_id"] = client_id
if client_secret:
body["client_secret"] = client_secret

resp = http_client.post(
provider.oauth.token_url,
data=None if use_basic else body,
json=body if use_basic else None,
auth=(client_id, client_secret or "") if use_basic else None,
headers={"Accept": "application/json"},
timeout=30,
)

try:
resp = http_client.post(
provider.oauth.token_url,
data=payload,
headers={"Accept": "application/json"},
timeout=30,
)
resp.raise_for_status()
except http_client.RequestException as exc:
raise AuthenticationFailedError(f"Token exchange failed: {exc}", provider=provider.name) from exc
Expand Down
1 change: 1 addition & 0 deletions src/authsome/auth/models/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class OAuthConfig(BaseModel):
device_authorization_url: str | None = None
#: ``json`` = poll token URL with ``POST`` JSON body ``{"device_code": "..."}`` (e.g. Postiz CLI auth).
device_token_request: Literal["oauth2_form", "json"] = "oauth2_form"
client_secret_handling: Literal["post", "basic"] = "post"
scopes: list[str] = Field(default_factory=list)
pkce: bool = True
supports_device_code: bool = False
Expand Down
28 changes: 24 additions & 4 deletions src/authsome/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,34 @@ def required_inputs( # noqa: PLR0913

if flow_type == FlowType.PKCE and (provider_config_only or not flow_client_id):
fields.append(InputField(name="client_id", label="Client ID", secret=False, default=flow_client_id or ""))
fields.append(InputField(name="client_secret", label="Client Secret", secret=True, default=""))
fields.append(
InputField(
name="client_secret",
label="Client Secret",
secret=True,
default=client_record.client_secret if provider_config_only and client_record else "",
)
)
elif flow_type == FlowType.DEVICE_CODE and (provider_config_only or not flow_client_id):
fields.append(InputField(name="client_id", label="Client ID", secret=False, default=flow_client_id or ""))
fields.append(InputField(name="client_secret", label="Client Secret (Optional)", secret=True, default=""))
fields.append(
InputField(
name="client_secret",
label="Client Secret (Optional)",
secret=True,
default=client_record.client_secret if provider_config_only and client_record else "",
)
)

needs_scopes = flow_type in (FlowType.PKCE, FlowType.DEVICE_CODE, FlowType.DCR_PKCE)
if needs_scopes and scopes is None and persisted_scopes is None:
default_scopes = ",".join(provider.oauth.scopes) if provider.oauth and provider.oauth.scopes else ""
if needs_scopes and scopes is None and (provider_config_only or persisted_scopes is None):
default_scopes = ",".join(
persisted_scopes
if provider_config_only and persisted_scopes is not None
else provider.oauth.scopes
if provider.oauth and provider.oauth.scopes
else []
)
fields.append(InputField(name="scopes", label="Scopes (comma-separated)", secret=False, default=default_scopes))

if flow_type == FlowType.API_KEY:
Expand Down
27 changes: 26 additions & 1 deletion src/authsome/server/credential_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,21 @@ async def get_connection(
)
return record

async def list_connection_records(self, provider: str) -> list[ConnectionRecord]:
"""Return stored connection records for a provider in this service's vault."""
keys = await self._credentials.list_connection_keys()
records: list[ConnectionRecord] = []
for key in keys:
parts = parse_store_key(key)
if parts.record_type != "connection" or not parts.provider or not parts.connection:
continue
if parts.provider != provider:
continue
record = await self._credentials.get_connection(parts.provider, parts.connection)
if record is not None:
records.append(record)
return records

async def resolve_connection_name(self, provider: str, connection: str | None = None) -> str:
"""Resolve an optional connection name to the provider default."""
if connection:
Expand Down Expand Up @@ -354,7 +369,17 @@ async def get_required_inputs(
client_record=client_record,
scopes=scopes,
base_url=base_url,
provider_config_only=bool(session.payload.get("provider_config_only")),
)

async def get_provider_configuration_inputs(self, provider: str) -> list[InputField]:
"""Return provider-level configuration fields for admin management UI."""
definition = await self.get_provider(provider)
client_record = await self._credentials.get_provider_client(provider)
return required_inputs(
provider=definition,
flow_type=definition.flow,
client_record=client_record,
provider_config_only=True,
)

async def save_inputs(self, session: AuthSession, inputs: dict[str, str]) -> None:
Expand Down
10 changes: 9 additions & 1 deletion src/authsome/server/routes/_deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,22 @@ async def get_auth_service(
return _build_service(request, resolved)


async def require_auth_service(
async def require_auth_service( # noqa: PLR0913
request: Request,
*,
identity: str | None = None,
principal_id: str | None = None,
acting_auth: CredentialService | None = None,
require_admin_for_other_principal: bool = False,
status_code: int = 404,
detail: str = "Authentication context not found",
) -> CredentialService:
if acting_auth is not None and principal_id is not None:
if principal_id == acting_auth.principal_id:
return acting_auth
if require_admin_for_other_principal and acting_auth.principal_role != PrincipalRole.ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin role required")

auth = await get_auth_service(request, identity=identity, principal_id=principal_id)
if auth is None:
raise HTTPException(status_code=status_code, detail=detail)
Expand Down
18 changes: 1 addition & 17 deletions src/authsome/server/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,6 @@ async def get_session_input(
callback_url = None
if definition.auth_type == AuthType.OAUTH2:
callback_url = build_callback_url(server_base_url)
warning_message = None
if session.payload.get("provider_config_only") and session.payload.get("existing_provider_client"):
warning_message = "Changing these credentials will revoke existing connections for this provider."

return {
"session_id": session.session_id,
Expand All @@ -249,7 +246,7 @@ async def get_session_input(
"docs_url": definition.docs_url,
"fields": fields,
"callback_url": callback_url,
"warning": warning_message,
"warning": None,
}


Expand Down Expand Up @@ -365,19 +362,6 @@ async def _submit_session_input( # noqa: PLR0911
form = await request.form()
inputs = {key: str(value) for key, value in form.items()}

if session.payload.get("provider_config_only"):
all_vaults = await request.app.state.store.vaults.list_all()
vault_ids = [vault.vault_id for vault in all_vaults] or ([auth.vault_id] if auth.vault_id else [])
await auth.update_provider_configuration(session.provider, inputs, vault_ids=vault_ids)
session.state = AuthSessionStatus.COMPLETED
session.status_message = "Provider configuration updated"
await sessions.save(session)
if return_url := session.payload.get("return_url"):
return RedirectResponse(str(return_url), status_code=status.HTTP_303_SEE_OTHER)
return RedirectResponse(
build_auth_success_url(server_base_url, session.session_id), status_code=status.HTTP_303_SEE_OTHER
)

await auth.save_inputs(session, inputs)

flow = FlowType(session.flow_type)
Expand Down
Loading
Loading