Files
DECNET/decnet/web/db/models/auth.py
anti d80e6aa6d1 fix(security): close MEDIUM ASVS findings — JWT pinning, SSE tickets, SSRF, mTLS pin, rate limits + correctness bugs
Auth (V2.1.1/V3.1.2, V2.1.3, V3.1.1):
- Pin JWT iss/aud/typ at mint and require+verify them at decode; revocation
  (jti denylist + tokens_valid_from) still enforced.
- Change-password now requires min_length=12.
- SSE auth moves off JWT-in-URL to a single-use 60s opaque ticket
  (POST /auth/sse-ticket); raw JWT in query no longer authenticates a stream.
  Removed dead fail-open get_stream_user helper.

Egress (V5.1.1, V9.1.1/V14.1.3):
- Webhook delivery + CRUD reject SSRF destinations (private/loopback/link-local/
  metadata, IPv4-mapped, multi-A-record) via resolved-IP validation, pin to the
  vetted IP, and never auto-follow redirects. Opt-out via DECNET_WEBHOOK_ALLOW_PRIVATE.
- UpdaterClient pins the worker leaf cert SHA-256 against the stored per-host
  fingerprint (fail closed on missing/mismatch); DECNET_VERIFY_HOSTNAME now
  defaults True.

Hardening (V13.1.3, V4.1.4, V13.1.2):
- Rate-limit change-password (5/min), enroll-bundle (10/min), webhook-create
  (20/min), host-delete (20/min) via the existing slowapi limiter.
- Correct false 'global auth middleware' comment; document enroll-bundle proxy
  trust.

Correctness (BUG-7..11):
- BUG-7 unbound bus in finally; BUG-8 apply_ceiling clamps to min(base,ceiling);
  BUG-9 commit before emit; BUG-10 multi-actor rearm for sub-threshold identities;
  BUG-11 normalize naive timestamps to UTC.

Already-closed (no change): V14.1.1, V2.1.2/V3.1.3, V5.1.2. Tests added for
every fix; unanimous adversarial review.
2026-06-10 12:32:15 -04:00

106 lines
3.5 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Auth + user-management tables and DTOs."""
from datetime import datetime, timezone
from typing import List, Literal, Optional
from pydantic import BaseModel, Field as PydanticField
from sqlmodel import Field, SQLModel
class User(SQLModel, table=True):
__tablename__ = "users"
uuid: str = Field(primary_key=True)
username: str = Field(index=True, unique=True)
password_hash: str
role: str = Field(default="viewer")
must_change_password: bool = Field(default=False)
# Bulk session-revocation cutoff: any token whose ``iat`` predates this
# instant is rejected. Bumped to "now" on password change, role change,
# and admin password reset. NULL means no bulk revocation has occurred.
tokens_valid_from: Optional[datetime] = Field(default=None)
class RevokedToken(SQLModel, table=True):
"""A single JWT explicitly revoked via logout, keyed on its ``jti``.
This denylist holds only explicitly-revoked, not-yet-expired tokens, so it
stays tiny — ``revoke_token`` opportunistically prunes rows past expiry on
every insert. Bulk "log out everywhere" events use ``User.tokens_valid_from``
instead, because there is no per-user registry of live ``jti``s to enumerate.
"""
__tablename__ = "revoked_tokens"
jti: str = Field(primary_key=True)
user_uuid: str = Field(index=True) # User.uuid; no FK (independent audit row)
expires_at: datetime = Field(index=True) # token exp; row is prunable past this
revoked_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
# --- API Request/Response Models (Pydantic) ---
class Token(BaseModel):
access_token: str
token_type: str
must_change_password: bool = False
class LoginRequest(BaseModel):
username: str
password: str = PydanticField(..., max_length=72)
class ChangePasswordRequest(BaseModel):
old_password: str = PydanticField(..., max_length=72)
# min_length=12 aligns with the DECNET_ADMIN_PASSWORD >=12 policy. The
# forced first-login flow routes through /auth/change-password, so without a
# floor a seeded admin could clear must_change_password with a 1-char secret.
new_password: str = PydanticField(..., min_length=12, max_length=72)
class SSETicketResponse(BaseModel):
"""Single-use, short-lived opaque ticket the dashboard exchanges its header
JWT for, then passes to an SSE endpoint as ?ticket= (EventSource cannot set
an Authorization header). See decnet.web.dependencies SSE ticket store."""
ticket: str
expires_in: int
# --- Configuration Models ---
class CreateUserRequest(BaseModel):
username: str = PydanticField(..., min_length=1, max_length=64)
password: str = PydanticField(..., min_length=8, max_length=72)
role: Literal["admin", "viewer"] = "viewer"
class UpdateUserRoleRequest(BaseModel):
role: Literal["admin", "viewer"]
class ResetUserPasswordRequest(BaseModel):
new_password: str = PydanticField(..., min_length=8, max_length=72)
class DeploymentLimitRequest(BaseModel):
deployment_limit: int = PydanticField(..., ge=1, le=500)
class GlobalMutationIntervalRequest(BaseModel):
global_mutation_interval: str = PydanticField(..., pattern=r"^[1-9]\d*[mdMyY]$")
class UserResponse(BaseModel):
uuid: str
username: str
role: str
must_change_password: bool
class ConfigResponse(BaseModel):
role: str
deployment_limit: int
global_mutation_interval: str
class AdminConfigResponse(ConfigResponse):
users: List[UserResponse]