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
fix(db): make an invitation's three gates the store's job, not each caller's
Petr Bauchf7829e566201
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 579df1fc9..f61bfb12f 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -1,4 +1,5 @@import uuid+from datetime import datetimefrom sqlalchemy import (DDL,@@ -287,6 +288,14 @@ class Invitation(TenantScoped, Base):None of the three are optional here — a table that could not expire or berevoked would not be a credential, and the design this implements isexplicit that expiry and revocation are not optional.++ The floor under `uses_remaining` is a constraint rather than a convention+ because the thing it guards against is a lost race, not a typo: two+ concurrent acceptances of a single-use invitation can both read `1` and+ both write `0`, and read-committed will let both commit. `consume`+ (`db/stores/invitation_store.py`) is the decrement that cannot lose that+ race; the constraint is what makes any other decrement fail loudly instead+ of over-granting membership."""__tablename__ = "invitations"@@ -294,6 +303,9 @@ class Invitation(TenantScoped, Base):CheckConstraint("role IN ('owner', 'admin', 'member')", name="ck_invitations_role"),+ CheckConstraint(+ "uses_remaining >= 0", name="ck_invitations_uses_remaining_not_negative"+ ),)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)@@ -303,15 +315,17 @@ class Invitation(TenantScoped, Base):# resolves the hash before a tenant is known, so it cannot be scoped by# one.token_hash: Mapped[str] = mapped_column(Text, unique=True, nullable=False)- expires_at: Mapped[str] = mapped_column(DateTime(timezone=True), nullable=False)+ expires_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False+ )uses_remaining: Mapped[int] = mapped_column(Integer, nullable=False)- revoked_at: Mapped[str | None] = mapped_column(+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)created_by: Mapped[str] = mapped_column(Text, ForeignKey("users.id"), nullable=False)- created_at: Mapped[str] = mapped_column(+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)diff --git a/core/switch_core/db/stores/invitation_store.py b/core/switch_core/db/stores/invitation_store.pyindex c7d9fa419..0e6b73d1e 100644--- a/core/switch_core/db/stores/invitation_store.py+++ b/core/switch_core/db/stores/invitation_store.py@@ -4,7 +4,7 @@ import hashlibimport secretsfrom datetime import UTC, datetime-from sqlalchemy import select+from sqlalchemy import ColumnElement, and_, func, select, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.db.models import Invitation@@ -12,6 +12,33 @@ from switch_core.db.models import Invitation_TOKEN_BYTES = 32+class InvitationNotUsableError(Exception):+ """An invitation was asked to grant membership and could not.++ Raised rather than returned as `None`, because the three ways to get here+ — revoked, expired, spent — are all states a caller has to answer for+ rather than states it can usefully retry or ignore. Also raised when the+ invitation does not exist at all, or belongs to a tenant this session is+ not bound to: the row-level-security policy makes those indistinguishable+ from the outside, which is the point of it.+ """+++def _usable() -> ColumnElement[bool]:+ """The three independent gates on an invitation, as one predicate.++ Written once and shared by everything that asks the question, because+ three gates hand-rolled per call site is how the second call site ends up+ checking two. Postgres evaluates it — expiry against the database's clock,+ not the caller's — so `consume` can decide and decrement in one statement.+ """+ return and_(+ Invitation.revoked_at.is_(None),+ Invitation.expires_at > func.now(),+ Invitation.uses_remaining > 0,+ )++def generate_invitation_token() -> tuple[str, str]:"""A fresh invitation token and the hash that is all Switch ever stores.@@ -72,6 +99,53 @@ class InvitationStore:)return result.scalar_one_or_none()+ async def get_valid_by_token_hash(+ self, session: AsyncSession, token_hash: str+ ) -> Invitation | None:+ """The invitation named by a token's hash, if it is still usable.++ What `get_by_token_hash` finds says nothing about whether the token+ still works: a revoked, expired or spent invitation is an ordinary row+ and reads back like any other. This is the read for anyone about to+ act on one — showing the invitee what they were invited to, say —+ and it answers with the same predicate `consume` enforces.++ A `None` here is not permission to skip `consume`'s own check. The row+ can be spent between the two by whoever else holds the same link;+ `consume` is where that race is settled.+ """+ result = await session.execute(+ select(Invitation).where(Invitation.token_hash == token_hash, _usable())+ )+ return result.scalar_one_or_none()++ async def consume(self, session: AsyncSession, invitation_id: str) -> Invitation:+ """Spend one use of an invitation, or refuse.++ One conditional `UPDATE`: the gates are in the `WHERE`, so the row is+ checked and decremented in the same statement and Postgres arbitrates+ between concurrent acceptances. Read-then-write cannot do that — two+ acceptances of a single-use invitation both read `1`, both write `0`,+ both commit, and one invite grants two memberships.++ No row updated means no usable invitation was there to update, which+ is what `InvitationNotUsableError` reports.+ """+ result = await session.execute(+ update(Invitation)+ .where(Invitation.id == invitation_id, _usable())+ .values(uses_remaining=Invitation.uses_remaining - 1)+ .returning(Invitation)+ .execution_options(populate_existing=True)+ )+ invitation = result.scalar_one_or_none()+ if invitation is None:+ raise InvitationNotUsableError(+ f"Invitation {invitation_id} is revoked, expired, spent, or not "+ "visible to this session"+ )+ return invitation+async def list_for_tenant(self, session: AsyncSession) -> list[Invitation]:"""Every invitation of the session's bound tenant.@@ -87,6 +161,6 @@ class InvitationStore:invitation = await session.get(Invitation, invitation_id)if invitation is None:raise ValueError(f"Invitation not found: {invitation_id}")- invitation.revoked_at = datetime.now(UTC) # type: ignore[assignment]+ invitation.revoked_at = datetime.now(UTC)await session.flush()return invitationdiff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.pyindex c99ff92e0..dcb3fbcfe 100644--- a/core/switch_core/db/tenant_lookup.py+++ b/core/switch_core/db/tenant_lookup.py@@ -102,9 +102,11 @@ request carries a token and nothing else, no tenant is bound yet, and thetable it would have to read (`invitations`) is tenant-scoped like everythingelse, so the policy refuses exactly the read that has to happen first. Resolvethe tenant here, bind it, then read the invitation itself — its role, its-email, whether it is spent or revoked — through the ordinary scoped store.-Nothing about *that* row crosses the exemption; only the tenant id does, which-is the property every lookup in this module rests on.+email, whether it is spent, expired or revoked — through the ordinary scoped+store, whose `get_valid_by_token_hash` and `consume` are where those three+gates are actually enforced. Nothing about *that* row crosses the exemption;+only the tenant id does, which is the property every lookup in this module+rests on.Why not the obvious alternatives is argued in`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the shortdiff --git a/core/switch_core/migrations/versions/5daaea6b674d_invitations.py b/core/switch_core/migrations/versions/5daaea6b674d_invitations.pyindex d30e2d615..a44e9c4ce 100644--- a/core/switch_core/migrations/versions/5daaea6b674d_invitations.py+++ b/core/switch_core/migrations/versions/5daaea6b674d_invitations.py@@ -13,6 +13,13 @@ before a tenant is known, so a per-tenant index could not answer the questionbeing asked. Only the hash is ever stored — the token itself never reachesthis table, or any other.+`uses_remaining >= 0` is a constraint and not a convention because the failure+it prevents is a lost race rather than a typo: two concurrent acceptances of a+single-use invitation can both read `1` and both write `0` under read-+committed, and both commit. The store's `consume` does the decrement as one+conditional `UPDATE` so that cannot happen; this constraint is what makes any+future decrement that forgets fail loudly rather than grant membership twice.+`tenant_of_invitation(token_hash)` is the lookup that resolves it, and it isan addition to the closed set of `SECURITY DEFINER` functions `9c41a7b0e5d8`installed as the whole exemption from row-level security. That set is@@ -92,6 +99,9 @@ def upgrade() -> None:sa.CheckConstraint("role IN ('owner', 'admin', 'member')", name="ck_invitations_role"),+ sa.CheckConstraint(+ "uses_remaining >= 0", name="ck_invitations_uses_remaining_not_negative"+ ),sa.PrimaryKeyConstraint("id"),sa.ForeignKeyConstraint(["tenant_id"], ["tenants.id"], name="fk_invitations_tenant"diff --git a/core/tests/switch_core/db/stores/test_invitation_store.py b/core/tests/switch_core/db/stores/test_invitation_store.pyindex 34159a8c9..2514be439 100644--- a/core/tests/switch_core/db/stores/test_invitation_store.py+++ b/core/tests/switch_core/db/stores/test_invitation_store.py@@ -11,17 +11,20 @@ with no tenant filter of the store's own doing the work.from __future__ import annotations+import asyncioimport hashlibimport uuidfrom datetime import UTC, datetime, timedeltaimport pytest-from sqlalchemy.exc import DBAPIError+from sqlalchemy import text+from sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import Tenant, User+from switch_core.db.models import Invitation, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.invitation_store import (+ InvitationNotUsableError,InvitationStore,generate_invitation_token,)@@ -41,6 +44,66 @@ def _expires_soon() -> datetime:return datetime.now(UTC) + timedelta(days=7)+async def _make_invitation(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ uses_remaining: int = 1,+ expires_at: datetime | None = None,+ revoked: bool = False,+) -> tuple[str, str]:+ """An invitation in the state the test needs, as `(id, token_hash)`."""+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ invitation, token = await _STORE.create(+ session,+ role="member",+ email=None,+ expires_at=expires_at if expires_at is not None else _expires_soon(),+ uses_remaining=uses_remaining,+ created_by=owner.id,+ )+ if revoked:+ invitation.revoked_at = datetime.now(UTC)+ await session.commit()+ return invitation.id, hashlib.sha256(token.encode()).hexdigest()+++# The three independent ways an invitation stops working. Shared by the two+# classes below so that a fourth gate cannot be added to one and forgotten in+# the other.+_UNUSABLE: list[dict[str, object]] = [+ {"revoked": True},+ {"expires_at": datetime.now(UTC) - timedelta(seconds=1)},+ {"uses_remaining": 0},+]+_UNUSABLE_IDS = ["revoked", "expired", "spent"]+++async def _consume_racing(+ session_factory: async_sessionmaker[AsyncSession],+ invitation_id: str,+ barrier: asyncio.Barrier,+) -> bool:+ """Consume in a session of its own, timed to collide with the other one.++ The `SELECT 1` before the barrier is what makes the collision real. A+ session that has not spoken to the database yet has no connection: the+ second acceptance would spend the race connecting and authenticating, land+ after the first has already committed, and read the state it was supposed+ to read *concurrently with*. That test passes against a double-spending+ implementation, which is the opposite of the point.+ """+ async with session_factory() as session:+ await session.execute(text("SELECT 1"))+ await barrier.wait()+ try:+ await _STORE.consume(session, invitation_id)+ except InvitationNotUsableError:+ return False+ await session.commit()+ return True++class TestTokenGeneration:def test_the_token_and_its_hash_are_not_the_same_string(self) -> None:token, token_hash = generate_invitation_token()@@ -156,6 +219,119 @@ class TestInvitationStoreRoundTrip:await _STORE.revoke(session, "nope")+class TestAskingWhetherAnInvitationIsUsable:+ """`get_by_token_hash` finds the row; it says nothing about the token.++ Revoked, expired and spent are three independent gates, and the reason+ they are expressed once in the store rather than at each call site is that+ a caller checking two of the three looks exactly like a caller checking+ all three until the day it doesn't.+ """++ @pytest.mark.parametrize("kwargs", _UNUSABLE, ids=_UNUSABLE_IDS)+ async def test_an_unusable_invitation_is_found_but_not_valid(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ kwargs: dict[str, object],+ ) -> None:+ _id, token_hash = await _make_invitation(session_factory, **kwargs) # type: ignore[arg-type]+ async with session_factory() as session:+ assert await _STORE.get_by_token_hash(session, token_hash) is not None, (+ "an unusable invitation is still an ordinary row"+ )+ assert await _STORE.get_valid_by_token_hash(session, token_hash) is None, (+ "an unusable invitation must not read back as usable"+ )++ async def test_a_usable_invitation_reads_back_from_both(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ invitation_id, token_hash = await _make_invitation(session_factory)+ async with session_factory() as session:+ valid = await _STORE.get_valid_by_token_hash(session, token_hash)+ assert valid is not None+ assert valid.id == invitation_id+++class TestConsume:+ async def test_consuming_spends_one_use(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ invitation_id, _hash = await _make_invitation(session_factory, uses_remaining=3)+ async with session_factory() as session:+ consumed = await _STORE.consume(session, invitation_id)+ assert consumed.uses_remaining == 2+ await session.commit()++ @pytest.mark.parametrize("kwargs", _UNUSABLE, ids=_UNUSABLE_IDS)+ async def test_an_unusable_invitation_refuses_to_be_consumed(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ kwargs: dict[str, object],+ ) -> None:+ """The gates are in the `UPDATE`'s `WHERE`, so each of the three is+ enforced by the statement that would have granted membership rather+ than by whatever the caller remembered to check first."""+ invitation_id, _hash = await _make_invitation(session_factory, **kwargs) # type: ignore[arg-type]+ async with session_factory() as session:+ with pytest.raises(InvitationNotUsableError):+ await _STORE.consume(session, invitation_id)++ async def test_consuming_an_invitation_that_does_not_exist_refuses(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(InvitationNotUsableError):+ await _STORE.consume(session, "no-such-invitation")++ async def test_two_concurrent_acceptances_of_one_use_grant_exactly_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The race this whole shape exists for.++ Read the row, check `uses_remaining > 0`, decrement in Python, flush:+ both transactions read `1`, both write `0`, read-committed lets both+ commit, and one single-use invitation grants two memberships. One+ conditional `UPDATE` cannot do that — the second blocks on the row+ lock, re-evaluates its `WHERE` against the committed version, matches+ nothing, and refuses.+ """+ invitation_id, _hash = await _make_invitation(session_factory, uses_remaining=1)++ barrier = asyncio.Barrier(2)+ outcomes = await asyncio.gather(+ _consume_racing(session_factory, invitation_id, barrier),+ _consume_racing(session_factory, invitation_id, barrier),+ )++ assert sorted(outcomes) == [False, True], (+ f"exactly one acceptance should have won, got {outcomes}"+ )+ async with session_factory() as session:+ invitation = await session.get(Invitation, invitation_id)+ assert invitation is not None+ assert invitation.uses_remaining == 0++ async def test_the_database_refuses_a_negative_remaining_count(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`>= 0` and not `> 0`: a spent invitation is a `0`, and it has to+ stay representable. What the constraint rules out is the state below+ that, which no correct decrement produces and any careless one+ would."""+ async with session_factory() as session:+ owner = await _make_user(session, "alice")+ with pytest.raises(IntegrityError, match="ck_invitations_uses_remaining"):+ await _STORE.create(+ session,+ role="member",+ email=None,+ expires_at=_expires_soon(),+ uses_remaining=-1,+ created_by=owner.id,+ )++class TestInvitationIsolation:"""The property the design doc calls out by name: an invitation belongingto tenant A must be invisible to a session bound to tenant B."""@@ -242,6 +418,45 @@ class TestInvitationIsolation:"invitation reaching this listing means the policy let it through")+ async def test_tenant_b_cannot_consume_tenant_as_invitation(+ self, rls_harness: RLSHarness+ ) -> None:+ """`consume` is an `UPDATE`, and the policy's `USING` clause applies to+ the rows it may reach the same way it applies to a `SELECT`. Knowing+ the id is not knowing the tenant."""+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"+ async with rls_harness.owner() as session:+ session.add_all(+ [+ Tenant(id=tenant_a, slug=tenant_a, name=tenant_a),+ Tenant(id=tenant_b, slug=tenant_b, name=tenant_b),+ ]+ )+ await session.commit()++ async with tenant_session(rls_harness.restricted, tenant_a) as session:+ owner = await _make_user(session, "alice")+ invitation, _token = await _STORE.create(+ session,+ role="member",+ email=None,+ expires_at=_expires_soon(),+ uses_remaining=1,+ created_by=owner.id,+ )+ invitation_id = invitation.id+ await session.commit()++ async with tenant_session(rls_harness.restricted, tenant_b) as session:+ with pytest.raises(InvitationNotUsableError):+ await _STORE.consume(session, invitation_id)++ async with tenant_session(rls_harness.restricted, tenant_a) as session:+ still_there = await session.get(Invitation, invitation_id)+ assert still_there is not None+ assert still_there.uses_remaining == 1+async def test_a_session_with_no_tenant_bound_cannot_read_invitations(self, rls_harness: RLSHarness) -> None: