Skip to content

Commit 42bef23

Browse files
authored
fix(people): resolve experts only by verified identities, validate SCIM time zones on write, fair Slack identity sweep (#10572)
* fix(people): resolve experts only by verified identities; validate SCIM time zones on write; fair Slack identity sweep - Expert search resolves a contributor to a directory person only by a verified email or the organization's own Slack identity. A name, such as a commit author or a Slack Connect guest, is free text anyone can set, so it stays an outside contributor. - SCIM time zones are validated as they are staged, so person reads take the stored zone instead of scanning pg_timezone_names for every row. - The Slack identity sweep takes never-visited and longest-overdue organizations first, and one without People only has its identities cleared, without taking a refresh from one that has it. * refactor(people): lease one Slack identity refresh at a time * fix(people): stage a SCIM time zone in the catalog's spelling, whatever its case
1 parent 4ff7170 commit 42bef23

7 files changed

Lines changed: 232 additions & 93 deletions

File tree

‎apps/sim/ee/scim/lib/repository/people-profiles.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,11 @@ export async function readProvisionedProfiles(
111111
}
112112
}
113113

114-
/** Holds provisioning status through publication; null means an administrator paused the source. */
114+
/**
115+
* Holds provisioning status through publication; null means an administrator paused the source.
116+
* SCIM records a time zone as free text, so it is staged only when Postgres knows it, in the
117+
* catalog's own spelling whatever its case; person reads then take stored zones as they are.
118+
*/
115119
export async function stageScimDirectory(
116120
tx: DbTransaction,
117121
organizationId: string,
@@ -146,11 +150,14 @@ export async function stageScimDirectory(
146150
total: string
147151
}>(sql`
148152
WITH source(external_id,email,name,location,title,timezone,department,manager_external_id) AS (${source}),
153+
zones AS (SELECT lower(name) AS zone_key, min(name) AS zone_name FROM pg_timezone_names GROUP BY 1),
149154
staged AS (
150155
INSERT INTO ${peopleDirectoryStage} (organization_id,run_id,external_id,proposed_id,email,name,title,department,location,timezone,manager_external_id,reports_complete)
151156
SELECT ${organizationId},${runId},external_id,gen_random_uuid()::text,email,
152-
coalesce(nullif(btrim(name),''),email),nullif(title,''),nullif(department,''),nullif(location,''),timezone,nullif(manager_external_id,''),true
153-
FROM source WHERE char_length(external_id) BETWEEN 1 AND 512 AND char_length(email) <= 320 AND email ~ ${z.regexes.email.source}
157+
coalesce(nullif(btrim(name),''),email),nullif(title,''),nullif(department,''),nullif(location,''),
158+
zones.zone_name,nullif(manager_external_id,''),true
159+
FROM source LEFT JOIN zones ON zones.zone_key = lower(btrim(source.timezone))
160+
WHERE char_length(external_id) BETWEEN 1 AND 512 AND char_length(email) <= 320 AND email ~ ${z.regexes.email.source}
154161
ON CONFLICT DO NOTHING RETURNING 1
155162
), counts AS (SELECT (SELECT count(*) FROM source) AS expected,(SELECT count(*) FROM staged) AS actual)
156163
SELECT expected=actual AS complete, actual::text AS total,

‎apps/sim/lib/knowledge/application/experts.integration.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -309,19 +309,32 @@ it('counts an item once per person at their strongest role, and caps chat messag
309309

310310
it("adds up one person's work however each source names them", async () => {
311311
liveItems.value = [
312-
item('jira', 'ENG-8', [{ role: 'assignee', email: email(billingDev) }]),
313-
item('confluence', 'page-8', [{ role: 'author', name: 'Pat Developer' }]),
312+
item('jira', 'ENG-8', [{ role: 'assignee', email: email(billingLead) }]),
313+
item('slack', 'msg-8', [{ role: 'author', providerUserId: 'U-LEAD', name: 'lead' }]),
314314
]
315315
const result = await search()
316-
expect(result.experts.map((expert) => expert.personId)).toEqual([billingDev])
316+
expect(result.experts.map((expert) => expert.personId)).toEqual([billingLead])
317317
expect(result.experts[0]?.contributions).toEqual(
318318
expect.arrayContaining([
319319
{ source: 'jira', role: 'assignee', count: 1 },
320-
{ source: 'confluence', role: 'author', count: 1 },
320+
{ source: 'slack', role: 'author', count: 1 },
321321
])
322322
)
323323
})
324324

325+
it('never credits a directory person by a name anyone can write, such as a commit author', async () => {
326+
liveItems.value = [
327+
item('gitlab', 'commit-1', [{ role: 'author', name: 'Pat Developer' }]),
328+
item('slack', 'msg-ext', [
329+
{ role: 'author', providerUserId: 'U-EXTERNAL', name: 'Pat Developer' },
330+
]),
331+
]
332+
const result = await search()
333+
expect(result.experts).toEqual([])
334+
expect(result.otherContributors).toEqual([expect.objectContaining({ name: 'Pat Developer' })])
335+
expect(result.otherContributors?.[0]).not.toHaveProperty('personId')
336+
})
337+
325338
it('counts an item two connected accounts both return once', async () => {
326339
liveItems.value = [
327340
item('jira', 'ENG-9', [{ role: 'assignee', email: email(billingDev) }]),

‎apps/sim/lib/knowledge/application/experts.ts‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,7 @@ import { knowledgeOperations } from '@/lib/knowledge/application/operations'
1212
import { type RankedContributor, rankContributors } from '@/lib/knowledge/experts/rank'
1313
import { listOrganizationSearchApprovals } from '@/lib/knowledge/search/integration-policy'
1414
import { canLookUpPeople, personFacts } from '@/lib/people/directory-lookup'
15-
import {
16-
type DirectoryIdentity,
17-
foldDirectoryName,
18-
resolveDirectoryIdentities,
19-
} from '@/lib/people/repository'
15+
import { type DirectoryIdentity, resolveDirectoryIdentities } from '@/lib/people/repository'
2016
import { listLiveAccounts } from '@/lib/sim-search/live/accounts'
2117
import {
2218
connectHint,
@@ -69,7 +65,11 @@ function sourceStatus(account: LiveSearchAccountStatus, organizationId: string):
6965
}
7066
}
7167

72-
/** How a contributor is matched to the directory: a folded email, else a folded name. */
68+
/**
69+
* Who a contributor is: a verified email, from the source's own account or the organization's
70+
* Slack identity, else only the name the source shows. Only an email resolves to a directory
71+
* person; a name is free text anyone can set, such as a commit's author, so it never does.
72+
*/
7373
type ContributorIdentity =
7474
| { email: string; name?: string | undefined }
7575
| { email?: undefined; name: string }
@@ -109,8 +109,9 @@ function contains(value: string | null | undefined, filter: string | undefined)
109109
/**
110110
* `search_experts`: people ranked by what they did on items matching a topic, read live from the
111111
* caller's own sources, so only items the caller can open count and every expert carries links
112-
* to them. People resolve to the directory by email, Slack account, or an unambiguous name; a
113-
* caller who may not browse the directory gets the people named in the items, without profiles.
112+
* to them. People resolve to the directory only by a verified email or the organization's own
113+
* Slack identity; anyone named only by a name stays an outside contributor. A caller who may not
114+
* browse the directory gets the people named in the items, without profiles.
114115
*/
115116
export const searchExperts = defineAuthorizedKnowledgeUseCase({
116117
operation: knowledgeOperations.search,
@@ -148,21 +149,17 @@ export const searchExperts = defineAuthorizedKnowledgeUseCase({
148149
])
149150

150151
const directoryOpen = await canBrowseDirectory
151-
const named = { emails: new Set<string>(), names: new Set<string>(), slack: new Set<string>() }
152+
const named = { emails: new Set<string>(), slack: new Set<string>() }
152153
for (const item of items)
153154
for (const contributor of item.contributors) {
154155
if (contributor.email) named.emails.add(contributor.email)
155156
else if (item.provider === 'slack' && contributor.providerUserId)
156157
named.slack.add(contributor.providerUserId)
157-
// A Slack ID may not resolve to an email, so its name stays a fallback.
158-
if (contributor.name && (!contributor.email || item.provider === 'slack'))
159-
named.names.add(foldDirectoryName(contributor.name))
160158
}
161159
const cap = (values: Set<string>) => [...values].slice(0, MAX_RESOLVED_IDENTITIES)
162160
const directory = directoryOpen
163161
? await resolveDirectoryIdentities(input.organizationId, {
164162
emails: cap(named.emails),
165-
names: cap(named.names),
166163
slackUserIds: cap(named.slack),
167164
})
168165
: undefined
@@ -174,9 +171,7 @@ export const searchExperts = defineAuthorizedKnowledgeUseCase({
174171
const identity = contributorIdentity(contributor, provider, slackEmails)
175172
if (!identity) return undefined
176173
const person =
177-
identity.email !== undefined
178-
? directory?.byEmail.get(identity.email)
179-
: directory?.byName.get(foldDirectoryName(identity.name))
174+
identity.email !== undefined ? directory?.byEmail.get(identity.email) : undefined
180175
if (person) {
181176
const key = `person:${person.memberId}`
182177
people.set(key, person)
@@ -185,7 +180,7 @@ export const searchExperts = defineAuthorizedKnowledgeUseCase({
185180
const key =
186181
identity.email !== undefined
187182
? `email:${identity.email}`
188-
: `name:${foldDirectoryName(identity.name)}`
183+
: `name:${identity.name.trim().toLowerCase()}`
189184
if (!identities.has(key)) identities.set(key, identity)
190185
return key
191186
})

‎apps/sim/lib/people/repository.ts‎

Lines changed: 27 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -152,14 +152,12 @@ function profileRelations(source = sql`links`) {
152152

153153
/**
154154
* A person's full record, read from `people p` joined to `summaries manager` and to the person's
155-
* Slack identity by {@link personJoins}. SCIM stores a time zone verbatim, so a directory zone
156-
* counts only when Postgres knows it; otherwise the Slack zone stands.
155+
* Slack identity by {@link personJoins}. Every source validates a time zone as it writes it, so
156+
* a directory zone is read as stored; without one the Slack zone stands.
157157
*/
158158
const PERSON_FIELDS = sql`${SUMMARY_FIELDS}, lower(p.name) AS "sortName",
159159
p.department, p.location, p.start_date::text AS "startDate",
160-
coalesce(
161-
(SELECT tz.name FROM pg_timezone_names tz WHERE tz.name = p.timezone LIMIT 1), slack.timezone
162-
) AS timezone,
160+
coalesce(p.timezone, slack.timezone) AS timezone,
163161
slack.slack_user_id AS "slackUserId", slack.slack_team_id AS "slackTeamId",
164162
p.source AS "directorySource",
165163
p.manager_id AS "managerMemberId", to_jsonb(manager) AS manager,
@@ -312,37 +310,18 @@ export type DirectoryIdentity = Pick<
312310
| 'slackTeamId'
313311
>
314312

315-
/** A name as the directory matches it: trimmed and lowercased, as `lower(btrim(name))` in SQL. */
316-
export function foldDirectoryName(name: string): string {
317-
return name.trim().toLowerCase()
318-
}
319-
320-
/** Each key held by exactly one person, mapped to that person. */
321-
function onlyHolders(
322-
entries: [string, DirectoryIdentity & { foldedEmail: string; foldedName: string }][]
323-
): Map<string, DirectoryIdentity> {
324-
const holders = new Map<string, DirectoryIdentity | null>()
325-
for (const [key, { foldedEmail: _email, foldedName: _name, ...person }] of entries)
326-
holders.set(
327-
key,
328-
!holders.has(key) || holders.get(key)?.memberId === person.memberId ? person : null
329-
)
330-
return new Map([...holders].flatMap(([key, person]) => (person ? [[key, person] as const] : [])))
331-
}
332-
333313
/**
334-
* The directory people behind contributor identities: by folded email, by a folded name only one
335-
* person holds, and the email behind each Slack user ID. Each list is matched in one query.
314+
* The directory people behind verified contributor identities: by folded email, held by exactly
315+
* one person, and the email behind each Slack user ID of the organization's own workspaces.
316+
* Names never resolve: they are free text anyone can set.
336317
*/
337318
export async function resolveDirectoryIdentities(
338319
organizationId: string,
339320
{
340321
emails = [],
341-
names = [],
342322
slackUserIds = [],
343323
}: {
344324
emails?: readonly string[] | undefined
345-
names?: readonly string[] | undefined
346325
slackUserIds?: readonly string[] | undefined
347326
}
348327
) {
@@ -357,7 +336,7 @@ export async function resolveDirectoryIdentities(
357336
)
358337
)
359338
: []
360-
/** A Slack ID two workspaces give different people resolves to no one; names stay the fallback. */
339+
/** A Slack ID two workspaces give different people resolves to no one. */
361340
const slackEmails = new Map<string, string>()
362341
const conflicting = new Set<string>()
363342
for (const row of slackRows) {
@@ -368,25 +347,26 @@ export async function resolveDirectoryIdentities(
368347
}
369348
for (const slackUserId of conflicting) slackEmails.delete(slackUserId)
370349
const wantedEmails = [...new Set([...emails, ...slackEmails.values()].map(normalizeEmail))]
371-
const wantedNames = [...new Set(names.map(foldDirectoryName))]
372-
const rows =
373-
wantedEmails.length || wantedNames.length
374-
? await db.execute<DirectoryIdentity & { foldedEmail: string; foldedName: string }>(sql`
375-
WITH ${identityRelations(organizationId)}, ${profileRelations()}
376-
SELECT p.id AS "memberId", p.name, p.email, p.title, p.department, p.location,
377-
slack.slack_user_id AS "slackUserId", slack.slack_team_id AS "slackTeamId",
378-
${foldedEmail(sql`p.email`)} AS "foldedEmail", lower(btrim(p.name)) AS "foldedName"
379-
FROM people p ${slackJoin(organizationId)}
380-
WHERE ${or(
381-
wantedEmails.length ? inArray(foldedEmail(sql`p.email`), wantedEmails) : undefined,
382-
wantedNames.length ? inArray(sql`lower(btrim(p.name))`, wantedNames) : undefined
383-
)}
384-
`)
385-
: []
386-
// An email or name two people share names neither of them.
387-
const byEmail = onlyHolders(rows.map((row) => [row.foldedEmail, row]))
388-
const byName = onlyHolders(rows.map((row) => [row.foldedName, row]))
389-
return { byEmail, byName, slackEmails }
350+
const rows = wantedEmails.length
351+
? await db.execute<DirectoryIdentity & { foldedEmail: string }>(sql`
352+
WITH ${identityRelations(organizationId)}, ${profileRelations()}
353+
SELECT p.id AS "memberId", p.name, p.email, p.title, p.department, p.location,
354+
slack.slack_user_id AS "slackUserId", slack.slack_team_id AS "slackTeamId",
355+
${foldedEmail(sql`p.email`)} AS "foldedEmail"
356+
FROM people p ${slackJoin(organizationId)}
357+
WHERE ${inArray(foldedEmail(sql`p.email`), wantedEmails)}
358+
`)
359+
: []
360+
/** An email two people share names neither of them. */
361+
const holders = new Map<string, DirectoryIdentity | null>()
362+
for (const { foldedEmail: email, ...person } of rows)
363+
holders.set(
364+
email,
365+
!holders.has(email) || holders.get(email)?.memberId === person.memberId ? person : null
366+
)
367+
const byEmail = new Map<string, DirectoryIdentity>()
368+
for (const [email, person] of holders) if (person) byEmail.set(email, person)
369+
return { byEmail, slackEmails }
390370
}
391371

392372
export async function getPerson(

0 commit comments

Comments
 (0)