feat: review and revoke active devices (#325)
This commit is contained in:
1 parent
d46d296e09
commit
7034ec55ed
16 files changed
+464
-34
No files matched your search
@@ -257,6 +257,72 @@ async def test_authenticated_session_status_exposes_only_csrf_proof(access_contr
|
||||
assert "correct horse battery staple" not in response.text
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_operator_can_review_and_revoke_one_remote_device(access_control):
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with (
|
||||
httpx.AsyncClient(transport=transport, base_url="https://test") as phone,
|
||||
httpx.AsyncClient(transport=transport, base_url="https://test") as laptop,
|
||||
):
|
||||
await phone.post(
|
||||
"/api/v1/session",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"device_label": "Pixel <script>",
|
||||
},
|
||||
)
|
||||
await laptop.post(
|
||||
"/api/v1/session",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"device_label": "Work laptop",
|
||||
},
|
||||
)
|
||||
|
||||
listed = await laptop.get("/api/v1/sessions")
|
||||
devices = listed.json()["devices"]
|
||||
phone_device = next(device for device in devices if device["device_label"] == "Pixel <script>")
|
||||
current_device = next(device for device in devices if device["current"])
|
||||
|
||||
missing_csrf = await laptop.delete(
|
||||
f"/api/v1/sessions/{phone_device['management_id']}"
|
||||
)
|
||||
revoked = await laptop.delete(
|
||||
f"/api/v1/sessions/{phone_device['management_id']}",
|
||||
headers={
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": laptop.cookies["stackchain_csrf"],
|
||||
},
|
||||
)
|
||||
phone_status = await phone.get("/api/v1/session")
|
||||
laptop_status = await laptop.get("/api/v1/session")
|
||||
|
||||
assert listed.status_code == 200
|
||||
assert listed.headers["cache-control"] == "no-store"
|
||||
assert current_device["device_label"] == "Work laptop"
|
||||
assert missing_csrf.status_code == 403
|
||||
assert revoked.json() == {"revoked": True, "current_session": False}
|
||||
assert phone_status.status_code == 401
|
||||
assert laptop_status.status_code == 200
|
||||
assert "session_hash" not in listed.text
|
||||
assert "csrf" not in listed.text
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_active_device_labels_are_bounded_at_sign_in(access_control):
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/session",
|
||||
json={
|
||||
"access_token": "correct horse battery staple",
|
||||
"device_label": "x" * 65,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mutation_requires_same_origin_and_session_csrf(access_control, monkeypatch):
|
||||
calls = 0
|
||||
@@ -566,7 +632,7 @@ async def test_session_activation_does_not_block_the_event_loop(
|
||||
return None
|
||||
|
||||
class SlowStore:
|
||||
def activate(self, session_id, expires_at):
|
||||
def activate(self, session_id, expires_at, **kwargs):
|
||||
time.sleep(0.15)
|
||||
|
||||
monkeypatch.setattr(main, "_login_attempt_store", lambda: Attempts())
|
||||
@@ -670,7 +736,7 @@ async def test_session_registry_read_failure_fails_closed_before_gitea(
|
||||
@pytest.mark.anyio
|
||||
async def test_sign_in_registry_write_failure_issues_no_cookie(access_control, monkeypatch):
|
||||
class BrokenStore:
|
||||
def activate(self, session_id, expires_at):
|
||||
def activate(self, session_id, expires_at, **kwargs):
|
||||
raise SessionStoreError("database path and secret details")
|
||||
|
||||
monkeypatch.setattr(main.dashboard_auth, "_session_store", lambda now=None: BrokenStore())
|
||||
|
||||
@@ -14,7 +14,7 @@ SESSION_JS = ROOT / "frontend" / "session.js"
|
||||
def run_session_scenario(scenario: str) -> dict:
|
||||
harness = f"""
|
||||
const createSessionBoundary = require({json.dumps(str(SESSION_JS))});
|
||||
const state = {{ requests: [], removed: [], deletedDatabases: [], deletionCompleted: false, deletedCaches: [], assigned: '', replaced: [], assignedAfterDeletion: false, workerMessages: [], confirmations: [], clearErrors: [], responseStatus: 200 }};
|
||||
const state = {{ requests: [], removed: [], deletedDatabases: [], deletionCompleted: false, deletedCaches: [], assigned: '', replaced: [], assignedAfterDeletion: false, workerMessages: [], confirmations: [], clearErrors: [], responseStatus: 200, responsePayload: {{}} }};
|
||||
const storage = {{
|
||||
values: new Map([['stackchain.private', 'secret'], ['gitea.preference', 'keep']]),
|
||||
get length() {{ return this.values.size; }},
|
||||
@@ -27,7 +27,7 @@ const boundary = createSessionBoundary({{
|
||||
base: '/dashboard/',
|
||||
fetchImpl: async (url, options = {{}}) => {{
|
||||
state.requests.push({{ url: String(url), method: options.method || 'GET', headers: Object.fromEntries(new Headers(options.headers || {{}})) }});
|
||||
return new Response('{{}}', {{ status: state.responseStatus, headers: {{ 'Content-Type': 'application/json' }} }});
|
||||
return new Response(JSON.stringify(state.responsePayload), {{ status: state.responseStatus, headers: {{ 'Content-Type': 'application/json' }} }});
|
||||
}},
|
||||
localStorage: storage,
|
||||
sessionStorage: storage,
|
||||
@@ -159,6 +159,30 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["assigned"] == "/dashboard/login"
|
||||
|
||||
|
||||
def test_active_devices_can_be_loaded_and_one_remote_device_revoked():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
state.responsePayload = {devices:[
|
||||
{management_id:'remote-id-123456789', device_label:'Pixel <script>', created_at:1000, expires_at:2000, current:false},
|
||||
{management_id:'current-id-12345678', device_label:'Work laptop', created_at:1100, expires_at:2100, current:true},
|
||||
]};
|
||||
const devices = await boundary.listActiveDevices();
|
||||
await boundary.revokeActiveDevice(devices[0]);
|
||||
state.devices = devices;
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["devices"][0]["device_label"] == "Pixel <script>"
|
||||
assert result["requests"][0]["url"] == "/dashboard/api/v1/sessions"
|
||||
assert result["requests"][1]["url"] == (
|
||||
"/dashboard/api/v1/sessions/remote-id-123456789"
|
||||
)
|
||||
assert result["requests"][1]["method"] == "DELETE"
|
||||
assert result["requests"][1]["headers"]["x-csrf-token"] == "csrf-proof"
|
||||
assert result["confirmations"] == ["Sign out Pixel <script>?"]
|
||||
|
||||
|
||||
def test_authenticated_dashboard_load_requests_queued_delivery_resume():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
@@ -178,4 +202,7 @@ async def test_dashboard_loads_session_boundary_first_and_offers_sign_out():
|
||||
assert html.index('static/session.js') < html.index('static/markdown.js')
|
||||
assert '<button id="sign-out" type="button">Sign out & clear this device</button>' in html
|
||||
assert '<button id="sign-out-all" type="button">Sign out all devices</button>' in html
|
||||
assert '<button id="active-devices" type="button">Active devices</button>' in html
|
||||
assert 'id="active-devices-sheet"' in html
|
||||
assert 'aria-label="Active devices"' in html
|
||||
assert '#sign-out-all { min-height:44px; }' in html
|
||||
@@ -102,6 +102,30 @@ const controller = createLoginController({{
|
||||
)
|
||||
|
||||
|
||||
def test_login_sends_a_bounded_device_label_with_the_access_token():
|
||||
harness = f"""
|
||||
const createLoginController = require({json.dumps(str(LOGIN_JS))});
|
||||
let request = null;
|
||||
const controller = createLoginController({{
|
||||
form: {{ reset: () => {{}} }}, status: {{ textContent: '' }}, button: {{ disabled: false }},
|
||||
fetchImpl: async (url, options) => {{ request = {{url, body: JSON.parse(options.body)}}; return new Response('{{}}', {{ status: 200 }}); }},
|
||||
location: {{ replace: () => {{}} }},
|
||||
}});
|
||||
(async () => {{
|
||||
await controller.submit('operator-token', 'Timmy’s Pixel');
|
||||
process.stdout.write(JSON.stringify(request));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", harness], text=True, capture_output=True, check=True
|
||||
)
|
||||
|
||||
assert json.loads(result.stdout) == {
|
||||
"url": "api/v1/session",
|
||||
"body": {"access_token": "operator-token", "device_label": "Timmy’s Pixel"},
|
||||
}
|
||||
|
||||
|
||||
def test_shared_capture_login_explains_why_sign_in_is_required():
|
||||
harness = f"""
|
||||
const createLoginController = require({json.dumps(str(LOGIN_JS))});
|
||||
@@ -201,3 +225,5 @@ async def test_login_page_loads_rate_limit_controller():
|
||||
assert '<script src="static/login.js"></script>' in html
|
||||
assert "main{box-sizing:border-box" in html
|
||||
assert '<p id="status" role="status" aria-live="polite"></p>' in html
|
||||
assert 'name="device_label"' in html
|
||||
assert 'maxlength="64"' in html
|
||||
@@ -35,4 +35,4 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
|
||||
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
|
||||
|
||||
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
|
||||
assert "stackchain-dashboard-shell-v36" in worker
|
||||
assert "stackchain-dashboard-shell-v37" in worker
|
||||
@@ -97,7 +97,7 @@ async function dispatchNotificationClick(route) {{
|
||||
def test_share_target_sign_in_fix_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v36" in source
|
||||
assert "stackchain-dashboard-shell-v37" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -106,14 +106,14 @@ def test_share_target_sign_in_fix_ships_in_a_new_shell_cache():
|
||||
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v36" in source
|
||||
assert "stackchain-dashboard-shell-v37" in source
|
||||
assert "BASE + 'static/mobile-search-viewport.js'" in source
|
||||
|
||||
|
||||
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v36" in source
|
||||
assert "stackchain-dashboard-shell-v37" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -75,3 +75,47 @@ def test_expired_sessions_are_rejected_without_writing_during_validation(tmp_pat
|
||||
assert store.is_active("expiring-session", 1_001) is False
|
||||
with sqlite3.connect(store.path) as connection:
|
||||
assert connection.execute("SELECT COUNT(*) FROM active_sessions").fetchone() == (1,)
|
||||
|
||||
|
||||
def test_active_devices_are_listed_without_exposing_session_secrets(tmp_path):
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: 1_000.0)
|
||||
store.activate("phone-session-secret", 2_000, device_label="Pixel 9")
|
||||
store.activate("laptop-session-secret", 3_000, device_label="Work laptop")
|
||||
|
||||
devices = store.list_active("phone-session-secret")
|
||||
|
||||
assert [device.device_label for device in devices] == ["Work laptop", "Pixel 9"]
|
||||
assert [device.current for device in devices] == [False, True]
|
||||
assert all(device.management_id for device in devices)
|
||||
assert all(device.created_at == 1_000 for device in devices)
|
||||
assert "phone-session-secret" not in repr(devices)
|
||||
|
||||
|
||||
def test_revoke_managed_device_removes_only_the_selected_session(tmp_path):
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: 1_000.0)
|
||||
store.activate("phone", 2_000, device_label="Phone")
|
||||
store.activate("laptop", 2_000, device_label="Laptop")
|
||||
phone = next(device for device in store.list_active("laptop") if device.device_label == "Phone")
|
||||
|
||||
assert store.revoke_managed(phone.management_id) is True
|
||||
assert store.is_active("phone", 2_000) is False
|
||||
assert store.is_active("laptop", 2_000) is True
|
||||
assert store.revoke_managed(phone.management_id) is False
|
||||
|
||||
|
||||
def test_existing_session_registry_migrates_without_invalidating_sessions(tmp_path):
|
||||
database = tmp_path / "sessions.sqlite3"
|
||||
digest = SessionStore._digest("existing-session")
|
||||
with sqlite3.connect(database) as connection:
|
||||
connection.execute(
|
||||
"CREATE TABLE active_sessions (session_hash TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)"
|
||||
)
|
||||
connection.execute("INSERT INTO active_sessions VALUES (?, ?)", (digest, 2_000))
|
||||
|
||||
store = SessionStore(database, clock=lambda: 1_000.0)
|
||||
store.activate("new-session", 3_000, device_label="New phone")
|
||||
|
||||
assert store.is_active("existing-session", 2_000) is True
|
||||
devices = store.list_active("existing-session")
|
||||
assert len(devices) == 2
|
||||
assert next(device for device in devices if device.current).device_label == "Existing device"
|
||||
Reference in new issue
Block a user