Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Let a person, or the operator for them, sign out of all devices
Petr Bauchf08d11140210
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28de9e9be..002d139d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -74,6 +74,16 @@ version of their own to them without also giving them a release of their own.about an agent's message are still posted for the room.#### Security+- **Sign out of all devices.** Signing out used to clear only that browser's+ cookie, so a copied cookie or a browser left signed in elsewhere stayed+ valid until it expired. The account menu now has **Sign out of all+ devices**, which ends every session the account holds+ (`POST /auth/sessions/revoke`), and the server administrator can do the+ same for anyone (`POST /users/{id}/sessions/revoke`, recorded in the server+ audit log). Changing a password, including a reset made directly in the+ database, and losing the server-admin role also end every session; the+ device that changed its own password stays signed in. Sessions from before+ this release stay valid.- **Messages with files attached are checked by Switch Trust.** A message witha file used to skip the check entirely, typed text included, both from aperson on a chat platform and from an agent sending files. Now the text isdiff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex f23306413..54d2dc8f1 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -122,6 +122,9 @@ class ServerAuditAction(StrEnum):USER_DELETED = "user.deleted"USER_DELETION_REFUSED = "user.deletion_refused"USER_DELETION_FAILED = "user.deletion_failed"+ # Every session the account held was ended, by the person ("Sign out of+ # all devices") or by the operator for them.+ USER_SESSIONS_ENDED = "user.sessions_ended"WORKSPACE_DELETED = "workspace.deleted"# WorkOS refused where the directory mirror had got to in its events, and# the mirror started again from now, with a full check of every linkeddiff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex e6de67b75..2257856d7 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -70,6 +70,11 @@ from switch_core.db.session_activity_notify_ddl import (CREATE_APPROVAL_STATE_TRIGGER,CREATE_SESSION_ACTIVITY_NOTIFY_FUNCTION,)+from switch_core.db.session_version_ddl import (+ CREATE_SESSION_VERSION_FUNCTION,+ CREATE_SESSION_VERSION_TRIGGER,+ DROP_SESSION_VERSION_TRIGGER,+)from switch_core.db.tenant_lookup import attach_tenant_lookupsfrom switch_core.tenant_context import current_organization_id, current_tenant_id@@ -374,6 +379,28 @@ class User(Base):workspaces_created: Mapped[int] = mapped_column(Integer, server_default=text("0"), nullable=False)+ # Every session cookie carries the value it was minted with, and one that+ # no longer matches is refused, so incrementing it signs the person out+ # everywhere. `db/session_version_ddl.py` increments it on a password or+ # server-admin change; "Sign out of all devices" does it directly.+ session_version: Mapped[int] = mapped_column(+ Integer, server_default=text("0"), nullable=False+ )+++# Changing a password or losing the server-admin role ends every session. As+# for the triggers below, `create_all` builds it for the tests and real+# databases get it from a migration. The SQL lives in+# `db/session_version_ddl.py`.+for _ddl in (CREATE_SESSION_VERSION_FUNCTION, CREATE_SESSION_VERSION_TRIGGER):+ event.listen(+ User.__table__, "after_create", DDL(_ddl).execute_if(dialect="postgresql")+ )+event.listen(+ User.__table__,+ "before_drop",+ DDL(DROP_SESSION_VERSION_TRIGGER).execute_if(dialect="postgresql"),+)# An OIDC login matches an account on email case-insensitively (CHOO-2624):diff --git a/core/switch_core/db/session_version_ddl.py b/core/switch_core/db/session_version_ddl.pynew file mode 100644index 000000000..f76f479b9--- /dev/null+++ b/core/switch_core/db/session_version_ddl.py@@ -0,0 +1,44 @@+"""The trigger that ends a person's sessions when their password or their+server-admin role changes.++A session cookie carries the `users.session_version` it was minted with, and+every authenticated request compares it with the row (`gateway/auth.py`), so+incrementing the column signs the person out everywhere. Most reasons to do+that come through the gateway ("Sign out of all devices"), but the two that+matter most for security also happen outside it: a password is reset and an+operator is demoted by hand, in SQL. A trigger is the one place neither path+can skip.++The migration that installs this carries its own copy, frozen as it was+written; this copy is what `create_all` builds for the tests.+"""++from __future__ import annotations++SESSION_VERSION_FUNCTION_NAME = "switch_bump_session_version"+SESSION_VERSION_TRIGGER_NAME = "users_bump_session_version"++CREATE_SESSION_VERSION_FUNCTION = f"""+CREATE OR REPLACE FUNCTION {SESSION_VERSION_FUNCTION_NAME}() RETURNS trigger AS $$+BEGIN+ IF NEW.password_hash IS DISTINCT FROM OLD.password_hash+ OR (OLD.role = 'admin' AND NEW.role IS DISTINCT FROM 'admin') THEN+ NEW.session_version := OLD.session_version + 1;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql+"""++CREATE_SESSION_VERSION_TRIGGER = f"""+CREATE TRIGGER {SESSION_VERSION_TRIGGER_NAME}+ BEFORE UPDATE ON users+ FOR EACH ROW EXECUTE FUNCTION {SESSION_VERSION_FUNCTION_NAME}()+"""++DROP_SESSION_VERSION_TRIGGER = (+ f"DROP TRIGGER IF EXISTS {SESSION_VERSION_TRIGGER_NAME} ON users"+)+DROP_SESSION_VERSION_FUNCTION = (+ f"DROP FUNCTION IF EXISTS {SESSION_VERSION_FUNCTION_NAME}()"+)diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 2aa6d466e..4af5d7f53 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -5,7 +5,7 @@ from collections.abc import Collectionfrom datetime import timedeltafrom typing import NamedTuple-from sqlalchemy import case, func, select+from sqlalchemy import case, func, select, updatefrom sqlalchemy.dialects.postgresql import insertfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession@@ -184,6 +184,25 @@ class UserStore:result = await session.execute(select(User.id).where(User.id == user_id))return result.first() is not None+ async def session_version(self, session: AsyncSession, user_id: str) -> int | None:+ """The account's current session version, or None if there is no+ such account. Read without loading the row, for the reason `exists`+ gives."""+ result = await session.execute(+ select(User.session_version).where(User.id == user_id)+ )+ version: int | None = result.scalar_one_or_none()+ return version++ async def end_sessions(self, session: AsyncSession, user_id: str) -> None:+ """Invalidate every session cookie the account holds by moving its+ session version on. Lands when the caller commits."""+ await session.execute(+ update(User)+ .where(User.id == user_id)+ .values(session_version=User.session_version + 1)+ )+async def created_in_last_hour(self, session: AsyncSession) -> tuple[int, int]:"""Users created in the last hour, and whole seconds until the oldestof them leaves that window (0 when there are none).diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 70d73ad4d..56ddf2e44 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -60,6 +60,10 @@ _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})JWT_ALGORITHM = "HS256"JWT_EXPIRY_HOURS = 24+# The `users.session_version` a session was minted with. A cookie minted before+# the claim existed carries none and counts as 0, the value every account+# started at, so the deploy that added it signed nobody out.+SESSION_VERSION_CLAIM = "sv"# The `error` discriminator on the three tenant-resolution failures a client# has to tell apart. A bare `{"detail": [...]}` is indistinguishable from@@ -103,7 +107,13 @@ async def verify_password_off_loop(password: str, password_hash: str | None) ->def create_jwt(- user_id: str, email: str, role: str, keyring: Keyring, tenant_id: str | None+ user_id: str,+ email: str,+ role: str,+ keyring: Keyring,+ tenant_id: str | None,+ *,+ session_version: int,) -> str:"""Sign a session JWT. `tenant_id` is the caller's selected tenant, or`None` for a session that has not selected one yet (a fresh login, or a@@ -118,6 +128,7 @@ def create_jwt("email": email,"role": role,"tenant_id": tenant_id,+ SESSION_VERSION_CLAIM: session_version,"exp": datetime.datetime.now(datetime.UTC)+ datetime.timedelta(hours=JWT_EXPIRY_HOURS),"iat": datetime.datetime.now(datetime.UTC),@@ -149,7 +160,14 @@ def set_session_cookie(`secure` gates the Secure flag: True on HTTPS deployments so the JWT isnever sent over plain HTTP, False for local dev served over http://."""- token = create_jwt(user.id, user.email, user.role, keyring, tenant_id)+ token = create_jwt(+ user.id,+ user.email,+ user.role,+ keyring,+ tenant_id,+ session_version=user.session_version,+ )response.set_cookie(key="switch_auth",value=token,@@ -205,7 +223,7 @@ async def _authenticate(one) and `get_authenticated_user_id` (which deliberately does not)."""payload = _session_claims(request, config)- await _require_user_exists(session_factory, user_store, payload["sub"])+ await _require_current_session(session_factory, user_store, payload)return payload@@ -216,6 +234,32 @@ def _session_claims(request: HTTPConnection, config: SwitchConfig) -> dict:return decode_jwt(token, config.keyring)+def _session_version(payload: dict) -> int:+ return int(payload.get(SESSION_VERSION_CLAIM, 0))+++def _refuse_ended_session(current_version: int, payload: dict) -> None:+ """401 for a cookie minted before the account's sessions were ended: a+ password change, losing the server-admin role, or "Sign out of all+ devices" (`users.session_version`)."""+ if current_version != _session_version(payload):+ raise HTTPException(status_code=401, detail="Session ended")+++async def _require_current_session(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ payload: dict,+) -> None:+ """The cookie's subject still exists and its sessions were not ended+ since this one was minted."""+ async with session_factory() as system_session:+ version = await user_store.session_version(system_session, payload["sub"])+ if version is None:+ raise HTTPException(status_code=401, detail="User not found")+ _refuse_ended_session(version, payload)++async def _require_user_exists(session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,@@ -998,6 +1042,7 @@ async def _bound_user(if user is None:# Deleted between the two reads; rare, and still not a 500.raise HTTPException(status_code=401, detail="User not found")+ _refuse_ended_session(user.session_version, payload)request.state.platform_access = (user.role == "admin"and not await user_store.administers_by_role(session, tenant_id, user_id)@@ -1050,6 +1095,7 @@ async def authenticate_socket("""payload = _session_claims(connection, config)user_id: str = payload["sub"]+ await _require_current_session(session_factory, user_store, payload)tenant_id = await _resolve_tenant_id(session_factory,user_store,diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex c6a612f61..7fb7cb968 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -41,6 +41,7 @@ from switch_core.gateway.auth import (describe_session_state,get_authenticated_caller,get_authenticated_session,+ get_authenticated_user_id,get_current_user,hash_password_off_loop,initial_tenant_claim,@@ -337,6 +338,35 @@ async def logout(response: Response) -> dict[str, bool]:return {"ok": True}[email protected]("/auth/sessions/revoke")+async def end_my_sessions(+ response: Response,+ user_id: Annotated[str, Depends(get_authenticated_user_id)],+ session: Annotated[AsyncSession, Depends(get_system_session)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+) -> dict[str, bool]:+ """Sign out of all devices, this one included.++ `/auth/logout` clears only this browser's cookie, so a copy of it, or a+ session left open elsewhere, stays valid until it expires. This moves the+ account's session version on, which every cookie minted before it fails+ against. Needs no workspace selected, like `/tenants/{id}/switch`, so a+ person with several can always reach it.+ """+ await user_store.end_sessions(session, user_id)+ await record_server_audit_event(+ session,+ actor_user_id=user_id,+ action=ServerAuditAction.USER_SESSIONS_ENDED,+ target_type="user",+ target_id=user_id,+ details=None,+ )+ await session.commit()+ response.delete_cookie("switch_auth", path="/")+ return {"ok": True}++@router.get("/auth/config")async def auth_config(config: Annotated[SwitchConfig, Depends(get_config)],@@ -620,14 +650,33 @@ async def update_me(@router.put("/auth/me/password")async def change_password(req: ChangePasswordRequest,+ request: Request,+ response: Response,session: Annotated[AsyncSession, Depends(get_session)],user: Annotated[User, Depends(get_current_user)],+ config: Annotated[SwitchConfig, Depends(get_config)],) -> dict[str, bool]:+ """Change the signed-in person's password, signing them out everywhere+ else.++ The database ends every session on a password change+ (`db/session_version_ddl.py`), this one included, so the cookie is+ minted again from the row as it now stands: whoever changed the password+ stays signed in here, and every other copy of the old cookie is refused.+ """if not await verify_password_off_loop(req.current_password, user.password_hash):raise HTTPException(status_code=403, detail="Current password is incorrect")user.password_hash = await hash_password_off_loop(req.new_password)await session.commit()+ await session.refresh(user)+ set_session_cookie(+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ request.state.tenant_id,+ )return {"ok": True}@@ -804,6 +853,34 @@ async def delete_user(return {"ok": True}[email protected]("/users/{user_id}/sessions/revoke")+async def end_user_sessions(+ user_id: str,+ response: Response,+ session: Annotated[AsyncSession, Depends(get_session)],+ admin: Annotated[User, Depends(require_admin)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+) -> dict[str, bool]:+ """The deployment operator signs someone out of all their devices, for a+ lost laptop or an account that looks taken over. Recorded in the server's+ audit log, like the operator deleting an account."""+ if await user_store.session_version(session, user_id) is None:+ raise HTTPException(status_code=404, detail="User not found")+ await user_store.end_sessions(session, user_id)+ await record_server_audit_event(+ session,+ actor_user_id=admin.id,+ action=ServerAuditAction.USER_SESSIONS_ENDED,+ target_type="user",+ target_id=user_id,+ details=None,+ )+ await session.commit()+ if user_id == admin.id:+ response.delete_cookie("switch_auth", path="/")+ return {"ok": True}++async def _record_refusal(session: AsyncSession, operator_id: str, target_id: str, reason: str) -> None:diff --git a/core/switch_core/migrations/versions/c7b2e9f4a1d6_session_version.py b/core/switch_core/migrations/versions/c7b2e9f4a1d6_session_version.pynew file mode 100644index 000000000..1fe2baf2f--- /dev/null+++ b/core/switch_core/migrations/versions/c7b2e9f4a1d6_session_version.py@@ -0,0 +1,63 @@+"""session version: end a person's sessions everywhere++``users.session_version`` is carried in every session cookie and compared on+every request, so incrementing it signs the person out on every device. The+trigger increments it when the password hash or a server-admin role changes,+however the change is made.++Expand only: a process from before this revision neither writes nor reads the+column, and the trigger touches only rows it would have updated anyway.++Revision ID: c7b2e9f4a1d6+Revises: e5c1b7a93d28+Create Date: 2026-11-06 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "c7b2e9f4a1d6"+down_revision: str | None = "e5c1b7a93d28"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++# Copies of the DDL in `db/session_version_ddl.py`, written out here so this+# migration keeps creating the same objects if that module changes.+CREATE_SESSION_VERSION_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_bump_session_version() RETURNS trigger AS $$+BEGIN+ IF NEW.password_hash IS DISTINCT FROM OLD.password_hash+ OR (OLD.role = 'admin' AND NEW.role IS DISTINCT FROM 'admin') THEN+ NEW.session_version := OLD.session_version + 1;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql+"""++CREATE_SESSION_VERSION_TRIGGER = """+CREATE TRIGGER users_bump_session_version+ BEFORE UPDATE ON users+ FOR EACH ROW EXECUTE FUNCTION switch_bump_session_version()+"""+++def upgrade() -> None:+ op.add_column(+ "users",+ sa.Column(+ "session_version", sa.Integer(), server_default=sa.text("0"), nullable=False+ ),+ )+ op.execute(CREATE_SESSION_VERSION_FUNCTION)+ op.execute(CREATE_SESSION_VERSION_TRIGGER)+++def downgrade() -> None:+ op.execute("DROP TRIGGER IF EXISTS users_bump_session_version ON users")+ op.execute("DROP FUNCTION IF EXISTS switch_bump_session_version()")+ op.drop_column("users", "session_version")diff --git a/core/tests/switch_core/db/test_frozen_ddl_matches_create_all.py b/core/tests/switch_core/db/test_frozen_ddl_matches_create_all.pyindex f7aa327d3..625355980 100644--- a/core/tests/switch_core/db/test_frozen_ddl_matches_create_all.py+++ b/core/tests/switch_core/db/test_frozen_ddl_matches_create_all.py@@ -61,6 +61,10 @@ from switch_core.db.rls_ddl import (from switch_core.db.session_activity_notify_ddl import (SESSION_ACTIVITY_NOTIFY_FUNCTION,)+from switch_core.db.session_version_ddl import (+ SESSION_VERSION_FUNCTION_NAME,+ SESSION_VERSION_TRIGGER_NAME,+)from switch_core.db.tenant_lookup import TENANT_LOOKUPS_CORE = Path(__file__).resolve().parents[3]@@ -248,6 +252,8 @@ class _DDLSnapshot:notify_trigger_def: strsession_activity_function_body: strsession_activity_trigger_defs: dict[str, str]+ session_version_function_body: str+ session_version_trigger_def: strdef _snapshot(connection: Connection) -> _DDLSnapshot:@@ -270,6 +276,12 @@ def _snapshot(connection: Connection) -> _DDLSnapshot:name: _trigger_def(connection, table, name)for table, name in _SESSION_ACTIVITY_TRIGGERS},+ session_version_function_body=_function_body(+ connection, SESSION_VERSION_FUNCTION_NAME+ ),+ session_version_trigger_def=_trigger_def(+ connection, "users", SESSION_VERSION_TRIGGER_NAME+ ),)@@ -325,6 +337,14 @@ async def test_migration_ddl_matches_the_live_copy(ddl_parity_urls: Any) -> None# A sanity floor on the live side: if this were ever empty, every# assertion below would pass vacuously against a schema with no policies# at all, which is exactly the failure this test exists to catch.+ assert _without_comments(+ migrated.session_version_function_body+ ) == _without_comments(live.session_version_function_body), (+ "the migration's frozen switch_bump_session_version() body no longer "+ "matches db/session_version_ddl.py's live copy"+ )+ assert migrated.session_version_trigger_def == live.session_version_trigger_def+assert len(live.policies) >= 30, ("create_all did not attach any tenant_isolation policies — ""db/rls_ddl.py is not wired into Base.metadata"diff --git a/core/tests/switch_core/gateway/test_admin_delete_user.py b/core/tests/switch_core/gateway/test_admin_delete_user.pyindex 18dfa7ee0..c0bf8d38b 100644--- a/core/tests/switch_core/gateway/test_admin_delete_user.py+++ b/core/tests/switch_core/gateway/test_admin_delete_user.py@@ -81,7 +81,9 @@ def _app(def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:- token = create_jwt(user_id, email, "user", TEST_KEYRING, TENANT_ZERO_ID)+ token = create_jwt(+ user_id, email, "user", TEST_KEYRING, TENANT_ZERO_ID, session_version=0+ )return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.pyindex 14e0c783d..121caf4a3 100644--- a/core/tests/switch_core/gateway/test_change_password.py+++ b/core/tests/switch_core/gateway/test_change_password.py@@ -97,7 +97,7 @@ async def _stored_hash(def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:- token = create_jwt(user_id, email, "user", _KEYRING, None)+ token = create_jwt(user_id, email, "user", _KEYRING, None, session_version=0)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_create_user.py b/core/tests/switch_core/gateway/test_create_user.pyindex 242977d53..59351994b 100644--- a/core/tests/switch_core/gateway/test_create_user.py+++ b/core/tests/switch_core/gateway/test_create_user.py@@ -74,7 +74,9 @@ async def _admin_client()await _USER_STORE.create(session, admin)await session.commit()- token = create_jwt(admin.id, admin.email, "admin", _KEYRING, None)+ token = create_jwt(+ admin.id, admin.email, "admin", _KEYRING, None, session_version=0+ )return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex 20bdead17..7486dc0cb 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -300,7 +300,9 @@ def _app(def _client(app: Any, user: User) -> httpx.AsyncClient:- token = create_jwt(user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID)+ token = create_jwt(+ user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID, session_version=0+ )return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.pyindex b36e8b820..649408f0f 100644--- a/core/tests/switch_core/gateway/test_messaging_installs_authz.py+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py@@ -84,7 +84,9 @@ async def _member(async def _list_installs(session_factory: async_sessionmaker[AsyncSession], user_id: str, name: str) -> httpx.Response:- token = create_jwt(user_id, f"{name}@example.invalid", "user", _KEYRING, _TENANT)+ token = create_jwt(+ user_id, f"{name}@example.invalid", "user", _KEYRING, _TENANT, session_version=0+ )async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_app(session_factory)),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 5f1ad34bd..245db0161 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -137,7 +137,12 @@ def _app(def _client(app: FastAPI, user_id: str, tenant_id: str | None) -> httpx.AsyncClient:token = create_jwt(- user_id, f"{user_id}@example.invalid", "user", _KEYRING, tenant_id+ user_id,+ f"{user_id}@example.invalid",+ "user",+ _KEYRING,+ tenant_id,+ session_version=0,)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),diff --git a/core/tests/switch_core/gateway/test_query_counts.py b/core/tests/switch_core/gateway/test_query_counts.pyindex 978dba0a7..73893e29b 100644--- a/core/tests/switch_core/gateway/test_query_counts.py+++ b/core/tests/switch_core/gateway/test_query_counts.py@@ -130,7 +130,9 @@ def _app(def _client(app: Any, user: User) -> httpx.AsyncClient:- token = create_jwt(user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID)+ token = create_jwt(+ user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID, session_version=0+ )return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",diff --git a/core/tests/switch_core/gateway/test_session_keys.py b/core/tests/switch_core/gateway/test_session_keys.pyindex 70dd2f925..4af14f9c5 100644--- a/core/tests/switch_core/gateway/test_session_keys.py+++ b/core/tests/switch_core/gateway/test_session_keys.py@@ -23,7 +23,9 @@ def _keyring(value: str, legacy: str | None = None) -> Keyring:def _session(keyring: Keyring) -> str:- return create_jwt("user-1", "[email protected]", "user", keyring, "tenant-1")+ return create_jwt(+ "user-1", "[email protected]", "user", keyring, "tenant-1", session_version=0+ )def _legacy_session() -> str:diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.pyindex 454bd66aa..79b1ace13 100644--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py@@ -66,6 +66,9 @@ _ROUTES_WITH_NO_TENANT_BOUND = {# Deletes the caller's `users` row and sign-in identities, which belong to# no workspace; each workspace is left in a `tenant_session` of its own.("DELETE", "/auth/me"),+ # "Sign out of all devices" moves the caller's `users` row on, which has no+ # tenant, and must work for a caller with no workspace selected.+ ("POST", "/auth/sessions/revoke"),}# Every route that does not resolve a tenant, for any reason. `get_current_user`@@ -98,6 +101,9 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {("POST", "/auth/login"),("POST", "/auth/signup"),("POST", "/auth/logout"),+ # Signing out of all devices acts on the account, not a workspace, and a+ # caller with several and none selected must be able to reach it.+ ("POST", "/auth/sessions/revoke"),# Deleting your account acts on every workspace you are in, each in a# `tenant_session` of its own (`accounts/deletion.py`).("DELETE", "/auth/me"),diff --git a/core/tests/switch_core/gateway/test_session_version.py b/core/tests/switch_core/gateway/test_session_version.pynew file mode 100644index 000000000..c7e5d13c1--- /dev/null+++ b/core/tests/switch_core/gateway/test_session_version.py@@ -0,0 +1,311 @@+"""Ending a person's sessions everywhere (`users.session_version`).++Every session cookie carries the session version it was minted with, and one+that no longer matches the account's is refused. These drive real HTTP against+real Postgres, so the trigger that moves the version on a password or role+change (`db/session_version_ddl.py`) is the one under test, not a stand-in.+"""++from __future__ import annotations++from types import SimpleNamespace++import httpx+import jwt+from fastapi import FastAPI+from sqlalchemy import select, update+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import ServerAuditEvent, User+from switch_core.db.stores.user_store import UserStore+from switch_core.gateway import dependencies as gw_deps+from switch_core.gateway.auth import JWT_ALGORITHM, create_jwt, hash_password+from switch_core.gateway.auth_routes import router+from switch_core.keys import Keyring, Purpose++_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow+_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)+_PASSWORD = "password-one-1"++_USER_STORE = UserStore()+++def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:+ async def _session_dep():+ async with session_factory() as session:+ yield session++ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[gw_deps.get_session] = _session_dep+ app.dependency_overrides[gw_deps.get_system_session] = _session_dep+ app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory+ app.dependency_overrides[gw_deps.get_user_store] = lambda: _USER_STORE+ app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(+ keyring=_KEYRING,+ gateway_cookie_secure=False,+ gateway_password_login_enabled=True,+ gateway_tenant_choice_enabled=False,+ )+ return app+++async def _seed_user(+ session_factory: async_sessionmaker[AsyncSession], email: str, role: str = "user"+) -> str:+ async with session_factory() as session:+ user = User(+ name=email.split("@")[0],+ email=email,+ role=role,+ password_hash=hash_password(_PASSWORD),+ )+ await _USER_STORE.create(session, user)+ await session.commit()+ return user.id+++async def _version(+ session_factory: async_sessionmaker[AsyncSession], user_id: str+) -> int:+ async with session_factory() as session:+ version = await _USER_STORE.session_version(session, user_id)+ assert version is not None+ return version+++def _token(user_id: str, email: str, role: str, version: int) -> str:+ return create_jwt(user_id, email, role, _KEYRING, None, session_version=version)+++def _client(app: FastAPI, token: str) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ cookies={"switch_auth": token},+ )+++async def _status(app: FastAPI, token: str) -> int:+ async with _client(app, token) as client:+ return (await client.get("/auth/me")).status_code+++class TestTheVersionIsChecked:+ async def test_a_cookie_from_before_the_sessions_ended_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _seed_user(session_factory, "[email protected]")+ app = _app(session_factory)+ token = _token(user_id, "[email protected]", "user", 0)+ assert await _status(app, token) == 200++ async with session_factory() as session:+ await _USER_STORE.end_sessions(session, user_id)+ await session.commit()++ assert await _status(app, token) == 401+ fresh = _token(user_id, "[email protected]", "user", 1)+ assert await _status(app, fresh) == 200++ async def test_the_routes_that_bind_no_workspace_check_it_too(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _seed_user(session_factory, "[email protected]")+ app = _app(session_factory)+ stale = _token(user_id, "[email protected]", "user", 0)+ async with session_factory() as session:+ await _USER_STORE.end_sessions(session, user_id)+ await session.commit()++ async with _client(app, stale) as client:+ refused = await client.post("/auth/sessions/revoke")+ assert refused.status_code == 401+ assert await _version(session_factory, user_id) == 1++ async def test_a_cookie_minted_before_the_claim_existed_counts_as_version_0(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _seed_user(session_factory, "[email protected]")+ app = _app(session_factory)+ claims = jwt.decode(+ _token(user_id, "[email protected]", "user", 0),+ options={"verify_signature": False},+ )+ del claims["sv"]+ legacy = jwt.encode(+ claims,+ _KEYRING.derive(Purpose.SESSION),+ algorithm=JWT_ALGORITHM,+ headers={"kid": _KEYRING.current.id},+ )+ assert await _status(app, legacy) == 200++ async with session_factory() as session:+ await _USER_STORE.end_sessions(session, user_id)+ await session.commit()+ assert await _status(app, legacy) == 401+++class TestWhatEndsSessions:+ async def test_changing_the_password_ends_other_sessions_but_keeps_this_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ app = _app(session_factory)+ other_device = _token(user_id, email, "user", 0)++ async with _client(app, _token(user_id, email, "user", 0)) as client:+ changed = await client.put(+ "/auth/me/password",+ json={"current_password": _PASSWORD, "new_password": "password-two-2"},+ )+ assert changed.status_code == 200, changed.text+ assert (await client.get("/auth/me")).status_code == 200++ assert await _version(session_factory, user_id) == 1+ assert await _status(app, other_device) == 401++ async def test_a_password_reset_outside_the_gateway_ends_sessions(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _seed_user(session_factory, "[email protected]")+ async with session_factory() as session:+ await session.execute(+ update(User)+ .where(User.id == user_id)+ .values(password_hash=hash_password("reset-by-hand-1"))+ )+ await session.commit()+ assert await _version(session_factory, user_id) == 1++ async def test_losing_the_server_admin_role_ends_sessions(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email, role="admin")+ app = _app(session_factory)+ token = _token(user_id, email, "admin", 0)+ assert await _status(app, token) == 200++ async with session_factory() as session:+ await session.execute(+ update(User).where(User.id == user_id).values(role="user")+ )+ await session.commit()++ assert await _version(session_factory, user_id) == 1+ assert await _status(app, token) == 401++ async def test_other_updates_leave_sessions_alone(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ user_id = await _seed_user(session_factory, "[email protected]")+ async with session_factory() as session:+ await session.execute(+ update(User).where(User.id == user_id).values(name="Renamed")+ )+ await session.execute(+ update(User).where(User.id == user_id).values(role="admin")+ )+ await session.commit()+ assert await _version(session_factory, user_id) == 0+++class TestSigningOutEverywhere:+ async def test_logout_ends_only_this_device(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ app = _app(session_factory)+ other_device = _token(user_id, email, "user", 0)++ async with _client(app, _token(user_id, email, "user", 0)) as client:+ assert (await client.post("/auth/logout")).status_code == 200++ assert await _status(app, other_device) == 200++ async def test_signing_out_of_all_devices_ends_every_session(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ app = _app(session_factory)+ this_device = _token(user_id, email, "user", 0)+ other_device = _token(user_id, email, "user", 0)++ async with _client(app, this_device) as client:+ ended = await client.post("/auth/sessions/revoke")+ assert ended.status_code == 200, ended.text+ assert "switch_auth" in ended.headers.get("set-cookie", "")++ assert await _status(app, this_device) == 401+ assert await _status(app, other_device) == 401+ async with session_factory() as session:+ actions = (+ await session.scalars(+ select(ServerAuditEvent.action).where(+ ServerAuditEvent.target_id == user_id+ )+ )+ ).all()+ assert actions == ["user.sessions_ended"]++ async def test_the_operator_can_sign_someone_out_everywhere(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator_id = await _seed_user(+ session_factory, "[email protected]", role="admin"+ )+ person = "[email protected]"+ person_id = await _seed_user(session_factory, person)+ app = _app(session_factory)+ person_token = _token(person_id, person, "user", 0)++ operator = _token(operator_id, "[email protected]", "admin", 0)+ async with _client(app, operator) as client:+ ended = await client.post(f"/users/{person_id}/sessions/revoke")+ assert ended.status_code == 200, ended.text++ assert await _status(app, person_token) == 401+ assert await _status(app, operator) == 200+ async with session_factory() as session:+ event = (+ await session.scalars(+ select(ServerAuditEvent).where(+ ServerAuditEvent.target_id == person_id+ )+ )+ ).one()+ assert (event.action, event.actor_user_id) == (+ "user.sessions_ended",+ operator_id,+ )++ async def test_only_the_operator_can_sign_someone_else_out(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ mallory = "[email protected]"+ mallory_id = await _seed_user(session_factory, mallory)+ victim = "[email protected]"+ victim_id = await _seed_user(session_factory, victim)+ app = _app(session_factory)++ async with _client(app, _token(mallory_id, mallory, "user", 0)) as client:+ refused = await client.post(f"/users/{victim_id}/sessions/revoke")+ assert refused.status_code == 403+ assert await _version(session_factory, victim_id) == 0++ async def test_the_operator_naming_no_account_gets_404(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ operator_id = await _seed_user(+ session_factory, "[email protected]", role="admin"+ )+ app = _app(session_factory)+ token = _token(operator_id, "[email protected]", "admin", 0)+ async with _client(app, token) as client:+ missing = await client.post("/users/no-such-user/sessions/revoke")+ assert missing.status_code == 404diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex dfe13a3d8..de2cb126a 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -253,7 +253,7 @@ async def _make_member(def _token(user_id: str, email: str, tenant_id: str | None) -> str:- return create_jwt(user_id, email, "user", _KEYRING, tenant_id)+ return create_jwt(user_id, email, "user", _KEYRING, tenant_id, session_version=0)def _tenant_claim(response: httpx.Response) -> str | None:@@ -462,7 +462,14 @@ class TestCreateTenant:user_id = await _make_unaffiliated_user(session_factory, name="operator", role="admin")- token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "admin",+ _KEYRING,+ None,+ session_version=0,+ )app = _app(session_factory, signup_mode="invite_only")async with _client(app, token) as client:@@ -479,7 +486,14 @@ class TestCreateTenant:user_id = await _make_unaffiliated_user(session_factory, name="operator", role="admin")- token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "admin",+ _KEYRING,+ None,+ session_version=0,+ )lifecycle = ClientLifecycleService(provisioning=MagicMock(),client_store=MagicMock(),@@ -771,7 +785,12 @@ class TestWorkspaceCreationLimit:session_factory, name="demoted", tenant_id=TENANT_A, role="member")stale_operator_token = create_jwt(- user_id, "[email protected]", "admin", _KEYRING, TENANT_A+ user_id,+ "[email protected]",+ "admin",+ _KEYRING,+ TENANT_A,+ session_version=0,)async with _client(@@ -3022,7 +3041,12 @@ class TestErasureRoutes:user_role="admin",)operator = create_jwt(- operator_id, "[email protected]", "admin", _KEYRING, TENANT_A+ operator_id,+ "[email protected]",+ "admin",+ _KEYRING,+ TENANT_A,+ session_version=0,)person_id = await self._person(session_factory, "ana")diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.pyindex cc8169960..24a4bff98 100644--- a/core/tests/switch_core/gateway/test_tenant_resolution.py+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py@@ -415,7 +415,14 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="ready", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, TENANT_B)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ TENANT_B,+ session_version=0,+ )response = await self._get(session_factory, token, signup_mode="default_tenant")@@ -436,7 +443,9 @@ class TestSessionStateEndpoint:self, session_factory: async_sessionmaker[AsyncSession]) -> None:user_id = await _make_user(session_factory, name="single", tenant_id=TENANT_B)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )body = (await self._get(session_factory, token, signup_mode="default_tenant")@@ -451,7 +460,14 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="chooser", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )body = (await self._get(session_factory, token, signup_mode="default_tenant")@@ -469,7 +485,12 @@ class TestSessionStateEndpoint:contradicted by the very next request."""user_id = await _make_user(session_factory, name="stale", tenant_id=TENANT_B)token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, NOT_A_MEMBER_TENANT+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ NOT_A_MEMBER_TENANT,+ session_version=0,)body = (@@ -496,7 +517,12 @@ class TestSessionStateEndpoint:session.add(Tenant(id=entered, slug=entered, name="Elsewhere"))await session.commit()token = create_jwt(- operator_id, "[email protected]", "admin", _KEYRING, entered+ operator_id,+ "[email protected]",+ "admin",+ _KEYRING,+ entered,+ session_version=0,)body = (@@ -520,7 +546,12 @@ class TestSessionStateEndpoint:operator.role = "admin"await session.commit()token = create_jwt(- operator_id, "[email protected]", "admin", _KEYRING, "gone"+ operator_id,+ "[email protected]",+ "admin",+ _KEYRING,+ "gone",+ session_version=0,)body = (@@ -535,7 +566,14 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="nowhere", tenant_ids=[])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )body = (await self._get(session_factory, token, signup_mode="open")).json()@@ -573,7 +611,12 @@ class TestSessionStateEndpoint:await self._get(session_factory,create_jwt(- admin_id, "[email protected]", "user", _KEYRING, TENANT_ZERO_ID+ admin_id,+ "[email protected]",+ "user",+ _KEYRING,+ TENANT_ZERO_ID,+ session_version=0,),signup_mode="invite_only",)@@ -582,7 +625,12 @@ class TestSessionStateEndpoint:await self._get(session_factory,create_jwt(- member_id, "[email protected]", "user", _KEYRING, TENANT_ZERO_ID+ member_id,+ "[email protected]",+ "user",+ _KEYRING,+ TENANT_ZERO_ID,+ session_version=0,),signup_mode="invite_only",)@@ -603,7 +651,14 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="waiting", tenant_ids=[])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )body = (await self._get(session_factory, token, signup_mode="invite_only")@@ -618,7 +673,14 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="single", tenant_ids=[TENANT_ZERO_ID])- token = create_jwt(user_id, "[email protected]", "admin", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "admin",+ _KEYRING,+ None,+ session_version=0,+ )body = (await self._get(@@ -634,7 +696,9 @@ class TestSessionStateEndpoint:user_id = await _make_user_with_memberships(session_factory, name="mailer", tenant_ids=[TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )off = await self._get(session_factory, token, signup_mode="open")on = await self._get(@@ -672,7 +736,9 @@ class TestAGatewayRequestBindsTheCallersTenant:await session.commit()user_id = user.id- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -708,7 +774,12 @@ class TestAClaimSelectsAMembership:session_factory, name="claimant", tenant_ids=[TENANT_ZERO_ID, TENANT_B])token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, TENANT_B+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ TENANT_B,+ session_version=0,)async with _client(_app(session_factory), token) as client:@@ -724,7 +795,12 @@ class TestAClaimSelectsAMembership:session_factory, name="mismatched", tenant_id=TENANT_ZERO_ID)token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, NOT_A_MEMBER_TENANT+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ NOT_A_MEMBER_TENANT,+ session_version=0,)async with _client(_app(session_factory), token) as client:@@ -755,7 +831,14 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="undecided", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_app(session_factory, choice_enabled=False), token@@ -771,7 +854,14 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="chooser", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_app(session_factory, choice_enabled=True), token) as client:response = await client.get("/whoami")@@ -811,7 +901,14 @@ class TestNoClaimWithSeveralMemberships:user_id = await _make_user_with_memberships(session_factory, name="counted", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_app(session_factory, choice_enabled=True), token) as client:response = await client.get("/whoami")@@ -840,7 +937,9 @@ class TestAUserWithNoMembership:await session.commit()user_id = user.id- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -862,7 +961,12 @@ class TestConcurrentRequests:async def _call(user_id: str, name: str) -> dict:token = create_jwt(- user_id, f"{name}@example.invalid", "user", _KEYRING, None+ user_id,+ f"{name}@example.invalid",+ "user",+ _KEYRING,+ None,+ session_version=0,)async with _client(app, token) as client:response = await client.get("/whoami", params={"hold": 0.2})@@ -890,7 +994,9 @@ class TestListTenantsEndpoint:user_id = await _make_user_with_memberships(session_factory, name="lister", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )async with _client(_tenants_app(session_factory), token) as client:response = await client.get("/tenants")@@ -912,7 +1018,12 @@ class TestListTenantsEndpoint:session_factory, name="undecided2", tenant_ids=[TENANT_ZERO_ID, TENANT_B])token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,)async with _client(_tenants_app(session_factory), token) as client:@@ -929,7 +1040,14 @@ class TestSwitchTenantEndpoint:user_id = await _make_user_with_memberships(session_factory, name="switcher", tenant_ids=[TENANT_ZERO_ID, TENANT_B])- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_tenants_app(session_factory), token) as client:response = await client.post(f"/tenants/{TENANT_B}/switch")@@ -948,7 +1066,14 @@ class TestSwitchTenantEndpoint:user_id = await _make_user(session_factory, name="notmember", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_tenants_app(session_factory), token) as client:response = await client.post(f"/tenants/{TENANT_B}/switch")@@ -995,7 +1120,9 @@ class TestARequestHoldsOneConnection:user_id = await _make_user(one_connection_session_factory, name="solo", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ )async with _client(_app(one_connection_session_factory), token) as client:response = await client.get("/whoami")@@ -1009,7 +1136,14 @@ class TestARequestHoldsOneConnection:user_id = await _make_user(one_connection_session_factory, name="editable", tenant_id=TENANT_ZERO_ID)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )app = _app(one_connection_session_factory)@app.post("/rename")@@ -1052,7 +1186,14 @@ class TestTenantListingHoldsOneConnectionAtATime:name="poolsolo",tenant_ids=[TENANT_ZERO_ID, TENANT_B],)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_tenants_app(one_connection_session_factory), token@@ -1112,7 +1253,14 @@ class TestSigningInHoldsOneConnectionAtATime:name="poolstate",tenant_ids=[TENANT_ZERO_ID, TENANT_B],)- token = create_jwt(user_id, "[email protected]", "user", _KEYRING, None)+ token = create_jwt(+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ )async with _client(_session_app(one_connection_session_factory, signup_mode="open"), tokendiff --git a/core/tests/switch_core/gateway/test_trust_settings.py b/core/tests/switch_core/gateway/test_trust_settings.pyindex 014410b83..a8b74f686 100644--- a/core/tests/switch_core/gateway/test_trust_settings.py+++ b/core/tests/switch_core/gateway/test_trust_settings.py@@ -65,7 +65,12 @@ async def _add_user(def _cookies_for(user: User) -> dict[str, str]:return {"switch_auth": create_jwt(- user.id, user.email, user.role, TEST_KEYRING, TENANT_ZERO_ID+ user.id,+ user.email,+ user.role,+ TEST_KEYRING,+ TENANT_ZERO_ID,+ session_version=0,)}diff --git a/core/tests/switch_core/gateway/test_update_me.py b/core/tests/switch_core/gateway/test_update_me.pyindex 47da06541..55dd4070c 100644--- a/core/tests/switch_core/gateway/test_update_me.py+++ b/core/tests/switch_core/gateway/test_update_me.py@@ -74,7 +74,11 @@ def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),base_url="http://test",- cookies={"switch_auth": create_jwt(user_id, email, "user", _KEYRING, None)},+ cookies={+ "switch_auth": create_jwt(+ user_id, email, "user", _KEYRING, None, session_version=0+ )+ },)diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.pyindex b3c30557c..3c4371617 100644--- a/core/tests/switch_core/management/harness.py+++ b/core/tests/switch_core/management/harness.py@@ -343,7 +343,7 @@ async def add_member(def cookies_for(user: User, tenant_id: str = TENANT_ZERO_ID) -> dict[str, str]:return {"switch_auth": create_jwt(- user.id, user.email, user.role, TEST_KEYRING, tenant_id+ user.id, user.email, user.role, TEST_KEYRING, tenant_id, session_version=0)}diff --git a/gateway/src/data/AuthContext.tsx b/gateway/src/data/AuthContext.tsxindex 9a8b71610..7ea33d690 100644--- a/gateway/src/data/AuthContext.tsx+++ b/gateway/src/data/AuthContext.tsx@@ -6,6 +6,7 @@ import {fetchSession,login as apiLogin,logout as apiLogout,+ signOutEverywhere,switchTenant,} from "./api";import { canAdminTenant as sessionCanAdminTenant, clearPendingInvite } from "./sessionState";@@ -22,6 +23,7 @@ interface AuthState {refresh: () => Promise<void>;login: (email: string, password: string) => Promise<void>;logout: () => Promise<void>;+ logoutEverywhere: () => Promise<void>;switchTo: (tenantId: string) => Promise<void>;}@@ -89,6 +91,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {setSession(null);}, []);+ const logoutEverywhere = useCallback(async () => {+ clearPendingInvite();+ await signOutEverywhere();+ setSession(null);+ }, []);+// A full reload rather than a state update: every page holds data fetched// for the workspace it was opened in, and none of it is valid in the next.const switchTo = useCallback(async (tenantId: string) => {@@ -106,6 +114,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {refresh,login,logout,+ logoutEverywhere,switchTo,};diff --git a/gateway/src/data/api.test.ts b/gateway/src/data/api.test.tsindex 6278e8b48..f9e22925c 100644--- a/gateway/src/data/api.test.ts+++ b/gateway/src/data/api.test.ts@@ -9,6 +9,7 @@ import {fetchTeamsAppPackage,removeBridgeFromTeam,setDefaultTeamsTeam,+ signOutEverywhere,} from "./api";describe("errorText", () => {@@ -219,3 +220,23 @@ describe("fetchTeamsAppPackage", () => {);});});++describe("signOutEverywhere", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("asks the server to end every session", async () => {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ ok: true }), { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);++ await signOutEverywhere();++ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toContain("/auth/sessions/revoke");+ expect(init.method).toBe("POST");+ });++ it("throws when the server refuses", async () => {+ respond(401, { detail: "Session ended" });+ await expect(signOutEverywhere()).rejects.toBeInstanceOf(ApiError);+ });+});diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 42262fb7f..3cd9bca14 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1124,6 +1124,12 @@ export async function logout(): Promise<void> {});}+// Ends every session the account holds, this one included: a copied cookie or+// a browser left signed in elsewhere stops working at once.+export async function signOutEverywhere(): Promise<void> {+ await jsonRequest("/auth/sessions/revoke", "POST");+}+export async function fetchMe(): Promise<UserInfo | null> {return fetchJson<UserInfo>("/auth/me");}diff --git a/gateway/src/layout/NavRail.tsx b/gateway/src/layout/NavRail.tsxindex 95b47261d..d70b7cae0 100644--- a/gateway/src/layout/NavRail.tsx+++ b/gateway/src/layout/NavRail.tsx@@ -135,7 +135,7 @@ function RailItem({ item, active }: { item: NavItem; active: boolean }) {export default memo(function NavRail() {const location = useLocation();- const { user, session, isOperator, logout, switchTo } = useAuth();+ const { user, session, isOperator, logout, logoutEverywhere, switchTo } = useAuth();const [anchor, setAnchor] = useState<HTMLElement | null>(null);const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);const [createOpen, setCreateOpen] = useState(false);@@ -358,6 +358,10 @@ export default memo(function NavRail() {<LogoutOutlined sx={{ fontSize: 16 }} />Sign out</MenuItem>+ <MenuItem onClick={logoutEverywhere} sx={{ gap: 1 }}>+ <LogoutOutlined sx={{ fontSize: 16 }} />+ Sign out of all devices+ </MenuItem></Menu><Dialog open={createOpen} onClose={() => setCreateOpen(false)} maxWidth="xs" fullWidth>diff --git a/gateway/src/pages/collaborations/CollaborationsPage.test.tsx b/gateway/src/pages/collaborations/CollaborationsPage.test.tsxindex 3bfa1fe4c..99c21950e 100644--- a/gateway/src/pages/collaborations/CollaborationsPage.test.tsx+++ b/gateway/src/pages/collaborations/CollaborationsPage.test.tsx@@ -37,6 +37,7 @@ function authState(canAdminTenant: boolean) {refresh: vi.fn(async () => {}),login: vi.fn(async () => {}),logout: vi.fn(async () => {}),+ logoutEverywhere: vi.fn(async () => {}),switchTo: vi.fn(async () => {}),};}diff --git a/gateway/src/pages/rooms/GroupsPage.test.tsx b/gateway/src/pages/rooms/GroupsPage.test.tsxindex 72180e765..2c5ac505b 100644--- a/gateway/src/pages/rooms/GroupsPage.test.tsx+++ b/gateway/src/pages/rooms/GroupsPage.test.tsx@@ -27,6 +27,7 @@ function authState(canAdminTenant: boolean) {refresh: vi.fn(async () => {}),login: vi.fn(async () => {}),logout: vi.fn(async () => {}),+ logoutEverywhere: vi.fn(async () => {}),switchTo: vi.fn(async () => {}),};}