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
End dashboard sessions 14 days after sign-in
Petr Bauch5e0110b88f96
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 002d139d0..589f16f6f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -84,6 +84,13 @@ version of their own to them without also giving them a release of their own.database, and losing the server-admin role also end every session; thedevice that changed its own password stays signed in. Sessions from beforethis release stay valid.+- **Dashboard sessions end 14 days after sign-in.** A session could be+ refreshed forever, so a browser that stayed active never had to sign in+ again. Refreshing or switching workspace now keeps the original sign-in+ time, and 14 days after it the session ends and the person signs in again,+ however active they are. A session still ends after 24 hours without a+ refresh. Sessions from before this release count from when their cookie+ was issued.- **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/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 56ddf2e44..7cde0055a 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -64,6 +64,14 @@ JWT_EXPIRY_HOURS = 24# 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"+# When the person last proved who they are, as a UNIX time. Every re-mint+# (refresh, switching workspace) carries it forward, and no session outlives+# it by more than `SESSION_MAX_AGE`, however often it is refreshed: then the+# person signs in again. A cookie minted before the claim existed is taken+# to have signed in when it was minted (`iat`), the earliest moment it can+# vouch for, so the deploy that added it signed nobody out early.+AUTH_TIME_CLAIM = "auth_time"+SESSION_MAX_AGE = datetime.timedelta(days=14)# The `error` discriminator on the three tenant-resolution failures a client# has to tell apart. A bare `{"detail": [...]}` is indistinguishable from@@ -114,6 +122,7 @@ def create_jwt(tenant_id: str | None,*,session_version: int,+ auth_time: datetime.datetime,) -> 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@@ -122,16 +131,22 @@ def create_jwt(The claim only ever *selects*: `_resolve_tenant_id` re-checks it against alive membership row on every request, so a forged or stale value buysnothing (`docs/old/multi-tenancy-phase2-tenants.md`, §3).++ `auth_time` is when the person signed in: now, for a sign-in, and the+ presented session's own (`session_auth_time`) for a re-mint. A session+ signed in `SESSION_MAX_AGE` ago or longer is refused with 401 rather than+ minted again."""+ now = datetime.datetime.now(datetime.UTC)payload = {"sub": user_id,"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),+ AUTH_TIME_CLAIM: int(auth_time.timestamp()),+ "exp": session_expires_at(now, auth_time),+ "iat": now,}return jwt.encode(payload,@@ -141,12 +156,25 @@ def create_jwt()+def session_expires_at(+ now: datetime.datetime, auth_time: datetime.datetime+) -> datetime.datetime:+ """When a session minted at `now` expires: `JWT_EXPIRY_HOURS` from now,+ or `SESSION_MAX_AGE` after its sign-in if that comes first. 401 for a+ session already past the second."""+ signed_in_until = auth_time + SESSION_MAX_AGE+ if signed_in_until <= now:+ raise HTTPException(status_code=401, detail="Session too old; sign in again")+ return min(now + datetime.timedelta(hours=JWT_EXPIRY_HOURS), signed_in_until)++def set_session_cookie(response: Response,user: User,keyring: Keyring,secure: bool,tenant_id: str | None,+ auth_time: datetime.datetime,) -> None:"""Mint the switch_auth session cookie for an authenticated user.@@ -159,7 +187,13 @@ 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://.++ `auth_time` is the same as `create_jwt`'s: now for a sign-in, and+ `session_auth_time(request)` for every re-mint, so refreshing or switching+ workspace never extends a session past `SESSION_MAX_AGE`."""+ now = datetime.datetime.now(datetime.UTC)+ expires_at = session_expires_at(now, auth_time)token = create_jwt(user.id,user.email,@@ -167,6 +201,7 @@ def set_session_cookie(keyring,tenant_id,session_version=user.session_version,+ auth_time=auth_time,)response.set_cookie(key="switch_auth",@@ -174,7 +209,7 @@ def set_session_cookie(httponly=True,samesite="lax",secure=secure,- max_age=86400,+ max_age=int((expires_at - now).total_seconds()),path="/",)@@ -228,10 +263,34 @@ async def _authenticate(def _session_claims(request: HTTPConnection, config: SwitchConfig) -> dict:+ """The session cookie's claims, verified. Also records on the request+ when the session signed in, for a route that mints it again+ (`session_auth_time`)."""token = request.cookies.get("switch_auth")if token is None:raise HTTPException(status_code=401, detail="Not authenticated")- return decode_jwt(token, config.keyring)+ payload = decode_jwt(token, config.keyring)+ request.state.session_auth_time = datetime.datetime.fromtimestamp(+ payload.get(AUTH_TIME_CLAIM, payload["iat"]), datetime.UTC+ )+ return payload+++def session_auth_time(request: Request) -> datetime.datetime:+ """When the request's session signed in, for minting it again.++ Set by every dependency that authenticates the session cookie, so a route+ that re-mints one without having authenticated it is a bug, and fails here+ rather than starting the session's lifetime over.+ """+ auth_time: datetime.datetime | None = getattr(+ request.state, "session_auth_time", None+ )+ if auth_time is None:+ raise RuntimeError(+ "session_auth_time read on a request whose session was not authenticated"+ )+ return auth_timedef _session_version(payload: dict) -> int:diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 7fb7cb968..8328e48c0 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -48,6 +48,7 @@ from switch_core.gateway.auth import (list_tenant_memberships,operator_entered_workspace,require_admin,+ session_auth_time,set_session_cookie,tenants_bindable_by,verify_password_off_loop,@@ -178,6 +179,7 @@ async def login(config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),+ datetime.now(UTC),)return _session_response(user)@@ -299,6 +301,7 @@ async def signup(config.keyring,config.gateway_cookie_secure,TENANT_ZERO_ID,+ datetime.now(UTC),)signed_in = _session_response(user)machine = await _prewarm(session, session_factory, user.id, config, settings)@@ -328,6 +331,7 @@ async def refresh(config.keyring,config.gateway_cookie_secure,request.state.tenant_id,+ session_auth_time(request),)return _session_response(user)@@ -676,6 +680,7 @@ async def change_password(config.keyring,config.gateway_cookie_secure,request.state.tenant_id,+ session_auth_time(request),)return {"ok": True}diff --git a/core/switch_core/gateway/oidc_routes.py b/core/switch_core/gateway/oidc_routes.pyindex 1b7c45244..11caac357 100644--- a/core/switch_core/gateway/oidc_routes.py+++ b/core/switch_core/gateway/oidc_routes.py@@ -8,6 +8,7 @@ import loggingimport reimport timefrom contextlib import AbstractContextManager, nullcontext+from datetime import UTC, datetimefrom typing import Annotated, Anyfrom urllib.parse import urlencode, urlsplit, urlunsplit@@ -455,6 +456,7 @@ async def oidc_callback(config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),+ datetime.now(UTC),)return response@@ -499,5 +501,6 @@ async def oidc_exchange(config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),+ datetime.now(UTC),)return responsediff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 8d797f5ac..910e49606 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -59,6 +59,7 @@ from switch_core.gateway.auth import (organization_candidates,organization_workspaces_bindable_by,organizations_bindable_by,+ session_auth_time,workspaces_in_organization,workspaces_reached_through_organization,)@@ -204,6 +205,7 @@ async def list_organizations(@router.post("/organizations", status_code=201)async def create_organization(req: OrganizationCreateRequest,+ request: Request,response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session: Annotated[AsyncSession, Depends(get_system_session)],@@ -240,6 +242,7 @@ async def create_organization(config,name=req.name,workspace_name=req.workspace_name or req.name,+ auth_time=session_auth_time(request),)diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 200a0cc31..33e3e4239 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -85,6 +85,7 @@ from switch_core.gateway.auth import (may_bind_tenant,record_operator_entry,require_tenant_admin,+ session_auth_time,set_session_cookie,tenant_of_invitation_token,tenants_open_to,@@ -350,6 +351,7 @@ async def current_tenant(@router.post("/tenants", status_code=201, deprecated=True)async def create_tenant(req: TenantCreateRequest,+ request: Request,response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session: Annotated[AsyncSession, Depends(get_system_session)],@@ -381,6 +383,7 @@ async def create_tenant(config,name=req.name,workspace_name=req.name,+ auth_time=session_auth_time(request),)return created.workspace@@ -389,6 +392,7 @@ async def create_tenant(async def delete_tenant(tenant_id: str,req: TenantDeleteRequest,+ request: Request,response: Response,session: Annotated[AsyncSession, Depends(get_session)],session_factory: Annotated[@@ -445,6 +449,7 @@ async def delete_tenant(config.keyring,config.gateway_cookie_secure,await initial_tenant_claim(session_factory, user_store, user),+ session_auth_time(request),)return {"ok": True}@@ -452,6 +457,7 @@ async def delete_tenant(@router.post("/tenants/{tenant_id}/switch")async def switch_tenant(tenant_id: str,+ request: Request,response: Response,user_id: Annotated[str, Depends(get_authenticated_user_id)],session: Annotated[AsyncSession, Depends(get_system_session)],@@ -488,7 +494,12 @@ async def switch_tenant(await user_store.record_last_tenant(session, user, tenant_id)await session.commit()set_session_cookie(- response, user, config.keyring, config.gateway_cookie_secure, tenant_id+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ tenant_id,+ session_auth_time(request),)return _session_response(user)@@ -1148,6 +1159,7 @@ async def revoke_invitation(@router.post("/invitations/accept")async def accept_invitation(req: InvitationAcceptRequest,+ request: Request,response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session_factory: Annotated[@@ -1206,7 +1218,12 @@ async def accept_invitation()set_session_cookie(- response, user, config.keyring, config.gateway_cookie_secure, tenant_id+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ tenant_id,+ session_auth_time(request),)return membership@@ -1390,6 +1407,7 @@ async def list_my_invitations(@router.post("/invitations/mine/accept")async def accept_my_invitation(req: AddressedInvitationAcceptRequest,+ request: Request,response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session_factory: Annotated[@@ -1437,6 +1455,7 @@ async def accept_my_invitation(config.keyring,config.gateway_cookie_secure,req.tenant_id,+ session_auth_time(request),)return membership@@ -1587,6 +1606,7 @@ async def list_joinable_tenants(@router.post("/joinable-tenants/{tenant_id}/join")async def join_tenant_by_domain(tenant_id: str,+ request: Request,response: Response,caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],session_factory: Annotated[@@ -1634,7 +1654,12 @@ async def join_tenant_by_domain(membership, user = await _enter(session, tenant_id, caller, user_store)set_session_cookie(- response, user, config.keyring, config.gateway_cookie_secure, tenant_id+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ tenant_id,+ session_auth_time(request),)return membershipdiff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.pyindex a69443c28..ea4f8ca67 100644--- a/core/switch_core/gateway/workspace_creation.py+++ b/core/switch_core/gateway/workspace_creation.py@@ -13,6 +13,7 @@ import loggingimport reimport secretsimport uuid+from datetime import datetimefrom fastapi import HTTPException, Responsefrom sqlalchemy import select@@ -198,6 +199,7 @@ async def create_organization_for(*,name: str,workspace_name: str,+ auth_time: datetime,) -> OrganizationCreateResponse:"""Create an organization and its first workspace for `caller`, count itagainst their allowance, and switch their session into the workspace.@@ -241,7 +243,12 @@ async def create_organization_for(await user_store.record_last_tenant(session, user, tenant.id)await session.commit()set_session_cookie(- response, user, config.keyring, config.gateway_cookie_secure, tenant.id+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ tenant.id,+ auth_time,)return OrganizationCreateResponse(organization=OrganizationSummary(diff --git a/core/tests/switch_core/gateway/test_admin_delete_user.py b/core/tests/switch_core/gateway/test_admin_delete_user.pyindex c0bf8d38b..12a165795 100644--- a/core/tests/switch_core/gateway/test_admin_delete_user.py+++ b/core/tests/switch_core/gateway/test_admin_delete_user.py@@ -7,6 +7,7 @@ effects outside the database are the fakes `test_account_deletion.py` uses.from __future__ import annotations+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -82,7 +83,13 @@ 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, session_version=0+ user_id,+ email,+ "user",+ TEST_KEYRING,+ TENANT_ZERO_ID,+ session_version=0,+ auth_time=datetime.now(UTC),)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),diff --git a/core/tests/switch_core/gateway/test_auth_refresh.py b/core/tests/switch_core/gateway/test_auth_refresh.pyindex c3eb24cf8..a7d526847 100644--- a/core/tests/switch_core/gateway/test_auth_refresh.py+++ b/core/tests/switch_core/gateway/test_auth_refresh.py@@ -10,6 +10,7 @@ route coroutine directly against a lightweight config stub.from __future__ import annotations+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespacefrom fastapi import Response@@ -22,6 +23,7 @@ from switch_core.keys import Keyring# Dummy HS256 signing key for these unit tests only — not a real secret._SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)+_SIGNED_IN = datetime.now(UTC) - timedelta(days=1)def _config(*, cookie_secure: bool = False) -> SimpleNamespace:@@ -30,10 +32,12 @@ def _config(*, cookie_secure: bool = False) -> SimpleNamespace:def _request(*, tenant_id: str | None) -> SimpleNamespace:- # refresh() only reads request.state.tenant_id — the tenant- # get_current_user just resolved this request to, which it must carry- # forward into the re-minted cookie (CHOO-2723).- return SimpleNamespace(state=SimpleNamespace(tenant_id=tenant_id))+ # refresh() only reads the tenant and sign-in time get_current_user just+ # resolved this request to, which it must carry forward into the re-minted+ # cookie (CHOO-2723).+ return SimpleNamespace(+ state=SimpleNamespace(tenant_id=tenant_id, session_auth_time=_SIGNED_IN)+ )def _extract_cookie(response: Response) -> str:@@ -46,7 +50,9 @@ def _extract_cookie(response: Response) -> str:async def test_refresh_remints_cookie_for_current_user() -> None:- user = User(id="u-1", name="Ada", email="[email protected]", role="user")+ user = User(+ id="u-1", name="Ada", email="[email protected]", role="user", session_version=0+ )response = Response()result = await refresh(_request(tenant_id="tenant-0"), response, user, _config())@@ -66,7 +72,9 @@ async def test_refresh_remints_cookie_for_current_user() -> None:async def test_refresh_carries_the_selected_tenant_forward() -> None:"""The trap the design calls out by name: re-minting from `user` alonewould silently drop whichever tenant this session had selected."""- user = User(id="u-3", name="Cy", email="[email protected]", role="user")+ user = User(+ id="u-3", name="Cy", email="[email protected]", role="user", session_version=0+ )response = Response()await refresh(_request(tenant_id="tenant-b"), response, user, _config())@@ -74,10 +82,13 @@ async def test_refresh_carries_the_selected_tenant_forward() -> None:token = _extract_cookie(response)payload = decode_jwt(token, _KEYRING)assert payload["tenant_id"] == "tenant-b"+ assert payload["auth_time"] == int(_SIGNED_IN.timestamp())async def test_refresh_cookie_is_httponly_and_respects_secure_flag() -> None:- user = User(id="u-2", name="Bo", email="[email protected]", role="admin")+ user = User(+ id="u-2", name="Bo", email="[email protected]", role="admin", session_version=0+ )insecure = Response()await refresh(diff --git a/core/tests/switch_core/gateway/test_change_password.py b/core/tests/switch_core/gateway/test_change_password.pyindex 121caf4a3..d1a6402ba 100644--- a/core/tests/switch_core/gateway/test_change_password.py+++ b/core/tests/switch_core/gateway/test_change_password.py@@ -15,6 +15,7 @@ loop, and the `session_factory` fixture's connections belong to this one.from __future__ import annotations+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -97,7 +98,15 @@ async def _stored_hash(def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:- token = create_jwt(user_id, email, "user", _KEYRING, None, session_version=0)+ token = create_jwt(+ user_id,+ email,+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),+ )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 59351994b..765354eaa 100644--- a/core/tests/switch_core/gateway/test_create_user.py+++ b/core/tests/switch_core/gateway/test_create_user.py@@ -17,6 +17,7 @@ The HTTP tests drive the real auth router against real Postgres, asfrom __future__ import annotationsimport asyncio+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -75,7 +76,13 @@ async def _admin_client(await _USER_STORE.create(session, admin)await session.commit()token = create_jwt(- admin.id, admin.email, "admin", _KEYRING, None, session_version=0+ admin.id,+ admin.email,+ "admin",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),diff --git a/core/tests/switch_core/gateway/test_held_connections.py b/core/tests/switch_core/gateway/test_held_connections.pyindex 7486dc0cb..f936657f7 100644--- a/core/tests/switch_core/gateway/test_held_connections.py+++ b/core/tests/switch_core/gateway/test_held_connections.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport secretsimport threadingfrom collections.abc import AsyncIterator, Callable+from datetime import UTC, datetimefrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import MagicMock@@ -301,7 +302,13 @@ def _app(def _client(app: Any, user: User) -> httpx.AsyncClient:token = create_jwt(- user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID, session_version=0+ user.id,+ user.email,+ user.role,+ _KEYRING,+ TENANT_ZERO_ID,+ session_version=0,+ auth_time=datetime.now(UTC),)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),diff --git a/core/tests/switch_core/gateway/test_messaging_installs_authz.py b/core/tests/switch_core/gateway/test_messaging_installs_authz.pyindex 649408f0f..861fbc2cb 100644--- a/core/tests/switch_core/gateway/test_messaging_installs_authz.py+++ b/core/tests/switch_core/gateway/test_messaging_installs_authz.py@@ -14,6 +14,7 @@ listing installs sees those chats and no OAuth workspace.from __future__ import annotations+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -85,7 +86,13 @@ 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, session_version=0+ user_id,+ f"{name}@example.invalid",+ "user",+ _KEYRING,+ _TENANT,+ session_version=0,+ auth_time=datetime.now(UTC),)async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_app(session_factory)),diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 245db0161..6a2a1c3e4 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -7,7 +7,7 @@ from __future__ import annotationsimport asyncioimport uuid-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespaceimport httpx@@ -143,6 +143,7 @@ def _client(app: FastAPI, user_id: str, tenant_id: str | None) -> httpx.AsyncCli_KEYRING,tenant_id,session_version=0,+ auth_time=datetime.now(UTC),)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 73893e29b..7e26de662 100644--- a/core/tests/switch_core/gateway/test_query_counts.py+++ b/core/tests/switch_core/gateway/test_query_counts.py@@ -131,7 +131,13 @@ def _app(def _client(app: Any, user: User) -> httpx.AsyncClient:token = create_jwt(- user.id, user.email, user.role, _KEYRING, TENANT_ZERO_ID, session_version=0+ user.id,+ user.email,+ user.role,+ _KEYRING,+ TENANT_ZERO_ID,+ session_version=0,+ auth_time=datetime.now(UTC),)return httpx.AsyncClient(transport=httpx.ASGITransport(app=app),diff --git a/core/tests/switch_core/gateway/test_session_keys.py b/core/tests/switch_core/gateway/test_session_keys.pyindex 4af14f9c5..3b4b7c4dd 100644--- a/core/tests/switch_core/gateway/test_session_keys.py+++ b/core/tests/switch_core/gateway/test_session_keys.py@@ -24,7 +24,13 @@ 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", session_version=0+ "user-1",+ "[email protected]",+ "user",+ keyring,+ "tenant-1",+ session_version=0,+ auth_time=datetime.datetime.now(datetime.UTC),)diff --git a/core/tests/switch_core/gateway/test_session_lifetime.py b/core/tests/switch_core/gateway/test_session_lifetime.pynew file mode 100644index 000000000..38efe74a5--- /dev/null+++ b/core/tests/switch_core/gateway/test_session_lifetime.py@@ -0,0 +1,198 @@+"""No session outlives its sign-in by more than `SESSION_MAX_AGE`.++A session cookie carries when the person signed in (`auth_time`). Refreshing+keeps it, and caps the new cookie's expiry at `SESSION_MAX_AGE` after it, so+an active client can renew every day and still has to sign in again in the+end. Real HTTP against real Postgres, like `test_session_version.py`.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++import httpx+import jwt+import pytest+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import 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,+ JWT_EXPIRY_HOURS,+ SESSION_MAX_AGE,+ create_jwt,+ decode_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+) -> str:+ async with session_factory() as session:+ user = User(+ name=email.split("@")[0],+ email=email,+ role="user",+ password_hash=hash_password(_PASSWORD),+ )+ await _USER_STORE.create(session, user)+ await session.commit()+ return user.id+++def _session_signed_in(+ user_id: str, email: str, signed_in: datetime, *, with_auth_time: bool = True+) -> str:+ """A valid, unexpired cookie whose sign-in was `signed_in`. With+ `with_auth_time` False it is shaped like a cookie from before the claim+ existed, minted (`iat`) at `signed_in`."""+ claims = decode_jwt(+ create_jwt(+ user_id,+ email,+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),+ ),+ _KEYRING,+ )+ if with_auth_time:+ claims["auth_time"] = int(signed_in.timestamp())+ else:+ del claims["auth_time"]+ claims["iat"] = int(signed_in.timestamp())+ return jwt.encode(+ claims,+ _KEYRING.derive(Purpose.SESSION),+ algorithm=JWT_ALGORITHM,+ headers={"kid": _KEYRING.current.id},+ )+++def _client(app: FastAPI, token: str | None) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ cookies={} if token is None else {"switch_auth": token},+ )+++async def test_signing_in_starts_the_session_now(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ email = "[email protected]"+ await _seed_user(session_factory, email)+ before = int(datetime.now(UTC).timestamp())++ async with _client(_app(session_factory), None) as client:+ signed_in = await client.post(+ "/auth/login", json={"email": email, "password": _PASSWORD}+ )++ assert signed_in.status_code == 200, signed_in.text+ claims = decode_jwt(signed_in.cookies["switch_auth"], _KEYRING)+ assert before <= claims["auth_time"] <= int(datetime.now(UTC).timestamp())+ assert claims["exp"] - claims["iat"] == JWT_EXPIRY_HOURS * 3600+++async def test_refreshing_keeps_when_the_session_signed_in(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ signed_in = datetime.now(UTC) - timedelta(days=3)++ async with _client(+ _app(session_factory), _session_signed_in(user_id, email, signed_in)+ ) as client:+ renewed = await client.post("/auth/refresh")++ assert renewed.status_code == 200, renewed.text+ claims = decode_jwt(renewed.cookies["switch_auth"], _KEYRING)+ assert claims["auth_time"] == int(signed_in.timestamp())+++async def test_the_last_refresh_expires_when_the_session_reaches_its_limit(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ signed_in = datetime.now(UTC) - SESSION_MAX_AGE + timedelta(hours=2)++ async with _client(+ _app(session_factory), _session_signed_in(user_id, email, signed_in)+ ) as client:+ renewed = await client.post("/auth/refresh")++ assert renewed.status_code == 200, renewed.text+ claims = decode_jwt(renewed.cookies["switch_auth"], _KEYRING)+ assert claims["exp"] == int((signed_in + SESSION_MAX_AGE).timestamp())+ max_age = int(renewed.headers["set-cookie"].split("Max-Age=")[1].split(";")[0])+ assert max_age <= 2 * 3600++[email protected]("with_auth_time", [True, False])+async def test_a_session_past_its_limit_cannot_be_refreshed(+ session_factory: async_sessionmaker[AsyncSession], with_auth_time: bool+) -> None:+ email = f"stale-{with_auth_time}@example.invalid"+ user_id = await _seed_user(session_factory, email)+ signed_in = datetime.now(UTC) - SESSION_MAX_AGE - timedelta(minutes=1)+ token = _session_signed_in(user_id, email, signed_in, with_auth_time=with_auth_time)++ async with _client(_app(session_factory), token) as client:+ refused = await client.post("/auth/refresh")++ assert refused.status_code == 401+ assert "switch_auth" not in refused.cookies+++async def test_a_cookie_from_before_the_claim_counts_from_when_it_was_minted(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ email = "[email protected]"+ user_id = await _seed_user(session_factory, email)+ minted = datetime.now(UTC) - timedelta(hours=1)+ token = _session_signed_in(user_id, email, minted, with_auth_time=False)++ async with _client(_app(session_factory), token) as client:+ renewed = await client.post("/auth/refresh")++ assert renewed.status_code == 200, renewed.text+ claims = decode_jwt(renewed.cookies["switch_auth"], _KEYRING)+ assert claims["auth_time"] == int(minted.timestamp())diff --git a/core/tests/switch_core/gateway/test_session_version.py b/core/tests/switch_core/gateway/test_session_version.pyindex c7e5d13c1..581a2098a 100644--- a/core/tests/switch_core/gateway/test_session_version.py+++ b/core/tests/switch_core/gateway/test_session_version.py@@ -8,6 +8,7 @@ change (`db/session_version_ddl.py`) is the one under test, not a stand-in.from __future__ import annotations+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -75,7 +76,15 @@ async def _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)+ return create_jwt(+ user_id,+ email,+ role,+ _KEYRING,+ None,+ session_version=version,+ auth_time=datetime.now(UTC),+ )def _client(app: FastAPI, token: str) -> httpx.AsyncClient:diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex de2cb126a..34e72cb88 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -24,6 +24,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport httpx+import jwtimport pytestfrom fastapi import FastAPIfrom sqlalchemy import select@@ -73,14 +74,19 @@ from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway import dependencies as gw_deps-from switch_core.gateway.auth import create_jwt, decode_jwt+from switch_core.gateway.auth import (+ JWT_ALGORITHM,+ SESSION_MAX_AGE,+ create_jwt,+ decode_jwt,+)from switch_core.gateway.invite_mail import (InviteEmail,InviteEmailFailed,InviteMailer,)from switch_core.gateway.tenants import router as tenants_router-from switch_core.keys import Keyring+from switch_core.keys import Keyring, Purposefrom switch_core.organization_directory import LocalDirectoryfrom tests.ownership import NeverOwnedfrom tests.switch_core.statement_counts import StatementCounts@@ -253,7 +259,15 @@ 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, session_version=0)+ return create_jwt(+ user_id,+ email,+ "user",+ _KEYRING,+ tenant_id,+ session_version=0,+ auth_time=datetime.now(UTC),+ )def _tenant_claim(response: httpx.Response) -> str | None:@@ -469,6 +483,7 @@ class TestCreateTenant:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)app = _app(session_factory, signup_mode="invite_only")@@ -493,6 +508,7 @@ class TestCreateTenant:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)lifecycle = ClientLifecycleService(provisioning=MagicMock(),@@ -791,6 +807,7 @@ class TestWorkspaceCreationLimit:_KEYRING,TENANT_A,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(@@ -1923,6 +1940,48 @@ class TestOrganizationAdmins:assert switched.status_code == 200, switched.textassert _tenant_claim(switched) == TENANT_B+ @pytest.mark.parametrize(+ ("signed_in_days_ago", "status"), [(3, 200), (SESSION_MAX_AGE.days + 1, 401)]+ )+ async def test_switching_keeps_when_the_session_signed_in(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ signed_in_days_ago: int,+ status: int,+ ) -> None:+ admin_id = await _make_unaffiliated_user(+ session_factory, name="org-admin", role="user"+ )+ await self._organization_of(+ session_factory, TENANT_A, TENANT_B, members={admin_id: "org_admin"}+ )+ signed_in = datetime.now(UTC) - timedelta(days=signed_in_days_ago)+ token = create_jwt(+ admin_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),+ )+ claims = decode_jwt(token, _KEYRING)+ claims["auth_time"] = int(signed_in.timestamp())+ forged = jwt.encode(+ claims,+ _KEYRING.derive(Purpose.SESSION),+ algorithm=JWT_ALGORITHM,+ headers={"kid": _KEYRING.current.id},+ )++ async with _client(_app(session_factory), forged) as client:+ switched = await client.post(f"/tenants/{TENANT_B}/switch")++ assert switched.status_code == status, switched.text+ if status == 200:+ minted = decode_jwt(switched.cookies["switch_auth"], _KEYRING)+ assert minted["auth_time"] == int(signed_in.timestamp())+async def test_an_org_admin_may_not_bind_another_organizations_workspace(self, session_factory: async_sessionmaker[AsyncSession]) -> None:@@ -3047,6 +3106,7 @@ class TestErasureRoutes:_KEYRING,TENANT_A,session_version=0,+ auth_time=datetime.now(UTC),)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 24a4bff98..a209a7c57 100644--- a/core/tests/switch_core/gateway/test_tenant_resolution.py+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py@@ -39,6 +39,7 @@ from __future__ import annotationsimport asyncioimport uuidfrom collections.abc import AsyncIterator+from datetime import UTC, datetimefrom types import SimpleNamespacefrom typing import Annotated@@ -422,6 +423,7 @@ class TestSessionStateEndpoint:_KEYRING,TENANT_B,session_version=0,+ auth_time=datetime.now(UTC),)response = await self._get(session_factory, token, signup_mode="default_tenant")@@ -444,7 +446,13 @@ class TestSessionStateEndpoint:) -> None:user_id = await _make_user(session_factory, name="single", tenant_id=TENANT_B)token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -467,6 +475,7 @@ class TestSessionStateEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -491,6 +500,7 @@ class TestSessionStateEndpoint:_KEYRING,NOT_A_MEMBER_TENANT,session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -523,6 +533,7 @@ class TestSessionStateEndpoint:_KEYRING,entered,session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -552,6 +563,7 @@ class TestSessionStateEndpoint:_KEYRING,"gone",session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -573,6 +585,7 @@ class TestSessionStateEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)body = (await self._get(session_factory, token, signup_mode="open")).json()@@ -617,6 +630,7 @@ class TestSessionStateEndpoint:_KEYRING,TENANT_ZERO_ID,session_version=0,+ auth_time=datetime.now(UTC),),signup_mode="invite_only",)@@ -631,6 +645,7 @@ class TestSessionStateEndpoint:_KEYRING,TENANT_ZERO_ID,session_version=0,+ auth_time=datetime.now(UTC),),signup_mode="invite_only",)@@ -658,6 +673,7 @@ class TestSessionStateEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -680,6 +696,7 @@ class TestSessionStateEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)body = (@@ -697,7 +714,13 @@ class TestSessionStateEndpoint:session_factory, name="mailer", tenant_ids=[TENANT_B])token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)off = await self._get(session_factory, token, signup_mode="open")@@ -737,7 +760,13 @@ class TestAGatewayRequestBindsTheCallersTenant:user_id = user.idtoken = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -780,6 +809,7 @@ class TestAClaimSelectsAMembership:_KEYRING,TENANT_B,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory), token) as client:@@ -801,6 +831,7 @@ class TestAClaimSelectsAMembership:_KEYRING,NOT_A_MEMBER_TENANT,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory), token) as client:@@ -838,6 +869,7 @@ class TestNoClaimWithSeveralMemberships:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(@@ -861,6 +893,7 @@ class TestNoClaimWithSeveralMemberships:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory, choice_enabled=True), token) as client:@@ -908,6 +941,7 @@ class TestNoClaimWithSeveralMemberships:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory, choice_enabled=True), token) as client:@@ -938,7 +972,13 @@ class TestAUserWithNoMembership:user_id = user.idtoken = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(session_factory), token) as client:response = await client.get("/whoami")@@ -967,6 +1007,7 @@ class TestConcurrentRequests:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(app, token) as client:response = await client.get("/whoami", params={"hold": 0.2})@@ -995,7 +1036,13 @@ class TestListTenantsEndpoint:session_factory, name="lister", tenant_ids=[TENANT_ZERO_ID, TENANT_B])token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_tenants_app(session_factory), token) as client:@@ -1024,6 +1071,7 @@ class TestListTenantsEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_tenants_app(session_factory), token) as client:@@ -1047,6 +1095,7 @@ class TestSwitchTenantEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_tenants_app(session_factory), token) as client:@@ -1073,6 +1122,7 @@ class TestSwitchTenantEndpoint:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_tenants_app(session_factory), token) as client:@@ -1121,7 +1171,13 @@ class TestARequestHoldsOneConnection:one_connection_session_factory, name="solo", tenant_id=TENANT_ZERO_ID)token = create_jwt(- user_id, "[email protected]", "user", _KEYRING, None, session_version=0+ user_id,+ "[email protected]",+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)async with _client(_app(one_connection_session_factory), token) as client:@@ -1143,6 +1199,7 @@ class TestARequestHoldsOneConnection:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)app = _app(one_connection_session_factory)@@ -1193,6 +1250,7 @@ class TestTenantListingHoldsOneConnectionAtATime:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(@@ -1260,6 +1318,7 @@ class TestSigningInHoldsOneConnectionAtATime:_KEYRING,None,session_version=0,+ auth_time=datetime.now(UTC),)async with _client(diff --git a/core/tests/switch_core/gateway/test_trust_settings.py b/core/tests/switch_core/gateway/test_trust_settings.pyindex a8b74f686..b1d339f8d 100644--- a/core/tests/switch_core/gateway/test_trust_settings.py+++ b/core/tests/switch_core/gateway/test_trust_settings.py@@ -7,6 +7,7 @@ is never echoed back, and a PUT that omits it leaves the stored one alone.from __future__ import annotationsfrom collections.abc import AsyncIterator+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -71,6 +72,7 @@ def _cookies_for(user: User) -> dict[str, str]:TEST_KEYRING,TENANT_ZERO_ID,session_version=0,+ auth_time=datetime.now(UTC),)}diff --git a/core/tests/switch_core/gateway/test_update_me.py b/core/tests/switch_core/gateway/test_update_me.pyindex 55dd4070c..1cfc6afe8 100644--- a/core/tests/switch_core/gateway/test_update_me.py+++ b/core/tests/switch_core/gateway/test_update_me.py@@ -8,6 +8,7 @@ the write was issued.from __future__ import annotations+from datetime import UTC, datetimefrom types import SimpleNamespaceimport httpx@@ -76,7 +77,13 @@ def _client(app: FastAPI, user_id: str, email: str) -> httpx.AsyncClient:base_url="http://test",cookies={"switch_auth": create_jwt(- user_id, email, "user", _KEYRING, None, session_version=0+ user_id,+ email,+ "user",+ _KEYRING,+ None,+ session_version=0,+ auth_time=datetime.now(UTC),)},)diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.pyindex 3c4371617..53307be7d 100644--- a/core/tests/switch_core/management/harness.py+++ b/core/tests/switch_core/management/harness.py@@ -343,7 +343,13 @@ 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, session_version=0+ user.id,+ user.email,+ user.role,+ TEST_KEYRING,+ tenant_id,+ session_version=0,+ auth_time=datetime.now(UTC),)}