Files
Metamorph/backend/app/cli.py

122 lines
3.5 KiB
Python
Raw Permalink 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
"""Flask CLI entry point.
Used as `flask --app app.cli metamorph <subcommand>` (or via the make targets).
"""
from __future__ import annotations
import sys
import click
from flask import Flask
from flask.cli import AppGroup
from app.core.install_token import (
ensure_install_token,
log_install_token_banner,
regenerate_install_token,
)
from app.core.logging import configure_logging
from app.services.bootstrap import ensure_system_groups
from app.core.config import settings
def _create_cli_app() -> Flask:
configure_logging(settings.LOG_LEVEL)
return Flask("metamorph-cli")
app = _create_cli_app()
metamorph = AppGroup("metamorph", help="Metamorph admin commands.")
@metamorph.command("print-install-token")
@click.option(
"--force",
is_flag=True,
help="Always mint a fresh token even if one is already pending.",
)
def print_install_token(force: bool):
"""Mint and print the bootstrap install token (idempotent unless --force)."""
ensure_system_groups()
if force:
token = regenerate_install_token()
else:
token = ensure_install_token()
if token is None:
click.echo(
"No install token minted: either at least one user already exists, "
"or a token is already pending (use --force to mint a fresh one).",
err=True,
)
sys.exit(1)
log_install_token_banner(token)
@metamorph.command("seed-mitre")
@click.option(
"--source",
default=None,
help="STIX bundle source: local path or HTTPS URL. Defaults to the pinned MITRE Enterprise release.",
)
@click.option(
"--checksum-sha256",
"checksum_sha256",
default=None,
help="Expected sha256 of the bundle (required with a non-default --source URL unless --skip-checksum).",
)
@click.option(
"--skip-checksum",
is_flag=True,
help="Skip sha256 verification entirely (escape hatch for testing).",
)
def seed_mitre(source: str | None, checksum_sha256: str | None, skip_checksum: bool):
"""Seed/refresh the MITRE ATT&CK Enterprise reference tables.
Upserts on `external_id`. Re-running with the same source updates the
name/description/url and re-applies the techniquetactic mapping.
"""
from app.services.mitre_seed import (
MITRE_DEFAULT_SHA256,
MITRE_DEFAULT_URL,
seed_mitre as seed_mitre_svc,
)
if skip_checksum:
expected_sha = None
elif checksum_sha256:
expected_sha = checksum_sha256
elif source is None or source == MITRE_DEFAULT_URL:
expected_sha = MITRE_DEFAULT_SHA256
else:
expected_sha = None # let seed_mitre_svc decide whether to refuse
click.echo(
f"Seeding from {source or MITRE_DEFAULT_URL} "
f"(sha256 check: {'off' if skip_checksum else expected_sha or 'unverified'}) ...",
err=True,
)
try:
result = seed_mitre_svc(
source=source,
expected_sha256=expected_sha,
allow_unverified=skip_checksum,
)
except Exception as e: # noqa: BLE001
click.echo(f"seed-mitre failed: {e}", err=True)
sys.exit(2)
click.echo(
f" tactics: {result.tactics_upserted}, "
f"techniques: {result.techniques_upserted}, "
f"subtechniques: {result.subtechniques_upserted} "
f"(skipped orphans: {result.subtechniques_skipped_orphan}), "
f"links: {result.technique_tactic_links}, "
f"duration: {(result.finished_at - result.started_at).total_seconds():.1f}s",
err=True,
)
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
app.cli.add_command(metamorph)