Files
alro65 13a2867ef6 sprint-2.5: RBAC 4 roles + Studio bootable + Flash Console
End-to-end implementation per docs/sprint-2.5-plan.md.

New requirement added by user mid-sprint: 4-role RBAC (Super Admin /
Engineer / Owner / User) with dual-auth for Engineer flashing firmware,
plus a "mini Arduino IDE" inside the Studio.

Tests: pytest 231/231 green (129 Sprint 2 + 102 Sprint 2.5 new).

RBAC core (arautopilot/core/):

- rbac.py: 4 roles, 12 capabilities, immutable capability matrix,
  has() / capabilities_of() / require() / requires_dual_auth() helpers.
  Engineer flashing firmware needs SA approval; everything else is
  single-factor.
- user.py: User model with PBKDF2-HMAC-SHA256 PIN hashing (200k iters,
  16-byte salt, self-describing hash format for future migrations).
  4-8 digit numeric PINs enforced.
- user_store.py: JSON-backed user database. seed_demo_users() for
  first-run UX.
- audit.py: append-only JSONL audit log. AuditEvent with timestamp,
  user_id, role, action, target, outcome, reason, secondary_user_id
  for dual-auth, optional extra payload. Crypto signing of lines
  deferred to Sprint 8.

Studio GUI (arautopilot/studio/):

- app.py: real entry point (replaces Sprint 0 stub). --seed-demo
  populates demo users without launching GUI; --data-dir overrides the
  ~/.ar-autopilot/studio/ default.
- session.py: Session + SessionHolder. check() always audits the
  decision; verify_super_admin_pin() + log_dual_auth_grant() for
  dual-auth flows.
- login_window.py: modal login dialog with user picker + PIN field.
  Audits login attempts (success and bad-PIN denials).
- main_window.py: top-level window with sidebar (user + role + caps)
  and tab area (Overview, Flash Console, Project placeholder,
  Telemetry placeholder).
- flash_console.py: the "mini Arduino IDE". Lists serial ports via
  pyserial; picks firmware variant (esp32-dev / esp32-debug); compiles
  via 'pio run'; flashes via 'pio run -t upload --upload-port <port>';
  streams pio output to a dark-themed read-only console; supports
  cancel. For Engineer flashes, asks the Super Admin for their PIN
  inline before invoking pio. Records dual-auth grant + pio exit code
  in the audit log.

Dependencies:

- New [project.optional-dependencies] group 'studio': PySide6>=6.6,
  pyserial>=3.5, platformio>=6.1. Kept optional so the core can be
  installed in lean / CI environments.

Tests (arautopilot/tests/):

- test_rbac.py: 32 tests for capability matrix, dual-auth policy,
  no-privilege-escalation invariants, partial overlap between roles.
- test_user.py: 11 tests for PIN hashing, verification, salting,
  serialisation, field validators.
- test_audit.py: 9 tests for JSONL append, immutability, round-trip,
  corrupt-line detection, dual-auth event shape, blank-line tolerance.
- test_user_store.py: 10 tests for CRUD, persistence, role filtering,
  demo seed idempotency.
- test_session.py: 9 tests for capability checks + audit side effects,
  SA PIN verification, dual-auth recording, SessionHolder lifecycle.
- test_studio_smoke.py: 5 headless tests verifying Studio modules
  import without a display server, --seed-demo works, helpers safe to
  call without hardware.

NOT in Sprint 2.5 (intentional):
  - Crypto signing of audit log lines (hash-chain) -- Sprint 8
  - HWID binding of the user store -- Sprint 8
  - Project configurator + .appack compiler -- Sprint 4
  - Flutter bridge display -- Sprint 4
  - Telemetry dashboard tab -- Sprint 4
  - Serial monitor as a separate tab -- future enhancement

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:04:27 -04:00

144 lines
4.6 KiB
Python

"""User entity + PIN hashing.
Sprint 2.5: minimal model to back the Studio login. PINs are 4-8 digit
numeric strings hashed with PBKDF2-HMAC-SHA256 (stdlib, no extra
dependency) using a per-user 16-byte salt and a 200k-iteration work
factor. Hash format follows a self-describing string so future migrations
(argon2, scrypt) can co-exist.
Format::
pbkdf2_sha256$<iterations>$<base64(salt)>$<base64(hash)>
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import os
from datetime import UTC, datetime
from pydantic import BaseModel, ConfigDict, Field, field_validator
from arautopilot.core.ids import new_vessel_id
from arautopilot.core.rbac import Role
_PBKDF2_ITERATIONS = 200_000
_PBKDF2_SALT_LEN = 16
_PBKDF2_HASH_LEN = 32
_PBKDF2_ALGO = "sha256"
def _hash_pin(pin: str, *, iterations: int = _PBKDF2_ITERATIONS) -> str:
"""Hash a PIN with PBKDF2-HMAC-SHA256. Returns the self-describing string."""
if not _looks_like_pin(pin):
raise ValueError(
"PIN must be 4-8 digits (numeric). Use ASCII digits only."
)
salt = os.urandom(_PBKDF2_SALT_LEN)
digest = hashlib.pbkdf2_hmac(
_PBKDF2_ALGO, pin.encode("utf-8"), salt, iterations, _PBKDF2_HASH_LEN
)
return (
f"pbkdf2_{_PBKDF2_ALGO}${iterations}"
f"${base64.b64encode(salt).decode('ascii')}"
f"${base64.b64encode(digest).decode('ascii')}"
)
def _verify_pin(pin: str, hashed: str) -> bool:
"""Constant-time verification of a PIN against a stored hash."""
if not _looks_like_pin(pin):
return False
try:
scheme, iters_s, salt_b64, hash_b64 = hashed.split("$", 3)
except ValueError:
return False
if scheme != f"pbkdf2_{_PBKDF2_ALGO}":
return False
try:
iterations = int(iters_s)
salt = base64.b64decode(salt_b64)
expected = base64.b64decode(hash_b64)
except (ValueError, TypeError):
return False
candidate = hashlib.pbkdf2_hmac(
_PBKDF2_ALGO, pin.encode("utf-8"), salt, iterations, len(expected)
)
return hmac.compare_digest(candidate, expected)
def _looks_like_pin(pin: str) -> bool:
return bool(pin) and 4 <= len(pin) <= 8 and pin.isdigit()
class User(BaseModel):
"""A user of the Studio or the bridge display.
Field ``pin_hash`` is the only sensitive value persisted -- the plain
PIN never lives in memory longer than the duration of a verify call.
"""
model_config = ConfigDict(extra="forbid", validate_assignment=True)
user_id: str = Field(default_factory=lambda: new_vessel_id())
display_name: str = Field(min_length=1, max_length=80)
role: Role
pin_hash: str = Field(min_length=8, max_length=300)
vessel_id: str | None = Field(
default=None,
description="If set, this user belongs to one specific vessel "
"(Owners + their crew). None means cross-vessel scope "
"(Super Admin + Engineer).",
)
active: bool = True
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
last_login_at: datetime | None = None
@field_validator("pin_hash")
@classmethod
def _looks_like_hash(cls, v: str) -> str:
# Cheap structural validation -- does not verify the hash itself.
parts = v.split("$")
if len(parts) != 4 or not parts[0].startswith("pbkdf2_"):
raise ValueError(
"pin_hash must be in the form pbkdf2_<algo>$<iter>$<salt>$<hash>"
)
return v
# ----- Construction helpers -------------------------------------------
@classmethod
def create(
cls,
*,
display_name: str,
role: Role,
pin: str,
vessel_id: str | None = None,
) -> "User":
"""Construct a new user from a plaintext PIN.
The PIN is hashed before the model is built; the plaintext does
not survive this call.
"""
return cls(
display_name=display_name,
role=role,
pin_hash=_hash_pin(pin),
vessel_id=vessel_id,
)
# ----- Authentication --------------------------------------------------
def verify_pin(self, pin: str) -> bool:
"""Return True iff ``pin`` matches this user's stored hash."""
return _verify_pin(pin, self.pin_hash)
def set_pin(self, pin: str) -> "User":
"""Return a copy with a freshly-hashed new PIN."""
return self.model_copy(update={"pin_hash": _hash_pin(pin)})
def touch_login(self) -> "User":
"""Return a copy with ``last_login_at`` refreshed to now (UTC)."""
return self.model_copy(update={"last_login_at": datetime.now(UTC)})