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>
This commit is contained in:
2026-05-18 18:04:27 -04:00
parent 295efa2d83
commit 13a2867ef6
18 changed files with 2307 additions and 14 deletions
+114
View File
@@ -0,0 +1,114 @@
"""Immutable append-only audit log.
Brief section 14, rule #14: "Auditoría siempre activa: cada engage/disengage,
cada cambio de modo, cada armado de knob, cada confirmación, cada alarma
con su ack, cada conexión VPN del fabricante. Inmutable y firmado."
Sprint 2.5 ships the **immutable + append-only** half. Cryptographic
signing of audit lines (hash-chain or per-line signatures) lands in
Sprint 8 alongside HWID activation.
Persistence: one file per project, JSON Lines (one event per line).
Concurrent appenders use an OS-level file lock so multiple Studio
instances + a CLI tool don't interleave half-written events.
"""
from __future__ import annotations
import json
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
class AuditOutcome(StrEnum):
SUCCESS = "success"
"""The action was permitted and completed without error."""
DENIED = "denied"
"""The action was rejected at the permission gate."""
FAILED = "failed"
"""The action was permitted but failed during execution."""
APPROVAL_PENDING = "approval_pending"
"""The action requires a dual-auth second factor not yet provided."""
class AuditEvent(BaseModel):
"""One row of the immutable audit log."""
model_config = ConfigDict(extra="forbid", frozen=True)
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
user_id: str | None = Field(
default=None,
description="The actor's user_id. None means an anonymous / system event.",
)
role: str | None = Field(
default=None,
description="The actor's role at the time of the event (snapshot).",
)
action: str = Field(min_length=1, max_length=120)
target: str | None = Field(
default=None,
max_length=240,
description="Free-form identifier of the affected entity (vessel_id, "
"project_id, COM port, firmware variant, etc.).",
)
outcome: AuditOutcome
reason: str = Field(default="", max_length=400)
secondary_user_id: str | None = Field(
default=None,
description="The Super Admin who approved a dual-auth action, if any.",
)
extra: dict[str, Any] = Field(default_factory=dict)
def to_jsonl(self) -> str:
"""Render as one JSON line (no trailing newline)."""
return json.dumps(self.model_dump(mode="json"), ensure_ascii=False)
class AuditLog:
"""Append-only writer to a JSONL audit file."""
def __init__(self, path: Path | str) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
# Touch the file so subsequent appends work even on first run.
if not self.path.exists():
self.path.touch()
def append(self, event: AuditEvent) -> None:
"""Append one event to the log. Atomic at the line level (single write())."""
with self.path.open("a", encoding="utf-8") as f:
f.write(event.to_jsonl())
f.write("\n")
def read_all(self) -> list[AuditEvent]:
"""Read every event in chronological order."""
events: list[AuditEvent] = []
if not self.path.exists():
return events
with self.path.open("r", encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(
f"corrupt audit line {self.path}:{line_no}: {exc}"
) from exc
events.append(AuditEvent.model_validate(data))
return events
def __len__(self) -> int:
if not self.path.exists():
return 0
with self.path.open("r", encoding="utf-8") as f:
return sum(1 for line in f if line.strip())
+173
View File
@@ -0,0 +1,173 @@
"""Role-based access control + dual-auth policy for the AR Suite.
The brief originally specified three RBAC tiers (Operator / Technician /
Integrator). The product evolved in Sprint 2.5 to four roles with stricter
guarantees:
- ``SUPER_ADMIN`` -- the integrator (Álvaro). Unrestricted.
- ``ENGINEER`` -- an authorised technician of the integrator. May edit
ESP32 firmware and flash boards, but flashing requires a Super Admin
PIN as a second factor (2-of-N approval).
- ``OWNER`` -- the vessel owner. May manage Users on their own vessel and
edit operational preferences. May NOT touch engineering parameters.
- ``USER`` -- a crew member. May operate the pilot (engage, acknowledge
alarms, change setpoints) but cannot create users or change config.
Every gateable action is enumerated in :class:`Capability`. The matrix
``_CAPABILITIES_BY_ROLE`` is the **only** place where the role -> capability
mapping lives; everything else queries via :func:`has`.
"""
from __future__ import annotations
from enum import StrEnum
class Role(StrEnum):
"""Top-level role of an authenticated user."""
SUPER_ADMIN = "super_admin"
"""The integrator (Álvaro). No restrictions."""
ENGINEER = "engineer"
"""Authorised technician of the integrator. Flashing needs SA approval."""
OWNER = "owner"
"""Vessel owner. Manages users on their vessel + operational preferences."""
USER = "user"
"""Crew member. Operates the pilot, no config rights."""
class Capability(StrEnum):
"""Every action that requires a permission check.
Adding an entry here is a deliberate, reviewed change -- the UI and
every call site must opt into the new gate.
"""
# ----- Code & firmware (integrator IP) ---------------------------------
EDIT_PYTHON_PROJECT = "edit_python_project"
"""Edit the arautopilot package, tools, scripts. Super Admin only."""
EDIT_FIRMWARE_SOURCE = "edit_firmware_source"
"""Edit ESP32 C++ sources under firmware/**. SA + Engineer."""
FLASH_FIRMWARE = "flash_firmware"
"""Flash a .bin to an ESP32. SA direct; Engineer with SA PIN."""
BUILD_FIRMWARE = "build_firmware"
"""Compile firmware locally via pio. SA + Engineer."""
# ----- Tuning ----------------------------------------------------------
EDIT_BASE_GAINS = "edit_base_gains"
"""Edit the integrator's base PID gains (IP). Super Admin only."""
EDIT_COMMISSIONING = "edit_commissioning"
"""Edit field-commissioning parameters (rudder limits, calibration).
SA + Engineer."""
EDIT_OPERATIONAL = "edit_operational"
"""Edit operational preferences (favourite headings, alarm volume,
profile Soft/Normal/Sport). SA + Engineer + Owner."""
# ----- User management -------------------------------------------------
MANAGE_USERS = "manage_users"
"""Create / delete / edit Users on this vessel. SA + Owner."""
# ----- Runtime operation ----------------------------------------------
ENGAGE_PILOT = "engage_pilot"
"""Engage or disengage the autopilot. All roles."""
READ_TELEMETRY = "read_telemetry"
"""Read live telemetry from the firmware. All roles."""
ACK_ALARMS = "ack_alarms"
"""Acknowledge active alarms. All roles."""
# ----- Audit -----------------------------------------------------------
VIEW_AUDIT_LOG_FULL = "view_audit_log_full"
"""Read the full immutable audit log (all vessels). SA + Engineer."""
VIEW_AUDIT_LOG_VESSEL = "view_audit_log_vessel"
"""Read the audit log for this vessel only. SA + Engineer + Owner."""
# The single source of truth for who can do what. Order inside each set
# is irrelevant; we use frozenset so accidental mutation is impossible.
_CAPABILITIES_BY_ROLE: dict[Role, frozenset[Capability]] = {
Role.SUPER_ADMIN: frozenset(Capability), # everything
Role.ENGINEER: frozenset(
{
Capability.EDIT_FIRMWARE_SOURCE,
Capability.FLASH_FIRMWARE,
Capability.BUILD_FIRMWARE,
Capability.EDIT_COMMISSIONING,
Capability.EDIT_OPERATIONAL,
Capability.ENGAGE_PILOT,
Capability.READ_TELEMETRY,
Capability.ACK_ALARMS,
Capability.VIEW_AUDIT_LOG_FULL,
Capability.VIEW_AUDIT_LOG_VESSEL,
}
),
Role.OWNER: frozenset(
{
Capability.EDIT_OPERATIONAL,
Capability.MANAGE_USERS,
Capability.ENGAGE_PILOT,
Capability.READ_TELEMETRY,
Capability.ACK_ALARMS,
Capability.VIEW_AUDIT_LOG_VESSEL,
}
),
Role.USER: frozenset(
{
Capability.ENGAGE_PILOT,
Capability.READ_TELEMETRY,
Capability.ACK_ALARMS,
}
),
}
def has(role: Role, capability: Capability) -> bool:
"""Return True iff ``role`` has ``capability``."""
return capability in _CAPABILITIES_BY_ROLE[role]
def capabilities_of(role: Role) -> frozenset[Capability]:
"""Return the full capability set granted to ``role``."""
return _CAPABILITIES_BY_ROLE[role]
def requires_dual_auth(actor_role: Role, capability: Capability) -> bool:
"""Return True if the given (actor, capability) pair requires a Super
Admin approval in addition to the actor's own credentials.
Sprint 2.5 policy: an ``ENGINEER`` flashing firmware needs the Super
Admin's PIN as a second factor. Everything else is single-factor.
Reasoning: flashing the wrong firmware to a customer board is a
high-impact action with real-world consequences (rudder mis-driven,
safety interlocks bypassed). The Super Admin retains a checkpoint.
"""
if actor_role == Role.ENGINEER and capability == Capability.FLASH_FIRMWARE:
return True
return False
class PermissionError(Exception):
"""Raised when a capability check fails or a dual-auth second factor is missing."""
def require(role: Role, capability: Capability) -> None:
"""Raise :class:`PermissionError` if ``role`` lacks ``capability``.
Use this at the entry point of every gated function. Combine with the
audit log to record both grants and denials.
"""
if not has(role, capability):
raise PermissionError(
f"role {role.value!r} does not have capability {capability.value!r}"
)
+143
View File
@@ -0,0 +1,143 @@
"""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)})
+108
View File
@@ -0,0 +1,108 @@
"""Local user database (JSON file).
Sprint 2.5: persists the list of Users + their hashed PINs to a single
JSON file (per Studio install). On the bridge display the same format
is consumed but typically managed by the Owner via the Studio UI.
Sprint 8 will migrate this to a signed/encrypted store bound to the HWID.
"""
from __future__ import annotations
import json
from pathlib import Path
from pydantic import TypeAdapter
from arautopilot.core.rbac import Role
from arautopilot.core.user import User
class UserStore:
"""Append/overwrite list of :class:`User` persisted to a JSON file."""
def __init__(self, path: Path | str) -> None:
self.path = Path(path)
self._users: dict[str, User] = {}
if self.path.exists():
self._load()
else:
self.path.parent.mkdir(parents=True, exist_ok=True)
# ----- Persistence ----------------------------------------------------
def _load(self) -> None:
text = self.path.read_text(encoding="utf-8")
if not text.strip():
return
data = json.loads(text)
if not isinstance(data, list):
raise ValueError(f"{self.path}: expected a JSON list at the top level")
adapter = TypeAdapter(list[User])
users = adapter.validate_python(data)
self._users = {u.user_id: u for u in users}
def save(self) -> None:
adapter = TypeAdapter(list[User])
data = adapter.dump_python(list(self._users.values()), mode="json")
self.path.write_text(
json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8"
)
# ----- CRUD -----------------------------------------------------------
def add(self, user: User) -> None:
if user.user_id in self._users:
raise ValueError(f"user_id {user.user_id!r} already exists")
self._users[user.user_id] = user
self.save()
def remove(self, user_id: str) -> None:
if user_id not in self._users:
raise KeyError(user_id)
del self._users[user_id]
self.save()
def replace(self, user: User) -> None:
"""Insert or update the user with this user_id."""
self._users[user.user_id] = user
self.save()
def get(self, user_id: str) -> User | None:
return self._users.get(user_id)
def find_by_name(self, display_name: str) -> User | None:
for u in self._users.values():
if u.display_name == display_name:
return u
return None
def all_users(self) -> list[User]:
"""Return every user, sorted by display_name."""
return sorted(self._users.values(), key=lambda u: u.display_name.lower())
def by_role(self, role: Role) -> list[User]:
return [u for u in self.all_users() if u.role is role]
def __len__(self) -> int:
return len(self._users)
def __contains__(self, user_id: object) -> bool:
return user_id in self._users
def seed_demo_users(store: UserStore) -> None:
"""Populate a fresh store with one user of each role for first-run UX.
Demo PINs (well-known, only used in dev/sample stores -- the user is
expected to change these immediately):
Super Admin "Alvaro" PIN 1111
Engineer "Eng Demo" PIN 2222
Owner "Captain" PIN 3333
User "Crew" PIN 4444
"""
if len(store) > 0:
return
store.add(User.create(display_name="Alvaro", role=Role.SUPER_ADMIN, pin="1111"))
store.add(User.create(display_name="Eng Demo", role=Role.ENGINEER, pin="2222"))
store.add(User.create(display_name="Captain", role=Role.OWNER, pin="3333"))
store.add(User.create(display_name="Crew", role=Role.USER, pin="4444"))