feat(auth): 接入 Casdoor 登录并让前端持有本服务会话

管理台可以密码登录、按角色进入,并把 Watchman 会话 token 交给浏览器。HXOPS 真实跳转仍未联调。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-17 18:39:56 +08:00
1 parent 21338337a1
commit ab31d828d4
64 files changed
+4140 -339

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ from sqlalchemy import engine_from_config, pool
from watchman.core.config import get_settings
from watchman.models.base import Base
from watchman.models import AuditEvent, RunRecord # noqa: F401
from watchman.models import AuthSession, AuditEvent, RunRecord # noqa: F401
config = context.config
if config.config_file_name is not None:
@@ -0,0 +1,61 @@
"""Create tenant-scoped Watchman authentication sessions.
Revision ID: 20261117_0002
Revises: 20261117_0001
Create Date: 2026-11-17
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261117_0002"
down_revision: Union[str, None] = "20261117_0001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
TABLE_NAME = "auth_sessions"
def upgrade() -> None:
"""Create the session table without storing credentials or raw tokens."""
op.create_table(
TABLE_NAME,
sa.Column("token_hash", sa.String(length=64), primary_key=True),
sa.Column("subject", sa.String(length=255), nullable=False),
sa.Column("issuer", sa.String(length=512), nullable=False),
sa.Column("display_name", sa.String(length=255), nullable=False),
sa.Column(
"role_snapshot",
postgresql.JSONB(astext_type=sa.Text()),
server_default=sa.text("'[]'::jsonb"),
nullable=False,
),
sa.Column("role_checked_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
)
op.execute(f"ALTER TABLE {TABLE_NAME} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {TABLE_NAME} FORCE ROW LEVEL SECURITY")
op.execute(
f"""
CREATE POLICY tenant_isolation ON {TABLE_NAME}
FOR ALL
TO {APP_ROLE}
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
"""
)
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {TABLE_NAME} TO {APP_ROLE}")
def downgrade() -> None:
"""Remove the auth session RLS policy and table."""
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {TABLE_NAME}")
op.drop_table(TABLE_NAME)
@@ -0,0 +1,31 @@
"""Store the Casdoor login name used to refresh roles.
Revision ID: 20261117_0003
Revises: 20261117_0002
Create Date: 2026-11-17
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20261117_0003"
down_revision: Union[str, None] = "20261117_0002"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Add the non-secret login name required to reload Casdoor roles."""
op.add_column(
"auth_sessions",
sa.Column("login_name", sa.String(length=255), nullable=False, server_default=""),
)
def downgrade() -> None:
"""Remove the login name column."""
op.drop_column("auth_sessions", "login_name")
+1
View File
@@ -13,6 +13,7 @@ dependencies = [
"psycopg[binary]>=3.2,<4",
"celery>=5.4,<6",
"python-dotenv>=1.0,<2",
"pyjwt[crypto]>=2.10,<3",
]
[build-system]
+2 -1
View File
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from watchman.api.routes import health, platform
from watchman.api.routes import auth, health, platform
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
from watchman.core.errors import AppError, ValidationError
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
@@ -75,6 +75,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
)
app.add_middleware(RequestIdMiddleware)
app.include_router(health.router)
app.include_router(auth.router)
app.include_router(platform.router)
@app.exception_handler(AppError)
@@ -0,0 +1,148 @@
"""Password login, HXOPS entry, current-user, and logout endpoints.
These routes establish Watchman sessions. Platform writes are authorized separately.
Depends on injectable Casdoor and session-store ports plus the standard response envelope.
"""
from __future__ import annotations
from fastapi import APIRouter, Cookie, Depends, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from watchman.auth.casdoor import CasdoorPort, get_casdoor_port
from watchman.auth.hxops import HxopsAssertionLogin, get_hxops_login
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
SESSION_LIFETIME,
SessionStore,
get_session_store,
hash_cookie_token,
issue_cookie_token,
read_session_token,
utc_now,
)
from watchman.core.errors import UnauthorizedError
from watchman.core.response import success_body
router = APIRouter(prefix="/auth", tags=["auth"])
class PasswordLoginRequest(BaseModel):
"""Password-login input passed only to the injectable Casdoor port."""
username: str = Field(min_length=1)
password: str = Field(min_length=1)
class HxopsEntryRequest(BaseModel):
"""One short-lived HXOPS assertion. It is not stored."""
assertion: str = Field(min_length=1)
def _public_identity(row: object, *, access_token: str | None = None) -> dict[str, object]:
"""Map stored session data to the fields the browser is allowed to keep."""
data: dict[str, object] = {
"subject": row.subject, # type: ignore[attr-defined]
"display_name": row.display_name, # type: ignore[attr-defined]
"login_name": row.login_name, # type: ignore[attr-defined]
"roles": list(row.role_snapshot), # type: ignore[attr-defined]
}
if access_token is not None:
data["access_token"] = access_token
data["token_type"] = "Bearer"
data["expires_in"] = int(SESSION_LIFETIME.total_seconds())
return data
def _session_response(request: Request, row: object, token: str) -> JSONResponse:
"""Return the session token for the frontend and set the HttpOnly cookie."""
response = JSONResponse(
content=success_body(
_public_identity(row, access_token=token),
request_id=request.state.request_id,
)
)
response.set_cookie(
key=SESSION_COOKIE_NAME,
value=token,
httponly=True,
samesite="lax",
path="/",
)
return response
@router.post("/login")
def login(
request: Request,
body: PasswordLoginRequest,
casdoor: CasdoorPort = Depends(get_casdoor_port),
sessions: SessionStore = Depends(get_session_store),
) -> JSONResponse:
"""Verify submitted credentials, create a server-side session, and set its HttpOnly cookie."""
identity = casdoor.authenticate_password(username=body.username, password=body.password)
token = issue_cookie_token()
row = sessions.create(
token_hash=hash_cookie_token(token),
identity=identity,
now=utc_now(),
login_name=body.username,
)
return _session_response(request, row, token)
@router.post("/hxops-entry")
def hxops_entry(
request: Request,
body: HxopsEntryRequest,
entry: HxopsAssertionLogin = Depends(get_hxops_login),
sessions: SessionStore = Depends(get_session_store),
) -> JSONResponse:
"""Verify an HXOPS assertion and open the same kind of session as password login.
Roles are loaded by the entry service. The assertion body is not written to the session.
"""
identity, login_name = entry.authenticate(body.assertion)
token = issue_cookie_token()
row = sessions.create(
token_hash=hash_cookie_token(token),
identity=identity,
now=utc_now(),
login_name=login_name,
)
return _session_response(request, row, token)
@router.get("/me")
def current_user(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
) -> JSONResponse:
"""Return the current public identity only when a non-expired server session exists."""
token = read_session_token(request, session_token)
if token is None:
raise UnauthorizedError()
row = sessions.get(token_hash=hash_cookie_token(token), now=utc_now())
if row is None:
raise UnauthorizedError()
return JSONResponse(content=success_body(_public_identity(row), request_id=request.state.request_id))
@router.post("/logout")
def logout(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
) -> JSONResponse:
"""Invalidate this Watchman session and remove its browser cookie."""
token = read_session_token(request, session_token)
if token is not None:
sessions.invalidate(token_hash=hash_cookie_token(token))
response = JSONResponse(
content=success_body({"logged_out": True}, request_id=request.state.request_id)
)
response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
return response
@@ -12,6 +12,7 @@ from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from watchman.auth.principal import require_platform_writer
from watchman.core.db import get_db_session
from watchman.core.response import success_body
from watchman.services.platform_records import create_audit_event, create_run_record
@@ -34,6 +35,7 @@ class RunCreateRequest(BaseModel):
def post_audit_event(
request: Request,
body: AuditCreateRequest,
_: None = Depends(require_platform_writer),
session: Session = Depends(get_db_session),
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
) -> JSONResponse:
@@ -57,6 +59,7 @@ def post_audit_event(
def post_run_record(
request: Request,
body: RunCreateRequest,
_: None = Depends(require_platform_writer),
session: Session = Depends(get_db_session),
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
) -> JSONResponse:
@@ -0,0 +1,3 @@
"""Authentication primitives for verified Watchman identities.
Only local token verification belongs here; sessions and external identity calls do not.
Depends on watchman.core.errors for authentication failures."""
@@ -0,0 +1,48 @@
"""Role checks for the three Watchman permission nodes.
Decides enter, platform write, and object read from Casdoor role names.
Depends on semantic errors only; it does not call Casdoor or open a session.
"""
from __future__ import annotations
from watchman.core.errors import ForbiddenError
ENTER_NODE = "perm:app:emp:watchman.enter"
PLATFORM_WRITE_NODE = "perm:data:emp:watchman.platform.write"
OBJECT_READ_NODE = "perm:data:emp:watchman.object.read"
ROLE_ADMIN = "watchman-admin"
ROLE_OPERATOR = "watchman-operator"
ROLE_VIEWER = "watchman-viewer"
# GUARD: empty roles must never be treated as viewer. Do not add other names here.
ENTER_ROLES = frozenset({ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER})
def allows_enter(role_names: list[str]) -> bool:
"""Return whether these roles may open the shell.
Any of the three Watchman roles is enough. An empty or unknown list is denied,
and this function does not raise.
"""
return bool(ENTER_ROLES.intersection(role_names))
def require_platform_write(role_names: list[str]) -> None:
"""Allow a platform write only for watchman-admin.
Other roles, including viewer and operator, raise ForbiddenError with the
platform write permission node.
"""
if ROLE_ADMIN not in role_names:
raise ForbiddenError(permission_node=PLATFORM_WRITE_NODE)
def require_object_access(role_names: list[str], object_id: str) -> None:
"""Reject every object id until a later module grants row access.
M02 has no object grants, so admin and every other role are refused with
the object-read permission node. The id is not used as proof of access.
"""
del role_names, object_id
raise ForbiddenError(permission_node=OBJECT_READ_NODE)
@@ -0,0 +1,225 @@
"""Injectable Casdoor password-login port using OpenID Connect discovery."""
from __future__ import annotations
from dataclasses import dataclass
import json
from typing import Protocol
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from watchman.core.config import Settings, get_settings
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
@dataclass(frozen=True)
class CasdoorIdentity:
"""Verified identity returned by a Casdoor password-login adapter."""
subject: str
issuer: str
display_name: str
role_names: list[str]
class CasdoorPort(Protocol):
"""Authenticate credentials through Casdoor without exposing upstream tokens."""
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
"""Return a verified identity or raise a semantic authentication/service error."""
@dataclass(frozen=True)
class HttpResponse:
"""Minimal HTTP response used by the injectable Casdoor transport."""
status_code: int
body: bytes
class CasdoorHttpTransport(Protocol):
"""Perform one HTTP request for the Casdoor adapter."""
def request(
self,
*,
method: str,
url: str,
headers: dict[str, str],
data: bytes | None = None,
) -> HttpResponse:
"""Return a response or raise a network exception."""
class UrllibCasdoorHttpTransport:
"""Production transport with a bounded timeout and no response logging."""
def request(
self,
*,
method: str,
url: str,
headers: dict[str, str],
data: bytes | None = None,
) -> HttpResponse:
request = Request(url, data=data, headers=headers, method=method)
try:
with urlopen(request, timeout=8) as response:
return HttpResponse(status_code=response.status, body=response.read())
except HTTPError as error:
return HttpResponse(status_code=error.code, body=error.read())
class DefaultCasdoorPort:
"""Authenticate passwords through Casdoor's discovered OpenID Connect endpoints."""
def __init__(
self,
settings: Settings | None = None,
transport: CasdoorHttpTransport | None = None,
) -> None:
self._settings = settings or get_settings()
self._transport = transport or UrllibCasdoorHttpTransport()
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
"""Exchange credentials for a verified identity without retaining credentials or tokens."""
configured = (
self._settings.casdoor_endpoint
and self._settings.casdoor_client_id
and self._settings.casdoor_client_secret
)
# GUARD: never log password, client secret, or tokens.
if not configured:
raise ServiceUnavailableError("Casdoor login is unavailable")
try:
discovery = self._json_response(
self._transport.request(
method="GET",
url=f"{self._settings.casdoor_endpoint.rstrip('/')}/.well-known/openid-configuration",
headers={"Accept": "application/json"},
)
)
token_endpoint = self._required_endpoint(discovery, "token_endpoint")
userinfo_endpoint = self._required_endpoint(discovery, "userinfo_endpoint")
token_response = self._transport.request(
method="POST",
url=token_endpoint,
headers={
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
data=urlencode(
{
"grant_type": "password",
"username": username,
"password": password,
"client_id": self._settings.casdoor_client_id,
"client_secret": self._settings.casdoor_client_secret,
"scope": "openid profile email",
}
).encode("utf-8"),
)
except UnauthorizedError:
raise
except Exception as error:
raise ServiceUnavailableError("Casdoor login is unavailable") from error
token_body = self._decode_json(token_response.body)
if self._is_credential_rejection(token_response, token_body):
raise UnauthorizedError("Invalid username or password")
if token_response.status_code < 200 or token_response.status_code >= 300:
raise ServiceUnavailableError("Casdoor login is unavailable")
access_token = token_body.get("access_token")
if not isinstance(access_token, str) or not access_token:
raise ServiceUnavailableError("Casdoor login is unavailable")
try:
userinfo_response = self._transport.request(
method="GET",
url=userinfo_endpoint,
headers={
"Accept": "application/json",
"Authorization": f"Bearer {access_token}",
},
)
except Exception as error:
raise ServiceUnavailableError("Casdoor login is unavailable") from error
userinfo = self._decode_json(userinfo_response.body)
if userinfo_response.status_code in {400, 401}:
raise UnauthorizedError("Invalid username or password")
if userinfo_response.status_code < 200 or userinfo_response.status_code >= 300:
raise ServiceUnavailableError("Casdoor login is unavailable")
subject = userinfo.get("sub")
if not isinstance(subject, str) or not subject:
raise UnauthorizedError("Invalid username or password")
display_name = userinfo.get("name") or userinfo.get("preferred_username") or username
return CasdoorIdentity(
subject=subject,
issuer=self._settings.casdoor_issuer or self._settings.casdoor_endpoint,
display_name=display_name if isinstance(display_name, str) else username,
role_names=self._role_names(userinfo.get("roles")),
)
@staticmethod
def _json_response(response: HttpResponse) -> dict[str, object]:
"""Require a successful JSON discovery response."""
if response.status_code < 200 or response.status_code >= 300:
raise ServiceUnavailableError("Casdoor login is unavailable")
return DefaultCasdoorPort._decode_json(response.body)
@staticmethod
def _decode_json(body: bytes) -> dict[str, object]:
"""Decode a JSON object without including upstream response content in errors."""
try:
decoded = json.loads(body)
except (TypeError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise ServiceUnavailableError("Casdoor login is unavailable") from error
if not isinstance(decoded, dict):
raise ServiceUnavailableError("Casdoor login is unavailable")
return decoded
@staticmethod
def _required_endpoint(document: dict[str, object], key: str) -> str:
"""Read a non-empty endpoint URL from the discovery document."""
endpoint = document.get(key)
if not isinstance(endpoint, str) or not endpoint:
raise ServiceUnavailableError("Casdoor login is unavailable")
return endpoint
@staticmethod
def _is_credential_rejection(response: HttpResponse, payload: dict[str, object]) -> bool:
"""Recognize password-grant rejection without exposing upstream text."""
error = payload.get("error")
if error in {"unsupported_grant_type", "invalid_client", "server_error"}:
return False
if error == "invalid_grant" or response.status_code in {400, 401}:
return True
description = payload.get("error_description")
return (
error == "invalid_request"
and isinstance(description, str)
and any(term in description.lower() for term in ("user", "username", "password", "credential"))
)
@staticmethod
def _role_names(roles: object) -> list[str]:
"""Extract configured role names while ignoring unsupported role shapes."""
if not isinstance(roles, list):
return []
names: list[str] = []
for role in roles:
if isinstance(role, str):
names.append(role)
elif isinstance(role, dict) and isinstance(role.get("name"), str):
names.append(role["name"])
return names
def get_casdoor_port() -> CasdoorPort:
"""Provide the production port; tests override this dependency with a stand-in."""
return DefaultCasdoorPort()
@@ -0,0 +1,84 @@
"""Accept a short-lived HXOPS assertion and turn it into a Watchman identity.
Verifies the assertion, then loads roles from Casdoor. Assertion permission claims are ignored.
Depends on the RS256 verifier, settings, and a role directory.
"""
from __future__ import annotations
from fastapi import Depends
from watchman.auth.casdoor import CasdoorIdentity
from watchman.auth.principal import RoleDirectory, get_role_directory
from watchman.auth.token_verifier import verify_rs256_token
from watchman.core.config import Settings, get_settings
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
class HxopsAssertionLogin:
"""Create a Casdoor identity from one HXOPS SSO assertion."""
def __init__(self, settings: Settings, directory: RoleDirectory) -> None:
self._settings = settings
self._directory = directory
def authenticate(self, assertion: str) -> tuple[CasdoorIdentity, str]:
"""Return a Casdoor identity and login name, or refuse the assertion.
Missing HXOPS key material is unavailable. A bad signature, a missing
Casdoor reference, or a local user id used as that reference is unauthorized.
Roles come only from the directory. Directory failure does not create an identity.
"""
settings = self._settings
if not (settings.hxops_sso_issuer and settings.hxops_sso_audience and settings.hxops_sso_public_key):
raise ServiceUnavailableError("HXOPS entry is unavailable")
claims = verify_rs256_token(
assertion,
public_key=settings.hxops_sso_public_key,
issuer=settings.hxops_sso_issuer,
audience=settings.hxops_sso_audience,
)
subject, issuer = _casdoor_reference(claims, expected_issuer=settings.casdoor_issuer)
login_name = _login_name(claims)
# GUARD: never copy roles, permissions, or tokens from the assertion.
roles = self._directory.lookup_roles(login_name=login_name)
display_name = claims.get("name") or claims.get("preferred_username") or login_name
if not isinstance(display_name, str) or not display_name:
display_name = login_name
identity = CasdoorIdentity(
subject=subject,
issuer=issuer,
display_name=display_name,
role_names=list(roles),
)
return identity, login_name
def _casdoor_reference(claims: dict[str, object], *, expected_issuer: str) -> tuple[str, str]:
"""Read the explicit Casdoor subject. The HXOPS token subject is not that identity."""
if not expected_issuer:
raise ServiceUnavailableError("HXOPS entry is unavailable")
issuer = claims.get("identity_issuer") or claims.get("casdoor_iss")
if not isinstance(issuer, str) or issuer != expected_issuer:
raise UnauthorizedError()
subject = claims.get("casdoor_sub")
if not isinstance(subject, str) or not subject:
raise UnauthorizedError()
local_id = claims.get("user_id")
if local_id is not None and str(local_id) == subject:
raise UnauthorizedError()
return subject, issuer
def _login_name(claims: dict[str, object]) -> str:
"""Choose the Casdoor login name used for a later role refresh."""
for key in ("preferred_username", "employee_id"):
value = claims.get(key)
if isinstance(value, str) and value:
return value
raise UnauthorizedError()
def get_hxops_login(directory: RoleDirectory = Depends(get_role_directory)) -> HxopsAssertionLogin:
"""Provide HXOPS entry from server settings. Tests replace this dependency."""
return HxopsAssertionLogin(get_settings(), directory)
@@ -0,0 +1,119 @@
"""Reload Casdoor roles for a login name without keeping a user token.
Uses the application client to read one user. Tests replace the transport.
Depends on settings and the shared HTTP transport used by password login.
"""
from __future__ import annotations
import base64
from datetime import timedelta
from typing import Protocol
from urllib.parse import quote
from fastapi import Cookie, Depends, Request
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
from watchman.auth.access import require_platform_write
from watchman.auth.sessions import (
SESSION_COOKIE_NAME,
SessionStore,
get_session_store,
hash_cookie_token,
read_session_token,
utc_now,
)
from watchman.core.config import Settings, get_settings
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
class RoleDirectory(Protocol):
"""Fetch the current role names for a Casdoor login name."""
def lookup_roles(self, *, login_name: str) -> list[str]:
"""Return role names or raise ServiceUnavailableError. Never returns a token."""
class CasdoorRoleDirectory:
"""Read roles from Casdoor get-user using the application client."""
def __init__(
self,
settings: Settings | None = None,
transport: UrllibCasdoorHttpTransport | None = None,
) -> None:
self._settings = settings or get_settings()
self._transport = transport or UrllibCasdoorHttpTransport()
def lookup_roles(self, *, login_name: str) -> list[str]:
"""Load role names for organization/login_name.
Missing configuration, an empty login name, or a failed response raises
ServiceUnavailableError and does not include credentials in the message.
"""
settings = self._settings
# GUARD: never log the client secret or the Authorization header.
if not (
settings.casdoor_endpoint
and settings.casdoor_client_id
and settings.casdoor_client_secret
and settings.casdoor_organization
and login_name
):
raise ServiceUnavailableError("Casdoor login is unavailable")
user_id = f"{quote(settings.casdoor_organization, safe='')}/{quote(login_name, safe='')}"
url = f"{settings.casdoor_endpoint.rstrip('/')}/api/get-user?id={user_id}"
basic = base64.b64encode(
f"{settings.casdoor_client_id}:{settings.casdoor_client_secret}".encode()
).decode("ascii")
try:
response = self._transport.request(
method="GET",
url=url,
headers={"Accept": "application/json", "Authorization": f"Basic {basic}"},
)
except Exception as error:
raise ServiceUnavailableError("Casdoor login is unavailable") from error
if response.status_code < 200 or response.status_code >= 300:
raise ServiceUnavailableError("Casdoor login is unavailable")
payload = DefaultCasdoorPort._decode_json(response.body)
if payload.get("status") == "error":
raise ServiceUnavailableError("Casdoor login is unavailable")
data = payload.get("data")
if not isinstance(data, dict):
raise ServiceUnavailableError("Casdoor login is unavailable")
return DefaultCasdoorPort._role_names(data.get("roles"))
def get_role_directory() -> RoleDirectory:
"""Provide the production role lookup; tests override this dependency."""
return CasdoorRoleDirectory()
ROLE_FRESHNESS = timedelta(minutes=5)
def require_platform_writer(
request: Request,
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
sessions: SessionStore = Depends(get_session_store),
directory: RoleDirectory = Depends(get_role_directory),
) -> None:
"""Reject a platform write unless a fresh watchman-admin session is present.
A missing or expired session is 41000. A stale role snapshot is reloaded from
Casdoor; if that reload fails the write is refused with 503 and the old
roles are not used. Any other role is 42000.
"""
token = read_session_token(request, session_token)
if token is None:
raise UnauthorizedError()
now = utc_now()
row = sessions.get(token_hash=hash_cookie_token(token), now=now)
if row is None:
raise UnauthorizedError()
roles = list(row.role_snapshot)
if now - row.role_checked_at >= ROLE_FRESHNESS:
roles = directory.lookup_roles(login_name=row.login_name)
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
require_platform_write(roles)
@@ -0,0 +1,141 @@
"""Session creation, lookup, and revocation for authenticated browsers.
Persists only token hashes and public identity snapshots through tenant-scoped SQLAlchemy sessions.
Depends on the auth-session model and server-side Watchman settings.
"""
from __future__ import annotations
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from typing import Protocol
from fastapi import Depends, Request
from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from watchman.auth.casdoor import CasdoorIdentity
from watchman.core.config import get_settings
from watchman.core.db import get_db_session
from watchman.models.auth_session import AuthSession
SESSION_LIFETIME = timedelta(hours=8)
SESSION_COOKIE_NAME = "watchman_session"
class SessionStore(Protocol):
"""Persist and retrieve browser sessions without exposing their raw cookie token."""
def create(
self,
*,
token_hash: str,
identity: CasdoorIdentity,
now: datetime,
login_name: str,
) -> AuthSession:
"""Store one identity snapshot and return its new session record."""
def get(self, *, token_hash: str, now: datetime) -> AuthSession | None:
"""Return a live session or remove and hide an expired session."""
def invalidate(self, *, token_hash: str) -> None:
"""Invalidate a browser session identified by its hashed cookie token."""
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
"""Replace a live session's role snapshot after a successful Casdoor refresh."""
class SqlAlchemySessionStore:
"""Tenant-scoped session store backed by the application database session."""
def __init__(self, session: Session) -> None:
self._session = session
def create(
self,
*,
token_hash: str,
identity: CasdoorIdentity,
now: datetime,
login_name: str,
) -> AuthSession:
"""Save a server-owned session using only the configured tenant identity."""
row = AuthSession(
token_hash=token_hash,
subject=identity.subject,
issuer=identity.issuer,
display_name=identity.display_name,
login_name=login_name,
role_snapshot=list(identity.role_names),
role_checked_at=now,
expires_at=now + SESSION_LIFETIME,
tenant_id=get_settings().tenant_id,
)
self._session.add(row)
self._session.commit()
return row
def get(self, *, token_hash: str, now: datetime) -> AuthSession | None:
"""Read a live session and remove stale rows so expiry cannot be reused."""
row = self._session.scalar(
select(AuthSession).where(
AuthSession.token_hash == token_hash,
AuthSession.expires_at > now,
)
)
if row is not None:
return row
self._session.execute(
delete(AuthSession).where(
AuthSession.token_hash == token_hash,
AuthSession.expires_at <= now,
)
)
self._session.commit()
return None
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
"""Persist a refreshed role snapshot without changing who the session belongs to."""
row = self._session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash))
if row is None:
return
row.role_snapshot = list(role_names)
row.role_checked_at = now
self._session.commit()
def invalidate(self, *, token_hash: str) -> None:
"""Delete the row so logout takes effect before the cookie itself expires."""
self._session.execute(delete(AuthSession).where(AuthSession.token_hash == token_hash))
self._session.commit()
def get_session_store(session: Session = Depends(get_db_session)) -> SessionStore:
"""Provide the tenant-scoped SQLAlchemy store; tests replace this dependency."""
return SqlAlchemySessionStore(session)
def issue_cookie_token() -> str:
"""Return an unguessable token that is sent only in the HttpOnly cookie."""
return secrets.token_urlsafe(32)
def hash_cookie_token(token: str) -> str:
"""Hash a raw browser token before it is used as a database lookup key."""
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def read_session_token(request: Request, cookie_token: str | None) -> str | None:
"""Prefer the bearer token the browser stored, and fall back to the cookie."""
authorization = request.headers.get("authorization", "")
if authorization.lower().startswith("bearer "):
token = authorization[7:].strip()
if token:
return token
return cookie_token
def utc_now() -> datetime:
"""Return the current timezone-aware UTC instant for session expiry checks."""
return datetime.now(timezone.utc)
@@ -0,0 +1,63 @@
"""Verify signed JWT identity assertions with local public keys.
Only validates tokens; session creation and Casdoor communication remain outside this module.
Depends on PyJWT and watchman.core.errors.UnauthorizedError."""
from __future__ import annotations
from collections.abc import Mapping
from datetime import datetime, timezone
from typing import Any
import jwt
from watchman.core.errors import UnauthorizedError
def verify_rs256_token(
token: str,
*,
public_key: str,
issuer: str,
audience: str,
now: datetime | None = None,
) -> dict[str, Any]:
"""Return claims only after local signature and identity checks succeed.
Inputs are an RS256 token, trusted public key, expected issuer/audience, and optional UTC clock;
invalid signatures, algorithms, claims, or expiry raise UnauthorizedError without exposing details.
"""
current_time = now or datetime.now(timezone.utc)
if current_time.tzinfo is None or current_time.utcoffset() is None:
raise ValueError("now must be timezone-aware")
try:
header = jwt.get_unverified_header(token)
if header.get("alg") != "RS256":
raise UnauthorizedError()
claims = jwt.decode(
token,
public_key,
# GUARD: RS256 only; never include none or HS*.
algorithms=["RS256"],
audience=audience,
issuer=issuer,
options={"require": ["exp"], "verify_exp": False},
)
_verify_expiration(claims, now=current_time)
except (jwt.PyJWTError, TypeError, ValueError):
raise UnauthorizedError() from None
return dict(claims)
def _verify_expiration(claims: Mapping[str, Any], *, now: datetime) -> None:
"""Reject expired or malformed expiry claims using the injected deterministic clock.
Input is a signature-verified claim mapping and UTC clock; returns only for a future numeric expiry;
malformed, missing, or expired values raise ValueError for the public verifier to map to UnauthorizedError.
"""
expires_at = claims["exp"]
if isinstance(expires_at, bool) or not isinstance(expires_at, int | float):
raise ValueError("exp must be a numeric date")
if expires_at <= now.timestamp():
raise ValueError("token has expired")
@@ -103,6 +103,14 @@ class Settings(BaseSettings):
default="amqp://guest:CHANGE-ME@127.0.0.1:56729//",
alias="CELERY_BROKER_URL",
)
casdoor_endpoint: str = Field(default="", alias="CASDOOR_ENDPOINT")
casdoor_issuer: str = Field(default="", alias="CASDOOR_ISSUER")
casdoor_client_id: str = Field(default="", alias="CASDOOR_CLIENT_ID")
casdoor_client_secret: str = Field(default="", alias="CASDOOR_CLIENT_SECRET")
casdoor_organization: str = Field(default="", alias="CASDOOR_ORGANIZATION")
hxops_sso_issuer: str = Field(default="", alias="HXOPS_SSO_ISSUER")
hxops_sso_audience: str = Field(default="", alias="HXOPS_SSO_AUDIENCE")
hxops_sso_public_key: str = Field(default="", alias="HXOPS_SSO_PUBLIC_KEY")
def _settings_from_env_map(env: dict[str, str]) -> Settings:
@@ -125,6 +133,14 @@ def _settings_from_env_map(env: dict[str, str]) -> Settings:
"CELERY_BROKER_URL",
"amqp://guest:CHANGE-ME@127.0.0.1:56729//",
),
casdoor_endpoint=env.get("CASDOOR_ENDPOINT", ""),
casdoor_issuer=env.get("CASDOOR_ISSUER", ""),
casdoor_client_id=env.get("CASDOOR_CLIENT_ID", ""),
casdoor_client_secret=env.get("CASDOOR_CLIENT_SECRET", ""),
casdoor_organization=env.get("CASDOOR_ORGANIZATION", ""),
hxops_sso_issuer=env.get("HXOPS_SSO_ISSUER", ""),
hxops_sso_audience=env.get("HXOPS_SSO_AUDIENCE", ""),
hxops_sso_public_key=env.get("HXOPS_SSO_PUBLIC_KEY", ""),
)
@@ -1,5 +1,6 @@
"""SQLAlchemy models for the Watchman service package."""
from watchman.models.auth_session import AuthSession
from watchman.models.platform import AuditEvent, RunRecord
__all__ = ["AuditEvent", "RunRecord"]
__all__ = ["AuthSession", "AuditEvent", "RunRecord"]
@@ -0,0 +1,40 @@
"""Server-side authentication session persistence.
Stores only public identity snapshots and a hash of the browser token; it never stores credentials.
Depends on SQLAlchemy and the shared Watchman declarative base.
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import DateTime, String, func, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from watchman.models.base import Base
class AuthSession(Base):
"""A tenant-scoped browser session with an opaque, hashed lookup token."""
__tablename__ = "auth_sessions"
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
subject: Mapped[str] = mapped_column(String(255), nullable=False)
issuer: Mapped[str] = mapped_column(String(512), nullable=False)
display_name: Mapped[str] = mapped_column(String(255), nullable=False)
login_name: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
role_snapshot: Mapped[list[str]] = mapped_column(
JSONB,
nullable=False,
server_default=text("'[]'::jsonb"),
)
role_checked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
nullable=False,
server_default=func.now(),
)
@@ -0,0 +1,364 @@
"""Acceptance tests for M02 S2 password sessions without external Casdoor calls.
Uses injected in-memory ports so API tests do not require a network or local PostgreSQL.
Depends on FastAPI dependency overrides and public authentication interfaces.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from watchman.api.app import create_app
from watchman.auth.casdoor import CasdoorIdentity, DefaultCasdoorPort, HttpResponse, get_casdoor_port
from watchman.auth.sessions import SESSION_LIFETIME, SessionStore, get_session_store
from watchman.core.config import Settings
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
FAKE_PASSWORD = "fixed-fake-password"
FAKE_ACCESS_TOKEN = "fixed-fake-access-token"
@dataclass
class StoredSession:
"""Minimal stored-session shape used by the in-memory API-test port."""
token_hash: str
subject: str
issuer: str
display_name: str
login_name: str
role_snapshot: list[str]
role_checked_at: datetime
expires_at: datetime
class InMemorySessionStore:
"""Test-only session store preserving the production port contract."""
def __init__(self) -> None:
self.rows: dict[str, StoredSession] = {}
def create(
self,
*,
token_hash: str,
identity: CasdoorIdentity,
now: datetime,
login_name: str,
) -> StoredSession:
row = StoredSession(
token_hash=token_hash,
subject=identity.subject,
issuer=identity.issuer,
display_name=identity.display_name,
login_name=login_name,
role_snapshot=list(identity.role_names),
role_checked_at=now,
expires_at=now + SESSION_LIFETIME,
)
self.rows[token_hash] = row
return row
def get(self, *, token_hash: str, now: datetime) -> StoredSession | None:
row = self.rows.get(token_hash)
if row is not None and row.expires_at > now:
return row
self.rows.pop(token_hash, None)
return None
def invalidate(self, *, token_hash: str) -> None:
self.rows.pop(token_hash, None)
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
row = self.rows.get(token_hash)
if row is None:
return
row.role_snapshot = list(role_names)
row.role_checked_at = now
class AcceptingCasdoor:
"""Stand-in that returns only safe identity values and never contacts Casdoor."""
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
if password != FAKE_PASSWORD:
raise UnauthorizedError()
return CasdoorIdentity(
subject="casdoor-subject-1",
issuer="https://casdoor.test",
display_name="Test Operator",
role_names=["watchman-operator", "watchman-viewer"],
)
class RejectingCasdoor:
"""Stand-in for generic upstream credential rejection."""
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
raise UnauthorizedError()
class FakeCasdoorTransport:
"""Queue controlled HTTP results so Casdoor adapter tests never use the network."""
def __init__(self, responses: list[HttpResponse | Exception]) -> None:
self._responses = iter(responses)
self.calls: list[tuple[str, str, dict[str, str], bytes | None]] = []
def request(
self,
*,
method: str,
url: str,
headers: dict[str, str],
data: bytes | None = None,
) -> HttpResponse:
self.calls.append((method, url, headers, data))
result = next(self._responses)
if isinstance(result, Exception):
raise result
return result
@pytest.fixture()
def auth_client() -> tuple[TestClient, InMemorySessionStore]:
"""Return a client with only local stand-ins, avoiding database and network access."""
app = create_app(validate_runtime=False)
store = InMemorySessionStore()
app.dependency_overrides[get_casdoor_port] = lambda: AcceptingCasdoor()
app.dependency_overrides[get_session_store] = lambda: store
with TestClient(app) as client:
yield client, store
def test_password_login_creates_session_returns_roles_and_hides_password(
auth_client: tuple[TestClient, InMemorySessionStore],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Successful injected login must create a session without leaking the submitted password."""
client, store = auth_client
caplog.set_level(logging.DEBUG)
response = client.post(
"/auth/login",
json={"username": "operator", "password": FAKE_PASSWORD},
)
assert response.status_code == 200
body = response.json()
assert body["success"] is True
assert body["data"]["subject"] == "casdoor-subject-1"
assert body["data"]["display_name"] == "Test Operator"
assert body["data"]["login_name"] == "operator"
assert body["data"]["roles"] == ["watchman-operator", "watchman-viewer"]
assert body["data"]["token_type"] == "Bearer"
assert body["data"]["expires_in"] == 8 * 60 * 60
assert body["data"]["access_token"]
assert FAKE_PASSWORD not in body["data"]["access_token"]
assert len(store.rows) == 1
assert FAKE_PASSWORD not in response.text
assert FAKE_PASSWORD not in caplog.text
cookie = response.headers["set-cookie"].lower()
assert "httponly" in cookie
assert "samesite=lax" in cookie
assert "path=/" in cookie
assert "secure" not in cookie
def test_bearer_token_reads_current_user_without_cookie(
auth_client: tuple[TestClient, InMemorySessionStore],
) -> None:
"""The access token returned to the browser can authorize a later request."""
client, _store = auth_client
login = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
token = login.json()["data"]["access_token"]
bare = TestClient(client.app)
response = bare.get("/auth/me", headers={"Authorization": f"Bearer {token}"})
assert response.status_code == 200
assert response.json()["data"]["subject"] == "casdoor-subject-1"
assert "access_token" not in response.json()["data"]
def test_rejected_login_is_unauthorized_and_creates_no_session() -> None:
"""Casdoor credential rejection must map to 41000 without persisting a session."""
app = create_app(validate_runtime=False)
store = InMemorySessionStore()
app.dependency_overrides[get_casdoor_port] = lambda: RejectingCasdoor()
app.dependency_overrides[get_session_store] = lambda: store
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
assert response.status_code == 401
assert response.json()["error"]["code"] == 41000
assert len(store.rows) == 0
def test_unconfigured_default_port_returns_retryable_503_without_session() -> None:
"""Incomplete Casdoor settings must fail closed before session creation."""
app = create_app(validate_runtime=False)
store = InMemorySessionStore()
incomplete_settings = Settings(
casdoor_endpoint="",
casdoor_client_id="",
casdoor_client_secret="",
)
app.dependency_overrides[get_casdoor_port] = lambda: DefaultCasdoorPort(incomplete_settings)
app.dependency_overrides[get_session_store] = lambda: store
with TestClient(app, raise_server_exceptions=False) as client:
response = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
assert response.status_code == 503
assert response.json()["error"]["code"] == 50000
assert response.json()["error"]["retryable"] is True
assert len(store.rows) == 0
def test_default_port_password_grant_returns_safe_identity_and_roles() -> None:
"""A discovered password grant returns userinfo roles without retaining credentials."""
transport = FakeCasdoorTransport(
[
HttpResponse(
200,
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
),
HttpResponse(200, b'{"access_token":"fixed-fake-access-token"}'),
HttpResponse(200, b'{"sub":"employee-1","name":"Employee","roles":["watchman-admin"]}'),
]
)
port = DefaultCasdoorPort(
Settings(
casdoor_endpoint="https://casdoor.test/",
casdoor_issuer="https://issuer.casdoor.test",
casdoor_client_id="test-client",
casdoor_client_secret="test-secret",
),
transport,
)
identity = port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
assert identity == CasdoorIdentity(
subject="employee-1",
issuer="https://issuer.casdoor.test",
display_name="Employee",
role_names=["watchman-admin"],
)
assert FAKE_PASSWORD not in repr(identity)
assert FAKE_ACCESS_TOKEN not in repr(identity)
assert [call[0] for call in transport.calls] == ["GET", "POST", "GET"]
assert transport.calls[0][1] == "https://casdoor.test/.well-known/openid-configuration"
assert b"grant_type=password" in transport.calls[1][3]
assert transport.calls[2][2]["Authorization"] == f"Bearer {FAKE_ACCESS_TOKEN}"
def test_default_port_invalid_grant_is_unauthorized() -> None:
"""Casdoor invalid_grant is a generic credential rejection."""
transport = FakeCasdoorTransport(
[
HttpResponse(
200,
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
),
HttpResponse(400, b'{"error":"invalid_grant","error_description":"upstream secret detail"}'),
]
)
port = DefaultCasdoorPort(
Settings(
casdoor_endpoint="https://casdoor.test",
casdoor_client_id="test-client",
casdoor_client_secret="test-secret",
),
transport,
)
with pytest.raises(UnauthorizedError, match="Invalid username or password"):
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
def test_default_port_unsupported_grant_is_unavailable() -> None:
"""A disabled grant type is a configuration failure, not a wrong password."""
transport = FakeCasdoorTransport(
[
HttpResponse(
200,
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
),
HttpResponse(400, b'{"error":"unsupported_grant_type"}'),
]
)
port = DefaultCasdoorPort(
Settings(
casdoor_endpoint="https://casdoor.test",
casdoor_client_id="test-client",
casdoor_client_secret="test-secret",
),
transport,
)
with pytest.raises(ServiceUnavailableError):
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
def test_default_port_transport_failure_is_retryable() -> None:
"""Network failures are mapped to the retryable integration error."""
transport = FakeCasdoorTransport([OSError("network unavailable")])
port = DefaultCasdoorPort(
Settings(
casdoor_endpoint="https://casdoor.test",
casdoor_client_id="test-client",
casdoor_client_secret="test-secret",
),
transport,
)
with pytest.raises(ServiceUnavailableError):
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
def test_unconfigured_default_port_does_not_call_transport() -> None:
"""Missing Casdoor configuration fails before the injected transport is used."""
transport = FakeCasdoorTransport([])
port = DefaultCasdoorPort(Settings(), transport)
with pytest.raises(ServiceUnavailableError):
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
assert transport.calls == []
def test_logout_invalidates_session_and_me_then_returns_41000(
auth_client: tuple[TestClient, InMemorySessionStore],
) -> None:
"""Logout must remove the server-side session before a later current-user request."""
client, _store = auth_client
assert client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD}).status_code == 200
assert client.get("/auth/me").status_code == 200
logout = client.post("/auth/logout")
assert logout.status_code == 200
assert "max-age=0" in logout.headers["set-cookie"].lower()
me = client.get("/auth/me")
assert me.status_code == 401
assert me.json()["error"]["code"] == 41000
def test_health_remains_anonymous_and_missing_login_fields_are_40000() -> None:
"""The auth router must not introduce a global auth requirement or bypass validation envelopes."""
app = create_app(validate_runtime=False)
app.dependency_overrides[get_casdoor_port] = lambda: AcceptingCasdoor()
app.dependency_overrides[get_session_store] = lambda: InMemorySessionStore()
with TestClient(app) as client:
assert client.get("/health").status_code == 200
response = client.post("/auth/login", json={"username": "operator"})
assert response.status_code == 400
assert response.json()["error"]["code"] == 40000
+221
View File
@@ -0,0 +1,221 @@
"""HXOPS assertion entry tests.
Uses an in-memory session and a scripted role directory. No network and no .env.local.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from fastapi.testclient import TestClient
from watchman.api.app import create_app
from watchman.auth.casdoor import CasdoorIdentity
from watchman.auth.hxops import HxopsAssertionLogin, get_hxops_login
from watchman.auth.sessions import SESSION_LIFETIME, get_session_store
from watchman.core.config import Settings
from watchman.core.errors import ServiceUnavailableError
ISSUER = "https://hxops.test"
AUDIENCE = "watchman"
CASDOOR_ISSUER = "https://casdoor.test"
NOW = datetime(2030, 1, 1, tzinfo=timezone.utc)
class MemoryStore:
"""Small session stand-in for the assertion route."""
def __init__(self) -> None:
self.rows: dict[str, object] = {}
def create(self, *, token_hash: str, identity: CasdoorIdentity, now: datetime, login_name: str) -> object:
row = type(
"Row",
(),
{
"subject": identity.subject,
"display_name": identity.display_name,
"role_snapshot": list(identity.role_names),
"login_name": login_name,
"expires_at": now + SESSION_LIFETIME,
},
)()
self.rows[token_hash] = row
return row
def get(self, *, token_hash: str, now: datetime) -> object | None:
row = self.rows.get(token_hash)
if row is not None and row.expires_at > now:
return row
return None
def invalidate(self, *, token_hash: str) -> None:
self.rows.pop(token_hash, None)
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
del token_hash, role_names, now
class Directory:
def __init__(self, roles: list[str] | None = None, fail: bool = False) -> None:
self.roles = roles or ["watchman-viewer"]
self.fail = fail
self.login_name = ""
def lookup_roles(self, *, login_name: str) -> list[str]:
if self.fail:
raise ServiceUnavailableError("Casdoor login is unavailable")
self.login_name = login_name
return list(self.roles)
def _keys() -> tuple[rsa.RSAPrivateKey, str]:
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_pem = private_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
).decode()
return private_key, public_pem
def _settings(public_pem: str) -> Settings:
return Settings(
hxops_sso_issuer=ISSUER,
hxops_sso_audience=AUDIENCE,
hxops_sso_public_key=public_pem,
casdoor_issuer=CASDOOR_ISSUER,
)
def _token(private_key: rsa.RSAPrivateKey, **overrides: object) -> str:
claims: dict[str, object] = {
"iss": ISSUER,
"aud": AUDIENCE,
"sub": "1001",
"casdoor_sub": "casdoor-subject-1",
"identity_issuer": CASDOOR_ISSUER,
"preferred_username": "26110002",
"name": "Worker",
"user_id": 1001,
"roles": ["watchman-admin"],
"exp": int((NOW + timedelta(seconds=60)).timestamp()),
}
claims.update(overrides)
return jwt.encode(claims, private_key, algorithm="RS256")
def _client(entry: HxopsAssertionLogin, store: MemoryStore) -> TestClient:
app = create_app(validate_runtime=False)
app.dependency_overrides[get_hxops_login] = lambda: entry
app.dependency_overrides[get_session_store] = lambda: store
return TestClient(app)
def test_valid_assertion_uses_directory_roles_not_assertion_roles() -> None:
"""A signed assertion opens a session, and Casdoor roles replace assertion roles."""
private_key, public_pem = _keys()
directory = Directory(["watchman-viewer"])
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), directory)
client = _client(entry, store)
response = client.post("/auth/hxops-entry", json={"assertion": _token(private_key)})
assert response.status_code == 200
assert response.json()["data"]["roles"] == ["watchman-viewer"]
assert response.json()["data"]["subject"] == "casdoor-subject-1"
assert directory.login_name == "26110002"
assert len(store.rows) == 1
assert "watchman-admin" not in response.text
def test_local_user_id_cannot_impersonate_casdoor_subject() -> None:
"""Using the HXOPS primary key as the Casdoor subject does not create a session."""
private_key, public_pem = _keys()
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
client = _client(entry, store)
response = client.post(
"/auth/hxops-entry",
json={"assertion": _token(private_key, casdoor_sub="1001")},
)
assert response.status_code == 401
assert response.json()["error"]["code"] == 41000
assert len(store.rows) == 0
def test_hxops_subject_without_casdoor_sub_is_unauthorized() -> None:
"""The HXOPS token subject is not accepted when casdoor_sub is absent."""
private_key, public_pem = _keys()
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
client = _client(entry, store)
response = client.post(
"/auth/hxops-entry",
json={"assertion": _token(private_key, sub="1001", casdoor_sub="", user_id=None)},
)
assert response.status_code == 401
assert response.json()["error"]["code"] == 41000
assert len(store.rows) == 0
def test_missing_casdoor_reference_is_unauthorized() -> None:
"""An assertion without a Casdoor issuer reference is rejected."""
private_key, public_pem = _keys()
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
client = _client(entry, store)
token = _token(private_key, identity_issuer="", casdoor_iss="")
response = client.post("/auth/hxops-entry", json={"assertion": token})
assert response.status_code == 401
assert len(store.rows) == 0
def test_bad_signature_creates_no_session() -> None:
"""A token signed by another key cannot enter."""
_, public_pem = _keys()
other, _ = _keys()
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
client = _client(entry, store)
response = client.post("/auth/hxops-entry", json={"assertion": _token(other)})
assert response.status_code == 401
assert len(store.rows) == 0
def test_directory_failure_creates_no_session() -> None:
"""If Casdoor cannot supply roles, the assertion does not become a session."""
private_key, public_pem = _keys()
store = MemoryStore()
entry = HxopsAssertionLogin(_settings(public_pem), Directory(fail=True))
client = _client(entry, store)
response = client.post("/auth/hxops-entry", json={"assertion": _token(private_key)})
assert response.status_code == 503
assert response.json()["error"]["retryable"] is True
assert len(store.rows) == 0
def test_unconfigured_hxops_entry_is_unavailable() -> None:
"""Missing HXOPS key material fails before role lookup."""
directory = Directory()
entry = HxopsAssertionLogin(Settings(), directory)
try:
entry.authenticate("not-a-token")
except ServiceUnavailableError:
pass
else:
raise AssertionError("unconfigured entry did not fail")
assert directory.login_name == ""
+46 -4
View File
@@ -5,14 +5,18 @@ from __future__ import annotations
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
from watchman.api.app import create_app
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
from watchman.core.config import get_settings, reload_settings
from sqlalchemy.orm import Session
from watchman.core.db import get_session_factory, reset_engine, set_tenant
from watchman.models.auth_session import AuthSession
from watchman.models.platform import AuditEvent
from watchman.services import platform_records
from sqlalchemy import select
@@ -34,10 +38,45 @@ def _count_for_key(table: str, key: str) -> int:
return int(value)
def _admin_token() -> str:
"""Insert a fresh admin session and return the raw cookie token."""
token = issue_cookie_token()
now = datetime.now(timezone.utc)
settings = get_settings()
factory = get_session_factory()
session = factory()
try:
set_tenant(session, settings.tenant_id)
session.add(
AuthSession(
token_hash=hash_cookie_token(token),
subject="idem-admin",
issuer="https://casdoor.test",
display_name="Idem Admin",
login_name="idem-admin",
role_snapshot=["watchman-admin"],
role_checked_at=now,
expires_at=now + timedelta(hours=1),
tenant_id=settings.tenant_id,
)
)
session.commit()
finally:
session.close()
return token
def _admin_client() -> TestClient:
"""Return an API client that already carries a fresh admin session."""
client = TestClient(create_app())
client.cookies.set(SESSION_COOKIE_NAME, _admin_token())
return client
def test_duplicate_idempotency_key_returns_same_audit() -> None:
reload_settings()
reset_engine()
client = TestClient(create_app())
client = _admin_client()
key = f"idem-audit-{uuid.uuid4().hex}"
headers = {"x-idempotency-key": key, "X-Request-Id": "req-idem-1"}
body = {"action": "idem-test", "payload": {"n": 1}}
@@ -52,7 +91,7 @@ def test_duplicate_idempotency_key_returns_same_audit() -> None:
def test_duplicate_idempotency_key_returns_same_run_record() -> None:
reload_settings()
reset_engine()
client = TestClient(create_app())
client = _admin_client()
key = f"idem-run-{uuid.uuid4().hex}"
headers = {"x-idempotency-key": key, "X-Request-Id": "req-idem-2"}
body = {"kind": "idem-test", "status": "ok", "detail": {"n": 1}}
@@ -67,7 +106,7 @@ def test_duplicate_idempotency_key_returns_same_run_record() -> None:
def test_missing_idempotency_key_is_40000() -> None:
reload_settings()
reset_engine()
client = TestClient(create_app())
client = _admin_client()
response = client.post("/platform/audit-events", json={"action": "no-key", "payload": {}})
assert response.status_code == 400
assert response.json()["error"]["code"] == 40000
@@ -79,8 +118,11 @@ def test_concurrent_duplicate_audit_returns_same_id() -> None:
key = f"idem-race-{uuid.uuid4().hex}"
body = {"action": "race", "payload": {}}
token = _admin_token()
def _post() -> str:
client = TestClient(create_app())
client.cookies.set(SESSION_COOKIE_NAME, token)
response = client.post(
"/platform/audit-events",
json=body,
@@ -99,7 +141,7 @@ def test_caller_tenant_id_is_ignored() -> None:
reload_settings()
reset_engine()
settings = get_settings()
client = TestClient(create_app())
client = _admin_client()
key = f"tenant-inject-{uuid.uuid4().hex}"
response = client.post(
"/platform/audit-events",
@@ -0,0 +1,191 @@
"""Platform write authorization and object-access checks.
Covers anonymous denial, role denial, admin allowance, and stale role refresh.
Depends on a local Postgres session row and an injected role directory.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timedelta, timezone
from fastapi.testclient import TestClient
from watchman.api.app import create_app
from watchman.auth.access import (
OBJECT_READ_NODE,
PLATFORM_WRITE_NODE,
allows_enter,
require_object_access,
)
from watchman.auth.casdoor import HttpResponse
from watchman.auth.principal import CasdoorRoleDirectory, get_role_directory
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
from watchman.core.config import Settings, get_settings, reload_settings
from watchman.core.db import get_session_factory, reset_engine, set_tenant
from watchman.core.errors import ForbiddenError, ServiceUnavailableError
from watchman.models.auth_session import AuthSession
def _seed(roles: list[str], *, age: timedelta = timedelta(0), login_name: str = "worker") -> str:
"""Insert one session and return its raw cookie token."""
token = issue_cookie_token()
now = datetime.now(timezone.utc)
settings = get_settings()
session = get_session_factory()()
try:
set_tenant(session, settings.tenant_id)
session.add(
AuthSession(
token_hash=hash_cookie_token(token),
subject=f"subject-{uuid.uuid4().hex}",
issuer="https://casdoor.test",
display_name="Worker",
login_name=login_name,
role_snapshot=list(roles),
role_checked_at=now - age,
expires_at=now + timedelta(hours=1),
tenant_id=settings.tenant_id,
)
)
session.commit()
finally:
session.close()
return token
def _client(token: str | None, directory: object | None = None) -> TestClient:
"""Build a client, optionally replacing Casdoor role lookup."""
reload_settings()
reset_engine()
app = create_app()
if directory is not None:
app.dependency_overrides[get_role_directory] = lambda: directory
client = TestClient(app)
if token is not None:
client.cookies.set(SESSION_COOKIE_NAME, token)
return client
def test_anonymous_platform_write_is_401_without_permission_node() -> None:
"""A missing session is unauthorized and must not name a permission node."""
client = _client(None)
response = client.post(
"/platform/audit-events",
json={"action": "hidden", "payload": {}},
headers={"x-idempotency-key": f"anon-{uuid.uuid4().hex}"},
)
assert response.status_code == 401
error = response.json()["error"]
assert error["code"] == 41000
assert "permission_node" not in error
def test_viewer_platform_write_is_forbidden() -> None:
"""A viewer session cannot create an audit event."""
client = _client(_seed(["watchman-viewer"]))
response = client.post(
"/platform/audit-events",
json={"action": "hidden", "payload": {}},
headers={"x-idempotency-key": f"viewer-{uuid.uuid4().hex}"},
)
assert response.status_code == 403
assert response.json()["error"]["permission_node"] == PLATFORM_WRITE_NODE
def test_admin_platform_write_is_allowed() -> None:
"""A fresh admin session can create a run record."""
client = _client(_seed(["watchman-admin"]))
response = client.post(
"/platform/run-records",
json={"kind": "check", "status": "ok", "detail": {}},
headers={"x-idempotency-key": f"admin-{uuid.uuid4().hex}"},
)
assert response.status_code == 200
assert response.json()["success"] is True
def test_stale_roles_fail_closed_when_directory_is_down() -> None:
"""An expired role snapshot is not reused when Casdoor cannot be asked."""
class DownDirectory:
def lookup_roles(self, *, login_name: str) -> list[str]:
raise ServiceUnavailableError("Casdoor login is unavailable")
client = _client(_seed(["watchman-admin"], age=timedelta(minutes=6)), DownDirectory())
response = client.post(
"/platform/audit-events",
json={"action": "stale", "payload": {}},
headers={"x-idempotency-key": f"stale-{uuid.uuid4().hex}"},
)
assert response.status_code == 503
assert response.json()["error"]["retryable"] is True
def test_stale_roles_refresh_before_write() -> None:
"""A successful refresh replaces the snapshot and then allows the admin write."""
class AdminDirectory:
def lookup_roles(self, *, login_name: str) -> list[str]:
assert login_name == "worker"
return ["watchman-admin"]
client = _client(_seed(["watchman-viewer"], age=timedelta(minutes=6)), AdminDirectory())
response = client.post(
"/platform/audit-events",
json={"action": "refreshed", "payload": {}},
headers={"x-idempotency-key": f"refresh-{uuid.uuid4().hex}"},
)
assert response.status_code == 200
def test_enter_and_object_rules() -> None:
"""Enter allows only the three roles. Object ids never authorize themselves."""
assert allows_enter(["watchman-admin"])
assert allows_enter(["watchman-operator"])
assert allows_enter(["watchman-viewer"])
assert not allows_enter([])
assert not allows_enter(["someone-else"])
for object_id in ("object-a", "object-b"):
try:
require_object_access(["watchman-admin"], object_id)
except ForbiddenError as exc:
assert exc.permission_node == OBJECT_READ_NODE
else:
raise AssertionError(object_id)
class _ScriptedTransport:
def __init__(self, response: HttpResponse) -> None:
self.response = response
self.calls = 0
def request(self, *, method: str, url: str, headers: dict[str, str], data: bytes | None = None) -> HttpResponse:
self.calls += 1
return self.response
def test_role_directory_reads_names_without_calling_when_unconfigured() -> None:
"""Role lookup parses Casdoor role names and does not run without configuration."""
transport = _ScriptedTransport(
HttpResponse(200, b'{"status":"ok","data":{"roles":[{"name":"watchman-admin"}]}}')
)
directory = CasdoorRoleDirectory(
Settings(
casdoor_endpoint="https://casdoor.test",
casdoor_client_id="client",
casdoor_client_secret="secret",
casdoor_organization="organization_HX",
),
transport,
)
assert directory.lookup_roles(login_name="worker") == ["watchman-admin"]
assert transport.calls == 1
bare = CasdoorRoleDirectory(Settings(), transport)
try:
bare.lookup_roles(login_name="worker")
except ServiceUnavailableError:
pass
else:
raise AssertionError("unconfigured lookup called the transport")
assert transport.calls == 1
@@ -0,0 +1,205 @@
"""Acceptance tests for local RS256 JWT verification.
Locks requirement criterion 1 without HTTP routes, sessions, or external identity providers.
Depends on in-memory RSA keys, PyJWT, and the Watchman verifier."""
from __future__ import annotations
import base64
from datetime import datetime, timedelta, timezone
import hashlib
import hmac
import json
from typing import Any
import jwt
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from watchman.auth.token_verifier import verify_rs256_token
from watchman.core.errors import UnauthorizedError
ISSUER = "https://issuer.test/watchman"
AUDIENCE = "watchman-test"
NOW = datetime(2030, 1, 1, tzinfo=timezone.utc)
@pytest.fixture
def rsa_keys() -> tuple[rsa.RSAPrivateKey, str, bytes]:
"""Create test-only RSA material without persisting any key data.
Returns private signing material plus PEM and DER public representations for local verification;
key generation failures fail the test process before any token assertion can run.
"""
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
).decode()
public_der = public_key.public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
return private_key, public_pem, public_der
def _claims(**overrides: Any) -> dict[str, Any]:
"""Build signed-token claims that satisfy the local verifier's expected identity contract.
Optional overrides replace the default issuer, audience, or expiry values; callers use them to create
a specific rejection case while retaining a valid claim shape.
"""
claims: dict[str, Any] = {
"sub": "test-subject",
"iss": ISSUER,
"aud": AUDIENCE,
"exp": int((NOW + timedelta(minutes=5)).timestamp()),
}
claims.update(overrides)
return claims
def _signed_token(private_key: rsa.RSAPrivateKey, **overrides: Any) -> str:
"""Sign a valid baseline claim set so each test isolates one acceptance condition.
Input is in-memory RSA material and optional claim replacements; signing failures surface to the test
rather than being confused with the verifier's unauthorized result.
"""
return jwt.encode(_claims(**overrides), private_key, algorithm="RS256")
def test_verifier_returns_claims_after_valid_rs256_signature_and_checks(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
) -> None:
"""Locks acceptance criterion 1's required success case after all verification checks pass."""
private_key, public_pem, _ = rsa_keys
claims = verify_rs256_token(
_signed_token(private_key),
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
assert claims["sub"] == "test-subject"
def test_verifier_rejects_invalid_signature(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
) -> None:
"""Locks acceptance criterion 1: a token signed by another key cannot authenticate."""
_, public_pem, _ = rsa_keys
other_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
with pytest.raises(UnauthorizedError):
verify_rs256_token(
_signed_token(other_private_key),
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
def test_verifier_rejects_wrong_issuer(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
) -> None:
"""Locks acceptance criterion 1: a signed token from another issuer cannot authenticate."""
private_key, public_pem, _ = rsa_keys
with pytest.raises(UnauthorizedError):
verify_rs256_token(
_signed_token(private_key, iss="https://issuer.test/other"),
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
def test_verifier_rejects_wrong_audience(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
) -> None:
"""Locks acceptance criterion 1: a signed token for another audience cannot authenticate."""
private_key, public_pem, _ = rsa_keys
with pytest.raises(UnauthorizedError):
verify_rs256_token(
_signed_token(private_key, aud="another-service"),
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
def test_verifier_rejects_clearly_expired_token(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
) -> None:
"""Locks acceptance criterion 1: deterministic expiry before now cannot authenticate."""
private_key, public_pem, _ = rsa_keys
with pytest.raises(UnauthorizedError):
verify_rs256_token(
_signed_token(private_key, exp=int((NOW - timedelta(days=1)).timestamp())),
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
def test_verifier_rejects_unsigned_none_algorithm_token(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Locks the explicit S1 algorithm policy: unsigned alg none tokens cannot authenticate."""
_, public_pem, _ = rsa_keys
token = jwt.encode(_claims(), key=None, algorithm="none")
monkeypatch.setattr(
jwt,
"decode",
lambda *args, **kwargs: pytest.fail("jwt.decode must not process alg none tokens"),
)
with pytest.raises(UnauthorizedError):
verify_rs256_token(
token,
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)
def test_verifier_rejects_hs256_public_key_confusion(
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Locks the explicit S1 algorithm policy: public-key-as-HMAC tokens cannot authenticate."""
_, public_pem, public_der = rsa_keys
encoded_header = base64.urlsafe_b64encode(
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
).rstrip(b"=")
encoded_claims = base64.urlsafe_b64encode(
json.dumps(_claims(), separators=(",", ":")).encode()
).rstrip(b"=")
signing_input = encoded_header + b"." + encoded_claims
signature = hmac.new(public_der, signing_input, hashlib.sha256).digest()
token = f"{signing_input.decode()}.{base64.urlsafe_b64encode(signature).rstrip(b'=').decode()}"
monkeypatch.setattr(
jwt,
"decode",
lambda *args, **kwargs: pytest.fail("jwt.decode must not process HS256 tokens"),
)
with pytest.raises(UnauthorizedError):
verify_rs256_token(
token,
public_key=public_pem,
issuer=ISSUER,
audience=AUDIENCE,
now=NOW,
)