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
[CHOO-3906] Record organization changes in the organization's own audit log
Petr Bauch4cb374673152
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.tsindex 4b8eac4b6..2955725b1 100644--- a/console/tooling-e2e/src/clients/switch-client.ts+++ b/console/tooling-e2e/src/clients/switch-client.ts@@ -499,6 +499,18 @@ export class SwitchClient {};}+ /** `GET /gateway/organizations/current/audit-events` — the organization's audit log, newest first; organization admin only. */+ async organizationAuditEvents(): Promise<+ {+ action: string;+ actor_user_id: string | null;+ target_id: string | null;+ details: Record<string, unknown> | null;+ }[]+ > {+ return this.gateway("GET", "/organizations/current/audit-events");+ }+/** `GET /gateway/organizations` — the caller's organizations and their role in each. */async organizations(): Promise<OrganizationSummary[]> {return this.gateway<OrganizationSummary[]>("GET", "/organizations");diff --git a/console/tooling-e2e/src/fast/organization-members.ts b/console/tooling-e2e/src/fast/organization-members.tsindex 100db9e36..9e210a004 100644--- a/console/tooling-e2e/src/fast/organization-members.ts+++ b/console/tooling-e2e/src/fast/organization-members.ts@@ -5,8 +5,9 @@ import type { FastScenario } from './scenario.ts';/*** An organization's admins manage who else is one: the harness admin, the* default workspace's organization admin, lists its members, makes a- * colleague organization admin, and takes it back. The colleague can list- * the members only while they hold the role. The workspace roster shows each+ * colleague organization admin, and takes it back, both recorded in the+ * organization's audit log. The colleague can list the members only while+ * they hold the role. The workspace roster shows each* person's organization role. Removing the colleague from the organization is* refused while they are still in its workspace, and goes through once they* are not. Only the harness admin, a platform operator, lists every@@ -22,6 +23,7 @@ export const organizationMembers: FastScenario = {'GET /gateway/organizations/current/members','PATCH /gateway/organizations/current/members/{user_id}','DELETE /gateway/organizations/current/members/{user_id}',+ 'GET /gateway/organizations/current/audit-events','GET /gateway/operator/workspaces','GET /gateway/tenants/{tenant_id}/members','DELETE /gateway/tenants/{tenant_id}/members/{user_id}',@@ -64,6 +66,13 @@ export const organizationMembers: FastScenario = {const taken = await switchClient.setOrganizationRole(id, 'member');expect(taken.role).toBe('member');+ const changes = (await switchClient.organizationAuditEvents())+ .filter((event) => event.action === 'organization.role_changed' && event.target_id === id)+ .map((event) => event.details?.to);+ expect(changes, 'both changes in the organization audit log, newest first').toEqual([+ 'member',+ 'org_admin',+ ]);expect(await refused(), 'a member again').toBe(403);const status = async (call: () => Promise<unknown>): Promise<[number, string]> => {diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex dd10274ac..a1a9702b8 100644--- a/console/tooling-e2e/surface/server-surface.json+++ b/console/tooling-e2e/surface/server-surface.json@@ -596,6 +596,11 @@"auth": "session","flags": []},+ {+ "route": "GET /gateway/organizations/current/audit-events",+ "auth": "session",+ "flags": []+ },{"route": "GET /gateway/organizations/current/members","auth": "session",diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex de81cd4f4..346e561a5 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -1,7 +1,9 @@"""The audit logs: append an event in the caller's transaction, read it back.-A tenant's changes go to `audit_events`; a change to the server as a whole,-which no tenant owns, goes to `server_audit_events`.+A tenant's changes go to `audit_events`; a change to an organization as a+whole, its members and workspaces, goes to `organization_audit_events`; a+change to the server as a whole, which no tenant owns, goes to+`server_audit_events`.Functions rather than an injected store because there is nothing to hold: eachcall takes the session of the change it records, so the event commits or rolls@@ -17,7 +19,11 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import AuditEvent, ServerAuditEvent+from switch_core.db.models import (+ AuditEvent,+ OrganizationAuditEvent,+ ServerAuditEvent,+)class AuditAction(StrEnum):@@ -28,8 +34,6 @@ class AuditAction(StrEnum):MEMBER_JOINED_BY_DOMAIN = "member.joined_by_domain"MEMBER_ROLE_CHANGED = "member.role_changed"MEMBER_REMOVED = "member.removed"- ORGANIZATION_ROLE_CHANGED = "organization.role_changed"- ORGANIZATION_MEMBER_REMOVED = "organization.member_removed"# The platform operator acting in a workspace on the operator flag alone:# entering it, and every write while there.PLATFORM_ACCESS = "platform.access"@@ -58,6 +62,13 @@ class AuditAction(StrEnum):WORKSPACE_SERVICE_DISABLED = "workspace_service.disabled"+class OrganizationAuditAction(StrEnum):+ ORGANIZATION_CREATED = "organization.created"+ WORKSPACE_CREATED = "organization.workspace_created"+ ROLE_CHANGED = "organization.role_changed"+ MEMBER_REMOVED = "organization.member_removed"++class ServerAuditAction(StrEnum):CONNECTOR_APP_SAVED = "connector_app.saved"CONNECTOR_APP_IMPORTED = "connector_app.imported"@@ -88,6 +99,34 @@ async def record_audit_event(return event+async def record_organization_audit_event(+ session: AsyncSession,+ *,+ organization_id: str,+ actor_user_id: str | None,+ action: OrganizationAuditAction,+ target_type: str,+ target_id: str | None,+ details: dict[str, Any] | None,+) -> OrganizationAuditEvent:+ """Add an organization event to `session`; it lands when the caller commits.++ `session` may be bound to the organization or to any of its workspaces:+ the policy derives the organization from either.+ """+ event = OrganizationAuditEvent(+ organization_id=organization_id,+ actor_user_id=actor_user_id,+ action=action.value,+ target_type=target_type,+ target_id=target_id,+ details=details,+ )+ session.add(event)+ await session.flush()+ return event++async def record_server_audit_event(session: AsyncSession,*,@@ -126,3 +165,26 @@ async def list_audit_events(query.order_by(AuditEvent.occurred_at.desc(), AuditEvent.id.desc()).limit(limit))return list(result.scalars().all())+++async def list_organization_audit_events(+ session: AsyncSession,+ *,+ organization_id: str,+ limit: int,+ before: datetime | None,+) -> list[OrganizationAuditEvent]:+ """Newest first. Names its organization as well as relying on the policy,+ as `list_audit_events` does."""+ query = select(OrganizationAuditEvent).where(+ OrganizationAuditEvent.organization_id == organization_id+ )+ if before is not None:+ query = query.where(OrganizationAuditEvent.occurred_at < before)+ result = await session.execute(+ query.order_by(+ OrganizationAuditEvent.occurred_at.desc(),+ OrganizationAuditEvent.id.desc(),+ ).limit(limit)+ )+ return list(result.scalars().all())diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex cb263fc8d..c36aecf18 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -712,6 +712,38 @@ class AuditEvent(TenantScoped, Base):details: Mapped[dict | None] = mapped_column(JSONB, nullable=True)+class OrganizationAuditEvent(OrganizationScoped, Base):+ """One change to an organization as a whole: its members, their roles,+ its workspaces. The organization's counterpart of `AuditEvent`, with the+ same rules: written in the transaction of the change it records,+ append-only for the runtime role, `actor_user_id` without a foreign key,+ and `details` free of secrets.++ A change inside one workspace stays in that workspace's `audit_events`;+ this holds what no single workspace owns, so an organization's admins+ read it in one place whichever workspace the change was made from.+ """++ __tablename__ = "organization_audit_events"+ __table_args__ = (+ Index(+ "ix_organization_audit_events_organization_occurred_at",+ "organization_id",+ "occurred_at",+ ),+ )++ id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)+ occurred_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), server_default=func.clock_timestamp(), nullable=False+ )+ actor_user_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ action: Mapped[str] = mapped_column(Text, nullable=False)+ target_type: Mapped[str] = mapped_column(Text, nullable=False)+ target_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ details: Mapped[dict | None] = mapped_column(JSONB, nullable=True)++# ── Clients ────────────────────────────────────────────────────────────────────diff --git a/core/switch_core/db/runtime_role.py b/core/switch_core/db/runtime_role.pyindex c942c6b3c..52e861ce7 100644--- a/core/switch_core/db/runtime_role.py+++ b/core/switch_core/db/runtime_role.py@@ -153,10 +153,11 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:it is a statement about what this owner creates, and this owner createsonly this schema.- `audit_events` and `server_audit_events` are the tables the role may not- change once written: it gets `SELECT` and `INSERT` there and nothing- else, so a compromised or buggy process can add to a tenant's or the- server's history but not rewrite it. The+ `audit_events`, `organization_audit_events` and `server_audit_events` are+ the tables the role may not change once written: it gets `SELECT` and+ `INSERT` there and nothing else, so a compromised or buggy process can add+ to a tenant's, an organization's or the server's history but not rewrite+ it. Therevoke follows the blanket grant on every boot, so the next boot puts itback if anything granted more in between.@@ -169,6 +170,7 @@ async def grant_runtime_role(owner: AsyncConnection, role: str) -> None:f"GRANT USAGE ON SCHEMA public TO {identifier}",f"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {identifier}",f"REVOKE UPDATE, DELETE ON audit_events FROM {identifier}",+ f"REVOKE UPDATE, DELETE ON organization_audit_events FROM {identifier}",f"REVOKE UPDATE, DELETE ON server_audit_events FROM {identifier}",f"GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {identifier}","REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC",diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 03f0d5b61..3272ea785 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -9,21 +9,29 @@ its `org_admin`s. The one exception is an organization with no `org_admin`left: the platform operator may list its members and make one of them`org_admin`, and being there on the operator flag alone, does so on`platform_access`, recorded as every operator write is (`gateway/auth.py`).-See `docs/design/organizations-v1.md`.++Changes to the organization itself are recorded in its own audit log+(`organization_audit_events`), whichever workspace they were made from, and+read back by its `org_admin`s. See `docs/design/organizations-v1.md`."""from __future__ import annotations+from datetime import datetimefrom typing import Annotated-from fastapi import APIRouter, Depends, HTTPException, Response+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Responsefrom sqlalchemy import deletefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfig-from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.audit import (+ OrganizationAuditAction,+ list_organization_audit_events,+ record_organization_audit_event,+)from switch_core.db.models import (OrganizationMember,Tenant,@@ -51,6 +59,7 @@ from switch_core.gateway.dependencies import (get_user_store,)from switch_core.gateway.schemas import (+ AuditEventDetail,OrganizationCreateRequest,OrganizationCreateResponse,OrganizationMemberDetail,@@ -254,6 +263,50 @@ async def create_organization_workspace()+def _made_from(request: Request) -> dict[str, object]:+ """Where an organization change was made: the workspace the request was+ bound to, and whether the platform operator made it on the operator flag+ alone, which the organization's admins read here as they would in that+ workspace's own log."""+ details: dict[str, object] = {"workspace_id": require_tenant_id()}+ if request.state.platform_access:+ details["platform_access"] = True+ return details++[email protected]("/organizations/current/audit-events")+async def list_organization_audit_log(+ session: Annotated[AsyncSession, Depends(get_session)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],+ user: Annotated[User, Depends(get_current_user)],+ limit: Annotated[int, Query(ge=1, le=200)] = 50,+ before: Annotated[datetime | None, Query()] = None,+) -> list[AuditEventDetail]:+ """The organization's audit log, newest first. `org_admin` only.++ Page back by passing the oldest `occurred_at` returned as `before`.+ """+ organization_id = await _require_organization_admin(+ session, user_store, organization_store, user, operator_restores=False+ )+ events = await list_organization_audit_events(+ session, organization_id=organization_id, limit=limit, before=before+ )+ return [+ AuditEventDetail(+ id=event.id,+ occurred_at=event.occurred_at.isoformat(),+ actor_user_id=event.actor_user_id,+ action=event.action,+ target_type=event.target_type,+ target_id=event.target_id,+ details=event.details,+ )+ for event in events+ ]++@router.get("/organizations/current/members")async def list_organization_members(session: Annotated[AsyncSession, Depends(get_session)],@@ -274,6 +327,7 @@ async def list_organization_members(async def update_organization_member_role(user_id: str,req: OrganizationMemberUpdateRequest,+ request: Request,session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],@@ -283,7 +337,7 @@ async def update_organization_member_role(the one role that grants `org_admin`.Refuses to demote the last `org_admin`: nobody else could grant the role- again. Recorded in the bound workspace's audit log.+ again. Recorded in the organization's audit log."""organization_id = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=True@@ -301,17 +355,17 @@ async def update_organization_member_role()if member.role != req.role:- await record_audit_event(+ await record_organization_audit_event(session,- tenant_id=require_tenant_id(),+ organization_id=organization_id,actor_user_id=user.id,- action=AuditAction.ORGANIZATION_ROLE_CHANGED,+ action=OrganizationAuditAction.ROLE_CHANGED,target_type="user",target_id=user_id,details={- "organization_id": organization_id,"from": member.role,"to": req.role,+ **_made_from(request),},)member.role = req.role@@ -325,6 +379,7 @@ async def update_organization_member_role(@router.delete("/organizations/current/members/{user_id}")async def remove_organization_member(user_id: str,+ request: Request,session: Annotated[AsyncSession, Depends(get_session)],session_factory: Annotated[async_sessionmaker[AsyncSession], Depends(get_session_factory)@@ -339,7 +394,7 @@ async def remove_organization_member(leaving a workspace revokes their keys and connections there and refuseswhile they own agents, and that is the workspace member route's to do,one workspace at a time. Refuses the last `org_admin` too. Recorded in- the bound workspace's audit log.+ the organization's audit log."""organization_id = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=False@@ -375,14 +430,14 @@ async def remove_organization_member(OrganizationMember.user_id == user_id,))- await record_audit_event(+ await record_organization_audit_event(session,- tenant_id=require_tenant_id(),+ organization_id=organization_id,actor_user_id=user.id,- action=AuditAction.ORGANIZATION_MEMBER_REMOVED,+ action=OrganizationAuditAction.MEMBER_REMOVED,target_type="user",target_id=user_id,- details={"organization_id": organization_id, "role": role},+ details={"role": role, **_made_from(request)},)await session.commit()return {"ok": True}diff --git a/core/switch_core/gateway/workspace_creation.py b/core/switch_core/gateway/workspace_creation.pyindex 313be202e..f9a123e06 100644--- a/core/switch_core/gateway/workspace_creation.py+++ b/core/switch_core/gateway/workspace_creation.py@@ -25,7 +25,12 @@ from switch_core.clients.client_lifecycle_service import (TenantIsolationNotInForce,)from switch_core.config import SwitchConfig-from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.audit import (+ AuditAction,+ OrganizationAuditAction,+ record_audit_event,+ record_organization_audit_event,+)from switch_core.db.models import Organization, Tenant, Userfrom switch_core.db.session_scope import organization_session, tenant_sessionfrom switch_core.db.stores.organization_store import (@@ -286,12 +291,7 @@ async def create_organization(tenant,creator_id,organization_role=ORGANIZATION_ADMIN_ROLE,- details={- "name": tenant.name,- "slug": tenant.slug,- "organization_id": organization.id,- "organization_created": True,- },+ new_organization=organization,)return organization, tenant@@ -320,12 +320,7 @@ async def create_workspace(creator_id,# Already the organization's `org_admin`, a row joining leaves as it is.organization_role="member",- details={- "name": tenant.name,- "slug": tenant.slug,- "organization_id": organization_id,- "organization_created": False,- },+ new_organization=None,)return tenant@@ -353,9 +348,11 @@ async def _add_creator(creator_id: str,*,organization_role: str,- details: dict[str, object],+ new_organization: Organization | None,) -> None:- """Make `creator_id` the new workspace's `owner` and record its creation.+ """Make `creator_id` the new workspace's `owner` and record its creation:+ in the workspace's audit log, and in its organization's, with the+ organization's own creation first when `new_organization` was made for it.A transaction of its own, after the workspace's: the tenant row has to becommitted before `ensure_system_client` can provision against it, and that@@ -379,7 +376,34 @@ async def _add_creator(action=AuditAction.TENANT_CREATED,target_type="tenant",target_id=tenant.id,- details=details,+ details={+ "name": tenant.name,+ "slug": tenant.slug,+ "organization_id": tenant.organization_id,+ },+ )+ assert tenant.organization_id is not None+ if new_organization is not None:+ await record_organization_audit_event(+ session,+ organization_id=tenant.organization_id,+ actor_user_id=creator_id,+ action=OrganizationAuditAction.ORGANIZATION_CREATED,+ target_type="organization",+ target_id=new_organization.id,+ details={+ "name": new_organization.name,+ "slug": new_organization.slug,+ },+ )+ await record_organization_audit_event(+ session,+ organization_id=tenant.organization_id,+ actor_user_id=creator_id,+ action=OrganizationAuditAction.WORKSPACE_CREATED,+ target_type="workspace",+ target_id=tenant.id,+ details={"name": tenant.name, "slug": tenant.slug},)await session.commit()except Exception:diff --git a/core/switch_core/migrations/versions/9d41b7e2c6a3_organization_audit_events.py b/core/switch_core/migrations/versions/9d41b7e2c6a3_organization_audit_events.pynew file mode 100644index 000000000..b1d515cbe--- /dev/null+++ b/core/switch_core/migrations/versions/9d41b7e2c6a3_organization_audit_events.py@@ -0,0 +1,83 @@+"""organization audit events: the history of changes to an organization++One organization-scoped table, `organization_audit_events`, with the policy+every organization-scoped table carries (`db/rls_ddl.py`), compared against+the `require_organization_id()` function `238c68b7306e` created. Append-only+for the runtime role as `audit_events` is: the revoke is reissued by+`grant_runtime_role` on every boot.++The policy DDL is a verbatim copy of `switch_core/db/rls_ddl.py` as it stood+when this migration was written, copied rather than imported for the reason+`265ed188ad6f` gives.++Expand only: a process from before this revision never reads the table.++Revision ID: 9d41b7e2c6a3+Revises: 5c2e8f17a9d4+Create Date: 2026-10-29 00:00:00.000000++"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "9d41b7e2c6a3"+down_revision: str | Sequence[str] | None = "5c2e8f17a9d4"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++REQUIRE_ORGANIZATION_FUNCTION_NAME = "require_organization_id"+ORGANIZATION_POLICY_NAME = "organization_isolation"+_PREDICATE = f'"organization_id" = (SELECT {REQUIRE_ORGANIZATION_FUNCTION_NAME}())'+++def upgrade() -> None:+ op.create_table(+ "organization_audit_events",+ sa.Column("id", sa.Text(), nullable=False),+ sa.Column(+ "occurred_at",+ sa.DateTime(timezone=True),+ server_default=sa.text("clock_timestamp()"),+ nullable=False,+ ),+ sa.Column("actor_user_id", sa.Text(), nullable=True),+ sa.Column("action", sa.Text(), nullable=False),+ sa.Column("target_type", sa.Text(), nullable=False),+ sa.Column("target_id", sa.Text(), nullable=True),+ sa.Column("details", postgresql.JSONB(), nullable=True),+ sa.Column("organization_id", sa.Text(), nullable=False),+ sa.ForeignKeyConstraint(+ ["organization_id"],+ ["organizations.id"],+ name="fk_organization_audit_events_organization",+ ),+ sa.PrimaryKeyConstraint("id"),+ )+ op.create_index(+ "ix_organization_audit_events_organization_occurred_at",+ "organization_audit_events",+ ["organization_id", "occurred_at"],+ )+ op.execute('ALTER TABLE "organization_audit_events" ENABLE ROW LEVEL SECURITY')+ op.execute(+ f'CREATE POLICY {ORGANIZATION_POLICY_NAME} ON "organization_audit_events"\n'+ f" FOR ALL\n"+ f" USING ({_PREDICATE})\n"+ f" WITH CHECK ({_PREDICATE})"+ )+++def downgrade() -> None:+ op.execute(+ f'DROP POLICY IF EXISTS {ORGANIZATION_POLICY_NAME} ON "organization_audit_events"'+ )+ op.drop_index(+ "ix_organization_audit_events_organization_occurred_at",+ table_name="organization_audit_events",+ )+ op.drop_table("organization_audit_events")diff --git a/core/tests/switch_core/db/test_organization_audit_events.py b/core/tests/switch_core/db/test_organization_audit_events.pynew file mode 100644index 000000000..c02571056--- /dev/null+++ b/core/tests/switch_core/db/test_organization_audit_events.py@@ -0,0 +1,115 @@+"""An organization's audit log: written from any of its workspaces, read only+within the organization, and append-only for the role the server connects as.+Every assertion goes through `rls_harness.restricted`, the role the policies+apply to; `owner` only arranges fixtures."""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy import select, text+from sqlalchemy.exc import ProgrammingError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.audit import (+ OrganizationAuditAction,+ list_organization_audit_events,+ record_organization_audit_event,+)+from switch_core.db.models import Organization, OrganizationAuditEvent, Tenant+from switch_core.db.session_scope import organization_session, tenant_session+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++async def _organization(owner: async_sessionmaker[AsyncSession]) -> tuple[str, str]:+ """An organization with one workspace: (organization id, workspace id)."""+ organization_id = f"org-{uuid.uuid4().hex[:8]}"+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with owner() as session:+ session.add(Organization(id=organization_id, slug=organization_id, name="O"))+ await session.flush()+ session.add(+ Tenant(+ id=tenant_id,+ slug=tenant_id,+ name="W",+ organization_id=organization_id,+ )+ )+ await session.commit()+ return organization_id, tenant_id+++async def _record(+ restricted: async_sessionmaker[AsyncSession], organization_id: str, tenant_id: str+) -> None:+ async with tenant_session(restricted, tenant_id) as session:+ await record_organization_audit_event(+ session,+ organization_id=organization_id,+ actor_user_id="ada",+ action=OrganizationAuditAction.ROLE_CHANGED,+ target_type="user",+ target_id="bob",+ details={"from": "member", "to": "org_admin"},+ )+ await session.commit()+++async def test_written_from_a_workspace_and_read_only_within_its_organization(+ rls_harness: RLSHarness,+) -> None:+ org_a, tenant_a = await _organization(rls_harness.owner)+ org_b, tenant_b = await _organization(rls_harness.owner)+ await _record(rls_harness.restricted, org_a, tenant_a)++ async with organization_session(rls_harness.restricted, org_a) as session:+ [event] = await list_organization_audit_events(+ session, organization_id=org_a, limit=10, before=None+ )+ async with tenant_session(rls_harness.restricted, tenant_b) as session:+ seen_from_b = (await session.scalars(select(OrganizationAuditEvent))).all()++ assert (event.actor_user_id, event.target_id) == ("ada", "bob")+ assert seen_from_b == []+++async def test_a_workspace_cannot_write_into_another_organization(+ rls_harness: RLSHarness,+) -> None:+ org_a, _ = await _organization(rls_harness.owner)+ _, tenant_b = await _organization(rls_harness.owner)++ with pytest.raises(ProgrammingError, match="row-level security"):+ await _record(rls_harness.restricted, org_a, tenant_b)+++ "statement",+ [+ "UPDATE organization_audit_events SET action = 'rewritten'",+ "DELETE FROM organization_audit_events",+ ],+)+async def test_the_runtime_role_cannot_rewrite_history(+ rls_harness: RLSHarness, statement: str+) -> None:+ organization_id, tenant_id = await _organization(rls_harness.owner)+ await _record(rls_harness.restricted, organization_id, tenant_id)++ async with tenant_session(rls_harness.restricted, tenant_id) as session:+ with pytest.raises(ProgrammingError, match="permission denied"):+ await session.execute(text(statement))++ async with rls_harness.owner() as session:+ [event] = (+ await session.scalars(+ select(OrganizationAuditEvent).where(+ OrganizationAuditEvent.organization_id == organization_id+ )+ )+ ).all()+ assert event.action == OrganizationAuditAction.ROLE_CHANGEDdiff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.pyindex 7a76022b3..a8359af38 100644--- a/core/tests/switch_core/db/test_row_level_security.py+++ b/core/tests/switch_core/db/test_row_level_security.py@@ -381,6 +381,7 @@ class TestCatalogueCoverage:assert organization_scoped == {"organizations": "id","organization_members": "organization_id",+ "organization_audit_events": "organization_id",}assert len(scoped) >= 30, scopedassert scoped["tenants"] == "id"diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 7e39f5191..5b4015609 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -13,10 +13,11 @@ from fastapi import FastAPIfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.audit import AuditAction+from switch_core.db.audit import AuditAction, OrganizationAuditActionfrom switch_core.db.models import (AuditEvent,Organization,+ OrganizationAuditEvent,OrganizationMember,Tenant,TenantMember,@@ -188,16 +189,15 @@ class TestChangingRoles:assert response.status_code == 200, response.textassert response.json()["role"] == "org_admin"- async with tenant_session(session_factory, tenant_id) as session:- event = await session.scalar(- select(AuditEvent).where(- AuditEvent.action == AuditAction.ORGANIZATION_ROLE_CHANGED- )- )- assert event is not None+ [event] = await _organization_events(+ session_factory, tenant_id, OrganizationAuditAction.ROLE_CHANGED+ )assert event.actor_user_id == ada and event.target_id == bob- assert event.details is not None- assert (event.details["from"], event.details["to"]) == ("member", "org_admin")+ assert event.details == {+ "from": "member",+ "to": "org_admin",+ "workspace_id": tenant_id,+ }async def test_a_member_cannot_grant_themselves_org_admin(self, session_factory: async_sessionmaker[AsyncSession]@@ -293,6 +293,25 @@ async def _events()+async def _organization_events(+ session_factory: async_sessionmaker[AsyncSession],+ tenant_id: str,+ action: OrganizationAuditAction,+) -> list[OrganizationAuditEvent]:+ """`action`'s events in the log of `tenant_id`'s organization."""+ async with tenant_session(session_factory, tenant_id) as session:+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None+ return list(+ await session.scalars(+ select(OrganizationAuditEvent).where(+ OrganizationAuditEvent.organization_id == tenant.organization_id,+ OrganizationAuditEvent.action == action,+ )+ )+ )++class TestRemoving:async def test_someone_still_in_a_workspace_of_it_is_refused_by_name(self, session_factory: async_sessionmaker[AsyncSession]@@ -325,10 +344,13 @@ class TestRemoving:assert response.status_code == 200, response.textassert [row["user_id"] for row in listed.json()] == [ada]- [event] = await _events(- session_factory, tenant_id, AuditAction.ORGANIZATION_MEMBER_REMOVED+ [event] = await _organization_events(+ session_factory, tenant_id, OrganizationAuditAction.MEMBER_REMOVED)assert event.target_id == bob+ assert (+ await _events(session_factory, tenant_id, AuditAction.MEMBER_REMOVED) == []+ )async def test_the_last_org_admin_cannot_be_removed(self, session_factory: async_sessionmaker[AsyncSession]@@ -491,6 +513,12 @@ class TestThePlatformOperator:assert refused.status_code == 403[event] = await _events(session_factory, orphaned, AuditAction.PLATFORM_ACCESS)assert event.details is not None and event.details["method"] == "PATCH"+ [changed] = await _organization_events(+ session_factory, orphaned, OrganizationAuditAction.ROLE_CHANGED+ )+ assert changed.actor_user_id == operator_id+ assert changed.details is not None+ assert changed.details["platform_access"] is Trueasync def _user(session_factory: async_sessionmaker[AsyncSession], role: str) -> str:@@ -563,6 +591,20 @@ class TestCreatingAnOrganization:assert membership is not None and membership.role == "owner"assert organization_member is not Noneassert organization_member.role == "org_admin"+ async with tenant_session(session_factory, workspace["id"]) as session:+ logged = [+ (event.action, event.target_id)+ for event in await session.scalars(+ select(OrganizationAuditEvent).order_by(+ OrganizationAuditEvent.occurred_at+ )+ )+ if event.organization_id == organization["id"]+ ]+ assert logged == [+ (OrganizationAuditAction.ORGANIZATION_CREATED, organization["id"]),+ (OrganizationAuditAction.WORKSPACE_CREATED, workspace["id"]),+ ]async def test_the_first_workspace_takes_the_organization_name_by_default(self, session_factory: async_sessionmaker[AsyncSession]@@ -636,8 +678,16 @@ class TestCreatingAWorkspace:session_factory, workspace["id"], AuditAction.TENANT_CREATED)assert event.actor_user_id == ada- assert event.details is not None- assert event.details["organization_created"] is False+ [added] = await _organization_events(+ session_factory, tenant_id, OrganizationAuditAction.WORKSPACE_CREATED+ )+ assert (added.actor_user_id, added.target_id) == (ada, workspace["id"])+ assert (+ await _organization_events(+ session_factory, tenant_id, OrganizationAuditAction.ORGANIZATION_CREATED+ )+ == []+ )async with tenant_session(session_factory, workspace["id"]) as session:membership = await session.get(TenantMember, (workspace["id"], ada))assert membership is not None and membership.role == "owner"@@ -764,3 +814,47 @@ class TestListingOrganizationsAndWorkspaces:("Acme", "org_admin"),("Globex", "org_admin"),]+++class TestTheOrganizationAuditLog:+ async def test_an_org_admin_reads_it_newest_first(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}+ )++ async with _client(_app(session_factory), ada, tenant_id) as client:+ for role in ("org_admin", "member"):+ changed = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": role}+ )+ assert changed.status_code == 200, changed.text+ response = await client.get("/organizations/current/audit-events")+ older = await client.get(+ "/organizations/current/audit-events",+ params={"before": response.json()[0]["occurred_at"]},+ )++ assert response.status_code == 200, response.text+ assert [+ (row["details"]["from"], row["details"]["to"]) for row in response.json()+ ] == [+ ("org_admin", "member"),+ ("member", "org_admin"),+ ]+ assert [row["id"] for row in older.json()] == [response.json()[1]["id"]]++ async def test_a_workspace_admin_who_is_no_org_admin_is_refused(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}+ )++ async with _client(_app(session_factory), bob, tenant_id) as client:+ response = await client.get("/organizations/current/audit-events")++ assert response.status_code == 403