Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f327f7b
feat(company-os): company-scoped team create/delete and member add/re…
mrveiss Nov 1, 2026
1272119
fix(frontend): re-pin the reach floors this branch moved (#14106)
mrveiss Nov 1, 2026
4bd1b31
Merge remote-tracking branch 'origin/issue-18245-company-teams' into …
mrveiss Nov 1, 2026
66c3c8f
feat(frontend): create and delete a team, add and remove members on t…
mrveiss Nov 1, 2026
2005518
fix(frontend): re-pin the reach floors this branch moved (#14106)
mrveiss Nov 1, 2026
0c17acc
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 1, 2026
82cd008
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 2, 2026
a7443a5
Merge remote-tracking branch 'origin/issue-14106-company-team-routes'…
mrveiss Nov 2, 2026
c1c6582
Merge remote-tracking branch 'origin/issue-14106-company-team-routes'…
mrveiss Nov 2, 2026
d170cec
chore(merge): merge origin/main into issue-14106-company-team-routes …
mrveiss Nov 3, 2026
05b98a4
fix(company-os): generated types include the company team routes (#14…
mrveiss Nov 3, 2026
a4844fe
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
fe59f38
chore(merge): merge #20558 into issue-14106-company-team-routes so bo…
mrveiss Nov 3, 2026
2bdd5f0
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
ac70be9
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
45a34bc
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
fe7a3fc
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
a69d051
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
87655de
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
76e2986
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
b524614
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
2636450
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
588406a
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
57a55aa
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
c3f6e01
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
b6f9da9
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
46a61aa
Merge main into issue-14106-company-team-routes (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions autobot-backend/llc/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .company_os import router as company_os_router
from .company_os_plans import router as company_os_plans_router
from .company_os_skills import router as company_os_skills_router
from .company_teams import router as company_teams_router
from .contacts import router as contacts_router
from .context import router as context_router
from .controls import router as controls_router
Expand Down Expand Up @@ -64,6 +65,7 @@
router.include_router(costs_by_model_router)
router.include_router(companies_router)
router.include_router(company_members_router)
router.include_router(company_teams_router)
router.include_router(company_ceo_router)
router.include_router(contacts_router)
router.include_router(agent_hires_router)
Expand Down
179 changes: 179 additions & 0 deletions autobot-backend/llc/api/company_teams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Company OS team writes: create and delete a team, add and remove a member (#14106).

The write side of ``GET /companies/{company_id}/teams`` (``companies.py``). There is one
team implementation, :class:`~user_management.services.TeamService`, shared with
``/teams``; this module only supplies what that service cannot know:

* **Scope** is the path's company. ``TeamService`` reads its organisation from the
context it is built with, so it is built here with ``org_id=company_id`` rather than
the ambient tenant context. Every team lookup is then filtered by that company, so a
team of another company is "not found" -- the same answer as one that does not exist.
* **Authority** is the rule neighbouring Company OS writes use
(:func:`~llc.services.authz.require_company_admin_unless_platform`): owner or admin of
*this* company. A plain member is refused.
* **Membership**: a user may only join a team of a company they belong to.

The audit trail is ``TeamService``'s own (``TEAM_CREATED`` / ``TEAM_DELETED`` /
``TEAM_MEMBER_ADDED`` / ``TEAM_MEMBER_REMOVED`` rows, stamped with the company and the
acting user), written in the same transaction as the change.
"""

from __future__ import annotations

import uuid

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from api.schemas_agent import (
MemberAddedResponse,
MemberRemovedResponse,
TeamCreate,
TeamCreatedResponse,
TeamDeletedResponse,
)
from api.user_management.dependencies import get_current_user, require_org_context
from api.user_management.teams import _membership_to_response, _team_to_response
from llc.deps import assert_company_access
from llc.models.membership import LLCCompanyMembership
from llc.services.authz import NotAuthorisedError, require_company_admin_unless_platform
from user_management.database import get_async_session
from user_management.services import TeamService, TenantContext
from user_management.services.team_service import DuplicateTeamError, MembershipError, TeamNotFoundError

router = APIRouter(prefix="/companies", tags=["llc-companies"])

_TEAM_NOT_FOUND = "Team not found"
_USER_NOT_FOUND = "User not found in this company"


def _team_service(session: AsyncSession, company_id: uuid.UUID, ctx: TenantContext) -> TeamService:
"""The shared team logic, scoped to the path's company and acting as the caller."""
return TeamService(
session,
TenantContext(org_id=company_id, user_id=ctx.user_id, is_platform_admin=ctx.is_platform_admin),
)


async def _authorize(session: AsyncSession, company_id: uuid.UUID, ctx: TenantContext) -> None:
"""404 for another tenant's company, 403 unless owner/admin here (platform admins pass)."""
assert_company_access(ctx, company_id)
try:
await require_company_admin_unless_platform(
session, company_id, ctx.user_id, platform_admin=ctx.is_platform_admin
)
except NotAuthorisedError as exc:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.public_detail)


async def _require_company_user(session: AsyncSession, company_id: uuid.UUID, user_id: uuid.UUID) -> None:
"""404 unless *user_id* is a member of *company_id*; same answer as an unknown user."""
found = await session.execute(
select(LLCCompanyMembership.id).where(
LLCCompanyMembership.company_id == company_id,
LLCCompanyMembership.user_id == user_id,
)
)
if found.first() is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_USER_NOT_FOUND)


@router.post("/{company_id}/teams", response_model=TeamCreatedResponse, status_code=status.HTTP_201_CREATED)
async def create_company_team(
company_id: uuid.UUID,
body: TeamCreate,
session: AsyncSession = Depends(get_async_session),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> TeamCreatedResponse:
"""Create a team in the path's company; the caller becomes its team owner (``TeamService``)."""
await _authorize(session, company_id, ctx)
try:
team = await _team_service(session, company_id, ctx).create_team(
name=body.name, description=body.description, settings=body.settings, is_default=body.is_default
)
response = TeamCreatedResponse(message=f"Team '{team.name}' created successfully", team=_team_to_response(team))
await session.commit()
except DuplicateTeamError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="A team with that name already exists")
return response


@router.delete("/{company_id}/teams/{team_id}", response_model=TeamDeletedResponse)
async def delete_company_team(
company_id: uuid.UUID,
team_id: uuid.UUID,
session: AsyncSession = Depends(get_async_session),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> TeamDeletedResponse:
"""Soft-delete a team of the path's company. A user action: nothing here deletes teams on its own."""
await _authorize(session, company_id, ctx)
try:
await _team_service(session, company_id, ctx).delete_team(team_id, hard_delete=False)
await session.commit()
except TeamNotFoundError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_TEAM_NOT_FOUND)
return TeamDeletedResponse(message=f"Team {team_id} deleted successfully")


@router.post(
"/{company_id}/teams/{team_id}/members/{user_id}",
response_model=MemberAddedResponse,
status_code=status.HTTP_201_CREATED,
)
async def add_company_team_member(
company_id: uuid.UUID,
team_id: uuid.UUID,
user_id: uuid.UUID,
role: str = Query("member", description="Member role (owner, admin, member)"),
session: AsyncSession = Depends(get_async_session),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> MemberAddedResponse:
"""Add one of the company's own users to one of its teams."""
await _authorize(session, company_id, ctx)
await _require_company_user(session, company_id, user_id)
try:
membership = await _team_service(session, company_id, ctx).add_member(team_id, user_id, role=role)
response = MemberAddedResponse(
message=f"User added to team with role '{role}'", member=_membership_to_response(membership)
)
await session.commit()
except TeamNotFoundError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_TEAM_NOT_FOUND)
except MembershipError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Already a member, or invalid role")
return response


@router.delete("/{company_id}/teams/{team_id}/members/{user_id}", response_model=MemberRemovedResponse)
async def remove_company_team_member(
company_id: uuid.UUID,
team_id: uuid.UUID,
user_id: uuid.UUID,
session: AsyncSession = Depends(get_async_session),
_current_user: dict = Depends(get_current_user),
ctx: TenantContext = Depends(require_org_context),
) -> MemberRemovedResponse:
"""Remove a user from one of the company's teams."""
await _authorize(session, company_id, ctx)
try:
await _team_service(session, company_id, ctx).remove_member(team_id, user_id)
await session.commit()
except TeamNotFoundError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_TEAM_NOT_FOUND)
except MembershipError:
await session.rollback()
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Not a member, or last team owner")
return MemberRemovedResponse(message="Member removed from team")
187 changes: 187 additions & 0 deletions autobot-backend/llc/tests/test_company_teams_14106.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""Company-scoped team writes: owner/admin only, scoped by the path's company, audited (#14106).

The real ``TeamService`` runs; only the lookups that need a database are patched, so the
audit rows it adds to the session and the organisation it filters on are the real ones.
"""

from __future__ import annotations

import uuid
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
from fastapi import HTTPException

from api.schemas_agent import TeamCreate
from autobot_shared.user_management.models.audit import AuditLog
from autobot_shared.user_management.models.team import Team
from llc.api import company_teams as routes
from user_management.services import TeamService

_COMPANY = uuid.uuid4()
_OTHER = uuid.uuid4()
_ACTOR = uuid.uuid4()
_USER = uuid.uuid4()
_TEAM_ID = uuid.uuid4()
_SERVICE = "autobot_shared.user_management.team_service"


def _ctx(org=_COMPANY, admin=False) -> MagicMock:
return MagicMock(org_id=org, user_id=_ACTOR, is_platform_admin=admin)


def _session(company_user: bool = True) -> AsyncMock:
"""A session whose only direct query is 'is this user in the company'."""
session = AsyncMock()
session.add = MagicMock()
session.execute.return_value = MagicMock(first=MagicMock(return_value=(1,) if company_user else None))
return session


def _team() -> Team:
return Team(id=_TEAM_ID, org_id=_COMPANY, name="Platform", settings={}, is_default=False)


def _as(role):
return patch("llc.services.authz.membership_role", AsyncMock(return_value=role))


def _audits(session) -> list[AuditLog]:
return [c.args[0] for c in session.add.call_args_list if isinstance(c.args[0], AuditLog)]


async def _call(name: str, session, ctx):
"""Invoke one route the way FastAPI would, for the same ids."""
if name == "create":
return await routes.create_company_team(_COMPANY, TeamCreate(name="Platform"), session, {}, ctx)
if name == "delete":
return await routes.delete_company_team(_COMPANY, _TEAM_ID, session, {}, ctx)
if name == "add":
return await routes.add_company_team_member(_COMPANY, _TEAM_ID, _USER, "member", session, {}, ctx)
return await routes.remove_company_team_member(_COMPANY, _TEAM_ID, _USER, session, {}, ctx)


def _real_service_lookups():
"""Patch the database lookups of the real TeamService; membership writes still audit."""
return (
patch.object(TeamService, "_find_team_by_name", AsyncMock(return_value=None)),
patch.object(TeamService, "get_team", AsyncMock(return_value=_team())),
patch.object(TeamService, "_get_membership", AsyncMock(return_value=None)),
patch(f"{_SERVICE}.run_after_commit"),
)


@pytest.mark.asyncio
@pytest.mark.parametrize("role", ["owner", "admin"])
@pytest.mark.parametrize(
"route,action", [("create", "team.create"), ("delete", "team.delete"), ("add", "team.member_add")]
)
async def test_an_owner_or_admin_manages_the_teams_and_it_is_audited(role, route, action):
session = _session()
lookups = _real_service_lookups()
with _as(role), lookups[0], lookups[1], lookups[2], lookups[3]:
await _call(route, session, _ctx())
session.commit.assert_awaited_once()
rows = _audits(session)
assert any(row.org_id == _COMPANY and row.user_id == _ACTOR and row.action == action for row in rows), [
r.action for r in rows
]


@pytest.mark.asyncio
async def test_removing_a_member_is_audited():
session = _session()
lookups = _real_service_lookups()
membership = MagicMock(role="member")
with (
_as("admin"),
lookups[0],
lookups[1],
lookups[3],
patch.object(TeamService, "_get_membership", AsyncMock(return_value=membership)),
):
await _call("remove", session, _ctx())
session.commit.assert_awaited_once()
assert any(row.org_id == _COMPANY and row.action == "team.member_remove" for row in _audits(session))


@pytest.mark.asyncio
@pytest.mark.parametrize("role", ["member", "viewer", None])
@pytest.mark.parametrize("route", ["create", "delete", "add", "remove"])
async def test_a_plain_member_is_refused_and_nothing_is_written(role, route):
session = _session()
with _as(role), pytest.raises(HTTPException) as raised:
await _call(route, session, _ctx())
assert raised.value.status_code == 403
session.commit.assert_not_awaited()
assert not _audits(session)


@pytest.mark.asyncio
@pytest.mark.parametrize("route", ["create", "delete", "add", "remove"])
async def test_another_companys_caller_gets_404_even_as_its_owner(route):
session = _session()
with _as("owner"), pytest.raises(HTTPException) as raised:
await _call(route, session, _ctx(org=_OTHER))
assert raised.value.status_code == 404
session.commit.assert_not_awaited()
assert not _audits(session)


@pytest.mark.asyncio
async def test_scope_is_the_paths_company_not_the_ambient_one_for_a_platform_admin():
session = _session()
seen = []
real = routes._team_service

def spy(*args):
service = real(*args)
seen.append(service.context.org_id)
return service

lookups = _real_service_lookups()
with patch.object(routes, "_team_service", spy), lookups[0], lookups[1], lookups[2], lookups[3]:
await _call("create", session, _ctx(org=_OTHER, admin=True))
assert seen == [_COMPANY]
assert all(row.org_id == _COMPANY for row in _audits(session))


@pytest.mark.asyncio
async def test_another_companys_team_is_not_found_and_the_lookup_is_filtered_by_the_path_company():
session = AsyncMock()
session.execute.return_value = MagicMock(scalar_one_or_none=MagicMock(return_value=None))
with _as("admin"), pytest.raises(HTTPException) as raised:
await _call("delete", session, _ctx())
assert raised.value.status_code == 404
session.rollback.assert_awaited_once()
sql = session.execute.await_args.args[0].compile().params
assert _COMPANY in sql.values() and _TEAM_ID in sql.values()


@pytest.mark.asyncio
async def test_a_user_outside_the_company_cannot_be_added_and_looks_like_an_unknown_user():
session = _session(company_user=False)
with (
_as("admin"),
patch.object(TeamService, "add_member", AsyncMock()) as add,
pytest.raises(HTTPException) as raised,
):
await _call("add", session, _ctx())
assert raised.value.status_code == 404
add.assert_not_awaited()
session.commit.assert_not_awaited()


def test_the_routes_exist_and_the_router_is_mounted():
paths = {(m, r.path) for r in routes.router.routes for m in r.methods}
assert ("POST", "/companies/{company_id}/teams") in paths
assert ("DELETE", "/companies/{company_id}/teams/{team_id}") in paths
assert ("POST", "/companies/{company_id}/teams/{team_id}/members/{user_id}") in paths
assert ("DELETE", "/companies/{company_id}/teams/{team_id}/members/{user_id}") in paths
mount = Path(routes.__file__).with_name("__init__.py").read_text(encoding="utf-8")
assert "router.include_router(company_teams_router)" in mount
Loading