Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

30.8 KB
Raw Blame
import { describe, expect, it, afterEach, beforeEach } from 'bun:test';
import { eq, inArray } from 'drizzle-orm';
import { setWorkspaceScim } from '@repo/auth';
import { createWorkspace, db, team } from '@repo/db';
import { resetDb } from '#tests/helpers/db';
import { addUser, joinProject, type Actor } from '#modules/god/__tests__/helpers';
import { createRole, teamIdOf } from '#tests/helpers/roles';
import { createProject as createOwnProject, ownWorkspaceId } from '#tests/helpers/app';
import { patchOps, scimUserBody, setupOtherWorkspace, setupScim, type ScimSetup } from '../helpers';
import { clearLimits, setLimits } from '#tests/helpers/limits';

// What a provisioned group grants: the mappings god or a workspace owner declares turn
// group membership into project membership. Only the rows the sync owns
// are ever touched, so a membership somebody set up through an invite survives.

async function createProject(owner: Actor, name: string, key: string) {
  const created = await createOwnProject(owner.api, { name, key });
  return created.data!;
}

async function membersOf(owner: Actor, projectKey: string) {
  const res = await owner.api.projects({ projectKey }).members.get();
  return res.data!.items;
}

async function teamMemberIds(owner: Actor, teamId: number) {
  const res = await owner.api.teams({ teamId }).members.get();
  return res.data!.items.map((m) => m.userId);
}

async function provisionGroup(
  setup: Pick<ScimSetup, 'scim'>,
  displayName: string,
  memberIds: string[],
) {
  const created = await setup.scim.scim.v2.Groups.post({
    schemas: ['urn:ietf:params:scim:schemas:core:2.0:Group'],
    displayName,
    members: memberIds.map((value) => ({ value })),
  });
  return created.data!.id;
}

describe('SCIM group reconciliation', () => {
  beforeEach(resetDb);
  afterEach(clearLimits);

  it('adds nobody the workspace has no seat for', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    // The instance owner alone already fills the workspace.
    setLimits({ maxSeats: 1 });

    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    expect(await membersOf(setup.god, 'MKT')).not.toContainEqual(
      expect.objectContaining({ userId: ada.data!.id }),
    );
  });

  it('grants membership at the mapped role when a group is mapped', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);

    const res = await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    expect(res.status).toBe(200);
    expect(res.data).toMatchObject({
      displayName: 'Engineering',
      memberCount: 1,
      mappings: [{ projectId: project.id, projectKey: 'MKT', role: 'member' }],
    });

    const members = await membersOf(setup.god, 'MKT');
    expect(members).toContainEqual(
      expect.objectContaining({ userId: ada.data!.id, role: 'member', source: 'scim' }),
    );
  });

  it('assigns the project role named in the mapping', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const role = await createRole(setup.god.api, 'MKT', { name: 'Reviewer', permissions: {} });
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);

    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: role.data!.id }],
    });

    const members = await membersOf(setup.god, 'MKT');
    expect(members).toContainEqual(
      expect.objectContaining({ userId: ada.data!.id, roleId: role.data!.id }),
    );
  });

  it('assigns a system role, and the default role when the mapping names none', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const viewer = await setup.god.api.god.roles.post({ name: 'Viewer', permissions: {} });
    const member = (await setup.god.api.god.roles.get()).data!.find((r) => r.isDefault)!;
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const bob = await setup.scim.scim.v2.Users.post(scimUserBody({ userName: '[email protected]' }));
    const viewers = await provisionGroup(setup, 'Viewers', [ada.data!.id]);
    const everyone = await provisionGroup(setup, 'Everyone', [bob.data!.id]);

    const mapped = await setup.settings.groups({ groupId: viewers }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: viewer.data!.id }],
    });
    await setup.settings.groups({ groupId: everyone }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    expect(mapped.status).toBe(200);
    const members = await membersOf(setup.god, 'MKT');
    expect(members).toContainEqual(
      expect.objectContaining({ userId: ada.data!.id, roleId: viewer.data!.id }),
    );
    expect(members).toContainEqual(
      expect.objectContaining({ userId: bob.data!.id, roleId: member.id }),
    );
    const projects = await setup.settings.projects.get();
    expect(projects.data!.find((p) => p.id === project.id)!.roles.map((r) => r.name)).toEqual([
      'Member',
      'Viewer',
    ]);
  });

  it('revokes membership when the member leaves the group', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));

    const members = await membersOf(setup.god, 'MKT');
    expect(members.map((m) => m.userId)).not.toContain(ada.data!.id);
  });

  it('grants the team membership the project one stands on, and takes it back', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const teamId = await teamIdOf(setup.god.api, 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });
    expect(await teamMemberIds(setup.god, teamId)).toContain(ada.data!.id);

    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));

    expect(await teamMemberIds(setup.god, teamId)).not.toContain(ada.data!.id);
  });

  it('takes the team membership back when the project it stood on is deleted', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const teamId = await teamIdOf(setup.god.api, 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    const deleted = await setup.god.api.projects({ projectKey: 'MKT' }).delete();

    expect(deleted.status).toBe(204);
    expect(await teamMemberIds(setup.god, teamId)).not.toContain(ada.data!.id);
  });

  it('leaves a team membership that came from an invite alone', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const teamId = await teamIdOf(setup.god.api, 'MKT');
    const invited = await addUser({ email: '[email protected]' });
    const invite = await setup.god.api
      .teams({ teamId })
      .invites.post({ email: invited.email, role: 'member' });
    await invited.api.invites({ token: invite.data!.token }).accept.post();
    const groupId = await provisionGroup(setup, 'Engineering', [invited.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: invited.id }] }]));

    expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).not.toContain(invited.id);
    expect(await teamMemberIds(setup.god, teamId)).toContain(invited.id);
  });

  it('revokes membership when the group is unmapped, and when it is deleted', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    const mapTo = (mappings: { projectId: number; role: 'owner' | 'member'; roleId: null }[]) =>
      setup.settings.groups({ groupId }).mappings.put({ mappings });

    await mapTo([{ projectId: project.id, role: 'member', roleId: null }]);
    await mapTo([]);
    expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).not.toContain(ada.data!.id);

    await mapTo([{ projectId: project.id, role: 'member', roleId: null }]);
    expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).toContain(ada.data!.id);

    await setup.scim.scim.v2.Groups({ id: groupId }).delete();
    expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).not.toContain(ada.data!.id);
  });

  it('leaves a membership that came from an invite alone', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const invited = await addUser({ email: '[email protected]' });
    await joinProject(setup.god, invited, 'MKT', 'member');
    const groupId = await provisionGroup(setup, 'Engineering', [invited.id]);

    // Mapped as owner, but the invited membership outranks it and is not re-roled.
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'owner', roleId: null }],
    });
    let members = await membersOf(setup.god, 'MKT');
    expect(members).toContainEqual(
      expect.objectContaining({ userId: invited.id, role: 'member', source: 'invite' }),
    );

    // And removing them from the group does not take the invited membership away.
    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: invited.id }] }]));
    members = await membersOf(setup.god, 'MKT');
    expect(members.map((m) => m.userId)).toContain(invited.id);
  });

  it('resolves a user in two mappings to the stronger role', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const members = await provisionGroup(setup, 'Members', [ada.data!.id]);
    const leads = await provisionGroup(setup, 'Leads', [ada.data!.id]);

    await setup.settings.groups({ groupId: members }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });
    await setup.settings.groups({ groupId: leads }).mappings.put({
      mappings: [{ projectId: project.id, role: 'owner', roleId: null }],
    });

    expect(await membersOf(setup.god, 'MKT')).toContainEqual(
      expect.objectContaining({ userId: ada.data!.id, role: 'owner' }),
    );
  });

  it('keeps the last owner even when the group no longer grants it', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Leads', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'owner', roleId: null }],
    });
    // The creator leaves, which the second owner makes possible. The project is
    // now owned by the provisioned membership alone.
    await setup.god.api.projects({ projectKey: 'MKT' }).members({ userId: setup.god.id }).delete();

    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'remove', path: 'members', value: [{ value: ada.data!.id }] }]));

    // Read through god mode: the creator is no longer a member, so the project's
    // own members route is closed to them.
    const detail = await setup.god.api.god.users({ userId: ada.data!.id }).get();
    expect(detail.data!.projects).toContainEqual(
      expect.objectContaining({ projectKey: 'MKT', role: 'owner' }),
    );
  });

  it('refuses to edit or remove a membership the sync owns', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    const promoted = await setup.god.api
      .projects({ projectKey: 'MKT' })
      .members({ userId: ada.data!.id })
      .patch({ role: 'owner' });
    expect(promoted.status).toBe(409);
    expect(promoted.error!.value).toMatchObject({ error: 'This membership is managed by SCIM' });

    const removed = await setup.god.api
      .projects({ projectKey: 'MKT' })
      .members({ userId: ada.data!.id })
      .delete();
    expect(removed.status).toBe(409);
  });

  it('refuses to remove or leave the team membership the sync owns', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const teamId = await teamIdOf(setup.god.api, 'MKT');
    const ada = await addUser({ email: '[email protected]' });
    const groupId = await provisionGroup(setup, 'Engineering', [ada.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    const removed = await setup.god.api.teams({ teamId }).members({ userId: ada.id }).delete();
    expect(removed.status).toBe(409);
    expect(removed.error!.value).toMatchObject({ error: 'This membership is managed by SCIM' });

    const left = await ada.api.teams({ teamId }).leave.post();
    expect(left.status).toBe(409);
    expect(await teamMemberIds(setup.god, teamId)).toContain(ada.id);
  });

  // Left behind, the mapping's role_id would be nulled by its foreign key and the next
  // sync would put the members it provisions on the default matrix instead.
  it('counts a mapping on a role and moves it when the role is deleted', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const teamId = await teamIdOf(setup.god.api, 'MKT');
    const reviewer = await createRole(setup.god.api, 'MKT', { name: 'Reviewer', permissions: {} });
    const editor = await createRole(setup.god.api, 'MKT', { name: 'Editor', permissions: {} });
    const roleId = reviewer.data!.id;
    const groupId = await provisionGroup(setup, 'Engineering', []);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId }],
    });

    const usage = await setup.god.api.teams({ teamId }).roles({ roleId }).usage.get();
    expect(usage.data).toMatchObject({ members: 0, agents: 0, invites: 0, groups: 1 });

    const deleted = await setup.god.api
      .teams({ teamId })
      .roles({ roleId })
      .delete(undefined, { query: { targetRoleId: editor.data!.id } });
    expect(deleted.status).toBe(204);

    const groups = await setup.settings.groups.get();
    expect(groups.data!.find((g) => g.id === groupId)!.mappings).toEqual([
      expect.objectContaining({ projectId: project.id, roleId: editor.data!.id }),
    ]);
  });

  describe('mapping validation', () => {
    it('404s an unknown group', async () => {
      const setup = await setupScim();

      const res = await setup.settings
        .groups({
          groupId: '00000000-0000-4000-8000-000000000000',
        })
        .mappings.put({ mappings: [] });

      expect(res.status).toBe(404);
    });

    it('refuses an unknown project', async () => {
      const setup = await setupScim();
      const groupId = await provisionGroup(setup, 'Engineering', []);

      const res = await setup.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: 987654, role: 'member', roleId: null }],
      });

      expect(res.status).toBe(400);
      expect(res.error!.value).toMatchObject({ error: 'Unknown project' });
    });

    it('refuses a role that belongs to another team', async () => {
      const setup = await setupScim();
      const marketing = await createProject(setup.god, 'Marketing', 'MKT');
      const otherTeam = await setup.god.api.teams.post({
        name: 'Design',
        slug: 'design',
        workspaceId: await ownWorkspaceId(setup.god.api),
      });
      await setup.god.api.teams({ teamId: otherTeam.data!.id }).projects.post({
        key: 'DSN',
        name: 'Design',
      });
      const role = await createRole(setup.god.api, 'DSN', { name: 'Reviewer', permissions: {} });
      const groupId = await provisionGroup(setup, 'Engineering', []);

      const res = await setup.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: marketing.id, role: 'member', roleId: role.data!.id }],
      });

      expect(res.status).toBe(400);
      expect(res.error!.value).toMatchObject({
        error: 'The role does not belong to that project',
      });
    });

    it('refuses the same project twice', async () => {
      const setup = await setupScim();
      const project = await createProject(setup.god, 'Marketing', 'MKT');
      const groupId = await provisionGroup(setup, 'Engineering', []);

      const res = await setup.settings.groups({ groupId }).mappings.put({
        mappings: [
          { projectId: project.id, role: 'member', roleId: null },
          { projectId: project.id, role: 'owner', roleId: null },
        ],
      });

      expect(res.status).toBe(400);
    });

    it('refuses anyone but the instance owner', async () => {
      const setup = await setupScim();
      const someone = await addUser({ email: '[email protected]' });
      const groupId = await provisionGroup(setup, 'Engineering', []);
      const scim = someone.api.god.scim;

      expect((await scim.groups.get()).status).toBe(403);
      expect((await scim.groups({ groupId }).mappings.put({ mappings: [] })).status).toBe(403);
    });
  });

  it('leaves a deactivated member what the groups granted', async () => {
    const setup = await setupScim();
    const project = await createProject(setup.god, 'Marketing', 'MKT');
    const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
    const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
    await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    await setup.scim.scim.v2
      .Users({ id: ada.data!.id })
      .patch(patchOps([{ op: 'replace', path: 'active', value: false }]));
    await setup.scim.scim.v2
      .Groups({ id: groupId })
      .patch(patchOps([{ op: 'replace', path: 'displayName', value: 'Engineers' }]));

    expect((await membersOf(setup.god, 'MKT')).map((m) => m.userId)).toContain(ada.data!.id);
  });

  it('maps a project of any workspace', async () => {
    const setup = await setupScim();
    const outsider = await addUser({ email: '[email protected]' });
    const project = await createProject(outsider, 'Sales', 'SAL');
    await db
      .update(team)
      .set({ workspaceId: await createWorkspace(db, 'Other', outsider.id) })
      .where(eq(team.id, project.teamId));
    const groupId = await provisionGroup(setup, 'Engineering', []);

    const res = await setup.settings.groups({ groupId }).mappings.put({
      mappings: [{ projectId: project.id, role: 'member', roleId: null }],
    });

    expect(res.status).toBe(200);
    const options = (await setup.settings.projects.get()).data!;
    expect(options.map((o) => o.key)).toContain('SAL');
  });

  // Set up per workspace, as in a hosted build, a workspace's group grants projects of
  // its own workspace only, and nothing to a person its provider deactivated. The
  // instance's provider still grants projects of every workspace, except one that set up
  // SCIM of its own: its provider decides there.
  describe('set up per workspace', () => {
    beforeEach(() => setWorkspaceScim());
    afterEach(() => setWorkspaceScim(false));

    it('grants a deactivated member nothing, and grants it again once they are back', async () => {
      const god = await addUser({ email: '[email protected]' });
      const project = await createProject(god, 'Marketing', 'MKT');
      const own = await setupOtherWorkspace(god, [project.teamId]);
      const ada = await own.scim.scim.v2.Users.post(scimUserBody());
      const groupId = await provisionGroup(own, 'Engineering', [ada.data!.id]);
      await own.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: project.id, role: 'member', roleId: null }],
      });
      const setActive = (value: boolean) =>
        own.scim.scim.v2
          .Users({ id: ada.data!.id })
          .patch(patchOps([{ op: 'replace', path: 'active', value }]));

      await setActive(false);
      // A group change reconciles the project again; the deactivated member stays out.
      await own.scim.scim.v2
        .Groups({ id: groupId })
        .patch(patchOps([{ op: 'replace', path: 'displayName', value: 'Engineers' }]));
      expect((await membersOf(god, 'MKT')).map((m) => m.userId)).not.toContain(ada.data!.id);

      await setActive(true);
      expect((await membersOf(god, 'MKT')).map((m) => m.userId)).toContain(ada.data!.id);
    });

    it('refuses a project of another workspace', async () => {
      const god = await addUser({ email: '[email protected]' });
      const project = await createProject(god, 'Marketing', 'MKT');
      const own = await setupOtherWorkspace(god);
      const groupId = await provisionGroup(own, 'Engineering', []);

      const res = await own.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: project.id, role: 'member', roleId: null }],
      });

      expect(res.status).toBe(400);
      expect(res.error!.value).toMatchObject({ error: 'Unknown project' });
    });

    it("takes the instance's groups out of a workspace with its own, and lets them back", async () => {
      const setup = await setupScim();
      const outsider = await addUser({ email: '[email protected]' });
      const project = await createProject(outsider, 'Sales', 'SAL');
      const workspaceId = await createWorkspace(db, 'Other', outsider.id);
      await db.update(team).set({ workspaceId }).where(eq(team.id, project.teamId));
      const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
      const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
      await setup.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: project.id, role: 'member', roleId: null }],
      });
      const memberIds = async () => (await membersOf(outsider, 'SAL')).map((m) => m.userId);
      const options = async () => (await setup.settings.projects.get()).data!.map((o) => o.key);
      expect(await memberIds()).toContain(ada.data!.id);

      const own = outsider.api.workspaces({ workspaceId }).scim;
      await own.token.post();
      expect((await own.patch({ enabled: true })).status).toBe(200);
      expect(await memberIds()).not.toContain(ada.data!.id);
      expect(await options()).not.toContain('SAL');

      await own.patch({ enabled: false });
      expect(await memberIds()).toContain(ada.data!.id);
      expect(await options()).toContain('SAL');
    });

    it('keeps a mapping into a workspace with its own when the group is saved again', async () => {
      const setup = await setupScim();
      const outsider = await addUser({ email: '[email protected]' });
      const sales = await createProject(outsider, 'Sales', 'SAL');
      const support = await createProject(outsider, 'Support', 'SUP');
      const marketing = await createProject(setup.god, 'Marketing', 'MKT');
      const workspaceId = await createWorkspace(db, 'Other', outsider.id);
      await db
        .update(team)
        .set({ workspaceId })
        .where(inArray(team.id, [sales.teamId, support.teamId]));
      const ada = await setup.scim.scim.v2.Users.post(scimUserBody());
      const groupId = await provisionGroup(setup, 'Engineering', [ada.data!.id]);
      const map = (...projectIds: number[]) =>
        setup.settings.groups({ groupId }).mappings.put({
          mappings: projectIds.map((projectId) => ({
            projectId,
            role: 'member' as const,
            roleId: null,
          })),
        });
      const memberIds = async () => (await membersOf(outsider, 'SAL')).map((m) => m.userId);
      await map(sales.id);
      const own = outsider.api.workspaces({ workspaceId }).scim;
      await own.token.post();
      await own.patch({ enabled: true });

      expect((await map(sales.id, marketing.id)).status).toBe(200);
      expect(await memberIds()).not.toContain(ada.data!.id);
      expect((await map(sales.id, marketing.id, support.id)).status).toBe(400);

      await own.patch({ enabled: false });
      expect(await memberIds()).toContain(ada.data!.id);
    });
  });

  // A directory that never calls POST /Groups still grants access this way: it
  // embeds the groups a user belongs to right on the user payload, which is what
  // "push groups" means in some identity providers instead of a separate sync.
  describe('groups embedded on a user', () => {
    it('creates the group from a userless sync and adds the account to it', async () => {
      const setup = await setupScim();

      const created = await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ display: 'Engineering' }],
      });

      const groups = await setup.settings.groups.get();
      expect(groups.data).toContainEqual(
        expect.objectContaining({ displayName: 'Engineering', memberCount: 1 }),
      );
      expect(groups.data!.find((g) => g.displayName === 'Engineering')!.mappings).toEqual([]);
      expect(created.status).toBe(201);
    });

    it('falls back to value when the provider sends no display name', async () => {
      const setup = await setupScim();

      await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ value: 'Engineering' }],
      });

      const groups = await setup.settings.groups.get();
      expect(groups.data).toContainEqual(
        expect.objectContaining({ displayName: 'Engineering', memberCount: 1 }),
      );
    });

    // The same parser reads an OIDC `groups` claim, which is conventionally a bare
    // array of names rather than SCIM's `{ value, display }` refs.
    it('accepts a plain array of group names', async () => {
      const setup = await setupScim();

      await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: ['Engineering', 'Design'],
      });

      const groups = await setup.settings.groups.get();
      expect(groups.data!.map((g) => g.displayName).sort()).toEqual(['Design', 'Engineering']);
    });

    it('grants project access right away when the group is already mapped', async () => {
      const setup = await setupScim();
      const project = await createProject(setup.god, 'Marketing', 'MKT');
      const groupId = await provisionGroup(setup, 'Engineering', []);
      await setup.settings.groups({ groupId }).mappings.put({
        mappings: [{ projectId: project.id, role: 'member', roleId: null }],
      });

      const created = await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ display: 'Engineering' }],
      });

      const members = await membersOf(setup.god, 'MKT');
      expect(members).toContainEqual(
        expect.objectContaining({ userId: created.data!.id, role: 'member', source: 'scim' }),
      );
    });

    it('does not duplicate a group already pushed through POST /Groups', async () => {
      const setup = await setupScim();
      const groupId = await provisionGroup(setup, 'Engineering', []);

      await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ display: 'Engineering' }],
      });

      const groups = await setup.settings.groups.get();
      expect(groups.data!.filter((g) => g.displayName === 'Engineering')).toHaveLength(1);
      expect(groups.data!.find((g) => g.id === groupId)!.memberCount).toBe(1);
    });

    it('adds an updated group without removing the ones already there', async () => {
      const setup = await setupScim();

      const created = await setup.scim.scim.v2.Users.post({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ display: 'Engineering' }],
      });
      await setup.scim.scim.v2.Users({ id: created.data!.id }).put({
        schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
        userName: '[email protected]',
        emails: [{ value: '[email protected]', primary: true }],
        groups: [{ display: 'Design' }],
      });

      const groups = await setup.settings.groups.get();
      expect(groups.data!.find((g) => g.displayName === 'Engineering')!.memberCount).toBe(1);
      expect(groups.data!.find((g) => g.displayName === 'Design')!.memberCount).toBe(1);
    });
  });
});