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:
+98
-12
@@ -1,24 +1,110 @@
|
||||
"""Studio application entry point — Sprint 4 stub.
|
||||
"""AR-Autopilot Studio application entry point.
|
||||
|
||||
This module is intentionally a stub. The real PySide6 ``QApplication`` and
|
||||
``MainWindow`` arrive in Sprint 4. Trying to launch the Studio now will
|
||||
print a friendly notice and exit cleanly.
|
||||
Usage:
|
||||
|
||||
python studio_main.py # launch the GUI
|
||||
python -m arautopilot.studio.app # same
|
||||
python -m arautopilot.studio.app --seed-demo
|
||||
# populate the local user store
|
||||
# with one of each role + default
|
||||
# PINs (1111 SA, 2222 Eng,
|
||||
# 3333 Owner, 4444 User)
|
||||
|
||||
The Studio runs locally on the integrator's workstation. The dedicated
|
||||
bridge display is a separate Flutter app (Sprint 4+); the two share the
|
||||
same data model (``arautopilot.core``) and Modbus register map
|
||||
(``arautopilot.shared.modbus_register_map``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from arautopilot.core.audit import AuditLog
|
||||
from arautopilot.core.user_store import UserStore, seed_demo_users
|
||||
from arautopilot.studio.session import studio_data_dir
|
||||
|
||||
|
||||
def run() -> int:
|
||||
"""Stub entry point. Will be replaced by a real ``QApplication`` in Sprint 4."""
|
||||
print(
|
||||
"AR-Autopilot Studio — Sprint 0 stub.\n"
|
||||
"The Studio GUI is implemented starting in Sprint 4.\n"
|
||||
"For now, use the core API (`arautopilot.core`) and the demo:\n"
|
||||
" python examples/sprint0_demo.py"
|
||||
def run(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--seed-demo",
|
||||
action="store_true",
|
||||
help="Populate the local user store with one of each role + default "
|
||||
"PINs (1111/2222/3333/4444). Then exit.",
|
||||
)
|
||||
return 0
|
||||
parser.add_argument(
|
||||
"--data-dir",
|
||||
type=Path,
|
||||
default=None,
|
||||
help="Override the per-user data directory. Defaults to "
|
||||
"~/.ar-autopilot/studio/.",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
data_dir = args.data_dir or studio_data_dir()
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
user_store = UserStore(data_dir / "users.json")
|
||||
audit_log = AuditLog(data_dir / "audit.jsonl")
|
||||
|
||||
if args.seed_demo:
|
||||
before = len(user_store)
|
||||
seed_demo_users(user_store)
|
||||
after = len(user_store)
|
||||
print(
|
||||
f"User store at {user_store.path}: {before} -> {after} users.\n"
|
||||
"Demo PINs: 1111 (Super Admin), 2222 (Engineer), 3333 (Owner), "
|
||||
"4444 (User).\n"
|
||||
"Change them with the Studio's user manager (Sprint 4+) before "
|
||||
"shipping to a customer."
|
||||
)
|
||||
return 0
|
||||
|
||||
# Lazy-import the Qt machinery so that --seed-demo (and pytest collection
|
||||
# of this module) does not depend on a working display server.
|
||||
try:
|
||||
from PySide6.QtWidgets import QApplication, QMessageBox
|
||||
except ImportError:
|
||||
sys.stderr.write(
|
||||
"PySide6 is not installed. Run:\n\n"
|
||||
" pip install -e \".[studio]\"\n\n"
|
||||
"or:\n\n"
|
||||
" pip install PySide6 pyserial\n"
|
||||
)
|
||||
return 2
|
||||
|
||||
from arautopilot.studio.login_window import LoginDialog
|
||||
from arautopilot.studio.main_window import StudioMainWindow
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName("AR-Autopilot Studio")
|
||||
|
||||
if len(user_store) == 0:
|
||||
QMessageBox.information(
|
||||
None,
|
||||
"No users",
|
||||
"The local user store is empty. The Studio will seed it with "
|
||||
"demo users (PINs 1111/2222/3333/4444). Change them immediately "
|
||||
"in production.",
|
||||
)
|
||||
seed_demo_users(user_store)
|
||||
|
||||
login = LoginDialog(store=user_store, audit=audit_log)
|
||||
win_holder: list[StudioMainWindow] = []
|
||||
|
||||
def on_logged_in(_session: object) -> None:
|
||||
from arautopilot.studio.session import SessionHolder
|
||||
session = SessionHolder.require()
|
||||
win = StudioMainWindow(session)
|
||||
win.show()
|
||||
win_holder.append(win)
|
||||
|
||||
login.logged_in.connect(on_logged_in)
|
||||
if login.exec() == 0 and not win_holder:
|
||||
return 0
|
||||
return app.exec()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
"""Flash Console widget -- "mini Arduino IDE" inside the Studio.
|
||||
|
||||
What it does
|
||||
------------
|
||||
- Enumerates available serial ports (pyserial).
|
||||
- Lets the operator pick the firmware variant (``esp32-dev`` or
|
||||
``esp32-debug``).
|
||||
- Compiles the firmware via PlatformIO (`pio run -e <variant> -d
|
||||
firmware/ar_autopilot_v1`).
|
||||
- Flashes the firmware via `pio run -t upload --upload-port <port>`.
|
||||
- Streams the build/flash output to a read-only text area.
|
||||
|
||||
Permissions
|
||||
-----------
|
||||
- Super Admin: flashes directly, single factor.
|
||||
- Engineer: flashes only after providing the Super Admin's PIN. The
|
||||
dialog asks for the SA's PIN inline; on success the audit
|
||||
trail records both engineer's and SA's user_ids.
|
||||
- Owner / User: the Flash Console button is hidden.
|
||||
|
||||
The actual ``pio`` invocations run in a worker thread so the GUI never
|
||||
blocks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from PySide6.QtCore import QObject, QThread, Signal
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFormLayout,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPlainTextEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from arautopilot.core.audit import AuditOutcome
|
||||
from arautopilot.core.rbac import Capability
|
||||
from arautopilot.studio.session import Session
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
FIRMWARE_DIR = REPO_ROOT / "firmware" / "ar_autopilot_v1"
|
||||
PIO_EXE_CANDIDATES = [
|
||||
REPO_ROOT / ".venv" / "Scripts" / "pio.exe", # Windows venv
|
||||
REPO_ROOT / ".venv" / "bin" / "pio", # POSIX venv
|
||||
Path("pio"), # PATH fallback
|
||||
]
|
||||
|
||||
|
||||
def _find_pio() -> Path | None:
|
||||
for c in PIO_EXE_CANDIDATES:
|
||||
if c.exists():
|
||||
return c
|
||||
# Last-resort PATH lookup -- subprocess will find it.
|
||||
return Path("pio")
|
||||
|
||||
|
||||
def list_serial_ports() -> list[tuple[str, str]]:
|
||||
"""Return ``[(device, description), ...]`` for every available port."""
|
||||
try:
|
||||
from serial.tools import list_ports # type: ignore[import-untyped]
|
||||
except ImportError:
|
||||
return []
|
||||
return [(p.device, p.description or "") for p in list_ports.comports()]
|
||||
|
||||
|
||||
class _PioWorker(QObject):
|
||||
"""Runs `pio ...` in a background thread and streams stdout."""
|
||||
|
||||
line = Signal(str) # one line of output (no trailing \n)
|
||||
finished_ok = Signal(int) # exit code on success
|
||||
failed = Signal(str) # error description
|
||||
|
||||
def __init__(self, argv: list[str], cwd: Path) -> None:
|
||||
super().__init__()
|
||||
self._argv = argv
|
||||
self._cwd = cwd
|
||||
self._proc: subprocess.Popen[str] | None = None
|
||||
self._cancel = False
|
||||
|
||||
def run(self) -> None:
|
||||
try:
|
||||
env = os.environ.copy()
|
||||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||||
self._proc = subprocess.Popen(
|
||||
self._argv,
|
||||
cwd=str(self._cwd),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
env=env,
|
||||
)
|
||||
assert self._proc.stdout is not None
|
||||
for raw_line in self._proc.stdout:
|
||||
if self._cancel:
|
||||
break
|
||||
self.line.emit(raw_line.rstrip("\n"))
|
||||
code = self._proc.wait()
|
||||
self.finished_ok.emit(code)
|
||||
except FileNotFoundError as exc:
|
||||
self.failed.emit(f"executable not found: {exc}")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.failed.emit(f"unexpected error: {exc}")
|
||||
|
||||
def cancel(self) -> None:
|
||||
self._cancel = True
|
||||
if self._proc is not None:
|
||||
try:
|
||||
self._proc.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class FlashConsoleWidget(QWidget):
|
||||
"""A self-contained Flash Console for embedding in the main window."""
|
||||
|
||||
def __init__(self, session: Session, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self._session = session
|
||||
self._thread: QThread | None = None
|
||||
self._worker: _PioWorker | None = None
|
||||
self._build_ui()
|
||||
self.refresh_ports()
|
||||
|
||||
# ----- UI ------------------------------------------------------------
|
||||
def _build_ui(self) -> None:
|
||||
outer = QVBoxLayout(self)
|
||||
outer.setContentsMargins(8, 8, 8, 8)
|
||||
|
||||
header = QLabel(
|
||||
"<b>Flash Console</b><br/>"
|
||||
"Compile and flash AR-Autopilot firmware to an AR-NMEA-IO board.<br/>"
|
||||
f"Logged in as <b>{self._session.user.display_name}</b> "
|
||||
f"({self._session.role.value})."
|
||||
)
|
||||
header.setTextFormat(0x1) # PlainText would lose <br/>; RichText = 1
|
||||
header.setWordWrap(True)
|
||||
outer.addWidget(header)
|
||||
|
||||
form_group = QGroupBox("Target")
|
||||
form = QFormLayout(form_group)
|
||||
|
||||
port_row = QHBoxLayout()
|
||||
self._port_combo = QComboBox()
|
||||
self._port_combo.setMinimumWidth(280)
|
||||
port_row.addWidget(self._port_combo, stretch=1)
|
||||
refresh_btn = QPushButton("Refresh")
|
||||
refresh_btn.clicked.connect(self.refresh_ports)
|
||||
port_row.addWidget(refresh_btn)
|
||||
form.addRow("Serial port:", port_row)
|
||||
|
||||
self._variant_combo = QComboBox()
|
||||
self._variant_combo.addItem("esp32-dev (release, -Os)", userData="esp32-dev")
|
||||
self._variant_combo.addItem("esp32-debug (-O0, verbose)", userData="esp32-debug")
|
||||
form.addRow("Variant:", self._variant_combo)
|
||||
|
||||
outer.addWidget(form_group)
|
||||
|
||||
action_row = QHBoxLayout()
|
||||
self._compile_btn = QPushButton("Compile only")
|
||||
self._compile_btn.clicked.connect(self._on_compile)
|
||||
action_row.addWidget(self._compile_btn)
|
||||
|
||||
self._flash_btn = QPushButton("Compile + Flash")
|
||||
self._flash_btn.clicked.connect(self._on_flash)
|
||||
action_row.addWidget(self._flash_btn)
|
||||
|
||||
self._cancel_btn = QPushButton("Cancel")
|
||||
self._cancel_btn.setEnabled(False)
|
||||
self._cancel_btn.clicked.connect(self._on_cancel)
|
||||
action_row.addWidget(self._cancel_btn)
|
||||
action_row.addStretch(1)
|
||||
outer.addLayout(action_row)
|
||||
|
||||
self._output = QPlainTextEdit()
|
||||
self._output.setReadOnly(True)
|
||||
self._output.setStyleSheet(
|
||||
"background-color: #0d1117; color: #c9d1d9; font-family: Consolas, "
|
||||
"'Cascadia Mono', monospace; font-size: 11px;"
|
||||
)
|
||||
outer.addWidget(self._output, stretch=1)
|
||||
|
||||
# Gate the buttons by capability.
|
||||
if not self._session.can(Capability.BUILD_FIRMWARE):
|
||||
self._compile_btn.setEnabled(False)
|
||||
self._compile_btn.setToolTip("Your role cannot build firmware.")
|
||||
if not self._session.can(Capability.FLASH_FIRMWARE):
|
||||
self._flash_btn.setEnabled(False)
|
||||
self._flash_btn.setToolTip("Your role cannot flash firmware.")
|
||||
|
||||
# ----- Public --------------------------------------------------------
|
||||
def refresh_ports(self) -> None:
|
||||
self._port_combo.clear()
|
||||
ports = list_serial_ports()
|
||||
if not ports:
|
||||
self._port_combo.addItem("(no boards found)", userData=None)
|
||||
else:
|
||||
for device, desc in ports:
|
||||
label = f"{device} -- {desc}" if desc else device
|
||||
self._port_combo.addItem(label, userData=device)
|
||||
|
||||
# ----- Handlers ------------------------------------------------------
|
||||
def _on_compile(self) -> None:
|
||||
if not self._session.check(Capability.BUILD_FIRMWARE, target=self._variant()):
|
||||
QMessageBox.warning(self, "Permission denied",
|
||||
"Your role cannot build firmware.")
|
||||
return
|
||||
self._run_pio(["run", "-e", self._variant()])
|
||||
|
||||
def _on_flash(self) -> None:
|
||||
# Capability gate (logged either way).
|
||||
if not self._session.check(Capability.FLASH_FIRMWARE,
|
||||
target=self._port_or_none()):
|
||||
QMessageBox.warning(self, "Permission denied",
|
||||
"Your role cannot flash firmware.")
|
||||
return
|
||||
port = self._port_or_none()
|
||||
if port is None:
|
||||
QMessageBox.warning(self, "No port",
|
||||
"No serial port selected. Connect a board and "
|
||||
"click Refresh.")
|
||||
return
|
||||
|
||||
# Dual-auth check: Engineer needs Super Admin PIN.
|
||||
if self._session.needs_dual_auth(Capability.FLASH_FIRMWARE):
|
||||
sa_user = _ask_super_admin_pin(self, self._session)
|
||||
if sa_user is None:
|
||||
self._session.log_action(
|
||||
"flash_firmware",
|
||||
outcome=AuditOutcome.APPROVAL_PENDING,
|
||||
target=f"{port}:{self._variant()}",
|
||||
reason="Super Admin approval refused or cancelled",
|
||||
)
|
||||
return
|
||||
self._session.log_dual_auth_grant(
|
||||
Capability.FLASH_FIRMWARE,
|
||||
sa_user,
|
||||
target=f"{port}:{self._variant()}",
|
||||
extra={"variant": self._variant()},
|
||||
)
|
||||
|
||||
self._run_pio([
|
||||
"run", "-e", self._variant(), "-t", "upload",
|
||||
"--upload-port", port,
|
||||
])
|
||||
|
||||
def _on_cancel(self) -> None:
|
||||
if self._worker is not None:
|
||||
self._worker.cancel()
|
||||
self._append_line("[cancelled by operator]")
|
||||
|
||||
# ----- pio worker ----------------------------------------------------
|
||||
def _run_pio(self, args: list[str]) -> None:
|
||||
pio = _find_pio()
|
||||
argv = [str(pio), *args]
|
||||
self._output.clear()
|
||||
self._append_line(f"$ {' '.join(shlex.quote(a) for a in argv)}")
|
||||
self._set_running(True)
|
||||
|
||||
self._thread = QThread(self)
|
||||
self._worker = _PioWorker(argv=argv, cwd=FIRMWARE_DIR)
|
||||
self._worker.moveToThread(self._thread)
|
||||
self._thread.started.connect(self._worker.run)
|
||||
self._worker.line.connect(self._append_line)
|
||||
self._worker.finished_ok.connect(self._on_pio_done)
|
||||
self._worker.failed.connect(self._on_pio_failed)
|
||||
self._worker.finished_ok.connect(self._thread.quit)
|
||||
self._worker.failed.connect(self._thread.quit)
|
||||
self._thread.finished.connect(self._cleanup_thread)
|
||||
self._thread.start()
|
||||
|
||||
def _on_pio_done(self, code: int) -> None:
|
||||
self._append_line(f"[pio exit code: {code}]")
|
||||
outcome = AuditOutcome.SUCCESS if code == 0 else AuditOutcome.FAILED
|
||||
self._session.log_action(
|
||||
"flash_firmware_run",
|
||||
outcome=outcome,
|
||||
target=self._port_or_none(),
|
||||
extra={"variant": self._variant(), "exit_code": code},
|
||||
)
|
||||
|
||||
def _on_pio_failed(self, msg: str) -> None:
|
||||
self._append_line(f"[pio failed: {msg}]")
|
||||
self._session.log_action(
|
||||
"flash_firmware_run",
|
||||
outcome=AuditOutcome.FAILED,
|
||||
target=self._port_or_none(),
|
||||
reason=msg,
|
||||
)
|
||||
|
||||
def _cleanup_thread(self) -> None:
|
||||
self._set_running(False)
|
||||
if self._thread is not None:
|
||||
self._thread.deleteLater()
|
||||
self._thread = None
|
||||
if self._worker is not None:
|
||||
self._worker.deleteLater()
|
||||
self._worker = None
|
||||
|
||||
def _set_running(self, running: bool) -> None:
|
||||
self._compile_btn.setEnabled(
|
||||
not running and self._session.can(Capability.BUILD_FIRMWARE)
|
||||
)
|
||||
self._flash_btn.setEnabled(
|
||||
not running and self._session.can(Capability.FLASH_FIRMWARE)
|
||||
)
|
||||
self._cancel_btn.setEnabled(running)
|
||||
|
||||
def _append_line(self, line: str) -> None:
|
||||
self._output.appendPlainText(line)
|
||||
|
||||
def _variant(self) -> str:
|
||||
return str(self._variant_combo.currentData())
|
||||
|
||||
def _port_or_none(self) -> str | None:
|
||||
v = self._port_combo.currentData()
|
||||
return None if v is None else str(v)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Super Admin PIN approval dialog
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ask_super_admin_pin(parent: QWidget, session: Session):
|
||||
"""Modal dialog asking the SA for their PIN. Returns the SA :class:`User`
|
||||
on success, ``None`` on cancel / bad PIN."""
|
||||
dlg = QDialog(parent)
|
||||
dlg.setWindowTitle("Super Admin approval required")
|
||||
dlg.setModal(True)
|
||||
|
||||
layout = QVBoxLayout(dlg)
|
||||
layout.addWidget(QLabel(
|
||||
"Flashing firmware as an Engineer requires Super Admin approval.\n"
|
||||
"Ask the Super Admin to enter their PIN below."
|
||||
))
|
||||
form = QFormLayout()
|
||||
pin_field = QLineEdit()
|
||||
pin_field.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
pin_field.setMaxLength(8)
|
||||
form.addRow("Super Admin PIN:", pin_field)
|
||||
layout.addLayout(form)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
result_holder: dict[str, Optional[object]] = {"user": None}
|
||||
|
||||
def _accept() -> None:
|
||||
sa = session.verify_super_admin_pin(pin_field.text())
|
||||
if sa is None:
|
||||
QMessageBox.warning(dlg, "Approval failed",
|
||||
"Incorrect Super Admin PIN.")
|
||||
pin_field.clear()
|
||||
pin_field.setFocus()
|
||||
return
|
||||
result_holder["user"] = sa
|
||||
dlg.accept()
|
||||
|
||||
buttons.accepted.connect(_accept)
|
||||
buttons.rejected.connect(dlg.reject)
|
||||
dlg.exec()
|
||||
return result_holder["user"]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Standalone smoke test
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover -- manual launch helper
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from arautopilot.core.audit import AuditLog
|
||||
from arautopilot.core.user import User
|
||||
from arautopilot.core.user_store import UserStore
|
||||
from arautopilot.core.rbac import Role
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
store = UserStore(REPO_ROOT / ".tmp" / "users.json")
|
||||
if len(store) == 0:
|
||||
store.add(User.create(display_name="Smoke", role=Role.SUPER_ADMIN, pin="0000"))
|
||||
sa = next(iter(store.by_role(Role.SUPER_ADMIN)))
|
||||
audit = AuditLog(REPO_ROOT / ".tmp" / "audit.jsonl")
|
||||
session = Session(user=sa, store=store, audit=audit)
|
||||
w = FlashConsoleWidget(session)
|
||||
w.resize(800, 600)
|
||||
w.show()
|
||||
sys.exit(app.exec())
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Studio login window (PySide6).
|
||||
|
||||
Lists every active user from the local store, lets the operator pick
|
||||
themselves and enter their PIN. On success, populates the global
|
||||
:class:`SessionHolder` and emits :pyattr:`logged_in`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFormLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from arautopilot.core.audit import AuditEvent, AuditLog, AuditOutcome
|
||||
from arautopilot.core.user_store import UserStore
|
||||
from arautopilot.studio.session import Session, SessionHolder
|
||||
|
||||
|
||||
class LoginDialog(QDialog):
|
||||
"""Modal login dialog. Emits :pyattr:`logged_in(session)` on success."""
|
||||
|
||||
logged_in = Signal(object) # Session
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: UserStore,
|
||||
audit: AuditLog,
|
||||
parent: object | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self._store = store
|
||||
self._audit = audit
|
||||
self.setWindowTitle("AR-Autopilot Studio -- Login")
|
||||
self.setModal(True)
|
||||
self.setMinimumWidth(360)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
intro = QLabel("Select your user and enter the PIN.")
|
||||
intro.setWordWrap(True)
|
||||
layout.addWidget(intro)
|
||||
|
||||
form = QFormLayout()
|
||||
self._user_combo = QComboBox()
|
||||
for user in self._store.all_users():
|
||||
if not user.active:
|
||||
continue
|
||||
self._user_combo.addItem(
|
||||
f"{user.display_name} -- {user.role.value}",
|
||||
userData=user.user_id,
|
||||
)
|
||||
form.addRow("User:", self._user_combo)
|
||||
|
||||
self._pin_field = QLineEdit()
|
||||
self._pin_field.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self._pin_field.setMaxLength(8)
|
||||
self._pin_field.setPlaceholderText("4-8 digits")
|
||||
self._pin_field.setInputMethodHints(Qt.InputMethodHint.ImhDigitsOnly)
|
||||
form.addRow("PIN:", self._pin_field)
|
||||
layout.addLayout(form)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(self._try_login)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
if self._user_combo.count() == 0:
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"No users available",
|
||||
"The local user store is empty. Run the demo seed:\n\n"
|
||||
" python -m arautopilot.studio.app --seed-demo",
|
||||
)
|
||||
|
||||
# ----- Internal -------------------------------------------------------
|
||||
def _try_login(self) -> None:
|
||||
user_id = self._user_combo.currentData()
|
||||
pin = self._pin_field.text()
|
||||
user = self._store.get(user_id) if user_id else None
|
||||
if user is None:
|
||||
QMessageBox.warning(self, "Login", "Pick a user.")
|
||||
return
|
||||
if not user.active:
|
||||
QMessageBox.warning(self, "Login", "This user is disabled.")
|
||||
return
|
||||
if not user.verify_pin(pin):
|
||||
self._audit.append(
|
||||
AuditEvent(
|
||||
user_id=user.user_id,
|
||||
role=user.role.value,
|
||||
action="login",
|
||||
outcome=AuditOutcome.DENIED,
|
||||
reason="bad PIN",
|
||||
)
|
||||
)
|
||||
QMessageBox.warning(self, "Login", "Incorrect PIN.")
|
||||
self._pin_field.clear()
|
||||
self._pin_field.setFocus()
|
||||
return
|
||||
|
||||
touched = user.touch_login()
|
||||
self._store.replace(touched)
|
||||
self._audit.append(
|
||||
AuditEvent(
|
||||
user_id=touched.user_id,
|
||||
role=touched.role.value,
|
||||
action="login",
|
||||
outcome=AuditOutcome.SUCCESS,
|
||||
)
|
||||
)
|
||||
session = Session(user=touched, store=self._store, audit=self._audit)
|
||||
SessionHolder.set(session)
|
||||
self.logged_in.emit(session)
|
||||
self.accept()
|
||||
@@ -1,4 +1,110 @@
|
||||
"""Studio main window — Sprint 4 stub.
|
||||
"""Studio main window (PySide6) -- Sprint 2.5.
|
||||
|
||||
Reserved namespace for the PySide6 ``QMainWindow`` arriving in Sprint 4.
|
||||
Three areas:
|
||||
|
||||
- Sidebar (left) -- user + role + capabilities they hold.
|
||||
- Central tab area -- Flash Console (Sprint 2.5) + placeholders for the
|
||||
project configurator that lands in Sprint 4.
|
||||
- Status bar -- session info + audit log path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import (
|
||||
QLabel,
|
||||
QListWidget,
|
||||
QMainWindow,
|
||||
QSplitter,
|
||||
QStatusBar,
|
||||
QTabWidget,
|
||||
QTextEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from arautopilot.core.rbac import capabilities_of
|
||||
from arautopilot.studio.flash_console import FlashConsoleWidget
|
||||
from arautopilot.studio.session import Session
|
||||
from arautopilot.version import __version__
|
||||
|
||||
|
||||
class StudioMainWindow(QMainWindow):
|
||||
"""Top-level Studio window."""
|
||||
|
||||
def __init__(self, session: Session) -> None:
|
||||
super().__init__()
|
||||
self._session = session
|
||||
self.setWindowTitle(
|
||||
f"AR-Autopilot Studio v{__version__} -- "
|
||||
f"{session.user.display_name} ({session.role.value})"
|
||||
)
|
||||
self.resize(1100, 700)
|
||||
|
||||
splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
splitter.addWidget(self._build_sidebar())
|
||||
splitter.addWidget(self._build_central())
|
||||
splitter.setStretchFactor(0, 0)
|
||||
splitter.setStretchFactor(1, 1)
|
||||
splitter.setSizes([260, 840])
|
||||
self.setCentralWidget(splitter)
|
||||
|
||||
status = QStatusBar(self)
|
||||
status.showMessage(f"Audit log: {session.audit.path}")
|
||||
self.setStatusBar(status)
|
||||
|
||||
# ----- UI ------------------------------------------------------------
|
||||
def _build_sidebar(self) -> QWidget:
|
||||
w = QWidget()
|
||||
layout = QVBoxLayout(w)
|
||||
layout.setContentsMargins(8, 8, 8, 8)
|
||||
layout.addWidget(QLabel(
|
||||
f"<b>{self._session.user.display_name}</b><br/>"
|
||||
f"<i>{self._session.role.value}</i>"
|
||||
))
|
||||
layout.addWidget(QLabel("<b>Capabilities</b>"))
|
||||
caps = QListWidget()
|
||||
for cap in sorted(capabilities_of(self._session.role), key=lambda c: c.value):
|
||||
caps.addItem(cap.value)
|
||||
layout.addWidget(caps, stretch=1)
|
||||
return w
|
||||
|
||||
def _build_central(self) -> QWidget:
|
||||
tabs = QTabWidget()
|
||||
|
||||
tabs.addTab(self._build_overview_tab(), "Overview")
|
||||
tabs.addTab(FlashConsoleWidget(self._session), "Flash Console")
|
||||
tabs.addTab(self._placeholder_tab(
|
||||
"Project configurator -- Sprint 4.\n\n"
|
||||
"Will let you create / edit a per-vessel ProjectConfig and "
|
||||
"compile it into an .appack for deployment."
|
||||
), "Project")
|
||||
tabs.addTab(self._placeholder_tab(
|
||||
"Telemetry -- Sprint 4.\n\n"
|
||||
"Live Modbus telemetry from the connected AR-NMEA-IO board."
|
||||
), "Telemetry")
|
||||
return tabs
|
||||
|
||||
def _build_overview_tab(self) -> QWidget:
|
||||
w = QWidget()
|
||||
layout = QVBoxLayout(w)
|
||||
layout.addWidget(QLabel(
|
||||
"<h2>AR-Autopilot Studio</h2>"
|
||||
"<p>Welcome. Use the <b>Flash Console</b> tab to compile and "
|
||||
"flash firmware to an AR-NMEA-IO board.</p>"
|
||||
"<p>The <b>Project</b> tab (Sprint 4) will let you configure a "
|
||||
"vessel and produce a deployable <code>.appack</code>.</p>"
|
||||
"<p>Every action you take is recorded in the audit log "
|
||||
"(see status bar at the bottom).</p>"
|
||||
))
|
||||
layout.addStretch(1)
|
||||
return w
|
||||
|
||||
def _placeholder_tab(self, text: str) -> QWidget:
|
||||
w = QWidget()
|
||||
layout = QVBoxLayout(w)
|
||||
edit = QTextEdit()
|
||||
edit.setReadOnly(True)
|
||||
edit.setPlainText(text)
|
||||
layout.addWidget(edit)
|
||||
return w
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Authenticated session state for the Studio.
|
||||
|
||||
A ``Session`` is the runtime context of a logged-in user. It carries the
|
||||
:class:`User`, exposes capability checks, and writes audit events for
|
||||
every gated decision (granted or denied). Window code reaches for the
|
||||
current Session via the :class:`SessionHolder` singleton; tests can swap
|
||||
it out trivially.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from arautopilot.core.audit import AuditEvent, AuditLog, AuditOutcome
|
||||
from arautopilot.core.rbac import Capability, Role, has, requires_dual_auth
|
||||
from arautopilot.core.user import User
|
||||
from arautopilot.core.user_store import UserStore
|
||||
|
||||
|
||||
class Session:
|
||||
"""The current user + their audit log + capability gate."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
user: User,
|
||||
store: UserStore,
|
||||
audit: AuditLog,
|
||||
) -> None:
|
||||
self.user = user
|
||||
self.store = store
|
||||
self.audit = audit
|
||||
|
||||
@property
|
||||
def role(self) -> Role:
|
||||
return self.user.role
|
||||
|
||||
def can(self, capability: Capability) -> bool:
|
||||
return has(self.user.role, capability)
|
||||
|
||||
def check(self, capability: Capability, *, target: str | None = None,
|
||||
extra: dict[str, object] | None = None) -> bool:
|
||||
"""Capability check with audit side effect.
|
||||
|
||||
Returns True on grant, False on denial. Records an audit event
|
||||
either way so the trail is complete.
|
||||
"""
|
||||
granted = self.can(capability)
|
||||
self.audit.append(
|
||||
AuditEvent(
|
||||
user_id=self.user.user_id,
|
||||
role=self.user.role.value,
|
||||
action=f"check:{capability.value}",
|
||||
target=target,
|
||||
outcome=AuditOutcome.SUCCESS if granted else AuditOutcome.DENIED,
|
||||
reason="" if granted
|
||||
else f"role {self.user.role.value!r} lacks {capability.value!r}",
|
||||
extra=extra or {},
|
||||
)
|
||||
)
|
||||
return granted
|
||||
|
||||
def needs_dual_auth(self, capability: Capability) -> bool:
|
||||
return requires_dual_auth(self.user.role, capability)
|
||||
|
||||
def verify_super_admin_pin(self, pin: str) -> Optional[User]:
|
||||
"""Look up the (first) Super Admin in the store and verify the PIN.
|
||||
|
||||
Returns the SA :class:`User` on success, ``None`` on failure.
|
||||
"""
|
||||
for sa in self.store.by_role(Role.SUPER_ADMIN):
|
||||
if sa.verify_pin(pin):
|
||||
return sa
|
||||
return None
|
||||
|
||||
def log_dual_auth_grant(
|
||||
self,
|
||||
capability: Capability,
|
||||
sa_user: User,
|
||||
*,
|
||||
target: str | None = None,
|
||||
extra: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
"""Record an audit event for a successful dual-auth approval."""
|
||||
self.audit.append(
|
||||
AuditEvent(
|
||||
user_id=self.user.user_id,
|
||||
role=self.user.role.value,
|
||||
action=f"dual_auth_approved:{capability.value}",
|
||||
target=target,
|
||||
outcome=AuditOutcome.SUCCESS,
|
||||
secondary_user_id=sa_user.user_id,
|
||||
reason=f"approved by Super Admin {sa_user.display_name!r}",
|
||||
extra=extra or {},
|
||||
)
|
||||
)
|
||||
|
||||
def log_action(
|
||||
self,
|
||||
action: str,
|
||||
*,
|
||||
outcome: AuditOutcome = AuditOutcome.SUCCESS,
|
||||
target: str | None = None,
|
||||
reason: str = "",
|
||||
extra: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
"""Free-form audit event for downstream business actions."""
|
||||
self.audit.append(
|
||||
AuditEvent(
|
||||
user_id=self.user.user_id,
|
||||
role=self.user.role.value,
|
||||
action=action,
|
||||
target=target,
|
||||
outcome=outcome,
|
||||
reason=reason,
|
||||
extra=extra or {},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class SessionHolder:
|
||||
"""Process-global current session (set after login)."""
|
||||
|
||||
_current: Session | None = None
|
||||
|
||||
@classmethod
|
||||
def set(cls, session: Session | None) -> None:
|
||||
cls._current = session
|
||||
|
||||
@classmethod
|
||||
def current(cls) -> Session | None:
|
||||
return cls._current
|
||||
|
||||
@classmethod
|
||||
def require(cls) -> Session:
|
||||
if cls._current is None:
|
||||
raise RuntimeError("no active Studio session -- log in first")
|
||||
return cls._current
|
||||
|
||||
|
||||
def studio_data_dir() -> Path:
|
||||
"""Per-user directory under ``~/.ar-autopilot/studio/`` for the local
|
||||
user store and audit log."""
|
||||
base = Path.home() / ".ar-autopilot" / "studio"
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
return base
|
||||
Reference in New Issue
Block a user