Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(security): authz hardening round 2 (plan 29)

Juan Denis6b6237bc174c
diff --git a/backend/app/services/member_action_service.py b/backend/app/services/member_action_service.py
new file mode 100644
index 00000000..46ac154e
--- /dev/null
+++ b/backend/app/services/member_action_service.py
@@ -0,0 +1,178 @@
+"""Member action templates — the safe write escape hatch (plan 19 Phase 5).
+
+A member action is a CURATED, parameterized action a workspace member may trigger
+for an app they can reach. It is the only member-write path beyond the plan's
+Phase-4 matrix, and it is deliberately narrow:
+
+ - No free text ever reaches a shell. Every parameter is validated against a
+ typed schema (enum / bounded int) before the executor runs.
+ - Each template declares (id, label, param schema, executor, min_role). The
+ min_role reuses the same capability tiers as the rest of the plan
+ (can_operate_app for 'member', can_admin_app for 'admin').
+ - Every run is audit-logged.
+ - The whole surface is feature-flagged (config MEMBER_ACTIONS_ENABLED).
+
+The registry ships one concrete template today — `set-backup-frequency`, which
+adjusts an app's backup schedule through the existing BackupPolicyService (no new
+side-channel). The cron "ping this app's scheduler every N minutes" template
+named in the plan is deferred until plan 21 #10 lands its ScheduledJob wiring;
+adding it is just another registry entry.
+"""
+from app.services.resource_grant_service import ResourceGrantService
+from app.services.audit_service import AuditService
+
+
+class ActionError(ValueError):
+ """Raised for an unknown action, a disabled surface, or invalid params."""
+
+
+# --------------------------------------------------------------------------- #
+# Parameter validation — typed, bounded, no free text.
+# --------------------------------------------------------------------------- #
+
+def _validate_params(schema, raw):
+ """Validate `raw` against `schema` (name -> spec). Returns a clean dict of only
+ the declared params, coerced to their type. Raises ActionError on any problem."""
+ raw = raw or {}
+ out = {}
+ for name, spec in schema.items():
+ required = spec.get('required', False)
+ if name not in raw or raw[name] in (None, ''):
+ if required:
+ raise ActionError(f"Missing required parameter '{name}'")
+ if 'default' in spec:
+ out[name] = spec['default']
+ continue
+ value = raw[name]
+ kind = spec['type']
+ if kind == 'enum':
+ if value not in spec['choices']:
+ raise ActionError(
+ f"Parameter '{name}' must be one of {spec['choices']}")
+ out[name] = value
+ elif kind == 'int':
+ try:
+ value = int(value)
+ except (TypeError, ValueError):
+ raise ActionError(f"Parameter '{name}' must be an integer")
+ if 'min' in spec and value < spec['min']:
+ raise ActionError(f"Parameter '{name}' must be >= {spec['min']}")
+ if 'max' in spec and value > spec['max']:
+ raise ActionError(f"Parameter '{name}' must be <= {spec['max']}")
+ out[name] = value
+ else: # pragma: no cover - guards against a malformed registry entry
+ raise ActionError(f"Unsupported parameter type '{kind}'")
+ return out
+
+
+# --------------------------------------------------------------------------- #
+# Executors — each takes (app, params) and returns a JSON-safe result. They only
+# ever call vetted service methods; they never build a shell string.
+# --------------------------------------------------------------------------- #
+
+# Backup frequency enum -> the cron the schedule actually stores (runs at 02:00).
+_FREQUENCY_CRON = {
+ 'daily': '0 2 * * *',
+ 'weekly': '0 2 * * 0',
+ 'monthly': '0 2 1 * *',
+}
+
+
+def _exec_set_backup_frequency(app, params):
+ from app.services.backup_policy_service import BackupPolicyService
+ cron = _FREQUENCY_CRON[params['frequency']]
+ policy = BackupPolicyService.get_or_create_policy('application', app.id)
+ BackupPolicyService.update_policy(policy, {'enabled': True, 'schedule_cron': cron})
+ return {'frequency': params['frequency'], 'schedule_cron': cron, 'enabled': True}
+
+
+# --------------------------------------------------------------------------- #
+# The registry.
+# --------------------------------------------------------------------------- #
+
+MEMBER_ACTIONS = {
+ 'set-backup-frequency': {
+ 'id': 'set-backup-frequency',
+ 'label': 'Set backup frequency',
+ 'description': "Enable protection and set how often this app is backed up.",
+ 'min_role': 'member',
+ 'param_schema': {
+ 'frequency': {
+ 'type': 'enum',
+ 'choices': ['daily', 'weekly', 'monthly'],
+ 'required': True,
+ 'label': 'Frequency',
+ },
+ },
+ 'executor': _exec_set_backup_frequency,
+ },
+}
+
+
+def is_enabled():
+ """Feature flag — the whole member-action surface can be turned off.
+
+ Two independent kill switches, both must allow (plan 29 #13): the
+ ``MEMBER_ACTIONS_ENABLED`` app config (deployment-level, default ON) AND the
+ admin-visible ``security_member_actions_enabled`` system setting (default ON).
+ Either set to false disables the surface."""
+ from app.services.settings_service import SettingsService
+ from flask import current_app
+ if not current_app.config.get('MEMBER_ACTIONS_ENABLED', True):
+ return False
+ val = SettingsService.get('security_member_actions_enabled', None)
+ return True if val is None else bool(val)
+
+
+def _public(template):
+ """The client-safe view of a template (no executor callable)."""
+ return {
+ 'id': template['id'],
+ 'label': template['label'],
+ 'description': template['description'],
+ 'min_role': template['min_role'],
+ 'param_schema': template['param_schema'],
+ }
+
+
+def list_actions():
+ """Every registered template (client-safe), or [] when the surface is off."""
+ if not is_enabled():
+ return []
+ return [_public(t) for t in MEMBER_ACTIONS.values()]
+
+
+def _authorized(user, app, min_role):
+ """Whether `user` may run a template whose min_role is `min_role` on `app`."""
+ if min_role == 'admin':
+ return ResourceGrantService.can_admin_app(user, app)
+ return ResourceGrantService.can_operate_app(user, app)
+
+
+def run(user, app, action_id, raw_params):
+ """Validate + authorize + execute + audit one member action.
+
+ Returns (result_dict, None) on success or (None, (error_message, status)) so
+ the caller can shape the JSON error response consistently."""
+ if not is_enabled():
+ return None, ('Member actions are disabled', 403)
+ template = MEMBER_ACTIONS.get(action_id)
+ if template is None:
+ return None, ('Unknown action', 404)
+ if not _authorized(user, app, template['min_role']):
+ return None, ('Access denied', 403)
+ try:
+ params = _validate_params(template['param_schema'], raw_params)
+ except ActionError as e:
+ return None, (str(e), 400)
+
+ result = template['executor'](app, params)
+
+ AuditService.log_app_action(
+ action=f'member_action.{action_id}',
+ user_id=user.id,
+ app_id=app.id,
+ app_name=app.name,
+ details={'params': params},
+ )
+ return {'action': action_id, 'result': result}, None
diff --git a/backend/tests/test_api_authz_hardening.py b/backend/tests/test_api_authz_hardening.py
new file mode 100644
index 00000000..cb865439
--- /dev/null
+++ b/backend/tests/test_api_authz_hardening.py
@@ -0,0 +1,385 @@
+"""Persona x route authorization matrix for plan 18 (API Authorization Hardening).
+
+This is the load-bearing proving suite for the "one canonical gate everywhere"
+seal: every per-app WordPress / env-var / status-page / docker-DB route must deny
+a non-owner, non-grantee caller through the shared ResourceGrantService seam,
+while an admin still reaches every sealed route (Decision 8 — single-admin
+installs are invariant).
+
+The RBAC fixture defined here (owner / editor-grant / viewer-grant / foreign
+non-member / admin) is intentionally reusable: plan 19 Phase 1 inherits it.
+"""
+import pytest
+
+
+# --------------------------------------------------------------------------- #
+# Reusable RBAC fixture: five personas over one shared WordPress application.
+# --------------------------------------------------------------------------- #
+
+def _mk_user(db, username, role='developer'):
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ u = User(email=f'{username}@t.local', username=username,
+ password_hash=generate_password_hash('x'), role=role, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _token(user_id):
+ from flask_jwt_extended import create_access_token
+ return {'Authorization': f'Bearer {create_access_token(identity=user_id)}'}
+
+
+def rbac(app):
+ """Owner + editor-grant + viewer-grant + foreign + admin over one WP app.
+
+ Returns a namespace with per-persona auth headers and the shared ids. The WP
+ site is deliberately NOT production and has no root_path, so destructive
+ service calls bail out with a safe 400 rather than touching Docker — the
+ security assertion only cares that the *gate* opened (anything but the auth
+ 404) vs. denied (404)."""
+ from types import SimpleNamespace
+ from app import db
+ from app.models import Application, WordPressSite
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'authz_owner')
+ editor = _mk_user(db, 'authz_editor')
+ viewer = _mk_user(db, 'authz_viewer')
+ foreign = _mk_user(db, 'authz_foreign')
+ admin = _mk_user(db, 'authz_admin', role='admin')
+
+ a = Application(name='authz-wp', app_type='wordpress', user_id=owner.id,
+ root_path='')
+ db.session.add(a)
+ db.session.commit()
+ site = WordPressSite(application_id=a.id, is_production=False)
+ db.session.add(site)
+ db.session.commit()
+
+ ResourceGrantService.grant(user_id=editor.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='editor')
+ ResourceGrantService.grant(user_id=viewer.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='viewer')
+
+ return SimpleNamespace(
+ app_id=a.id,
+ site_id=site.id,
+ owner=_token(owner.id),
+ editor=_token(editor.id),
+ viewer=_token(viewer.id),
+ foreign=_token(foreign.id),
+ admin=_token(admin.id),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Phase 1 — the P0 destructive <site_id> lifecycle mutations.
+# Denied (viewer-grant, foreign non-member) -> 404 (sealed-from-open, Decision 5).
+# Allowed (owner, editor-grant, admin) -> the gate opens (status != 404).
+# --------------------------------------------------------------------------- #
+
+def _destructive_calls(client, rbac):
+ """(label, callable(headers)->response) for every P0 write route."""
+ sid = rbac.site_id
+ base = f'/api/v1/wordpress/sites/{sid}'
+ return [
+ ('delete_site', lambda h: client.delete(base, headers=h)),
+ ('archive', lambda h: client.post(f'{base}/archive', headers=h)),
+ ('unarchive', lambda h: client.post(f'{base}/unarchive', headers=h)),
+ ('set_tags', lambda h: client.patch(f'{base}/tags', json={'tags': ['x']}, headers=h)),
+ ('clone', lambda h: client.post(f'{base}/clone', json={}, headers=h)),
+ ('create_env', lambda h: client.post(f'{base}/environments', json={}, headers=h)),
+ ('delete_env', lambda h: client.delete(f'{base}/environments/999999', headers=h)),
+ ]
+
+
[email protected]('persona', ['viewer', 'foreign'])
+def test_p0_destructive_denied_for_unauthorized(app, client, rbac, persona):
+ """A viewer-grant and a foreign non-member cannot delete/alter any site —
+ the regression anchor: a viewer cannot delete a site."""
+ headers = getattr(rbac, persona)
+ for label, call in _destructive_calls(client, rbac):
+ r = call(headers)
+ assert r.status_code == 404, f'{persona} reached {label} (got {r.status_code}, expected 404)'
+
+
[email protected]('persona', ['owner', 'editor', 'admin'])
+def test_p0_destructive_allowed_for_authorized(app, client, rbac, persona):
+ """Owner, editor-grantee, and admin all pass the write gate (the operation
+ itself may 400 without Docker, but it must NOT be the auth 404)."""
+ headers = getattr(rbac, persona)
+ for label, call in _destructive_calls(client, rbac):
+ r = call(headers)
+ assert r.status_code != 404, f'{persona} was denied {label} (got 404)'
+
+
+def test_p0_destructive_missing_site_is_404_even_for_admin(app, client, rbac):
+ """A non-existent site is 404 for everyone, including admin (no info leak /
+ no crash) — the guard resolves the app before acting."""
+ r = client.delete('/api/v1/wordpress/sites/987654', headers=rbac.admin)
+ assert r.status_code == 404
+
+
+# --------------------------------------------------------------------------- #
+# Phase 2 — WordPress read holes + convergence.
+# --------------------------------------------------------------------------- #
+
+def _sealed_denied(r):
+ """True iff the sealed-from-open gate (Decision 5) denied the caller — a 404
+ whose body is exactly the gate's `{'error': 'Not found'}`. Distinguishes the
+ gate's 404 from a service-level 404 (e.g. 'Not a production site')."""
+ return r.status_code == 404 and (r.get_json() or {}).get('error') == 'Not found'
+
+
+def test_sealed_reads_hidden_from_foreign(app, client, rbac):
+ """Previously-open <site_id>/<app_id> reads now hide behind the gate for a
+ foreign caller (404 'Not found') and open for any grant (Decision 5)."""
+ sid, aid = rbac.site_id, rbac.app_id
+ sealed_reads = [
+ f'/api/v1/wordpress/sites/{sid}',
+ f'/api/v1/wordpress/sites/{sid}/environments',
+ f'/api/v1/wordpress/sites/{aid}/page-cache',
+ f'/api/v1/wordpress/sites/{aid}/object-cache',
+ f'/api/v1/wordpress/sites/{aid}/plugins/managed',
+ ]
+ for url in sealed_reads:
+ assert _sealed_denied(client.get(url, headers=rbac.foreign)), f'foreign reached {url}'
+ # A viewer-grant (read) and admin pass the gate — a service-level 404
+ # (non-production, no docker) is fine; only the gate's 404 is a denial.
+ assert not _sealed_denied(client.get(url, headers=rbac.viewer)), f'viewer denied {url}'
+ assert not _sealed_denied(client.get(url, headers=rbac.admin)), f'admin denied {url}'
+
+
+def test_convergence_reads_403_for_foreign_grant_opens(app, client, rbac):
+ """The eight formerly-inline `role != 'admin'` feature reads keep their 403 on
+ denial (Decision 5) but now honor grants (Decision 3): a viewer-grant reaches
+ them, exactly as it already reaches the app's volumes/deployments."""
+ aid = rbac.app_id
+ converged_reads = [
+ f'/api/v1/wordpress/sites/{aid}/php',
+ f'/api/v1/wordpress/sites/{aid}/status-page',
+ f'/api/v1/wordpress/sites/{aid}/analytics',
+ f'/api/v1/wordpress/sites/{aid}/vulnerabilities',
+ f'/api/v1/wordpress/sites/{aid}/info',
+ f'/api/v1/wordpress/sites/{aid}/plugins',
+ f'/api/v1/wordpress/sites/{aid}/themes',
+ f'/api/v1/wordpress/sites/{aid}/backups',
+ ]
+ for url in converged_reads:
+ assert client.get(url, headers=rbac.foreign).status_code == 403, f'foreign reached {url}'
+ assert client.get(url, headers=rbac.viewer).status_code != 403, f'grant did not open {url}'
+ assert client.get(url, headers=rbac.admin).status_code != 403, f'admin denied {url}'
+
+
+# --------------------------------------------------------------------------- #
+# Phase 3 — env vars convergence (read = can_access_app, write = can_edit_app).
+# --------------------------------------------------------------------------- #
+
+def env_rbac(app):
+ """Same five personas over a plain (non-WP) app for the env-var surface."""
+ from types import SimpleNamespace
+ from app import db
+ from app.models import Application
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'env_owner')
+ editor = _mk_user(db, 'env_editor')
+ viewer = _mk_user(db, 'env_viewer')
+ foreign = _mk_user(db, 'env_foreign')
+ admin = _mk_user(db, 'env_admin', role='admin')
+
+ a = Application(name='env-app', app_type='php', user_id=owner.id, root_path='/srv/env')
+ db.session.add(a)
+ db.session.commit()
+ ResourceGrantService.grant(user_id=editor.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='editor')
+ ResourceGrantService.grant(user_id=viewer.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='viewer')
+
+ return SimpleNamespace(
+ app_id=a.id,
+ owner=_token(owner.id), editor=_token(editor.id), viewer=_token(viewer.id),
+ foreign=_token(foreign.id), admin=_token(admin.id),
+ )
+
+
+def test_env_read_matrix(app, client, env_rbac):
+ """Reads: owner/admin/editor/viewer reach env vars; a foreign caller is 403."""
+ url = f'/api/v1/apps/{env_rbac.app_id}/env'
+ for persona in ('owner', 'admin', 'editor', 'viewer'):
+ assert client.get(url, headers=getattr(env_rbac, persona)).status_code == 200, persona
+ assert client.get(url, headers=env_rbac.foreign).status_code == 403
+
+
+def test_env_write_matrix(app, client, env_rbac):
+ """Writes: owner/admin/editor can create; viewer-grant and foreign are 403
+ (viewer is read-only — the editor-vs-viewer split is the whole point)."""
+ url = f'/api/v1/apps/{env_rbac.app_id}/env'
+ # Allowed to write.
+ for i, persona in enumerate(('owner', 'admin', 'editor')):
+ r = client.post(url, json={'key': f'K{i}', 'value': 'v'}, headers=getattr(env_rbac, persona))
+ assert r.status_code in (200, 201), f'{persona} could not write env ({r.status_code})'
+ # Denied write.
+ assert client.post(url, json={'key': 'NOPE', 'value': 'v'}, headers=env_rbac.viewer).status_code == 403
+ assert client.post(url, json={'key': 'NOPE', 'value': 'v'}, headers=env_rbac.foreign).status_code == 403
+
+
+def test_env_secret_masking_preserved(app, client, env_rbac):
+ """Convergence must not change secret masking: a secret's value is masked when
+ ?mask=true and revealed otherwise (existing behavior)."""
+ url = f'/api/v1/apps/{env_rbac.app_id}/env'
+ client.post(url, json={'key': 'API_TOKEN', 'value': 'supersecret', 'is_secret': True},
+ headers=env_rbac.owner)
+
+ masked = client.get(f'{url}?mask=true', headers=env_rbac.viewer).get_json()['env_vars']
+ token = next(e for e in masked if e['key'] == 'API_TOKEN')
+ assert token['value'] != 'supersecret' # masked for the reader
+
+ clear = client.get(f'{url}?mask=false', headers=env_rbac.owner).get_json()['env_vars']
+ token = next(e for e in clear if e['key'] == 'API_TOKEN')
+ assert token['value'] == 'supersecret' # unmasked path intact
+
+
+# --------------------------------------------------------------------------- #
+# Phase 4 — status pages (mutations admin-only, reads open) + raw docker-DB.
+# --------------------------------------------------------------------------- #
+
+def test_status_page_mutations_admin_only(app, client):
+ """Reads stay open to any authed user; every mutation is admin-only via the
+ @admin_required decorator (plan 18 Decision 6). A non-admin is 403."""
+ from app import db
+ dev = _mk_user(db, 'sp_dev', role='developer')
+ admin = _mk_user(db, 'sp_admin', role='admin')
+
+ # Reads are open to a plain developer.
+ assert client.get('/api/v1/status/', headers=_token(dev.id)).status_code == 200
+
+ # Admin can create a page.
+ r = client.post('/api/v1/status/', json={'name': 'Ops', 'slug': 'ops'}, headers=_token(admin.id))
+ assert r.status_code == 201
+ page_id = r.get_json()['id']
+
+ # A developer is denied every mutation.
+ assert client.post('/api/v1/status/', json={'name': 'X', 'slug': 'x'}, headers=_token(dev.id)).status_code == 403
+ assert client.put(f'/api/v1/status/{page_id}', json={'name': 'Y'}, headers=_token(dev.id)).status_code == 403
+ assert client.delete(f'/api/v1/status/{page_id}', headers=_token(dev.id)).status_code == 403
+ assert client.post(f'/api/v1/status/{page_id}/components', json={'name': 'c', 'check_type': 'http'},
+ headers=_token(dev.id)).status_code == 403
+ assert client.post(f'/api/v1/status/{page_id}/incidents', json={'title': 't'},
+ headers=_token(dev.id)).status_code == 403
+
+
+def test_raw_docker_db_routes_admin_only(app, client):
+ """The bare-container docker DB routes (no app linkage) are system-level and
+ admin-only (Decision 7). A non-admin is 403; an admin passes the gate."""
+ from app import db
+ dev = _mk_user(db, 'rd_dev', role='developer')
+ admin = _mk_user(db, 'rd_admin', role='admin')
+
+ raw = [
+ ('get', '/api/v1/databases/docker/ghost/databases', None),
+ ('get', '/api/v1/databases/docker/ghost/wordpress/tables', None),
+ ('post', '/api/v1/databases/docker/ghost/wordpress/query', {'query': 'SELECT 1'}),
+ ]
+ for method, url, body in raw:
+ call = getattr(client, method)
+ kwargs = {'json': body} if body is not None else {}
+ assert call(url, headers=_token(dev.id), **kwargs).status_code == 403, f'dev reached {url}'
+ # Admin passes the gate (the docker exec itself may fail, but not 403).
+ assert call(url, headers=_token(admin.id), **kwargs).status_code != 403, f'admin denied {url}'
+
+
+def test_per_app_docker_db_read_open_to_grantee(app, client):
+ """The per-app DB endpoint stays grant-checked (not admin-gated): a grantee
+ reaches it, a foreign caller does not — the non-admin path the UI should use."""
+ from app import db
+ from app.models import Application
+ from app.services.resource_grant_service import ResourceGrantService
+
+ owner = _mk_user(db, 'dd_owner')
+ grantee = _mk_user(db, 'dd_grantee')
+ foreign = _mk_user(db, 'dd_foreign')
+ a = Application(name='dd-docker', app_type='docker', user_id=owner.id, root_path='/srv/dd')
+ db.session.add(a)
+ db.session.commit()
+ ResourceGrantService.grant(user_id=grantee.id, resource_type='application',
+ resource_id=a.id, granted_by=owner.id, role='viewer')
+
+ url = f'/api/v1/databases/docker/app/{a.id}'
+ assert client.get(url, headers=_token(grantee.id)).status_code != 403
+ assert client.get(url, headers=_token(foreign.id)).status_code == 403
+
+
+# --------------------------------------------------------------------------- #
+# Phase 5 — the static gate (#13): no per-app WordPress route may be jwt-only
+# without an access call. A structural regression net so a new per-app route
+# can't silently reintroduce an open hole.
+# --------------------------------------------------------------------------- #
+
+def test_no_ungated_per_app_wordpress_route():
+ """SUPERSEDED (plan 29 #10) by the generic AST sweep in
+ test_authz_structural_sweep.py, which covers wordpress.py alongside the whole
+ api/ surface with the complete gate family (fixing this gate's missing-verbs
+ gap). This thin alias is retained for one release; delete after."""
+ from test_authz_structural_sweep import test_no_ungated_per_app_route
+ test_no_ungated_per_app_route()
+
+
+# --------------------------------------------------------------------------- #
+# Plan 29 Phase 1 — seal the leftover routes plan 18's ledger missed.
+# Each is a host/system surface with no app linkage, so it converges onto
+# @admin_required to match its already-admin siblings. Personas from the
+# `scoping_rbac` fixture (viewer/member/foreign are non-admin; admin bypasses).
+# --------------------------------------------------------------------------- #
+
[email protected]('persona', ['viewer', 'member', 'foreign'])
+def test_raw_docker_container_list_admin_only(app, client, scoping_rbac, persona):
+ """#2 — `GET /databases/docker` host-container enumeration is System-level
+ (no app/workspace linkage) → admin-only. Any non-admin is 403; admin passes."""
+ r = client.get('/api/v1/databases/docker', headers=getattr(scoping_rbac, persona))
+ assert r.status_code == 403, f'{persona} reached the raw docker list ({r.status_code})'
+ assert client.get('/api/v1/databases/docker', headers=scoping_rbac.admin).status_code != 403
+
+
[email protected]('persona', ['viewer', 'member', 'foreign'])
+def test_raw_docker_processes_admin_only(app, client, scoping_rbac, persona):
+ """#1 — the bare-container processlist read takes `X-DB-Password` and has no
+ app linkage → admin-only, matching its `kill` sibling. Non-admin is 403."""
+ url = '/api/v1/databases/docker/ghost/processes'
+ assert client.get(url, headers=getattr(scoping_rbac, persona)).status_code == 403, persona
+ # Admin passes the gate (the docker exec itself may fail, but not with 403).
+ assert client.get(url, headers=scoping_rbac.admin).status_code != 403
+
+
[email protected]('persona', ['viewer', 'member', 'foreign'])
+def test_wordpress_standalone_host_ops_admin_only(app, client, scoping_rbac, persona):
+ """#3 — the standalone install/uninstall/start/stop/restart host ops predate
+ the per-app model and touch the host → admin-only (plan 19's host-touching
+ matrix). A non-admin is 403 on every one; admin passes the gate."""
+ base = '/api/v1/wordpress/standalone'
+ ops = [
+ ('post', f'{base}/install'),
+ ('post', f'{base}/uninstall'),
+ ('post', f'{base}/start'),
+ ('post', f'{base}/stop'),
+ ('post', f'{base}/restart'),
+ ]
+ headers = getattr(scoping_rbac, persona)
+ for method, url in ops:
+ call = getattr(client, method)
+ assert call(url, json={}, headers=headers).status_code == 403, f'{persona} reached {url}'
+ assert call(url, json={}, headers=scoping_rbac.admin).status_code != 403, f'admin denied {url}'
+
+
[email protected]('persona', ['viewer', 'member', 'foreign'])
+def test_status_component_check_admin_only(app, client, scoping_rbac, persona):
+ """#4 — `POST /status/components/<id>/check` triggers a live check + persists a
+ result (write-ish), so it joins its 9 admin-only mutation siblings. A non-admin
+ is 403; admin passes the gate (the check itself may 404 on a missing id)."""
+ url = '/api/v1/status/components/999999/check'
+ assert client.post(url, headers=getattr(scoping_rbac, persona)).status_code == 403, persona
+ assert client.post(url, headers=scoping_rbac.admin).status_code != 403
diff --git a/backend/tests/test_authz_structural_sweep.py b/backend/tests/test_authz_structural_sweep.py
new file mode 100644
index 00000000..fd2ab319
--- /dev/null
+++ b/backend/tests/test_authz_structural_sweep.py
@@ -0,0 +1,182 @@
+"""Plan 29 Phase 3 (#9/#10) — the ONE generic structural authorization gate.
+
+A single AST sweep over every Flask route file under ``backend/app/api/`` plus the
+flagship WordPress bridge. It replaces the two narrow gates plan 18/19 shipped
+(the WordPress-only AST test and the hardcoded 6-file bucket-header test), which
+could each only see part of the surface.
+
+For every route handler whose URL carries ``<app_id>`` or ``<site_id>`` (any
+converter form) it enforces:
+
+ (a) the route FILE declares a ``# Bucket:`` header in its first lines, so a new
+ per-app surface can't ship without being classified; and
+ (b) the handler REACHES a known gate — either a gating decorator
+ (``admin_required`` / ``require_app_member``) or a gate CALL in its body.
+
+Gate calls are recognised robustly: the canonical family
+(``can_access_app`` / ``can_operate_app`` / ``can_edit_app`` / ``can_admin_app``
+and the WP ``_guard_app`` / ``_guard_sealed_app``), PLUS any *local* helper in the
+same file whose own body reaches one of those (env_vars' ``check_app_access``,
+previews' ``_get_app_or_404``, waf's ``_get_application_or_404`` …) or performs an
+explicit admin check (``is_admin``). Auto-discovering wrappers means the sweep
+follows the code instead of a brittle hand-maintained name list.
+
+Deliberate exceptions live in ``ALLOWLIST`` below, each with a one-line reason;
+additions must carry a justification.
+"""
+import ast
+import os
+
+import pytest
+
+
+# --------------------------------------------------------------------------- #
+# Surface
+# --------------------------------------------------------------------------- #
+
+def _repo_root():
+ return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+
+def _route_files():
+ """Every api/*.py file + the WordPress flagship bridge, as (label, abspath)."""
+ root = _repo_root()
+ api_dir = os.path.join(root, 'backend', 'app', 'api')
+ files = []
+ for fname in sorted(os.listdir(api_dir)):
+ if fname.endswith('.py') and fname != '__init__.py':
+ files.append((fname, os.path.join(api_dir, fname)))
+ files.append((
+ 'wordpress.py',
+ os.path.join(root, 'builtin-extensions', 'serverkit-wordpress', 'backend', 'wordpress.py'),
+ ))
+ return files
+
+
+# Canonical per-app gates + WP guards. A handler (or a helper it calls) that
+# references any of these is authorization-gated for the target app.
+CANONICAL_GATES = {
+ 'can_access_app', 'can_operate_app', 'can_edit_app', 'can_admin_app',
+ '_guard_app', '_guard_sealed_app',
+}
+# Markers that a helper performs an admin check (admin is a valid gate for
+# host/system per-app surfaces, e.g. WAF mutations, image-update triggers).
+ADMIN_MARKERS = {'is_admin', 'admin_required'}
+# Decorators that gate directly.
+GATING_DECORATORS = {'admin_required', 'require_app_member'}
+
+# Deliberate exceptions: 'file.py:handler' -> reason. Keep minimal; each addition
+# needs a justification line.
+ALLOWLIST = {
+ # Public inbound Git webhooks: authenticated by the <token> path segment +
+ # the provider HMAC signature, not by a user session — so no per-app user gate
+ # applies (mirrors git.py:receive_webhook).
+ 'deploy.py:webhook': 'signature/token-verified public webhook (no user auth)',
+}
+
+
+# --------------------------------------------------------------------------- #
+# AST helpers
+# --------------------------------------------------------------------------- #
+
+def _decorator_names(node):
+ names = []
+ for dec in node.decorator_list:
+ target = dec.func if isinstance(dec, ast.Call) else dec
+ names.append(getattr(target, 'id', None) or getattr(target, 'attr', None))
+ return [n for n in names if n]
+
+
+def _route_paths(node):
+ paths = []
+ for dec in node.decorator_list:
+ if (isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute)
+ and dec.func.attr == 'route' and dec.args
+ and isinstance(dec.args[0], ast.Constant)):
+ paths.append(dec.args[0].value)
+ return paths
+
+
+def _is_per_app(paths):
+ return any(('app_id' in p or 'site_id' in p) for p in paths)
+
+
+def _discover_gate_helpers(source, tree):
+ """Names of functions in this module that themselves reach a gate — either a
+ canonical gate call or an explicit admin check. These are the file-local
+ wrappers (check_app_access, _get_app_or_404, _require_admin, …) that callers
+ delegate to; recognising them lets the sweep follow the code."""
+ helpers = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ body_src = ast.get_source_segment(source, node) or ''
+ if any(g in body_src for g in CANONICAL_GATES) or any(m in body_src for m in ADMIN_MARKERS):
+ helpers.add(node.name)
+ return helpers
+
+
+def _has_inline_owner_check(body_src):
+ """Recognise the hand-rolled owner-or-admin idiom used in a few apps.py
+ handlers, e.g. ``if user.role != 'admin' and app.user_id != user.id``. It gates
+ just as effectively as a named helper; the co-occurrence of an ownership
+ comparison (``user_id``) and an admin check (``admin``) in a route body is a
+ reliable signal (and false positives only *relax* the net, never tighten it
+ wrongly — a truly ungated body won't contain both)."""
+ return 'user_id' in body_src and 'admin' in body_src
+
+
+def _handler_is_gated(node, source, gate_tokens):
+ if any(d in GATING_DECORATORS for d in _decorator_names(node)):
+ return True
+ body_src = ast.get_source_segment(source, node) or ''
+ if any(tok in body_src for tok in gate_tokens):
+ return True
+ return _has_inline_owner_check(body_src)
+
+
+# --------------------------------------------------------------------------- #
+# The sweep
+# --------------------------------------------------------------------------- #
+
+def _sweep():
+ """Return (bucketless_files, ungated_handlers) across the whole surface."""
+ bucketless, ungated = [], []
+ for label, path in _route_files():
+ with open(path, encoding='utf-8') as fh:
+ source = fh.read()
+ tree = ast.parse(source)
+ header = '\n'.join(source.splitlines()[:12])
+
+ gate_tokens = CANONICAL_GATES | ADMIN_MARKERS | _discover_gate_helpers(source, tree)
+
+ file_has_per_app = False
+ for node in tree.body:
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ paths = _route_paths(node)
+ if not paths or not _is_per_app(paths):
+ continue
+ file_has_per_app = True
+ if f'{label}:{node.name}' in ALLOWLIST:
+ continue
+ if not _handler_is_gated(node, source, gate_tokens):
+ ungated.append(f'{label}:{node.name}')
+
+ if file_has_per_app and '# Bucket:' not in header:
+ bucketless.append(label)
+ return bucketless, ungated
+
+
+def test_every_per_app_route_file_declares_a_bucket():
+ bucketless, _ = _sweep()
+ assert not bucketless, (
+ 'per-app route files missing a `# Bucket:` header (plan 29 #9): '
+ f'{bucketless}')
+
+
+def test_no_ungated_per_app_route():
+ _, ungated = _sweep()
+ assert not ungated, (
+ 'per-app route handlers with no reachable authorization gate '
+ f'(plan 29 #9 — add a gate or an ALLOWLIST justification): {ungated}')
diff --git a/backend/tests/test_cron_rbac.py b/backend/tests/test_cron_rbac.py
new file mode 100644
index 00000000..04590fa9
--- /dev/null
+++ b/backend/tests/test_cron_rbac.py
@@ -0,0 +1,137 @@
+"""Cron ownership + workspace-visibility RBAC (plan 21 Phase 3, #12).
+
+Uses the shared `scoping_rbac` fixture (five personas over one workspace + app).
+Cron jobs live in a JSON store, so `cron_store` isolates it to a tmp file and
+forces the non-Linux (metadata-only) path so no real crontab is touched.
+"""
+import pytest
+
+from app.services.cron_service import CronService
+
+
+def cron_store(tmp_path, monkeypatch):
+ import app.services.cron_service as mod
+ monkeypatch.setattr(mod, 'JOBS_FILE', str(tmp_path / 'cron_jobs.json'))
+ monkeypatch.setattr(CronService, 'is_linux', classmethod(lambda cls: False))
+ return mod
+
+
+def _mk_job(app_id, name='App Cron'):
+ res = CronService.add_job('0 0 * * *', '/usr/bin/app-task.sh', name=name,
+ application_id=app_id)
+ assert res['success']
+ return res['job_id']
+
+
+# --------------------------------------------------------------------------- #
+# for-app visibility gate
+# --------------------------------------------------------------------------- #
+
+def test_member_sees_for_app_jobs(client, scoping_rbac, cron_store):
+ _mk_job(scoping_rbac.app_id)
+ r = client.get(f'/api/v1/cron/jobs/for-app/{scoping_rbac.app_id}',
+ headers=scoping_rbac.member)
+ assert r.status_code == 200
+ body = r.get_json()
+ assert body['count'] == 1
+ job = body['jobs'][0]
+ assert job['name'] == 'App Cron'
+ assert job['schedule_human']
+ # Member-facing surface never leaks the raw host command.
+ assert 'command' not in job
+
+
+def test_viewer_sees_read_only(client, scoping_rbac, cron_store):
+ _mk_job(scoping_rbac.app_id)
+ r = client.get(f'/api/v1/cron/jobs/for-app/{scoping_rbac.app_id}',
+ headers=scoping_rbac.viewer)
+ assert r.status_code == 200
+ assert r.get_json()['count'] == 1
+
+
+def test_owner_and_admin_see_for_app_jobs(client, scoping_rbac, cron_store):
+ _mk_job(scoping_rbac.app_id)
+ for hdr in (scoping_rbac.owner, scoping_rbac.admin):
+ r = client.get(f'/api/v1/cron/jobs/for-app/{scoping_rbac.app_id}', headers=hdr)
+ assert r.status_code == 200
+ assert r.get_json()['count'] == 1
+
+
+def test_foreign_member_forbidden(client, scoping_rbac, cron_store):
+ _mk_job(scoping_rbac.app_id)
+ r = client.get(f'/api/v1/cron/jobs/for-app/{scoping_rbac.app_id}',
+ headers=scoping_rbac.foreign)
+ assert r.status_code == 403
+
+
+def test_for_app_missing_app_404(client, scoping_rbac, cron_store):
+ r = client.get('/api/v1/cron/jobs/for-app/999999', headers=scoping_rbac.admin)
+ assert r.status_code == 404
+
+
+# --------------------------------------------------------------------------- #
+# admin /cron surface: attribution + create validation
+# --------------------------------------------------------------------------- #
+
+def test_admin_list_carries_attribution(client, scoping_rbac, cron_store):
+ _mk_job(scoping_rbac.app_id)
+ r = client.get('/api/v1/cron/jobs', headers=scoping_rbac.admin)
+ assert r.status_code == 200
+ jobs = r.get_json()['jobs']
+ attributed = [j for j in jobs if j.get('app')]
+ assert attributed
+ j = attributed[0]
+ assert j['app']['id'] == scoping_rbac.app_id
+ assert j['workspace']['id'] == scoping_rbac.ws_id
+
+
+def test_create_rejects_unknown_application(client, scoping_rbac, cron_store):
+ r = client.post('/api/v1/cron/jobs', headers=scoping_rbac.admin, json={
+ 'name': 'X', 'command': '/usr/bin/x.sh', 'schedule': '0 0 * * *',
+ 'application_id': 987654,
+ })
+ assert r.status_code == 400
+ assert 'not found' in r.get_json()['error'].lower()
+
+
+def test_member_cannot_create_job(client, scoping_rbac, cron_store):
+ # Creating stays admin (Decision 2) — a workspace member is not an admin.
+ r = client.post('/api/v1/cron/jobs', headers=scoping_rbac.member, json={
+ 'name': 'X', 'command': '/usr/bin/x.sh', 'schedule': '0 0 * * *',
+ })
+ assert r.status_code in (401, 403)
+
+
+# --------------------------------------------------------------------------- #
+# association lifecycle
+# --------------------------------------------------------------------------- #
+
+def test_association_survives_app_rename(client, scoping_rbac, cron_store):
+ from app import db
+ from app.models import Application
+ _mk_job(scoping_rbac.app_id)
+
+ app = Application.query.get(scoping_rbac.app_id)
+ app.name = 'renamed-app'
+ db.session.commit()
+
+ r = client.get('/api/v1/cron/jobs', headers=scoping_rbac.admin)
+ attributed = [j for j in r.get_json()['jobs'] if j.get('app')]
+ assert attributed and attributed[0]['app']['name'] == 'renamed-app'
+
+
+def test_app_deletion_falls_back_to_system_bucket(client, scoping_rbac, cron_store):
+ from app import db
+ from app.models import Application
+ job_id = _mk_job(scoping_rbac.app_id)
+
+ app = Application.query.get(scoping_rbac.app_id)
+ db.session.delete(app) # fires the before_delete association-clear
+ db.session.commit()
+
+ # Job is NOT deleted; it just loses its association (System bucket).
+ assert CronService.jobs_for_application(scoping_rbac.app_id) == []
+ meta = CronService._load_jobs_metadata()
+ assert job_id in meta['jobs']
+ assert meta['jobs'][job_id]['application_id'] is None
diff --git a/backend/tests/test_git_webhook_authz.py b/backend/tests/test_git_webhook_authz.py
new file mode 100644
index 00000000..d13186f0
--- /dev/null
+++ b/backend/tests/test_git_webhook_authz.py
@@ -0,0 +1,81 @@
+"""Plan 29 Phase 4 (#11) — git-webhook READ reclassification.
+
+Webhook/deploy reads move off panel-wide @viewer_required onto the linked app's
+workspace visibility (can_access_app on the webhook's app_id). A foreign-workspace
+viewer loses visibility of an app-linked webhook; a workspace member keeps it.
+Webhooks with no app linkage stay panel-wide viewer-visible. Mutations stay
+admin-only (explicitly re-deferred) and are not touched here.
+"""
+import pytest
+
+
+def _mk_webhook(db, name, app_id=None):
+ from app.models import GitWebhook
+ w = GitWebhook(
+ name=name, source='github',
+ source_repo_url='https://example.com/r.git',
+ secret='s', webhook_token=f'tok-{name}',
+ app_id=app_id,
+ )
+ db.session.add(w)
+ db.session.commit()
+ return w
+
+
+def webhook_rbac(app, scoping_rbac):
+ """One app-linked webhook (on scoping_rbac's app) + one unlinked webhook."""
+ from types import SimpleNamespace
+ from app import db
+ linked = _mk_webhook(db, 'linked', app_id=scoping_rbac.app_id)
+ unlinked = _mk_webhook(db, 'unlinked', app_id=None)
+ return SimpleNamespace(linked_id=linked.id, unlinked_id=unlinked.id, s=scoping_rbac)
+
+
+def test_webhook_get_scoped_to_app_visibility(client, webhook_rbac):
+ """The app-linked webhook is reachable by owner/member/viewer/admin of its
+ workspace, but a foreign caller gets a 404 (sealed-from-open, no leak)."""
+ s = webhook_rbac.s
+ url = f'/api/v1/git/webhooks/{webhook_rbac.linked_id}'
+ for persona in ('owner', 'member', 'viewer', 'admin'):
+ assert client.get(url, headers=getattr(s, persona)).status_code == 200, persona
+ assert client.get(url, headers=s.foreign).status_code == 404
+
+
+def test_webhook_logs_scoped_to_app_visibility(client, webhook_rbac):
+ """Webhook logs follow the same app-visibility seam as the webhook itself."""
+ s = webhook_rbac.s
+ url = f'/api/v1/git/webhooks/{webhook_rbac.linked_id}/logs'
+ assert client.get(url, headers=s.member).status_code == 200
+ assert client.get(url, headers=s.foreign).status_code == 404
+
+
+def test_webhook_list_filters_to_visible(client, webhook_rbac):
+ """The collection lists only webhooks the caller can see: a member sees the
+ app-linked + unlinked ones; a foreign caller sees only the unlinked one."""
+ s = webhook_rbac.s
+
+ member_ids = {w['id'] for w in client.get('/api/v1/git/webhooks', headers=s.member).get_json()['webhooks']}
+ assert webhook_rbac.linked_id in member_ids
+ assert webhook_rbac.unlinked_id in member_ids
+
+ foreign_ids = {w['id'] for w in client.get('/api/v1/git/webhooks', headers=s.foreign).get_json()['webhooks']}
+ assert webhook_rbac.linked_id not in foreign_ids # lost visibility of the app-linked hook
+ assert webhook_rbac.unlinked_id in foreign_ids # unlinked stays panel-wide visible
+
+
+def test_webhook_unlinked_visible_to_all(client, webhook_rbac):
+ """A webhook with no app linkage is a panel-wide resource — any authenticated
+ viewer (even a foreign one) can read it directly."""
+ s = webhook_rbac.s
+ url = f'/api/v1/git/webhooks/{webhook_rbac.unlinked_id}'
+ assert client.get(url, headers=s.foreign).status_code == 200
+
+
+def test_webhook_mutations_stay_admin_only(client, webhook_rbac):
+ """Deferred by design: mutations remain admin-only. A member (who can now READ
+ the linked webhook) still cannot delete or toggle it."""
+ s = webhook_rbac.s
+ wid = webhook_rbac.linked_id
+ assert client.delete(f'/api/v1/git/webhooks/{wid}', headers=s.member).status_code == 403
+ assert client.post(f'/api/v1/git/webhooks/{wid}/toggle', headers=s.member).status_code == 403
diff --git a/backend/tests/test_server_permissions.py b/backend/tests/test_server_permissions.py
index 54444730..d292b314 100644
--- a/backend/tests/test_server_permissions.py
+++ b/backend/tests/test_server_permissions.py
@@ -46,3 +46,37 @@ def test_wildcard_permissions_still_match_agent_actions():
assert server.has_permission('docker:container:list')
assert server.has_permission('docker:container:restart')
assert not server.has_permission('docker:image:list')
+
+
+def test_probe_classifies_as_read():
+ """doctor:probe is a read (plan 28 #7): it expands to doctor:read, not
+ doctor:write, and is_read_action treats it as Observed-safe."""
+ assert 'probe' in Server.READ_ACTION_VERBS
+ assert Server.is_read_action('doctor:probe') is True
+ # cron:update / systemd:restart stay mutating.
+ assert Server.is_read_action('cron:update') is False
+ assert Server.is_read_action('systemd:restart') is False
+
+
+def test_scoped_profiles_grant_fleet_doctor_scopes():
+ """Each scoped canned profile must let the fleet doctor pass has_permission
+ on BOTH negotiation paths: doctor:probe (v2) and systemd:status (v1
+ composed). systemd:restart / cron:update stay OUT of the read profiles
+ (explicit grant or * only) per Decision 5."""
+ from app.api.servers import PERMISSION_PROFILES
+
+ for key in ('docker_readonly', 'docker_manager', 'deployment_runner'):
+ perms = PERMISSION_PROFILES[key]['permissions']
+ server = Server(name=f'srv-{key}', permissions=list(perms))
+ assert server.has_permission('doctor:probe'), key
+ assert server.has_permission('systemd:status'), key
+ assert server.has_permission('survey:read'), key
+ # Mutating v2 verbs must NOT be implied by the read profile.
+ assert not server.has_permission('systemd:restart'), key
+ assert not server.has_permission('cron:update'), key
+
+ # full_access ('*') covers everything, including the mutating verbs.
+ full = Server(name='full', permissions=list(PERMISSION_PROFILES['full_access']['permissions']))
+ assert full.has_permission('doctor:probe')
+ assert full.has_permission('systemd:restart')
+ assert full.has_permission('cron:update')
diff --git a/frontend/src/components/settings/TwoFactorPolicyCard.jsx b/frontend/src/components/settings/TwoFactorPolicyCard.jsx
new file mode 100644
index 00000000..4e9d8954
--- /dev/null
+++ b/frontend/src/components/settings/TwoFactorPolicyCard.jsx
@@ -0,0 +1,112 @@
+import { useEffect, useState } from 'react';
+import api from '../../services/api';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
+
+// Admin control for the require-2FA policy (plan 22 #14). A policy, never a
+// default: 'off' (nobody forced), 'admins', or 'all'. Within the grace window a
+// user still logs in with a password + a nudge; past it, login yields an
+// enrollment-scoped token until they add a passkey or authenticator app.
+// SSO-authenticated users are always exempt (the IdP owns their second factor).
+
+const POLICY_LABELS = {
+ off: 'Off — nobody is forced to enrol',
+ admins: 'Admins — admin accounts must enrol',
+ all: 'Everyone — all accounts must enrol',
+};
+
+const TwoFactorPolicyCard = () => {
+ const [policy, setPolicy] = useState('off');
+ const [graceDays, setGraceDays] = useState(7);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [message, setMessage] = useState(null);
+
+ useEffect(() => {
+ api.getSystemSettings()
+ .then((data) => {
+ setPolicy(data.security_require_2fa || 'off');
+ if (data.security_require_2fa_grace_days != null) {
+ setGraceDays(data.security_require_2fa_grace_days);
+ }
+ })
+ .catch(() => { /* leave defaults */ })
+ .finally(() => setLoading(false));
+ }, []);
+
+ async function handleSave() {
+ setSaving(true);
+ setMessage(null);
+ try {
+ await api.updateSystemSettings({
+ security_require_2fa: policy,
+ security_require_2fa_grace_days: Number(graceDays) || 0,
+ });
+ setMessage({ type: 'success', text: 'Two-factor policy saved.' });
+ } catch (err) {
+ setMessage({ type: 'error', text: err.message || 'Failed to save policy' });
+ } finally {
+ setSaving(false);
+ setTimeout(() => setMessage(null), 6000);
+ }
+ }
+
+ if (loading) return null;
+
+ return (
+ <div className="settings-card">
+ <h3>Two-Factor Authentication Policy</h3>
+ <p className="form-help" style={{ marginTop: 0 }}>
+ Require accounts to protect themselves with a passkey or authenticator
+ app. Passwords keep working until the grace window ends; after that,
+ sign-in only lets the user reach the enrolment screen until they add a
+ second factor. Single sign-on users are always exempt.
+ </p>
+
+ <div className="form-group">
+ <label>Who must enrol</label>
+ <Select value={policy} onValueChange={setPolicy}>
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(POLICY_LABELS).map(([value, label]) => (
+ <SelectItem key={value} value={value}>{label}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {policy !== 'off' && (
+ <div className="form-group">
+ <label>Grace period (days)</label>
+ <Input
+ type="number"
+ min="0"
+ value={graceDays}
+ onChange={(e) => setGraceDays(e.target.value)}
+ style={{ maxWidth: '120px' }}
+ />
+ <span className="form-help">
+ Days a newly-covered account may keep signing in with just a
+ password before enrolment is enforced.
+ </span>
+ </div>
+ )}
+
+ <div className="form-actions">
+ <Button variant="default" onClick={handleSave} disabled={saving}>
+ {saving ? 'Saving…' : 'Save policy'}
+ </Button>
+ {message && (
+ <span className={`timezone-message ${message.type}`} style={{ marginLeft: '0.75rem' }}>
+ {message.text}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default TwoFactorPolicyCard;