Files
Metamorph/backend/app/core/jwt_tokens.py

98 lines
2.7 KiB
Python
Raw Normal View History

feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages Crypto + tokens - app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost= 64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown once, only the hash lives in the DB). - app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access 1h, refresh 30d. Services - services/auth.py: login, refresh with token rotation + reuse-detection chain revoke, logout (idempotent), change_password (forces logout-all). - services/invitations.py: create, preview, accept, revoke. Default 7d TTL. - services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam), consumes the install token, attaches the first user to admin. - core/install_token.py: mints, persists in settings, marks consumed, regenerate hook for /diag/reset. API - POST /setup (consume install token, create 1st admin) + GET /setup (status). - POST /auth/{login,refresh,logout,change-password} + GET /auth/me. - POST /invitations + GET /invitations + GET /invitations/preview/<token> + POST /invitations/accept/<token> + POST /invitations/<id>/revoke. - POST /diag/reset: test-only kill switch (truncate auth tables + mint fresh install token). Allowed in dev too (with WARNING log) so the e2e suite can run against a make-up stack; production locked out. Middleware - @require_auth populates g.current_user (snapshot dataclass, session closed before request handler runs). - @require_perm(*codes): atomic perm union check; admin group bypasses. Perm catalogue lands in M3, scaffolding here. - flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on /auth/change-password & /setup, 10–20/min on invitation endpoints. Disabled in APP_ENV=test. CLI - flask --app app.cli metamorph print-install-token [--force] - flask --app app.cli metamorph seed-mitre (M4 placeholder) Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/. Email validation: app.api._validation.Email permissive RFC-shape regex so internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's deliverability check is too strict for red-team labs. Frontend - lib/{api,auth}.ts: access token in module memory, refresh cookie, automatic 401-retry via /auth/refresh, useAuth() hook. - components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx. - pages/{Login,Setup,Register,Profile}. Testing - tests/test_auth_flow.py: 15 integration tests (24 backend total). - e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total). - tasks/testing-m2.md. DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass applied (Secure unconditional, refresh limit 10/min/IP). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 06:16:48 +02:00
"""JWT encoding / decoding.
Two token types:
- `access` short-lived (1 h), in `Authorization: Bearer ...` headers, kept
client-side **in memory** only (cf. spec §M2).
- `refresh` long-lived (30 d), in an HTTPOnly Secure SameSite=Strict cookie
scoped to `/api/v1/auth/`. Rotated on every successful refresh,
old `jti` revoked.
We sign HS256 with `settings.JWT_SECRET`. The `jti` claim links each token to
its DB row in `refresh_tokens` for revocation; access tokens are stateless.
"""
from __future__ import annotations
import secrets
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Literal
import jwt
from app.core.config import settings
ACCESS_TOKEN_TTL = timedelta(hours=1)
REFRESH_TOKEN_TTL = timedelta(days=30)
ALGORITHM = "HS256"
ISSUER = "metamorph"
TokenType = Literal["access", "refresh"]
@dataclass(frozen=True)
class TokenClaims:
sub: str # user id (UUID as string)
type: TokenType
jti: str
iat: datetime
exp: datetime
def _now() -> datetime:
return datetime.now(tz=timezone.utc)
def generate_jti() -> str:
"""Compact, URL-safe random identifier (≈22 chars)."""
return secrets.token_urlsafe(16)
def encode_token(
user_id: uuid.UUID | str,
token_type: TokenType,
*,
jti: str | None = None,
) -> tuple[str, TokenClaims]:
"""Return `(jwt_string, claims)`. `jti` is generated if not provided."""
now = _now()
ttl = ACCESS_TOKEN_TTL if token_type == "access" else REFRESH_TOKEN_TTL
claims = TokenClaims(
sub=str(user_id),
type=token_type,
jti=jti or generate_jti(),
iat=now,
exp=now + ttl,
)
payload = {
"iss": ISSUER,
"sub": claims.sub,
"type": claims.type,
"jti": claims.jti,
"iat": int(claims.iat.timestamp()),
"exp": int(claims.exp.timestamp()),
}
return jwt.encode(payload, settings.JWT_SECRET, algorithm=ALGORITHM), claims
def decode_token(token: str, *, expected_type: TokenType) -> TokenClaims:
"""Decode and validate a JWT. Raises `jwt.PyJWTError` on any failure."""
payload = jwt.decode(
token,
settings.JWT_SECRET,
algorithms=[ALGORITHM],
issuer=ISSUER,
options={"require": ["sub", "type", "jti", "iat", "exp"]},
)
if payload["type"] != expected_type:
raise jwt.InvalidTokenError(f"expected {expected_type} token, got {payload['type']}")
return TokenClaims(
sub=payload["sub"],
type=payload["type"],
jti=payload["jti"],
iat=datetime.fromtimestamp(payload["iat"], tz=timezone.utc),
exp=datetime.fromtimestamp(payload["exp"], tz=timezone.utc),
)