Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

wip: scim groups & users

Nikolai Gimana580ed31f4c5
diff --git a/api/src/App.ts b/api/src/App.ts
index 41dcde0..7337d49 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -13,6 +13,7 @@ import { validateSsoEnvOnStartup } from './tv-modules/sso/sso.utils';
import { FileStorageFactory } from './tv-modules/files/storage/FileStorageFactory';
import cookieParser from 'cookie-parser';
import { registerAllEventHandlers, startAllWorkers } from './core/all-events';
+import { ScimBodyErrorHandler } from './tv-modules/scim/middlewares/ScimBodyErrorHandler';
export default class App {
public app: express.Application;
@@ -93,6 +94,7 @@ export default class App {
for (const i in routes) {
this.app.use(i, new routes[i]().getRouter());
}
+ this.app.use('/scim/v2', ScimBodyErrorHandler);
}
public listen() {
diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.json
index 96c73f4..ed34688 100644
--- a/api/src/migrations/taskview/migrate.json
+++ b/api/src/migrations/taskview/migrate.json
@@ -842,5 +842,24 @@
"New schema tv_automations with the rules table. A rule belongs to a project and links a trigger (module, event, params) to an action (module, action, params); actions run on behalf of the rule creator with their current project permissions.",
"New permission group 8 'automations' with automation_can_view and automation_can_manage. New projects grant them to editor (both) and executor (view) through the updated add_roles_and_permissions() trigger. Existing projects are not backfilled: owners grant the permissions to their roles in the role editor."
]
+ },
+ "65": {
+ "version": "1.70.0",
+ "name": "SCIM: provisioned users and groups",
+ "releaseDate": "20261015",
+ "scripts": [
+ "/1.70.0/0.create-scim-users.sql",
+ "/1.70.0/1.backfill-scim-users.sql",
+ "/1.70.0/2.remove-orphan-role-links.sql",
+ "/1.70.0/3.create-scim-groups.sql",
+ "/1.70.0/4.create-scim-group-projects.sql"
+ ],
+ "description": [
+ "New table tv_auth.scim_users: users provisioned by an identity provider over SCIM, per SSO configuration. Stores the SCIM id, userName, externalId, email, name attributes and the active flag; deactivated users keep their row and the organization role and project access they had, which are restored on reactivation.",
+ "Existing members of organizations with a SCIM token are backfilled with their email as SCIM id and userName, so identity providers connected before this version keep working.",
+ "Removing a person from a project now also removes their links to that project's roles; links left behind by earlier removals are deleted.",
+ "New tables tv_auth.scim_groups and tv_auth.scim_group_members: groups pushed by an identity provider over SCIM and their members, per SSO configuration. Groups are stored only and do not grant access yet.",
+ "New table tv_auth.scim_group_projects: an organization admin links a SCIM group to a project with a default role. People who join the group, or are in it when the link is made, or are reactivated while in it, are added to the project with that role unless they are already in it. Leaving the group changes nothing: the project is managed in TaskView."
+ ]
}
}
diff --git a/api/src/migrations/taskview/sql/1.70.0/0.create-scim-users.sql b/api/src/migrations/taskview/sql/1.70.0/0.create-scim-users.sql
new file mode 100644
index 0000000..ecade28
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.70.0/0.create-scim-users.sql
@@ -0,0 +1,21 @@
+CREATE TABLE IF NOT EXISTS tv_auth.scim_users (
+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ sso_config_id INTEGER NOT NULL REFERENCES tv_auth.sso_configs(id) ON DELETE CASCADE,
+ scim_id VARCHAR(255) NOT NULL,
+ user_name VARCHAR(255) NOT NULL,
+ external_id VARCHAR(255),
+ email VARCHAR(255) NOT NULL,
+ member_email VARCHAR(255) NOT NULL,
+ display_name VARCHAR(255),
+ given_name VARCHAR(255),
+ family_name VARCHAR(255),
+ active BOOLEAN NOT NULL DEFAULT TRUE,
+ suspended_membership JSONB,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS scim_users_config_scim_id_uidx ON tv_auth.scim_users (sso_config_id, scim_id);
+CREATE UNIQUE INDEX IF NOT EXISTS scim_users_config_user_name_uidx ON tv_auth.scim_users (sso_config_id, lower(user_name));
+CREATE UNIQUE INDEX IF NOT EXISTS scim_users_config_email_uidx ON tv_auth.scim_users (sso_config_id, email);
+CREATE UNIQUE INDEX IF NOT EXISTS scim_users_config_external_id_uidx ON tv_auth.scim_users (sso_config_id, external_id) WHERE external_id IS NOT NULL;
diff --git a/api/src/migrations/taskview/sql/1.70.0/1.backfill-scim-users.sql b/api/src/migrations/taskview/sql/1.70.0/1.backfill-scim-users.sql
new file mode 100644
index 0000000..2e58e2b
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.70.0/1.backfill-scim-users.sql
@@ -0,0 +1,10 @@
+-- Identity providers connected before 1.70.0 know their users by email (the old SCIM id).
+-- Keep those ids so existing provisioning keeps working. Only addresses of the SSO domain:
+-- SCIM must never manage members outside it.
+INSERT INTO tv_auth.scim_users (sso_config_id, scim_id, user_name, email, member_email)
+SELECT c.id, m.email, lower(m.email), lower(m.email), m.email
+FROM tv_auth.sso_configs c
+JOIN tv_auth.organization_members m ON m.organization_id = c.organization_id
+WHERE c.scim_token IS NOT NULL
+ AND lower(split_part(m.email, '@', 2)) = lower(c.email_domain_restriction)
+ON CONFLICT DO NOTHING;
diff --git a/api/src/migrations/taskview/sql/1.70.0/2.remove-orphan-role-links.sql b/api/src/migrations/taskview/sql/1.70.0/2.remove-orphan-role-links.sql
new file mode 100644
index 0000000..6c3591e
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.70.0/2.remove-orphan-role-links.sql
@@ -0,0 +1,11 @@
+-- Removing a person from a project used to keep their links to that project's roles,
+-- so a later invitation silently brought the old roles back. Drop the links left behind.
+DELETE FROM collaboration.users_to_roles ur
+USING collaboration.roles r
+WHERE r.id = ur.role_id
+ AND NOT EXISTS (
+ SELECT 1
+ FROM collaboration.users_to_goals ug
+ WHERE ug.user_id = ur.user_id
+ AND ug.goal_id = r.goal_id
+ );
diff --git a/api/src/migrations/taskview/sql/1.70.0/3.create-scim-groups.sql b/api/src/migrations/taskview/sql/1.70.0/3.create-scim-groups.sql
new file mode 100644
index 0000000..775d949
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.70.0/3.create-scim-groups.sql
@@ -0,0 +1,24 @@
+CREATE TABLE IF NOT EXISTS tv_auth.scim_groups (
+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ sso_config_id INTEGER NOT NULL REFERENCES tv_auth.sso_configs(id) ON DELETE CASCADE,
+ scim_id VARCHAR(255) NOT NULL,
+ display_name VARCHAR(255) NOT NULL,
+ external_id VARCHAR(255),
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS scim_groups_config_scim_id_uidx ON tv_auth.scim_groups (sso_config_id, scim_id);
+-- displayName is not unique (RFC 7643, Pocket ID repeats friendly names); the index serves the displayName filter
+CREATE INDEX IF NOT EXISTS scim_groups_config_display_name_idx ON tv_auth.scim_groups (sso_config_id, lower(display_name));
+CREATE UNIQUE INDEX IF NOT EXISTS scim_groups_config_external_id_uidx ON tv_auth.scim_groups (sso_config_id, external_id) WHERE external_id IS NOT NULL;
+
+CREATE TABLE IF NOT EXISTS tv_auth.scim_group_members (
+ group_id INTEGER NOT NULL REFERENCES tv_auth.scim_groups(id) ON DELETE CASCADE,
+ scim_user_id INTEGER NOT NULL REFERENCES tv_auth.scim_users(id) ON DELETE CASCADE,
+ -- When the person joined: a reactivated person gets the projects of groups joined while deactivated
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (group_id, scim_user_id)
+);
+
+CREATE INDEX IF NOT EXISTS scim_group_members_scim_user_id_idx ON tv_auth.scim_group_members (scim_user_id);
diff --git a/api/src/migrations/taskview/sql/1.70.0/4.create-scim-group-projects.sql b/api/src/migrations/taskview/sql/1.70.0/4.create-scim-group-projects.sql
new file mode 100644
index 0000000..bf1bc3d
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.70.0/4.create-scim-group-projects.sql
@@ -0,0 +1,11 @@
+-- An organization admin links a SCIM group to a project: people who join the group are added
+-- to the project with the default role. Only additions follow, the project is managed in TaskView
+CREATE TABLE IF NOT EXISTS tv_auth.scim_group_projects (
+ group_id INTEGER NOT NULL REFERENCES tv_auth.scim_groups(id) ON DELETE CASCADE,
+ goal_id INTEGER NOT NULL REFERENCES tasks.goals(id) ON DELETE CASCADE,
+ role_id INTEGER NOT NULL REFERENCES collaboration.roles(id) ON DELETE CASCADE,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (group_id, goal_id)
+);
+
+CREATE INDEX IF NOT EXISTS scim_group_projects_goal_id_idx ON tv_auth.scim_group_projects (goal_id);
diff --git a/api/src/tv-modules/auth/AuthController.ts b/api/src/tv-modules/auth/AuthController.ts
index 4eb05ef..ab57a75 100644
--- a/api/src/tv-modules/auth/AuthController.ts
+++ b/api/src/tv-modules/auth/AuthController.ts
@@ -226,13 +226,16 @@ export default class AuthController {
return res.status(400).send('User not found');
}
+ // Providers may return mixed-case addresses; every other login path stores emails lowercased
+ const email = user.email.trim().toLowerCase();
+
let userData = await req.appUser.authManager.repository.getUserByLogin(
- user.email,
- isEmail(user.email)
+ email,
+ isEmail(email)
);
if (!userData) {
- if (!(await this.canCreateAccount(req, user.email))) {
+ if (!(await this.canCreateAccount(req, email))) {
$logger.info(`[AuthController:loginByProvider] public registration disabled, email not invited`);
return res.redirect(`${process.env.APP_URL}/login?sso_error=registration-disabled`);
}
@@ -242,7 +245,7 @@ export default class AuthController {
const id = await req.appUser.authManager.repository.registerUserInDb({
login,
- email: user.email,
+ email,
password: hashSync(password, 10),
block: 0,
confirmEmailCode: '',
@@ -253,17 +256,17 @@ export default class AuthController {
return res.status(500).send(`Can not register user`);
}
- await this.createPersonalWorkspace(id, user.email, login)
+ await this.createPersonalWorkspace(id, email, login)
userData = await req.appUser.authManager.repository.getUserByLogin(
- user.email,
- isEmail(user.email)
+ email,
+ isEmail(email)
);
}
if (!userData) {
$logger.error(`Can not find user after registration`);
- return res.status(500).send(`Can not find user ${user.email} after registration`);
+ return res.status(500).send(`Can not find user ${email} after registration`);
}
const code = this.generateLoginCode();
diff --git a/api/src/tv-modules/auth/AuthModel.ts b/api/src/tv-modules/auth/AuthModel.ts
index eec20fa..7e2f778 100644
--- a/api/src/tv-modules/auth/AuthModel.ts
+++ b/api/src/tv-modules/auth/AuthModel.ts
@@ -1,5 +1,5 @@
import { eq, sql } from 'drizzle-orm';
-import { CollaborationUsersSchema, OrganizationMembersSchema, SsoIdentitiesSchema, UsersSchema } from 'taskview-db-schemas';
+import { CollaborationUsersSchema, OrganizationMembersSchema, ScimUsersSchema, SsoIdentitiesSchema, UsersSchema } from 'taskview-db-schemas';
import { Database } from '../../modules/db';
import { $logger } from '../../modules/logget';
import type { RegisterUserInDb, UpdateUserCredentialsArgs, UpdateUserEmailArgs, UpdateUserCredentialsResult, UserDbRecord } from '../../types/auth.types';
@@ -13,11 +13,15 @@ export default class AuthModel {
async getUserByLogin(login: string, isEmail: boolean = false): Promise<UserDbRecord | false> {
const field = isEmail ? 'email' : 'login';
+ // Emails are case-insensitive; legacy rows may still hold mixed case, oldest account wins
+ const query = isEmail
+ ? 'select * from tv_auth.users where lower(email) = lower($1) order by id limit 1'
+ : 'select * from tv_auth.users where login = $1';
$logger.info({ field }, `[AuthModel:getUserByLogin] field`);
try {
- const data = await this.db.query<UserDbRecord>(`select * from tv_auth.users where ${field} = $1`, [login]);
+ const data = await this.db.query<UserDbRecord>(query, [login]);
- $logger.info({ login }, `[AuthModel:getUserByLogin] select * from tv_auth.users where ${field} = $1`);
+ $logger.info({ login }, `[AuthModel:getUserByLogin] ${query}`);
$logger.info(data, `[AuthModel:getUserByLogin] data`);
if (data.rows && data.rows.length > 0) {
@@ -182,11 +186,11 @@ export default class AuthModel {
await tx
.update(OrganizationMembersSchema)
.set({ email: args.email })
- .where(eq(OrganizationMembersSchema.email, args.oldEmail));
+ .where(sql`lower(${OrganizationMembersSchema.email}) = ${args.oldEmail.toLowerCase()}`);
await tx
.update(CollaborationUsersSchema)
.set({ email: args.email })
- .where(eq(CollaborationUsersSchema.email, args.oldEmail));
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${args.oldEmail.toLowerCase()}`);
await tx
.update(SsoIdentitiesSchema)
.set({ email: args.email })
@@ -214,11 +218,15 @@ export default class AuthModel {
await tx
.update(OrganizationMembersSchema)
.set({ email: args.email })
- .where(eq(OrganizationMembersSchema.email, args.oldEmail));
+ .where(sql`lower(${OrganizationMembersSchema.email}) = ${args.oldEmail.toLowerCase()}`);
await tx
.update(CollaborationUsersSchema)
.set({ email: args.email })
- .where(eq(CollaborationUsersSchema.email, args.oldEmail));
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${args.oldEmail.toLowerCase()}`);
+ await tx
+ .update(ScimUsersSchema)
+ .set({ memberEmail: args.email })
+ .where(sql`lower(${ScimUsersSchema.memberEmail}) = ${args.oldEmail.toLowerCase()}`);
await tx
.update(SsoIdentitiesSchema)
.set({ email: args.email })
diff --git a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts b/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
index ff803b1..9af9c8f 100644
--- a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
+++ b/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts
@@ -77,6 +77,20 @@ describe('AuthModel Integration Tests', () => {
});
});
+ it('getUserByLogin finds a mixed-case email case-insensitively', async () => {
+ const userId = await authModel.registerUserInDb({
+ login: `${emailNum}testuser`,
+ email: `${emailNum}[email protected]`,
+ password: 'hashed_password',
+ confirmEmailCode: '',
+ block: 0,
+ });
+ expect(userId).toBeTruthy();
+
+ const user = await authModel.getUserByLogin(`${emailNum}[email protected]`, true);
+ expect(user && user.id).toBe(userId);
+ });
+
it('fetchUserById', async () => {
const userData: RegisterUserInDb = {
login: `${emailNum}testuser2`,
diff --git a/api/src/tv-modules/auth/__tests__/LoginByProvider.spec.ts b/api/src/tv-modules/auth/__tests__/LoginByProvider.spec.ts
new file mode 100644
index 0000000..08a9ae9
--- /dev/null
+++ b/api/src/tv-modules/auth/__tests__/LoginByProvider.spec.ts
@@ -0,0 +1,53 @@
+import type { Request, Response } from 'express';
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { Database } from '../../../modules/db';
+import AuthController from '../AuthController';
+import AuthModel from '../AuthModel';
+
+describe('loginByProvider email normalization', () => {
+ const prefix = `${Date.now()}${Math.floor(Math.random() * 1000)}`;
+ const lowerEmail = `${prefix}[email protected]`;
+ const authModel = new AuthModel();
+ const controller = new AuthController();
+
+ afterAll(async () => {
+ await Database.getInstance().query('delete from tv_auth.users where lower(email) = $1', [lowerEmail]);
+ });
+
+ const callWith = async (email: string) => {
+ const req = {
+ user: { email, provider: 'github' },
+ appUser: { authManager: { repository: authModel } },
+ query: {},
+ } as unknown as Request;
+ const res = {
+ redirect: vi.fn(),
+ status: vi.fn().mockReturnThis(),
+ send: vi.fn(),
+ } as unknown as Response;
+
+ await controller.loginByProvider(req, res);
+ return res;
+ };
+
+ it('stores a mixed-case provider email lowercased', async () => {
+ const res = await callWith(`${prefix}[email protected]`);
+ expect(res.redirect).toHaveBeenCalled();
+
+ const rows = await Database.getInstance().query<{ email: string }>(
+ 'select email from tv_auth.users where lower(email) = $1',
+ [lowerEmail],
+ );
+ expect(rows.rows.map((r) => r.email)).toEqual([lowerEmail]);
+ });
+
+ it('signs the same person in again with different casing instead of creating a second account', async () => {
+ await callWith(`${prefix}[email protected]`);
+
+ const rows = await Database.getInstance().query<{ id: number }>(
+ 'select id from tv_auth.users where lower(email) = $1',
+ [lowerEmail],
+ );
+ expect(rows.rows).toHaveLength(1);
+ });
+});
diff --git a/api/src/tv-modules/collaboration/CollaborationRepository.ts b/api/src/tv-modules/collaboration/CollaborationRepository.ts
index ff496ae..463434f 100644
--- a/api/src/tv-modules/collaboration/CollaborationRepository.ts
+++ b/api/src/tv-modules/collaboration/CollaborationRepository.ts
@@ -239,15 +239,30 @@ export class CollaborationRepository {
async deleteUserNew(args: CollaborationArgDeleteUser) {
const result = await callWithCatch(() =>
- this.db.dbDrizzle
- .delete(CollaborationUsersToGoalsSchema)
- .where(
- and(
- eq(CollaborationUsersToGoalsSchema.userId, args.id),
- eq(CollaborationUsersToGoalsSchema.goalId, args.goalId)
+ this.db.dbDrizzle.transaction(async (tx) => {
+ const goalRoles = tx
+ .select({ id: CollaborationRolesSchema.id })
+ .from(CollaborationRolesSchema)
+ .where(eq(CollaborationRolesSchema.goalId, args.goalId));
+ await tx
+ .delete(CollaborationUsersToRolesSchema)
+ .where(
+ and(
+ eq(CollaborationUsersToRolesSchema.userId, args.id),
+ inArray(CollaborationUsersToRolesSchema.roleId, goalRoles)
+ )
+ );
+
+ return await tx
+ .delete(CollaborationUsersToGoalsSchema)
+ .where(
+ and(
+ eq(CollaborationUsersToGoalsSchema.userId, args.id),
+ eq(CollaborationUsersToGoalsSchema.goalId, args.goalId)
+ )
)
- )
- .returning()
+ .returning();
+ })
);
return !!(result && result.length > 0);
diff --git a/api/src/tv-modules/organizations/OrganizationRepository.ts b/api/src/tv-modules/organizations/OrganizationRepository.ts
index 43cc569..87edc62 100644
--- a/api/src/tv-modules/organizations/OrganizationRepository.ts
+++ b/api/src/tv-modules/organizations/OrganizationRepository.ts
@@ -1,9 +1,11 @@
-import { and, eq, inArray, ne } from 'drizzle-orm'
+import { and, eq, inArray, ne, sql } from 'drizzle-orm'
import {
OrganizationsSchema,
OrganizationMembersSchema,
+ CollaborationRolesSchema,
CollaborationUsersSchema,
CollaborationUsersToGoalsSchema,
+ CollaborationUsersToRolesSchema,
GoalsSchema,
UsersSchema,
UserTokensSchema,
@@ -234,7 +236,7 @@ export class OrganizationRepository {
const collabUsers = await this.db.dbDrizzle
.select({ id: CollaborationUsersSchema.id })
.from(CollaborationUsersSchema)
- .where(eq(CollaborationUsersSchema.email, email))
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${email.toLowerCase()}`)
const orgGoals = await this.db.dbDrizzle
.select({ id: GoalsSchema.id })
@@ -245,14 +247,28 @@ export class OrganizationRepository {
const goalIds = orgGoals.map(g => g.id)
if (userIds.length && goalIds.length) {
- await this.db.dbDrizzle
- .delete(CollaborationUsersToGoalsSchema)
- .where(
- and(
- inArray(CollaborationUsersToGoalsSchema.userId, userIds),
- inArray(CollaborationUsersToGoalsSchema.goalId, goalIds),
+ await this.db.dbDrizzle.transaction(async (tx) => {
+ const goalRoles = tx
+ .select({ id: CollaborationRolesSchema.id })
+ .from(CollaborationRolesSchema)
+ .where(inArray(CollaborationRolesSchema.goalId, goalIds))
+ await tx
+ .delete(CollaborationUsersToRolesSchema)
+ .where(
+ and(
+ inArray(CollaborationUsersToRolesSchema.userId, userIds),
+ inArray(CollaborationUsersToRolesSchema.roleId, goalRoles),
+ )
)
- )
+ await tx
+ .delete(CollaborationUsersToGoalsSchema)
+ .where(
+ and(
+ inArray(CollaborationUsersToGoalsSchema.userId, userIds),
+ inArray(CollaborationUsersToGoalsSchema.goalId, goalIds),
+ )
+ )
+ })
}
})
}
diff --git a/api/src/tv-modules/scim/ScimController.ts b/api/src/tv-modules/scim/ScimController.ts
index 8a9b591..8ccd708 100644
--- a/api/src/tv-modules/scim/ScimController.ts
+++ b/api/src/tv-modules/scim/ScimController.ts
@@ -1,93 +1,158 @@
+import { ArkErrors } from 'arktype'
import type { Request, Response } from 'express'
import { $logger } from '../../modules/logget'
+import { PublicApiUrl } from '../../modules/public-url'
+import { ScimError } from './ScimError'
+import { ScimGroupsManager } from './ScimGroupsManager'
import { ScimManager } from './ScimManager'
-import { toScimUser, toScimList, toScimError } from './scim.helpers'
+import { scimGroupResourceType, scimGroupSchema, scimServiceProviderConfig, scimUserResourceType, scimUserSchema } from './scim.discovery'
+import { SCIM_GROUP_SCHEMA, excludesMembers, groupAttributesFromBody, parseGroupListQuery, toScimGroup } from './scim.groups.helpers'
+import { SCIM_USER_SCHEMA, attributesFromBody, parseListQuery, toScimError, toScimList, toScimUser } from './scim.helpers'
+import { ScimGroupArkType, ScimPatchArkType, ScimUserArkType, type ScimContext, type ScimHandler, type ScimValidateArgs } from './types'
export class ScimController {
private readonly manager = new ScimManager()
+ private readonly groups = new ScimGroupsManager()
+
+ listUsers = this.handle(async (req, res) => {
+ const query = parseListQuery(req.query as Record<string, unknown>)
+ const { users, totalResults } = await this.manager.listUsers({ ...this.contextOf(res), query })
+ const baseUrl = this.baseUrl(req)
+ return res.json(toScimList({
+ resources: users.map((user) => toScimUser({ user, baseUrl })),
+ totalResults,
+ startIndex: query.startIndex,
+ }))
+ })
+
+ getUser = this.handle(async (req, res) => {
+ const user = await this.manager.getUser({ ...this.contextOf(res), scimId: req.params.id })
+ return res.json(toScimUser({ user, baseUrl: this.baseUrl(req) }))
+ })
+
+ createUser = this.handle(async (req, res) => {
+ const attributes = attributesFromBody(this.validate({ schema: ScimUserArkType, body: req.body }))
+ const user = await this.manager.createUser({ ...this.contextOf(res), attributes })
+ const resource = toScimUser({ user, baseUrl: this.baseUrl(req) })
+ return res.status(201).location(resource.meta.location).json(resource)
+ })
+
+ replaceUser = this.handle(async (req, res) => {
+ const attributes = attributesFromBody(this.validate({ schema: ScimUserArkType, body: req.body }))
+ const user = await this.manager.replaceUser({ ...this.contextOf(res), scimId: req.params.id, attributes })
+ return res.json(toScimUser({ user, baseUrl: this.baseUrl(req) }))
+ })
+
+ patchUser = this.handle(async (req, res) => {
+ const { Operations } = this.validate({ schema: ScimPatchArkType, body: req.body })
+ const user = await this.manager.patchUser({ ...this.contextOf(res), scimId: req.params.id, operations: Operations })
+ return res.json(toScimUser({ user, baseUrl: this.baseUrl(req) }))
+ })
+
+ deleteUser = this.handle(async (req, res) => {
+ await this.manager.deleteUser({ ...this.contextOf(res), scimId: req.params.id })
+ return res.status(204).end()
+ })
+
+ listGroups = this.handle(async (req, res) => {
+ const query = parseGroupListQuery(req.query as Record<string, unknown>)
+ const { groups, totalResults } = await this.groups.listGroups({ ...this.contextOf(res), query })
+ const baseUrl = this.baseUrl(req)
+ return res.json(toScimList({
+ resources: groups.map((view) => toScimGroup({ view, baseUrl })),
+ totalResults,
+ startIndex: query.startIndex,
+ }))
+ })
+
+ getGroup = this.handle(async (req, res) => {
+ const excludeMembers = excludesMembers(req.query as Record<string, unknown>)
+ const view = await this.groups.getGroup({ ...this.contextOf(res), scimId: req.params.id, excludeMembers })
+ return res.json(toScimGroup({ view, baseUrl: this.baseUrl(req) }))
+ })
+
+ createGroup = this.handle(async (req, res) => {
+ const attributes = groupAttributesFromBody(this.validate({ schema: ScimGroupArkType, body: req.body }))
+ const view = await this.groups.createGroup({ ...this.contextOf(res), attributes })
+ const resource = toScimGroup({ view, baseUrl: this.baseUrl(req) })
+ return res.status(201).location(resource.meta.location).json(resource)
+ })
+
+ replaceGroup = this.handle(async (req, res) => {
+ const attributes = groupAttributesFromBody(this.validate({ schema: ScimGroupArkType, body: req.body }))
+ const view = await this.groups.replaceGroup({ ...this.contextOf(res), scimId: req.params.id, attributes })
+ return res.json(toScimGroup({ view, baseUrl: this.baseUrl(req) }))
+ })
+
+ // Microsoft Entra ID expects 204 here and advises against returning the whole member list
+ patchGroup = this.handle(async (req, res) => {
+ const { Operations } = this.validate({ schema: ScimPatchArkType, body: req.body })
+ await this.groups.patchGroup({ ...this.contextOf(res), scimId: req.params.id, operations: Operations })
+ return res.status(204).end()
+ })
- listUsers = async (_req: Request, res: Response) => {
- const { scimOrg } = res.locals
- const members = await this.manager.listUsers(scimOrg.id)
-
- return res.json(toScimList(members.map(m => toScimUser(m, true))))
- }
-
- getUser = async (req: Request, res: Response) => {
- const { scimOrg } = res.locals
- const email = decodeURIComponent(req.params.id)
-
- const member = await this.manager.getUserByEmail(scimOrg.id, email)
- if (!member) {
- return res.status(404).json(toScimError(404, 'User not found'))
+ deleteGroup = this.handle(async (req, res) => {
+ await this.groups.deleteGroup({ ...this.contextOf(res), scimId: req.params.id })
+ return res.status(204).end()
+ })
+
+ serviceProviderConfig = this.handle(async (req, res) => {
+ return res.json(scimServiceProviderConfig(this.baseUrl(req)))
+ })
+
+ resourceTypes = this.handle(async (req, res) => {
+ const resources = [scimUserResourceType(this.baseUrl(req)), scimGroupResourceType(this.baseUrl(req))]
+ return res.json(toScimList({ resources, totalResults: resources.length, startIndex: 1 }))
+ })
+
+ resourceType = this.handle(async (req, res) => {
+ if (req.params.id === 'User') return res.json(scimUserResourceType(this.baseUrl(req)))
+ if (req.params.id === 'Group') return res.json(scimGroupResourceType(this.baseUrl(req)))
+ throw new ScimError({ status: 404, detail: 'Resource type not found' })
+ })
+
+ schemas = this.handle(async (req, res) => {
+ const resources = [scimUserSchema(this.baseUrl(req)), scimGroupSchema(this.baseUrl(req))]
+ return res.json(toScimList({ resources, totalResults: resources.length, startIndex: 1 }))
+ })
+
+ schema = this.handle(async (req, res) => {
+ if (req.params.id === SCIM_USER_SCHEMA) return res.json(scimUserSchema(this.baseUrl(req)))
+ if (req.params.id === SCIM_GROUP_SCHEMA) return res.json(scimGroupSchema(this.baseUrl(req)))
+ throw new ScimError({ status: 404, detail: 'Schema not found' })
+ })
+
+ notFound = this.handle(async () => {
+ throw new ScimError({ status: 404, detail: 'Endpoint not found' })
+ })
+
+ private handle(handler: ScimHandler) {
+ return async (req: Request, res: Response) => {
+ try {
+ await handler(req, res)
+ } catch (error) {
+ if (error instanceof ScimError) {
+ return res.status(error.status).json(toScimError({ status: error.status, detail: error.message, scimType: error.scimType }))
+ }
+ $logger.error(error, 'SCIM: unexpected error')
+ return res.status(500).json(toScimError({ status: 500, detail: 'Internal server error' }))
+ }
}
-
- return res.json(toScimUser(member, true))
}
- createUser = async (req: Request, res: Response) => {
- const { scimOrg } = res.locals
- const email = req.body.userName || req.body.emails?.[0]?.value
-
- if (!email) {
- return res.status(400).json(toScimError(400, 'userName or emails[0].value is required'))
+ private validate<T>(args: ScimValidateArgs<T>): T {
+ const result = args.schema(args.body ?? {})
+ if (result instanceof ArkErrors) {
+ throw new ScimError({ status: 400, scimType: 'invalidSyntax', detail: result.summary })
}
-
- await this.manager.reactivateUser(scimOrg, email)
-
- const member = await this.manager.getUserByEmail(scimOrg.id, email)
- if (!member) {
- return res.status(500).json(toScimError(500, 'Failed to create user'))
- }
-
- return res.status(201).json(toScimUser(member, true))
+ return result
}
- patchUser = async (req: Request, res: Response) => {
- const { scimOrg, scimConfig } = res.locals
- const email = decodeURIComponent(req.params.id)
-
- const operations = req.body.Operations
-
- if (!Array.isArray(operations) || operations.length === 0) {
- return res.status(400).json(toScimError(400, 'Operations must be a non-empty array'))
- }
-
- for (const op of operations) {
- if (op.op === 'replace' && (op.path === 'active' || op.value?.active !== undefined)) {
- const active = op.path === 'active' ? op.value : op.value.active
-
- if (active === false || active === 'false') {
- const result = await this.manager.deactivateUser(scimOrg, scimConfig, email)
- if (!result) {
- return res.status(404).json(toScimError(404, 'User not found'))
- }
- $logger.info(`SCIM: deactivated user ${email} from org ${scimOrg.id}`)
- return res.json(toScimUser({ email, role: 'member' }, false))
- }
-
- if (active === true || active === 'true') {
- await this.manager.reactivateUser(scimOrg, email)
- $logger.info(`SCIM: reactivated user ${email} in org ${scimOrg.id}`)
- const member = await this.manager.getUserByEmail(scimOrg.id, email)
- return res.json(toScimUser(member || { email, role: 'member' }, true))
- }
- }
- }
-
- return res.status(200).json(toScimUser({ email, role: 'member' }, true))
+ private contextOf(res: Response): ScimContext {
+ return { org: res.locals.scimOrg, config: res.locals.scimConfig }
}
- deleteUser = async (req: Request, res: Response) => {
- const { scimOrg, scimConfig } = res.locals
- const email = decodeURIComponent(req.params.id)
-
- const result = await this.manager.deactivateUser(scimOrg, scimConfig, email)
- if (!result) {
- return res.status(404).json(toScimError(404, 'User not found'))
- }
-
- $logger.info(`SCIM: deleted user ${email} from org ${scimOrg.id}`)
- return res.status(204).end()
+ private baseUrl(req: Request): string {
+ return `${PublicApiUrl.base(req)}/scim/v2`
}
}
diff --git a/api/src/tv-modules/scim/ScimError.ts b/api/src/tv-modules/scim/ScimError.ts
new file mode 100644
index 0000000..3d86e95
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimError.ts
@@ -0,0 +1,12 @@
+import type { ScimErrorArgs, ScimErrorType } from './types'
+
+export class ScimError extends Error {
+ readonly status: number
+ readonly scimType?: ScimErrorType
+
+ constructor(args: ScimErrorArgs) {
+ super(args.detail)
+ this.status = args.status
+ this.scimType = args.scimType
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimGroupProjectsManager.ts b/api/src/tv-modules/scim/ScimGroupProjectsManager.ts
new file mode 100644
index 0000000..810281a
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimGroupProjectsManager.ts
@@ -0,0 +1,56 @@
+import { $logger } from '../../modules/logget'
+import { ScimGroupProjectsRepository } from './ScimGroupProjectsRepository'
+import type {
+ ScimAddToLinkedProjectsArgs,
+ ScimGroupLinksOverview,
+ ScimGroupLinksOverviewArgs,
+ ScimGroupProjectRef,
+ ScimLinkGroupProjectArgs,
+ ScimLinkGroupProjectResult,
+ ScimUnlinkGroupProjectResult,
+} from './types'
+
+export class ScimGroupProjectsManager {
+ private readonly repository = new ScimGroupProjectsRepository()
+
+ async overview(args: ScimGroupLinksOverviewArgs): Promise<ScimGroupLinksOverview> {
+ const [groups, projects] = await Promise.all([
+ this.repository.listGroups(args.config.id),
+ this.repository.projectsWithRoles(args.config.organizationId),
+ ])
+ return { groups, projects }
+ }
+
+ async link(args: ScimLinkGroupProjectArgs): Promise<ScimLinkGroupProjectResult> {
+ const { config, groupId, goalId, roleId } = args
+ const group = await this.repository.findGroup({ ssoConfigId: config.id, groupId })
+ if (!group) return 'group_not_found'
+ // Whoever configures SSO can already decide who signs in, so any active project of the organization can be linked
+ if (!(await this.repository.isActiveProject({ organizationId: config.organizationId, goalId }))) return 'project_not_found'
+ if (!(await this.repository.isProjectRole({ organizationId: config.organizationId, goalId, roleId }))) return 'role_not_in_project'
+
+ const saved = await this.repository.save({ groupId, goalId, roleId })
+ if (!saved) throw new Error('Failed to link a SCIM group to a project')
+ $logger.info(`SCIM: linked group ${group.scimId} to project ${goalId} in SSO config ${config.id}`)
+
+ await this.addToLinkedProjects({ orgId: config.organizationId, groupIds: [groupId], goalIds: [goalId] })
+ return 'ok'
+ }
+
+ async unlink(args: ScimGroupProjectRef): Promise<ScimUnlinkGroupProjectResult> {
+ const group = await this.repository.findGroup({ ssoConfigId: args.config.id, groupId: args.groupId })
+ if (!group) return 'not_found'
+ return await this.repository.delete({ groupId: args.groupId, goalId: args.goalId }) ? 'ok' : 'not_found'
+ }
+
+ async addToLinkedProjects(args: ScimAddToLinkedProjectsArgs): Promise<void> {
+ if (args.scimUserIds?.length === 0) return
+ const grants = await this.repository.grants(args)
+ const added = await this.repository.addToProjects(grants)
+ if (added === null) {
+ $logger.error(`SCIM: failed to add group members to linked projects in org ${args.orgId}`)
+ return
+ }
+ if (added) $logger.info(`SCIM: added group members to ${added} linked project(s) in org ${args.orgId}`)
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimGroupProjectsRepository.ts b/api/src/tv-modules/scim/ScimGroupProjectsRepository.ts
new file mode 100644
index 0000000..23299de
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimGroupProjectsRepository.ts
@@ -0,0 +1,228 @@
+import { and, asc, count, eq, gt, inArray, or, sql } from 'drizzle-orm'
+import {
+ CollaborationRolesSchema,
+ CollaborationUsersSchema,
+ CollaborationUsersToGoalsSchema,
+ CollaborationUsersToRolesSchema,
+ GoalsSchema,
+ OrganizationMembersSchema,
+ ScimGroupMembersSchema,
+ ScimGroupProjectsSchema,
+ ScimGroupsSchema,
+ ScimUsersSchema,
+ UsersSchema,
+ type ScimGroupsSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { Database } from '../../modules/db'
+import { callWithCatch } from '../../utils/helpers'
+import type {
+ ScimAddToLinkedProjectsArgs,
+ ScimAdminGroup,
+ ScimAdminProject,
+ ScimDeleteGroupProjectArgs,
+ ScimFindActiveProjectArgs,
+ ScimFindGroupForConfigArgs,
+ ScimFindProjectRoleArgs,
+ ScimProjectGrant,
+ ScimSaveGroupProjectArgs,
+} from './types'
+
+export class ScimGroupProjectsRepository {
+ private readonly db: Database
+
+ constructor() {
+ this.db = Database.getInstance()
+ }
+
+ async listGroups(ssoConfigId: number): Promise<ScimAdminGroup[]> {
+ const groups = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ id: ScimGroupsSchema.id, displayName: ScimGroupsSchema.displayName, membersCount: count(ScimGroupMembersSchema.scimUserId) })
+ .from(ScimGroupsSchema)
+ .leftJoin(ScimGroupMembersSchema, eq(ScimGroupMembersSchema.groupId, ScimGroupsSchema.id))
+ .where(eq(ScimGroupsSchema.ssoConfigId, ssoConfigId))
+ .groupBy(ScimGroupsSchema.id)
+ .orderBy(asc(sql`lower(${ScimGroupsSchema.displayName})`), asc(ScimGroupsSchema.id))
+ )
+ if (!groups?.length) return []
+
+ const links = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({
+ groupId: ScimGroupProjectsSchema.groupId,
+ goalId: ScimGroupProjectsSchema.goalId,
+ goalName: GoalsSchema.name,
+ roleId: ScimGroupProjectsSchema.roleId,
+ roleName: CollaborationRolesSchema.name,
+ })
+ .from(ScimGroupProjectsSchema)
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, ScimGroupProjectsSchema.goalId))
+ .innerJoin(CollaborationRolesSchema, eq(CollaborationRolesSchema.id, ScimGroupProjectsSchema.roleId))
+ .where(inArray(ScimGroupProjectsSchema.groupId, groups.map((group) => group.id)))
+ .orderBy(asc(GoalsSchema.name))
+ ) ?? []
+
+ return groups.map((group) => ({
+ ...group,
+ projects: links
+ .filter((link) => link.groupId === group.id)
+ .map((link) => ({ goalId: link.goalId, goalName: link.goalName ?? '', roleId: link.roleId, roleName: link.roleName })),
+ }))
+ }
+
+ async projectsWithRoles(organizationId: number): Promise<ScimAdminProject[]> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ goalId: GoalsSchema.id, name: GoalsSchema.name, roleId: CollaborationRolesSchema.id, roleName: CollaborationRolesSchema.name })
+ .from(GoalsSchema)
+ .leftJoin(CollaborationRolesSchema, eq(CollaborationRolesSchema.goalId, GoalsSchema.id))
+ .where(and(eq(GoalsSchema.organizationId, organizationId), eq(GoalsSchema.archive, 0)))
+ .orderBy(asc(GoalsSchema.name), asc(CollaborationRolesSchema.id))
+ ) ?? []
+
+ const projects = new Map<number, ScimAdminProject>()
+ for (const row of rows) {
+ const project = projects.get(row.goalId) ?? { goalId: row.goalId, name: row.name ?? '', roles: [] }
+ if (row.roleId !== null && row.roleName !== null) project.roles.push({ id: row.roleId, name: row.roleName })
+ projects.set(row.goalId, project)
+ }
+ return [...projects.values()]
+ }
+
+ async findGroup(args: ScimFindGroupForConfigArgs): Promise<ScimGroupsSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimGroupsSchema)
+ .where(and(eq(ScimGroupsSchema.ssoConfigId, args.ssoConfigId), eq(ScimGroupsSchema.id, args.groupId)))
+ )
+ return rows?.[0] ?? null
+ }
+
+ async isActiveProject(args: ScimFindActiveProjectArgs): Promise<boolean> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ id: GoalsSchema.id })
+ .from(GoalsSchema)
+ .where(and(eq(GoalsSchema.id, args.goalId), eq(GoalsSchema.organizationId, args.organizationId), eq(GoalsSchema.archive, 0)))
+ )
+ return !!rows?.length
+ }
+
+ async isProjectRole(args: ScimFindProjectRoleArgs): Promise<boolean> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ id: CollaborationRolesSchema.id })
+ .from(CollaborationRolesSchema)
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, CollaborationRolesSchema.goalId))
+ .where(and(
+ eq(CollaborationRolesSchema.id, args.roleId),
+ eq(CollaborationRolesSchema.goalId, args.goalId),
+ eq(GoalsSchema.organizationId, args.organizationId),
+ ))
+ )
+ return !!rows?.length
+ }
+
+ async save(args: ScimSaveGroupProjectArgs): Promise<boolean> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .insert(ScimGroupProjectsSchema)
+ .values({ groupId: args.groupId, goalId: args.goalId, roleId: args.roleId })
+ .onConflictDoUpdate({
+ target: [ScimGroupProjectsSchema.groupId, ScimGroupProjectsSchema.goalId],
+ set: { roleId: args.roleId },
+ })
+ .returning()
+ )
+ return !!rows?.length
+ }
+
+ async delete(args: ScimDeleteGroupProjectArgs): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .delete(ScimGroupProjectsSchema)
+ .where(and(eq(ScimGroupProjectsSchema.groupId, args.groupId), eq(ScimGroupProjectsSchema.goalId, args.goalId)))
+ )
+ return !!result?.rowCount
+ }
+
+ // What the links promise to active group members, skipping projects they own
+ async grants(args: ScimAddToLinkedProjectsArgs): Promise<ScimProjectGrant[]> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ email: ScimUsersSchema.memberEmail, goalId: ScimGroupProjectsSchema.goalId, roleId: ScimGroupProjectsSchema.roleId })
+ .from(ScimGroupProjectsSchema)
+ .innerJoin(ScimGroupMembersSchema, eq(ScimGroupMembersSchema.groupId, ScimGroupProjectsSchema.groupId))
+ .innerJoin(ScimUsersSchema, and(eq(ScimUsersSchema.id, ScimGroupMembersSchema.scimUserId), eq(ScimUsersSchema.active, true)))
+ .innerJoin(GoalsSchema, and(
+ eq(GoalsSchema.id, ScimGroupProjectsSchema.goalId),
+ eq(GoalsSchema.organizationId, args.orgId),
+ eq(GoalsSchema.archive, 0),
+ ))
+ // Someone an admin removed from the organization keeps an active SCIM record, but gets no project
+ .innerJoin(OrganizationMembersSchema, and(
+ eq(OrganizationMembersSchema.organizationId, args.orgId),
+ sql`lower(${OrganizationMembersSchema.email}) = lower(${ScimUsersSchema.memberEmail})`,
+ ))
+ .leftJoin(UsersSchema, eq(UsersSchema.id, GoalsSchema.owner))
+ .where(and(
+ sql`lower(${UsersSchema.email}) is distinct from lower(${ScimUsersSchema.memberEmail})`,
+ ...(args.groupIds ? [inArray(ScimGroupProjectsSchema.groupId, args.groupIds)] : []),
+ ...(args.goalIds ? [inArray(ScimGroupProjectsSchema.goalId, args.goalIds)] : []),
+ ...(args.scimUserIds ? [inArray(ScimGroupMembersSchema.scimUserId, args.scimUserIds)] : []),
+ ...(args.since ? [or(gt(ScimGroupProjectsSchema.createdAt, args.since), gt(ScimGroupMembersSchema.createdAt, args.since))] : []),
+ ))
+ )
+ return rows ?? []
+ }
+
+ // Adds each person to the projects they are not in yet; a project they are in already is left as it is
+ async addToProjects(grants: ScimProjectGrant[]): Promise<number | null> {
+ if (!grants.length) return 0
+ const byEmail = Map.groupBy(grants, (grant) => grant.email.toLowerCase())
+
+ return await callWithCatch(() =>
+ this.db.dbDrizzle.transaction(async (tx) => {
+ let added = 0
+ for (const [email, personGrants] of byEmail) {
+ // Concurrent SCIM requests for the same person must not both insert: neither table has a unique key for this
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${`scim-grant:${email}`}))`)
+ const [existing] = await tx
+ .select({ id: CollaborationUsersSchema.id })
+ .from(CollaborationUsersSchema)
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${email}`)
+ const collabUserId = existing?.id
+ ?? (await tx.insert(CollaborationUsersSchema).values({ email }).returning({ id: CollaborationUsersSchema.id }))[0].id
+
+ const goalIds = [...new Set(personGrants.map((grant) => grant.goalId))]
+ const linked = await tx
+ .select({ goalId: CollaborationUsersToGoalsSchema.goalId })
+ .from(CollaborationUsersToGoalsSchema)
+ .where(and(eq(CollaborationUsersToGoalsSchema.userId, collabUserId), inArray(CollaborationUsersToGoalsSchema.goalId, goalIds)))
+ const linkedGoalIds = new Set(linked.map((link) => link.goalId))
+ const fresh = personGrants.filter((grant) => !linkedGoalIds.has(grant.goalId))
+ if (!fresh.length) continue
+
+ const freshGoalIds = [...new Set(fresh.map((grant) => grant.goalId))]
+ await tx
+ .insert(CollaborationUsersToGoalsSchema)
+ .values(freshGoalIds.map((goalId) => ({ userId: collabUserId, goalId })))
+ .onConflictDoNothing()
+ // users_to_roles has no unique key, so links the person already holds are left out by hand
+ const held = await tx
+ .select({ roleId: CollaborationUsersToRolesSchema.roleId })
+ .from(CollaborationUsersToRolesSchema)
+ .where(eq(CollaborationUsersToRolesSchema.userId, collabUserId))
+ const heldRoleIds = new Set(held.map((link) => link.roleId))
+ const roleIds = [...new Set(fresh.map((grant) => grant.roleId))].filter((roleId) => !heldRoleIds.has(roleId))
+ if (roleIds.length) {
+ await tx.insert(CollaborationUsersToRolesSchema).values(roleIds.map((roleId) => ({ userId: collabUserId, roleId })))
+ }
+ added += freshGoalIds.length
+ }
+ return added
+ })
+ )
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimGroupsManager.ts b/api/src/tv-modules/scim/ScimGroupsManager.ts
new file mode 100644
index 0000000..917423e
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimGroupsManager.ts
@@ -0,0 +1,135 @@
+import type { ScimGroupsSchemaTypeForSelect } from 'taskview-db-schemas'
+import { $logger } from '../../modules/logget'
+import { ScimError } from './ScimError'
+import { ScimGroupProjectsManager } from './ScimGroupProjectsManager'
+import { ScimGroupsRepository } from './ScimGroupsRepository'
+import { applyGroupPatchOperations } from './scim.groups.helpers'
+import type {
+ ScimApplyGroupChangesArgs,
+ ScimCreateGroupArgs,
+ ScimGetGroupArgs,
+ ScimGroupAttributes,
+ ScimGroupByIdArgs,
+ ScimGroupView,
+ ScimListGroupsArgs,
+ ScimListGroupsResult,
+ ScimPatchGroupArgs,
+ ScimReplaceGroupArgs,
+ ScimWithMembersArgs,
+ ScimFindUsersByScimIdsArgs,
+} from './types'
+
+export class ScimGroupsManager {
+ private readonly repository = new ScimGroupsRepository()
+ private readonly projects = new ScimGroupProjectsManager()
+
+ async listGroups(args: ScimListGroupsArgs): Promise<ScimListGroupsResult> {
+ const { config, query } = args
+
+ if (query.filter) {
+ const found = await this.repository.findByFilter({ ssoConfigId: config.id, filter: query.filter })
+ const groups = found.slice(query.startIndex - 1, query.startIndex - 1 + query.count)
+ return { groups: await this.withMembers({ groups, excludeMembers: query.excludeMembers }), totalResults: found.length }
+ }
+
+ const [totalResults, groups] = await Promise.all([
+ this.repository.countForConfig(config.id),
+ this.repository.listPage({ ssoConfigId: config.id, offset: query.startIndex - 1, limit: query.count }),
+ ])
+ return { groups: await this.withMembers({ groups, excludeMembers: query.excludeMembers }), totalResults }
+ }
+
+ async getGroup(args: ScimGetGroupArgs): Promise<ScimGroupView> {
+ const group = await this.findGroup(args)
+ const [view] = await this.withMembers({ groups: [group], excludeMembers: args.excludeMembers })
+ return view
+ }
+
+ async createGroup(args: ScimCreateGroupArgs): Promise<ScimGroupView> {
+ const { config, attributes } = args
+
+ const conflict = await this.repository.findConflict({ ssoConfigId: config.id, externalId: attributes.externalId })
+ if (conflict) throw new ScimError({ status: 409, scimType: 'uniqueness', detail: 'A group with this externalId already exists' })
+ const scimUserIds = await this.resolveMembers({ ssoConfigId: config.id, scimIds: attributes.members })
+
+ const group = await this.repository.insert({
+ values: {
+ ssoConfigId: config.id,
+ scimId: crypto.randomUUID(),
+ displayName: attributes.displayName,
+ externalId: attributes.externalId,
+ },
+ scimUserIds,
+ })
+ if (!group) throw new ScimError({ status: 500, detail: 'Failed to create group' })
+ $logger.info(`SCIM: provisioned group ${group.scimId} for SSO config ${config.id}`)
+
+ const [view] = await this.withMembers({ groups: [group], excludeMembers: false })
+ return view
+ }
+
+ async replaceGroup(args: ScimReplaceGroupArgs): Promise<ScimGroupView> {
+ const group = await this.findGroup(args)
+ return await this.applyChanges({ org: args.org, config: args.config, group, next: args.attributes })
+ }
+
+ async patchGroup(args: ScimPatchGroupArgs): Promise<ScimGroupView> {
+ const group = await this.findGroup(args)
+ const [view] = await this.withMembers({ groups: [group], excludeMembers: false })
+ const current: ScimGroupAttributes = {
+ displayName: group.displayName,
+ externalId: group.externalId,
+ members: (view.members ?? []).map((member) => member.scimId),
+ }
+ const next = applyGroupPatchOperations({ current, operations: args.operations })
+ return await this.applyChanges({ org: args.org, config: args.config, group, next })
+ }
+
+ async deleteGroup(args: ScimGroupByIdArgs): Promise<void> {
+ const group = await this.findGroup(args)
+ await this.repository.deleteById(group.id)
+ $logger.info(`SCIM: deleted group ${group.scimId} of SSO config ${args.config.id}`)
+ }
+
+ private async applyChanges(args: ScimApplyGroupChangesArgs): Promise<ScimGroupView> {
+ const { config, group, next } = args
+
+ const conflict = await this.repository.findConflict({ ssoConfigId: config.id, externalId: next.externalId, excludeId: group.id })
+ if (conflict) throw new ScimError({ status: 409, scimType: 'uniqueness', detail: 'Another group already has this externalId' })
+ const scimUserIds = await this.resolveMembers({ ssoConfigId: config.id, scimIds: next.members })
+ const before = new Set(await this.repository.memberIds(group.id))
+
+ const updated = await this.repository.update({ id: group.id, values: next, scimUserIds })
+ if (!updated) throw new ScimError({ status: 500, detail: 'Failed to update group' })
+
+ // Only the people who just joined: someone taken out of a linked project by hand stays out
+ const joined = scimUserIds.filter((id) => !before.has(id))
+ await this.projects.addToLinkedProjects({ orgId: args.org.id, groupIds: [group.id], scimUserIds: joined })
+
+ const [view] = await this.withMembers({ groups: [updated], excludeMembers: false })
+ return view
+ }
+
+ private async findGroup(args: ScimGroupByIdArgs): Promise<ScimGroupsSchemaTypeForSelect> {
+ const group = await this.repository.findByScimId({ ssoConfigId: args.config.id, scimId: args.scimId })
+ if (!group) throw new ScimError({ status: 404, detail: 'Group not found' })
+ return group
+ }
+
+ private async resolveMembers(args: ScimFindUsersByScimIdsArgs): Promise<number[]> {
+ const users = await this.repository.findUsersByScimIds(args)
+ const known = new Set(users.map((user) => user.scimId))
+ const unknown = args.scimIds.filter((id) => !known.has(id))
+ if (unknown.length) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `Unknown member: ${unknown[0]}` })
+ }
+ return users.map((user) => user.id)
+ }
+
+ private async withMembers(args: ScimWithMembersArgs): Promise<ScimGroupView[]> {
+ const { groups, excludeMembers } = args
+ if (excludeMembers) return groups.map((group) => ({ group, members: null }))
+ const members = await this.repository.membersOf(groups.map((group) => group.id))
+ return groups.map((group) => ({ group, members: members.filter((member) => member.groupId === group.id) }))
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimGroupsRepository.ts b/api/src/tv-modules/scim/ScimGroupsRepository.ts
new file mode 100644
index 0000000..b59bf9b
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimGroupsRepository.ts
@@ -0,0 +1,190 @@
+import { and, asc, count, eq, inArray, ne, notInArray, sql } from 'drizzle-orm'
+import {
+ ScimGroupMembersSchema,
+ ScimGroupsSchema,
+ ScimUsersSchema,
+ type ScimGroupsSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { Database } from '../../modules/db'
+import { callWithCatch } from '../../utils/helpers'
+import type {
+ ScimFindByScimIdArgs,
+ ScimFindGroupArgs,
+ ScimFindGroupConflictArgs,
+ ScimFindUsersByScimIdsArgs,
+ ScimGroupMember,
+ ScimListPageArgs,
+ ScimInsertGroupArgs,
+ ScimReplaceGroupMembersArgs,
+ ScimUpdateGroupArgs,
+ ScimUserRef,
+} from './types'
+
+export class ScimGroupsRepository {
+ private readonly db: Database
+
+ constructor() {
+ this.db = Database.getInstance()
+ }
+
+ async findByScimId(args: ScimFindByScimIdArgs): Promise<ScimGroupsSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimGroupsSchema)
+ .where(and(eq(ScimGroupsSchema.ssoConfigId, args.ssoConfigId), eq(ScimGroupsSchema.scimId, args.scimId)))
+ )
+ return rows?.[0] ?? null
+ }
+
+ // displayName is not unique, so a filter by it may match several groups
+ async findByFilter(args: ScimFindGroupArgs): Promise<ScimGroupsSchemaTypeForSelect[]> {
+ const { attribute, value } = args.filter
+ const condition = attribute === 'displayName'
+ ? sql`lower(${ScimGroupsSchema.displayName}) = lower(${value})`
+ : eq(ScimGroupsSchema.externalId, value)
+
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimGroupsSchema)
+ .where(and(eq(ScimGroupsSchema.ssoConfigId, args.ssoConfigId), condition))
+ .orderBy(asc(ScimGroupsSchema.id))
+ )
+ return rows ?? []
+ }
+
+ // Only the externalId identifies a group of the identity provider
+ async findConflict(args: ScimFindGroupConflictArgs): Promise<ScimGroupsSchemaTypeForSelect | null> {
+ const { externalId } = args
+ if (!externalId) return null
+
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimGroupsSchema)
+ .where(and(
+ eq(ScimGroupsSchema.ssoConfigId, args.ssoConfigId),
+ eq(ScimGroupsSchema.externalId, externalId),
+ ...(args.excludeId ? [ne(ScimGroupsSchema.id, args.excludeId)] : []),
+ ))
+ .limit(1)
+ )
+ return rows?.[0] ?? null
+ }
+
+ async listPage(args: ScimListPageArgs): Promise<ScimGroupsSchemaTypeForSelect[]> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimGroupsSchema)
+ .where(eq(ScimGroupsSchema.ssoConfigId, args.ssoConfigId))
+ .orderBy(asc(ScimGroupsSchema.id))
+ .offset(args.offset)
+ .limit(args.limit)
+ )
+ return rows ?? []
+ }
+
+ async countForConfig(ssoConfigId: number): Promise<number> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ total: count() })
+ .from(ScimGroupsSchema)
+ .where(eq(ScimGroupsSchema.ssoConfigId, ssoConfigId))
+ )
+ return rows?.[0]?.total ?? 0
+ }
+
+ async membersOf(groupIds: number[]): Promise<ScimGroupMember[]> {
+ if (!groupIds.length) return []
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({
+ groupId: ScimGroupMembersSchema.groupId,
+ scimId: ScimUsersSchema.scimId,
+ displayName: ScimUsersSchema.displayName,
+ userName: ScimUsersSchema.userName,
+ })
+ .from(ScimGroupMembersSchema)
+ .innerJoin(ScimUsersSchema, eq(ScimUsersSchema.id, ScimGroupMembersSchema.scimUserId))
+ .where(inArray(ScimGroupMembersSchema.groupId, groupIds))
+ .orderBy(asc(ScimUsersSchema.id))
+ )
+ return (rows ?? []).map((row) => ({ groupId: row.groupId, scimId: row.scimId, display: row.displayName ?? row.userName }))
+ }
+
+ async memberIds(groupId: number): Promise<number[]> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ scimUserId: ScimGroupMembersSchema.scimUserId })
+ .from(ScimGroupMembersSchema)
+ .where(eq(ScimGroupMembersSchema.groupId, groupId))
+ )
+ return (rows ?? []).map((row) => row.scimUserId)
+ }
+
+ async findUsersByScimIds(args: ScimFindUsersByScimIdsArgs): Promise<ScimUserRef[]> {
+ if (!args.scimIds.length) return []
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ id: ScimUsersSchema.id, scimId: ScimUsersSchema.scimId })
+ .from(ScimUsersSchema)
+ .where(and(eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId), inArray(ScimUsersSchema.scimId, args.scimIds)))
+ )
+ return rows ?? []
+ }
+
+ async insert(args: ScimInsertGroupArgs): Promise<ScimGroupsSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle.transaction(async (tx) => {
+ const [group] = await tx.insert(ScimGroupsSchema).values(args.values).returning()
+ await this.replaceMembers({ tx, groupId: group.id, scimUserIds: args.scimUserIds })
+ return [group]
+ })
+ )
+ return rows?.[0] ?? null
+ }
+
+ async update(args: ScimUpdateGroupArgs): Promise<ScimGroupsSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle.transaction(async (tx) => {
+ const updated = await tx
+ .update(ScimGroupsSchema)
+ .set({
+ displayName: args.values.displayName,
+ externalId: args.values.externalId,
+ updatedAt: new Date(),
+ })
+ .where(eq(ScimGroupsSchema.id, args.id))
+ .returning()
+ await this.replaceMembers({ tx, groupId: args.id, scimUserIds: args.scimUserIds })
+ return updated
+ })
+ )
+ return rows?.[0] ?? null
+ }
+
+ private async replaceMembers(args: ScimReplaceGroupMembersArgs) {
+ const { tx, groupId, scimUserIds } = args
+ await tx
+ .delete(ScimGroupMembersSchema)
+ .where(and(
+ eq(ScimGroupMembersSchema.groupId, groupId),
+ ...(scimUserIds.length ? [notInArray(ScimGroupMembersSchema.scimUserId, scimUserIds)] : []),
+ ))
+ if (scimUserIds.length) {
+ await tx
+ .insert(ScimGroupMembersSchema)
+ .values(scimUserIds.map((scimUserId) => ({ groupId, scimUserId })))
+ .onConflictDoNothing()
+ }
+ }
+
+ async deleteById(id: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.delete(ScimGroupsSchema).where(eq(ScimGroupsSchema.id, id))
+ )
+ return !!(result?.rowCount && result.rowCount > 0)
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimManager.ts b/api/src/tv-modules/scim/ScimManager.ts
index a14bfc8..d3c8a17 100644
--- a/api/src/tv-modules/scim/ScimManager.ts
+++ b/api/src/tv-modules/scim/ScimManager.ts
@@ -1,50 +1,231 @@
-import type { SsoConfigsSchemaTypeForSelect, OrganizationsSchemaTypeForSelect } from 'taskview-db-schemas'
+import type { ScimSuspendedMembership, ScimUsersSchemaTypeForSelect } from 'taskview-db-schemas'
+import { $logger } from '../../modules/logget'
+import { isEmail } from '../../utils/helpers'
import AuthModel from '../auth/AuthModel'
import SessionStorage from '../auth/SessionStorage'
import { OrganizationRepository } from '../organizations/OrganizationRepository'
import { SsoRepository } from '../sso/SsoRepository'
+import { ScimError } from './ScimError'
+import { ScimGroupProjectsManager } from './ScimGroupProjectsManager'
+import { ScimRepository } from './ScimRepository'
+import { applyPatchOperations, attributesOf } from './scim.helpers'
+import type {
+ ScimApplyChangesArgs,
+ ScimChangeEmailArgs,
+ ScimCreateUserArgs,
+ ScimEmailArgs,
+ ScimLinkMemberArgs,
+ ScimListUsersArgs,
+ ScimListUsersResult,
+ ScimPatchUserArgs,
+ ScimReactivateArgs,
+ ScimReplaceUserArgs,
+ ScimUserByIdArgs,
+} from './types'
export class ScimManager {
+ private readonly repository = new ScimRepository()
private readonly orgRepo = new OrganizationRepository()
private readonly ssoRepo = new SsoRepository()
private readonly authModel = new AuthModel()
private readonly sessionStorage = new SessionStorage()
+ private readonly groupProjects = new ScimGroupProjectsManager()
- async deactivateUser(
- org: OrganizationsSchemaTypeForSelect,
- config: SsoConfigsSchemaTypeForSelect,
- email: string,
- ) {
- const member = await this.orgRepo.getMemberByEmail(org.id, email)
- if (!member) return false
+ async listUsers(args: ScimListUsersArgs): Promise<ScimListUsersResult> {
+ const { config, query } = args
- const user = await this.authModel.fetchUserByEmail(email)
+ if (query.filter) {
+ const found = await this.repository.findByFilter({ ssoConfigId: config.id, filter: query.filter })
+ const user = found ?? (query.filter.attribute !== 'externalId' && isEmail(query.filter.value)
+ ? await this.linkExistingMember({ ...args, email: query.filter.value.toLowerCase(), userName: query.filter.value })
+ : null)
+ const users = user ? [user] : []
+ return { users: users.slice(query.startIndex - 1, query.startIndex - 1 + query.count), totalResults: users.length }
+ }
+
+ const [totalResults, users] = await Promise.all([
+ this.repository.countForConfig(config.id),
+ this.repository.listPage({ ssoConfigId: config.id, offset: query.startIndex - 1, limit: query.count }),
+ ])
+ return { users, totalResults }
+ }
+
+ async getUser(args: ScimUserByIdArgs): Promise<ScimUsersSchemaTypeForSelect> {
+ const user = await this.repository.findByScimId({ ssoConfigId: args.config.id, scimId: args.scimId })
+ if (!user) throw new ScimError({ status: 404, detail: 'User not found' })
+ return user
+ }
+
+ async createUser(args: ScimCreateUserArgs): Promise<ScimUsersSchemaTypeForSelect> {
+ const { org, config, attributes } = args
+ this.assertAllowedDomain({ ...args, email: attributes.email })
+
+ const conflict = await this.repository.findConflict({ ssoConfigId: config.id, attributes })
+ if (conflict) throw new ScimError({ status: 409, scimType: 'uniqueness', detail: 'User already exists' })
+
+ const member = await this.orgRepo.getMemberByEmail(org.id, attributes.email)
+ if (!member && attributes.active) {
+ const added = await this.orgRepo.addMember(org.id, attributes.email, config.defaultOrgRole)
+ if (!added) throw new ScimError({ status: 500, detail: 'Failed to add the user to the organization' })
+ }
+
+ // An existing member provisioned as inactive starts active so the usual deactivation revokes their access
+ const startsActive = attributes.active || !!member
+ const created = await this.repository.insert({
+ ssoConfigId: config.id,
+ scimId: crypto.randomUUID(),
+ userName: attributes.userName,
+ email: attributes.email,
+ memberEmail: attributes.email,
+ externalId: attributes.externalId,
+ displayName: attributes.displayName,
+ givenName: attributes.givenName,
+ familyName: attributes.familyName,
+ active: startsActive,
+ suspendedMembership: startsActive ? null : { role: config.defaultOrgRole, goals: [], suspendedAt: new Date().toISOString() },
+ })
+ if (!created) throw new ScimError({ status: 500, detail: 'Failed to create user' })
+ $logger.info(`SCIM: provisioned user ${created.scimId} in org ${org.id}`)
+
+ if (startsActive && !attributes.active) {
+ return await this.applyChanges({ org, config, user: created, next: attributes })
+ }
+ return created
+ }
+
+ async replaceUser(args: ScimReplaceUserArgs): Promise<ScimUsersSchemaTypeForSelect> {
+ const user = await this.getUser(args)
+ return await this.applyChanges({ org: args.org, config: args.config, user, next: args.attributes })
+ }
+
+ async patchUser(args: ScimPatchUserArgs): Promise<ScimUsersSchemaTypeForSelect> {
+ const user = await this.getUser(args)
+ const next = applyPatchOperations({ current: attributesOf(user), operations: args.operations })
+ return await this.applyChanges({ org: args.org, config: args.config, user, next })
+ }
+
+ async deleteUser(args: ScimUserByIdArgs): Promise<void> {
+ const user = await this.getUser(args)
+ if (user.active) await this.revokeAccess({ org: args.org, config: args.config, email: user.memberEmail })
+ await this.repository.deleteById(user.id)
+ $logger.info(`SCIM: deleted user ${user.scimId} from org ${args.org.id}`)
+ }
+
+ private async applyChanges(args: ScimApplyChangesArgs): Promise<ScimUsersSchemaTypeForSelect> {
+ const { org, config, user, next } = args
+
+ const identityChanged = next.userName.toLowerCase() !== user.userName.toLowerCase()
+ || next.email !== user.email
+ || next.externalId !== user.externalId
+ if (identityChanged) {
+ const conflict = await this.repository.findConflict({ ssoConfigId: config.id, attributes: next, excludeId: user.id })
+ if (conflict) throw new ScimError({ status: 409, scimType: 'uniqueness', detail: 'Another user already has this userName, email or externalId' })
+ }
+
+ if (user.active && !next.active) await this.assertNotOwner({ org, config, email: user.memberEmail })
+ let memberEmail = user.memberEmail
+ if (next.email !== user.email) {
+ this.assertAllowedDomain({ org, config, email: next.email })
+ memberEmail = await this.changeEmail({ org, config, memberEmail, email: next.email, active: user.active })
+ }
+
+ let suspendedMembership = user.suspendedMembership
+ if (user.active && !next.active) {
+ suspendedMembership = await this.revokeAccess({ org, config, email: memberEmail })
+ $logger.info(`SCIM: deactivated user ${user.scimId} in org ${org.id}`)
+ } else if (!user.active && next.active) {
+ await this.reactivate({ org, config, email: memberEmail, suspended: user.suspendedMembership })
+ suspendedMembership = null
+ $logger.info(`SCIM: reactivated user ${user.scimId} in org ${org.id}`)
+ }
+
+ const updated = await this.repository.update({ id: user.id, values: { ...next, memberEmail, suspendedMembership } })
+ if (!updated) throw new ScimError({ status: 500, detail: 'Failed to update user' })
+
+ if (!user.active && next.active) {
+ const suspendedAt = user.suspendedMembership?.suspendedAt
+ await this.groupProjects.addToLinkedProjects({
+ orgId: org.id,
+ scimUserIds: [user.id],
+ since: suspendedAt ? new Date(suspendedAt) : user.updatedAt,
+ })
+ }
+ return updated
+ }
+
+ private isAllowedDomain(args: ScimEmailArgs): boolean {
+ return args.email.split('@')[1] === args.config.emailDomainRestriction.toLowerCase()
+ }
+
+ private assertAllowedDomain(args: ScimEmailArgs) {
+ if (!this.isAllowedDomain(args)) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `Email domain must be ${args.config.emailDomainRestriction.toLowerCase()}` })
+ }
+ }
+
+ // Returns the address the person holds in this organization after the change
+ private async changeEmail(args: ScimChangeEmailArgs): Promise<string> {
+ // An account renames itself everywhere at its next SSO sign-in, where the IdP identity is proven.
+ // Renaming here too would leave two rows for the new address and block that sign-in.
+ const account = await this.authModel.getUserByLogin(args.memberEmail, true)
+ if (account) return args.memberEmail
+ if (!args.active) return args.email
+
+ // Nobody has signed in with the old address yet: only this organization's invitation moves
+ const moved = await this.repository.moveOrgMembership({ orgId: args.org.id, oldEmail: args.memberEmail, email: args.email })
+ if (!moved) {
+ throw new ScimError({ status: 409, scimType: 'uniqueness', detail: 'This email is already used in the organization' })
+ }
+ return args.email
+ }
+
+ private async assertNotOwner(args: ScimEmailArgs) {
+ const account = await this.authModel.getUserByLogin(args.email, true)
+ if (account && account.id === args.org.ownerId) {
+ throw new ScimError({ status: 400, scimType: 'mutability', detail: 'The organization owner cannot be deactivated over SCIM' })
+ }
+ }
+
+ private async revokeAccess(args: ScimEmailArgs): Promise<ScimSuspendedMembership> {
+ const { org, config, email } = args
+ await this.assertNotOwner(args)
+ const account = await this.authModel.getUserByLogin(email, true)
+
+ const snapshot = await this.repository.snapshotMembership({ orgId: org.id, email })
await this.orgRepo.removeMember(org.id, email)
await this.orgRepo.removeUserFromOrgGoals(org.id, email)
- if (user) {
- await this.ssoRepo.deleteIdentityByUser(user.id, config.id)
- await this.sessionStorage.deleteAllSessions(user.id)
+ if (account) {
+ await this.ssoRepo.deleteIdentityByUser(account.id, config.id)
+ await this.sessionStorage.deleteAllSessions(account.id)
}
- return true
+ return { ...(snapshot ?? { role: config.defaultOrgRole, goals: [] }), suspendedAt: new Date().toISOString() }
}
- async reactivateUser(
- org: OrganizationsSchemaTypeForSelect,
- email: string,
- role: string = 'member',
- ) {
- await this.orgRepo.addMember(org.id, email, role)
- return true
+ private async reactivate(args: ScimReactivateArgs) {
+ const { org, config, email, suspended } = args
+ await this.orgRepo.addMember(org.id, email, suspended?.role ?? config.defaultOrgRole)
+ const restored = await this.repository.restoreGoals({ orgId: org.id, email, goals: suspended?.goals ?? [] })
+ if (!restored) $logger.error(`SCIM: failed to restore project access in org ${org.id}`)
}
- async listUsers(orgId: number) {
- return await this.orgRepo.fetchMembers(orgId)
- }
+ private async linkExistingMember(args: ScimLinkMemberArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ if (!this.isAllowedDomain(args)) return null
+ const member = await this.orgRepo.getMemberByEmail(args.org.id, args.email)
+ if (!member) return null
+
+ // The email already belongs to a provisioned user with another userName: no match for this one
+ const byEmail = await this.repository.findByFilter({ ssoConfigId: args.config.id, filter: { attribute: 'email', value: args.email } })
+ if (byEmail) return null
- async getUserByEmail(orgId: number, email: string) {
- return await this.orgRepo.getMemberByEmail(orgId, email)
+ return await this.repository.insert({
+ ssoConfigId: args.config.id,
+ scimId: args.email,
+ userName: args.userName,
+ email: args.email,
+ memberEmail: args.email,
+ })
}
}
diff --git a/api/src/tv-modules/scim/ScimRepository.ts b/api/src/tv-modules/scim/ScimRepository.ts
new file mode 100644
index 0000000..8ca62d2
--- /dev/null
+++ b/api/src/tv-modules/scim/ScimRepository.ts
@@ -0,0 +1,307 @@
+import { and, asc, count, eq, inArray, ne, or, sql } from 'drizzle-orm'
+import {
+ CollaborationRolesSchema,
+ CollaborationUsersSchema,
+ CollaborationUsersToGoalsSchema,
+ CollaborationUsersToRolesSchema,
+ GoalsSchema,
+ OrganizationMembersSchema,
+ ScimUsersSchema,
+ type ScimSuspendedMembership,
+ type ScimUsersSchemaTypeForInsert,
+ type ScimUsersSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { Database } from '../../modules/db'
+import { callWithCatch } from '../../utils/helpers'
+import type {
+ ScimFindByFilterArgs,
+ ScimFindByScimIdArgs,
+ ScimFindConflictArgs,
+ ScimFindForSignInArgs,
+ ScimListPageArgs,
+ ScimMembershipArgs,
+ ScimMoveMembershipArgs,
+ ScimRestoreMembershipArgs,
+ ScimUpdateUserArgs,
+} from './types'
+
+export class ScimRepository {
+ private readonly db: Database
+
+ constructor() {
+ this.db = Database.getInstance()
+ }
+
+ async findByScimId(args: ScimFindByScimIdArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimUsersSchema)
+ .where(and(eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId), eq(ScimUsersSchema.scimId, args.scimId)))
+ )
+ return rows?.[0] ?? null
+ }
+
+ async findForSignIn(args: ScimFindForSignInArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimUsersSchema)
+ .where(and(
+ eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId),
+ or(inArray(ScimUsersSchema.email, args.emails), inArray(ScimUsersSchema.memberEmail, args.emails)),
+ ))
+ .orderBy(asc(ScimUsersSchema.id))
+ )
+ return rows?.[0] ?? null
+ }
+
+ async findByFilter(args: ScimFindByFilterArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const { attribute, value } = args.filter
+ const condition = attribute === 'userName'
+ ? sql`lower(${ScimUsersSchema.userName}) = lower(${value})`
+ : attribute === 'externalId'
+ ? eq(ScimUsersSchema.externalId, value)
+ : eq(ScimUsersSchema.email, value)
+
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimUsersSchema)
+ .where(and(eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId), condition))
+ )
+ return rows?.[0] ?? null
+ }
+
+ async findConflict(args: ScimFindConflictArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const { userName, email, externalId } = args.attributes
+ const sameIdentity = or(
+ sql`lower(${ScimUsersSchema.userName}) = lower(${userName})`,
+ eq(ScimUsersSchema.email, email),
+ ...(externalId ? [eq(ScimUsersSchema.externalId, externalId)] : []),
+ )
+
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimUsersSchema)
+ .where(and(
+ eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId),
+ sameIdentity,
+ ...(args.excludeId ? [ne(ScimUsersSchema.id, args.excludeId)] : []),
+ ))
+ .limit(1)
+ )
+ return rows?.[0] ?? null
+ }
+
+ async listPage(args: ScimListPageArgs): Promise<ScimUsersSchemaTypeForSelect[]> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(ScimUsersSchema)
+ .where(eq(ScimUsersSchema.ssoConfigId, args.ssoConfigId))
+ .orderBy(asc(ScimUsersSchema.id))
+ .offset(args.offset)
+ .limit(args.limit)
+ )
+ return rows ?? []
+ }
+
+ async countForConfig(ssoConfigId: number): Promise<number> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select({ total: count() })
+ .from(ScimUsersSchema)
+ .where(eq(ScimUsersSchema.ssoConfigId, ssoConfigId))
+ )
+ return rows?.[0]?.total ?? 0
+ }
+
+ async insert(values: ScimUsersSchemaTypeForInsert): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle.insert(ScimUsersSchema).values(values).returning()
+ )
+ return rows?.[0] ?? null
+ }
+
+ async update(args: ScimUpdateUserArgs): Promise<ScimUsersSchemaTypeForSelect | null> {
+ const { values } = args
+ const rows = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .update(ScimUsersSchema)
+ .set({
+ userName: values.userName,
+ email: values.email,
+ memberEmail: values.memberEmail,
+ externalId: values.externalId,
+ displayName: values.displayName,
+ givenName: values.givenName,
+ familyName: values.familyName,
+ active: values.active,
+ suspendedMembership: values.suspendedMembership,
+ updatedAt: new Date(),
+ })
+ .where(eq(ScimUsersSchema.id, args.id))
+ .returning()
+ )
+ return rows?.[0] ?? null
+ }
+
+ async deleteById(id: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.delete(ScimUsersSchema).where(eq(ScimUsersSchema.id, id))
+ )
+ return !!result?.rowCount
+ }
+
+ async snapshotMembership(args: ScimMembershipArgs): Promise<ScimSuspendedMembership | null> {
+ return await callWithCatch(async () => {
+ const [member] = await this.db.dbDrizzle
+ .select({ role: OrganizationMembersSchema.role })
+ .from(OrganizationMembersSchema)
+ .where(and(eq(OrganizationMembersSchema.organizationId, args.orgId), eq(OrganizationMembersSchema.email, args.email)))
+ if (!member) return null
+
+ const goals = await this.db.dbDrizzle
+ .select({ goalId: CollaborationUsersToGoalsSchema.goalId, collabUserId: CollaborationUsersSchema.id })
+ .from(CollaborationUsersToGoalsSchema)
+ .innerJoin(CollaborationUsersSchema, eq(CollaborationUsersSchema.id, CollaborationUsersToGoalsSchema.userId))
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, CollaborationUsersToGoalsSchema.goalId))
+ .where(and(eq(GoalsSchema.organizationId, args.orgId), sql`lower(${CollaborationUsersSchema.email}) = ${args.email}`))
+
+ const goalIds = goals.map((g) => g.goalId)
+ const roles = goalIds.length
+ ? await this.db.dbDrizzle
+ .select({ goalId: CollaborationRolesSchema.goalId, roleId: CollaborationRolesSchema.id })
+ .from(CollaborationUsersToRolesSchema)
+ .innerJoin(CollaborationRolesSchema, eq(CollaborationRolesSchema.id, CollaborationUsersToRolesSchema.roleId))
+ .where(and(
+ inArray(CollaborationUsersToRolesSchema.userId, goals.map((g) => g.collabUserId)),
+ inArray(CollaborationRolesSchema.goalId, goalIds),
+ ))
+ : []
+
+ return {
+ role: member.role,
+ goals: goalIds.map((goalId) => ({
+ goalId,
+ roleIds: roles.filter((r) => r.goalId === goalId).map((r) => r.roleId),
+ })),
+ }
+ })
+ }
+
+ async restoreGoals(args: ScimRestoreMembershipArgs): Promise<boolean> {
+ if (!args.goals.length) return true
+
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.transaction(async (tx) => {
+ const goals = await tx
+ .select({ id: GoalsSchema.id })
+ .from(GoalsSchema)
+ .where(and(inArray(GoalsSchema.id, args.goals.map((g) => g.goalId)), eq(GoalsSchema.organizationId, args.orgId)))
+ const liveGoalIds = new Set(goals.map((g) => g.id))
+ if (!liveGoalIds.size) return true
+
+ const [existing] = await tx
+ .select({ id: CollaborationUsersSchema.id })
+ .from(CollaborationUsersSchema)
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${args.email}`)
+ const collabUserId = existing?.id
+ ?? (await tx.insert(CollaborationUsersSchema).values({ email: args.email }).returning({ id: CollaborationUsersSchema.id }))[0].id
+
+ await tx
+ .insert(CollaborationUsersToGoalsSchema)
+ .values([...liveGoalIds].map((goalId) => ({ userId: collabUserId, goalId })))
+ .onConflictDoNothing()
+
+ const wantedRoleIds = args.goals.filter((g) => liveGoalIds.has(g.goalId)).flatMap((g) => g.roleIds)
+ if (!wantedRoleIds.length) return true
+
+ const liveRoles = await tx
+ .select({ id: CollaborationRolesSchema.id })
+ .from(CollaborationRolesSchema)
+ .where(and(inArray(CollaborationRolesSchema.id, wantedRoleIds), inArray(CollaborationRolesSchema.goalId, [...liveGoalIds])))
+ const linked = await tx
+ .select({ roleId: CollaborationUsersToRolesSchema.roleId })
+ .from(CollaborationUsersToRolesSchema)
+ .where(eq(CollaborationUsersToRolesSchema.userId, collabUserId))
+ const linkedIds = new Set(linked.map((l) => l.roleId))
+ const missing = liveRoles.map((r) => r.id).filter((id) => !linkedIds.has(id))
+
+ if (missing.length) {
+ await tx.insert(CollaborationUsersToRolesSchema).values(missing.map((roleId) => ({ userId: collabUserId, roleId })))
+ }
+ return true
+ })
+ )
+ return result === true
+ }
+
+ async moveOrgMembership(args: ScimMoveMembershipArgs): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.transaction(async (tx) => {
+ await tx
+ .update(OrganizationMembersSchema)
+ .set({ email: args.email })
+ .where(and(eq(OrganizationMembersSchema.organizationId, args.orgId), eq(OrganizationMembersSchema.email, args.oldEmail)))
+
+ // collaboration.users is one row per email for the whole instance: only this
+ // organization's project links and roles move to the new address, the shared row stays
+ const [oldUser] = await tx
+ .select({ id: CollaborationUsersSchema.id })
+ .from(CollaborationUsersSchema)
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${args.oldEmail}`)
+ if (!oldUser) return true
+
+ const links = await tx
+ .select({ goalId: CollaborationUsersToGoalsSchema.goalId })
+ .from(CollaborationUsersToGoalsSchema)
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, CollaborationUsersToGoalsSchema.goalId))
+ .where(and(eq(CollaborationUsersToGoalsSchema.userId, oldUser.id), eq(GoalsSchema.organizationId, args.orgId)))
+ const goalIds = links.map((l) => l.goalId)
+ if (!goalIds.length) return true
+
+ const [existing] = await tx
+ .select({ id: CollaborationUsersSchema.id })
+ .from(CollaborationUsersSchema)
+ .where(sql`lower(${CollaborationUsersSchema.email}) = ${args.email}`)
+ const newUserId = existing?.id
+ ?? (await tx.insert(CollaborationUsersSchema).values({ email: args.email }).returning({ id: CollaborationUsersSchema.id }))[0].id
+
+ await tx
+ .insert(CollaborationUsersToGoalsSchema)
+ .values(goalIds.map((goalId) => ({ userId: newUserId, goalId })))
+ .onConflictDoNothing()
+
+ const roles = await tx
+ .select({ roleId: CollaborationUsersToRolesSchema.roleId })
+ .from(CollaborationUsersToRolesSchema)
+ .innerJoin(CollaborationRolesSchema, eq(CollaborationRolesSchema.id, CollaborationUsersToRolesSchema.roleId))
+ .where(and(eq(CollaborationUsersToRolesSchema.userId, oldUser.id), inArray(CollaborationRolesSchema.goalId, goalIds)))
+ const roleIds = roles.map((r) => r.roleId)
+ if (roleIds.length) {
+ const already = await tx
+ .select({ roleId: CollaborationUsersToRolesSchema.roleId })
+ .from(CollaborationUsersToRolesSchema)
+ .where(and(eq(CollaborationUsersToRolesSchema.userId, newUserId), inArray(CollaborationUsersToRolesSchema.roleId, roleIds)))
+ const alreadyIds = new Set(already.map((r) => r.roleId))
+ const missing = roleIds.filter((id) => !alreadyIds.has(id))
+ if (missing.length) {
+ await tx.insert(CollaborationUsersToRolesSchema).values(missing.map((roleId) => ({ userId: newUserId, roleId })))
+ }
+ await tx
+ .delete(CollaborationUsersToRolesSchema)
+ .where(and(eq(CollaborationUsersToRolesSchema.userId, oldUser.id), inArray(CollaborationUsersToRolesSchema.roleId, roleIds)))
+ }
+
+ await tx
+ .delete(CollaborationUsersToGoalsSchema)
+ .where(and(eq(CollaborationUsersToGoalsSchema.userId, oldUser.id), inArray(CollaborationUsersToGoalsSchema.goalId, goalIds)))
+ return true
+ })
+ )
+ return result === true
+ }
+}
diff --git a/api/src/tv-modules/scim/ScimRoutes.ts b/api/src/tv-modules/scim/ScimRoutes.ts
index abb3773..b96fc1e 100644
--- a/api/src/tv-modules/scim/ScimRoutes.ts
+++ b/api/src/tv-modules/scim/ScimRoutes.ts
@@ -22,10 +22,26 @@ export default class ScimRoutes implements Routable {
this.router.use(ScimContentType)
this.router.use(ScimAuth)
+ this.router.get('/ServiceProviderConfig', this.controller.serviceProviderConfig)
+ this.router.get('/ResourceTypes', this.controller.resourceTypes)
+ this.router.get('/ResourceTypes/:id', this.controller.resourceType)
+ this.router.get('/Schemas', this.controller.schemas)
+ this.router.get('/Schemas/:id', this.controller.schema)
+
this.router.get('/Users', this.controller.listUsers)
this.router.get('/Users/:id', this.controller.getUser)
this.router.post('/Users', this.controller.createUser)
+ this.router.put('/Users/:id', this.controller.replaceUser)
this.router.patch('/Users/:id', this.controller.patchUser)
this.router.delete('/Users/:id', this.controller.deleteUser)
+
+ this.router.get('/Groups', this.controller.listGroups)
+ this.router.get('/Groups/:id', this.controller.getGroup)
+ this.router.post('/Groups', this.controller.createGroup)
+ this.router.put('/Groups/:id', this.controller.replaceGroup)
+ this.router.patch('/Groups/:id', this.controller.patchGroup)
+ this.router.delete('/Groups/:id', this.controller.deleteGroup)
+
+ this.router.use(this.controller.notFound)
}
}
diff --git a/api/src/tv-modules/scim/__tests__/ScimEmailChange.integration.spec.ts b/api/src/tv-modules/scim/__tests__/ScimEmailChange.integration.spec.ts
new file mode 100644
index 0000000..b7a07da
--- /dev/null
+++ b/api/src/tv-modules/scim/__tests__/ScimEmailChange.integration.spec.ts
@@ -0,0 +1,177 @@
+import fs from 'fs/promises'
+import { and, eq, inArray, sql } from 'drizzle-orm'
+import { join } from 'path'
+import {
+ CollaborationUsersSchema,
+ CollaborationUsersToGoalsSchema,
+ GoalsSchema,
+ OrganizationMembersSchema,
+ OrganizationsSchema,
+ ScimUsersSchema,
+ SsoConfigsSchema,
+ UsersSchema,
+ type OrganizationsSchemaTypeForSelect,
+ type SsoConfigsSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { Database } from '../../../modules/db'
+import AuthModel from '../../auth/AuthModel'
+import { ScimManager } from '../ScimManager'
+import type { ScimUserAttributes } from '../types'
+
+const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.70.0')
+const run = `${Date.now() % 1e8}${Math.floor(Math.random() * 100)}`
+const DOMAIN = `sm${run}.example`
+let seq = 0
+
+const db = () => Database.getInstance().dbDrizzle
+const manager = new ScimManager()
+const authModel = new AuthModel()
+
+let ownerId = 0
+let org: OrganizationsSchemaTypeForSelect
+let otherOrg: OrganizationsSchemaTypeForSelect
+let config: SsoConfigsSchemaTypeForSelect
+const userIds: number[] = []
+
+async function createAccount(email: string): Promise<number> {
+ const [user] = await db()
+ .insert(UsersSchema)
+ .values({ login: `scim-${run}-${seq++}`, email, password: 'not-used' })
+ .returning({ id: UsersSchema.id })
+ userIds.push(user.id)
+ return user.id
+}
+
+async function createOrg(name: string): Promise<OrganizationsSchemaTypeForSelect> {
+ const [created] = await db()
+ .insert(OrganizationsSchema)
+ .values({ name, slug: `${name}-${run}`, ownerId })
+ .returning()
+ return created
+}
+
+async function inviteToNewGoal(organizationId: number, email: string): Promise<number> {
+ const [goal] = await db()
+ .insert(GoalsSchema)
+ .values({ name: `goal-${run}`, owner: ownerId, organizationId })
+ .returning({ id: GoalsSchema.id })
+ const [existing] = await db()
+ .select({ id: CollaborationUsersSchema.id })
+ .from(CollaborationUsersSchema)
+ .where(eq(CollaborationUsersSchema.email, email))
+ const collabId = existing?.id
+ ?? (await db().insert(CollaborationUsersSchema).values({ email }).returning({ id: CollaborationUsersSchema.id }))[0].id
+ await db().insert(CollaborationUsersToGoalsSchema).values({ userId: collabId, goalId: goal.id })
+ return goal.id
+}
+
+async function goalEmails(goalId: number): Promise<string[]> {
+ const rows = await db()
+ .select({ email: CollaborationUsersSchema.email })
+ .from(CollaborationUsersToGoalsSchema)
+ .innerJoin(CollaborationUsersSchema, eq(CollaborationUsersSchema.id, CollaborationUsersToGoalsSchema.userId))
+ .where(eq(CollaborationUsersToGoalsSchema.goalId, goalId))
+ // The project owner is a collaborator too: only the provisioned people matter here
+ return rows.map((r) => r.email).filter((email) => email.endsWith(`@${DOMAIN}`))
+}
+
+async function memberEmails(organizationId: number): Promise<string[]> {
+ const rows = await db()
+ .select({ email: OrganizationMembersSchema.email })
+ .from(OrganizationMembersSchema)
+ .where(eq(OrganizationMembersSchema.organizationId, organizationId))
+ return rows.map((r) => r.email).filter((email) => email.endsWith(`@${DOMAIN}`))
+}
+
+const attributesFor = (email: string): ScimUserAttributes => ({
+ userName: email,
+ email,
+ externalId: null,
+ displayName: null,
+ givenName: null,
+ familyName: null,
+ active: true,
+})
+
+const changeEmailOp = (email: string) => [{ op: 'replace', path: 'emails[type eq "work"].value', value: email }]
+
+describe('SCIM email change of a person who already has an account', () => {
+ beforeAll(async () => {
+ const client = await Database.getInstance().getClient()
+ // Integration specs run in parallel and re-apply migration SQL; an advisory lock keeps the DDL from racing.
+ await client.query('SELECT pg_advisory_lock(1401070)')
+ try {
+ await client.query(await fs.readFile(join(MIGRATION_DIR, '0.create-scim-users.sql'), 'utf8'))
+ } finally {
+ await client.query('SELECT pg_advisory_unlock(1401070)')
+ client.release()
+ }
+
+ ownerId = await createAccount(`owner-${run}@owner.example`)
+ org = await createOrg('scim-move')
+ otherOrg = await createOrg('scim-move-other')
+ const [created] = await db()
+ .insert(SsoConfigsSchema)
+ .values({ organizationId: org.id, protocol: 'saml', displayName: 'scim-move', emailDomainRestriction: DOMAIN })
+ .returning()
+ config = created
+ })
+
+ afterAll(async () => {
+ const emails = sql`${CollaborationUsersSchema.email} like ${`%@${DOMAIN}`}`
+ await db().delete(CollaborationUsersSchema).where(emails)
+ await db().delete(OrganizationsSchema).where(inArray(OrganizationsSchema.id, [org.id, otherOrg.id]))
+ await db().delete(UsersSchema).where(inArray(UsersSchema.id, userIds))
+ })
+
+ it('leaves renaming to the next sign-in, which then succeeds, and deactivation keeps working', async () => {
+ const email = `person-${run}@${DOMAIN}`
+ const renamed = `renamed-${run}@${DOMAIN}`
+ const accountId = await createAccount(email)
+ await db().insert(OrganizationMembersSchema).values({ organizationId: otherOrg.id, email, role: 'member' })
+ const ownGoal = await inviteToNewGoal(org.id, email)
+ const foreignGoal = await inviteToNewGoal(otherOrg.id, email)
+
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ await manager.patchUser({ org, config, scimId: user.scimId, operations: changeEmailOp(renamed) })
+
+ expect(await memberEmails(org.id)).toEqual([email])
+ expect(await goalEmails(ownGoal)).toEqual([email])
+ const [stored] = await db().select().from(ScimUsersSchema).where(eq(ScimUsersSchema.id, user.id))
+ expect(stored.email).toBe(renamed)
+ expect(stored.memberEmail).toBe(email)
+
+ // The SSO sign-in with the new address renames the account everywhere
+ const result = await authModel.updateUserEmail({ userId: accountId, oldEmail: email, email: renamed })
+ expect(result).toBe('ok')
+ expect(await memberEmails(org.id)).toEqual([renamed])
+ expect(await memberEmails(otherOrg.id)).toEqual([renamed])
+ expect(await goalEmails(ownGoal)).toEqual([renamed])
+ expect(await goalEmails(foreignGoal)).toEqual([renamed])
+ const [synced] = await db().select().from(ScimUsersSchema).where(eq(ScimUsersSchema.id, user.id))
+ expect(synced.memberEmail).toBe(renamed)
+
+ await manager.patchUser({ org, config, scimId: user.scimId, operations: [{ op: 'replace', path: 'active', value: false }] })
+ expect(await memberEmails(org.id)).toEqual([])
+ expect(await goalEmails(ownGoal)).toEqual([])
+ expect(await goalEmails(foreignGoal)).toEqual([renamed])
+ })
+
+ it('deactivates by the address the person still holds before their next sign-in', async () => {
+ const email = `waiting-${run}@${DOMAIN}`
+ await createAccount(email)
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ await manager.patchUser({ org, config, scimId: user.scimId, operations: changeEmailOp(`waiting-new-${run}@${DOMAIN}`) })
+
+ await manager.patchUser({ org, config, scimId: user.scimId, operations: [{ op: 'replace', path: 'active', value: false }] })
+ const members = await db()
+ .select()
+ .from(OrganizationMembersSchema)
+ .where(and(eq(OrganizationMembersSchema.organizationId, org.id), eq(OrganizationMembersSchema.email, email)))
+ expect(members).toEqual([])
+
+ await manager.patchUser({ org, config, scimId: user.scimId, operations: [{ op: 'replace', path: 'active', value: true }] })
+ expect(await memberEmails(org.id)).toContain(email)
+ })
+})
diff --git a/api/src/tv-modules/scim/middlewares/ScimAuth.ts b/api/src/tv-modules/scim/middlewares/ScimAuth.ts
index 3380eeb..6fe2974 100644
--- a/api/src/tv-modules/scim/middlewares/ScimAuth.ts
+++ b/api/src/tv-modules/scim/middlewares/ScimAuth.ts
@@ -1,6 +1,7 @@
import { createHash } from 'crypto'
import type { NextFunction, Request, Response } from 'express'
import { SsoRepository } from '../../sso/SsoRepository'
+import { isSsoDomainVerified } from '../../sso/sso.utils'
import { OrganizationRepository } from '../../organizations/OrganizationRepository'
const ssoRepo = new SsoRepository()
@@ -28,6 +29,14 @@ export const ScimAuth = async (req: Request, res: Response, next: NextFunction)
})
}
+ if (!isSsoDomainVerified(config)) {
+ return res.status(403).json({
+ schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
+ detail: 'Verify the SSO email domain before using SCIM provisioning',
+ status: '403',
+ })
+ }
+
const org = await orgRepo.findById(config.organizationId)
if (!org) {
return res.status(401).json({
diff --git a/api/src/tv-modules/scim/middlewares/ScimBodyErrorHandler.ts b/api/src/tv-modules/scim/middlewares/ScimBodyErrorHandler.ts
new file mode 100644
index 0000000..f99dd78
--- /dev/null
+++ b/api/src/tv-modules/scim/middlewares/ScimBodyErrorHandler.ts
@@ -0,0 +1,14 @@
+import type { NextFunction, Request, Response } from 'express'
+import { toScimError } from '../scim.helpers'
+
+export const ScimBodyErrorHandler = (err: { type?: string; status?: number }, _req: Request, res: Response, next: NextFunction) => {
+ if (res.headersSent) return next(err)
+
+ if (err.type === 'entity.parse.failed') {
+ return res.status(400).type('application/scim+json').json(toScimError({ status: 400, scimType: 'invalidSyntax', detail: 'Malformed JSON body' }))
+ }
+ if (err.type === 'entity.too.large') {
+ return res.status(413).type('application/scim+json').json(toScimError({ status: 413, detail: 'Request body is too large' }))
+ }
+ return next(err)
+}
diff --git a/api/src/tv-modules/scim/scim.discovery.ts b/api/src/tv-modules/scim/scim.discovery.ts
new file mode 100644
index 0000000..6879a1b
--- /dev/null
+++ b/api/src/tv-modules/scim/scim.discovery.ts
@@ -0,0 +1,126 @@
+import { SCIM_GROUP_SCHEMA } from './scim.groups.helpers'
+import { SCIM_MAX_PAGE_SIZE, SCIM_USER_SCHEMA } from './scim.helpers'
+import type { ScimSchemaAttributeArgs } from './types'
+
+const SPC_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig'
+const RESOURCE_TYPE_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:ResourceType'
+const SCHEMA_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:Schema'
+
+export function scimServiceProviderConfig(baseUrl: string) {
+ return {
+ schemas: [SPC_SCHEMA],
+ patch: { supported: true },
+ bulk: { supported: false, maxOperations: 0, maxPayloadSize: 0 },
+ filter: { supported: true, maxResults: SCIM_MAX_PAGE_SIZE },
+ changePassword: { supported: false },
+ sort: { supported: false },
+ etag: { supported: false },
+ authenticationSchemes: [{
+ type: 'oauthbearertoken',
+ name: 'OAuth Bearer Token',
+ description: 'SCIM token generated in the organization SSO settings',
+ primary: true,
+ }],
+ meta: { resourceType: 'ServiceProviderConfig', location: `${baseUrl}/ServiceProviderConfig` },
+ }
+}
+
+export function scimUserResourceType(baseUrl: string) {
+ return {
+ schemas: [RESOURCE_TYPE_SCHEMA],
+ id: 'User',
+ name: 'User',
+ endpoint: '/Users',
+ description: 'Organization member',
+ schema: SCIM_USER_SCHEMA,
+ meta: { resourceType: 'ResourceType', location: `${baseUrl}/ResourceTypes/User` },
+ }
+}
+
+export function scimGroupResourceType(baseUrl: string) {
+ return {
+ schemas: [RESOURCE_TYPE_SCHEMA],
+ id: 'Group',
+ name: 'Group',
+ endpoint: '/Groups',
+ description: 'Group of organization members, owned by the identity provider',
+ schema: SCIM_GROUP_SCHEMA,
+ meta: { resourceType: 'ResourceType', location: `${baseUrl}/ResourceTypes/Group` },
+ }
+}
+
+const stringAttribute = (args: ScimSchemaAttributeArgs) => ({
+ type: 'string',
+ multiValued: false,
+ required: false,
+ caseExact: false,
+ mutability: 'readWrite',
+ returned: 'default',
+ uniqueness: 'none',
+ ...args,
+})
+
+export function scimUserSchema(baseUrl: string) {
+ return {
+ schemas: [SCHEMA_SCHEMA],
+ id: SCIM_USER_SCHEMA,
+ name: 'User',
+ description: 'Organization member',
+ attributes: [
+ stringAttribute({ name: 'userName', required: true, uniqueness: 'server' }),
+ stringAttribute({ name: 'externalId', caseExact: true }),
+ {
+ name: 'name',
+ type: 'complex',
+ multiValued: false,
+ required: false,
+ mutability: 'readWrite',
+ returned: 'default',
+ subAttributes: [stringAttribute({ name: 'givenName' }), stringAttribute({ name: 'familyName' })],
+ },
+ stringAttribute({ name: 'displayName' }),
+ {
+ name: 'emails',
+ type: 'complex',
+ multiValued: true,
+ required: true,
+ mutability: 'readWrite',
+ returned: 'default',
+ subAttributes: [
+ stringAttribute({ name: 'value', required: true }),
+ stringAttribute({ name: 'type', canonicalValues: ['work'] }),
+ { name: 'primary', type: 'boolean', multiValued: false, required: false, mutability: 'readWrite', returned: 'default' },
+ ],
+ },
+ { name: 'active', type: 'boolean', multiValued: false, required: false, mutability: 'readWrite', returned: 'default' },
+ ],
+ meta: { resourceType: 'Schema', location: `${baseUrl}/Schemas/${SCIM_USER_SCHEMA}` },
+ }
+}
+
+export function scimGroupSchema(baseUrl: string) {
+ return {
+ schemas: [SCHEMA_SCHEMA],
+ id: SCIM_GROUP_SCHEMA,
+ name: 'Group',
+ description: 'Group of organization members, owned by the identity provider',
+ attributes: [
+ stringAttribute({ name: 'displayName', required: true }),
+ stringAttribute({ name: 'externalId', caseExact: true }),
+ {
+ name: 'members',
+ type: 'complex',
+ multiValued: true,
+ required: false,
+ mutability: 'readWrite',
+ returned: 'default',
+ subAttributes: [
+ stringAttribute({ name: 'value', required: true, mutability: 'immutable' }),
+ stringAttribute({ name: 'display', mutability: 'readOnly' }),
+ { name: '$ref', type: 'reference', referenceTypes: ['User'], multiValued: false, required: false, mutability: 'immutable', returned: 'default' },
+ ],
+ },
+ ],
+ meta: { resourceType: 'Schema', location: `${baseUrl}/Schemas/${SCIM_GROUP_SCHEMA}` },
+ }
+}
diff --git a/api/src/tv-modules/scim/scim.groups.helpers.ts b/api/src/tv-modules/scim/scim.groups.helpers.ts
new file mode 100644
index 0000000..8a5226d
--- /dev/null
+++ b/api/src/tv-modules/scim/scim.groups.helpers.ts
@@ -0,0 +1,133 @@
+import { ScimError } from './ScimError'
+import { matchScimFilter, optionalString, parsePage, requiredString } from './scim.helpers'
+import type {
+ ScimApplyGroupPatchArgs,
+ ScimApplyGroupPatchValueArgs,
+ ScimGroupAttributes,
+ ScimGroupBody,
+ ScimGroupFilter,
+ ScimGroupListQuery,
+ ScimGroupResourceArgs,
+} from './types'
+
+export const SCIM_GROUP_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:Group'
+
+const MEMBER_FILTER_PATH = /^members\[value eq "([^"]*)"\]$/i
+
+export function toScimGroup(args: ScimGroupResourceArgs) {
+ const { view, baseUrl } = args
+ const { group, members } = view
+
+ return {
+ schemas: [SCIM_GROUP_SCHEMA],
+ id: group.scimId,
+ ...(group.externalId ? { externalId: group.externalId } : {}),
+ displayName: group.displayName,
+ ...(members
+ ? {
+ members: members.map((member) => ({
+ value: member.scimId,
+ display: member.display,
+ $ref: `${baseUrl}/Users/${encodeURIComponent(member.scimId)}`,
+ })),
+ }
+ : {}),
+ meta: {
+ resourceType: 'Group',
+ created: group.createdAt.toISOString(),
+ lastModified: group.updatedAt.toISOString(),
+ location: `${baseUrl}/Groups/${encodeURIComponent(group.scimId)}`,
+ },
+ }
+}
+
+export function parseGroupFilter(raw: string): ScimGroupFilter {
+ const { attribute, value } = matchScimFilter(raw)
+ const key = attribute.toLowerCase()
+
+ if (key === 'displayname') return { attribute: 'displayName', value }
+ if (key === 'externalid') return { attribute: 'externalId', value }
+
+ throw new ScimError({ status: 400, scimType: 'invalidFilter', detail: `Filtering by ${attribute} is not supported` })
+}
+
+// Microsoft Entra ID reads groups with excludedAttributes=members and does not need the member list back
+export function excludesMembers(query: Record<string, unknown>): boolean {
+ if (typeof query.excludedAttributes !== 'string') return false
+ return query.excludedAttributes.split(',').some((name) => name.trim().toLowerCase() === 'members')
+}
+
+export function parseGroupListQuery(query: Record<string, unknown>): ScimGroupListQuery {
+ const filter = typeof query.filter === 'string' && query.filter.trim() ? parseGroupFilter(query.filter) : null
+ return { filter, excludeMembers: excludesMembers(query), ...parsePage(query) }
+}
+
+export function groupAttributesFromBody(body: ScimGroupBody): ScimGroupAttributes {
+ return {
+ displayName: requiredString(body.displayName, 'displayName'),
+ externalId: optionalString(body.externalId, 'externalId'),
+ members: memberIds(body.members ?? []),
+ }
+}
+
+export function applyGroupPatchOperations(args: ScimApplyGroupPatchArgs): ScimGroupAttributes {
+ const next = { ...args.current, members: [...args.current.members] }
+
+ for (const operation of args.operations) {
+ const op = operation.op.toLowerCase()
+ if (op !== 'add' && op !== 'replace' && op !== 'remove') {
+ throw new ScimError({ status: 400, scimType: 'invalidSyntax', detail: `Unsupported PATCH op: ${operation.op}` })
+ }
+
+ if (operation.path) {
+ applyGroupPatchValue({ target: next, path: operation.path, value: operation.value, op })
+ continue
+ }
+
+ if (op === 'remove' || !operation.value || typeof operation.value !== 'object' || Array.isArray(operation.value)) {
+ throw new ScimError({ status: 400, scimType: 'invalidPath', detail: 'A PATCH operation without path needs an object value' })
+ }
+ for (const [path, value] of Object.entries(operation.value as Record<string, unknown>)) {
+ applyGroupPatchValue({ target: next, path, value, op })
+ }
+ }
+
+ return next
+}
+
+function applyGroupPatchValue(args: ScimApplyGroupPatchValueArgs) {
+ const { target, path, value, op } = args
+ const key = path.trim().toLowerCase()
+
+ if (key === 'displayname') {
+ if (op === 'remove') throw new ScimError({ status: 400, scimType: 'mutability', detail: 'displayName cannot be removed' })
+ target.displayName = requiredString(value, 'displayName')
+ } else if (key === 'externalid') {
+ target.externalId = op === 'remove' ? null : optionalString(value, 'externalId')
+ } else if (key === 'members') {
+ // A remove without value clears the whole member list (RFC 7644, section 3.5.2.2)
+ const ids = op === 'remove' && value === undefined ? target.members : memberIds(value)
+ if (op === 'add') target.members = [...new Set([...target.members, ...ids])]
+ else if (op === 'replace') target.members = ids
+ else target.members = target.members.filter((id) => !ids.includes(id))
+ } else {
+ const member = MEMBER_FILTER_PATH.exec(path.trim())
+ if (member) {
+ if (op !== 'remove') throw new ScimError({ status: 400, scimType: 'invalidPath', detail: `${path} only supports remove` })
+ target.members = target.members.filter((id) => id !== member[1])
+ }
+ }
+ // Group attributes TaskView does not store are ignored, as for users
+}
+
+function memberIds(value: unknown): string[] {
+ const entries = Array.isArray(value) ? value : [value]
+ const ids = entries.map((entry) => {
+ const id = entry && typeof entry === 'object' ? (entry as Record<string, unknown>).value : undefined
+ if (typeof id !== 'string' || !id.trim()) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: 'Each member needs a value with the user id' })
+ }
+ return id.trim()
+ })
+ return [...new Set(ids)]
+}
diff --git a/api/src/tv-modules/scim/scim.helpers.ts b/api/src/tv-modules/scim/scim.helpers.ts
index a729029..49e51df 100644
--- a/api/src/tv-modules/scim/scim.helpers.ts
+++ b/api/src/tv-modules/scim/scim.helpers.ts
@@ -1,31 +1,265 @@
-const SCIM_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User'
+import type { ScimUsersSchemaTypeForSelect } from 'taskview-db-schemas'
+import { isEmail } from '../../utils/helpers'
+import { ScimError } from './ScimError'
+import type {
+ ScimApplyPatchArgs,
+ ScimApplyPatchValueArgs,
+ ScimErrorArgs,
+ ScimFilterMatch,
+ ScimListQuery,
+ ScimPage,
+ ScimListResponseArgs,
+ ScimUserAttributes,
+ ScimUserBody,
+ ScimUserFilter,
+ ScimUserResourceArgs,
+} from './types'
+
+export const SCIM_USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User'
const SCIM_LIST_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:ListResponse'
const SCIM_ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'
-export function toScimUser(member: { email: string; role: string }, active: boolean) {
+export const SCIM_DEFAULT_PAGE_SIZE = 100
+export const SCIM_MAX_PAGE_SIZE = 200
+const SCIM_MAX_STRING_LENGTH = 255
+const SCIM_MAX_FILTER_LENGTH = 512
+
+const EMAIL_PATH = /^emails(\[type eq "[^"]*"\])?(\.value)?$/i
+const FILTER = /^\s*(emails\[type eq "[^"]*"\]\.value|[A-Za-z.]+)\s+eq\s+(.+?)\s*$/i
+
+export function toScimError(args: ScimErrorArgs) {
+ return {
+ schemas: [SCIM_ERROR_SCHEMA],
+ status: String(args.status),
+ ...(args.scimType ? { scimType: args.scimType } : {}),
+ detail: args.detail,
+ }
+}
+
+export function toScimUser(args: ScimUserResourceArgs) {
+ const { user, baseUrl } = args
+ const name = {
+ ...(user.givenName ? { givenName: user.givenName } : {}),
+ ...(user.familyName ? { familyName: user.familyName } : {}),
+ }
+
return {
- schemas: [SCIM_SCHEMA],
- id: member.email,
- userName: member.email,
- emails: [{ value: member.email, primary: true }],
- active,
- roles: [{ value: member.role }],
+ schemas: [SCIM_USER_SCHEMA],
+ id: user.scimId,
+ ...(user.externalId ? { externalId: user.externalId } : {}),
+ userName: user.userName,
+ ...(Object.keys(name).length ? { name } : {}),
+ ...(user.displayName ? { displayName: user.displayName } : {}),
+ emails: [{ value: user.email, type: 'work', primary: true }],
+ active: user.active,
+ meta: {
+ resourceType: 'User',
+ created: user.createdAt.toISOString(),
+ lastModified: user.updatedAt.toISOString(),
+ location: `${baseUrl}/Users/${encodeURIComponent(user.scimId)}`,
+ },
}
}
-export function toScimList(resources: ReturnType<typeof toScimUser>[]) {
+export function toScimList(args: ScimListResponseArgs) {
return {
schemas: [SCIM_LIST_SCHEMA],
- totalResults: resources.length,
- Resources: resources,
+ totalResults: args.totalResults,
+ startIndex: args.startIndex,
+ itemsPerPage: args.resources.length,
+ Resources: args.resources,
+ }
+}
+
+export function matchScimFilter(raw: string): ScimFilterMatch {
+ if (raw.length > SCIM_MAX_FILTER_LENGTH) {
+ throw new ScimError({ status: 400, scimType: 'invalidFilter', detail: 'Filter is too long' })
+ }
+ const match = FILTER.exec(raw)
+ if (!match) {
+ throw new ScimError({ status: 400, scimType: 'invalidFilter', detail: `Unsupported filter: ${raw}` })
+ }
+ return { attribute: match[1], value: parseFilterValue(match[2]) }
+}
+
+export function parseScimFilter(raw: string): ScimUserFilter {
+ const { attribute, value } = matchScimFilter(raw)
+ const key = attribute.toLowerCase()
+
+ if (key === 'username') return { attribute: 'userName', value }
+ if (key === 'externalid') return { attribute: 'externalId', value }
+ if (EMAIL_PATH.test(key)) return { attribute: 'email', value: value.toLowerCase() }
+
+ throw new ScimError({ status: 400, scimType: 'invalidFilter', detail: `Filtering by ${attribute} is not supported` })
+}
+
+function parseFilterValue(raw: string): string {
+ if (raw.startsWith('"')) {
+ try {
+ const value: unknown = JSON.parse(raw)
+ if (typeof value === 'string') return value
+ } catch {
+ // falls through to the error below
+ }
+ } else if (!/\s/.test(raw)) {
+ return raw
+ }
+ throw new ScimError({ status: 400, scimType: 'invalidFilter', detail: `Unsupported filter value: ${raw}` })
+}
+
+export function parseListQuery(query: Record<string, unknown>): ScimListQuery {
+ const filter = typeof query.filter === 'string' && query.filter.trim() ? parseScimFilter(query.filter) : null
+ return { filter, ...parsePage(query) }
+}
+
+export function parsePage(query: Record<string, unknown>): ScimPage {
+ const startIndex = Math.max(1, toInteger(query.startIndex) ?? 1)
+ const count = Math.min(SCIM_MAX_PAGE_SIZE, Math.max(0, toInteger(query.count) ?? SCIM_DEFAULT_PAGE_SIZE))
+ return { startIndex, count }
+}
+
+function toInteger(value: unknown): number | null {
+ if (typeof value !== 'string' || !/^-?\d+$/.test(value)) return null
+ return Number(value)
+}
+
+export function parseActive(value: unknown): boolean {
+ if (typeof value === 'boolean') return value
+ if (typeof value === 'string') {
+ const normalized = value.trim().toLowerCase()
+ if (normalized === 'true') return true
+ if (normalized === 'false') return false
+ }
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: 'active must be a boolean' })
+}
+
+export function requiredString(value: unknown, attribute: string): string {
+ if (typeof value !== 'string' || !value.trim()) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `${attribute} must be a non-empty string` })
+ }
+ return limited(value.trim(), attribute)
+}
+
+export function optionalString(value: unknown, attribute: string): string | null {
+ if (value === null || value === undefined) return null
+ if (typeof value !== 'string') {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `${attribute} must be a string` })
+ }
+ return value.trim() ? limited(value.trim(), attribute) : null
+}
+
+function limited(value: string, attribute: string): string {
+ if (value.length > SCIM_MAX_STRING_LENGTH) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `${attribute} is longer than ${SCIM_MAX_STRING_LENGTH} characters` })
}
+ return value
}
-export function toScimError(status: number, detail: string) {
+function normalizeEmail(value: unknown): string {
+ const email = requiredString(value, 'emails.value').toLowerCase()
+ if (!isEmail(email)) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: `${email} is not a valid email address` })
+ }
+ return email
+}
+
+function pickEmail(emails: unknown): string | null {
+ if (!Array.isArray(emails) || emails.length === 0) return null
+ const entries = emails.filter((e): e is Record<string, unknown> => !!e && typeof e === 'object')
+ const isPrimary = (e: Record<string, unknown>) => e.primary === true || (typeof e.primary === 'string' && e.primary.toLowerCase() === 'true')
+ const chosen = entries.find(isPrimary) ?? entries.find((e) => e.type === 'work') ?? entries[0]
+ return chosen ? normalizeEmail(chosen.value) : null
+}
+
+export function attributesFromBody(body: ScimUserBody): ScimUserAttributes {
+ const userName = requiredString(body.userName, 'userName')
+ const email = pickEmail(body.emails) ?? (isEmail(userName) ? userName.toLowerCase() : null)
+ if (!email) {
+ throw new ScimError({ status: 400, scimType: 'invalidValue', detail: 'A work email is required: send emails[].value, or a userName that is an email address' })
+ }
+
return {
- schemas: [SCIM_ERROR_SCHEMA],
- detail,
- status: String(status),
+ userName,
+ email,
+ externalId: optionalString(body.externalId, 'externalId'),
+ displayName: optionalString(body.displayName, 'displayName'),
+ givenName: optionalString(body.name?.givenName, 'name.givenName'),
+ familyName: optionalString(body.name?.familyName, 'name.familyName'),
+ active: body.active === undefined ? true : parseActive(body.active),
}
}
+export function attributesOf(user: ScimUsersSchemaTypeForSelect): ScimUserAttributes {
+ return {
+ userName: user.userName,
+ email: user.email,
+ externalId: user.externalId,
+ displayName: user.displayName,
+ givenName: user.givenName,
+ familyName: user.familyName,
+ active: user.active,
+ }
+}
+
+export function applyPatchOperations(args: ScimApplyPatchArgs): ScimUserAttributes {
+ const next = { ...args.current }
+
+ for (const operation of args.operations) {
+ const op = operation.op.toLowerCase()
+ if (op !== 'add' && op !== 'replace' && op !== 'remove') {
+ throw new ScimError({ status: 400, scimType: 'invalidSyntax', detail: `Unsupported PATCH op: ${operation.op}` })
+ }
+
+ if (operation.path) {
+ applyPatchValue({ target: next, path: operation.path, value: operation.value, remove: op === 'remove' })
+ continue
+ }
+
+ if (op === 'remove' || !operation.value || typeof operation.value !== 'object' || Array.isArray(operation.value)) {
+ throw new ScimError({ status: 400, scimType: 'invalidPath', detail: 'A PATCH operation without path needs an object value' })
+ }
+ for (const [path, value] of Object.entries(operation.value as Record<string, unknown>)) {
+ applyPatchValue({ target: next, path, value, remove: false })
+ }
+ }
+
+ return next
+}
+
+function applyPatchValue(args: ScimApplyPatchValueArgs) {
+ const { target, path, value, remove } = args
+ const key = path.trim().toLowerCase()
+ const forbidRemove = () => {
+ if (remove) throw new ScimError({ status: 400, scimType: 'mutability', detail: `${path} cannot be removed` })
+ }
+
+ if (key === 'active') {
+ forbidRemove()
+ target.active = parseActive(value)
+ } else if (key === 'username') {
+ forbidRemove()
+ target.userName = requiredString(value, 'userName')
+ } else if (key === 'externalid') {
+ target.externalId = remove ? null : optionalString(value, 'externalId')
+ } else if (key === 'displayname') {
+ target.displayName = remove ? null : optionalString(value, 'displayName')
+ } else if (key === 'name.givenname') {
+ target.givenName = remove ? null : optionalString(value, 'name.givenName')
+ } else if (key === 'name.familyname') {
+ target.familyName = remove ? null : optionalString(value, 'name.familyName')
+ } else if (key === 'name') {
+ if (remove) {
+ target.givenName = null
+ target.familyName = null
+ } else if (value && typeof value === 'object') {
+ const name = value as Record<string, unknown>
+ if ('givenName' in name) target.givenName = optionalString(name.givenName, 'name.givenName')
+ if ('familyName' in name) target.familyName = optionalString(name.familyName, 'name.familyName')
+ }
+ } else if (EMAIL_PATH.test(key)) {
+ forbidRemove()
+ target.email = Array.isArray(value) ? (pickEmail(value) ?? target.email) : normalizeEmail(value)
+ }
+ // Attributes TaskView does not store (title, phoneNumbers, enterprise extension, ...) are ignored,
+ // so identity providers with default attribute mappings keep syncing without errors.
+}
diff --git a/api/src/tv-modules/scim/types.ts b/api/src/tv-modules/scim/types.ts
new file mode 100644
index 0000000..ba7d0a3
--- /dev/null
+++ b/api/src/tv-modules/scim/types.ts
@@ -0,0 +1,447 @@
+import { type, type ArkErrors } from 'arktype'
+import type { Request, Response } from 'express'
+import type { Database } from '../../modules/db'
+import type {
+ OrganizationsSchemaTypeForSelect,
+ ScimGroupsSchemaTypeForInsert,
+ ScimGroupsSchemaTypeForSelect,
+ ScimSuspendedMembership,
+ ScimUsersSchemaTypeForSelect,
+ SsoConfigsSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+
+export const ScimEmailArkType = type({
+ value: 'string',
+ 'type?': 'string',
+ 'primary?': 'boolean | string',
+})
+
+export const ScimUserArkType = type({
+ 'userName?': 'string',
+ 'externalId?': 'string | null',
+ 'emails?': ScimEmailArkType.array(),
+ 'displayName?': 'string | null',
+ 'name?': {
+ 'givenName?': 'string | null',
+ 'familyName?': 'string | null',
+ },
+ 'active?': 'boolean | string',
+})
+
+export type ScimUserBody = typeof ScimUserArkType.infer
+
+export const ScimGroupArkType = type({
+ 'displayName?': 'string',
+ 'externalId?': 'string | null',
+ 'members?': type({ value: 'string' }).array(),
+})
+
+export type ScimGroupBody = typeof ScimGroupArkType.infer
+
+export const ScimPatchArkType = type({
+ Operations: type({
+ op: 'string',
+ 'path?': 'string',
+ 'value?': 'unknown',
+ }).array().atLeastLength(1),
+})
+
+export type ScimPatchOperation = typeof ScimPatchArkType.infer['Operations'][number]
+
+export type ScimErrorType =
+ | 'invalidFilter'
+ | 'invalidSyntax'
+ | 'invalidPath'
+ | 'invalidValue'
+ | 'mutability'
+ | 'uniqueness'
+
+export type ScimErrorArgs = {
+ status: number
+ detail: string
+ scimType?: ScimErrorType
+}
+
+export type ScimUserAttributes = {
+ userName: string
+ email: string
+ externalId: string | null
+ displayName: string | null
+ givenName: string | null
+ familyName: string | null
+ active: boolean
+}
+
+export type ScimFilterAttribute = 'userName' | 'externalId' | 'email'
+
+export type ScimUserFilter = {
+ attribute: ScimFilterAttribute
+ value: string
+}
+
+export type ScimFilterMatch = {
+ attribute: string
+ value: string
+}
+
+export type ScimPage = {
+ startIndex: number
+ count: number
+}
+
+export type ScimListQuery = ScimPage & {
+ filter: ScimUserFilter | null
+}
+
+export type ScimContext = {
+ org: OrganizationsSchemaTypeForSelect
+ config: SsoConfigsSchemaTypeForSelect
+}
+
+export type ScimListUsersArgs = ScimContext & {
+ query: ScimListQuery
+}
+
+export type ScimListUsersResult = {
+ users: ScimUsersSchemaTypeForSelect[]
+ totalResults: number
+}
+
+export type ScimUserByIdArgs = ScimContext & {
+ scimId: string
+}
+
+export type ScimCreateUserArgs = ScimContext & {
+ attributes: ScimUserAttributes
+}
+
+export type ScimReplaceUserArgs = ScimUserByIdArgs & {
+ attributes: ScimUserAttributes
+}
+
+export type ScimPatchUserArgs = ScimUserByIdArgs & {
+ operations: ScimPatchOperation[]
+}
+
+export type ScimApplyChangesArgs = ScimContext & {
+ user: ScimUsersSchemaTypeForSelect
+ next: ScimUserAttributes
+}
+
+export type ScimEmailArgs = ScimContext & {
+ email: string
+}
+
+export type ScimReactivateArgs = ScimEmailArgs & {
+ suspended: ScimSuspendedMembership | null
+}
+
+export type ScimChangeEmailArgs = ScimContext & {
+ memberEmail: string
+ email: string
+ active: boolean
+}
+
+export type ScimLinkMemberArgs = ScimEmailArgs & {
+ userName: string
+}
+
+export type ScimMembershipArgs = {
+ orgId: number
+ email: string
+}
+
+export type ScimRestoreMembershipArgs = ScimMembershipArgs & {
+ goals: ScimSuspendedMembership['goals']
+}
+
+export type ScimFindByScimIdArgs = {
+ ssoConfigId: number
+ scimId: string
+}
+
+export type ScimUpdateUserArgs = {
+ id: number
+ values: ScimUserAttributes & {
+ memberEmail: string
+ suspendedMembership: ScimSuspendedMembership | null
+ }
+}
+
+export type ScimFindConflictArgs = {
+ ssoConfigId: number
+ attributes: Pick<ScimUserAttributes, 'userName' | 'email' | 'externalId'>
+ excludeId?: number
+}
+
+export type ScimFindForSignInArgs = {
+ ssoConfigId: number
+ emails: string[]
+}
+
+export type ScimFindByFilterArgs = {
+ ssoConfigId: number
+ filter: ScimUserFilter
+}
+
+export type ScimListPageArgs = {
+ ssoConfigId: number
+ offset: number
+ limit: number
+}
+
+export type ScimMoveMembershipArgs = {
+ orgId: number
+ oldEmail: string
+ email: string
+}
+
+export type ScimApplyPatchArgs = {
+ current: ScimUserAttributes
+ operations: ScimPatchOperation[]
+}
+
+export type ScimApplyPatchValueArgs = {
+ target: ScimUserAttributes
+ path: string
+ value: unknown
+ remove: boolean
+}
+
+export type ScimUserResourceArgs = {
+ user: ScimUsersSchemaTypeForSelect
+ baseUrl: string
+}
+
+export type ScimListResponseArgs = {
+ resources: unknown[]
+ totalResults: number
+ startIndex: number
+}
+
+export type ScimSchemaAttributeArgs = Record<string, unknown> & {
+ name: string
+}
+
+export type ScimHandler = (req: Request, res: Response) => Promise<unknown>
+
+export type ScimValidateArgs<T> = {
+ schema: (data: unknown) => T | ArkErrors
+ body: unknown
+}
+
+export type ScimGroupFilter = {
+ attribute: 'displayName' | 'externalId'
+ value: string
+}
+
+export type ScimGroupListQuery = ScimPage & {
+ filter: ScimGroupFilter | null
+ excludeMembers: boolean
+}
+
+export type ScimGroupAttributes = {
+ displayName: string
+ externalId: string | null
+ // SCIM ids of the member users
+ members: string[]
+}
+
+export type ScimGroupMember = {
+ groupId: number
+ scimId: string
+ display: string
+}
+
+export type ScimGroupView = {
+ group: ScimGroupsSchemaTypeForSelect
+ // null when the client asked to leave members out
+ members: ScimGroupMember[] | null
+}
+
+export type ScimListGroupsArgs = ScimContext & {
+ query: ScimGroupListQuery
+}
+
+export type ScimListGroupsResult = {
+ groups: ScimGroupView[]
+ totalResults: number
+}
+
+export type ScimGroupByIdArgs = ScimContext & {
+ scimId: string
+}
+
+export type ScimGetGroupArgs = ScimGroupByIdArgs & {
+ excludeMembers: boolean
+}
+
+export type ScimCreateGroupArgs = ScimContext & {
+ attributes: ScimGroupAttributes
+}
+
+export type ScimReplaceGroupArgs = ScimGroupByIdArgs & {
+ attributes: ScimGroupAttributes
+}
+
+export type ScimPatchGroupArgs = ScimGroupByIdArgs & {
+ operations: ScimPatchOperation[]
+}
+
+export type ScimApplyGroupChangesArgs = ScimContext & {
+ group: ScimGroupsSchemaTypeForSelect
+ next: ScimGroupAttributes
+}
+
+export type ScimFindGroupArgs = {
+ ssoConfigId: number
+ filter: ScimGroupFilter
+}
+
+export type ScimFindGroupConflictArgs = {
+ ssoConfigId: number
+ externalId: ScimGroupAttributes['externalId']
+ excludeId?: number
+}
+
+export type ScimFindUsersByScimIdsArgs = {
+ ssoConfigId: number
+ scimIds: string[]
+}
+
+export type ScimUserRef = {
+ id: number
+ scimId: string
+}
+
+export type ScimInsertGroupArgs = {
+ values: ScimGroupsSchemaTypeForInsert
+ scimUserIds: number[]
+}
+
+export type ScimUpdateGroupArgs = {
+ id: number
+ values: Pick<ScimGroupAttributes, 'displayName' | 'externalId'>
+ scimUserIds: number[]
+}
+
+export type ScimDbTransaction = Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0]
+
+export type ScimReplaceGroupMembersArgs = {
+ tx: ScimDbTransaction
+ groupId: number
+ scimUserIds: number[]
+}
+
+export type ScimWithMembersArgs = {
+ groups: ScimGroupsSchemaTypeForSelect[]
+ excludeMembers: boolean
+}
+
+export type ScimApplyGroupPatchArgs = {
+ current: ScimGroupAttributes
+ operations: ScimPatchOperation[]
+}
+
+export type ScimApplyGroupPatchValueArgs = {
+ target: ScimGroupAttributes
+ path: string
+ value: unknown
+ op: 'add' | 'replace' | 'remove'
+}
+
+export type ScimGroupResourceArgs = {
+ view: ScimGroupView
+ baseUrl: string
+}
+
+export type ScimAddToLinkedProjectsArgs = {
+ orgId: number
+ groupIds?: number[]
+ goalIds?: number[]
+ scimUserIds?: number[]
+ // Only links made or group memberships started after this moment
+ since?: Date
+}
+
+export type ScimProjectGrant = {
+ email: string
+ goalId: number
+ roleId: number
+}
+
+export type ScimGroupProjectLink = {
+ goalId: number
+ goalName: string
+ roleId: number
+ roleName: string
+}
+
+export type ScimAdminGroup = {
+ id: number
+ displayName: string
+ membersCount: number
+ projects: ScimGroupProjectLink[]
+}
+
+export type ScimAdminProjectRole = {
+ id: number
+ name: string
+}
+
+export type ScimAdminProject = {
+ goalId: number
+ name: string
+ roles: ScimAdminProjectRole[]
+}
+
+export type ScimGroupLinksOverview = {
+ groups: ScimAdminGroup[]
+ // Active projects of the organization with their roles
+ projects: ScimAdminProject[]
+}
+
+export type ScimGroupLinksOverviewArgs = {
+ config: SsoConfigsSchemaTypeForSelect
+}
+
+export type ScimGroupProjectRef = {
+ config: SsoConfigsSchemaTypeForSelect
+ groupId: number
+ goalId: number
+}
+
+export type ScimLinkGroupProjectArgs = ScimGroupProjectRef & {
+ roleId: number
+}
+
+export type ScimLinkGroupProjectResult = 'ok' | 'group_not_found' | 'project_not_found' | 'role_not_in_project'
+
+export type ScimUnlinkGroupProjectResult = 'ok' | 'not_found'
+
+export type ScimFindGroupForConfigArgs = {
+ ssoConfigId: number
+ groupId: number
+}
+
+export type ScimFindProjectRoleArgs = {
+ organizationId: number
+ goalId: number
+ roleId: number
+}
+
+export type ScimSaveGroupProjectArgs = {
+ groupId: number
+ goalId: number
+ roleId: number
+}
+
+export type ScimDeleteGroupProjectArgs = {
+ groupId: number
+ goalId: number
+}
+
+export type ScimFindActiveProjectArgs = {
+ organizationId: number
+ goalId: number
+}
diff --git a/api/src/tv-modules/sso/SsoController.ts b/api/src/tv-modules/sso/SsoController.ts
index 816be6a..6fe0616 100644
--- a/api/src/tv-modules/sso/SsoController.ts
+++ b/api/src/tv-modules/sso/SsoController.ts
@@ -9,15 +9,19 @@ import { generateLetters, generateString } from '../../utils/helpers'
import AuthModel from '../auth/AuthModel'
import { GoalsRepository } from '../goals/GoalsRepository'
import { OrganizationRepository } from '../organizations/OrganizationRepository'
+import { ScimGroupProjectsManager } from '../scim/ScimGroupProjectsManager'
+import { ScimRepository } from '../scim/ScimRepository'
import { createSsoProvider } from './providers/provider-factory'
import { SsoRepository } from './SsoRepository'
import { parseSamlMetadata } from './saml-metadata-parser'
import { checkSsoFetchUrl, generateLoginCode, isSsoDomainVerified, stripSecrets } from './sso.utils'
import {
+ ScimGroupProjectArkType,
SsoConfigArkTypeCreate,
SsoConfigArkTypeUpdate,
SsoDomainNotVerifiedError,
type ApplySsoIdpEmailArgs,
+ type CheckSsoScimAccessArgs,
type ResolveSsoUserArgs,
type ResolveSsoUserResult,
type SsoCallbackError,
@@ -29,6 +33,8 @@ export class SsoController {
private readonly authModel = new AuthModel()
private readonly orgRepo = new OrganizationRepository()
private readonly goalsRepo = new GoalsRepository()
+ private readonly scimRepo = new ScimRepository()
+ private readonly scimGroupProjects = new ScimGroupProjectsManager()
private async resolveLogin(preferredUsername?: string): Promise<string> {
const base = preferredUsername?.trim().slice(0, 50)
@@ -127,6 +133,25 @@ export class SsoController {
return { ok: true, user: created }
}
+ // With SCIM on, the identity provider decides who is in the organization: signing in must not
+ // bring back someone it deactivated or deleted, nor add someone it never provisioned
+ private async checkScimAccess(args: CheckSsoScimAccessArgs): Promise<SsoCallbackError | null> {
+ const { config } = args
+ if (!config.scimEnabled) return null
+
+ const identity = await this.ssoRepo.findIdentity({ ssoConfigId: config.id, externalId: args.externalId })
+ const account = identity ? await this.authModel.fetchUserById(identity.userId) : false
+ const emails = [...new Set([args.email, account ? account.email : null].filter((email): email is string => !!email).map((email) => email.toLowerCase()))]
+
+ const scimUser = await this.scimRepo.findForSignIn({ ssoConfigId: config.id, emails })
+ if (scimUser) return scimUser.active ? null : 'account_deactivated'
+
+ for (const email of emails) {
+ if (await this.orgRepo.getMemberByEmail(config.organizationId, email)) return null
+ }
+ return 'not_provisioned'
+ }
+
initiateLogin = async (req: Request, res: Response) => {
const configId = Number(req.params.configId)
if (!configId) return res.status(400).tvJson({ message: 'Invalid config ID' })
@@ -172,6 +197,16 @@ export class SsoController {
return res.status(403).tvJson({ message: 'Email domain not allowed for this SSO provider' })
}
+ const scimDenied = await this.checkScimAccess({
+ config,
+ email: ssoResult.email,
+ externalId: ssoResult.externalId,
+ })
+ if (scimDenied) {
+ $logger.info(`SSO: sign-in to SSO config ${config.id} refused by SCIM (${scimDenied})`)
+ return this.redirectSsoError(res, scimDenied)
+ }
+
const resolved = await this.resolveSsoUser({
ssoConfigId: config.id,
email: ssoResult.email,
@@ -404,6 +439,44 @@ export class SsoController {
return res.tvJson({ scimEnabled: config.scimEnabled })
}
+ listScimGroups = async (req: Request, res: Response) => {
+ const config = await this.ssoRepo.findById(Number(req.params.configId))
+ if (!config) return res.status(404).tvJson({ message: 'SSO config not found' })
+
+ return res.tvJson(await this.scimGroupProjects.overview({ config }))
+ }
+
+ linkScimGroupProject = async (req: Request, res: Response) => {
+ const groupId = Number(req.params.groupId)
+ const goalId = Number(req.params.goalId)
+ if (!Number.isInteger(groupId) || !Number.isInteger(goalId)) return res.status(400).end()
+
+ const body = ScimGroupProjectArkType(req.body)
+ if (body instanceof type.errors) return res.status(400).tvJson({ message: body.summary })
+
+ const config = await this.ssoRepo.findById(Number(req.params.configId))
+ if (!config) return res.status(404).tvJson({ message: 'SSO config not found' })
+
+ const result = await this.scimGroupProjects.link({ config, groupId, goalId, roleId: body.roleId })
+ if (result === 'group_not_found') return res.status(404).tvJson({ message: 'SCIM group not found' })
+ if (result === 'project_not_found') return res.status(404).tvJson({ message: 'Project not found' })
+ if (result === 'role_not_in_project') return res.status(400).tvJson({ message: 'The role does not belong to this project' })
+ return res.tvJson(true)
+ }
+
+ unlinkScimGroupProject = async (req: Request, res: Response) => {
+ const groupId = Number(req.params.groupId)
+ const goalId = Number(req.params.goalId)
+ if (!Number.isInteger(groupId) || !Number.isInteger(goalId)) return res.status(400).end()
+
+ const config = await this.ssoRepo.findById(Number(req.params.configId))
+ if (!config) return res.status(404).tvJson({ message: 'SSO config not found' })
+
+ const result = await this.scimGroupProjects.unlink({ config, groupId, goalId })
+ if (result === 'not_found') return res.status(404).tvJson({ message: 'Link not found' })
+ return res.tvJson(true)
+ }
+
deleteConfig = async (req: Request, res: Response) => {
const configId = Number(req.params.configId)
if (!configId) return res.status(400).end()
diff --git a/api/src/tv-modules/sso/SsoRoutes.ts b/api/src/tv-modules/sso/SsoRoutes.ts
index 2fa332f..ca739b5 100644
--- a/api/src/tv-modules/sso/SsoRoutes.ts
+++ b/api/src/tv-modules/sso/SsoRoutes.ts
@@ -40,5 +40,8 @@ export default class SsoRoutes implements Routable {
this.router.post('/admin/configs/:configId/verify-domain/check', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.checkDomainVerification)
this.router.post('/admin/configs/:configId/scim-token', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.generateScimToken)
this.router.patch('/admin/configs/:configId/scim', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.toggleScim)
+ this.router.get('/admin/configs/:configId/scim-groups', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.listScimGroups)
+ this.router.put('/admin/configs/:configId/scim-groups/:groupId/projects/:goalId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.linkScimGroupProject)
+ this.router.delete('/admin/configs/:configId/scim-groups/:groupId/projects/:goalId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.unlinkScimGroupProject)
}
}
diff --git a/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.ts b/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.ts
new file mode 100644
index 0000000..c61f99a
--- /dev/null
+++ b/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.ts
@@ -0,0 +1,215 @@
+import type { Request, Response } from 'express'
+import { and, eq, inArray, like } from 'drizzle-orm'
+import {
+ OrganizationMembersSchema,
+ OrganizationsSchema,
+ SsoConfigsSchema,
+ UsersSchema,
+ type OrganizationsSchemaTypeForSelect,
+ type SsoConfigsSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { Database } from '../../../modules/db'
+import { ScimManager } from '../../scim/ScimManager'
+import type { ScimUserAttributes } from '../../scim/types'
+import { SsoController } from '../SsoController'
+import type { CreateConfigArgs, SignInArgs, SignInOutcome } from './SsoSignInScim.integration.spec.types'
+
+// Only the identity provider's answer is faked: the callback, the SCIM rules and the database are real
+const idp = vi.hoisted(() => ({ result: { email: '', externalId: '' } }))
+vi.mock('../providers/provider-factory', () => ({
+ createSsoProvider: () => ({ handleCallback: async () => ({ ...idp.result }) }),
+}))
+
+const run = `${Date.now() % 1e8}${Math.floor(Math.random() * 100)}`
+const DOMAIN = `si${run}.example`
+const JIT_DOMAIN = `sj${run}.example`
+let seq = 0
+
+const db = () => Database.getInstance().dbDrizzle
+const controller = new SsoController()
+const manager = new ScimManager()
+
+let ownerId = 0
+let org: OrganizationsSchemaTypeForSelect
+let jitOrg: OrganizationsSchemaTypeForSelect
+let config: SsoConfigsSchemaTypeForSelect
+let jitConfig: SsoConfigsSchemaTypeForSelect
+
+const nextEmail = (label: string, domain = DOMAIN) => `${label}-${run}-${seq++}@${domain}`
+
+async function createOrg(name: string): Promise<OrganizationsSchemaTypeForSelect> {
+ const [created] = await db().insert(OrganizationsSchema).values({ name, slug: `${name}-${run}`, ownerId }).returning()
+ return created
+}
+
+async function createConfig(args: CreateConfigArgs) {
+ const [created] = await db()
+ .insert(SsoConfigsSchema)
+ .values({
+ organizationId: args.organizationId,
+ protocol: 'saml',
+ displayName: `sign-in-${run}`,
+ emailDomainRestriction: args.domain,
+ domainVerifiedAt: new Date(),
+ scimEnabled: args.scimEnabled,
+ defaultOrgRole: 'member',
+ })
+ .returning()
+ return created
+}
+
+async function signIn(args: SignInArgs): Promise<SignInOutcome> {
+ idp.result = { email: args.email, externalId: args.externalId }
+ let location = ''
+ const res = {
+ redirect: (url: string) => { location = url },
+ status: () => res,
+ tvJson: () => res,
+ }
+ const req = { params: { configId: String(args.configId) }, body: {}, query: {} }
+ await controller.handleCallback(req as unknown as Request, res as unknown as Response)
+ const query = new URL(location, 'http://app.test').searchParams
+ return { tokens: query.has('tokens'), error: query.get('sso_error') }
+}
+
+async function memberRole(organizationId: number, email: string): Promise<string | null> {
+ const [member] = await db()
+ .select({ role: OrganizationMembersSchema.role })
+ .from(OrganizationMembersSchema)
+ .where(and(eq(OrganizationMembersSchema.organizationId, organizationId), eq(OrganizationMembersSchema.email, email)))
+ return member?.role ?? null
+}
+
+async function accountExists(email: string): Promise<boolean> {
+ const rows = await db().select({ id: UsersSchema.id }).from(UsersSchema).where(eq(UsersSchema.email, email))
+ return rows.length > 0
+}
+
+const attributesFor = (email: string): ScimUserAttributes => ({
+ userName: email,
+ email,
+ externalId: `ext-${email}`,
+ displayName: null,
+ givenName: null,
+ familyName: null,
+ active: true,
+})
+
+const setActive = (scimId: string, value: boolean) =>
+ manager.patchUser({ org, config, scimId, operations: [{ op: 'replace', path: 'active', value }] })
+
+describe('SSO sign-in to an organization with SCIM', () => {
+ beforeAll(async () => {
+ const [owner] = await db()
+ .insert(UsersSchema)
+ .values({ login: `sso-owner-${run}`, email: `owner-${run}@owner.example`, password: 'not-used' })
+ .returning({ id: UsersSchema.id })
+ ownerId = owner.id
+ org = await createOrg('sso-scim')
+ jitOrg = await createOrg('sso-jit')
+ config = await createConfig({ organizationId: org.id, domain: DOMAIN, scimEnabled: 1 })
+ jitConfig = await createConfig({ organizationId: jitOrg.id, domain: JIT_DOMAIN, scimEnabled: 0 })
+ })
+
+ afterAll(async () => {
+ // Accounts made by the sign-in take their personal organizations and SSO identities with them
+ await db().delete(OrganizationsSchema).where(inArray(OrganizationsSchema.id, [org.id, jitOrg.id]))
+ await db().delete(UsersSchema).where(like(UsersSchema.email, `%@${DOMAIN}`))
+ await db().delete(UsersSchema).where(like(UsersSchema.email, `%@${JIT_DOMAIN}`))
+ await db().delete(UsersSchema).where(eq(UsersSchema.id, ownerId))
+ })
+
+ it('lets in a person SCIM provisioned', async () => {
+ const email = nextEmail('active')
+ await manager.createUser({ org, config, attributes: attributesFor(email) })
+
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ expect(await memberRole(org.id, email)).toBe('member')
+ })
+
+ it('refuses a person SCIM deactivated and does not bring them back', async () => {
+ const email = nextEmail('deactivated')
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+
+ await setActive(user.scimId, false)
+ expect(await memberRole(org.id, email)).toBeNull()
+
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: false, error: 'account_deactivated' })
+ expect(await memberRole(org.id, email)).toBeNull()
+ expect((await manager.getUser({ org, config, scimId: user.scimId })).active).toBe(false)
+
+ // Reactivation over SCIM is what lets them in again
+ await setActive(user.scimId, true)
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ expect(await memberRole(org.id, email)).toBe('member')
+ })
+
+ it('refuses a deactivated person who has not signed in yet and creates no account', async () => {
+ const email = nextEmail('never-signed-in')
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ await setActive(user.scimId, false)
+
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: false, error: 'account_deactivated' })
+ expect(await accountExists(email)).toBe(false)
+ })
+
+ it('refuses a deactivated person who signs in with an address SCIM has not caught up with', async () => {
+ const email = nextEmail('old-address')
+ const renamed = nextEmail('new-address')
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ await setActive(user.scimId, false)
+
+ // The identity provider already sends the new address, the SCIM record still holds the old one.
+ // Deactivation dropped the SSO identity, so the new address leads to nobody we know
+ expect(await signIn({ configId: config.id, email: renamed, externalId: `idp-${email}` })).toEqual({ tokens: false, error: 'not_provisioned' })
+ expect(await memberRole(org.id, email)).toBeNull()
+ expect(await memberRole(org.id, renamed)).toBeNull()
+ })
+
+ it('refuses a person SCIM deleted', async () => {
+ const email = nextEmail('deleted')
+ const user = await manager.createUser({ org, config, attributes: attributesFor(email) })
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+
+ await manager.deleteUser({ org, config, scimId: user.scimId })
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: false, error: 'not_provisioned' })
+ expect(await memberRole(org.id, email)).toBeNull()
+ })
+
+ it('refuses a person SCIM never provisioned and creates no account', async () => {
+ const email = nextEmail('unknown')
+
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: false, error: 'not_provisioned' })
+ expect(await memberRole(org.id, email)).toBeNull()
+ expect(await accountExists(email)).toBe(false)
+ })
+
+ it('lets in a member added by hand, whom SCIM does not manage', async () => {
+ const email = nextEmail('manual')
+ await db().insert(OrganizationMembersSchema).values({ organizationId: org.id, email, role: 'admin' })
+
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ expect(await memberRole(org.id, email)).toBe('admin')
+ })
+
+ it('lets in a member added by hand whose address changed in the identity provider', async () => {
+ const email = nextEmail('manual-old')
+ const renamed = nextEmail('manual-new')
+ await db().insert(OrganizationMembersSchema).values({ organizationId: org.id, email, role: 'admin' })
+ expect(await signIn({ configId: config.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+
+ expect(await signIn({ configId: config.id, email: renamed, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ expect(await memberRole(org.id, renamed)).toBe('admin')
+ expect(await memberRole(org.id, email)).toBeNull()
+ })
+
+ it('still adds anyone who signs in when SCIM is off', async () => {
+ const email = nextEmail('jit', JIT_DOMAIN)
+
+ expect(await signIn({ configId: jitConfig.id, email, externalId: `idp-${email}` })).toEqual({ tokens: true, error: null })
+ expect(await memberRole(jitOrg.id, email)).toBe('member')
+ })
+})
diff --git a/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.types.ts b/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.types.ts
new file mode 100644
index 0000000..adcf334
--- /dev/null
+++ b/api/src/tv-modules/sso/__tests__/SsoSignInScim.integration.spec.types.ts
@@ -0,0 +1,17 @@
+export type CreateConfigArgs = {
+ organizationId: number
+ domain: string
+ scimEnabled: number
+}
+
+export type SignInArgs = {
+ configId: number
+ email: string
+ externalId: string
+}
+
+// Where the callback sent the browser: a login code on success, an error code otherwise
+export type SignInOutcome = {
+ tokens: boolean
+ error: string | null
+}
diff --git a/api/src/tv-modules/sso/types.ts b/api/src/tv-modules/sso/types.ts
index 2e95f78..d5113ac 100644
--- a/api/src/tv-modules/sso/types.ts
+++ b/api/src/tv-modules/sso/types.ts
@@ -70,6 +70,10 @@ export type CheckSsoDomainProofArgs = {
token: string
}
+export const ScimGroupProjectArkType = type({
+ roleId: 'number.integer > 0',
+})
+
export type SsoDomainVerificationMethod = 'dns' | 'http' | 'trusted'
export type StartDomainVerificationResult = {
@@ -128,7 +132,18 @@ export type ApplySsoIdpEmailArgs = {
email: string
}
-export type SsoCallbackError = 'authentication_failed' | 'email_in_use' | 'account_blocked'
+export type SsoCallbackError =
+ | 'authentication_failed'
+ | 'email_in_use'
+ | 'account_blocked'
+ | 'account_deactivated'
+ | 'not_provisioned'
+
+export type CheckSsoScimAccessArgs = {
+ config: SsoConfigsSchemaTypeForSelect
+ email: string
+ externalId: string
+}
export type ResolveSsoUserResult =
| { ok: true, user: UserDbRecord }
diff --git a/docs/2.features/11.sso.md b/docs/2.features/11.sso.md
index 92bd077..21428ae 100644
--- a/docs/2.features/11.sso.md
+++ b/docs/2.features/11.sso.md
@@ -16,7 +16,7 @@ SSO lets your organization's members sign in to TaskView using your corporate id
5. IdP redirects back to TaskView with identity proof
6. TaskView creates an account (if new) and logs the user in
-Users who sign in via SSO are automatically added to the organization that owns the SSO config.
+Users who sign in via SSO are automatically added to the organization that owns the SSO config. With [SCIM provisioning](/docs/features/scim) on, only people the IdP has provisioned (and existing members) can sign in.
## Setting up SSO
@@ -134,7 +134,7 @@ For existing users (already registered with the same email), SSO login links the
:::callout{icon="i-lucide-info" color="info"}
**Removing users from the organization:** If you remove a user from the organization in TaskView but do not deactivate their account in the identity provider (IdP), the user will be automatically re-added to the organization on their next SSO login. This is standard JIT (Just-In-Time) provisioning behavior — the IdP is the source of truth for access.
-To fully block a user's access, deactivate or delete their account in the IdP. If SCIM provisioning is enabled, deactivating the user via SCIM will remove them from both the IdP and TaskView.
+To fully block a user's access, deactivate or delete them in the IdP and use [SCIM provisioning](/docs/features/scim). With SCIM on, SSO stops adding new people on their first sign-in, and people the IdP deactivated or deleted cannot sign in.
:::
## Replay attack protection (SAML)
diff --git a/docs/2.features/14.scim.md b/docs/2.features/14.scim.md
new file mode 100644
index 0000000..c09f173
--- /dev/null
+++ b/docs/2.features/14.scim.md
@@ -0,0 +1,135 @@
+---
+title: SCIM provisioning
+description: Let your identity provider create, update and deactivate organization members over SCIM 2.0, and link provider groups to projects so new group members get project access automatically.
+navigation:
+ icon: i-lucide-users-round
+---
+
+SCIM lets your identity provider (IdP) manage who is in your TaskView organization. The IdP creates people, changes their details and turns their access off; TaskView follows. Groups from the IdP can be linked to projects, so people who join a group are added to the project with a role you choose.
+
+SCIM works on top of an [SSO configuration](/docs/features/sso): each SSO config has its own SCIM token and its own set of provisioned users and groups.
+
+## Turning SCIM on
+
+1. Open your organization's settings → **SSO** tab. You need the **admin** or **owner** role.
+2. Make sure the SSO email domain is verified (see [Domain verification](/docs/features/sso#domain-verification)). SCIM requests are refused with `403` until it is.
+3. In the SSO config card, switch on **SCIM Provisioning**.
+4. Click **Generate SCIM Token** and copy the token. It is shown only once; TaskView stores only its hash. **Regenerate Token** replaces it, and the old token stops working.
+5. In your IdP, set the SCIM base URL to the **SCIM Endpoint URL** shown in the card (`<API URL>/scim/v2`) and the token as a Bearer token.
+
+Switching SCIM off deletes the token. To turn it back on, generate a new one.
+
+::callout{icon="i-lucide-network" color="warning"}
+Behind a reverse proxy, set [`API_PUBLIC_URL`](/docs/configuration/environment-variables#application) so the SCIM Endpoint URL points to an address your IdP can reach.
+::
+
+## People
+
+| What the IdP does | What happens in TaskView |
+|---|---|
+| Creates an active user | The person is added to the organization with the **member** role. Someone who is already a member keeps their role. |
+| Creates an inactive user | Nobody is added to the organization. |
+| Changes name or email | The SCIM record is updated. If the person already has a TaskView account, a new address is applied to it at their next SSO sign-in; otherwise their invitation to the organization moves to the new address. |
+| Deactivates a user (`active: false`) | The person is removed from the organization and from all of its projects, their SSO link and sessions are deleted. TaskView remembers their organization role and projects with roles. |
+| Reactivates a user | The remembered organization role and projects come back, plus the projects of groups linked or joined while the person was deactivated (see [Groups and projects](#groups-and-projects)). |
+| Deletes a user | Same as deactivation, and the SCIM record is deleted. |
+
+Rules that always apply:
+
+- **Email.** TaskView takes the address from `emails` (the primary one, otherwise the `work` one, otherwise the first). If there is none, `userName` is used when it is an email address. Without an address the request is refused with `400`.
+- **Domain.** The address must belong to the SSO config's email domain, otherwise the request is refused with `400`.
+- **Owner.** The organization owner cannot be deactivated or deleted over SCIM (`400`).
+- **Existing members.** When the IdP looks a person up by `userName` or email and they are already a member of the organization (added by hand or before SCIM was turned on), TaskView links them to the IdP instead of creating a duplicate. Only addresses in the SSO domain are linked.
+- **Members added by hand** who the IdP never sent are not touched by SCIM.
+
+## Signing in with SCIM on
+
+While SCIM is on, the IdP decides who may enter the organization. When someone signs in through this SSO config:
+
+- an **active** SCIM user or an existing member of the organization signs in as usual;
+- a **deactivated** SCIM user is refused with *"Your access to the organization is turned off"*;
+- anyone else is refused with *"You have not been added to the organization yet"*: SSO no longer adds new people on their first sign-in.
+
+With SCIM off, SSO works as described in [User provisioning](/docs/features/sso#user-provisioning): new people are added on their first sign-in.
+
+::callout{icon="i-lucide-info" color="info"}
+If you remove a person from the organization by hand while the IdP still has them as active, they come back with the SSO config's default role (**member**) at their next SSO sign-in. To keep someone out, deactivate them in the IdP.
+::
+
+## Groups and projects
+
+Groups sent by the IdP appear in the SSO config card under **SCIM Provisioning → Groups** (visible while SCIM is on), with the number of members. A group can be linked to one or more projects, each with a **default role**.
+
+SCIM **only adds** people to projects. It never removes anyone and never changes the roles of someone who is already in a project:
+
+| Event | Result |
+|---|---|
+| A group is linked to a project | Everyone currently in the group is added to the project with the default role. |
+| A person joins a linked group | They are added to the linked projects with the default role. |
+| The person is already in the project | Nothing changes: their roles stay as they are. |
+| A person leaves the group | Nothing changes: they stay in the project. |
+| The link is removed | Nothing changes for people already in the project; new group members are no longer added. |
+| Someone removes the person from the project by hand | They stay out. Syncs of the same group do not bring them back. |
+
+A person who was removed from a project by hand is added again only by a new event: they leave the group and join it again, they join another group linked to the same project, or the link is removed and created again.
+
+People are added only if they are an active SCIM user **and** a current member of the organization. Archived projects are not filled, and the project owner is skipped.
+
+### Linking a group
+
+1. In the **Groups** list, click **Add project** next to the group.
+2. Choose a project and a default role. The role must exist in that project; create it in the project's settings first if needed.
+3. Click **Link**.
+
+Linking the same project again with another role changes the default role for people who join later. People already in the project keep their roles.
+
+Who can link: organization **owners** and **admins**, the same people who manage SSO. They can link any active project of the organization, even one they are not a member of. In this list they see only project and role names; opening a project still requires being a member of it.
+
+### What else changes a link
+
+- The IdP deletes the group: its links are deleted, people stay in the projects.
+- The project or the role is deleted: the link is deleted.
+- The project is archived: the link stays, but nobody is added while the project is archived.
+
+## Supported SCIM operations
+
+Base path: `/scim/v2`. Every request needs `Authorization: Bearer <SCIM token>`.
+
+| Method | Path | Notes |
+|---|---|---|
+| GET | `/ServiceProviderConfig`, `/ResourceTypes`, `/Schemas` | Discovery |
+| GET | `/Users` | Filters: `userName eq` (case-insensitive), `externalId eq`, `emails eq`, `emails.value eq`, `emails[type eq "work"].value eq`. Pagination with `startIndex` and `count` (default 100, max 200) |
+| GET, PUT, PATCH, DELETE | `/Users/{id}` | Deactivated users stay readable with `active: false` |
+| POST | `/Users` | `409` if the `userName`, email or `externalId` is already used in this SSO config |
+| GET | `/Groups` | Filters: `displayName eq`, `externalId eq`. Supports `excludedAttributes=members` |
+| GET, PUT, PATCH, DELETE | `/Groups/{id}` | Members must be users of the same SSO config, otherwise `400` |
+| POST | `/Groups` | `409` if the `externalId` is already used in this SSO config |
+
+Group names do not have to be unique: two groups may share a `displayName`. Only `externalId` identifies a group.
+
+## Provider notes
+
+**Pocket ID**
+
+- Restrict the OIDC client used for SCIM to user groups. Otherwise Pocket ID also sends its built-in API user, which has no email, and the sync fails with `400`.
+- During a sync Pocket ID deletes SCIM users it did not create itself, such as ones connected by another provider. If it has a user with the same email, that user takes their place; otherwise the person is removed from the organization. Members added by hand and never sent over SCIM are not affected.
+- When a user is taken out of a group on the user's page, Pocket ID v2.18.0 does not send the change. Change membership on the group's page instead. Leaving a group does not remove anyone from a project anyway, but TaskView keeps showing the person in the group.
+
+## API endpoints for group links
+
+Require authentication and the organization **admin** or **owner** role.
+
+| Method | URL | Description |
+|---|---|---|
+| GET | `/module/sso/admin/configs/{configId}/scim-groups` | Groups with their links, and the projects with roles that can be linked |
+| PUT | `/module/sso/admin/configs/{configId}/scim-groups/{groupId}/projects/{goalId}` | Link a group to a project. Body: `{ "roleId": number }` |
+| DELETE | `/module/sso/admin/configs/{configId}/scim-groups/{groupId}/projects/{goalId}` | Remove the link |
+
+## Database tables
+
+| Table | Purpose |
+|---|---|
+| `tv_auth.scim_users` | Users provisioned over SCIM, per SSO config, with the remembered access of deactivated users |
+| `tv_auth.scim_groups` | Groups sent by the IdP |
+| `tv_auth.scim_group_members` | Who is in which group, and since when |
+| `tv_auth.scim_group_projects` | Links between groups and projects with the default role |
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3d9e49f..769c157 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -45,6 +45,12 @@ importers:
api:
dependencies:
+ '@aws-sdk/client-s3':
+ specifier: ^3.1138.0
+ version: 3.1152.0
+ '@aws-sdk/lib-storage':
+ specifier: ^3.1138.0
+ version: 3.1152.0(@aws-sdk/[email protected])
'@node-saml/node-saml':
specifier: ^5.1.0
version: 5.1.0
@@ -78,6 +84,9 @@ importers:
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
+ busboy:
+ specifier: ^1.6.0
+ version: 1.6.0
cookie-parser:
specifier: ^1.4.7
version: 1.4.7
@@ -178,6 +187,9 @@ importers:
'@types/bcrypt':
specifier: ^5.0.2
version: 5.0.2
+ '@types/busboy':
+ specifier: ^1.5.4
+ version: 1.5.5
'@types/cookie-parser':
specifier: ^1.4.10
version: 1.4.10(@types/[email protected])
@@ -555,6 +567,84 @@ packages:
resolution: {integrity: sha512-JPy/NGWn/lvf1WmGCPw2VGpBg5utZraE84I7wli18EDF3p3zc/e9WolT35tINeZO3l7C77SjqRJeAUoT0CvMRg==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-CcAkVyEUKGngbEqJdVdSc53Iy52+XzVL5NIcTen2BlK8UByNC1DThVtf5VKSrNzyA+SqyTvs+3S+knVBbOUizQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-oI1+ZaM6pSOwZazu4nAb7rL8ug7LSjg31tDoJqRB9MooRqqWCf/qvkIZqne1mRA3xK3slg6K0RNWXaJYHbWLvg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-nslpzUCTI9b2IQMWSd6mSAXldBexPc8rr0d3dXUutXYFLFaTdsHa2GD7sJdsn3PhyjK0O5K8ypd6zi+RXXPVlg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-rsRJcW2iFUhCgclyD6OSbMEaPl8Eu0qSeRZb2uuCK1ViZ66hl5wOe/p6Vr6MO3b+ydyKgFeqza2p6tZThvILlw==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-pnKdh0Br7OJPj+7qKjzgTfDTFW0RhEMKXNDR2jv9CAM4oHuG/4z3hRh8KtutLfpmItuRtDbKBmwWkDqHwwAWXw==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-kcjvAxqQEV8yuwkX58RelNn3ne65o7JgRWf3Z/gVvbi7Xuw1qSDLJlatrLD76+40cmRxmNkLxBoyp/vAQChQ5g==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-CeQHSbE2CnVdaHIJ/NayRaCecIER+Pm9faUPkmRATO54rCoMTEPSbVieGHzEwvm1dZM2HIs6qQZCznhayNTWJQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-WNttSyr6e8innPtBSty//CdnqJcgZN6eAbtw3v/CR2IObz6MYZEo8eusdtuCHJ2ujwFqC2bSPHVyhXGHx8HruQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-Yj6kZFJQdbR+PygTkqdVLPHHpdDpOS9GCYVcDCuweCRRig9LF24ELQBMfyUw1vspvrZJUfnOGVyMjhaL094ahw==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-FnpPhdY4qUGtX/8X6eKxh+uD+9Y19i9FYibgk4SBe0M935s9vocHkHzaxaMNk+YkHmvzgdu8cHA5SCoeU+kkew==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-TJF25Ndwy2HxcVj6oxMgp8qVlJAawlExHYBXqhuC6Zt2m+A7WpdkjBD6QglNbiArlteYljZHEY3R7KKmno6ISA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-UU1fDLKBd8az+4AmNx30ggnA4D4HolUd1MxT/J6ka76qKcckI0IxjAy6FpX/vwiUf2KDNxxN2YX0cfwjMqzWoQ==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ '@aws-sdk/client-s3': ^3.1152.0
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-UfgAQosf4IEXldMsyntVuHsJnaQzlH6pmkOr6dQy7CaOYSlGz3mWiW4Di7XfQ/kPJP6xE7oMshz1V0E8RqGdRg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-B01jdXJtAW/XOiUzGdI2mz67WyEHbGEc9X6Euzw3bjLAa+txTqdZDER4X2FsIEcXzV2ABqudVZ5thali8tCCzQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-wDU36ofhabZYu+d2KSriyDbwzxNoaOp+4dG0p3qkabk7HeALR5nIWyQbjoyJZLn3iqWkv/xNdyUfbfevDVDzzg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==}
+ engines: {node: '>=20.0.0'}
+
+ resolution: {integrity: sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==}
+ engines: {node: '>=18.0.0'}
+
resolution: {integrity: sha512-JYgintcMjRiCvS8mMECzaEn+m3PfoQiyqukOMCCVQtoJGYJw8j/8LBJEiqkHLkfwCcs74E3pbAUFNg7d9VNJ+Q==}
engines: {node: '>=6.9.0'}
@@ -2883,6 +2973,30 @@ packages:
'@rushstack/[email protected]':
resolution: {integrity: sha512-YmrFTFUdHXblYSa+Xc9OO9FsL/XFcckZy0ycQ6q7VSBsVs5P0uD9vcges5Q9vctGlVdu27w+Ct6IuJ458V0cTQ==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-3hJiwG1F5t1SoXqp/yOCmYXziyx7ZVqF63S5W6YU201e/qwVaHPex+E/3vvyY9a3ORq/b+BydeNZpP2saQ9X2g==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==}
+ engines: {node: '>=18.0.0'}
+
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==}
+ engines: {node: '>=18.0.0'}
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
@@ -3262,6 +3376,9 @@ packages:
resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-IwqrfVFxWa23c4WeE7uZswssCqGfvnl5Q7b1pdshbT3HaQDa3UIbJx5BAxtcj9nZYX9tVDArM9TUv9SpvORbpQ==}
+
resolution: {integrity: sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==}
@@ -4280,6 +4397,9 @@ packages:
resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
+ resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
+
resolution: {integrity: sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==}
@@ -4335,6 +4455,9 @@ packages:
resolution: {integrity: sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==}
+ resolution: {integrity: sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==}
+
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
@@ -4351,6 +4474,10 @@ packages:
os: [darwin, linux, win32]
hasBin: true
+ resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==}
+ engines: {node: '>=10.16.0'}
+
resolution: {integrity: sha512-s6webAy+R4SR8XVuJWt2V2rGvhnrhxN+9S15GNuTK3wKPOXFF6RNc+8ug2XhH+2s4f+uudG4kUVYmYOQWL2g0Q==}
engines: {node: '>=0.10.0'}
@@ -7842,6 +7969,9 @@ packages:
resolution: {integrity: sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==}
+ resolution: {integrity: sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==}
+
resolution: {integrity: sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==}
engines: {node: '>= 0.10.0'}
@@ -7852,6 +7982,10 @@ packages:
resolution: {integrity: sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==}
+ resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}
+ engines: {node: '>=10.0.0'}
+
resolution: {integrity: sha512-kn+e44esVfn2Fa/O0CPFcex27fjIL6MkVae0Mm6q+E6f0hWv578YCERbv+4m02cjxvDsPKLnmxral/rR6lBMAg==}
@@ -9034,6 +9168,181 @@ snapshots:
'@ark/[email protected]': {}
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/checksums': 3.1001.3
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/credential-provider-node': 3.972.86
+ '@aws-sdk/middleware-sdk-s3': 3.972.79
+ '@aws-sdk/signature-v4-multi-region': 3.996.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/fetch-http-handler': 5.8.0
+ '@smithy/node-http-handler': 4.12.1
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.974.6
+ '@aws-sdk/xml-builder': 3.972.41
+ '@aws/lambda-invoke-store': 0.3.0
+ '@smithy/core': 3.36.0
+ '@smithy/signature-v4': 5.7.4
+ '@smithy/types': 4.19.0
+ bowser: 2.14.1
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/fetch-http-handler': 5.8.0
+ '@smithy/node-http-handler': 4.12.1
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/credential-provider-env': 3.972.74
+ '@aws-sdk/credential-provider-http': 3.972.76
+ '@aws-sdk/credential-provider-login': 3.972.81
+ '@aws-sdk/credential-provider-process': 3.972.74
+ '@aws-sdk/credential-provider-sso': 3.973.18
+ '@aws-sdk/credential-provider-web-identity': 3.972.80
+ '@aws-sdk/nested-clients': 3.997.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/credential-provider-imds': 4.5.2
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/nested-clients': 3.997.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/credential-provider-env': 3.972.74
+ '@aws-sdk/credential-provider-http': 3.972.76
+ '@aws-sdk/credential-provider-ini': 3.973.19
+ '@aws-sdk/credential-provider-process': 3.972.74
+ '@aws-sdk/credential-provider-sso': 3.973.18
+ '@aws-sdk/credential-provider-web-identity': 3.972.80
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/credential-provider-imds': 4.5.2
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/nested-clients': 3.997.48
+ '@aws-sdk/token-providers': 3.1150.0
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/nested-clients': 3.997.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected](@aws-sdk/[email protected])':
+ dependencies:
+ '@aws-sdk/client-s3': 3.1152.0
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ buffer: 5.6.0
+ events: 3.3.0
+ stream-browserify: 3.0.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/signature-v4-multi-region': 3.996.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/signature-v4-multi-region': 3.996.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/fetch-http-handler': 5.8.0
+ '@smithy/node-http-handler': 4.12.1
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/types': 3.974.6
+ '@smithy/signature-v4': 5.7.4
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.978.3
+ '@aws-sdk/nested-clients': 3.997.48
+ '@aws-sdk/types': 3.974.6
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@aws/[email protected]': {}
+
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -11687,6 +11996,39 @@ snapshots:
transitivePeerDependencies:
- '@types/node'
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ '@smithy/core': 3.36.0
+ '@smithy/types': 4.19.0
+ tslib: 2.8.1
+
+ '@smithy/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
'@standard-schema/[email protected]': {}
@@ -12108,6 +12450,10 @@ snapshots:
'@types/connect': 3.4.38
'@types/node': 22.19.7
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.7
+
optional: true
@@ -13415,6 +13761,8 @@ snapshots:
+
dependencies:
stream-buffers: 2.2.0
@@ -13475,6 +13823,11 @@ snapshots:
ieee754: 1.2.1
isarray: 1.0.0
+ dependencies:
+ base64-js: 1.5.1
+ ieee754: 1.2.1
+
dependencies:
base64-js: 1.5.1
@@ -13502,6 +13855,10 @@ snapshots:
'@oven/bun-windows-x64': 1.3.6
'@oven/bun-windows-x64-baseline': 1.3.6
+ dependencies:
+ streamsearch: 1.1.0
+
@@ -17315,6 +17672,11 @@ snapshots:
+ dependencies:
+ inherits: 2.0.4
+ readable-stream: 3.6.2
+
@@ -17325,6 +17687,8 @@ snapshots:
optional: true
+
dependencies:
events-universal: 1.0.1
diff --git a/taskview-packages/taskview-api/src/api/__tests__/collaboration.test.ts b/taskview-packages/taskview-api/src/api/__tests__/collaboration.test.ts
index b092a88..5ab65a1 100644
--- a/taskview-packages/taskview-api/src/api/__tests__/collaboration.test.ts
+++ b/taskview-packages/taskview-api/src/api/__tests__/collaboration.test.ts
@@ -672,4 +672,29 @@ describe('Collaboration', () => {
await $api.tasks.deleteTask(task.id).catch(() => {});
});
-});
\ No newline at end of file
+
+ it('does not bring back old project roles when a removed user is invited again', async () => {
+ const goal = await $api.goals.createGoal({ name: 'Collaboration roles goal' });
+ const otherGoal = await $api.goals.createGoal({ name: 'Collaboration roles other goal' });
+ if (!goal || !otherGoal) {
+ throw new Error('Failed to create goals');
+ }
+
+ // A second project keeps the collaborator row alive after the removal
+ const invited = await addUserToGoal(goal.id, email);
+ await addUserToGoal(otherGoal.id, email);
+ const role = await $api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: `Role ${Date.now()}` });
+ if (!invited || !role) {
+ throw new Error('Failed to prepare collaborator');
+ }
+ await $api.collaboration.toggleUserRoles({ goalId: goal.id, userId: invited.id, roles: [role.id] });
+
+ await $api.collaboration.deleteUserFromGoal({ goalId: goal.id, id: invited.id });
+ const again = await addUserToGoal(goal.id, email);
+ expect(again?.id).toBe(invited.id);
+
+ const users = await $api.collaboration.fetchUsersForGoal(goal.id);
+ expect(users.find((u) => u.email === email)?.roles).toEqual([]);
+ expect((await $api.collaboration.fetchRolesForGoal(goal.id)).map((r) => r.id)).toContain(role.id);
+ });
+});
diff --git a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml
index 0297532..c9a3b67 100644
--- a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml
+++ b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml
@@ -39,8 +39,9 @@ services:
# IdP-facing URLs are built from this base (see sso-public-urls.test.ts)
API_PUBLIC_URL: "https://api.public.example"
# Domains that skip DNS/HTTP ownership proof — used by sso.test.ts to
- # deterministically produce a *verified* config (method 'trusted').
- SSO_TRUSTED_DOMAINS: "owned-sso.example"
+ # deterministically produce a *verified* config (method 'trusted'),
+ # and by scim.test.ts / scim-pocket-id.test.ts / scim-group-projects.test.ts, since SCIM requires a verified domain.
+ SSO_TRUSTED_DOMAINS: "owned-sso.example,scim-e2e.example,scim-e2e-other.example,scim-pocketid.example,scim-groups.example"
# The webhook receiver of webhooks.test.ts runs on the host and is reached
# via host.docker.internal, a private address from inside the container.
WEBHOOKS_ALLOW_PRIVATE_URLS: "true"
@@ -51,3 +52,28 @@ services:
interval: 3s
timeout: 3s
retries: 10
+
+ # A real SCIM client for scim-pocket-id.test.ts: it pushes its users to the api over the compose network
+ pocket-id:
+ image: ghcr.io/pocket-id/pocket-id:v2.18.0
+ restart: "no"
+ ports:
+ - "11411:1411"
+ depends_on:
+ api:
+ condition: service_healthy
+ environment:
+ APP_URL: "http://localhost:11411"
+ ENCRYPTION_KEY: "taskview-test-encryption-key-0123456789"
+ # Admin access for the tests without a sign-in: requests send it in the X-API-Key header
+ STATIC_API_KEY: "taskview-test-pocket-id-api-key"
+ # Turns off the hourly and the "5 minutes after a change" syncs: the tests trigger every sync themselves
+ APP_ENV: "test"
+ ANALYTICS_DISABLED: "true"
+ VERSION_CHECK_DISABLED: "true"
+ DISABLE_RATE_LIMITING: "true"
+ healthcheck:
+ test: ["CMD", "/app/pocket-id", "healthcheck"]
+ interval: 3s
+ timeout: 3s
+ retries: 20
diff --git a/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.ts b/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.ts
new file mode 100644
index 0000000..28f8d64
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.ts
@@ -0,0 +1,105 @@
+import axios, { type AxiosInstance } from 'axios'
+import type {
+ PocketIdGroupInput,
+ PocketIdRenameGroupArgs,
+ PocketIdScimProviderArgs,
+ PocketIdSetAllowedGroupsArgs,
+ PocketIdSetUserGroupsArgs,
+ PocketIdSetGroupUsersArgs,
+ PocketIdSyncResult,
+ PocketIdUpdateUserArgs,
+ PocketIdUser,
+ PocketIdUserInput,
+} from './pocket-id-client.types'
+
+export const POCKET_ID_URL = process.env.POCKET_ID_TEST_URL || 'http://localhost:11411'
+// STATIC_API_KEY of the pocket-id service in docker/docker-compose.yml
+const POCKET_ID_API_KEY = process.env.POCKET_ID_TEST_API_KEY || 'taskview-test-pocket-id-api-key'
+
+// The admin API of a real Pocket ID instance, used to drive its SCIM client in the tests
+export class PocketIdClient {
+ private readonly http: AxiosInstance
+
+ constructor() {
+ this.http = axios.create({ baseURL: `${POCKET_ID_URL}/api`, headers: { 'X-API-Key': POCKET_ID_API_KEY } })
+ }
+
+ async createGroup(input: PocketIdGroupInput): Promise<string> {
+ const { data } = await this.http.post('/user-groups', input)
+ return data.id
+ }
+
+ async renameGroup(args: PocketIdRenameGroupArgs) {
+ await this.http.put(`/user-groups/${args.id}`, { name: args.name, friendlyName: args.friendlyName })
+ }
+
+ async deleteGroup(id: string) {
+ await this.http.delete(`/user-groups/${id}`)
+ }
+
+ async setGroupUsers(args: PocketIdSetGroupUsersArgs) {
+ await this.http.put(`/user-groups/${args.groupId}/users`, { userIds: args.userIds })
+ }
+
+ // Changes the membership from the user page rather than from the group page
+ async setUserGroups(args: PocketIdSetUserGroupsArgs) {
+ await this.http.put(`/users/${args.userId}/user-groups`, { userGroupIds: args.groupIds })
+ }
+
+ async createUser(input: PocketIdUserInput): Promise<PocketIdUser> {
+ const { data } = await this.http.post('/users', { ...input, emailVerified: true })
+ return { ...input, id: data.id }
+ }
+
+ // Pocket ID replaces the whole user on update, so the request carries every field
+ async updateUser(args: PocketIdUpdateUserArgs): Promise<PocketIdUser> {
+ const next = { ...args.user, ...args.changes }
+ await this.http.put(`/users/${next.id}`, {
+ username: next.username,
+ email: next.email,
+ emailVerified: true,
+ firstName: next.firstName,
+ lastName: next.lastName,
+ disabled: !!next.disabled,
+ })
+ return next
+ }
+
+ async deleteUser(id: string) {
+ await this.http.delete(`/users/${id}`)
+ }
+
+ // A client restricted to one group: only its members are pushed over SCIM
+ async createGroupClient(groupId: string): Promise<string> {
+ const { data } = await this.http.post('/oidc/clients', {
+ name: `taskview-${groupId.slice(0, 8)}`,
+ callbackURLs: ['http://localhost/callback'],
+ isGroupRestricted: true,
+ })
+ await this.setAllowedGroups({ clientId: data.id, groupIds: [groupId] })
+ return data.id
+ }
+
+ async setAllowedGroups(args: PocketIdSetAllowedGroupsArgs) {
+ await this.http.put(`/oidc/clients/${args.clientId}/allowed-user-groups`, { userGroupIds: args.groupIds })
+ }
+
+ async deleteClient(id: string) {
+ await this.http.delete(`/oidc/clients/${id}`)
+ }
+
+ async createScimProvider(args: PocketIdScimProviderArgs): Promise<string> {
+ const { data } = await this.http.post('/scim/service-provider', args)
+ return data.id
+ }
+
+ async deleteScimProvider(id: string) {
+ await this.http.delete(`/scim/service-provider/${id}`)
+ }
+
+ // Answers once the sync has finished; a failed request inside the sync makes it answer with an error
+ async sync(providerId: string): Promise<PocketIdSyncResult> {
+ const res = await this.http.post(`/scim/service-provider/${providerId}/sync`, undefined, { validateStatus: () => true })
+ return { status: res.status, body: res.data }
+ }
+}
diff --git a/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.types.ts b/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.types.ts
new file mode 100644
index 0000000..8d18f8a
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/pocket-id-client.types.ts
@@ -0,0 +1,51 @@
+export type PocketIdUserInput = {
+ username: string
+ email: string
+ firstName: string
+ lastName: string
+ disabled?: boolean
+}
+
+export type PocketIdUser = PocketIdUserInput & {
+ id: string
+}
+
+export type PocketIdUpdateUserArgs = {
+ user: PocketIdUser
+ changes: Partial<PocketIdUserInput>
+}
+
+export type PocketIdSetGroupUsersArgs = {
+ groupId: string
+ userIds: string[]
+}
+
+export type PocketIdScimProviderArgs = {
+ endpoint: string
+ token: string
+ oidcClientId: string
+}
+
+export type PocketIdSyncResult = {
+ status: number
+ body: unknown
+}
+
+export type PocketIdGroupInput = {
+ name: string
+ friendlyName: string
+}
+
+export type PocketIdRenameGroupArgs = PocketIdGroupInput & {
+ id: string
+}
+
+export type PocketIdSetUserGroupsArgs = {
+ userId: string
+ groupIds: string[]
+}
+
+export type PocketIdSetAllowedGroupsArgs = {
+ clientId: string
+ groupIds: string[]
+}
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.ts b/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.ts
new file mode 100644
index 0000000..41f7542
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.ts
@@ -0,0 +1,363 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import axios from 'axios'
+import { TvApi } from '@/tv'
+import { initApi, API_URL } from './init-api'
+import type {
+ GroupProjectsLinkArgs,
+ GroupProjectsMembersArgs,
+ GroupProjectsProject,
+ GroupProjectsRequestArgs,
+} from './scim-group-projects.test.types'
+
+// Trusted in docker/docker-compose.yml, since SCIM requires a verified domain
+const DOMAIN = 'scim-groups.example'
+const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp'
+
+const run = `${Date.now()}${Math.floor(Math.random() * 1000)}`
+let seq = 0
+
+let user1Api: TvApi
+let user2Api: TvApi
+let user2Email: string
+let deleteAllGoals: () => Promise<void>
+let orgId: number
+let otherOrgId: number
+let configId: number
+let otherConfigId: number
+let scimToken: string
+
+const unique = (label: string) => `${label}-${run}-${seq++}`
+const emailFor = (label: string) => `${unique(label)}@${DOMAIN}`
+
+async function scim(args: GroupProjectsRequestArgs) {
+ return axios.request({
+ method: args.method,
+ url: `${API_URL}/scim/v2${args.path}`,
+ data: args.body,
+ headers: { Authorization: `Bearer ${scimToken}`, 'Content-Type': 'application/scim+json' },
+ validateStatus: () => true,
+ })
+}
+
+async function createUser(label: string) {
+ const email = emailFor(label)
+ const res = await scim({ method: 'post', path: '/Users', body: { userName: email, emails: [{ value: email, primary: true }] } })
+ expect(res.status).toBe(201)
+ return { id: res.data.id as string, email }
+}
+
+async function createGroup(members: string[] = []) {
+ const displayName = unique('Group')
+ const res = await scim({ method: 'post', path: '/Groups', body: { displayName, externalId: unique('ext'), members: members.map((value) => ({ value })) } })
+ expect(res.status).toBe(201)
+ const overview = await user1Api.sso.fetchScimGroups(configId)
+ const stored = overview.groups.find((group) => group.displayName === displayName)
+ if (!stored) throw new Error('The group is missing from the overview')
+ return { scimId: res.data.id as string, id: stored.id, displayName }
+}
+
+const addToGroup = async (scimGroupId: string, scimUserId: string) => {
+ const res = await scim({
+ method: 'patch',
+ path: `/Groups/${scimGroupId}`,
+ body: { schemas: [PATCH_SCHEMA], Operations: [{ op: 'add', path: 'members', value: [{ value: scimUserId }] }] },
+ })
+ expect(res.status).toBe(204)
+}
+
+// A full replacement, the way Pocket ID and Okta send the members
+const putMembers = async (args: GroupProjectsMembersArgs) => {
+ const current = await scim({ method: 'get', path: `/Groups/${args.scimGroupId}` })
+ const res = await scim({
+ method: 'put',
+ path: `/Groups/${args.scimGroupId}`,
+ body: { displayName: current.data.displayName, externalId: current.data.externalId, members: args.scimUserIds.map((value) => ({ value })) },
+ })
+ expect(res.status).toBe(200)
+}
+
+const setActive = async (scimUserId: string, active: boolean) => {
+ const res = await scim({ method: 'patch', path: `/Users/${scimUserId}`, body: { Operations: [{ op: 'replace', path: 'active', value: active }] } })
+ expect(res.status).toBe(200)
+}
+
+async function projectWithRole(organizationId = orgId): Promise<GroupProjectsProject> {
+ const goal = await user1Api.goals.createGoal({ name: `SCIM groups ${unique('g')}`, organizationId })
+ if (!goal) throw new Error('Failed to create the project')
+ const role = await user1Api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: unique('role') })
+ if (!role) throw new Error('Failed to create the role')
+ return { goalId: goal.id, roleId: role.id }
+}
+
+const link = (args: GroupProjectsLinkArgs) => user1Api.sso.linkScimGroupProject({ configId, ...args })
+
+async function projectRoles(goalId: number, email: string): Promise<number[] | null> {
+ const users = await user1Api.collaboration.fetchUsersForGoal(goalId)
+ const user = users.find((u) => u.email === email)
+ return user ? [...user.roles].sort() : null
+}
+
+beforeAll(async () => {
+ const init = await initApi()
+ user1Api = init.$tvApi
+ user2Api = init.$tvApiForSecondUser
+ user2Email = init.user2Email
+ deleteAllGoals = init.deleteAllGoals
+
+ const samlConfig = {
+ protocol: 'saml' as const,
+ samlEntryPoint: 'https://idp.example.com/saml/sso',
+ samlCert: 'MIICmzCCAYMCBgF...',
+ samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
+ }
+ orgId = (await user1Api.organizations.create({ name: 'SCIM Groups Org' })).id
+ const config = await user1Api.sso.createConfig({ ...samlConfig, organizationId: orgId, displayName: 'SCIM groups', emailDomainRestriction: DOMAIN, samlIssuer: `scim-groups-${run}` })
+ configId = config.id
+ scimToken = (await user1Api.sso.generateScimToken(configId)).token
+
+ otherOrgId = (await user1Api.organizations.create({ name: 'SCIM Groups Other Org' })).id
+ const otherConfig = await user1Api.sso.createConfig({
+ ...samlConfig,
+ organizationId: otherOrgId,
+ displayName: 'SCIM groups other',
+ emailDomainRestriction: `other-${DOMAIN}`,
+ samlIssuer: `scim-groups-other-${run}`,
+ })
+ otherConfigId = otherConfig.id
+
+ // An admin of the organization who is in none of its projects
+ await user1Api.organizations.addMember({ organizationId: orgId, email: user2Email, role: 'admin' })
+})
+
+afterAll(async () => {
+ await user1Api.sso.deleteConfig(configId).catch(() => {})
+ await user1Api.sso.deleteConfig(otherConfigId).catch(() => {})
+ await user1Api.organizations.delete(orgId).catch(() => {})
+ await user1Api.organizations.delete(otherOrgId).catch(() => {})
+ await deleteAllGoals()
+})
+
+describe('SCIM groups linked to projects', () => {
+ it('adds a person who joins a linked group to the project with the default role', async () => {
+ const project = await projectWithRole()
+ const group = await createGroup()
+ await link({ groupId: group.id, ...project })
+
+ const user = await createUser('joiner')
+ expect(await projectRoles(project.goalId, user.email)).toBeNull()
+ await addToGroup(group.scimId, user.id)
+
+ expect(await projectRoles(project.goalId, user.email)).toEqual([project.roleId])
+ })
+
+ it('adds the current members when the link is made, but not deactivated ones', async () => {
+ const member = await createUser('member')
+ const deactivated = await createUser('deactivated')
+ const group = await createGroup([member.id, deactivated.id])
+ await setActive(deactivated.id, false)
+
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+
+ expect(await projectRoles(project.goalId, member.email)).toEqual([project.roleId])
+ expect(await projectRoles(project.goalId, deactivated.email)).toBeNull()
+ })
+
+ it('leaves the roles of someone already in the project as they are', async () => {
+ const user = await createUser('already-in')
+ const project = await projectWithRole()
+ const ownRole = await user1Api.collaboration.createRoleForGoal({ goalId: project.goalId, roleName: unique('own') })
+ const collaborator = await user1Api.collaboration.inviteUserToGoal({ goalId: project.goalId, email: user.email })
+ if (!ownRole || !collaborator) throw new Error('Failed to prepare the collaborator')
+ await user1Api.collaboration.toggleUserRoles({ goalId: project.goalId, userId: collaborator.id, roles: [ownRole.id] })
+
+ const group = await createGroup()
+ await link({ groupId: group.id, ...project })
+ await addToGroup(group.scimId, user.id)
+
+ expect(await projectRoles(project.goalId, user.email)).toEqual([ownRole.id])
+ })
+
+ it('does not bring back someone taken out of the project by hand', async () => {
+ const leaver = await createUser('taken-out')
+ const newcomer = await createUser('newcomer')
+ const group = await createGroup([leaver.id])
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+ expect(await projectRoles(project.goalId, leaver.email)).toEqual([project.roleId])
+
+ const collaborator = (await user1Api.collaboration.fetchUsersForGoal(project.goalId)).find((u) => u.email === leaver.email)
+ if (!collaborator) throw new Error('The member is missing from the project')
+ await user1Api.collaboration.deleteUserFromGoal({ goalId: project.goalId, id: collaborator.id })
+
+ // The provider repeats the whole list on every change
+ await putMembers({ scimGroupId: group.scimId, scimUserIds: [leaver.id] })
+ await putMembers({ scimGroupId: group.scimId, scimUserIds: [leaver.id, newcomer.id] })
+
+ expect(await projectRoles(project.goalId, leaver.email)).toBeNull()
+ expect(await projectRoles(project.goalId, newcomer.email)).toEqual([project.roleId])
+ })
+
+ it('keeps the project of someone who leaves the group', async () => {
+ const user = await createUser('leaves-group')
+ const group = await createGroup([user.id])
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+
+ await putMembers({ scimGroupId: group.scimId, scimUserIds: [] })
+ expect(await projectRoles(project.goalId, user.email)).toEqual([project.roleId])
+ })
+
+ it('adds a reactivated person to what was linked while they were off, and not to what they lost before', async () => {
+ const user = await createUser('reactivated')
+ const group = await createGroup([user.id])
+ const earlier = await projectWithRole()
+ await link({ groupId: group.id, ...earlier })
+ const collaborator = (await user1Api.collaboration.fetchUsersForGoal(earlier.goalId)).find((u) => u.email === user.email)
+ if (!collaborator) throw new Error('The member is missing from the project')
+ await user1Api.collaboration.deleteUserFromGoal({ goalId: earlier.goalId, id: collaborator.id })
+
+ await setActive(user.id, false)
+ const later = await projectWithRole()
+ await link({ groupId: group.id, ...later })
+ expect(await projectRoles(later.goalId, user.email)).toBeNull()
+
+ await setActive(user.id, true)
+ expect(await projectRoles(later.goalId, user.email)).toEqual([later.roleId])
+ expect(await projectRoles(earlier.goalId, user.email)).toBeNull()
+ })
+
+ it('adds a reactivated person to the projects of a group they joined while off', async () => {
+ const user = await createUser('joined-while-off')
+ const project = await projectWithRole()
+ const group = await createGroup()
+ await link({ groupId: group.id, ...project })
+
+ await setActive(user.id, false)
+ await addToGroup(group.scimId, user.id)
+ expect(await projectRoles(project.goalId, user.email)).toBeNull()
+
+ await setActive(user.id, true)
+ expect(await projectRoles(project.goalId, user.email)).toEqual([project.roleId])
+ })
+
+ it('does not add someone an admin removed from the organization', async () => {
+ const user = await createUser('removed-from-org')
+ const group = await createGroup([user.id])
+ await user1Api.organizations.removeMember({ organizationId: orgId, email: user.email })
+
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+ expect(await projectRoles(project.goalId, user.email)).toBeNull()
+ })
+
+ it('does not add people to an archived project', async () => {
+ const group = await createGroup()
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+ await user1Api.goals.updateGoal({ id: project.goalId, archive: 1 })
+
+ const user = await createUser('archived')
+ await addToGroup(group.scimId, user.id)
+ expect(await projectRoles(project.goalId, user.email)).toBeNull()
+ })
+
+ it('stops adding people once the project is unlinked', async () => {
+ const group = await createGroup()
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+ await user1Api.sso.unlinkScimGroupProject({ configId, groupId: group.id, goalId: project.goalId })
+
+ const user = await createUser('after-unlink')
+ await addToGroup(group.scimId, user.id)
+ expect(await projectRoles(project.goalId, user.email)).toBeNull()
+ })
+
+ it('shows the groups with their projects and the projects the admin may link', async () => {
+ const user = await createUser('listed')
+ const group = await createGroup([user.id])
+ const project = await projectWithRole()
+ await link({ groupId: group.id, ...project })
+
+ const overview = await user1Api.sso.fetchScimGroups(configId)
+ const listed = overview.groups.find((g) => g.id === group.id)
+ expect(listed).toMatchObject({ displayName: group.displayName, membersCount: 1 })
+ expect(listed?.projects).toEqual([expect.objectContaining({ goalId: project.goalId, roleId: project.roleId })])
+
+ const linkable = overview.projects.find((p) => p.goalId === project.goalId)
+ expect(linkable?.roles.map((r) => r.id)).toContain(project.roleId)
+ })
+})
+
+describe('SCIM group links: who may make them', () => {
+ const expectStatus = async (request: Promise<unknown>, status: number) => {
+ const error = await request.then(() => null, (e) => e)
+ expect(error?.response?.status ?? error?.status).toBe(status)
+ }
+
+ it('refuses a role of another project', async () => {
+ const group = await createGroup()
+ const project = await projectWithRole()
+ const other = await projectWithRole()
+ await expectStatus(link({ groupId: group.id, goalId: project.goalId, roleId: other.roleId }), 400)
+ })
+
+ it('refuses a project of another organization', async () => {
+ const group = await createGroup()
+ const foreign = await projectWithRole(otherOrgId)
+ await expectStatus(link({ groupId: group.id, ...foreign }), 404)
+ })
+
+ it('refuses a group of another SSO configuration', async () => {
+ const group = await createGroup()
+ const project = await projectWithRole(otherOrgId)
+ await expectStatus(user1Api.sso.linkScimGroupProject({ configId: otherConfigId, groupId: group.id, ...project }), 404)
+ })
+
+ it('lets an organization admin link and unlink a project they are not in', async () => {
+ const user = await createUser('admin-link')
+ const group = await createGroup([user.id])
+ const project = await projectWithRole()
+
+ const overview = await user2Api.sso.fetchScimGroups(configId)
+ expect(overview.projects.map((p) => p.goalId)).toContain(project.goalId)
+ await user2Api.sso.linkScimGroupProject({ configId, groupId: group.id, ...project })
+ expect(await projectRoles(project.goalId, user.email)).toEqual([project.roleId])
+
+ const listed = (await user2Api.sso.fetchScimGroups(configId)).groups.find((g) => g.id === group.id)
+ expect(listed?.projects).toEqual([expect.objectContaining({ goalId: project.goalId, roleId: project.roleId, goalName: expect.any(String) })])
+ await user2Api.sso.unlinkScimGroupProject({ configId, groupId: group.id, goalId: project.goalId })
+ expect((await user2Api.sso.fetchScimGroups(configId)).groups.find((g) => g.id === group.id)?.projects).toEqual([])
+ })
+
+ it('does not offer or link an archived project', async () => {
+ const group = await createGroup()
+ const project = await projectWithRole()
+ await user1Api.goals.updateGoal({ id: project.goalId, archive: 1 })
+
+ const overview = await user1Api.sso.fetchScimGroups(configId)
+ expect(overview.projects.map((p) => p.goalId)).not.toContain(project.goalId)
+ await expectStatus(link({ groupId: group.id, ...project }), 404)
+ })
+
+ it('refuses someone who is not an organization admin', async () => {
+ const memberOrg = (await user1Api.organizations.create({ name: 'SCIM Groups Member Org' })).id
+ try {
+ const memberConfig = await user1Api.sso.createConfig({
+ organizationId: memberOrg,
+ protocol: 'saml',
+ displayName: 'SCIM groups member',
+ emailDomainRestriction: `member-${DOMAIN}`,
+ samlEntryPoint: 'https://idp.example.com/saml/sso',
+ samlIssuer: `scim-groups-member-${run}`,
+ samlCert: 'MIICmzCCAYMCBgF...',
+ samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
+ })
+ await user1Api.organizations.addMember({ organizationId: memberOrg, email: user2Email, role: 'member' })
+ await expectStatus(user2Api.sso.fetchScimGroups(memberConfig.id), 403)
+ await user1Api.sso.deleteConfig(memberConfig.id)
+ } finally {
+ await user1Api.organizations.delete(memberOrg).catch(() => {})
+ }
+ })
+})
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.types.ts
new file mode 100644
index 0000000..1d34056
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim-group-projects.test.types.ts
@@ -0,0 +1,21 @@
+export type GroupProjectsRequestArgs = {
+ method: 'get' | 'post' | 'put' | 'patch' | 'delete'
+ path: string
+ body?: unknown
+}
+
+export type GroupProjectsProject = {
+ goalId: number
+ roleId: number
+}
+
+export type GroupProjectsLinkArgs = {
+ groupId: number
+ goalId: number
+ roleId: number
+}
+
+export type GroupProjectsMembersArgs = {
+ scimGroupId: string
+ scimUserIds: string[]
+}
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.ts b/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.ts
new file mode 100644
index 0000000..6032128
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.ts
@@ -0,0 +1,532 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import axios from 'axios'
+import { TvApi } from '@/tv'
+import { initApi, API_URL } from './init-api'
+import { PocketIdClient } from './pocket-id-client'
+import type { PocketIdUser } from './pocket-id-client.types'
+import type { PocketIdTestProject, PocketIdTestProjectArgs } from './scim-pocket-id.test.types'
+
+// A real Pocket ID instance (docker/docker-compose.yml) provisions users into TaskView over SCIM
+const DOMAIN = 'scim-pocketid.example'
+// The address of the api as Pocket ID sees it from inside the compose network
+const SCIM_ENDPOINT = process.env.POCKET_ID_SCIM_ENDPOINT || 'http://api:1401/scim/v2'
+
+const run = `${Date.now()}${Math.floor(Math.random() * 1000)}`
+let seq = 0
+
+const pocketId = new PocketIdClient()
+let user1Api: TvApi
+let deleteAllGoals: () => Promise<void>
+let orgId: number
+let configId: number
+let scimToken: string
+let groupId: string
+let clientId: string
+let providerId: string
+const groupMembers: string[] = []
+const allowedGroups: string[] = []
+const pocketIdUsers: string[] = []
+
+const BULK_USERS = 600
+
+const unique = (label: string) => `${label}-${run}-${seq++}`
+const emailFor = (label: string) => `${unique(label)}@${DOMAIN}`
+
+async function scimGet(path: string) {
+ const res = await axios.get(`${API_URL}/scim/v2${path}`, {
+ headers: { Authorization: `Bearer ${scimToken}` },
+ validateStatus: () => true,
+ })
+ expect(res.status).toBe(200)
+ return res.data
+}
+
+// Every user of the connection, read page by page as an identity provider does
+async function allScimUsers() {
+ const users = []
+ for (let startIndex = 1; ; startIndex += 200) {
+ const page = await scimGet(`/Users?startIndex=${startIndex}&count=200`)
+ users.push(...page.Resources)
+ if (!page.Resources.length || users.length >= page.totalResults) return users
+ }
+}
+
+async function inBatches<T>(items: T[], work: (item: T) => Promise<unknown>) {
+ for (let i = 0; i < items.length; i += 25) await Promise.all(items.slice(i, i + 25).map(work))
+}
+
+async function scimUserByExternalId(externalId: string) {
+ const list = await scimGet(`/Users?filter=${encodeURIComponent(`externalId eq "${externalId}"`)}`)
+ return list.Resources[0]
+}
+
+async function scimUserByEmail(email: string) {
+ const list = await scimGet(`/Users?filter=${encodeURIComponent(`emails.value eq "${email}"`)}`)
+ return list.Resources[0]
+}
+
+async function orgMember(email: string) {
+ const members = await user1Api.organizations.fetchMembers(orgId)
+ return members.find((m) => m.email === email.toLowerCase())
+}
+
+async function projectMember(goalId: number, email: string) {
+ const users = await user1Api.collaboration.fetchUsersForGoal(goalId)
+ return users.find((u) => u.email === email.toLowerCase())
+}
+
+async function createPocketIdUser(label: string): Promise<PocketIdUser> {
+ const user = await pocketId.createUser({
+ username: unique(label),
+ email: emailFor(label),
+ firstName: 'Test',
+ lastName: label,
+ })
+ pocketIdUsers.push(user.id)
+ return user
+}
+
+async function grantAccess(user: PocketIdUser) {
+ groupMembers.push(user.id)
+ await pocketId.setGroupUsers({ groupId, userIds: groupMembers })
+}
+
+async function revokeAccess(user: PocketIdUser) {
+ groupMembers.splice(groupMembers.indexOf(user.id), 1)
+ await pocketId.setGroupUsers({ groupId, userIds: groupMembers })
+}
+
+// Pocket ID on SQLite keeps change times in whole seconds and skips a user whose change is not newer than
+// our meta.lastModified, so a change made in the same second as the last sync would never be pushed
+async function afterSecondOf(lastModified: string) {
+ const wait = Math.floor(Date.parse(lastModified) / 1000) * 1000 + 1100 - Date.now()
+ if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait))
+}
+
+async function nextSecond(externalId: string) {
+ const { meta } = await scimUserByExternalId(externalId)
+ await afterSecondOf(meta.lastModified)
+}
+
+// The same rule holds for groups: a group change is pushed only when it is newer than our meta.lastModified
+async function nextSecondForGroup(externalId: string) {
+ const { meta } = await scimGroupByExternalId(externalId)
+ await afterSecondOf(meta.lastModified)
+}
+
+async function scimGroupByExternalId(externalId: string) {
+ const list = await scimGet(`/Groups?filter=${encodeURIComponent(`externalId eq "${externalId}"`)}`)
+ return list.Resources[0]
+}
+
+// Our SCIM ids of the given Pocket ID users, in the order a group lists its members
+async function scimIdsOf(users: PocketIdUser[]) {
+ const ids = await Promise.all(users.map(async (user) => (await scimUserByExternalId(user.id)).id))
+ return ids.sort()
+}
+
+async function scimGroupMembers(externalId: string) {
+ const group = await scimGroupByExternalId(externalId)
+ return (group.members ?? []).map((member: { value: string }) => member.value).sort()
+}
+
+// A group the application allows, so Pocket ID pushes it with its members
+async function createAllowedGroup(members: PocketIdUser[], friendlyName = unique('Group')): Promise<string> {
+ const id = await pocketId.createGroup({ name: unique('group'), friendlyName })
+ allowedGroups.push(id)
+ await pocketId.setGroupUsers({ groupId: id, userIds: members.map((user) => user.id) })
+ await pocketId.setAllowedGroups({ clientId, groupIds: [groupId, ...allowedGroups] })
+ return id
+}
+
+async function disallowGroup(id: string) {
+ allowedGroups.splice(allowedGroups.indexOf(id), 1)
+ await pocketId.setAllowedGroups({ clientId, groupIds: [groupId, ...allowedGroups] })
+}
+
+// People who keep access to the application through the access group, so a group change only changes membership
+async function usersWithAccess(count: number, label: string) {
+ const users: PocketIdUser[] = []
+ for (let i = 0; i < count; i++) users.push(await createPocketIdUser(label))
+ groupMembers.push(...users.map((user) => user.id))
+ await pocketId.setGroupUsers({ groupId, userIds: groupMembers })
+ return users
+}
+
+async function syncOk() {
+ const result = await pocketId.sync(providerId)
+ expect(result, JSON.stringify(result.body)).toMatchObject({ status: 200 })
+}
+
+// A project of the organization where the person holds a project role
+async function projectWithRole(args: PocketIdTestProjectArgs): Promise<PocketIdTestProject> {
+ const goal = await user1Api.goals.createGoal({ name: `Pocket ID ${unique(args.label)}`, organizationId: orgId })
+ if (!goal) throw new Error('Failed to create the project')
+ const collaborator = await user1Api.collaboration.inviteUserToGoal({ goalId: goal.id, email: args.email })
+ const role = await user1Api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: `role ${unique('r')}` })
+ if (!collaborator || !role) throw new Error('Failed to prepare the collaborator')
+ await user1Api.collaboration.toggleUserRoles({ goalId: goal.id, userId: collaborator.id, roles: [role.id] })
+ return { goalId: goal.id, roleId: role.id }
+}
+
+beforeAll(async () => {
+ const init = await initApi()
+ user1Api = init.$tvApi
+ deleteAllGoals = init.deleteAllGoals
+
+ const org = await user1Api.organizations.create({ name: 'Pocket ID SCIM Org' })
+ orgId = org.id
+ const config = await user1Api.sso.createConfig({
+ organizationId: orgId,
+ protocol: 'saml',
+ displayName: 'Pocket ID SCIM',
+ emailDomainRestriction: DOMAIN,
+ samlEntryPoint: 'https://idp.example.com/saml/sso',
+ samlIssuer: 'taskview-scim-pocket-id',
+ samlCert: 'MIICmzCCAYMCBgF...',
+ samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
+ defaultOrgRole: 'member',
+ })
+ configId = config.id
+ scimToken = (await user1Api.sso.generateScimToken(configId)).token
+
+ const accessGroup = unique('taskview')
+ groupId = await pocketId.createGroup({ name: accessGroup, friendlyName: accessGroup })
+ clientId = await pocketId.createGroupClient(groupId)
+ providerId = await pocketId.createScimProvider({ endpoint: SCIM_ENDPOINT, token: scimToken, oidcClientId: clientId })
+})
+
+afterAll(async () => {
+ await pocketId.deleteScimProvider(providerId).catch(() => {})
+ await pocketId.deleteClient(clientId).catch(() => {})
+ await pocketId.deleteGroup(groupId).catch(() => {})
+ await inBatches(allowedGroups, (id) => pocketId.deleteGroup(id).catch(() => {}))
+ await inBatches(pocketIdUsers, (id) => pocketId.deleteUser(id).catch(() => {}))
+ await user1Api.sso.deleteConfig(configId).catch(() => {})
+ await user1Api.organizations.delete(orgId).catch(() => {})
+ await deleteAllGoals()
+})
+
+describe('SCIM with Pocket ID: users', () => {
+ it('provisions a user who gets access to the application', async () => {
+ const user = await createPocketIdUser('new')
+ await grantAccess(user)
+ await syncOk()
+
+ const scimUser = await scimUserByExternalId(user.id)
+ expect(scimUser).toMatchObject({
+ userName: user.username,
+ active: true,
+ emails: [expect.objectContaining({ value: user.email })],
+ name: { givenName: 'Test', familyName: 'new' },
+ })
+ expect(await orgMember(user.email)).toMatchObject({ role: 'member' })
+ })
+
+ it('does not provision users outside the allowed group', async () => {
+ const user = await createPocketIdUser('outsider')
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toBeUndefined()
+ expect(await orgMember(user.email)).toBeUndefined()
+ })
+
+ it('applies a changed email and name', async () => {
+ const user = await createPocketIdUser('rename')
+ await grantAccess(user)
+ await syncOk()
+
+ await nextSecond(user.id)
+ const renamed = await pocketId.updateUser({ user, changes: { email: emailFor('renamed'), lastName: 'Renamed' } })
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toMatchObject({
+ emails: [expect.objectContaining({ value: renamed.email })],
+ name: { givenName: 'Test', familyName: 'Renamed' },
+ })
+ // Without a TaskView account the invitation moves to the new address
+ expect(await orgMember(renamed.email)).toBeTruthy()
+ expect(await orgMember(user.email)).toBeUndefined()
+ })
+
+ it('takes access away from a disabled user and gives it back with the project roles', async () => {
+ const user = await createPocketIdUser('disabled')
+ await grantAccess(user)
+ await syncOk()
+ const project = await projectWithRole({ email: user.email, label: 'disabled' })
+
+ await nextSecond(user.id)
+ const disabled = await pocketId.updateUser({ user, changes: { disabled: true } })
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toMatchObject({ active: false })
+ expect(await orgMember(user.email)).toBeUndefined()
+ expect(await projectMember(project.goalId, user.email)).toBeUndefined()
+
+ await nextSecond(user.id)
+ await pocketId.updateUser({ user: disabled, changes: { disabled: false } })
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toMatchObject({ active: true })
+ expect(await orgMember(user.email)).toMatchObject({ role: 'member' })
+ expect((await projectMember(project.goalId, user.email))?.roles).toEqual([project.roleId])
+ })
+
+ it('removes a user who loses access to the application', async () => {
+ const user = await createPocketIdUser('revoked')
+ await grantAccess(user)
+ await syncOk()
+ const project = await projectWithRole({ email: user.email, label: 'revoked' })
+
+ await revokeAccess(user)
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toBeUndefined()
+ expect(await orgMember(user.email)).toBeUndefined()
+ expect(await projectMember(project.goalId, user.email)).toBeUndefined()
+ })
+
+ it('removes a user deleted in Pocket ID', async () => {
+ const user = await createPocketIdUser('deleted')
+ await grantAccess(user)
+ await syncOk()
+
+ groupMembers.splice(groupMembers.indexOf(user.id), 1)
+ await pocketId.deleteUser(user.id)
+ await syncOk()
+
+ expect(await scimUserByEmail(user.email)).toBeUndefined()
+ expect(await orgMember(user.email)).toBeUndefined()
+ })
+
+ it('leaves alone a member added by hand who is not in Pocket ID', async () => {
+ const email = emailFor('manual')
+ await user1Api.organizations.addMember({ organizationId: orgId, email, role: 'admin' })
+ await syncOk()
+
+ expect(await orgMember(email)).toMatchObject({ role: 'admin' })
+ })
+
+ it('links a member added by hand who is in Pocket ID and keeps their projects', async () => {
+ const user = await createPocketIdUser('linked')
+ await user1Api.organizations.addMember({ organizationId: orgId, email: user.email, role: 'admin' })
+ const project = await projectWithRole({ email: user.email, label: 'linked' })
+
+ await grantAccess(user)
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toMatchObject({ active: true })
+ expect(await orgMember(user.email)).toMatchObject({ role: 'admin' })
+ expect((await projectMember(project.goalId, user.email))?.roles).toEqual([project.roleId])
+ })
+
+ it('removes a member that another provider connected and Pocket ID does not know', async () => {
+ const email = emailFor('foreign')
+ await user1Api.organizations.addMember({ organizationId: orgId, email, role: 'member' })
+ // Another provider looks the member up by userName, which connects them to SCIM without a Pocket ID externalId
+ expect(await scimGet(`/Users?filter=${encodeURIComponent(`userName eq "${email}"`)}`)).toMatchObject({ totalResults: 1 })
+
+ await syncOk()
+
+ expect(await scimUserByEmail(email)).toBeUndefined()
+ expect(await orgMember(email)).toBeUndefined()
+ })
+
+ it('replaces a member that another provider connected with the Pocket ID user of the same email', async () => {
+ const user = await createPocketIdUser('takeover')
+ await user1Api.organizations.addMember({ organizationId: orgId, email: user.email, role: 'admin' })
+ const project = await projectWithRole({ email: user.email, label: 'takeover' })
+ await scimGet(`/Users?filter=${encodeURIComponent(`userName eq "${user.email}"`)}`)
+ await grantAccess(user)
+
+ // The create is refused because the email is taken, and the foreign record is deleted in the same sync
+ const first = await pocketId.sync(providerId)
+ expect(first.status).not.toBe(200)
+ expect(await scimUserByEmail(user.email)).toBeUndefined()
+ expect(await orgMember(user.email)).toBeUndefined()
+
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toMatchObject({ active: true })
+ expect(await orgMember(user.email)).toMatchObject({ role: 'member' })
+ expect(await projectMember(project.goalId, user.email)).toBeUndefined()
+ })
+
+ it('changes nothing when nothing changed in Pocket ID', async () => {
+ const user = await createPocketIdUser('stable')
+ await grantAccess(user)
+ await syncOk()
+ const before = await scimUserByExternalId(user.id)
+
+ await syncOk()
+
+ expect(await scimUserByExternalId(user.id)).toEqual(before)
+ })
+})
+
+describe('SCIM with Pocket ID: groups', () => {
+ it('provisions an allowed group with its members', async () => {
+ const users = await usersWithAccess(2, 'member')
+ const friendlyName = unique('Designers')
+ const id = await createAllowedGroup(users, friendlyName)
+ await syncOk()
+
+ expect(await scimGroupByExternalId(id)).toMatchObject({ displayName: friendlyName, externalId: id })
+ expect(await scimGroupMembers(id)).toEqual(await scimIdsOf(users))
+ })
+
+ it('does not provision a group the application does not allow', async () => {
+ const id = await pocketId.createGroup({ name: unique('hidden'), friendlyName: unique('Hidden') })
+ allowedGroups.push(id)
+ await pocketId.setAllowedGroups({ clientId, groupIds: [groupId, ...allowedGroups.filter((group) => group !== id)] })
+ await syncOk()
+
+ expect(await scimGroupByExternalId(id)).toBeUndefined()
+ await disallowGroup(id)
+ })
+
+ it('applies membership changes made on the group page', async () => {
+ const [first, second, third] = await usersWithAccess(3, 'page')
+ const id = await createAllowedGroup([first, second])
+ await syncOk()
+
+ await nextSecondForGroup(id)
+ await pocketId.setGroupUsers({ groupId: id, userIds: [second.id, third.id] })
+ await syncOk()
+
+ expect(await scimGroupMembers(id)).toEqual(await scimIdsOf([second, third]))
+ })
+
+ it('applies a rename', async () => {
+ const id = await createAllowedGroup(await usersWithAccess(1, 'rename'))
+ await syncOk()
+
+ const renamed = unique('Renamed')
+ await nextSecondForGroup(id)
+ await pocketId.renameGroup({ id, name: unique('renamed'), friendlyName: renamed })
+ await syncOk()
+
+ expect(await scimGroupByExternalId(id)).toMatchObject({ displayName: renamed })
+ })
+
+ it('adds a person who joins a group linked to a project to that project with the default role', async () => {
+ const [member, joining] = await usersWithAccess(2, 'linked')
+ const friendlyName = unique('Linked')
+ const id = await createAllowedGroup([member], friendlyName)
+ await syncOk()
+
+ const goal = await user1Api.goals.createGoal({ name: `Pocket ID ${unique('linked')}`, organizationId: orgId })
+ const role = goal && await user1Api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: unique('role') })
+ if (!goal || !role) throw new Error('Failed to prepare the project')
+ const overview = await user1Api.sso.fetchScimGroups(configId)
+ const group = overview.groups.find((g) => g.displayName === friendlyName)
+ if (!group) throw new Error('The group is missing from the overview')
+ await user1Api.sso.linkScimGroupProject({ configId, groupId: group.id, goalId: goal.id, roleId: role.id })
+ expect((await projectMember(goal.id, member.email))?.roles).toEqual([role.id])
+
+ await nextSecondForGroup(id)
+ await pocketId.setGroupUsers({ groupId: id, userIds: [member.id, joining.id] })
+ await syncOk()
+
+ expect((await projectMember(goal.id, joining.email))?.roles).toEqual([role.id])
+ })
+
+ it('applies a membership added on the user page', async () => {
+ const [member, joining] = await usersWithAccess(2, 'join')
+ const id = await createAllowedGroup([member])
+ await syncOk()
+
+ await nextSecondForGroup(id)
+ await pocketId.setUserGroups({ userId: joining.id, groupIds: [groupId, id] })
+ await syncOk()
+
+ expect(await scimGroupMembers(id)).toEqual(await scimIdsOf([member, joining]))
+ })
+
+ // Skipped: a Pocket ID bug (v2.18.0), not ours. UserService.UpdateUserGroups (user_service.go:629-635)
+ // bumps UpdatedAt only of the groups the user is put into, not of the ones they leave, so the sync
+ // sees no change in the left group and never sends its PUT. Removing the user on the group page works.
+ it.skip('applies a membership removed on the user page', async () => {
+ const [member, leaving] = await usersWithAccess(2, 'leave')
+ const id = await createAllowedGroup([member, leaving])
+ await syncOk()
+
+ await nextSecondForGroup(id)
+ await pocketId.setUserGroups({ userId: leaving.id, groupIds: [groupId] })
+ await syncOk()
+
+ expect(await scimGroupMembers(id)).toEqual(await scimIdsOf([member]))
+ })
+
+ it('drops a deleted user from the groups', async () => {
+ const [member, deleted] = await usersWithAccess(2, 'gone')
+ const id = await createAllowedGroup([member, deleted])
+ await syncOk()
+
+ groupMembers.splice(groupMembers.indexOf(deleted.id), 1)
+ await pocketId.deleteUser(deleted.id)
+ await syncOk()
+
+ expect(await scimGroupMembers(id)).toEqual(await scimIdsOf([member]))
+ })
+
+ it('removes a group the application no longer allows and keeps its members', async () => {
+ const users = await usersWithAccess(1, 'disallowed')
+ const id = await createAllowedGroup(users)
+ await syncOk()
+
+ await disallowGroup(id)
+ await syncOk()
+
+ expect(await scimGroupByExternalId(id)).toBeUndefined()
+ expect(await scimUserByExternalId(users[0].id)).toMatchObject({ active: true })
+ })
+
+ it('removes a group deleted in Pocket ID', async () => {
+ const id = await createAllowedGroup(await usersWithAccess(1, 'deleted-group'))
+ await syncOk()
+
+ allowedGroups.splice(allowedGroups.indexOf(id), 1)
+ await pocketId.deleteGroup(id)
+ await syncOk()
+
+ expect(await scimGroupByExternalId(id)).toBeUndefined()
+ })
+
+ it('provisions two groups that share a friendly name', async () => {
+ const friendlyName = unique('Shared')
+ const first = await createAllowedGroup(await usersWithAccess(1, 'shared'), friendlyName)
+ const second = await createAllowedGroup(await usersWithAccess(1, 'shared'), friendlyName)
+ await syncOk()
+
+ const [firstGroup, secondGroup] = [await scimGroupByExternalId(first), await scimGroupByExternalId(second)]
+ expect(firstGroup).toMatchObject({ displayName: friendlyName })
+ expect(secondGroup).toMatchObject({ displayName: friendlyName })
+ expect(secondGroup.id).not.toBe(firstGroup.id)
+ })
+})
+
+describe('SCIM with Pocket ID: many users', () => {
+ // We answer at most 200 users per page while Pocket ID asks for 1000, so it has to walk several pages
+ it(`provisions ${BULK_USERS} users and sees all of them on the next sync`, async () => {
+ const users: PocketIdUser[] = []
+ await inBatches([...Array(BULK_USERS).keys()], async () => {
+ users.push(await createPocketIdUser('bulk'))
+ })
+ groupMembers.push(...users.map((user) => user.id))
+ await pocketId.setGroupUsers({ groupId, userIds: groupMembers })
+
+ await syncOk()
+
+ const provisioned = await allScimUsers()
+ const ids = new Set(users.map((user) => user.id))
+ const bulk = provisioned.filter((user) => ids.has(user.externalId))
+ expect(bulk).toHaveLength(BULK_USERS)
+ expect(new Set(provisioned.map((user) => user.id)).size).toBe(provisioned.length)
+
+ // A user missed on a page would be created again and refused with 409, which fails the sync
+ await syncOk()
+
+ expect(await allScimUsers()).toEqual(provisioned)
+ }, 180_000)
+})
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.types.ts
new file mode 100644
index 0000000..c6d9f71
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim-pocket-id.test.types.ts
@@ -0,0 +1,9 @@
+export type PocketIdTestProjectArgs = {
+ email: string
+ label: string
+}
+
+export type PocketIdTestProject = {
+ goalId: number
+ roleId: number
+}
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts b/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts
index 34537c7..b0914f9 100644
--- a/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts
@@ -2,25 +2,71 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import axios from 'axios'
import { TvApi } from '@/tv'
import { initApi, API_URL } from './init-api'
+import type { ScimTestRequestArgs, ScimTestUserArgs } from './scim.test.types'
+
+const USER_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:User'
+const GROUP_SCHEMA = 'urn:ietf:params:scim:schemas:core:2.0:Group'
+const PATCH_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:PatchOp'
+const ERROR_SCHEMA = 'urn:ietf:params:scim:api:messages:2.0:Error'
+const DOMAIN = 'scim-e2e.example'
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
+
+const scimUrl = `${API_URL}/scim/v2`
+const run = `${Date.now()}${Math.floor(Math.random() * 1000)}`
+let seq = 0
let user1Api: TvApi
let user1Email: string
let user2Email: string
let deleteAllGoals: () => Promise<void>
-
let testOrgId: number
-let scimToken: string
+let otherOrgId: number
let configId: number
+let otherConfigId: number
+let scimToken: string
+let otherScimToken: string
+
+const unique = (label: string) => `${label}-${run}-${seq++}`
+const emailFor = (label: string) => `${unique(label)}@${DOMAIN}`
+
+async function scim(args: ScimTestRequestArgs) {
+ return axios.request({
+ method: args.method,
+ url: `${scimUrl}${args.path}`,
+ data: args.body,
+ headers: {
+ Authorization: `Bearer ${args.token ?? scimToken}`,
+ 'Content-Type': args.contentType ?? 'application/scim+json',
+ },
+ validateStatus: () => true,
+ })
+}
-const scimUrl = `${API_URL}/scim/v2`
+async function createUser(args: ScimTestUserArgs = {}) {
+ const email = args.email ?? emailFor('user')
+ const res = await scim({
+ method: 'post',
+ path: '/Users',
+ body: {
+ schemas: [USER_SCHEMA],
+ userName: args.userName ?? email,
+ emails: [{ value: email, type: 'work', primary: true }],
+ ...(args.externalId ? { externalId: args.externalId } : {}),
+ ...(args.displayName ? { displayName: args.displayName } : {}),
+ ...(args.active !== undefined ? { active: args.active } : {}),
+ },
+ })
+ expect(res.status).toBe(201)
+ return res.data
+}
-function scimHeaders() {
- return {
- Authorization: `Bearer ${scimToken}`,
- 'Content-Type': 'application/json',
- }
+async function orgMember(email: string) {
+ const members = await user1Api.organizations.fetchMembers(testOrgId)
+ return members.find((m) => m.email === email.toLowerCase())
}
+const filter = (expression: string) => scim({ method: 'get', path: `/Users?filter=${encodeURIComponent(expression)}` })
+
beforeAll(async () => {
const init = await initApi()
user1Api = init.$tvApi
@@ -30,285 +76,637 @@ beforeAll(async () => {
const org = await user1Api.organizations.create({ name: 'SCIM Test Org' })
testOrgId = org.id
-
const config = await user1Api.sso.createConfig({
organizationId: testOrgId,
protocol: 'saml',
displayName: 'SCIM SAML',
- emailDomainRestriction: 'scim-e2e.example',
+ emailDomainRestriction: DOMAIN,
samlEntryPoint: 'https://idp.example.com/saml/sso',
samlIssuer: 'taskview-scim-e2e',
samlCert: 'MIICmzCCAYMCBgF...',
samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
+ defaultOrgRole: 'admin',
})
configId = config.id
+ scimToken = (await user1Api.sso.generateScimToken(configId)).token
- const tokenResult = await user1Api.sso.generateScimToken(configId)
- scimToken = tokenResult.token
-
- await user1Api.organizations.addMember({
- organizationId: testOrgId,
- email: user2Email,
- role: 'member',
+ const otherOrg = await user1Api.organizations.create({ name: 'SCIM Other Org' })
+ otherOrgId = otherOrg.id
+ const otherConfig = await user1Api.sso.createConfig({
+ organizationId: otherOrgId,
+ protocol: 'saml',
+ displayName: 'SCIM SAML other',
+ emailDomainRestriction: 'scim-e2e-other.example',
+ samlEntryPoint: 'https://idp.example.com/saml/sso',
+ samlIssuer: 'taskview-scim-e2e-other',
+ samlCert: 'MIICmzCCAYMCBgF...',
+ samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
})
+ otherConfigId = otherConfig.id
+ otherScimToken = (await user1Api.sso.generateScimToken(otherConfigId)).token
+
+ await user1Api.organizations.addMember({ organizationId: testOrgId, email: user2Email, role: 'member' })
})
afterAll(async () => {
await user1Api.sso.deleteConfig(configId).catch(() => {})
+ await user1Api.sso.deleteConfig(otherConfigId).catch(() => {})
await user1Api.organizations.delete(testOrgId).catch(() => {})
+ await user1Api.organizations.delete(otherOrgId).catch(() => {})
await deleteAllGoals()
})
describe('SCIM: authentication', () => {
- it('should reject request without token', async () => {
+ it('rejects a request without token', async () => {
const res = await axios.get(`${scimUrl}/Users`, { validateStatus: () => true })
expect(res.status).toBe(401)
})
- it('should reject request with invalid token', async () => {
- const res = await axios.get(`${scimUrl}/Users`, {
- headers: { Authorization: 'Bearer invalid_token' },
- validateStatus: () => true,
- })
+ it('rejects an invalid token', async () => {
+ const res = await scim({ method: 'get', path: '/Users', token: 'invalid_token' })
expect(res.status).toBe(401)
})
- it('should accept request with valid token', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
+ it('answers with application/scim+json', async () => {
+ const res = await scim({ method: 'get', path: '/Users' })
expect(res.status).toBe(200)
+ expect(res.headers['content-type']).toContain('application/scim+json')
expect(res.data.schemas).toContain('urn:ietf:params:scim:api:messages:2.0:ListResponse')
})
})
-describe('SCIM: list users', () => {
- it('should return organization members', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
+describe('SCIM: discovery', () => {
+ it('describes the service provider', async () => {
+ const res = await scim({ method: 'get', path: '/ServiceProviderConfig' })
+ expect(res.status).toBe(200)
+ expect(res.data.patch.supported).toBe(true)
+ expect(res.data.filter.supported).toBe(true)
+ expect(res.data.bulk.supported).toBe(false)
+ expect(res.data.authenticationSchemes[0].type).toBe('oauthbearertoken')
+ })
+
+ it('lists the User and Group resource types and schemas', async () => {
+ const types = await scim({ method: 'get', path: '/ResourceTypes' })
+ expect(types.data.Resources.map((r: any) => r.id)).toEqual(['User', 'Group'])
+ expect((await scim({ method: 'get', path: '/ResourceTypes/Group' })).data.endpoint).toBe('/Groups')
- expect(res.data.totalResults).toBeGreaterThan(0)
- expect(res.data.Resources).toBeTruthy()
+ const schemas = await scim({ method: 'get', path: '/Schemas' })
+ expect(schemas.data.Resources.map((r: any) => r.id)).toEqual([USER_SCHEMA, GROUP_SCHEMA])
+ expect(schemas.data.Resources[0].attributes.map((a: any) => a.name)).toEqual(
+ expect.arrayContaining(['userName', 'externalId', 'emails', 'active']),
+ )
+ expect(schemas.data.Resources[1].attributes.map((a: any) => a.name)).toEqual(['displayName', 'externalId', 'members'])
- const emails = res.data.Resources.map((r: any) => r.userName)
- expect(emails).toContain(user1Email)
- expect(emails).toContain(user2Email)
+ expect((await scim({ method: 'get', path: `/Schemas/${USER_SCHEMA}` })).status).toBe(200)
+ expect((await scim({ method: 'get', path: `/Schemas/${GROUP_SCHEMA}` })).status).toBe(200)
})
- it('should return SCIM formatted users', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const user = res.data.Resources[0]
+ it('answers unknown endpoints with a SCIM 404', async () => {
+ const res = await scim({ method: 'get', path: '/Teams' })
+ expect(res.status).toBe(404)
+ expect(res.data.schemas).toContain(ERROR_SCHEMA)
+ })
- expect(user.schemas).toContain('urn:ietf:params:scim:schemas:core:2.0:User')
- expect(user.id).toBeTruthy()
- expect(user.userName).toBeTruthy()
- expect(user.emails).toBeTruthy()
- expect(user.active).toBe(true)
+ it('answers malformed JSON with a SCIM 400', async () => {
+ const res = await scim({ method: 'post', path: '/Users', body: '{"userName": ' })
+ expect(res.status).toBe(400)
+ expect(res.data.schemas).toContain(ERROR_SCHEMA)
+ expect(res.data.scimType).toBe('invalidSyntax')
})
})
-describe('SCIM: get user', () => {
- it('should return user by email', async () => {
- const res = await axios.get(`${scimUrl}/Users/${encodeURIComponent(user2Email)}`, {
- headers: scimHeaders(),
+describe('SCIM: create user', () => {
+ it('creates a user whose userName is not an email, with a stable uuid id', async () => {
+ const email = emailFor('jdoe')
+ const userName = unique('jdoe')
+ const res = await scim({
+ method: 'post',
+ path: '/Users',
+ body: { userName, emails: [{ value: email.toUpperCase(), type: 'work', primary: true }], externalId: unique('ext') },
})
- expect(res.status).toBe(200)
- expect(res.data.userName).toBe(user2Email)
- expect(res.data.active).toBe(true)
+ expect(res.status).toBe(201)
+ expect(res.data.id).toMatch(UUID)
+ expect(res.data.userName).toBe(userName)
+ expect(res.data.emails[0].value).toBe(email)
+ expect(res.data.meta.resourceType).toBe('User')
+ expect(res.headers.location).toBe(res.data.meta.location)
+ expect((await orgMember(email))?.role).toBe('admin')
+ })
+
+ it('creates a user from userName alone when it is an email', async () => {
+ const email = emailFor('only-username')
+ const res = await scim({ method: 'post', path: '/Users', body: { userName: email } })
+
+ expect(res.status).toBe(201)
+ expect(res.data.userName).toBe(email)
+ expect(await orgMember(email)).toBeTruthy()
+ })
+
+ it('rejects a user without any email', async () => {
+ const res = await scim({ method: 'post', path: '/Users', body: { userName: unique('no-email') } })
+ expect(res.status).toBe(400)
+ expect(res.data.scimType).toBe('invalidValue')
+ })
+
+ it('rejects an email outside the SSO domain', async () => {
+ const res = await scim({ method: 'post', path: '/Users', body: { userName: `${unique('outsider')}@elsewhere.example` } })
+ expect(res.status).toBe(400)
+ expect(res.data.scimType).toBe('invalidValue')
})
- it('should return 404 for unknown user', async () => {
- const res = await axios.get(`${scimUrl}/Users/${encodeURIComponent('[email protected]')}`, {
- headers: scimHeaders(),
- validateStatus: () => true,
+ it('returns 409 uniqueness for a duplicate userName in another case', async () => {
+ const user = await createUser({ userName: unique('Dup.User') })
+ const res = await scim({
+ method: 'post',
+ path: '/Users',
+ body: { userName: user.userName.toUpperCase(), emails: [{ value: emailFor('dup-other') }] },
})
- expect(res.status).toBe(404)
+ expect(res.status).toBe(409)
+ expect(res.data.scimType).toBe('uniqueness')
+ })
+
+ it('creates an inactive user without organization access', async () => {
+ const email = emailFor('inactive')
+ const user = await createUser({ email, active: false })
+
+ expect(user.active).toBe(false)
+ expect(await orgMember(email)).toBeUndefined()
})
})
-describe('SCIM: deactivate user', () => {
- it('should deactivate user (remove from org)', async () => {
- const res = await axios.patch(
- `${scimUrl}/Users/${encodeURIComponent(user2Email)}`,
- {
- Operations: [{ op: 'replace', path: 'active', value: false }],
- },
- { headers: scimHeaders() },
- )
+describe('SCIM: filter', () => {
+ it('finds a user by userName regardless of case', async () => {
+ const user = await createUser({ userName: unique('Case.User') })
+ const res = await filter(`USERNAME Eq "${user.userName.toLowerCase()}"`)
expect(res.status).toBe(200)
- expect(res.data.active).toBe(false)
+ expect(res.data.totalResults).toBe(1)
+ expect(res.data.Resources[0].id).toBe(user.id)
})
- it('should not appear in user list after deactivation', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const emails = res.data.Resources.map((r: any) => r.userName)
+ it('finds a user by externalId and by work email', async () => {
+ const externalId = unique('ext')
+ const user = await createUser({ userName: unique('by-ext'), externalId })
+
+ const byExternalId = await filter(`externalId eq "${externalId}"`)
+ expect(byExternalId.data.Resources.map((r: any) => r.id)).toEqual([user.id])
- expect(emails).not.toContain(user2Email)
+ const byEmail = await filter(`emails[type eq "work"].value eq "${user.emails[0].value}"`)
+ expect(byEmail.data.Resources.map((r: any) => r.id)).toEqual([user.id])
})
- it('should return 404 when getting deactivated user', async () => {
- const res = await axios.get(`${scimUrl}/Users/${encodeURIComponent(user2Email)}`, {
- headers: scimHeaders(),
- validateStatus: () => true,
- })
+ it('returns an empty list for an unknown user', async () => {
+ const res = await filter(`userName eq "${unique('nobody')}"`)
+ expect(res.status).toBe(200)
+ expect(res.data.totalResults).toBe(0)
+ expect(res.data.Resources).toEqual([])
+ })
+
+ it('rejects unsupported filters with invalidFilter', async () => {
+ for (const expression of ['displayName co "x"', 'userName eq "a" and active eq true']) {
+ const res = await filter(expression)
+ expect(res.status).toBe(400)
+ expect(res.data.scimType).toBe('invalidFilter')
+ }
+ })
+
+ it('links an existing organization member found by an email of the SSO domain', async () => {
+ const email = emailFor('member')
+ await user1Api.organizations.addMember({ organizationId: testOrgId, email, role: 'member' })
+
+ const res = await filter(`userName eq "${email}"`)
+ expect(res.data.totalResults).toBe(1)
+ expect(res.data.Resources[0].emails[0].value).toBe(email)
+
+ const again = await scim({ method: 'get', path: `/Users/${encodeURIComponent(res.data.Resources[0].id)}` })
+ expect(again.status).toBe(200)
+ })
+
+ it('never links members outside the SSO domain, the owner included', async () => {
+ for (const email of [user1Email, user2Email]) {
+ const res = await filter(`userName eq "${email}"`)
+ expect(res.data.totalResults).toBe(0)
+ }
+ })
+
+ it('rejects an oversized filter', async () => {
+ const res = await filter(`userName eq "${'a'.repeat(600)}"`)
+ expect(res.status).toBe(400)
+ expect(res.data.scimType).toBe('invalidFilter')
+ })
+})
+
+describe('SCIM: list and pagination', () => {
+ it('pages with a stable order', async () => {
+ for (let i = 0; i < 3; i++) await createUser()
+
+ const first = await scim({ method: 'get', path: '/Users?startIndex=1&count=2' })
+ expect(first.data.startIndex).toBe(1)
+ expect(first.data.itemsPerPage).toBe(2)
+ expect(first.data.totalResults).toBeGreaterThanOrEqual(3)
+
+ const second = await scim({ method: 'get', path: '/Users?startIndex=3&count=2' })
+ const firstIds = first.data.Resources.map((r: any) => r.id)
+ for (const r of second.data.Resources) expect(firstIds).not.toContain(r.id)
+ })
+
+ it('does not show users of another organization', async () => {
+ const user = await createUser()
+ const res = await scim({ method: 'get', path: `/Users/${user.id}`, token: otherScimToken })
expect(res.status).toBe(404)
})
})
-describe('SCIM: reactivate user', () => {
- it('should reactivate user (add back to org)', async () => {
- const res = await axios.patch(
- `${scimUrl}/Users/${encodeURIComponent(user2Email)}`,
- {
- Operations: [{ op: 'replace', path: 'active', value: true }],
- },
- { headers: scimHeaders() },
- )
+describe('SCIM: deactivate and reactivate', () => {
+ it('deactivates with an Entra-style PATCH and keeps the user retrievable', async () => {
+ const user = await createUser()
+ const email = user.emails[0].value
+ const res = await scim({
+ method: 'patch',
+ path: `/Users/${user.id}`,
+ body: { schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'], Operations: [{ op: 'Replace', path: 'active', value: 'False' }] },
+ })
+ expect(res.status).toBe(200)
+ expect(res.data.active).toBe(false)
+ expect(await orgMember(email)).toBeUndefined()
+
+ const get = await scim({ method: 'get', path: `/Users/${user.id}` })
+ expect(get.status).toBe(200)
+ expect(get.data.active).toBe(false)
+ })
+
+ it('restores the organization role and project access on reactivation', async () => {
+ const user = await createUser()
+ const email = user.emails[0].value
+
+ const goal = await user1Api.goals.createGoal({ name: `SCIM goal ${unique('g')}`, organizationId: testOrgId })
+ if (!goal) throw new Error('Failed to create goal')
+ const collaborator = await user1Api.collaboration.inviteUserToGoal({ goalId: goal.id, email })
+ if (!collaborator) throw new Error('Failed to invite collaborator')
+ const role = await user1Api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: `SCIM role ${unique('r')}` })
+ if (!role) throw new Error('Failed to create role')
+ await user1Api.collaboration.toggleUserRoles({ goalId: goal.id, userId: collaborator.id, roles: [role.id] })
+
+ await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'replace', path: 'active', value: false }] } })
+ expect((await user1Api.collaboration.fetchUsersForGoal(goal.id)).map((u) => u.email)).not.toContain(email)
+
+ const res = await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'replace', value: { active: true } }] } })
expect(res.status).toBe(200)
expect(res.data.active).toBe(true)
+ expect((await orgMember(email))?.role).toBe('admin')
+
+ const restored = (await user1Api.collaboration.fetchUsersForGoal(goal.id)).find((u) => u.email === email)
+ expect(restored).toBeTruthy()
+ expect(restored?.roles).toContain(role.id)
})
- it('should appear in user list after reactivation', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const emails = res.data.Resources.map((r: any) => r.userName)
+ it('drops the project role links on deactivation', async () => {
+ const user = await createUser()
+ const email = user.emails[0].value
+
+ const goal = await user1Api.goals.createGoal({ name: `SCIM goal ${unique('g')}`, organizationId: testOrgId })
+ const foreignGoal = await user1Api.goals.createGoal({ name: `SCIM foreign ${unique('g')}`, organizationId: otherOrgId })
+ if (!goal || !foreignGoal) throw new Error('Failed to create goals')
+ // A project of another organization keeps the collaborator row alive after the deactivation
+ await user1Api.collaboration.inviteUserToGoal({ goalId: foreignGoal.id, email })
+ const collaborator = await user1Api.collaboration.inviteUserToGoal({ goalId: goal.id, email })
+ const role = await user1Api.collaboration.createRoleForGoal({ goalId: goal.id, roleName: `SCIM role ${unique('r')}` })
+ if (!collaborator || !role) throw new Error('Failed to prepare collaborator')
+ await user1Api.collaboration.toggleUserRoles({ goalId: goal.id, userId: collaborator.id, roles: [role.id] })
+
+ await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'replace', path: 'active', value: false }] } })
+ await user1Api.collaboration.inviteUserToGoal({ goalId: goal.id, email })
+
+ const invitedAgain = (await user1Api.collaboration.fetchUsersForGoal(goal.id)).find((u) => u.email === email)
+ expect(invitedAgain?.id).toBe(collaborator.id)
+ expect(invitedAgain?.roles).toEqual([])
+ })
+
+ it('deactivates and reactivates through PUT (Okta)', async () => {
+ const user = await createUser({ displayName: 'Before' })
+ const email = user.emails[0].value
+ const body = { userName: user.userName, emails: [{ value: email, primary: true }], active: false }
+
+ const off = await scim({ method: 'put', path: `/Users/${user.id}`, body })
+ expect(off.status).toBe(200)
+ expect(off.data.active).toBe(false)
+ expect(off.data.displayName).toBeUndefined()
+ expect(await orgMember(email)).toBeUndefined()
- expect(emails).toContain(user2Email)
+ const on = await scim({ method: 'put', path: `/Users/${user.id}`, body: { ...body, active: true } })
+ expect(on.data.active).toBe(true)
+ expect(await orgMember(email)).toBeTruthy()
})
+
})
-describe('SCIM: create user', () => {
- const newUserEmail = '[email protected]'
-
- it('should create user via SCIM', async () => {
- const res = await axios.post(
- `${scimUrl}/Users`,
- {
- schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
- userName: newUserEmail,
- emails: [{ value: newUserEmail, primary: true }],
- active: true,
+describe('SCIM: update attributes', () => {
+ it('applies supported attributes and ignores unknown ones', async () => {
+ const user = await createUser()
+ const res = await scim({
+ method: 'patch',
+ path: `/Users/${user.id}`,
+ body: {
+ Operations: [
+ { op: 'add', path: 'displayName', value: 'Jane Doe' },
+ { op: 'replace', path: 'name.givenName', value: 'Jane' },
+ { op: 'replace', path: 'externalId', value: unique('ext') },
+ { op: 'replace', path: 'title', value: 'Engineer' },
+ ],
},
- { headers: scimHeaders() },
- )
+ })
- expect(res.status).toBe(201)
- expect(res.data.userName).toBe(newUserEmail)
+ expect(res.status).toBe(200)
+ expect(res.data.displayName).toBe('Jane Doe')
+ expect(res.data.name.givenName).toBe('Jane')
+ expect(res.data.title).toBeUndefined()
})
- it('should appear in user list', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const emails = res.data.Resources.map((r: any) => r.userName)
+ it('rejects a userName that another user already has', async () => {
+ const first = await createUser()
+ const second = await createUser()
+ const res = await scim({ method: 'patch', path: `/Users/${second.id}`, body: { Operations: [{ op: 'replace', path: 'userName', value: first.userName }] } })
- expect(emails).toContain(newUserEmail)
+ expect(res.status).toBe(409)
+ expect(res.data.scimType).toBe('uniqueness')
})
-})
-describe('SCIM: delete user', () => {
- beforeAll(async () => {
- await axios.patch(
- `${scimUrl}/Users/${encodeURIComponent(user2Email)}`,
- { Operations: [{ op: 'replace', path: 'active', value: true }] },
- { headers: scimHeaders() },
- ).catch(() => {})
- })
-
- it('should delete user from org', async () => {
- const res = await axios.delete(
- `${scimUrl}/Users/${encodeURIComponent(user2Email)}`,
- { headers: scimHeaders() },
- )
+ it('validates PATCH requests', async () => {
+ const user = await createUser()
- expect(res.status).toBe(204)
- })
+ const empty = await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [] } })
+ expect(empty.status).toBe(400)
- it('should not appear in user list after delete', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const emails = res.data.Resources.map((r: any) => r.userName)
+ const badOp = await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'move', path: 'active', value: false }] } })
+ expect(badOp.status).toBe(400)
- expect(emails).not.toContain(user2Email)
+ const unknown = await scim({ method: 'patch', path: `/Users/${unique('missing')}`, body: { Operations: [{ op: 'replace', path: 'active', value: false }] } })
+ expect(unknown.status).toBe(404)
})
- it('should return 404 for already deleted user', async () => {
- const res = await axios.delete(
- `${scimUrl}/Users/${encodeURIComponent(user2Email)}`,
- { headers: scimHeaders(), validateStatus: () => true },
- )
- expect(res.status).toBe(404)
+ it('accepts PUT and PATCH sent as application/json too', async () => {
+ const user = await createUser()
+ const res = await scim({
+ method: 'patch',
+ path: `/Users/${user.id}`,
+ contentType: 'application/json',
+ body: { Operations: [{ op: 'replace', path: 'displayName', value: 'Plain JSON' }] },
+ })
+ expect(res.data.displayName).toBe('Plain JSON')
})
})
-describe('SCIM: isolation between organizations', () => {
- it('should not see users from other organizations', async () => {
- const res = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- const emails: string[] = res.data.Resources.map((r: any) => r.userName)
-
- for (const email of emails) {
- const member = await user1Api.organizations.fetchMembers(testOrgId)
- .then(members => members.find(m => m.email === email))
- expect(member).toBeTruthy()
+describe('SCIM: security', () => {
+ it('refuses a token whose SSO domain is not verified', async () => {
+ const org = await user1Api.organizations.create({ name: 'SCIM Unverified Org' })
+ try {
+ const config = await user1Api.sso.createConfig({
+ organizationId: org.id,
+ protocol: 'saml',
+ displayName: 'SCIM unverified',
+ emailDomainRestriction: `${unique('unverified')}.example`,
+ samlEntryPoint: 'https://idp.example.com/saml/sso',
+ samlIssuer: 'taskview-scim-e2e-unverified',
+ samlCert: 'MIICmzCCAYMCBgF...',
+ samlCallbackUrl: `${API_URL}/module/sso/callback/0`,
+ })
+ const { token } = await user1Api.sso.generateScimToken(config.id)
+
+ const res = await scim({ method: 'get', path: '/Users', token })
+ expect(res.status).toBe(403)
+ expect(res.data.schemas).toContain(ERROR_SCHEMA)
+ } finally {
+ await user1Api.organizations.delete(org.id).catch(() => {})
}
})
-})
-describe('SCIM: application/scim+json content type (RFC 7644 §3.1)', () => {
- const scimJsonHeaders = () => ({
- Authorization: `Bearer ${scimToken}`,
- 'Content-Type': 'application/scim+json',
+ it('cannot provision or take over an account outside the SSO domain', async () => {
+ const res = await scim({ method: 'post', path: '/Users', body: { userName: user2Email } })
+ expect(res.status).toBe(400)
+ expect((await filter(`emails.value eq "${user2Email}"`)).data.totalResults).toBe(0)
})
- it('should create user with userName only', async () => {
- const email = `scim-json-create-${Date.now()}@scim-e2e.example`
+ it('moves only this organization project access on an email change', async () => {
+ const email = emailFor('mover')
+ const user = await createUser({ email })
+
+ const ownGoal = await user1Api.goals.createGoal({ name: `SCIM own ${unique('g')}`, organizationId: testOrgId })
+ const foreignGoal = await user1Api.goals.createGoal({ name: `SCIM foreign ${unique('g')}`, organizationId: otherOrgId })
+ if (!ownGoal || !foreignGoal) throw new Error('Failed to create goals')
+ await user1Api.organizations.addMember({ organizationId: otherOrgId, email, role: 'member' })
+ const own = await user1Api.collaboration.inviteUserToGoal({ goalId: ownGoal.id, email })
+ await user1Api.collaboration.inviteUserToGoal({ goalId: foreignGoal.id, email })
+ if (!own) throw new Error('Failed to invite collaborator')
+ const role = await user1Api.collaboration.createRoleForGoal({ goalId: ownGoal.id, roleName: `SCIM role ${unique('r')}` })
+ if (!role) throw new Error('Failed to create role')
+ await user1Api.collaboration.toggleUserRoles({ goalId: ownGoal.id, userId: own.id, roles: [role.id] })
+
+ const renamed = emailFor('renamed')
+ const res = await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'replace', path: 'emails[type eq "work"].value', value: renamed }] } })
+ expect(res.status).toBe(200)
+ expect(res.data.emails[0].value).toBe(renamed)
+
+ expect(await orgMember(email)).toBeUndefined()
+ expect(await orgMember(renamed)).toBeTruthy()
+ const ownUsers = await user1Api.collaboration.fetchUsersForGoal(ownGoal.id)
+ expect(ownUsers.find((u) => u.email === renamed)?.roles).toContain(role.id)
+ expect(ownUsers.map((u) => u.email)).not.toContain(email)
+
+ const foreignUsers = await user1Api.collaboration.fetchUsersForGoal(foreignGoal.id)
+ expect(foreignUsers.map((u) => u.email)).toContain(email)
+ expect(foreignUsers.map((u) => u.email)).not.toContain(renamed)
+ const otherMembers = await user1Api.organizations.fetchMembers(otherOrgId)
+ expect(otherMembers.map((m) => m.email)).toContain(email)
+ })
- const res = await axios.post(`${scimUrl}/Users`, { userName: email }, {
- headers: scimJsonHeaders(),
- validateStatus: () => true,
- })
+ it('rejects an email change to an address outside the SSO domain', async () => {
+ const user = await createUser()
+ const res = await scim({ method: 'patch', path: `/Users/${user.id}`, body: { Operations: [{ op: 'replace', path: 'emails', value: [{ value: user2Email, primary: true }] }] } })
+ expect(res.status).toBe(400)
+ })
+})
+describe('SCIM: groups', () => {
+ const createGroup = async (body: Record<string, unknown>) => {
+ const res = await scim({ method: 'post', path: '/Groups', body: { schemas: [GROUP_SCHEMA], ...body } })
expect(res.status).toBe(201)
- expect(res.data.userName).toBe(email)
- expect(res.headers['content-type']).toContain('application/scim+json')
+ return res.data
+ }
+ const membersOf = async (id: string) => {
+ const res = await scim({ method: 'get', path: `/Groups/${id}` })
+ expect(res.status).toBe(200)
+ return (res.data.members ?? []).map((m: any) => m.value).sort()
+ }
+ const patchGroup = (id: string, Operations: unknown[]) =>
+ scim({ method: 'patch', path: `/Groups/${id}`, body: { schemas: [PATCH_SCHEMA], Operations } })
+
+ it('creates a group with members and returns them', async () => {
+ const user = await createUser({ displayName: 'Group Member' })
+ const externalId = unique('ext')
+ const res = await scim({
+ method: 'post',
+ path: '/Groups',
+ body: { schemas: [GROUP_SCHEMA], displayName: unique('Marketing'), externalId, members: [{ value: user.id }] },
+ })
+ expect(res.status).toBe(201)
+ expect(res.data.id).toMatch(UUID)
+ expect(res.data.externalId).toBe(externalId)
+ expect(res.headers.location).toBe(res.data.meta.location)
+ expect(res.data.meta.resourceType).toBe('Group')
+ expect(res.data.members).toEqual([{ value: user.id, display: 'Group Member', $ref: expect.stringMatching(new RegExp(`/scim/v2/Users/${user.id}$`)) }])
+ })
- const list = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })
- expect(list.data.Resources.map((r: any) => r.userName)).toContain(email)
+ it('creates a group without members the way Microsoft Entra ID does', async () => {
+ const group = await createGroup({ displayName: unique('Empty'), externalId: unique('ext'), meta: { resourceType: 'Group' } })
+ expect(group.members).toEqual([])
})
- it('should deactivate user', async () => {
- const email = `scim-json-deactivate-${Date.now()}@scim-e2e.example`
- await axios.post(`${scimUrl}/Users`, { userName: email }, { headers: scimHeaders() })
+ // RFC 7643 sets no uniqueness on displayName and Pocket ID sends friendly names that may repeat
+ it('keeps two groups with the same displayName apart and finds both by it', async () => {
+ const displayName = unique('Sales')
+ const first = await createGroup({ displayName, externalId: unique('ext') })
+ const second = await createGroup({ displayName: displayName.toUpperCase(), externalId: unique('ext') })
+ expect(second.id).not.toBe(first.id)
+
+ const expression = encodeURIComponent(`displayName eq "${displayName}"`)
+ const res = await scim({ method: 'get', path: `/Groups?filter=${expression}` })
+ expect(res.data.totalResults).toBe(2)
+ expect(res.data.Resources.map((group: any) => group.id)).toEqual([first.id, second.id])
+ })
- const res = await axios.patch(
- `${scimUrl}/Users/${encodeURIComponent(email)}`,
- {
- schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],
- Operations: [{ op: 'replace', path: 'active', value: false }],
- },
- { headers: scimJsonHeaders(), validateStatus: () => true },
- )
+ it('rejects a second group with the same externalId', async () => {
+ const externalId = unique('ext')
+ const first = await createGroup({ displayName: unique('Finance'), externalId })
+ const res = await scim({ method: 'post', path: '/Groups', body: { displayName: unique('Finance'), externalId } })
+ expect(res.status).toBe(409)
+ expect(res.data.scimType).toBe('uniqueness')
+
+ const other = await createGroup({ displayName: unique('Legal'), externalId: unique('ext') })
+ const renamed = await scim({ method: 'put', path: `/Groups/${other.id}`, body: { displayName: unique('Legal'), externalId } })
+ expect(renamed.status).toBe(409)
+ expect((await scim({ method: 'get', path: `/Groups/${first.id}` })).data.externalId).toBe(externalId)
+ })
+ it('finds a group by displayName regardless of case and leaves members out on request', async () => {
+ const user = await createUser()
+ const displayName = unique('Support')
+ const group = await createGroup({ displayName, members: [{ value: user.id }] })
+
+ const expression = encodeURIComponent(`displayName eq "${displayName.toLowerCase()}"`)
+ const res = await scim({ method: 'get', path: `/Groups?excludedAttributes=members&filter=${expression}` })
expect(res.status).toBe(200)
- expect(res.data.active).toBe(false)
+ expect(res.data.totalResults).toBe(1)
+ expect(res.data.Resources[0].id).toBe(group.id)
+ expect(res.data.Resources[0].members).toBeUndefined()
+
+ const single = await scim({ method: 'get', path: `/Groups/${group.id}?excludedAttributes=members` })
+ expect(single.data.members).toBeUndefined()
+
+ const byExternalId = await scim({ method: 'get', path: `/Groups?filter=${encodeURIComponent('externalId eq "missing"')}` })
+ expect(byExternalId.data.totalResults).toBe(0)
+
+ const unsupported = await scim({ method: 'get', path: `/Groups?filter=${encodeURIComponent('members eq "x"')}` })
+ expect(unsupported.status).toBe(400)
+ expect(unsupported.data.scimType).toBe('invalidFilter')
+ })
+
+ it('adds and removes members with Microsoft Entra ID PATCH requests', async () => {
+ const first = await createUser()
+ const second = await createUser()
+ const group = await createGroup({ displayName: unique('Engineering') })
+
+ const add = await patchGroup(group.id, [{ op: 'Add', path: 'members', value: [{ $ref: null, value: first.id }, { $ref: null, value: second.id }] }])
+ expect(add.status).toBe(204)
+ expect(await membersOf(group.id)).toEqual([first.id, second.id].sort())
+
+ const remove = await patchGroup(group.id, [{ op: 'Remove', path: 'members', value: [{ $ref: null, value: first.id }] }])
+ expect(remove.status).toBe(204)
+ expect(await membersOf(group.id)).toEqual([second.id])
+
+ const byFilter = await patchGroup(group.id, [{ op: 'remove', path: `members[value eq "${second.id}"]` }])
+ expect(byFilter.status).toBe(204)
+ expect(await membersOf(group.id)).toEqual([])
+ })
+
+ it('renames a group with a PATCH replace', async () => {
+ const group = await createGroup({ displayName: unique('Old') })
+ const renamed = unique('New')
- const get = await axios.get(`${scimUrl}/Users/${encodeURIComponent(email)}`, {
- headers: scimHeaders(),
- validateStatus: () => true,
+ const res = await patchGroup(group.id, [{ op: 'Replace', path: 'displayName', value: renamed }])
+ expect(res.status).toBe(204)
+ const found = await scim({ method: 'get', path: `/Groups?filter=${encodeURIComponent(`displayName eq "${renamed}"`)}` })
+ expect(found.data.Resources[0].id).toBe(group.id)
+
+ const removeName = await patchGroup(group.id, [{ op: 'remove', path: 'displayName' }])
+ expect(removeName.status).toBe(400)
+ })
+
+ it('replaces the whole group with PUT', async () => {
+ const kept = await createUser()
+ const dropped = await createUser()
+ const group = await createGroup({ displayName: unique('Ops'), members: [{ value: kept.id }, { value: dropped.id }] })
+ const displayName = unique('Ops renamed')
+
+ const res = await scim({ method: 'put', path: `/Groups/${group.id}`, body: { displayName, externalId: 'ops-ext', members: [{ value: kept.id }] } })
+ expect(res.status).toBe(200)
+ expect(res.data.displayName).toBe(displayName)
+ expect(res.data.externalId).toBe('ops-ext')
+ expect(res.data.members.map((m: any) => m.value)).toEqual([kept.id])
+ })
+
+ it('rejects members that are not users of this connection', async () => {
+ const group = await createGroup({ displayName: unique('Strict') })
+ const unknown = await patchGroup(group.id, [{ op: 'add', path: 'members', value: [{ value: 'no-such-user' }] }])
+ expect(unknown.status).toBe(400)
+ expect(unknown.data.scimType).toBe('invalidValue')
+
+ const foreign = await scim({
+ method: 'post',
+ path: '/Users',
+ token: otherScimToken,
+ body: { userName: `${unique('foreign')}@scim-e2e-other.example` },
})
- expect(get.status).toBe(404)
+ expect(foreign.status).toBe(201)
+ const cross = await patchGroup(group.id, [{ op: 'add', path: 'members', value: [{ value: foreign.data.id }] }])
+ expect(cross.status).toBe(400)
+ expect(await membersOf(group.id)).toEqual([])
})
- it('should reject PATCH without Operations instead of reporting success', async () => {
- const email = `scim-json-noops-${Date.now()}@scim-e2e.example`
- await axios.post(`${scimUrl}/Users`, { userName: email }, { headers: scimHeaders() })
+ it('keeps groups of another connection invisible', async () => {
+ const group = await createGroup({ displayName: unique('Private') })
+ const res = await scim({ method: 'get', path: `/Groups/${group.id}`, token: otherScimToken })
+ expect(res.status).toBe(404)
+ const list = await scim({ method: 'get', path: '/Groups', token: otherScimToken })
+ expect(list.data.Resources.map((g: any) => g.id)).not.toContain(group.id)
+ })
- const res = await axios.patch(
- `${scimUrl}/Users/${encodeURIComponent(email)}`,
- { schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'] },
- { headers: scimJsonHeaders(), validateStatus: () => true },
- )
+ it('drops a deleted user from their groups', async () => {
+ const user = await createUser()
+ const group = await createGroup({ displayName: unique('Leavers'), members: [{ value: user.id }] })
- expect(res.status).toBe(400)
- expect(res.data.schemas).toContain('urn:ietf:params:scim:api:messages:2.0:Error')
+ expect((await scim({ method: 'delete', path: `/Users/${user.id}` })).status).toBe(204)
+ expect(await membersOf(group.id)).toEqual([])
+ })
- const get = await axios.get(`${scimUrl}/Users/${encodeURIComponent(email)}`, { headers: scimHeaders() })
- expect(get.data.active).toBe(true)
+ it('deletes a group', async () => {
+ const group = await createGroup({ displayName: unique('Temp') })
+ expect((await scim({ method: 'delete', path: `/Groups/${group.id}` })).status).toBe(204)
+ expect((await scim({ method: 'get', path: `/Groups/${group.id}` })).status).toBe(404)
+ })
+})
+
+describe('SCIM: delete user', () => {
+ it('deletes the user and their organization access', async () => {
+ const user = await createUser()
+ const email = user.emails[0].value
+
+ const res = await scim({ method: 'delete', path: `/Users/${user.id}` })
+ expect(res.status).toBe(204)
+ expect(await orgMember(email)).toBeUndefined()
+
+ const get = await scim({ method: 'get', path: `/Users/${user.id}` })
+ expect(get.status).toBe(404)
})
})
diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/scim.test.types.ts
new file mode 100644
index 0000000..d67a65c
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/scim.test.types.ts
@@ -0,0 +1,15 @@
+export type ScimTestRequestArgs = {
+ method: 'get' | 'post' | 'put' | 'patch' | 'delete'
+ path: string
+ body?: unknown
+ token?: string
+ contentType?: string
+}
+
+export type ScimTestUserArgs = {
+ userName?: string
+ email?: string
+ externalId?: string
+ active?: boolean
+ displayName?: string
+}
diff --git a/taskview-packages/taskview-api/src/api/sso.ts b/taskview-packages/taskview-api/src/api/sso.ts
index 2a09d51..1064aa4 100644
--- a/taskview-packages/taskview-api/src/api/sso.ts
+++ b/taskview-packages/taskview-api/src/api/sso.ts
@@ -1,7 +1,9 @@
import TvApiBase from './base'
import type { AppResponse } from './base.types'
import type {
+ SsoArgLinkScimGroupProject,
SsoArgParseMetadata,
+ SsoArgUnlinkScimGroupProject,
SsoParsedMetadata,
SsoConfig,
SsoConfigArgCreate,
@@ -10,6 +12,7 @@ import type {
SsoDomainVerificationStart,
SsoProviderPublic,
SsoPublicUrls,
+ SsoScimGroupsOverview,
} from './sso.types'
export default class TvSsoApi extends TvApiBase {
@@ -67,6 +70,29 @@ export default class TvSsoApi extends TvApiBase {
)
}
+ public async fetchScimGroups(configId: number) {
+ return this.request(
+ this.$axios.get<AppResponse<SsoScimGroupsOverview>>(`${this.moduleUrl}/admin/configs/${configId}/scim-groups`)
+ )
+ }
+
+ public async linkScimGroupProject(args: SsoArgLinkScimGroupProject) {
+ return this.request(
+ this.$axios.put<AppResponse<boolean>>(
+ `${this.moduleUrl}/admin/configs/${args.configId}/scim-groups/${args.groupId}/projects/${args.goalId}`,
+ { roleId: args.roleId },
+ )
+ )
+ }
+
+ public async unlinkScimGroupProject(args: SsoArgUnlinkScimGroupProject) {
+ return this.request(
+ this.$axios.delete<AppResponse<boolean>>(
+ `${this.moduleUrl}/admin/configs/${args.configId}/scim-groups/${args.groupId}/projects/${args.goalId}`,
+ )
+ )
+ }
+
public async startDomainVerification(configId: number) {
return this.request(
this.$axios.post<AppResponse<SsoDomainVerificationStart>>(`${this.moduleUrl}/admin/configs/${configId}/verify-domain`)
diff --git a/taskview-packages/taskview-api/src/api/sso.types.ts b/taskview-packages/taskview-api/src/api/sso.types.ts
index fd01a8d..ea7e7fe 100644
--- a/taskview-packages/taskview-api/src/api/sso.types.ts
+++ b/taskview-packages/taskview-api/src/api/sso.types.ts
@@ -119,3 +119,42 @@ export type SsoParsedMetadata = {
samlCert: string
samlLogoutUrl: string
}
+
+export type SsoScimGroupProject = {
+ goalId: number
+ goalName: string
+ roleId: number
+ roleName: string
+}
+
+export type SsoScimGroup = {
+ id: number
+ displayName: string
+ membersCount: number
+ projects: SsoScimGroupProject[]
+}
+
+export type SsoScimLinkableProject = {
+ goalId: number
+ name: string
+ roles: { id: number, name: string }[]
+}
+
+export type SsoScimGroupsOverview = {
+ groups: SsoScimGroup[]
+ // Projects the current admin may link a group to: the ones where they can manage users
+ projects: SsoScimLinkableProject[]
+}
+
+export type SsoArgLinkScimGroupProject = {
+ configId: number
+ groupId: number
+ goalId: number
+ roleId: number
+}
+
+export type SsoArgUnlinkScimGroupProject = {
+ configId: number
+ groupId: number
+ goalId: number
+}
diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.ts
index 71888ea..dac9b12 100644
--- a/taskview-packages/taskview-db-schemas/src/index.ts
+++ b/taskview-packages/taskview-db-schemas/src/index.ts
@@ -22,6 +22,7 @@ export * from './schemas/oauth-grants.schema';
export * from './schemas/user-tokens.schema';
export * from './schemas/organizations.schema';
export * from './schemas/sso.schema';
+export * from './schemas/scim.schema';
export * from './schemas/time-entries.schema';
export * from './schemas/time-entries-history.schema';
export * from './schemas/currencies.schema';
diff --git a/taskview-packages/taskview-db-schemas/src/schemas/scim.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/scim.schema.ts
new file mode 100644
index 0000000..dbf2355
--- /dev/null
+++ b/taskview-packages/taskview-db-schemas/src/schemas/scim.schema.ts
@@ -0,0 +1,78 @@
+import { sql } from 'drizzle-orm'
+import { boolean, index, integer, jsonb, pgSchema, primaryKey, timestamp, uniqueIndex, varchar } from 'drizzle-orm/pg-core'
+import { CollaborationRolesSchema } from './collaboration-users.schema'
+import { GoalsSchema } from './goals.schema'
+import { SsoConfigsSchema } from './sso.schema'
+
+export type ScimSuspendedMembership = {
+ role: string
+ goals: { goalId: number; roleIds: number[] }[]
+ // ISO time of the deactivation; missing in snapshots taken before group links existed
+ suspendedAt?: string
+}
+
+export const ScimUsersSchema = pgSchema('tv_auth').table('scim_users', {
+ id: integer().primaryKey().generatedAlwaysAsIdentity(),
+ ssoConfigId: integer('sso_config_id').notNull().references(() => SsoConfigsSchema.id, { onDelete: 'cascade' }),
+ scimId: varchar('scim_id', { length: 255 }).notNull(),
+ userName: varchar('user_name', { length: 255 }).notNull(),
+ externalId: varchar('external_id', { length: 255 }),
+ email: varchar({ length: 255 }).notNull(),
+ // The address this person holds in the organization. It trails `email` until their
+ // account picks up the new address at the next SSO sign-in.
+ memberEmail: varchar('member_email', { length: 255 }).notNull(),
+ displayName: varchar('display_name', { length: 255 }),
+ givenName: varchar('given_name', { length: 255 }),
+ familyName: varchar('family_name', { length: 255 }),
+ active: boolean().notNull().default(true),
+ suspendedMembership: jsonb('suspended_membership').$type<ScimSuspendedMembership | null>(),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+ updatedAt: timestamp('updated_at').notNull().defaultNow(),
+}, (table) => [
+ uniqueIndex('scim_users_config_scim_id_uidx').on(table.ssoConfigId, table.scimId),
+ uniqueIndex('scim_users_config_user_name_uidx').on(table.ssoConfigId, sql`lower(${table.userName})`),
+ uniqueIndex('scim_users_config_email_uidx').on(table.ssoConfigId, table.email),
+ uniqueIndex('scim_users_config_external_id_uidx').on(table.ssoConfigId, table.externalId).where(sql`${table.externalId} is not null`),
+])
+
+export type ScimUsersSchemaTypeForSelect = typeof ScimUsersSchema.$inferSelect
+export type ScimUsersSchemaTypeForInsert = typeof ScimUsersSchema.$inferInsert
+
+export const ScimGroupsSchema = pgSchema('tv_auth').table('scim_groups', {
+ id: integer().primaryKey().generatedAlwaysAsIdentity(),
+ ssoConfigId: integer('sso_config_id').notNull().references(() => SsoConfigsSchema.id, { onDelete: 'cascade' }),
+ scimId: varchar('scim_id', { length: 255 }).notNull(),
+ displayName: varchar('display_name', { length: 255 }).notNull(),
+ externalId: varchar('external_id', { length: 255 }),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+ updatedAt: timestamp('updated_at').notNull().defaultNow(),
+}, (table) => [
+ uniqueIndex('scim_groups_config_scim_id_uidx').on(table.ssoConfigId, table.scimId),
+ index('scim_groups_config_display_name_idx').on(table.ssoConfigId, sql`lower(${table.displayName})`),
+ uniqueIndex('scim_groups_config_external_id_uidx').on(table.ssoConfigId, table.externalId).where(sql`${table.externalId} is not null`),
+])
+
+export type ScimGroupsSchemaTypeForSelect = typeof ScimGroupsSchema.$inferSelect
+export type ScimGroupsSchemaTypeForInsert = typeof ScimGroupsSchema.$inferInsert
+
+export const ScimGroupMembersSchema = pgSchema('tv_auth').table('scim_group_members', {
+ groupId: integer('group_id').notNull().references(() => ScimGroupsSchema.id, { onDelete: 'cascade' }),
+ scimUserId: integer('scim_user_id').notNull().references(() => ScimUsersSchema.id, { onDelete: 'cascade' }),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+}, (table) => [
+ primaryKey({ columns: [table.groupId, table.scimUserId] }),
+ index('scim_group_members_scim_user_id_idx').on(table.scimUserId),
+])
+
+// People who join the group are added to the project with the role; leaving the group changes nothing
+export const ScimGroupProjectsSchema = pgSchema('tv_auth').table('scim_group_projects', {
+ groupId: integer('group_id').notNull().references(() => ScimGroupsSchema.id, { onDelete: 'cascade' }),
+ goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),
+ roleId: integer('role_id').notNull().references(() => CollaborationRolesSchema.id, { onDelete: 'cascade' }),
+ createdAt: timestamp('created_at').notNull().defaultNow(),
+}, (table) => [
+ primaryKey({ columns: [table.groupId, table.goalId] }),
+ index('scim_group_projects_goal_id_idx').on(table.goalId),
+])
+
+export type ScimGroupProjectsSchemaTypeForSelect = typeof ScimGroupProjectsSchema.$inferSelect
diff --git a/web/src/components/features/organizations/parts/OrgSsoScimGroupItem.vue b/web/src/components/features/organizations/parts/OrgSsoScimGroupItem.vue
new file mode 100644
index 0000000..cc6eb71
--- /dev/null
+++ b/web/src/components/features/organizations/parts/OrgSsoScimGroupItem.vue
@@ -0,0 +1,102 @@
+<template>
+ <div class="flex flex-col gap-2 p-2 rounded-md bg-elevated/50">
+ <div class="flex items-center justify-between gap-2">
+ <div class="min-w-0">
+ <p class="text-sm truncate">
+ {{ group.displayName }}
+ </p>
+ <p class="text-xs text-dimmed">
+ {{ t('scim.groups.members', { count: group.membersCount }) }}
+ </p>
+ </div>
+ <UPopover v-model:open="adding">
+ <UButton
+ :label="t('scim.groups.addProject')"
+ icon="i-lucide-plus"
+ size="xs"
+ variant="outline"
+ :disabled="!projects.length"
+ />
+ <template #content>
+ <OrgSsoScimGroupLinkForm
+ :projects="projects"
+ :saving="saving"
+ @submit="link"
+ @cancel="adding = false"
+ />
+ </template>
+ </UPopover>
+ </div>
+
+ <div
+ v-if="group.projects.length"
+ class="flex flex-wrap gap-1"
+ >
+ <UBadge
+ v-for="project in group.projects"
+ :key="project.goalId"
+ color="neutral"
+ variant="subtle"
+ class="gap-1"
+ >
+ {{ project.goalName }} · {{ project.roleName }}
+ <UButton
+ icon="i-lucide-x"
+ size="xs"
+ variant="link"
+ color="neutral"
+ class="p-0"
+ :aria-label="t('scim.groups.removeProject')"
+ @click="unlink(project.goalId)"
+ />
+ </UBadge>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { ref } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { $tvApi } from '@/plugins/axios'
+import type { SsoScimGroup, SsoScimLinkableProject } from 'taskview-api'
+import OrgSsoScimGroupLinkForm from './OrgSsoScimGroupLinkForm.vue'
+import type { ScimGroupLink } from './OrgSsoScimGroupLinkForm.types'
+
+const props = defineProps<{
+ configId: number
+ group: SsoScimGroup
+ projects: SsoScimLinkableProject[]
+}>()
+
+const emit = defineEmits<{
+ changed: []
+}>()
+
+const { t } = useI18n()
+const toast = useToast()
+
+const adding = ref(false)
+const saving = ref(false)
+
+async function link(value: ScimGroupLink) {
+ saving.value = true
+ try {
+ await $tvApi.sso.linkScimGroupProject({ configId: props.configId, groupId: props.group.id, ...value })
+ adding.value = false
+ emit('changed')
+ } catch {
+ toast.add({ title: t('scim.groups.linkFailed'), color: 'error' })
+ } finally {
+ saving.value = false
+ }
+}
+
+async function unlink(goalId: number) {
+ try {
+ await $tvApi.sso.unlinkScimGroupProject({ configId: props.configId, groupId: props.group.id, goalId })
+ emit('changed')
+ } catch {
+ toast.add({ title: t('scim.groups.unlinkFailed'), color: 'error' })
+ }
+}
+</script>
diff --git a/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.types.ts b/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.types.ts
new file mode 100644
index 0000000..5c96b8e
--- /dev/null
+++ b/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.types.ts
@@ -0,0 +1,4 @@
+export type ScimGroupLink = {
+ goalId: number
+ roleId: number
+}
diff --git a/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.vue b/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.vue
new file mode 100644
index 0000000..da0a66f
--- /dev/null
+++ b/web/src/components/features/organizations/parts/OrgSsoScimGroupLinkForm.vue
@@ -0,0 +1,84 @@
+<template>
+ <div class="flex flex-col gap-3 p-3 w-72">
+ <UFormField :label="t('scim.groups.project')">
+ <USelectMenu
+ v-model="goalId"
+ :items="projectItems"
+ value-key="value"
+ :placeholder="t('scim.groups.selectProject')"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField
+ :label="t('scim.groups.role')"
+ :hint="t('scim.groups.roleHint')"
+ >
+ <USelectMenu
+ v-model="roleId"
+ :items="roleItems"
+ value-key="value"
+ :placeholder="t('scim.groups.selectRole')"
+ :disabled="!goalId"
+ class="w-full"
+ />
+ </UFormField>
+ <p
+ v-if="goalId && !roleItems.length"
+ class="text-xs text-dimmed"
+ >
+ {{ t('scim.groups.noRoles') }}
+ </p>
+ <div class="flex justify-end gap-2">
+ <UButton
+ :label="t('common.cancel')"
+ variant="ghost"
+ size="sm"
+ @click="emit('cancel')"
+ />
+ <UButton
+ :label="t('scim.groups.link')"
+ size="sm"
+ :loading="saving"
+ :disabled="!goalId || !roleId"
+ @click="submit"
+ />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { SsoScimLinkableProject } from 'taskview-api'
+import type { ScimGroupLink } from './OrgSsoScimGroupLinkForm.types'
+
+const props = defineProps<{
+ projects: SsoScimLinkableProject[]
+ saving: boolean
+}>()
+
+const emit = defineEmits<{
+ submit: [value: ScimGroupLink]
+ cancel: []
+}>()
+
+const { t } = useI18n()
+
+const goalId = ref<number>()
+const roleId = ref<number>()
+
+const projectItems = computed(() => props.projects.map((project) => ({ label: project.name, value: project.goalId })))
+const roleItems = computed(() =>
+ (props.projects.find((project) => project.goalId === goalId.value)?.roles ?? [])
+ .map((role) => ({ label: role.name, value: role.id })),
+)
+
+watch(goalId, () => {
+ roleId.value = undefined
+})
+
+function submit() {
+ if (!goalId.value || !roleId.value) return
+ emit('submit', { goalId: goalId.value, roleId: roleId.value })
+}
+</script>
diff --git a/web/src/components/features/organizations/parts/OrgSsoScimGroups.vue b/web/src/components/features/organizations/parts/OrgSsoScimGroups.vue
new file mode 100644
index 0000000..4b3fe0c
--- /dev/null
+++ b/web/src/components/features/organizations/parts/OrgSsoScimGroups.vue
@@ -0,0 +1,64 @@
+<template>
+ <div class="flex flex-col gap-2">
+ <div>
+ <p class="text-sm font-medium">
+ {{ t('scim.groups.title') }}
+ </p>
+ <p class="text-xs text-dimmed">
+ {{ t('scim.groups.hint') }}
+ </p>
+ </div>
+
+ <USkeleton
+ v-if="loading && !overview"
+ class="h-12 w-full"
+ />
+ <p
+ v-else-if="!overview?.groups.length"
+ class="text-xs text-dimmed"
+ >
+ {{ t('scim.groups.empty') }}
+ </p>
+ <template v-else>
+ <OrgSsoScimGroupItem
+ v-for="group in overview.groups"
+ :key="group.id"
+ :config-id="configId"
+ :group="group"
+ :projects="overview.projects"
+ @changed="load"
+ />
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { onMounted, ref } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { $tvApi } from '@/plugins/axios'
+import type { SsoScimGroupsOverview } from 'taskview-api'
+import OrgSsoScimGroupItem from './OrgSsoScimGroupItem.vue'
+
+const props = defineProps<{
+ configId: number
+}>()
+
+const { t } = useI18n()
+const toast = useToast()
+
+const overview = ref<SsoScimGroupsOverview | null>(null)
+const loading = ref(false)
+
+async function load() {
+ loading.value = true
+ try {
+ overview.value = await $tvApi.sso.fetchScimGroups(props.configId)
+ } catch {
+ toast.add({ title: t('scim.groups.loadFailed'), color: 'error' })
+ } finally {
+ loading.value = false
+ }
+}
+
+onMounted(load)
+</script>
diff --git a/web/src/components/features/organizations/parts/OrgSsoScimSection.vue b/web/src/components/features/organizations/parts/OrgSsoScimSection.vue
index a5959ce..23d6005 100644
--- a/web/src/components/features/organizations/parts/OrgSsoScimSection.vue
+++ b/web/src/components/features/organizations/parts/OrgSsoScimSection.vue
@@ -16,6 +16,14 @@
</div>
<template v-if="config.scimEnabled">
+ <UAlert
+ color="warning"
+ variant="subtle"
+ icon="i-lucide-user-x"
+ :title="t('scim.unmanagedMembersTitle')"
+ :description="t('scim.unmanagedMembersHint')"
+ />
+
<div class="flex flex-col gap-1">
<p class="text-xs text-dimmed">
{{ t('scim.endpointUrl') }}
@@ -59,6 +67,8 @@
:loading="generating"
@click="generate"
/>
+
+ <OrgSsoScimGroups :config-id="config.id" />
</template>
</div>
</template>
@@ -68,6 +78,7 @@ import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { $tvApi } from '@/plugins/axios'
import type { SsoConfig } from 'taskview-api'
+import OrgSsoScimGroups from './OrgSsoScimGroups.vue'
const props = defineProps<{
config: SsoConfig
diff --git a/web/src/components/features/organizations/parts/SsoSamlForm.vue b/web/src/components/features/organizations/parts/SsoSamlForm.vue
index 0d18086..ca8bd78 100644
--- a/web/src/components/features/organizations/parts/SsoSamlForm.vue
+++ b/web/src/components/features/organizations/parts/SsoSamlForm.vue
@@ -1,5 +1,12 @@
<template>
<div class="flex flex-col gap-4">
+ <UAlert
+ color="info"
+ icon="i-lucide-fingerprint"
+ :title="t('sso.nameIdHintTitle')"
+ :description="t('sso.nameIdHint')"
+ />
+
<UFormField :label="t('sso.metadataUrl')">
<div class="flex gap-2">
<UInput
diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts
index 197fa51..468eb02 100644
--- a/web/src/locales/de.ts
+++ b/web/src/locales/de.ts
@@ -69,6 +69,8 @@ export default {
ssoError: 'SSO-Authentifizierung fehlgeschlagen. Bitte versuchen Sie es erneut.',
ssoDomainUnverified: 'SSO ist nicht verfügbar, bis die Organisation diese E-Mail-Domain bestätigt.',
ssoEmailInUse: 'Diese E-Mail wird bereits von einem anderen TaskView-Konto verwendet.',
+ ssoAccountDeactivated: 'Ihr Zugang zur Organisation ist deaktiviert. Wenden Sie sich an Ihren Administrator.',
+ ssoNotProvisioned: 'Sie wurden der Organisation noch nicht hinzugefügt. Wenden Sie sich an Ihren Administrator.',
ssoAccountBlocked: 'Dieses Konto ist gesperrt. Wenden Sie sich an Ihren Administrator.',
invalidEmail: 'Ungültige E-Mail-Adresse',
loginRequired: 'Anmeldung erforderlich',
@@ -940,6 +942,8 @@ export default {
samlCallbackUrl: 'ACS-URL (Callback)',
samlLogoutUrl: 'IdP-Logout-URL (SLO)',
requestSigning: 'Request-Signierung (Enterprise)',
+ nameIdHintTitle: 'Verwenden Sie eine dauerhafte Name ID',
+ nameIdHint: 'Setzen Sie die Name ID auf eine Kennung, die sich nie ändert, z. B. objectid in Microsoft Entra ID, und senden Sie die E-Mail als separates Attribut. Mit dem standardmäßigen Benutzerprinzipalnamen erzeugt eine geänderte E-Mail beim nächsten Login ein neues TaskView-Konto.',
requestSigningDescription: 'SAML AuthnRequests mit einem privaten Schlüssel signieren. Erforderlich bei einigen IdPs für erhöhte Sicherheit.',
generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
generateKeysHint: 'sp-key.pem → Feld Privater Schlüssel. sp-cert.pem → Feld Zertifikat + zum IdP hochladen.',
@@ -991,7 +995,27 @@ export default {
tokenWarning: 'Kopieren Sie dieses Token jetzt. Es wird nicht erneut angezeigt.',
tokenGenerated: 'SCIM-Token generiert',
tokenFailed: 'Token konnte nicht generiert werden',
+ unmanagedMembersTitle: 'Von einem anderen SCIM-Anbieter angelegte Mitglieder können entfernt werden',
+ unmanagedMembersHint: 'Einige Anbieter entfernen bei der Synchronisierung alle, die sie nicht selbst angelegt haben. Das betrifft Mitglieder, die bereits von einem anderen Anbieter verbunden wurden oder vor dem Update mit SCIM verbunden waren. Manuell hinzugefügte Mitglieder sind nicht betroffen.',
toggleFailed: 'SCIM konnte nicht umgeschaltet werden',
+ groups: {
+ title: 'Gruppen',
+ hint: 'Gruppen kommen vom Anbieter. Verknüpfen Sie eine Gruppe mit einem Projekt: Personen, die der Gruppe beitreten, werden dem Projekt mit der gewählten Rolle hinzugefügt. Ist jemand bereits im Projekt, bleiben seine Rollen unverändert. Das Verlassen der Gruppe entfernt niemanden aus dem Projekt — der Zugang im Projekt wird in TaskView verwaltet.',
+ empty: 'Der Anbieter hat noch keine Gruppen gesendet.',
+ members: 'Mitglieder: {count}',
+ addProject: 'Projekt hinzufügen',
+ removeProject: 'Projekt trennen',
+ project: 'Projekt',
+ selectProject: 'Projekt auswählen',
+ role: 'Standardrolle',
+ roleHint: 'Neue Gruppenmitglieder erhalten diese Rolle',
+ selectRole: 'Rolle auswählen',
+ noRoles: 'Dieses Projekt hat keine Rollen. Erstellen Sie zuerst eine Rolle in den Projekteinstellungen.',
+ link: 'Verknüpfen',
+ loadFailed: 'Gruppen konnten nicht geladen werden',
+ linkFailed: 'Die Gruppe konnte nicht mit dem Projekt verknüpft werden',
+ unlinkFailed: 'Das Projekt konnte nicht getrennt werden',
+ },
},
permissionGroups: {
1: 'Anwendungsebene',
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index 65a3ad7..5f18b87 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -81,6 +81,8 @@ export default {
ssoError: 'SSO authentication failed. Please try again.',
ssoDomainUnverified: 'SSO is not available until the organization verifies this email domain.',
ssoEmailInUse: 'This email is already used by another TaskView account.',
+ ssoAccountDeactivated: 'Your access to the organization is turned off. Contact your administrator.',
+ ssoNotProvisioned: 'You have not been added to the organization yet. Contact your administrator.',
ssoAccountBlocked: 'This account is blocked. Contact your administrator.',
// Validation
@@ -954,6 +956,8 @@ export default {
samlCallbackUrl: 'ACS URL (Callback)',
samlLogoutUrl: 'IdP Logout URL (SLO)',
requestSigning: 'Request signing (enterprise)',
+ nameIdHintTitle: 'Use a permanent Name ID',
+ nameIdHint: 'Set the Name ID to an identifier that never changes, such as objectid in Microsoft Entra ID, and send the email as a separate attribute. With the default user principal name, changing the email of a user creates a new TaskView account at their next sign-in.',
requestSigningDescription: 'Sign SAML AuthnRequests with a private key. Required by some IdPs for enhanced security.',
generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
generateKeysHint: 'sp-key.pem → Private Key field. sp-cert.pem → Certificate field + upload to IdP.',
@@ -1005,7 +1009,27 @@ export default {
tokenWarning: 'Copy this token now. It will not be shown again.',
tokenGenerated: 'SCIM token generated',
tokenFailed: 'Failed to generate token',
+ unmanagedMembersTitle: 'Members created by another SCIM provider may be removed',
+ unmanagedMembersHint: 'Some providers remove everyone they did not create themselves during a sync. This affects members already connected by another provider or connected to SCIM before the update. Members added manually are not affected.',
toggleFailed: 'Failed to toggle SCIM',
+ groups: {
+ title: 'Groups',
+ hint: 'Groups come from the provider. Link a group to a project: people who join the group are added to the project with the chosen role. If someone is already in the project, their roles stay as they are. Leaving the group does not remove anyone from the project — access in the project is managed in TaskView.',
+ empty: 'The provider has not sent any groups yet.',
+ members: 'Members: {count}',
+ addProject: 'Add project',
+ removeProject: 'Unlink project',
+ project: 'Project',
+ selectProject: 'Select a project',
+ role: 'Default role',
+ roleHint: 'New group members get this role',
+ selectRole: 'Select a role',
+ noRoles: 'This project has no roles. Create a role in the project settings first.',
+ link: 'Link',
+ loadFailed: 'Failed to load groups',
+ linkFailed: 'Failed to link the group to the project',
+ unlinkFailed: 'Failed to unlink the project',
+ },
},
permissionGroups: {
1: 'Application level',
diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts
index 3c7bff0..9d235ec 100644
--- a/web/src/locales/es.ts
+++ b/web/src/locales/es.ts
@@ -69,6 +69,8 @@ export default {
ssoError: 'Error de autenticación SSO. Inténtalo de nuevo.',
ssoDomainUnverified: 'SSO no está disponible hasta que la organización verifique este dominio de correo.',
ssoEmailInUse: 'Este correo ya está usado por otra cuenta de TaskView.',
+ ssoAccountDeactivated: 'Tu acceso a la organización está desactivado. Contacta con tu administrador.',
+ ssoNotProvisioned: 'Todavía no te han añadido a la organización. Contacta con tu administrador.',
ssoAccountBlocked: 'Esta cuenta está bloqueada. Contacta con tu administrador.',
invalidEmail: 'Dirección de correo electrónico inválida',
loginRequired: 'El usuario es obligatorio',
@@ -940,6 +942,8 @@ export default {
samlCallbackUrl: 'URL de ACS (Callback)',
samlLogoutUrl: 'URL de cierre de sesión del IdP (SLO)',
requestSigning: 'Firma de solicitudes (enterprise)',
+ nameIdHintTitle: 'Usa un Name ID permanente',
+ nameIdHint: 'Configura el Name ID con un identificador que nunca cambie, como objectid en Microsoft Entra ID, y envía el correo como un atributo aparte. Con el nombre principal de usuario predeterminado, cambiar el correo de un usuario crea una nueva cuenta de TaskView en su siguiente inicio de sesión.',
requestSigningDescription: 'Firma las AuthnRequest de SAML con una clave privada. Algunos IdP lo requieren para mayor seguridad.',
generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
generateKeysHint: 'sp-key.pem → campo Clave privada. sp-cert.pem → campo Certificado + subir al IdP.',
@@ -991,7 +995,27 @@ export default {
tokenWarning: 'Copia este token ahora. No se volverá a mostrar.',
tokenGenerated: 'Token de SCIM generado',
tokenFailed: 'Error al generar el token',
+ unmanagedMembersTitle: 'Los miembros creados por otro proveedor SCIM pueden ser eliminados',
+ unmanagedMembersHint: 'Algunos proveedores eliminan durante la sincronización a todas las personas que no crearon ellos mismos. Esto afecta a los miembros ya conectados por otro proveedor o conectados a SCIM antes de la actualización. Los miembros añadidos manualmente no se ven afectados.',
toggleFailed: 'Error al activar o desactivar SCIM',
+ groups: {
+ title: 'Grupos',
+ hint: 'Los grupos vienen del proveedor. Vincula un grupo a un proyecto: las personas que se unen al grupo se añaden al proyecto con el rol elegido. Si alguien ya está en el proyecto, sus roles no cambian. Salir del grupo no quita a nadie del proyecto: el acceso al proyecto se gestiona en TaskView.',
+ empty: 'El proveedor todavía no ha enviado ningún grupo.',
+ members: 'Miembros: {count}',
+ addProject: 'Añadir proyecto',
+ removeProject: 'Desvincular proyecto',
+ project: 'Proyecto',
+ selectProject: 'Selecciona un proyecto',
+ role: 'Rol por defecto',
+ roleHint: 'Los nuevos miembros del grupo reciben este rol',
+ selectRole: 'Selecciona un rol',
+ noRoles: 'Este proyecto no tiene roles. Crea primero un rol en la configuración del proyecto.',
+ link: 'Vincular',
+ loadFailed: 'No se pudieron cargar los grupos',
+ linkFailed: 'No se pudo vincular el grupo al proyecto',
+ unlinkFailed: 'No se pudo desvincular el proyecto',
+ },
},
permissionGroups: {
1: 'Nivel de aplicación',
diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.ts
index 975eb6d..0fddd54 100644
--- a/web/src/locales/pt-br.ts
+++ b/web/src/locales/pt-br.ts
@@ -81,6 +81,8 @@ export default {
ssoError: 'Falha na autenticação SSO. Tente novamente.',
ssoDomainUnverified: 'O SSO não estará disponível até que a organização verifique este domínio de e-mail.',
ssoEmailInUse: 'Este e-mail já é usado por outra conta do TaskView.',
+ ssoAccountDeactivated: 'Seu acesso à organização está desativado. Entre em contato com o administrador.',
+ ssoNotProvisioned: 'Você ainda não foi adicionado à organização. Entre em contato com o administrador.',
// Validation
invalidEmail: 'Endereço de e-mail inválido',
@@ -953,6 +955,8 @@ export default {
samlCallbackUrl: 'ACS URL (Callback)',
samlLogoutUrl: 'IdP Logout URL (SLO)',
requestSigning: 'Assinatura de solicitação (enterprise)',
+ nameIdHintTitle: 'Use um Name ID permanente',
+ nameIdHint: 'Defina o Name ID como um identificador que nunca muda, como objectid no Microsoft Entra ID, e envie o e-mail como um atributo separado. Com o nome principal de usuário padrão, alterar o e-mail de um usuário cria uma nova conta do TaskView no próximo login.',
requestSigningDescription: 'Assine AuthnRequests SAML com uma chave privada. Exigido por alguns IdPs para maior segurança.',
generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
generateKeysHint: 'sp-key.pem → Private Key field. sp-cert.pem → Certificate field + upload to IdP.',
@@ -1002,7 +1006,27 @@ export default {
tokenWarning: 'Copie este token agora. Não será mostrado novamente.',
tokenGenerated: 'Token SCIM gerado',
tokenFailed: 'Falha ao gerar o token',
+ unmanagedMembersTitle: 'Membros criados por outro provedor SCIM podem ser removidos',
+ unmanagedMembersHint: 'Alguns provedores removem, durante a sincronização, todas as pessoas que não criaram eles mesmos. Isso afeta membros já conectados por outro provedor ou conectados ao SCIM antes da atualização. Membros adicionados manualmente não são afetados.',
toggleFailed: 'Falha ao alternar o SCIM',
+ groups: {
+ title: 'Grupos',
+ hint: 'Os grupos vêm do provedor. Vincule um grupo a um projeto: as pessoas que entram no grupo são adicionadas ao projeto com a função escolhida. Se alguém já está no projeto, suas funções não mudam. Sair do grupo não remove ninguém do projeto — o acesso ao projeto é gerenciado no TaskView.',
+ empty: 'O provedor ainda não enviou nenhum grupo.',
+ members: 'Membros: {count}',
+ addProject: 'Adicionar projeto',
+ removeProject: 'Desvincular projeto',
+ project: 'Projeto',
+ selectProject: 'Selecione um projeto',
+ role: 'Função padrão',
+ roleHint: 'Novos membros do grupo recebem esta função',
+ selectRole: 'Selecione uma função',
+ noRoles: 'Este projeto não tem funções. Crie primeiro uma função nas configurações do projeto.',
+ link: 'Vincular',
+ loadFailed: 'Não foi possível carregar os grupos',
+ linkFailed: 'Não foi possível vincular o grupo ao projeto',
+ unlinkFailed: 'Não foi possível desvincular o projeto',
+ },
},
permissionGroups: {
1: 'Nível do aplicativo',
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index 27ebcf0..9680b1b 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -81,6 +81,8 @@ export default {
ssoError: 'Ошибка SSO авторизации. Попробуйте снова.',
ssoDomainUnverified: 'SSO недоступен, пока организация не подтвердит этот email-домен.',
ssoEmailInUse: 'Эта почта уже занята другим аккаунтом TaskView.',
+ ssoAccountDeactivated: 'Доступ к организации отключён. Обратитесь к администратору.',
+ ssoNotProvisioned: 'Вы ещё не добавлены в организацию. Обратитесь к администратору.',
ssoAccountBlocked: 'Аккаунт заблокирован. Обратитесь к администратору.',
// Validation
@@ -929,6 +931,8 @@ export default {
samlCallbackUrl: 'ACS URL (Callback)',
samlLogoutUrl: 'URL выхода IdP (SLO)',
requestSigning: 'Подпись запросов (enterprise)',
+ nameIdHintTitle: 'Используйте постоянный Name ID',
+ nameIdHint: 'Укажите в Name ID идентификатор, который никогда не меняется, например objectid в Microsoft Entra ID, а email передавайте отдельным атрибутом. Если оставить логин пользователя (по умолчанию), после смены email при следующем входе будет создан новый аккаунт TaskView.',
requestSigningDescription: 'Подписывать SAML AuthnRequest приватным ключом. Требуется некоторыми IdP для повышенной безопасности.',
generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
generateKeysHint: 'sp-key.pem → поле Private Key. sp-cert.pem → поле Certificate + загрузить в IdP.',
@@ -980,7 +984,27 @@ export default {
tokenWarning: 'Скопируйте токен сейчас. Он не будет показан повторно.',
tokenGenerated: 'SCIM токен сгенерирован',
tokenFailed: 'Не удалось сгенерировать токен',
+ unmanagedMembersTitle: 'Участники, созданные другим SCIM-провайдером, могут быть удалены',
+ unmanagedMembersHint: 'Некоторые провайдеры при синхронизации удаляют всех, кого не создавали сами. Это касается участников, которых уже подключил другой провайдер или которые были подключены к SCIM до обновления. Участников, добавленных вручную, это не касается.',
toggleFailed: 'Не удалось переключить SCIM',
+ groups: {
+ title: 'Группы',
+ hint: 'Группы приходят от провайдера. Свяжите группу с проектом: люди, которые попадают в группу, добавляются в проект с выбранной ролью. Если человек уже в проекте, его роли не меняются. Удаление из группы не убирает человека из проекта — доступом в проекте управляют в TaskView.',
+ empty: 'Провайдер ещё не передал ни одной группы.',
+ members: 'Участников: {count}',
+ addProject: 'Добавить проект',
+ removeProject: 'Отвязать проект',
+ project: 'Проект',
+ selectProject: 'Выберите проект',
+ role: 'Роль по умолчанию',
+ roleHint: 'Её получат новые участники группы',
+ selectRole: 'Выберите роль',
+ noRoles: 'В этом проекте нет ролей. Сначала создайте роль в настройках проекта.',
+ link: 'Связать',
+ loadFailed: 'Не удалось загрузить группы',
+ linkFailed: 'Не удалось связать группу с проектом',
+ unlinkFailed: 'Не удалось отвязать проект',
+ },
},
notifications: {
title: 'Уведомления',
diff --git a/web/src/pages/login.vue b/web/src/pages/login.vue
index f14b441..1c71f87 100644
--- a/web/src/pages/login.vue
+++ b/web/src/pages/login.vue
@@ -56,6 +56,8 @@ onMounted(async () => {
domain_unverified: 'auth.ssoDomainUnverified',
email_in_use: 'auth.ssoEmailInUse',
account_blocked: 'auth.ssoAccountBlocked',
+ account_deactivated: 'auth.ssoAccountDeactivated',
+ not_provisioned: 'auth.ssoNotProvisioned',
}[String(route.query.sso_error)] ?? 'auth.ssoError'
toast.add({