From 8d18d99298de7f61548a34bb686f06145c9c49b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Sun, 25 Oct 2026 11:40:01 +0000 Subject: [PATCH 1/4] feat(people): mirror PoliNetwork Auth roles and Microsoft 365 members The People register only filled through the dashboard and census imports, so Overview, Admins, Teams and the member register stayed empty while the same people held roles in PoliNetwork Auth and were in the Microsoft 365 Soci group. - Every five minutes the sweep reads the roles bound to People in the IdP (GET /api/internal/people-roles) and the Soci group. Role holders get linked records with their admin and team entries; Soci members get a membership numbered by employeeId. Entries People added on its own are left alone, and leaving the Soci group ends nothing. - Dashboard changes to a linked record's admin or team role, census answers and imports give or take back the bound role through POST /api/internal/people-roles for the acting user; the IdP decides. Direct actions fail on a refusal, census and imports note it. - Records known only from these sources have no campus, course or year yet: the contract's profile.campus is now nullable. - The Design team is now called Design & Marketing. - Imported memberships skip automatic fee reminders that year. Needs the IdP change that adds the endpoint, and the idp:people:roles scope on the backend client for writes. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 + src/azure/functions/members.ts | 11 +- src/azure/types.ts | 4 +- src/idp/index.ts | 62 +++++++ src/people/contract.ts | 8 +- src/people/index.ts | 19 +++ src/people/roles.ts | 296 +++++++++++++++++++++++++++++++++ src/people/service.ts | 133 ++++++++++++++- src/people/types.ts | 7 + tests/people-roles.test.ts | 271 ++++++++++++++++++++++++++++++ 10 files changed, 808 insertions(+), 12 deletions(-) create mode 100644 src/people/roles.ts create mode 100644 tests/people-roles.test.ts diff --git a/README.md b/README.md index f054ed6..5342beb 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,15 @@ The bot's socket.io client authenticates with its service token in `auth.token` The IdP notifies `POST /internal/events` when access changes; the backend also polls the snapshot every 30 s. The last good signing keys and snapshot are stored in `common_idp_state`, so a restart during an IdP outage resumes from them. Permission checks deny once the snapshot is more than an hour old. Configuration is in `.env.example`. +## People register sources + +Every five minutes the People sweep mirrors two sources into the register: + +- **PoliNetwork Auth roles.** `GET /api/internal/people-roles` lists the roles Master Admin bound to People in the IdP (`admin`, `team::member`, `team::lead`) and who holds them. Holders without a record get one (name only, linked to their account); a record without an account is linked when its Telegram ID or Microsoft 365 address matches. On linked records, an admin or team entry starts while its role is held and ends when a role it mirrored is taken back. Entries People added on its own (census import, dashboard before linking) are left alone, and so is any concept with no bound role. +- **The Microsoft 365 Soci group.** Each member gets a membership with the account's `employeeId` as member number and its creation date as admission date; a member without a usable number is flagged for review. Leaving the group changes nothing: the register keeps the status. Imported memberships get no automatic fee reminders in the year they were imported. + +When the dashboard changes a linked record's admin or team role, or a census answer or import does, the backend gives or takes back the bound role with `POST /api/internal/people-roles`, naming the dashboard user it authenticated; the IdP decides whether that user may (no self-grants, `people:write` or `people:appoint`, bounded delegation). Direct dashboard actions fail when the IdP refuses; census answers and imports note the refusal on the record. Writes need the backend's OAuth client to hold the `idp:people:roles` scope on the internal resource; reads use the existing `idp:access:read` token. + ## E-signing with the CIE The `esign` router and `/esign/agent/*` endpoints let dashboard users sign PDFs with the Italian identity card diff --git a/src/azure/functions/members.ts b/src/azure/functions/members.ts index 57dd98f..bd547d6 100644 --- a/src/azure/functions/members.ts +++ b/src/azure/functions/members.ts @@ -39,7 +39,16 @@ export async function getMembers(): Promise { .api(`/users`) .header("ConsistencyLevel", "eventual") .count(true) - .select(["displayName", "mail", "givenName", "surname", "id", "assignedLicenses", "employeeId"]) + .select([ + "displayName", + "mail", + "givenName", + "surname", + "id", + "assignedLicenses", + "employeeId", + "createdDateTime", + ]) .filter("endswith(mail, '@polinetwork.org') or endswith(userPrincipalName, '@polinetwork.org')") .get(), true diff --git a/src/azure/types.ts b/src/azure/types.ts index 60021d4..f8136f9 100644 --- a/src/azure/types.ts +++ b/src/azure/types.ts @@ -19,7 +19,7 @@ export type BasicUser = Pick< // this is the type representing our call to `/users` export type User = Pick< Required, - "displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId" + "displayName" | "mail" | "givenName" | "surname" | "id" | "assignedLicenses" | "employeeId" | "createdDateTime" > export type ParsedUser = { @@ -29,6 +29,8 @@ export type ParsedUser = { givenName: string | null surname: string | null employeeId: string | null + /** When the account was created, as Graph returns it; absent in the seeded directory. */ + createdDateTime?: string | null isMember: boolean assignedLicensesIds: string[] } diff --git a/src/idp/index.ts b/src/idp/index.ts index d050318..d168019 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -12,6 +12,7 @@ import { import { z } from "zod" import { env } from "@/env" import { logger } from "@/logger" +import { type PeopleRoles, RoleChangeError } from "@/people/roles" import { authenticate, type RequestAuth } from "./auth" import { dbPersistence } from "./persistence" @@ -20,6 +21,21 @@ const PROJECTION = "backend" const signerDirectory = z.array( z.object({ sub: z.string(), name: z.string(), email: z.string().nullable(), emailVerified: z.boolean().optional() }) ) +const peopleDirectory = z.object({ + roles: z.array(z.object({ key: z.string(), name: z.string(), binding: z.string() })), + users: z.array( + z.object({ + sub: z.string(), + name: z.string(), + email: z.string().nullable(), + telegramId: z.string().nullable(), + telegramUsername: z.string().nullable(), + roles: z.array(z.string()), + }) + ), +}) +/** Lets the backend give and take back the roles bound to People, for the dashboard user it authenticated. */ +const PEOPLE_ROLES_SCOPE = "idp:people:roles" function report(component: string) { return (error: unknown) => { @@ -58,6 +74,7 @@ function configure() { let snapshot = null let events = null let directory: (() => Promise>) | null = null + let peopleRoles: PeopleRoles | null = null if (env.OAUTH_INTERNAL_RESOURCE_URI && env.OAUTH_BACKEND_CLIENT_ID && env.OAUTH_BACKEND_PRIVATE_JWK) { const tokens = serviceTokenSource({ clientId: env.OAUTH_BACKEND_CLIENT_ID, @@ -87,6 +104,50 @@ function configure() { if (!response.ok) throw new Error(`IdP signer directory returned ${response.status}`) return signerDirectory.parse(await response.json()) } + // A separate token, so a client not yet granted the write scope still pulls the snapshot. + const roleTokens = serviceTokenSource({ + clientId: env.OAUTH_BACKEND_CLIENT_ID, + privateKey: parsePrivateKey(env.OAUTH_BACKEND_PRIVATE_JWK), + tokenUrl: endpoints.tokenUrl, + tokenAudience: endpoints.tokenAudience, + resource: env.OAUTH_INTERNAL_RESOURCE_URI, + scopes: [PEOPLE_ROLES_SCOPE], + onError: report("people roles token source"), + }) + const peopleRolesUrl = new URL("/api/internal/people-roles", endpoints.snapshotUrl) + peopleRoles = { + async directory() { + const token = await tokens.getToken() + const response = await fetch(peopleRolesUrl, { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(10_000), + }) + if (response.status === 401) tokens.invalidate() + if (!response.ok) throw new Error(`IdP People roles returned ${response.status}`) + return peopleDirectory.parse(await response.json()) + }, + async change(change) { + let token: string + try { + token = await roleTokens.getToken() + } catch { + throw new RoleChangeError(503, `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?`) + } + const response = await fetch(peopleRolesUrl, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(change), + signal: AbortSignal.timeout(10_000), + }) + if (response.status === 401) roleTokens.invalidate() + if (response.ok) return + const body = (await response.json().catch(() => null)) as { error?: unknown } | null + throw new RoleChangeError( + response.status, + typeof body?.error === "string" ? body.error : `request failed (${response.status})` + ) + }, + } events = createAccessEventHandler({ keyStore, issuer: endpoints.issuer, @@ -103,6 +164,7 @@ function configure() { keyStore, snapshot, directory, + peopleRoles, /** Fetch API handler for `POST /internal/events`, or null without a snapshot. */ events, verify: (token: string) => verifyAccessToken(token, { issuer: endpoints.issuer, audience, keyStore }), diff --git a/src/people/contract.ts b/src/people/contract.ts index 3356d29..73280ce 100644 --- a/src/people/contract.ts +++ b/src/people/contract.ts @@ -70,9 +70,11 @@ export const profileSchema = z.object({ phone: z.string().nullable(), telegramUsername: z.string().nullable(), telegramId: z.string().nullable(), + /** Empty, like `year`, for people known only from PoliNetwork Auth or Microsoft 365 until HR completes them. */ course: z.string(), year: z.string(), - campus: campusSchema, + /** `null` until known: people known only from PoliNetwork Auth or Microsoft 365. */ + campus: campusSchema.nullable(), otherAssociations: z.array(z.string()), studentRepresentative: z.string().nullable(), }) @@ -447,7 +449,7 @@ export const myAreaSchema = z.discriminatedUnion("state", [ name: z.string(), course: z.string(), year: z.string(), - campus: campusSchema, + campus: campusSchema.nullable(), roles: z.array(z.string()), }), reason: z.string(), @@ -523,7 +525,7 @@ export const TEAMS = { ], }, design: { - name: "Design & Social", + name: "Design & Marketing", fields: [ { key: "tools", diff --git a/src/people/index.ts b/src/people/index.ts index 471dbec..297a21c 100644 --- a/src/people/index.ts +++ b/src/people/index.ts @@ -1,3 +1,4 @@ +import { azureDirectory } from "@/azure/directory" import { DB, SCHEMA } from "@/db" import { sendPeopleEmail } from "@/emails/mailer" import { idp } from "@/idp" @@ -59,6 +60,24 @@ export const people = createPeopleService({ }, provisionMember, setMemberNumber, + peopleRoles: idp?.peopleRoles ?? null, + async azureMembers() { + return (await azureDirectory.getMembers()).flatMap((u) => + u.isMember && u.mail + ? [ + { + id: u.id, + mail: u.mail, + givenName: u.givenName, + surname: u.surname, + displayName: u.displayName, + employeeId: u.employeeId, + createdOn: u.createdDateTime?.slice(0, 10) ?? null, + }, + ] + : [] + ) + }, sendMail: sendPeopleEmail, async inspectSigned(sub, bytes) { const { esign } = await import("@/esign") diff --git a/src/people/roles.ts b/src/people/roles.ts new file mode 100644 index 0000000..6ac3f21 --- /dev/null +++ b/src/people/roles.ts @@ -0,0 +1,296 @@ +import * as C from "./contract" +import { academicYear, log, newPerson } from "./model" +import type { PeopleState, Person } from "./types" + +/** + * Roles in PoliNetwork Auth that Master Admin bound to People: `admin`, `team::member` or `team::lead`. + * PoliNetwork Auth is the source of truth for who holds them; People mirrors them on each person's record and changes + * them through `PeopleRoles.change`, which checks again what the acting dashboard user may do. + */ +export type RoleDirectory = { + roles: { key: string; name: string; binding: string }[] + users: { + sub: string + name: string + email: string | null + telegramId: string | null + telegramUsername: string | null + roles: string[] + }[] +} +export type RoleChange = { actor: string; sub: string; role: string; action: "assign" | "unassign"; reason: string } +export type PeopleRoles = { + directory(): Promise + change(change: RoleChange): Promise +} +/** A member of the Microsoft 365 Soci group. */ +export type AzureMember = { + id: string + mail: string + givenName: string | null + surname: string | null + displayName: string | null + employeeId: string | null + /** The account's creation date (`YYYY-MM-DD`), the best known admission date. */ + createdOn: string | null +} + +/** PoliNetwork Auth refused or failed a role change; `status` is its HTTP status. */ +export class RoleChangeError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message) + } +} + +type TeamRole = C.TeamMembership["role"] +export type Bound = { admin: string[]; teams: Record> } +/** A person's active roles, as People shows them. */ +export type RoleView = { admin: boolean; teams: Partial> } + +const isTeam = (value: string): value is C.TeamId => (C.TEAM_IDS as readonly string[]).includes(value) + +/** Role keys by what they mean in People. Bindings to unknown teams are ignored. */ +export function boundRoles(directory: RoleDirectory): Bound { + const bound: Bound = { + admin: [], + teams: Object.fromEntries( + C.TEAM_IDS.map((id) => [id, { member: [] as string[], lead: [] as string[] }]) + ) as Bound["teams"], + } + for (const role of directory.roles) { + if (role.binding === "admin") bound.admin.push(role.key) + const [kind, team, as] = role.binding.split(":") + if (kind === "team" && isTeam(team) && (as === "member" || as === "lead")) bound.teams[team][as].push(role.key) + } + return bound +} + +const teamBound = (bound: Bound, team: C.TeamId) => bound.teams[team].member.length + bound.teams[team].lead.length > 0 + +/** The roles PoliNetwork Auth says this account holds; a Lead role wins over a member one. */ +export function wantedView(bound: Bound, held: readonly string[]): RoleView { + const view: RoleView = { admin: bound.admin.some((key) => held.includes(key)), teams: {} } + for (const team of C.TEAM_IDS) { + if (bound.teams[team].lead.some((key) => held.includes(key))) view.teams[team] = "lead" + else if (bound.teams[team].member.some((key) => held.includes(key))) view.teams[team] = "member" + } + return view +} + +export function roleView(p: Person): RoleView { + const view: RoleView = { admin: p.admin?.status === "active", teams: {} } + for (const t of p.teams) if (!t.endedOn) view.teams[t.team] = t.role + return view +} + +/** + * The changes in PoliNetwork Auth that turn `before` into `after` for an account holding `held`. Ending a role takes + * back every bound role behind it, Lead roles first so a refused Lead change leaves the membership untouched. + */ +export function roleChanges( + bound: Bound, + held: readonly string[], + before: RoleView, + after: RoleView +): { role: string; action: RoleChange["action"] }[] { + const changes: { role: string; action: RoleChange["action"] }[] = [] + const holds = (keys: string[]) => keys.some((key) => held.includes(key)) + const take = (keys: string[]) => { + for (const role of keys) if (held.includes(role)) changes.push({ role, action: "unassign" }) + } + if (bound.admin.length && before.admin !== after.admin) { + if (after.admin && !holds(bound.admin)) changes.push({ role: bound.admin[0], action: "assign" }) + if (!after.admin) take(bound.admin) + } + for (const team of C.TEAM_IDS) { + const { member, lead } = bound.teams[team] + const [was, now] = [before.teams[team], after.teams[team]] + if (!teamBound(bound, team) || was === now) continue + if (!now) { + take(lead) + take(member) + continue + } + if (was === "lead") take(lead) + const keys = now === "lead" && lead.length ? lead : member + if (keys.length && !holds(keys)) changes.push({ role: keys[0], action: "assign" }) + } + return changes +} + +/** Records which of the person's active roles now mirror PoliNetwork Auth. */ +export function markSynced(p: Person, bound: Bound, view: RoleView) { + const teams = new Set(p.synced?.teams ?? []) + let admin = !!p.synced?.admin + if (bound.admin.length) admin = view.admin + for (const team of C.TEAM_IDS) if (teamBound(bound, team)) view.teams[team] ? teams.add(team) : teams.delete(team) + p.synced = { ...(admin ? { admin: true as const } : {}), ...(teams.size ? { teams: [...teams].sort() } : {}) } + if (!p.synced.admin && !p.synced.teams) delete p.synced +} + +/** A record with only a name, for someone People hears of from PoliNetwork Auth or Microsoft 365. */ +export function blankPerson(s: PeopleState, name: { first: string; last: string }, date: string) { + const p = newPerson( + s, + { + firstName: name.first, + lastName: name.last, + personalEmail: "", + phone: "", + telegramUsername: "", + course: "", + year: "Graduated", + campus: "External", + admin: false, + }, + date + ) + Object.assign(p.profile, { personalEmail: null, course: "", year: "", campus: null }) + return p +} + +function splitName(name: string) { + const parts = name.trim().split(/\s+/).filter(Boolean) + return { first: parts.shift() ?? "", last: parts.join(" ") } +} + +const lower = (value: string | null | undefined) => value?.trim().toLowerCase() || null + +type Clock = { date: string; now: Date } + +/** + * Mirrors PoliNetwork Auth's bound roles on People records: + * - everyone holding one gets a record, found by account, then by Telegram ID or Microsoft 365 address, and linked; + * - on linked records, a bound role's entry starts when the role is held and ends when it was mirrored and is no + * longer held. Entries People added itself (census, dashboard before linking) are left alone. + * Concepts with no bound role (for example a team nobody bound yet) stay owned by People. + */ +export function syncDirectory(s: PeopleState, directory: RoleDirectory, at: Clock) { + const bound = boundRoles(directory) + const persons = () => Object.values(s.persons) + const users = new Map(directory.users.map((u) => [u.sub, u])) + for (const u of directory.users) { + const wanted = wantedView(bound, u.roles) + if (!wanted.admin && !Object.keys(wanted.teams).length) continue + if (persons().some((p) => p.accountSub === u.sub)) continue + const email = lower(u.email) + const match = + persons().find((p) => !p.accountSub && u.telegramId && p.profile.telegramId === u.telegramId) ?? + persons().find( + (p) => !p.accountSub && email?.endsWith("@polinetwork.org") && lower(p.member?.m365Email) === email + ) + const p = match ?? blankPerson(s, splitName(u.name), at.date) + if (!match) log(p, "system", "Created from a role held in PoliNetwork Auth", at.now) + p.accountSub = u.sub + p.account = { + status: "linked", + email: u.email ?? "", + via: "PoliNetwork Auth", + linkedOn: at.date, + how: "Holds a People role in PoliNetwork Auth", + } + p.invite = null + if (!p.profile.telegramId && u.telegramId && !persons().some((other) => other.profile.telegramId === u.telegramId)) + p.profile.telegramId = u.telegramId + p.profile.telegramUsername ||= u.telegramUsername + log(p, "system", `Linked account ${u.sub}: holds a People role in PoliNetwork Auth`, at.now) + } + + for (const p of persons()) { + if (!p.accountSub || p.account.status !== "linked") continue + const wanted = wantedView(bound, users.get(p.accountSub)?.roles ?? []) + if (bound.admin.length) { + if (wanted.admin && p.admin?.status !== "active") { + p.admin = { + groups: [], + requested: [], + availableAsCapo: false, + capoOfReference: null, + capoScope: null, + ...p.admin, + status: "active", + since: at.date, + endedOn: null, + endReason: null, + } + log(p, "system", "Started admin role: held in PoliNetwork Auth", at.now) + } else if (!wanted.admin && p.admin?.status === "active" && p.synced?.admin) { + Object.assign(p.admin, { + status: "former", + endedOn: at.date, + endReason: "Role taken back in PoliNetwork Auth", + capoScope: null, + }) + log(p, "system", "Ended admin role: taken back in PoliNetwork Auth", at.now) + } + } + for (const team of C.TEAM_IDS) { + if (!teamBound(bound, team)) continue + const role = wanted.teams[team] + const active = p.teams.find((t) => t.team === team && !t.endedOn) + if (role && !active) { + p.teams.push({ team, role, since: at.date, endedOn: null, endReason: null, fields: {} }) + log(p, "system", `Joined ${team} as ${role}: held in PoliNetwork Auth`, at.now) + } else if (role && active && active.role !== role) { + active.role = role + log(p, "system", `Became ${role} of ${team}: held in PoliNetwork Auth`, at.now) + } else if (!role && active && p.synced?.teams?.includes(team)) { + Object.assign(active, { endedOn: at.date, endReason: "Role taken back in PoliNetwork Auth" }) + log(p, "system", `Ended ${team}: taken back in PoliNetwork Auth`, at.now) + } + } + markSynced(p, bound, wanted) + } +} + +/** + * Brings every member of the Microsoft 365 Soci group into the register: matched by Microsoft 365 account or address, + * or by the PoliNetwork address of a linked account, otherwise as a new record. The member number is the account's + * `employeeId`. Nothing is ended when someone leaves the group: the register's status stays with whoever keeps it. + */ +export function syncMembers(s: PeopleState, members: AzureMember[], at: Clock) { + const persons = () => Object.values(s.persons) + for (const m of members) { + const mail = lower(m.mail) + if (!mail) continue + const match = + persons().find((p) => p.azureId === m.id) ?? + persons().find((p) => lower(p.member?.m365Email) === mail) ?? + persons().find((p) => p.account.status === "linked" && lower(p.account.email) === mail) + const p = + match ?? + blankPerson( + s, + m.givenName || m.surname + ? { first: m.givenName?.trim() ?? "", last: m.surname?.trim() ?? "" } + : splitName(m.displayName ?? mail.split("@")[0]), + at.date + ) + if (!match) log(p, "system", "Created from the Microsoft 365 Soci group", at.now) + p.azureId ??= m.id + if (p.member) { + p.member.m365Email ||= m.mail + continue + } + const digits = m.employeeId?.trim() ?? "" + const number = /^\d{1,4}$/.test(digits) ? digits.padStart(4, "0") : null + if (!number || persons().some((other) => other.member?.number === number)) { + const message = `In the Microsoft 365 Soci group without a usable member number (${digits || "none"})` + if (!p.discrepancies.some((d) => d.message === message)) + p.discrepancies.push({ kind: "needs-review", message, suggestedTelegram: null }) + continue + } + p.member = { + number, + status: "active", + admittedOn: m.createdOn ?? at.date, + fee: "due", + m365Email: m.mail, + } + p.importedFeeYear = academicYear(at.date) + log(p, "system", `Imported member ${number} from the Microsoft 365 Soci group`, at.now) + } +} diff --git a/src/people/service.ts b/src/people/service.ts index be0afdd..47011f6 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -33,6 +33,19 @@ import { validateFields, } from "./model" import { receiptPdf } from "./pdf" +import { + type AzureMember, + boundRoles, + markSynced, + type PeopleRoles, + RoleChangeError, + type RoleView, + roleChanges, + roleView, + syncDirectory, + syncMembers, + wantedView, +} from "./roles" import type { Account, ImportRow, @@ -67,15 +80,79 @@ export type PeopleOptions = { inspectSigned: (sub: string, bytes: Uint8Array) => Promise<{ signer: string }> completeSigned: (sub: string, requestId: string, bytes: Uint8Array) => Promise transferType: (bytes: Uint8Array) => Promise + /** Roles bound to People in PoliNetwork Auth; `null` when the backend can't reach it. */ + peopleRoles?: PeopleRoles | null + /** Members of the Microsoft 365 Soci group. */ + azureMembers?: () => Promise } +/** How often the sweep mirrors PoliNetwork Auth and Microsoft 365 into the register. */ +export const SYNC_INTERVAL_MS = 5 * 60_000 +const NO_ROLES: RoleView = { admin: false, teams: {} } + export function createPeopleService(options: PeopleOptions) { const { store, config } = options const now = options.now ?? (() => new Date()) const date = () => today(now()) const year = () => academicYear(date()) const tx = (fn: (u: UnitOfWork) => Promise | T) => store.transaction(async (u) => fn(u)) + let lastSync = Number.NEGATIVE_INFINITY const currentFee = (p: Person) => fee(p, config, date()) ?? fail("CONFLICT", "This person is not a current member") + const roleViews = (s: PeopleState) => new Map(Object.values(s.persons).map((p) => [p.id, roleView(p)])) + const sameView = (a: RoleView, b: RoleView) => + a.admin === b.admin && C.TEAM_IDS.every((team) => a.teams[team] === b.teams[team]) + /** + * Makes PoliNetwork Auth follow the roles just changed on linked records, acting as `actor`, who must be allowed to + * there too. `strict` (a direct dashboard action) fails the whole change on a refusal; otherwise (census, import, + * linking) a refusal is noted on the record and the next sync restores whatever PoliNetwork Auth still says. + */ + async function pushRoles( + s: PeopleState, + before: Map, + actor: string, + reason: string, + strict: boolean + ) { + const roles = options.peopleRoles + if (!roles) return + const changed = Object.values(s.persons).filter((p) => { + const was = before.get(p.id) + return was && p.accountSub && p.account.status === "linked" && !sameView(was, roleView(p)) + }) + if (!changed.length) return + let directory: Awaited> + try { + directory = await roles.directory() + } catch { + if (strict) fail("PRECONDITION_FAILED", "PoliNetwork Auth is unavailable; try again later") + for (const p of changed) log(p, actor, "Couldn't update PoliNetwork Auth: it was unavailable", now()) + return + } + const bound = boundRoles(directory) + const names = new Map(directory.roles.map((r) => [r.key, r.name])) + for (const p of changed) { + const sub = p.accountSub as string + const held = new Set(directory.users.find((u) => u.sub === sub)?.roles ?? []) + try { + for (const change of roleChanges(bound, [...held], before.get(p.id) as RoleView, roleView(p))) { + await roles.change({ actor, sub, role: change.role, action: change.action, reason }) + change.action === "assign" ? held.add(change.role) : held.delete(change.role) + const name = names.get(change.role) ?? change.role + log(p, actor, `${change.action === "assign" ? "Gave" : "Took back"} ${name} in PoliNetwork Auth`, now()) + } + } catch (error) { + if (!(error instanceof RoleChangeError)) throw error + if (strict) + fail( + error.status === 403 ? "FORBIDDEN" : error.status === 404 ? "NOT_FOUND" : "PRECONDITION_FAILED", + `PoliNetwork Auth: ${error.message}` + ) + log(p, actor, `Couldn't update PoliNetwork Auth: ${error.message}`, now()) + } finally { + markSynced(p, bound, wantedView(bound, [...held])) + } + } + } function hydrateGroups(s: PeopleState, groups: TelegramGroup[]) { for (const p of Object.values(s.persons)) if (p.admin && p.profile.telegramId) { @@ -452,12 +529,14 @@ export function createPeopleService(options: PeopleOptions) { }, async endAdmin(v: Viewer, input: C.EndAdminInput) { requireGeneral(v, "people:write") - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const p = find(u.state, input.personId) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") if (p.admin.capoScope) requireGeneral(v, "people:appoint") Object.assign(p.admin, { status: "former", endedOn: date(), endReason: input.reason, capoScope: null }) log(p, v.sub, `Ended admin role: ${input.reason}`, now()) + await pushRoles(u.state, before, v.sub, input.reason, true) }) }, async setCapoScope(v: Viewer, input: C.CapoScopeInput) { @@ -513,7 +592,8 @@ export function createPeopleService(options: PeopleOptions) { }) }, async addTeamMember(v: Viewer, input: C.AddTeamMemberInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) teamAccess(u.state, v, input.teamId, true) if (input.role === "lead") requireGeneral(v, "people:appoint") validateFields(input.teamId, input.fields) @@ -531,6 +611,7 @@ export function createPeopleService(options: PeopleOptions) { fields: input.fields, }) log(p, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) + await pushRoles(u.state, before, v.sub, `Added to ${C.TEAMS[input.teamId].name} from People`, true) activeCampaign(u.state) }) }, @@ -546,7 +627,8 @@ export function createPeopleService(options: PeopleOptions) { }) }, async endTeamMembership(v: Viewer, input: C.EndTeamInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) teamAccess(u.state, v, input.teamId, true) const p = find(u.state, input.personId) const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) @@ -555,6 +637,7 @@ export function createPeopleService(options: PeopleOptions) { if (input.lastDay < t.since || input.lastDay > date()) fail("BAD_REQUEST", "Invalid last day") Object.assign(t, { endedOn: input.lastDay, endReason: input.reason }) log(p, v.sub, `Ended ${input.teamId}: ${input.reason}${input.note ? `; ${input.note}` : ""}`, now()) + await pushRoles(u.state, before, v.sub, input.reason, true) }) }, async listCampaigns(v: Viewer) { @@ -770,7 +853,8 @@ export function createPeopleService(options: PeopleOptions) { async importCommit(v: Viewer, input: C.ImportCommitInput) { requireGeneral(v, "people:write") const telegramGroups = await options.telegramGroups() - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const batch = u.state.imports[input.importId] if (!batch || batch.owner !== v.sub || batch.expiresAt < now().toISOString()) fail("NOT_FOUND", "Import preview expired") @@ -801,6 +885,7 @@ export function createPeopleService(options: PeopleOptions) { phone: r.profile.phone ?? "", telegramUsername: r.profile.telegramUsername ?? "", year: C.personInputSchema.shape.year.parse(r.profile.year), + campus: C.campusSchema.parse(r.profile.campus), admin: false, }, date() @@ -890,6 +975,7 @@ export function createPeopleService(options: PeopleOptions) { imported++ } batch.committed = true + await pushRoles(u.state, before, v.sub, `Census ${c.year} import`, false) return { imported } }) }, @@ -1085,7 +1171,12 @@ export function createPeopleService(options: PeopleOptions) { requireGeneral(v, "people:write") const account = (await options.directory()).find((a) => a.sub === input.accountId) if (!account) fail("NOT_FOUND", "IdP account not found") - return tx((u) => link(u.state, find(u.state, input.personId), account, v.sub, input.reason)) + return tx(async (u) => { + const p = find(u.state, input.personId) + link(u.state, p, account, v.sub, input.reason) + // The record's roles reach PoliNetwork Auth now that it knows whose they are. + await pushRoles(u.state, new Map([[p.id, NO_ROLES]]), v.sub, `Linked in People: ${input.reason}`, false) + }) }, async unlinkAccount(v: Viewer, input: { personId: string }) { requireGeneral(v, "people:write") @@ -1094,6 +1185,8 @@ export function createPeopleService(options: PeopleOptions) { if (!p.accountSub) fail("CONFLICT", "Account not linked") p.accountSub = null p.account = { status: "none" } + // Without an account its roles can't follow PoliNetwork Auth: People owns them from now on. + delete p.synced log(p, v.sub, "Unlinked account", now()) }) }, @@ -1253,7 +1346,8 @@ export function createPeopleService(options: PeopleOptions) { }) }, async answerCensus(v: Viewer, input: C.AnswerCensusInput) { - return tx((u) => { + return tx(async (u) => { + const before = roleViews(u.state) const p = requireOwn(u.state, v) const c = activeCampaign(u.state) if (c.status !== "open" || c.closesOn < date()) fail("CONFLICT", "Census is closed") @@ -1298,6 +1392,8 @@ export function createPeopleService(options: PeopleOptions) { })), v.sub ) + // Giving up one's own roles is always allowed in PoliNetwork Auth. + await pushRoles(u.state, before, v.sub, `Census ${c.year}: ${input.answer}`, false) }) }, async requestCorrection(v: Viewer, input: C.CorrectionInput) { @@ -1878,7 +1974,29 @@ export function createPeopleService(options: PeopleOptions) { }) } }, + /** Mirrors PoliNetwork Auth's bound roles and the Microsoft 365 Soci group into the register. */ + async syncSources() { + const [directory, members] = await Promise.allSettled([ + options.peopleRoles ? options.peopleRoles.directory() : null, + options.azureMembers ? options.azureMembers() : null, + ]) + await tx((u) => { + const at = { date: date(), now: now() } + if (directory.status === "fulfilled" && directory.value) syncDirectory(u.state, directory.value, at) + if (members.status === "fulfilled" && members.value) syncMembers(u.state, members.value, at) + activeCampaign(u.state) + }) + const failures = [directory, members].flatMap((r) => (r.status === "rejected" ? [r.reason] : [])) + if (failures.length) throw new AggregateError(failures, "People sources could not be read") + }, async sweep() { + let syncError: unknown = null + if (now().getTime() - lastSync >= SYNC_INTERVAL_MS) { + lastSync = now().getTime() + await this.syncSources().catch((error: unknown) => { + syncError = error + }) + } await tx(async (u) => { activeCampaign(u.state) for (const [id, batch] of Object.entries(u.state.batches)) @@ -1890,7 +2008,7 @@ export function createPeopleService(options: PeopleOptions) { if (batch.expiresAt < now().toISOString()) delete u.state.imports[id] for (const p of Object.values(u.state.persons)) { const f = fee(p, config, date()) - if (!f || f.status !== "due" || !p.member?.m365Email) continue + if (!f || f.status !== "due" || !p.member?.m365Email || p.importedFeeYear === f.year) continue const days = Math.round((Date.parse(f.dueOn) - Date.parse(date())) / 86400000) if (![14, 3].includes(days)) continue const id = `fee-auto:${p.id}:${f.year}:${days}` @@ -1908,6 +2026,7 @@ export function createPeopleService(options: PeopleOptions) { } }) await this.deliverPending() + if (syncError) throw syncError }, } } diff --git a/src/people/types.ts b/src/people/types.ts index dd84f48..1090f33 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -9,6 +9,13 @@ export type Person = Omit & { reminders: Record invite: { hash: string; expiresAt: string } | null pendingGroupRemovals?: { chatId: string; message: string }[] + /** + * Active roles that mirror a role held in PoliNetwork Auth (see `roles.ts`): they end when the role is taken back + * there, and ending them here takes the role back there. Roles not listed are owned by People alone. + */ + synced?: { admin?: true; teams?: import("./contract").TeamId[] } + /** The fee year whose membership came from Microsoft 365: its automatic reminders are skipped. */ + importedFeeYear?: string } export type StoredReceipt = Receipt & { officerPersonId: string diff --git a/tests/people-roles.test.ts b/tests/people-roles.test.ts new file mode 100644 index 0000000..a9600a6 --- /dev/null +++ b/tests/people-roles.test.ts @@ -0,0 +1,271 @@ +import { describe, expect, it, vi } from "vitest" +import { + type AzureMember, + boundRoles, + type PeopleRoles, + type RoleChange, + RoleChangeError, + type RoleDirectory, + roleChanges, +} from "@/people/roles" +import { SYNC_INTERVAL_MS } from "@/people/service" +import { harness, master, viewer } from "./people-fixtures" + +const ROLES: RoleDirectory["roles"] = [ + { key: "admin", name: "Admin", binding: "admin" }, + { key: "it-core", name: "IT Core", binding: "team:it:member" }, + { key: "it-lead", name: "IT Lead", binding: "team:it:lead" }, + { key: "design-member", name: "Member Design & Marketing", binding: "team:design:member" }, + { key: "design-lead", name: "Lead Design & Marketing", binding: "team:design:lead" }, + { key: "odd", name: "Unknown team", binding: "team:chess:member" }, +] + +/** An in-memory PoliNetwork Auth: `refuse` returns a reason to refuse a change. */ +function fakeAuth(users: RoleDirectory["users"], refuse: (change: RoleChange) => string | null = () => null) { + const changes: RoleChange[] = [] + const roles: PeopleRoles = { + directory: vi.fn(async () => structuredClone({ roles: ROLES, users })), + change: vi.fn(async (change: RoleChange) => { + const reason = refuse(change) + if (reason) throw new RoleChangeError(403, reason) + changes.push(change) + let user = users.find((u) => u.sub === change.sub) + if (!user) { + user = { sub: change.sub, name: change.sub, email: null, telegramId: null, telegramUsername: null, roles: [] } + users.push(user) + } + user.roles = + change.action === "assign" + ? [...new Set([...user.roles, change.role])].sort() + : user.roles.filter((role) => role !== change.role) + }), + } + return { roles, changes, users } +} + +const user = (sub: string, roles: string[], extra: Partial = {}) => ({ + sub, + name: "Giulia Neri", + email: null, + telegramId: null, + telegramUsername: null, + roles, + ...extra, +}) + +describe("roleChanges", () => { + const bound = boundRoles({ roles: ROLES, users: [] }) + it("ignores bindings to teams People doesn't have", () => { + expect(Object.values(bound.teams).flatMap((t) => [...t.member, ...t.lead])).not.toContain("odd") + }) + it("gives the bound role for a new entry and takes back every role behind an ended one, Lead first", () => { + expect(roleChanges(bound, [], { admin: false, teams: {} }, { admin: true, teams: { it: "member" } })).toEqual([ + { role: "admin", action: "assign" }, + { role: "it-core", action: "assign" }, + ]) + expect( + roleChanges(bound, ["it-core", "it-lead"], { admin: false, teams: { it: "lead" } }, { admin: false, teams: {} }) + ).toEqual([ + { role: "it-lead", action: "unassign" }, + { role: "it-core", action: "unassign" }, + ]) + }) + it("doesn't give a role already held", () => { + expect(roleChanges(bound, ["admin"], { admin: false, teams: {} }, { admin: true, teams: {} })).toEqual([]) + }) +}) + +describe("People mirrors PoliNetwork Auth", () => { + it("creates and links records for role holders, and links existing ones by Telegram ID", async () => { + const auth = fakeAuth([ + user("u-new", ["design-lead"], { name: "Giulia Neri", email: "giulia.neri@polinetwork.org" }), + user("u-tg", ["it-core"], { name: "Luca V.", telegramId: "777", telegramUsername: "lucav" }), + user("u-none", []), + ]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + state.persons["P-0003"].accountSub = null + state.persons["P-0003"].account = { status: "none" } + state.persons["P-0003"].profile.telegramId = "777" + }) + await h.service.syncSources() + const persons = Object.values(h.state().persons) + expect(persons).toHaveLength(4) + const giulia = persons.find((p) => p.accountSub === "u-new") + expect(giulia).toMatchObject({ + profile: { firstName: "Giulia", lastName: "Neri", campus: null, course: "", year: "", personalEmail: null }, + account: { status: "linked", via: "PoliNetwork Auth" }, + teams: [{ team: "design", role: "lead", endedOn: null }], + synced: { teams: ["design"] }, + }) + expect(h.state().persons["P-0003"]).toMatchObject({ + accountSub: "u-tg", + teams: [{ team: "it", role: "member" }], + }) + const rows = await h.service.listPeople(master) + expect(rows.find((r) => r.id === giulia?.id)?.profile.campus).toBeNull() + }) + + it("ends only the roles it mirrored when they are taken back", async () => { + const auth = fakeAuth([user("president", ["admin", "it-core"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + expect(h.state().persons["P-0001"]).toMatchObject({ + admin: { status: "active" }, + synced: { admin: true, teams: ["it"] }, + }) + // Anna (vice) was an admin in People before; PoliNetwork Auth never held it, so it stays. + expect(h.state().persons["P-0002"].admin?.status).toBe("active") + auth.users[0].roles = [] + await h.service.syncSources() + const p = h.state().persons["P-0001"] + expect(p.admin).toMatchObject({ status: "former", endReason: "Role taken back in PoliNetwork Auth" }) + expect(p.teams[0].endedOn).toBe("2026-10-18") + expect(p.synced).toBeUndefined() + expect(h.state().persons["P-0002"].admin?.status).toBe("active") + }) + + it("gives and takes back the role when the dashboard changes a linked record", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.addTeamMember(master, { + teamId: "design", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + expect(auth.changes).toEqual([ + { actor: "president", sub: "member", role: "design-member", action: "assign", reason: expect.any(String) }, + ]) + expect(h.state().persons["P-0003"].synced).toEqual({ teams: ["design"] }) + await h.service.endTeamMembership(master, { + teamId: "design", + personId: "P-0003", + lastDay: "2026-10-18", + reason: "Moved on", + note: "", + }) + expect(auth.changes.at(-1)).toMatchObject({ role: "design-member", action: "unassign", reason: "Moved on" }) + expect(h.state().persons["P-0003"].synced).toBeUndefined() + }) + + it("rolls the dashboard change back when PoliNetwork Auth refuses it", async () => { + const auth = fakeAuth([], () => "This role grants permissions you do not hold (tg:trusted).") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await expect( + h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + ).rejects.toMatchObject({ code: "FORBIDDEN", message: expect.stringContaining("tg:trusted") }) + expect(h.state().persons["P-0003"].teams).toEqual([]) + }) + + it("keeps unlinked records owned by People", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const { id } = await h.service.createPerson(master, { + firstName: "Sara", + lastName: "Blu", + personalEmail: "sara@example.org", + phone: "", + telegramUsername: "", + course: "Design della Comunicazione", + year: "1st year", + campus: "Bovisa", + admin: false, + }) + await h.service.addTeamMember(master, { + teamId: "design", + personId: id, + role: "member", + since: "2026-10-01", + fields: {}, + }) + expect(auth.roles.change).not.toHaveBeenCalled() + }) + + it("notes a refused census change instead of failing the answer", async () => { + const auth = fakeAuth([user("member", ["it-core"])], () => "Refused for the test.") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await h.service.answerCensus(viewer("member", ["people:self"]), { + answer: "leaving", + course: "Ingegneria Informatica", + year: "3rd year", + campus: "Leonardo", + keepGroups: [], + keepTeams: [], + reason: "Graduating", + note: "", + }) + const p = h.state().persons["P-0003"] + expect(p.census[0].answer).toBe("leaving") + expect(p.activity.some((a) => a.text.includes("Couldn't update PoliNetwork Auth: Refused for the test."))).toBe( + true + ) + }) +}) + +describe("People mirrors the Microsoft 365 Soci group", () => { + const member = (id: string, mail: string, employeeId: string | null, extra: Partial = {}) => ({ + id, + mail, + givenName: "Marta", + surname: "Gialli", + displayName: "Marta Gialli", + employeeId, + createdOn: "2025-03-02", + ...extra, + }) + + it("adds members with their number, merges with linked accounts and flags unusable numbers", async () => { + const auth = fakeAuth([user("u-marta", ["it-core"], { email: "marta.gialli@polinetwork.org" })]) + const members = [ + member("az-1", "marta.gialli@polinetwork.org", "42"), + member("az-2", "nonumber@polinetwork.org", null, { givenName: "Paolo", surname: "Viola" }), + ] + const h = harness({ peopleRoles: auth.roles, azureMembers: async () => members }) + await h.service.syncSources() + const persons = Object.values(h.state().persons) + expect(persons).toHaveLength(2) + expect(persons[0]).toMatchObject({ + accountSub: "u-marta", + azureId: "az-1", + member: { number: "0042", status: "active", admittedOn: "2025-03-02", m365Email: "marta.gialli@polinetwork.org" }, + teams: [{ team: "it" }], + }) + expect(persons[1]).toMatchObject({ member: null, discrepancies: [{ kind: "needs-review" }] }) + await h.service.syncSources() + expect(Object.values(h.state().persons)).toHaveLength(2) + expect(h.state().persons[persons[1].id].discrepancies).toHaveLength(1) + }) + + it("sends no automatic fee reminders for the year a membership was imported", async () => { + const h = harness({ azureMembers: async () => [member("az-1", "marta.gialli@polinetwork.org", "42")] }) + h.setDate("2026-10-28T08:00:00Z") + await h.service.sweep() + expect(Object.keys(h.state().outbox)).toEqual([]) + }) + + it("syncs from the sweep at most once per interval", async () => { + const azureMembers = vi.fn(async () => []) + const h = harness({ azureMembers }) + await h.service.sweep() + await h.service.sweep() + expect(azureMembers).toHaveBeenCalledTimes(1) + h.advance(SYNC_INTERVAL_MS) + await h.service.sweep() + expect(azureMembers).toHaveBeenCalledTimes(2) + }) +}) From dbf1504985c416481af4860a8e98bed678d2510e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Sun, 25 Oct 2026 13:26:39 +0000 Subject: [PATCH 2/4] fix(people): survive unreachable PoliNetwork Auth and inherited roles - A failed POST to PoliNetwork Auth (timeout, reset, DNS) is now a RoleChangeError: census answers, imports and linking note it instead of failing, and direct actions get PRECONDITION_FAILED. - Ending a role takes back only the bound roles given directly, using the IdP directory's new assigned list. Co-Authored-By: Claude Opus 5.5 --- src/idp/index.ts | 18 ++++++++++++------ src/people/roles.ts | 9 +++++++-- src/people/service.ts | 6 ++++-- tests/people-roles.test.ts | 30 ++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 10 deletions(-) diff --git a/src/idp/index.ts b/src/idp/index.ts index d168019..bc01222 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -31,6 +31,7 @@ const peopleDirectory = z.object({ telegramId: z.string().nullable(), telegramUsername: z.string().nullable(), roles: z.array(z.string()), + assigned: z.array(z.string()).optional(), }) ), }) @@ -133,12 +134,17 @@ function configure() { } catch { throw new RoleChangeError(503, `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?`) } - const response = await fetch(peopleRolesUrl, { - method: "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - body: JSON.stringify(change), - signal: AbortSignal.timeout(10_000), - }) + let response: Response + try { + response = await fetch(peopleRolesUrl, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(change), + signal: AbortSignal.timeout(10_000), + }) + } catch { + throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") + } if (response.status === 401) roleTokens.invalidate() if (response.ok) return const body = (await response.json().catch(() => null)) as { error?: unknown } | null diff --git a/src/people/roles.ts b/src/people/roles.ts index 6ac3f21..3e99e82 100644 --- a/src/people/roles.ts +++ b/src/people/roles.ts @@ -15,7 +15,10 @@ export type RoleDirectory = { email: string | null telegramId: string | null telegramUsername: string | null + /** Bound roles held, including through a parent role. */ roles: string[] + /** Those given directly, the only ones a change can take back; all of `roles` when absent. */ + assigned?: string[] }[] } export type RoleChange = { actor: string; sub: string; role: string; action: "assign" | "unassign"; reason: string } @@ -94,12 +97,14 @@ export function roleChanges( bound: Bound, held: readonly string[], before: RoleView, - after: RoleView + after: RoleView, + assigned: readonly string[] = held ): { role: string; action: RoleChange["action"] }[] { const changes: { role: string; action: RoleChange["action"] }[] = [] const holds = (keys: string[]) => keys.some((key) => held.includes(key)) + // A role held only through a parent can't be taken back on its own: the next sync shows what remains. const take = (keys: string[]) => { - for (const role of keys) if (held.includes(role)) changes.push({ role, action: "unassign" }) + for (const role of keys) if (assigned.includes(role)) changes.push({ role, action: "unassign" }) } if (bound.admin.length && before.admin !== after.admin) { if (after.admin && !holds(bound.admin)) changes.push({ role: bound.admin[0], action: "assign" }) diff --git a/src/people/service.ts b/src/people/service.ts index 47011f6..c181360 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -132,9 +132,11 @@ export function createPeopleService(options: PeopleOptions) { const names = new Map(directory.roles.map((r) => [r.key, r.name])) for (const p of changed) { const sub = p.accountSub as string - const held = new Set(directory.users.find((u) => u.sub === sub)?.roles ?? []) + const account = directory.users.find((u) => u.sub === sub) + const held = new Set(account?.roles ?? []) + const assigned = account?.assigned ?? account?.roles ?? [] try { - for (const change of roleChanges(bound, [...held], before.get(p.id) as RoleView, roleView(p))) { + for (const change of roleChanges(bound, [...held], before.get(p.id) as RoleView, roleView(p), assigned)) { await roles.change({ actor, sub, role: change.role, action: change.action, reason }) change.action === "assign" ? held.add(change.role) : held.delete(change.role) const name = names.get(change.role) ?? change.role diff --git a/tests/people-roles.test.ts b/tests/people-roles.test.ts index a9600a6..c528812 100644 --- a/tests/people-roles.test.ts +++ b/tests/people-roles.test.ts @@ -70,6 +70,13 @@ describe("roleChanges", () => { { role: "it-core", action: "unassign" }, ]) }) + it("takes back only roles given directly, not ones held through a parent", () => { + expect( + roleChanges(bound, ["it-core", "it-lead"], { admin: false, teams: { it: "lead" } }, { admin: false, teams: {} }, [ + "it-lead", + ]) + ).toEqual([{ role: "it-lead", action: "unassign" }]) + }) it("doesn't give a role already held", () => { expect(roleChanges(bound, ["admin"], { admin: false, teams: {} }, { admin: true, teams: {} })).toEqual([]) }) @@ -217,6 +224,29 @@ describe("People mirrors PoliNetwork Auth", () => { }) }) +describe("PoliNetwork Auth unreachable", () => { + it("notes the failure on a census answer instead of failing it", async () => { + const auth = fakeAuth([user("member", ["it-core"])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + vi.mocked(auth.roles.change).mockRejectedValue(new RoleChangeError(503, "PoliNetwork Auth could not be reached")) + await h.service.answerCensus(viewer("member", ["people:self"]), { + answer: "leaving", + course: "Ingegneria Informatica", + year: "3rd year", + campus: "Leonardo", + keepGroups: [], + keepTeams: [], + reason: "Graduating", + note: "", + }) + const p = h.state().persons["P-0003"] + expect(p.census[0].answer).toBe("leaving") + expect(p.activity.some((a) => a.text.includes("could not be reached"))).toBe(true) + }) +}) + describe("People mirrors the Microsoft 365 Soci group", () => { const member = (id: string, mail: string, employeeId: string | null, extra: Partial = {}) => ({ id, From c148fdb33a932e547d963f218312ab451a99d629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Mon, 26 Oct 2026 10:44:21 +0000 Subject: [PATCH 3/4] fix(people)!: grant roles only once PoliNetwork Auth confirms them Role changes on linked records become one durable command per person, saved in the People transaction and sent to Auth after it commits, so the People lock is never held across a network call. Until Auth confirms, the record keeps its previous roles: a requested or refused role never grants access. A refusal fails direct dashboard actions and flags the record for review otherwise; no answer keeps the command for the sweep, which resends it with the same ID. - Linking a record ends the roles recorded before it until Auth confirms them, keeping their history, instead of leaving refused roles active. - Auth owns every bound concept on linked records, so a Lead it refused can't survive a sync, and a sync that read Auth before a command was applied no longer overwrites it. - Other role edits, unlinking and merging wait while a command is pending, and a pending Lead appointment counts as the team's Lead. - Linked records take their account's Microsoft 365 ID, so a later PoliNetwork address doesn't create a second record on import, and identities matching several records are flagged instead of guessed. - Refreshing a linked record's identities no longer rewrites how it was linked. BREAKING CHANGE: needs PoliNetwork Auth with the command-based POST /api/internal/people-roles; deploy Auth first. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- src/idp/index.ts | 14 +- src/people/model.ts | 2 +- src/people/roles.ts | 239 +++++++++++++------------- src/people/service.ts | 243 ++++++++++++++++++++------- src/people/types.ts | 17 +- tests/people-roles.test.ts | 335 +++++++++++++++++++++++++++++++------ 7 files changed, 623 insertions(+), 233 deletions(-) diff --git a/README.md b/README.md index 5342beb..042d5fa 100644 --- a/README.md +++ b/README.md @@ -66,10 +66,10 @@ The IdP notifies `POST /internal/events` when access changes; the backend also p Every five minutes the People sweep mirrors two sources into the register: -- **PoliNetwork Auth roles.** `GET /api/internal/people-roles` lists the roles Master Admin bound to People in the IdP (`admin`, `team::member`, `team::lead`) and who holds them. Holders without a record get one (name only, linked to their account); a record without an account is linked when its Telegram ID or Microsoft 365 address matches. On linked records, an admin or team entry starts while its role is held and ends when a role it mirrored is taken back. Entries People added on its own (census import, dashboard before linking) are left alone, and so is any concept with no bound role. -- **The Microsoft 365 Soci group.** Each member gets a membership with the account's `employeeId` as member number and its creation date as admission date; a member without a usable number is flagged for review. Leaving the group changes nothing: the register keeps the status. Imported memberships get no automatic fee reminders in the year they were imported. +- **PoliNetwork Auth roles.** `GET /api/internal/people-roles` lists the roles Master Admin bound to People in the IdP (`admin`, `team::member`, `team::lead`), who holds them, and every account with a PoliNetwork Microsoft 365 login. Holders without a record get one (name only, linked to their account); a record without an account is linked when its Microsoft 365 ID, Telegram ID or Microsoft 365 address matches. When those identities point at more than one record, or at a record linked to another account, nothing changes hands and the records are flagged for review. Linked records take the account's Microsoft 365 ID, so the Soci group import finds them even after the PoliNetwork address changes. On linked records the IdP owns every bound concept: an admin or team entry starts while its role is held and ends while it is not, including entries People recorded before linking. Unlinked records, and any concept with no bound role, stay owned by People. +- **The Microsoft 365 Soci group.** Each member gets a membership with the account's `employeeId` as member number and its creation date as admission date (the activity log says so); a member without a usable number is flagged for review. Leaving the group changes nothing: the register keeps the status. Imported memberships get no automatic fee reminders in the year they were imported. -When the dashboard changes a linked record's admin or team role, or a census answer or import does, the backend gives or takes back the bound role with `POST /api/internal/people-roles`, naming the dashboard user it authenticated; the IdP decides whether that user may (no self-grants, `people:write` or `people:appoint`, bounded delegation). Direct dashboard actions fail when the IdP refuses; census answers and imports note the refusal on the record. Writes need the backend's OAuth client to hold the `idp:people:roles` scope on the internal resource; reads use the existing `idp:access:read` token. +When the dashboard changes a linked record's admin or team role, or a census answer, import, merge or account link does, the backend sends the IdP one command per person with `POST /api/internal/people-roles`: the desired state of each changed concept, the dashboard user it authenticated, and a command ID. The IdP picks the assignments, checks that user may make every one of them (no self-grants, `people:write` or `people:appoint`, bounded delegation) and applies all of them or none. The command is saved first and sent after the People transaction commits; until the IdP confirms it, the record keeps its previous roles, so a requested role never grants access, and other role edits of that person are refused. Direct dashboard actions fail when the IdP refuses; census answers, imports, merges and links note the refusal and flag the record for review, and a link ends the roles recorded before it with "Not confirmed by PoliNetwork Auth". When the IdP doesn't answer, the sweep sends the same command again: the IdP applies an ID once and answers with the current roles. Writes need the backend's OAuth client to hold the `idp:people:roles` scope on the internal resource; reads use the existing `idp:access:read` token. ## E-signing with the CIE diff --git a/src/idp/index.ts b/src/idp/index.ts index bc01222..2d88d63 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -28,6 +28,7 @@ const peopleDirectory = z.object({ sub: z.string(), name: z.string(), email: z.string().nullable(), + azureId: z.string().nullish(), telegramId: z.string().nullable(), telegramUsername: z.string().nullable(), roles: z.array(z.string()), @@ -35,6 +36,12 @@ const peopleDirectory = z.object({ }) ), }) +/** The person's bound roles after a role command, as `POST /api/internal/people-roles` answers. */ +const roleResult = z.object({ + roles: peopleDirectory.shape.roles, + held: z.array(z.string()), + assigned: z.array(z.string()), +}) /** Lets the backend give and take back the roles bound to People, for the dashboard user it authenticated. */ const PEOPLE_ROLES_SCOPE = "idp:people:roles" @@ -146,7 +153,12 @@ function configure() { throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") } if (response.status === 401) roleTokens.invalidate() - if (response.ok) return + if (response.ok) { + // The command was applied, but without a readable answer People can't confirm it: retry it by ID. + const result = roleResult.safeParse(await response.json().catch(() => null)) + if (!result.success) throw new RoleChangeError(503, "PoliNetwork Auth sent an unreadable answer") + return result.data + } const body = (await response.json().catch(() => null)) as { error?: unknown } | null throw new RoleChangeError( response.status, diff --git a/src/people/model.ts b/src/people/model.ts index 6f4456e..a103a87 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -44,7 +44,7 @@ export function requireOwn(s: PeopleState, v: Viewer) { requireSelf(v) return own(s, v) ?? fail("FORBIDDEN", "Confirm your account link first") } -export function leads(p: Person | null, team?: C.TeamId) { +export function leads(p: Pick | null, team?: C.TeamId) { return p?.teams.filter((m) => !m.endedOn && m.role === "lead" && (!team || m.team === team)).map((m) => m.team) ?? [] } export function teamAccess(s: PeopleState, v: Viewer, team: C.TeamId, write: boolean) { diff --git a/src/people/roles.ts b/src/people/roles.ts index 3e99e82..941200e 100644 --- a/src/people/roles.ts +++ b/src/people/roles.ts @@ -13,6 +13,7 @@ export type RoleDirectory = { sub: string name: string email: string | null + azureId?: string | null telegramId: string | null telegramUsername: string | null /** Bound roles held, including through a parent role. */ @@ -21,10 +22,17 @@ export type RoleDirectory = { assigned?: string[] }[] } -export type RoleChange = { actor: string; sub: string; role: string; action: "assign" | "unassign"; reason: string } +export type RoleChange = { + id: string + actor: string + sub: string + reason: string + changes: ({ kind: "admin"; active: boolean } | { kind: "team"; team: C.TeamId; role: "member" | "lead" | null })[] +} +export type RoleResult = { roles: RoleDirectory["roles"]; held: string[]; assigned: string[] } export type PeopleRoles = { directory(): Promise - change(change: RoleChange): Promise + change(change: RoleChange): Promise } /** A member of the Microsoft 365 Soci group. */ export type AzureMember = { @@ -83,59 +91,21 @@ export function wantedView(bound: Bound, held: readonly string[]): RoleView { return view } -export function roleView(p: Person): RoleView { +export function roleView(p: Pick): RoleView { const view: RoleView = { admin: p.admin?.status === "active", teams: {} } for (const t of p.teams) if (!t.endedOn) view.teams[t.team] = t.role return view } -/** - * The changes in PoliNetwork Auth that turn `before` into `after` for an account holding `held`. Ending a role takes - * back every bound role behind it, Lead roles first so a refused Lead change leaves the membership untouched. - */ -export function roleChanges( - bound: Bound, - held: readonly string[], - before: RoleView, - after: RoleView, - assigned: readonly string[] = held -): { role: string; action: RoleChange["action"] }[] { - const changes: { role: string; action: RoleChange["action"] }[] = [] - const holds = (keys: string[]) => keys.some((key) => held.includes(key)) - // A role held only through a parent can't be taken back on its own: the next sync shows what remains. - const take = (keys: string[]) => { - for (const role of keys) if (assigned.includes(role)) changes.push({ role, action: "unassign" }) - } - if (bound.admin.length && before.admin !== after.admin) { - if (after.admin && !holds(bound.admin)) changes.push({ role: bound.admin[0], action: "assign" }) - if (!after.admin) take(bound.admin) - } - for (const team of C.TEAM_IDS) { - const { member, lead } = bound.teams[team] - const [was, now] = [before.teams[team], after.teams[team]] - if (!teamBound(bound, team) || was === now) continue - if (!now) { - take(lead) - take(member) - continue - } - if (was === "lead") take(lead) - const keys = now === "lead" && lead.length ? lead : member - if (keys.length && !holds(keys)) changes.push({ role: keys[0], action: "assign" }) - } +/** Send desired organizational states; Auth chooses and validates the actual role assignments. */ +export function roleChanges(before: RoleView, after: RoleView): RoleChange["changes"] { + const changes: RoleChange["changes"] = [] + if (before.admin !== after.admin) changes.push({ kind: "admin", active: after.admin }) + for (const team of C.TEAM_IDS) + if (before.teams[team] !== after.teams[team]) changes.push({ kind: "team", team, role: after.teams[team] ?? null }) return changes } -/** Records which of the person's active roles now mirror PoliNetwork Auth. */ -export function markSynced(p: Person, bound: Bound, view: RoleView) { - const teams = new Set(p.synced?.teams ?? []) - let admin = !!p.synced?.admin - if (bound.admin.length) admin = view.admin - for (const team of C.TEAM_IDS) if (teamBound(bound, team)) view.teams[team] ? teams.add(team) : teams.delete(team) - p.synced = { ...(admin ? { admin: true as const } : {}), ...(teams.size ? { teams: [...teams].sort() } : {}) } - if (!p.synced.admin && !p.synced.teams) delete p.synced -} - /** A record with only a name, for someone People hears of from PoliNetwork Auth or Microsoft 365. */ export function blankPerson(s: PeopleState, name: { first: string; last: string }, date: string) { const p = newPerson( @@ -165,12 +135,17 @@ function splitName(name: string) { const lower = (value: string | null | undefined) => value?.trim().toLowerCase() || null type Clock = { date: string; now: Date } +/** Asks HR to look at the record, once per distinct reason. */ +export function flagForReview(p: Person, message: string) { + if (!p.discrepancies.some((d) => d.message === message)) + p.discrepancies.push({ kind: "needs-review", message, suggestedTelegram: null }) +} /** * Mirrors PoliNetwork Auth's bound roles on People records: * - everyone holding one gets a record, found by account, then by Telegram ID or Microsoft 365 address, and linked; * - on linked records, a bound role's entry starts when the role is held and ends when it was mirrored and is no - * longer held. Entries People added itself (census, dashboard before linking) are left alone. + * longer held. Previously local entries on linked records also follow Auth. * Concepts with no bound role (for example a team nobody bound yet) stay owned by People. */ export function syncDirectory(s: PeopleState, directory: RoleDirectory, at: Clock) { @@ -179,75 +154,96 @@ export function syncDirectory(s: PeopleState, directory: RoleDirectory, at: Cloc const users = new Map(directory.users.map((u) => [u.sub, u])) for (const u of directory.users) { const wanted = wantedView(bound, u.roles) - if (!wanted.admin && !Object.keys(wanted.teams).length) continue - if (persons().some((p) => p.accountSub === u.sub)) continue + const existing = persons().find((p) => p.accountSub === u.sub) + // Accounts without a bound role only refresh the identities of the record already linked to them. + if (!existing && !wanted.admin && !Object.keys(wanted.teams).length) continue const email = lower(u.email) - const match = - persons().find((p) => !p.accountSub && u.telegramId && p.profile.telegramId === u.telegramId) ?? - persons().find( - (p) => !p.accountSub && email?.endsWith("@polinetwork.org") && lower(p.member?.m365Email) === email - ) - const p = match ?? blankPerson(s, splitName(u.name), at.date) - if (!match) log(p, "system", "Created from a role held in PoliNetwork Auth", at.now) - p.accountSub = u.sub - p.account = { - status: "linked", - email: u.email ?? "", - via: "PoliNetwork Auth", - linkedOn: at.date, - how: "Holds a People role in PoliNetwork Auth", + const matches = persons().filter( + (p) => + p === existing || + (u.azureId && p.azureId === u.azureId) || + (u.telegramId && p.profile.telegramId === u.telegramId) || + (email?.endsWith("@polinetwork.org") && lower(p.member?.m365Email) === email) + ) + // Never guess between records, or move an identity off the record holding it: HR decides. + if ( + matches.length > 1 || + matches.some((p) => p.accountSub && p.accountSub !== u.sub) || + (existing?.azureId && u.azureId && existing.azureId !== u.azureId) + ) { + for (const p of matches) + flagForReview(p, `PoliNetwork Auth account ${u.sub} matches more than one record: check their account links.`) + continue + } + const p = matches[0] ?? blankPerson(s, splitName(u.name), at.date) + if (!matches.length) log(p, "system", "Created from a role held in PoliNetwork Auth", at.now) + if (existing) { + if (existing.account.status === "linked") existing.account.email = u.email ?? existing.account.email + } else { + p.accountSub = u.sub + p.account = { + status: "linked", + email: u.email ?? "", + via: "PoliNetwork Auth", + linkedOn: at.date, + how: "Holds a People role in PoliNetwork Auth", + } + p.invite = null + log(p, "system", `Linked account ${u.sub}: holds a People role in PoliNetwork Auth`, at.now) } - p.invite = null - if (!p.profile.telegramId && u.telegramId && !persons().some((other) => other.profile.telegramId === u.telegramId)) - p.profile.telegramId = u.telegramId + // Microsoft 365 members are matched by this ID, so a later PoliNetwork address doesn't make a second record. + if (u.azureId) p.azureId = u.azureId + if (!p.profile.telegramId && u.telegramId) p.profile.telegramId = u.telegramId p.profile.telegramUsername ||= u.telegramUsername - log(p, "system", `Linked account ${u.sub}: holds a People role in PoliNetwork Auth`, at.now) } for (const p of persons()) { - if (!p.accountSub || p.account.status !== "linked") continue - const wanted = wantedView(bound, users.get(p.accountSub)?.roles ?? []) - if (bound.admin.length) { - if (wanted.admin && p.admin?.status !== "active") { - p.admin = { - groups: [], - requested: [], - availableAsCapo: false, - capoOfReference: null, - capoScope: null, - ...p.admin, - status: "active", - since: at.date, - endedOn: null, - endReason: null, - } - log(p, "system", "Started admin role: held in PoliNetwork Auth", at.now) - } else if (!wanted.admin && p.admin?.status === "active" && p.synced?.admin) { - Object.assign(p.admin, { - status: "former", - endedOn: at.date, - endReason: "Role taken back in PoliNetwork Auth", - capoScope: null, - }) - log(p, "system", "Ended admin role: taken back in PoliNetwork Auth", at.now) + if (!p.accountSub || p.account.status !== "linked" || p.roleCommand) continue + syncPersonRoles(p, bound, wantedView(bound, users.get(p.accountSub)?.roles ?? []), at) + } +} + +/** For linked records Auth owns every bound concept, including previously local entries. */ +export function syncPersonRoles(p: Person, bound: Bound, wanted: RoleView, at: Clock) { + if (bound.admin.length) { + if (wanted.admin && p.admin?.status !== "active") { + p.admin = { + groups: [], + requested: [], + availableAsCapo: false, + capoOfReference: null, + capoScope: null, + ...p.admin, + status: "active", + since: at.date, + endedOn: null, + endReason: null, } + log(p, "system", "Started admin role: held in PoliNetwork Auth", at.now) + } else if (!wanted.admin && p.admin?.status === "active") { + Object.assign(p.admin, { + status: "former", + endedOn: at.date, + endReason: "Not held in PoliNetwork Auth", + capoScope: null, + }) + log(p, "system", "Ended admin role: not held in PoliNetwork Auth", at.now) } - for (const team of C.TEAM_IDS) { - if (!teamBound(bound, team)) continue - const role = wanted.teams[team] - const active = p.teams.find((t) => t.team === team && !t.endedOn) - if (role && !active) { - p.teams.push({ team, role, since: at.date, endedOn: null, endReason: null, fields: {} }) - log(p, "system", `Joined ${team} as ${role}: held in PoliNetwork Auth`, at.now) - } else if (role && active && active.role !== role) { - active.role = role - log(p, "system", `Became ${role} of ${team}: held in PoliNetwork Auth`, at.now) - } else if (!role && active && p.synced?.teams?.includes(team)) { - Object.assign(active, { endedOn: at.date, endReason: "Role taken back in PoliNetwork Auth" }) - log(p, "system", `Ended ${team}: taken back in PoliNetwork Auth`, at.now) - } + } + for (const team of C.TEAM_IDS) { + if (!teamBound(bound, team)) continue + const role = wanted.teams[team] + const active = p.teams.find((t) => t.team === team && !t.endedOn) + if (role && !active) { + p.teams.push({ team, role, since: at.date, endedOn: null, endReason: null, fields: {} }) + log(p, "system", `Joined ${team} as ${role}: held in PoliNetwork Auth`, at.now) + } else if (role && active && active.role !== role) { + active.role = role + log(p, "system", `Became ${role} of ${team}: held in PoliNetwork Auth`, at.now) + } else if (!role && active) { + Object.assign(active, { endedOn: at.date, endReason: "Not held in PoliNetwork Auth" }) + log(p, "system", `Ended ${team}: not held in PoliNetwork Auth`, at.now) } - markSynced(p, bound, wanted) } } @@ -261,10 +257,18 @@ export function syncMembers(s: PeopleState, members: AzureMember[], at: Clock) { for (const m of members) { const mail = lower(m.mail) if (!mail) continue - const match = - persons().find((p) => p.azureId === m.id) ?? - persons().find((p) => lower(p.member?.m365Email) === mail) ?? - persons().find((p) => p.account.status === "linked" && lower(p.account.email) === mail) + const matches = persons().filter( + (p) => + p.azureId === m.id || + lower(p.member?.m365Email) === mail || + (p.account.status === "linked" && lower(p.account.email) === mail) + ) + if (matches.length > 1 || matches.some((p) => p.azureId && p.azureId !== m.id)) { + for (const p of matches) + flagForReview(p, "Microsoft 365 identities match conflicting People records; review the account links.") + continue + } + const match = matches[0] const p = match ?? blankPerson( @@ -283,9 +287,7 @@ export function syncMembers(s: PeopleState, members: AzureMember[], at: Clock) { const digits = m.employeeId?.trim() ?? "" const number = /^\d{1,4}$/.test(digits) ? digits.padStart(4, "0") : null if (!number || persons().some((other) => other.member?.number === number)) { - const message = `In the Microsoft 365 Soci group without a usable member number (${digits || "none"})` - if (!p.discrepancies.some((d) => d.message === message)) - p.discrepancies.push({ kind: "needs-review", message, suggestedTelegram: null }) + flagForReview(p, `In the Microsoft 365 Soci group without a usable member number (${digits || "none"})`) continue } p.member = { @@ -296,6 +298,11 @@ export function syncMembers(s: PeopleState, members: AzureMember[], at: Clock) { m365Email: m.mail, } p.importedFeeYear = academicYear(at.date) - log(p, "system", `Imported member ${number} from the Microsoft 365 Soci group`, at.now) + log( + p, + "system", + `Imported member ${number} from the Microsoft 365 Soci group${m.createdOn ? "; admission date taken from the account's creation" : ""}`, + at.now + ) } } diff --git a/src/people/service.ts b/src/people/service.ts index c181360..bce4a14 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -36,14 +36,15 @@ import { receiptPdf } from "./pdf" import { type AzureMember, boundRoles, - markSynced, + flagForReview, type PeopleRoles, RoleChangeError, - type RoleView, + type RoleResult, roleChanges, roleView, syncDirectory, syncMembers, + syncPersonRoles, wantedView, } from "./roles" import type { @@ -88,72 +89,174 @@ export type PeopleOptions = { /** How often the sweep mirrors PoliNetwork Auth and Microsoft 365 into the register. */ export const SYNC_INTERVAL_MS = 5 * 60_000 -const NO_ROLES: RoleView = { admin: false, teams: {} } +type RoleSnapshot = Pick +const PENDING_ROLES = "A role change for this person is waiting for PoliNetwork Auth; try again in a moment." +const AWAITING_AUTH = "Awaiting confirmation from PoliNetwork Auth" + +/** + * The roles of a record about to be linked that PoliNetwork Auth has confirmed: none. Its active roles are ended until + * Auth confirms them, so a role Auth refuses never grants access; their history and details are kept. + */ +function unconfirmed(p: Person, on: string): RoleSnapshot { + const ended = { endedOn: on, endReason: AWAITING_AUTH } + return structuredClone({ + admin: + p.admin?.status === "active" ? { ...p.admin, ...ended, status: "former" as const, capoScope: null } : p.admin, + teams: p.teams.map((t) => (t.endedOn ? t : { ...t, ...ended })), + }) +} export function createPeopleService(options: PeopleOptions) { const { store, config } = options const now = options.now ?? (() => new Date()) const date = () => today(now()) const year = () => academicYear(date()) - const tx = (fn: (u: UnitOfWork) => Promise | T) => store.transaction(async (u) => fn(u)) + /** + * A People transaction. Role commands it records for PoliNetwork Auth are delivered after it commits, so the People + * lock is never held across a call to Auth; a refused direct dashboard change (`strict`) then fails the call. + */ + const tx = async (fn: (u: UnitOfWork) => Promise | T): Promise => { + let queued: { personId: string; strict: boolean }[] = [] + const result = await store.transaction(async (u) => { + const known = new Set(Object.values(u.state.persons).flatMap((p) => p.roleCommand?.request.id ?? [])) + const result = await fn(u) + queued = Object.values(u.state.persons).flatMap((p) => + p.roleCommand && !known.has(p.roleCommand.request.id) ? [{ personId: p.id, strict: p.roleCommand.strict }] : [] + ) + return result + }) + for (const command of queued) { + const error = await deliverRoleCommand(command.personId) + if (error && command.strict) + fail( + error.status === 403 ? "FORBIDDEN" : error.status === 404 ? "NOT_FOUND" : "PRECONDITION_FAILED", + error.message + ) + } + return result + } let lastSync = Number.NEGATIVE_INFINITY const currentFee = (p: Person) => fee(p, config, date()) ?? fail("CONFLICT", "This person is not a current member") - const roleViews = (s: PeopleState) => new Map(Object.values(s.persons).map((p) => [p.id, roleView(p)])) - const sameView = (a: RoleView, b: RoleView) => - a.admin === b.admin && C.TEAM_IDS.every((team) => a.teams[team] === b.teams[team]) + const roleViews = (s: PeopleState) => + new Map( + Object.values(s.persons).map((p) => [p.id, structuredClone({ admin: p.admin, teams: p.teams })]) + ) + /** Lets a sync tell whether a role changed while it read PoliNetwork Auth. */ + const bumpRoles = (s: PeopleState) => { + s.counters.roleRevision = (s.counters.roleRevision ?? 0) + 1 + } + const settled = (p: Person) => { + if (p.roleCommand) fail("CONFLICT", PENDING_ROLES) + } + /** - * Makes PoliNetwork Auth follow the roles just changed on linked records, acting as `actor`, who must be allowed to - * there too. `strict` (a direct dashboard action) fails the whole change on a refusal; otherwise (census, import, - * linking) a refusal is noted on the record and the next sync restores whatever PoliNetwork Auth still says. + * Turns the roles just changed on linked records into one command each for PoliNetwork Auth, acting as `actor`, who + * must be allowed to there too. Until Auth confirms it, the record keeps the roles it had (`before`): a requested + * role grants nothing. `strict` (a direct dashboard action) fails the call on a refusal; otherwise (census, import, + * linking) the refusal is noted on the record for HR. */ - async function pushRoles( + function pushRoles( s: PeopleState, - before: Map, + before: Map, actor: string, reason: string, strict: boolean ) { - const roles = options.peopleRoles - if (!roles) return - const changed = Object.values(s.persons).filter((p) => { + if (!options.peopleRoles) return + for (const p of Object.values(s.persons)) { const was = before.get(p.id) - return was && p.accountSub && p.account.status === "linked" && !sameView(was, roleView(p)) - }) - if (!changed.length) return - let directory: Awaited> - try { - directory = await roles.directory() - } catch { - if (strict) fail("PRECONDITION_FAILED", "PoliNetwork Auth is unavailable; try again later") - for (const p of changed) log(p, actor, "Couldn't update PoliNetwork Auth: it was unavailable", now()) - return + if (!was || !p.accountSub || p.account.status !== "linked") continue + const changes = roleChanges(roleView(was), roleView(p)) + if (!changes.length) continue + settled(p) + p.roleCommand = { + // PoliNetwork Auth keeps reasons of up to 500 characters. + request: { id: randomUUID(), actor, sub: p.accountSub, reason: reason.slice(0, 500), changes }, + desired: structuredClone({ admin: p.admin, teams: p.teams }), + strict, + } + for (const change of changes) + if (change.kind === "admin") p.admin = structuredClone(was.admin) + else + p.teams = [ + ...p.teams.filter((t) => t.team !== change.team), + ...structuredClone(was.teams.filter((t) => t.team === change.team)), + ] + log(p, actor, `Asked PoliNetwork Auth to change roles: ${reason}`, now()) + bumpRoles(s) } - const bound = boundRoles(directory) - const names = new Map(directory.roles.map((r) => [r.key, r.name])) - for (const p of changed) { - const sub = p.accountSub as string - const account = directory.users.find((u) => u.sub === sub) - const held = new Set(account?.roles ?? []) - const assigned = account?.assigned ?? account?.roles ?? [] - try { - for (const change of roleChanges(bound, [...held], before.get(p.id) as RoleView, roleView(p), assigned)) { - await roles.change({ actor, sub, role: change.role, action: change.action, reason }) - change.action === "assign" ? held.add(change.role) : held.delete(change.role) - const name = names.get(change.role) ?? change.role - log(p, actor, `${change.action === "assign" ? "Gave" : "Took back"} ${name} in PoliNetwork Auth`, now()) + } + + /** + * Sends a person's pending role command and applies Auth's answer. A refusal drops it; no answer (Auth unreachable, + * failing, or the response lost) keeps it for the sweep to send again with the same ID, which Auth applies once. + */ + async function deliverRoleCommand(personId: string): Promise { + const pending = await tx((u) => structuredClone(u.state.persons[personId]?.roleCommand)) + if (!pending || !options.peopleRoles) return null + const { request } = pending + let result: RoleResult + try { + result = await options.peopleRoles.change(request) + } catch (error) { + if (!(error instanceof RoleChangeError)) console.error(error) + const failure = error instanceof RoleChangeError ? error : new RoleChangeError(503, "No answer") + const unanswered = failure.status >= 500 || failure.status === 408 || failure.status === 429 + await tx((u) => { + const p = u.state.persons[personId] + if (p?.roleCommand?.request.id !== request.id) return + if (unanswered) { + if (!pending.unanswered) + log( + p, + request.actor, + `PoliNetwork Auth didn't answer (${failure.message}); the change will be retried`, + now() + ) + p.roleCommand.unanswered = true + return } - } catch (error) { - if (!(error instanceof RoleChangeError)) throw error - if (strict) - fail( - error.status === 403 ? "FORBIDDEN" : error.status === 404 ? "NOT_FOUND" : "PRECONDITION_FAILED", - `PoliNetwork Auth: ${error.message}` + delete p.roleCommand + for (const t of p.teams) if (t.endReason === AWAITING_AUTH) t.endReason = "Not confirmed by PoliNetwork Auth" + if (p.admin?.endReason === AWAITING_AUTH) p.admin.endReason = "Not confirmed by PoliNetwork Auth" + log(p, request.actor, `PoliNetwork Auth refused the role change: ${failure.message}`, now()) + if (!pending.strict) + flagForReview( + p, + `PoliNetwork Auth refused a role change (${request.reason}): ${failure.message} Its roles stay as Auth holds them: change them again from People or in Auth.` ) - log(p, actor, `Couldn't update PoliNetwork Auth: ${error.message}`, now()) - } finally { - markSynced(p, bound, wantedView(bound, [...held])) - } + bumpRoles(u.state) + }) + return new RoleChangeError( + failure.status, + unanswered + ? "PoliNetwork Auth didn't answer. The change is saved and will be retried automatically: don't repeat it." + : `PoliNetwork Auth: ${failure.message}` + ) } + await tx((u) => { + const p = u.state.persons[personId] + if (p?.roleCommand?.request.id !== request.id) return + for (const change of request.changes) + if (change.kind === "admin") + // Telegram groups are refreshed on every read: keep the current ones. + p.admin = pending.desired.admin && { + ...pending.desired.admin, + groups: p.admin?.groups ?? pending.desired.admin.groups, + } + else + p.teams = [ + ...p.teams.filter((t) => t.team !== change.team), + ...pending.desired.teams.filter((t) => t.team === change.team), + ] + delete p.roleCommand + log(p, request.actor, `PoliNetwork Auth confirmed the role change: ${request.reason}`, now()) + // What Auth holds after the command wins, for example a role it kept through a parent role. + const bound = boundRoles({ roles: result.roles, users: [] }) + syncPersonRoles(p, bound, wantedView(bound, result.held), { date: date(), now: now() }) + bumpRoles(u.state) + }) + return null } function hydrateGroups(s: PeopleState, groups: TelegramGroup[]) { for (const p of Object.values(s.persons)) @@ -294,10 +397,12 @@ export function createPeopleService(options: PeopleOptions) { if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) fail("CONFLICT", "This account is already linked to another person") if (p.accountSub && p.accountSub !== account.sub) fail("CONFLICT", "Unlink the existing account first") + const wasLinked = !!p.accountSub p.accountSub = account.sub p.account = { status: "linked", email: account.email ?? "", via: "IdP", linkedOn: date(), how: reason } p.invite = null log(p, actor, `Linked account ${account.sub}: ${reason}`, now()) + if (!wasLinked) pushRoles(s, new Map([[p.id, unconfirmed(p, date())]]), actor, `Linked in People: ${reason}`, false) } function candidate(s: PeopleState, v: Viewer, account: Account | undefined) { if (!account) return null @@ -538,13 +643,14 @@ export function createPeopleService(options: PeopleOptions) { if (p.admin.capoScope) requireGeneral(v, "people:appoint") Object.assign(p.admin, { status: "former", endedOn: date(), endReason: input.reason, capoScope: null }) log(p, v.sub, `Ended admin role: ${input.reason}`, now()) - await pushRoles(u.state, before, v.sub, input.reason, true) + pushRoles(u.state, before, v.sub, input.reason, true) }) }, async setCapoScope(v: Viewer, input: C.CapoScopeInput) { requireGeneral(v, "people:appoint") return tx((u) => { const p = find(u.state, input.personId) + settled(p) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") p.admin.capoScope = input.scope || null log(p, v.sub, `Set Capo Admin scope: ${input.scope ?? "none"}`, now()) @@ -554,6 +660,7 @@ export function createPeopleService(options: PeopleOptions) { requireGeneral(v, "people:write") return tx((u) => { const p = find(u.state, input.personId) + settled(p) if (p.admin?.status !== "active") fail("CONFLICT", "Not an active admin") const capo = input.capoId ? find(u.state, input.capoId) : null if (capo && (capo.id === p.id || capo.admin?.status !== "active" || !capo.admin.capoScope)) @@ -601,7 +708,13 @@ export function createPeopleService(options: PeopleOptions) { validateFields(input.teamId, input.fields) const p = find(u.state, input.personId) if (p.teams.some((t) => t.team === input.teamId && !t.endedOn)) fail("CONFLICT", "Already active in this team") - if (input.role === "lead" && Object.values(u.state.persons).some((p) => leads(p, input.teamId).length)) + // Including a Lead appointment PoliNetwork Auth hasn't confirmed yet. + if ( + input.role === "lead" && + Object.values(u.state.persons).some( + (p) => leads(p, input.teamId).length || (p.roleCommand && leads(p.roleCommand.desired, input.teamId).length) + ) + ) fail("CONFLICT", "End the existing Lead appointment first") if (input.since > date()) fail("BAD_REQUEST", "Start date is in the future") p.teams.push({ @@ -613,7 +726,7 @@ export function createPeopleService(options: PeopleOptions) { fields: input.fields, }) log(p, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) - await pushRoles(u.state, before, v.sub, `Added to ${C.TEAMS[input.teamId].name} from People`, true) + pushRoles(u.state, before, v.sub, `Added to ${C.TEAMS[input.teamId].name} from People`, true) activeCampaign(u.state) }) }, @@ -622,6 +735,7 @@ export function createPeopleService(options: PeopleOptions) { teamAccess(u.state, v, input.teamId, true) validateFields(input.teamId, input.fields) const p = find(u.state, input.personId) + settled(p) const t = p.teams.find((t) => t.team === input.teamId && !t.endedOn) if (!t) fail("CONFLICT", "No active team membership") t.fields = input.fields @@ -639,7 +753,7 @@ export function createPeopleService(options: PeopleOptions) { if (input.lastDay < t.since || input.lastDay > date()) fail("BAD_REQUEST", "Invalid last day") Object.assign(t, { endedOn: input.lastDay, endReason: input.reason }) log(p, v.sub, `Ended ${input.teamId}: ${input.reason}${input.note ? `; ${input.note}` : ""}`, now()) - await pushRoles(u.state, before, v.sub, input.reason, true) + pushRoles(u.state, before, v.sub, input.reason, true) }) }, async listCampaigns(v: Viewer) { @@ -977,7 +1091,7 @@ export function createPeopleService(options: PeopleOptions) { imported++ } batch.committed = true - await pushRoles(u.state, before, v.sub, `Census ${c.year} import`, false) + pushRoles(u.state, before, v.sub, `Census ${c.year} import`, false) return { imported } }) }, @@ -1081,12 +1195,19 @@ export function createPeopleService(options: PeopleOptions) { const second = find(u.state, r.other.id) if ([first.accountSub, second.accountSub].some((sub) => sub && sub !== account.sub)) fail("CONFLICT", "Unlink the other account before merging") + settled(first) + settled(second) + const before = roleViews(u.state) + const linked = !!first.accountSub r.mergedRecord = structuredClone(second) mergePeople(u.state, first, second, v, config, now()) link(u.state, first, account, v.sub, input.reason) + // Roles merged into an already linked record reach PoliNetwork Auth like any other change. + if (linked) pushRoles(u.state, before, v.sub, `Merged ${second.id}: ${input.reason}`, false) } else if (input.resolution === "unlink" && r.record) { const p = find(u.state, r.record.id) if (p.accountSub === r.sub) { + settled(p) p.accountSub = null p.account = { status: "none" } log(p, v.sub, `Unlinked account: ${input.reason}`, now()) @@ -1176,8 +1297,6 @@ export function createPeopleService(options: PeopleOptions) { return tx(async (u) => { const p = find(u.state, input.personId) link(u.state, p, account, v.sub, input.reason) - // The record's roles reach PoliNetwork Auth now that it knows whose they are. - await pushRoles(u.state, new Map([[p.id, NO_ROLES]]), v.sub, `Linked in People: ${input.reason}`, false) }) }, async unlinkAccount(v: Viewer, input: { personId: string }) { @@ -1185,10 +1304,10 @@ export function createPeopleService(options: PeopleOptions) { return tx((u) => { const p = find(u.state, input.personId) if (!p.accountSub) fail("CONFLICT", "Account not linked") + settled(p) p.accountSub = null p.account = { status: "none" } // Without an account its roles can't follow PoliNetwork Auth: People owns them from now on. - delete p.synced log(p, v.sub, "Unlinked account", now()) }) }, @@ -1395,7 +1514,7 @@ export function createPeopleService(options: PeopleOptions) { v.sub ) // Giving up one's own roles is always allowed in PoliNetwork Auth. - await pushRoles(u.state, before, v.sub, `Census ${c.year}: ${input.answer}`, false) + pushRoles(u.state, before, v.sub, `Census ${c.year}: ${input.answer}`, false) }) }, async requestCorrection(v: Viewer, input: C.CorrectionInput) { @@ -1978,13 +2097,15 @@ export function createPeopleService(options: PeopleOptions) { }, /** Mirrors PoliNetwork Auth's bound roles and the Microsoft 365 Soci group into the register. */ async syncSources() { + const revision = await tx((u) => u.state.counters.roleRevision ?? 0) const [directory, members] = await Promise.allSettled([ options.peopleRoles ? options.peopleRoles.directory() : null, options.azureMembers ? options.azureMembers() : null, ]) await tx((u) => { const at = { date: date(), now: now() } - if (directory.status === "fulfilled" && directory.value) syncDirectory(u.state, directory.value, at) + if (directory.status === "fulfilled" && directory.value && revision === (u.state.counters.roleRevision ?? 0)) + syncDirectory(u.state, directory.value, at) if (members.status === "fulfilled" && members.value) syncMembers(u.state, members.value, at) activeCampaign(u.state) }) @@ -1992,6 +2113,12 @@ export function createPeopleService(options: PeopleOptions) { if (failures.length) throw new AggregateError(failures, "People sources could not be read") }, async sweep() { + const pending = await tx((u) => + Object.values(u.state.persons) + .filter((p) => p.roleCommand) + .map((p) => p.id) + ) + for (const id of pending) await deliverRoleCommand(id) let syncError: unknown = null if (now().getTime() - lastSync >= SYNC_INTERVAL_MS) { lastSync = now().getTime() diff --git a/src/people/types.ts b/src/people/types.ts index 1090f33..a32c110 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -9,13 +9,20 @@ export type Person = Omit & { reminders: Record invite: { hash: string; expiresAt: string } | null pendingGroupRemovals?: { chatId: string; message: string }[] - /** - * Active roles that mirror a role held in PoliNetwork Auth (see `roles.ts`): they end when the role is taken back - * there, and ending them here takes the role back there. Roles not listed are owned by People alone. - */ - synced?: { admin?: true; teams?: import("./contract").TeamId[] } /** The fee year whose membership came from Microsoft 365: its automatic reminders are skipped. */ importedFeeYear?: string + /** + * A role change sent to PoliNetwork Auth and not yet answered. `admin` and `teams` keep the roles Auth confirmed; + * `desired` replaces them for the changed concepts once Auth confirms, so a requested role never grants access. + */ + roleCommand?: { + request: import("./roles").RoleChange + desired: Pick + /** A direct dashboard action, whose caller sees a refusal; otherwise HR is asked to review it. */ + strict: boolean + /** Auth didn't answer at least once; the sweep sends it again with the same ID. */ + unanswered?: true + } } export type StoredReceipt = Receipt & { officerPersonId: string diff --git a/tests/people-roles.test.ts b/tests/people-roles.test.ts index c528812..b55c285 100644 --- a/tests/people-roles.test.ts +++ b/tests/people-roles.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from "vitest" import { type AzureMember, - boundRoles, type PeopleRoles, type RoleChange, RoleChangeError, @@ -20,24 +19,55 @@ const ROLES: RoleDirectory["roles"] = [ { key: "odd", name: "Unknown team", binding: "team:chess:member" }, ] -/** An in-memory PoliNetwork Auth: `refuse` returns a reason to refuse a change. */ +/** Atomic, idempotent Auth contract fake. Individual assignment effects are exposed for assertions. */ function fakeAuth(users: RoleDirectory["users"], refuse: (change: RoleChange) => string | null = () => null) { - const changes: RoleChange[] = [] + const changes: { actor: string; sub: string; role: string; action: "assign" | "unassign"; reason: string }[] = [] + const receipts = new Map() + const result = (sub: string) => ({ + roles: ROLES, + held: users.find((u) => u.sub === sub)?.roles ?? [], + assigned: users.find((u) => u.sub === sub)?.roles ?? [], + }) const roles: PeopleRoles = { directory: vi.fn(async () => structuredClone({ roles: ROLES, users })), - change: vi.fn(async (change: RoleChange) => { - const reason = refuse(change) + change: vi.fn(async (command: RoleChange) => { + if (receipts.has(command.id)) return structuredClone(result(command.sub)) + const reason = refuse(command) if (reason) throw new RoleChangeError(403, reason) - changes.push(change) - let user = users.find((u) => u.sub === change.sub) + let user = users.find((u) => u.sub === command.sub) if (!user) { - user = { sub: change.sub, name: change.sub, email: null, telegramId: null, telegramUsername: null, roles: [] } + user = { sub: command.sub, name: command.sub, email: null, telegramId: null, telegramUsername: null, roles: [] } users.push(user) } - user.roles = - change.action === "assign" - ? [...new Set([...user.roles, change.role])].sort() - : user.roles.filter((role) => role !== change.role) + const next = new Set(user.roles) + for (const change of command.changes) { + const prefix = change.kind === "admin" ? "admin" : `team:${change.team}:` + const bound = ROLES.filter((r) => r.binding.startsWith(prefix)) + if (!bound.length) continue + for (const r of bound) next.delete(r.key) + const desired = + change.kind === "admin" + ? change.active + ? "admin" + : null + : change.role + ? `team:${change.team}:${change.role}` + : null + if (desired) { + const role = bound.find((r) => r.binding === desired) + if (!role) throw new RoleChangeError(409, "Missing binding") + next.add(role.key) + } + } + for (const role of user.roles) + if (!next.has(role)) + changes.push({ actor: command.actor, sub: command.sub, role, action: "unassign", reason: command.reason }) + for (const role of next) + if (!user.roles.includes(role)) + changes.push({ actor: command.actor, sub: command.sub, role, action: "assign", reason: command.reason }) + user.roles = [...next].sort() + receipts.set(command.id, JSON.stringify(command)) + return structuredClone(result(command.sub)) }), } return { roles, changes, users } @@ -54,32 +84,15 @@ const user = (sub: string, roles: string[], extra: Partial { - const bound = boundRoles({ roles: ROLES, users: [] }) - it("ignores bindings to teams People doesn't have", () => { - expect(Object.values(bound.teams).flatMap((t) => [...t.member, ...t.lead])).not.toContain("odd") - }) - it("gives the bound role for a new entry and takes back every role behind an ended one, Lead first", () => { - expect(roleChanges(bound, [], { admin: false, teams: {} }, { admin: true, teams: { it: "member" } })).toEqual([ - { role: "admin", action: "assign" }, - { role: "it-core", action: "assign" }, + it("sends one desired state per changed concept, leaving concrete assignments to Auth", () => { + expect(roleChanges({ admin: false, teams: {} }, { admin: true, teams: { it: "member" } })).toEqual([ + { kind: "admin", active: true }, + { kind: "team", team: "it", role: "member" }, ]) - expect( - roleChanges(bound, ["it-core", "it-lead"], { admin: false, teams: { it: "lead" } }, { admin: false, teams: {} }) - ).toEqual([ - { role: "it-lead", action: "unassign" }, - { role: "it-core", action: "unassign" }, + expect(roleChanges({ admin: false, teams: { it: "lead" } }, { admin: false, teams: {} })).toEqual([ + { kind: "team", team: "it", role: null }, ]) }) - it("takes back only roles given directly, not ones held through a parent", () => { - expect( - roleChanges(bound, ["it-core", "it-lead"], { admin: false, teams: { it: "lead" } }, { admin: false, teams: {} }, [ - "it-lead", - ]) - ).toEqual([{ role: "it-lead", action: "unassign" }]) - }) - it("doesn't give a role already held", () => { - expect(roleChanges(bound, ["admin"], { admin: false, teams: {} }, { admin: true, teams: {} })).toEqual([]) - }) }) describe("People mirrors PoliNetwork Auth", () => { @@ -104,7 +117,6 @@ describe("People mirrors PoliNetwork Auth", () => { profile: { firstName: "Giulia", lastName: "Neri", campus: null, course: "", year: "", personalEmail: null }, account: { status: "linked", via: "PoliNetwork Auth" }, teams: [{ team: "design", role: "lead", endedOn: null }], - synced: { teams: ["design"] }, }) expect(h.state().persons["P-0003"]).toMatchObject({ accountSub: "u-tg", @@ -114,24 +126,23 @@ describe("People mirrors PoliNetwork Auth", () => { expect(rows.find((r) => r.id === giulia?.id)?.profile.campus).toBeNull() }) - it("ends only the roles it mirrored when they are taken back", async () => { + it("Auth owns bound concepts on linked records, including legacy local roles", async () => { const auth = fakeAuth([user("president", ["admin", "it-core"])]) const h = harness({ peopleRoles: auth.roles }) await h.seed() await h.service.syncSources() expect(h.state().persons["P-0001"]).toMatchObject({ admin: { status: "active" }, - synced: { admin: true, teams: ["it"] }, + teams: [{ team: "it", endedOn: null }], }) - // Anna (vice) was an admin in People before; PoliNetwork Auth never held it, so it stays. - expect(h.state().persons["P-0002"].admin?.status).toBe("active") + // A local role cannot retain authority once its concept is owned by Auth. + expect(h.state().persons["P-0002"].admin?.status).toBe("former") auth.users[0].roles = [] await h.service.syncSources() const p = h.state().persons["P-0001"] - expect(p.admin).toMatchObject({ status: "former", endReason: "Role taken back in PoliNetwork Auth" }) + expect(p.admin).toMatchObject({ status: "former", endReason: "Not held in PoliNetwork Auth" }) expect(p.teams[0].endedOn).toBe("2026-10-18") - expect(p.synced).toBeUndefined() - expect(h.state().persons["P-0002"].admin?.status).toBe("active") + expect(h.state().persons["P-0002"].admin?.status).toBe("former") }) it("gives and takes back the role when the dashboard changes a linked record", async () => { @@ -148,7 +159,7 @@ describe("People mirrors PoliNetwork Auth", () => { expect(auth.changes).toEqual([ { actor: "president", sub: "member", role: "design-member", action: "assign", reason: expect.any(String) }, ]) - expect(h.state().persons["P-0003"].synced).toEqual({ teams: ["design"] }) + expect(h.state().persons["P-0003"].teams).toMatchObject([{ team: "design", role: "member", endedOn: null }]) await h.service.endTeamMembership(master, { teamId: "design", personId: "P-0003", @@ -157,7 +168,7 @@ describe("People mirrors PoliNetwork Auth", () => { note: "", }) expect(auth.changes.at(-1)).toMatchObject({ role: "design-member", action: "unassign", reason: "Moved on" }) - expect(h.state().persons["P-0003"].synced).toBeUndefined() + expect(h.state().persons["P-0003"].teams).toMatchObject([{ team: "design", endedOn: "2026-10-18" }]) }) it("rolls the dashboard change back when PoliNetwork Auth refuses it", async () => { @@ -218,9 +229,9 @@ describe("People mirrors PoliNetwork Auth", () => { }) const p = h.state().persons["P-0003"] expect(p.census[0].answer).toBe("leaving") - expect(p.activity.some((a) => a.text.includes("Couldn't update PoliNetwork Auth: Refused for the test."))).toBe( - true - ) + expect( + p.activity.some((a) => a.text.includes("PoliNetwork Auth refused the role change: Refused for the test.")) + ).toBe(true) }) }) @@ -243,7 +254,10 @@ describe("PoliNetwork Auth unreachable", () => { }) const p = h.state().persons["P-0003"] expect(p.census[0].answer).toBe("leaving") - expect(p.activity.some((a) => a.text.includes("could not be reached"))).toBe(true) + expect(p.activity.some((a) => a.text.includes("didn't answer"))).toBe(true) + // Still a member until Auth answers: the sweep sends the same command again. + expect(p.teams[0]).toMatchObject({ team: "it", endedOn: null }) + expect(p.roleCommand?.unanswered).toBe(true) }) }) @@ -299,3 +313,226 @@ describe("People mirrors the Microsoft 365 Soci group", () => { expect(azureMembers).toHaveBeenCalledTimes(2) }) }) + +describe("Auth is the authority for People role commands", () => { + it("never leaves a refused linked Lead authorized, even after synchronization", async () => { + const auth = fakeAuth([], () => "Appointing a Lead requires people:appoint") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const p = state.persons["P-0003"] + p.accountSub = null + p.account = { status: "none" } + p.teams.push({ team: "it", role: "lead", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) + }) + await h.service.linkAccount(master, { personId: "P-0003", accountId: "member", reason: "Verified identity" }) + // Ended, not deleted, and HR is asked to look at it. + expect(h.state().persons["P-0003"]).toMatchObject({ + teams: [{ team: "it", role: "lead", since: "2026-10-01", endReason: "Not confirmed by PoliNetwork Auth" }], + discrepancies: [{ kind: "needs-review", message: expect.stringContaining("people:appoint") }], + }) + await h.service.syncSources() + expect(h.state().persons["P-0003"].teams.some((t) => !t.endedOn)).toBe(false) + await expect( + h.service.listTeamCandidates(viewer("member", ["people:self"]), { teamId: "it" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + }) + + it("sends a revocation as one atomic command and preserves confirmed roles when refused", async () => { + const auth = fakeAuth([user("member", ["it-core", "it-lead"])], () => "Refused") + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await expect( + h.service.endTeamMembership(master, { + personId: "P-0003", + teamId: "it", + lastDay: "2026-10-18", + reason: "Leaving", + note: "", + }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + expect(auth.roles.change).toHaveBeenCalledTimes(1) + expect(vi.mocked(auth.roles.change).mock.calls[0][0].changes).toEqual([{ kind: "team", team: "it", role: null }]) + expect(auth.users[0].roles).toEqual(["it-core", "it-lead"]) + expect(h.state().persons["P-0003"].teams[0]).toMatchObject({ role: "lead", endedOn: null }) + }) + + it("recovers a lost response after restart using the persisted command ID, without granting pending roles", async () => { + const auth = fakeAuth([]) + const change = auth.roles.change + auth.roles.change = vi.fn(async (command) => { + await change(command) + throw new RoleChangeError(503, "Response lost after commit") + }) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await expect( + h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + ).rejects.toMatchObject({ message: expect.stringContaining("don't repeat") }) + const pending = h.state().persons["P-0003"].roleCommand + expect(pending).toBeDefined() + expect(h.state().persons["P-0003"].teams).toEqual([]) + auth.roles.change = vi.fn(change) + const restarted = harness({ store: h.store, peopleRoles: auth.roles }) + await restarted.service.sweep() + expect(vi.mocked(auth.roles.change).mock.calls[0][0].id).toBe(pending?.request.id) + expect(auth.changes).toHaveLength(1) + expect(h.state().persons["P-0003"].roleCommand).toBeUndefined() + expect(h.state().persons["P-0003"].teams[0]).toMatchObject({ team: "it", role: "member", endedOn: null }) + }) + + it("does not confirm an inherited revocation refused by Auth", async () => { + const auth = fakeAuth([user("member", ["it-core"])]) + auth.roles.change = vi.fn(async () => { + throw new RoleChangeError(409, "The role is inherited. Change its granting role in Auth.") + }) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + await expect( + h.service.endTeamMembership(master, { + personId: "P-0003", + teamId: "it", + lastDay: "2026-10-18", + reason: "Leaving", + note: "", + }) + ).rejects.toMatchObject({ message: expect.stringContaining("inherited") }) + expect(h.state().persons["P-0003"].teams[0].endedOn).toBeNull() + }) + + it("refreshes linked identities before importing Microsoft 365 and avoids a duplicate person", async () => { + const auth = fakeAuth([user("member", ["it-core"], { email: "luca@gmail.com" })]) + let members: AzureMember[] = [] + const h = harness({ peopleRoles: auth.roles, azureMembers: async () => members }) + await h.seed() + await h.service.syncSources() + auth.users[0].email = "luca@polinetwork.org" + auth.users[0].azureId = "azure-luca" + members = [ + { + id: "azure-luca", + mail: "luca@polinetwork.org", + givenName: "Luca", + surname: "Verdi", + displayName: "Luca Verdi", + employeeId: "42", + createdOn: "2020-01-01", + }, + ] + await h.service.syncSources() + expect(Object.values(h.state().persons)).toHaveLength(3) + expect(h.state().persons["P-0003"]).toMatchObject({ + azureId: "azure-luca", + member: { number: "0042" }, + account: { email: "luca@polinetwork.org" }, + }) + }) + + it("does not hold the People transaction open while contacting Auth", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const change = auth.roles.change + auth.roles.change = async (command) => { + await h.service.listPeople(master) + return change(command) + } + await h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + }, 2000) + + it("does not overwrite a confirmed command with a snapshot fetched before it", async () => { + const auth = fakeAuth([]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + const old = await auth.roles.directory() + let release!: (value: RoleDirectory) => void + let fetched!: () => void + const started = new Promise((resolve) => { + fetched = resolve + }) + vi.mocked(auth.roles.directory).mockImplementationOnce(() => { + fetched() + return new Promise((resolve) => { + release = resolve + }) + }) + const sync = h.service.syncSources() + await started + await h.service.addTeamMember(master, { + teamId: "it", + personId: "P-0003", + role: "member", + since: "2026-10-01", + fields: {}, + }) + release(old) + await sync + expect(h.state().persons["P-0003"].teams[0].endedOn).toBeNull() + }) + + it("keeps reads working and refuses other edits of the person while a command waits for Auth", async () => { + const auth = fakeAuth([user("member", ["admin", "it-core"])]) + const h = harness({ + peopleRoles: auth.roles, + telegramGroups: async () => [{ chatId: "-100", title: "Analisi 1", admins: ["103"] }], + }) + await h.seed() + await h.service.syncSources() + vi.mocked(auth.roles.change).mockRejectedValueOnce(new RoleChangeError(503, "Timed out")) + const end = { personId: "P-0003", teamId: "it" as const, lastDay: "2026-10-18", reason: "Leaving", note: "" } + await expect(h.service.endTeamMembership(master, end)).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + // Reading refreshes the Telegram groups of the pending admin: it must not be refused. + expect((await h.service.getPerson(master, { id: "P-0003" })).admin?.groups).toEqual([ + { chatId: "-100", title: "Analisi 1" }, + ]) + await expect( + h.service.updateTeamFields(master, { personId: "P-0003", teamId: "it", fields: {} }) + ).rejects.toMatchObject({ code: "CONFLICT" }) + await expect(h.service.unlinkAccount(master, { personId: "P-0003" })).rejects.toMatchObject({ code: "CONFLICT" }) + await expect(h.service.endTeamMembership(master, end)).rejects.toMatchObject({ code: "CONFLICT" }) + await h.service.sweep() + const p = h.state().persons["P-0003"] + expect(p.roleCommand).toBeUndefined() + expect(p.teams[0]).toMatchObject({ endedOn: "2026-10-18", endReason: "Leaving" }) + expect(p.admin).toMatchObject({ status: "active", groups: [{ chatId: "-100" }] }) + expect(p.activity.filter((a) => a.text.includes("didn't answer"))).toHaveLength(1) + }) + + it("refreshes a linked record's identities without rewriting how it was linked", async () => { + const auth = fakeAuth([user("member", [], { email: "luca@polinetwork.org", azureId: "azure-luca" })]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + expect(h.state().persons["P-0003"]).toMatchObject({ + azureId: "azure-luca", + account: { status: "linked", email: "luca@polinetwork.org", via: "IdP", linkedOn: "2026-10-01", how: "test" }, + }) + }) + + it("asks HR instead of guessing when Auth and Microsoft 365 identities match different records", async () => { + const auth = fakeAuth([user("member", ["it-core"], { telegramId: "101" })]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.service.syncSources() + // P-0001 holds Telegram 101 but is linked to another account: neither record changes hands. + expect(h.state().persons["P-0001"]).toMatchObject({ + accountSub: "president", + discrepancies: [{ kind: "needs-review", message: expect.stringContaining("member") }], + }) + expect(h.state().persons["P-0003"].discrepancies).toHaveLength(1) + }) +}) From c26df6c7a583bea1ebd0ccf534876b63ad2befa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Mon, 26 Oct 2026 13:31:45 +0000 Subject: [PATCH 4/4] fix(people): retry a stale-token 401 once and push roles merged into a linked record A 401 from PoliNetwork Auth now refreshes the token and sends the same command once more; a second 401 is a refusal. Merging an unlinked record into a linked one diffs against the roles Auth confirmed and sends the command. README: the member import only covers new memberships. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- src/idp/index.ts | 42 +++++++++++++++++++++++--------------- src/people/service.ts | 7 ++++++- tests/people-roles.test.ts | 29 ++++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 042d5fa..c68f26c 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ The IdP notifies `POST /internal/events` when access changes; the backend also p Every five minutes the People sweep mirrors two sources into the register: - **PoliNetwork Auth roles.** `GET /api/internal/people-roles` lists the roles Master Admin bound to People in the IdP (`admin`, `team::member`, `team::lead`), who holds them, and every account with a PoliNetwork Microsoft 365 login. Holders without a record get one (name only, linked to their account); a record without an account is linked when its Microsoft 365 ID, Telegram ID or Microsoft 365 address matches. When those identities point at more than one record, or at a record linked to another account, nothing changes hands and the records are flagged for review. Linked records take the account's Microsoft 365 ID, so the Soci group import finds them even after the PoliNetwork address changes. On linked records the IdP owns every bound concept: an admin or team entry starts while its role is held and ends while it is not, including entries People recorded before linking. Unlinked records, and any concept with no bound role, stay owned by People. -- **The Microsoft 365 Soci group.** Each member gets a membership with the account's `employeeId` as member number and its creation date as admission date (the activity log says so); a member without a usable number is flagged for review. Leaving the group changes nothing: the register keeps the status. Imported memberships get no automatic fee reminders in the year they were imported. +- **The Microsoft 365 Soci group.** Members without a membership are imported with the account's `employeeId` as member number and its creation date as admission date, or the sync date when there is none (the activity log says so); a member without a usable number is flagged for review. Existing memberships are not changed. Leaving the group changes nothing: the register keeps the status. Imported memberships get no automatic fee reminders in the year they were imported. When the dashboard changes a linked record's admin or team role, or a census answer, import, merge or account link does, the backend sends the IdP one command per person with `POST /api/internal/people-roles`: the desired state of each changed concept, the dashboard user it authenticated, and a command ID. The IdP picks the assignments, checks that user may make every one of them (no self-grants, `people:write` or `people:appoint`, bounded delegation) and applies all of them or none. The command is saved first and sent after the People transaction commits; until the IdP confirms it, the record keeps its previous roles, so a requested role never grants access, and other role edits of that person are refused. Direct dashboard actions fail when the IdP refuses; census answers, imports, merges and links note the refusal and flag the record for review, and a link ends the roles recorded before it with "Not confirmed by PoliNetwork Auth". When the IdP doesn't answer, the sweep sends the same command again: the IdP applies an ID once and answers with the current roles. Writes need the backend's OAuth client to hold the `idp:people:roles` scope on the internal resource; reads use the existing `idp:access:read` token. diff --git a/src/idp/index.ts b/src/idp/index.ts index 2d88d63..f42ff10 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -135,24 +135,34 @@ function configure() { return peopleDirectory.parse(await response.json()) }, async change(change) { - let token: string - try { - token = await roleTokens.getToken() - } catch { - throw new RoleChangeError(503, `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?`) + const send = async () => { + let token: string + try { + token = await roleTokens.getToken() + } catch { + throw new RoleChangeError( + 503, + `no token to change roles; is ${PEOPLE_ROLES_SCOPE} granted to this backend?` + ) + } + try { + return await fetch(peopleRolesUrl, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify(change), + signal: AbortSignal.timeout(10_000), + }) + } catch { + throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") + } } - let response: Response - try { - response = await fetch(peopleRolesUrl, { - method: "POST", - headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - body: JSON.stringify(change), - signal: AbortSignal.timeout(10_000), - }) - } catch { - throw new RoleChangeError(503, "PoliNetwork Auth could not be reached") + let response = await send() + // A stale cached token: ask for a new one and send the same command once more. A second 401 is a refusal. + if (response.status === 401) { + roleTokens.invalidate() + response = await send() + if (response.status === 401) roleTokens.invalidate() } - if (response.status === 401) roleTokens.invalidate() if (response.ok) { // The command was applied, but without a readable answer People can't confirm it: retry it by ID. const result = roleResult.safeParse(await response.json().catch(() => null)) diff --git a/src/people/service.ts b/src/people/service.ts index bce4a14..60adcac 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -1198,7 +1198,12 @@ export function createPeopleService(options: PeopleOptions) { settled(first) settled(second) const before = roleViews(u.state) - const linked = !!first.accountSub + // Auth confirmed only the linked record's roles: diff the merged result against those. + if (!first.accountSub && second.accountSub) { + const confirmed = before.get(second.id) + if (confirmed) before.set(first.id, confirmed) + } + const linked = !!first.accountSub || !!second.accountSub r.mergedRecord = structuredClone(second) mergePeople(u.state, first, second, v, config, now()) link(u.state, first, account, v.sub, input.reason) diff --git a/tests/people-roles.test.ts b/tests/people-roles.test.ts index b55c285..c1f2c50 100644 --- a/tests/people-roles.test.ts +++ b/tests/people-roles.test.ts @@ -338,6 +338,35 @@ describe("Auth is the authority for People role commands", () => { ).rejects.toMatchObject({ code: "FORBIDDEN" }) }) + it("sends the roles of an unlinked record merged into a linked one to Auth", async () => { + const auth = fakeAuth([user("member", [])]) + const h = harness({ peopleRoles: auth.roles }) + await h.seed() + await h.store.transaction(async ({ state }) => { + const first = state.persons["P-0002"] + first.accountSub = null + first.account = { status: "none" } + first.profile.telegramId = null + first.teams.push({ team: "it", role: "member", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) + state.reviews.R1 = { + id: "R1", + kind: "two-records", + sub: "member", + resolved: false, + rejectedPersonIds: [], + record: { id: "P-0002" }, + other: { id: "P-0003" }, + } as never + }) + await h.service.resolveReview(master, { reviewId: "R1", resolution: "merge-first", reason: "Same student" }) + expect(auth.roles.change).toHaveBeenCalled() + expect(vi.mocked(auth.roles.change).mock.calls[0][0].changes).toContainEqual({ + kind: "team", + team: "it", + role: "member", + }) + }) + it("sends a revocation as one atomic command and preserves confirmed roles when refused", async () => { const auth = fakeAuth([user("member", ["it-core", "it-lead"])], () => "Refused") const h = harness({ peopleRoles: auth.roles })