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
"""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 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: each
call takes the session of the change it records, so the event commits or rolls
back with that change.
"""
from __future__ import annotations
from datetime import datetime
from enum import StrEnum
from typing import Any
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from switch_core.db.models import (
AuditEvent,
OrganizationAuditEvent,
ServerAuditEvent,
)
class AuditAction(StrEnum):
TENANT_CREATED = "tenant.created"
TENANT_DELETED = "tenant.deleted"
INVITATION_CREATED = "invitation.created"
INVITATION_REVOKED = "invitation.revoked"
INVITATION_ACCEPTED = "invitation.accepted"
MEMBER_JOINED_BY_DOMAIN = "member.joined_by_domain"
MEMBER_ROLE_CHANGED = "member.role_changed"
MEMBER_REMOVED = "member.removed"
# Someone in the workspace only as their organization's `org_admin` stopped
# being one, and their keys and connections here were removed.
ORGANIZATION_ADMIN_ACCESS_ENDED = "organization_admin.access_ended"
# The platform operator acting in a workspace on the operator flag alone:
# entering it, and every write while there.
PLATFORM_ACCESS = "platform.access"
ACCOUNT_DELETED = "account.deleted"
JOIN_DOMAIN_ADDED = "join_domain.added"
JOIN_DOMAIN_REMOVED = "join_domain.removed"
API_KEY_CREATED = "api_key.created"
API_KEY_REVEALED = "api_key.revealed"
API_KEY_DELETED = "api_key.deleted"
BRIDGE_CREATED = "collaboration_bridge.created"
BRIDGE_UPDATED = "collaboration_bridge.updated"
BRIDGE_DEFAULT_SET = "collaboration_bridge.default_set"
BRIDGE_DELETED = "collaboration_bridge.deleted"
# A claim took effect. Once links needed confirming from the account
# (CHOO-3881), that is when the account confirmed one, not when someone
# asked for it (`BRIDGE_IDENTITY_LINK_REQUESTED`).
BRIDGE_IDENTITY_CLAIMED = "collaboration_bridge.identity_claimed"
BRIDGE_IDENTITY_LINK_REQUESTED = "collaboration_bridge.identity_link_requested"
BRIDGE_IDENTITY_LINK_CANCELLED = "collaboration_bridge.identity_link_cancelled"
BRIDGE_IDENTITY_CONFIRMATION_REQUIRED = (
"collaboration_bridge.identity_confirmation_required"
)
BRIDGE_IDENTITY_RELEASED = "collaboration_bridge.identity_released"
MESSAGING_INSTALL_STARTED = "messaging_install.started"
MESSAGING_INSTALL_CONNECTED = "messaging_install.connected"
MESSAGING_INSTALL_DISCONNECTED = "messaging_install.disconnected"
SERVICE_CONNECTED = "service.connected"
SERVICE_DISCONNECTED = "service.disconnected"
SERVICE_GRANT_SET = "service_grant.set"
SERVICE_GRANT_REMOVED = "service_grant.removed"
AGENT_DELETION_REQUESTED = "agent.deletion_requested"
AGENT_DELETED = "agent.deleted"
WORKSPACE_SERVICE_ENABLED = "workspace_service.enabled"
WORKSPACE_SERVICE_DISABLED = "workspace_service.disabled"
WORKSPACE_SERVICE_CLEARED = "workspace_service.cleared"
OWNERSHIP_TRANSFERRED = "ownership.transferred"
RETENTION_POLICY_SET = "retention_policy.set"
RETENTION_POLICY_CLEARED = "retention_policy.cleared"
PERSON_ERASURE_REQUESTED = "person_erasure.requested"
PERSON_ERASURE_COMPLETED = "person_erasure.completed"
class OrganizationAuditAction(StrEnum):
ORGANIZATION_CREATED = "organization.created"
WORKSPACE_CREATED = "organization.workspace_created"
ROLE_CHANGED = "organization.role_changed"
MEMBER_REMOVED = "organization.member_removed"
CONNECTOR_APP_SAVED = "organization.connector_app_saved"
CONNECTOR_APP_REMOVED = "organization.connector_app_removed"
SERVICE_SET = "organization.service_set"
SERVICE_CLEARED = "organization.service_cleared"
# Changes made in a directory kept outside Switch, brought in at sign-in,
# from its events or by the daily check (`details.source`).
MEMBER_ADDED_FROM_DIRECTORY = "organization.member_added_from_directory"
MEMBER_PROMOTED_FROM_DIRECTORY = "organization.member_promoted_from_directory"
MEMBER_DEMOTED_FROM_DIRECTORY = "organization.member_demoted_from_directory"
MEMBER_REMOVED_FROM_DIRECTORY = "organization.member_removed_from_directory"
# A change brought in from the directory broke a rule Switch keeps itself
# (the last Org Admin, agents left with an owner who can't act); applied
# anyway, and recorded for the organization's admins (`details.kind`).
DIRECTORY_CONFLICT = "organization.directory_conflict"
# An operator made the organization follow one in the directory.
LINKED_TO_DIRECTORY = "organization.linked_to_directory"
class OrganizationIssueKind(StrEnum):
"""What can need an organization admin's attention
(`organization_issues.py`). `directory_organization_deleted` is also the
`details.kind` of the `DIRECTORY_CONFLICT` that reports it. Mirrored by
hand as `OrganizationIssueKind` in the gateway's `data/api.ts`."""
NO_ORG_ADMIN = "no_org_admin"
WORKSPACE_WITHOUT_ADMIN = "workspace_without_admin"
AGENTS_WITHOUT_ACTING_OWNER = "agents_without_acting_owner"
DIRECTORY_ORGANIZATION_DELETED = "directory_organization_deleted"
class ServerAuditAction(StrEnum):
CONNECTOR_APP_SAVED = "connector_app.saved"
CONNECTOR_APP_IMPORTED = "connector_app.imported"
CONNECTOR_APP_REMOVED = "connector_app.removed"
USER_DELETED = "user.deleted"
USER_DELETION_REFUSED = "user.deletion_refused"
USER_DELETION_FAILED = "user.deletion_failed"
# Every session the account held was ended, by the person ("Sign out of
# all devices") or by the operator for them.
USER_SESSIONS_ENDED = "user.sessions_ended"
WORKSPACE_DELETED = "workspace.deleted"
# WorkOS refused where the directory mirror had got to in its events, and
# the mirror started again from now, with a full check of every linked
# organization.
DIRECTORY_EVENTS_RESTARTED = "directory.events_restarted"
async def record_audit_event(
session: AsyncSession,
*,
tenant_id: str,
actor_user_id: str | None,
action: AuditAction,
target_type: str,
target_id: str | None,
details: dict[str, Any] | None,
) -> AuditEvent:
"""Add an event to `session`; it lands when the caller commits."""
event = AuditEvent(
tenant_id=tenant_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_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,
*,
actor_user_id: str | None,
action: ServerAuditAction,
target_type: str,
target_id: str | None,
details: dict[str, Any] | None,
) -> ServerAuditEvent:
"""Add a server-wide event to `session`; it lands when the caller commits."""
event = ServerAuditEvent(
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 list_audit_events(
session: AsyncSession,
*,
tenant_id: str,
limit: int,
before: datetime | None,
) -> list[AuditEvent]:
"""Newest first. Names its tenant as well as relying on the policy, for the
reason `JoinDomainStore` gives."""
query = select(AuditEvent).where(AuditEvent.tenant_id == tenant_id)
if before is not None:
query = query.where(AuditEvent.occurred_at < before)
result = await session.execute(
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())