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] Name people in the organization audit log; add the current organization
Petr Bauche008e0c4225d
diff --git a/console/tooling-e2e/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.tsindex 2955725b1..320bd1cd3 100644--- a/console/tooling-e2e/src/clients/switch-client.ts+++ b/console/tooling-e2e/src/clients/switch-client.ts@@ -511,6 +511,15 @@ export class SwitchClient {return this.gateway("GET", "/organizations/current/audit-events");}+ /** `GET /gateway/organizations/current` — the current workspace's organization and the caller's role there. */+ async currentOrganization(): Promise<{+ id: string;+ name: string;+ role: string | null;+ }> {+ return this.gateway("GET", "/organizations/current");+ }+/** `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/organizations.ts b/console/tooling-e2e/src/fast/organizations.tsindex 9c1b2984e..0ca481826 100644--- a/console/tooling-e2e/src/fast/organizations.ts+++ b/console/tooling-e2e/src/fast/organizations.ts@@ -18,6 +18,7 @@ export const organizations: FastScenario = {covers: ['GET /gateway/organizations','POST /gateway/organizations',+ 'GET /gateway/organizations/current','GET /gateway/organizations/current/workspaces','POST /gateway/organizations/current/workspaces',],@@ -66,6 +67,10 @@ export const organizations: FastScenario = {organization_id: organization.id,});expect(await founder.tenantId(), 'switched into the first workspace').toBe(workspace.id);+ expect(await founder.currentOrganization()).toMatchObject({+ id: organization.id,+ role: 'org_admin',+ });const second = await founder.createOrganizationWorkspace(names.name('second'));expect(second.organization_id).toBe(organization.id);diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex a1a9702b8..f9f38d1e8 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",+ "auth": "session",+ "flags": []+ },{"route": "GET /gateway/organizations/current/audit-events","auth": "session",diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 68721e5f1..987238ee3 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -527,15 +527,21 @@ async def record_operator_entry(async def all_workspaces(session_factory: async_sessionmaker[AsyncSession],-) -> list[Tenant]:- """Every workspace on the server, oldest first, each read on its own short- session. For the platform operator's list only."""- found: list[Tenant] = []+) -> list[tuple[Tenant, Organization | None]]:+ """Every workspace on the server, oldest first, with its organization,+ each read on its own short session. For the platform operator's list+ only."""+ found: list[tuple[Tenant, Organization | None]] = []for tenant_id in await all_tenant_ids(session_factory):async with tenant_session(session_factory, tenant_id) as session:tenant = await session.get(Tenant, tenant_id)+ organization = (+ await session.get(Organization, tenant.organization_id)+ if tenant is not None and tenant.organization_id is not None+ else None+ )if tenant is not None:- found.append(tenant)+ found.append((tenant, organization))return founddiff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 3272ea785..ecc305021 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -33,6 +33,7 @@ from switch_core.db.audit import (record_organization_audit_event,)from switch_core.db.models import (+ Organization,OrganizationMember,Tenant,User,@@ -59,7 +60,8 @@ from switch_core.gateway.dependencies import (get_user_store,)from switch_core.gateway.schemas import (- AuditEventDetail,+ CurrentOrganizationResponse,+ OrganizationAuditEventDetail,OrganizationCreateRequest,OrganizationCreateResponse,OrganizationMemberDetail,@@ -182,6 +184,27 @@ async def create_organization()[email protected]("/organizations/current")+async def current_organization(+ session: Annotated[AsyncSession, Depends(get_session)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+) -> CurrentOrganizationResponse:+ """The organization the bound workspace belongs to, and the caller's role+ in it. Unlike `GET /organizations`, it answers for anyone bound to the+ workspace, the platform operator included."""+ organization_id = await _current_organization_id(session)+ organization = await session.get(Organization, organization_id)+ if organization is None:+ raise HTTPException(status_code=404, detail="Organization not found")+ return CurrentOrganizationResponse(+ id=organization.id,+ slug=organization.slug,+ name=organization.name,+ role=await user_store.organization_role(session, require_tenant_id(), user.id),+ )++@router.get("/organizations/current/workspaces")async def list_organization_workspaces(session: Annotated[AsyncSession, Depends(get_session)],@@ -282,10 +305,12 @@ async def list_organization_audit_log(user: Annotated[User, Depends(get_current_user)],limit: Annotated[int, Query(ge=1, le=200)] = 50,before: Annotated[datetime | None, Query()] = None,-) -> list[AuditEventDetail]:+) -> list[OrganizationAuditEventDetail]:"""The organization's audit log, newest first. `org_admin` only.- Page back by passing the oldest `occurred_at` returned as `before`.+ Page back by passing the oldest `occurred_at` returned as `before`. The+ actor, and a target that is a person, come with their names, read from+ `users`, which outlives membership."""organization_id = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=False@@ -293,14 +318,29 @@ async def list_organization_audit_log(events = await list_organization_audit_events(session, organization_id=organization_id, limit=limit, before=before)+ names = await user_store.names_by_id(+ session,+ {event.actor_user_id for event in events if event.actor_user_id}+ | {+ event.target_id+ for event in events+ if event.target_type == "user" and event.target_id+ },+ )return [- AuditEventDetail(+ OrganizationAuditEventDetail(id=event.id,occurred_at=event.occurred_at.isoformat(),actor_user_id=event.actor_user_id,+ actor_name=names.get(event.actor_user_id) if event.actor_user_id else None,action=event.action,target_type=event.target_type,target_id=event.target_id,+ target_name=(+ names.get(event.target_id)+ if event.target_type == "user" and event.target_id+ else None+ ),details=event.details,)for event in eventsdiff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 2e0dccdcb..149babe3f 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -923,6 +923,7 @@ class OperatorWorkspaceResponse(BaseModel):slug: strname: strorganization_id: str | None+ organization_name: str | Noneclass CurrentTenantResponse(TenantMembershipResponse):@@ -952,6 +953,32 @@ class OrganizationSummary(BaseModel):role: str+class CurrentOrganizationResponse(BaseModel):+ """The bound workspace's organization, and the caller's role in it: None+ for the platform operator there on the operator flag alone."""++ id: str+ slug: str+ name: str+ role: str | None+++class OrganizationAuditEventDetail(BaseModel):+ """An organization audit event, with the people it names resolved to+ names: an actor or a target removed since, or never a member (the platform+ operator), is not on the organization's member list to look up."""++ id: str+ occurred_at: str+ actor_user_id: str | None+ actor_name: str | None+ action: str+ target_type: str+ target_id: str | None+ target_name: str | None+ details: dict[str, Any] | None++class OrganizationCreateResponse(BaseModel):"""A new organization and its first workspace, which the session is nowbound to."""diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 450969008..d58a87f00 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -404,8 +404,9 @@ async def list_every_workspace(slug=tenant.slug,name=tenant.name,organization_id=tenant.organization_id,+ organization_name=organization.name if organization is not None else None,)- for tenant in await all_workspaces(session_factory)+ for tenant, organization in await all_workspaces(session_factory)]diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 5b4015609..75da14c2d 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -487,7 +487,8 @@ class TestThePlatformOperator:refused = await client.get("/operator/workspaces")assert listed.status_code == 200, listed.text- assert tenant_id in {row["id"] for row in listed.json()}+ [row] = [row for row in listed.json() if row["id"] == tenant_id]+ assert row["organization_name"] == "Acme"assert refused.status_code == 403async def test_restores_an_org_admin_only_where_there_is_none(@@ -858,3 +859,59 @@ class TestTheOrganizationAuditLog:response = await client.get("/organizations/current/audit-events")assert response.status_code == 403+++class TestTheCurrentOrganization:+ async def test_a_member_and_the_operator_are_told_its_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ bob = _name("bob")+ tenant_id = await _workspace(session_factory, {bob: ("member", "member")})+ operator_id = await _operator(session_factory)++ async with _client(_app(session_factory), bob, tenant_id) as client:+ as_member = await client.get("/organizations/current")+ async with _client(_app(session_factory), operator_id, tenant_id) as client:+ as_operator = await client.get("/organizations/current")++ assert as_member.status_code == 200, as_member.text+ assert (as_member.json()["name"], as_member.json()["role"]) == (+ "Acme",+ "member",+ )+ assert as_operator.status_code == 200, as_operator.text+ assert as_operator.json()["role"] is None+++class TestNamesInTheOrganizationAuditLog:+ async def test_people_no_longer_members_are_named(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The operator who restored an admin was never a member, and a+ removed member no longer is; both are named all the same."""+ bob, cy = _name("bob"), _name("cy")+ tenant_id = await _workspace(+ session_factory, {bob: ("owner", "member"), cy: ("member", "member")}+ )+ operator_id = await _operator(session_factory)+ app = _app(session_factory)+ async with _client(app, operator_id, tenant_id) as client:+ restored = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}+ )+ assert restored.status_code == 200, restored.text+ async with tenant_session(session_factory, tenant_id) as session:+ membership = await session.get(TenantMember, (tenant_id, cy))+ assert membership is not None+ await session.delete(membership)+ await session.commit()+ async with _client(app, bob, tenant_id) as client:+ removed = await client.delete(f"/organizations/current/members/{cy}")+ assert removed.status_code == 200, removed.text+ response = await client.get("/organizations/current/audit-events")++ assert response.status_code == 200, response.text+ by_action = {row["action"]: row for row in response.json()}+ assert by_action["organization.role_changed"]["actor_name"] == operator_id+ assert by_action["organization.member_removed"]["target_name"] == cy+ assert by_action["organization.member_removed"]["actor_name"] == bob