@@ -8,11 +8,17 @@ import { getCredentialGroupProviderId } from '@/lib/credential-groups/providers'
88 * The Slack account a federated search runs as: the asking person's own,
99 * enrolled through a Credential Group in this workspace.
1010 *
11- * The joins mirror the knowledge access scope exactly — verified email, live
12- * enrollment, active group, active managed credential, active option — because
13- * both answer the same question about the same rows, and a search that used a
14- * looser rule than the one governing document access would be the odd one out.
15- * Nothing is cached: revoking a credential takes effect on the next search.
11+ * Deliberately does not filter on `managedOauthStatus`. A credential that needs
12+ * authorizing again is still a connection the person made, and the difference
13+ * between "you never connected Slack" and "reconnect Slack" is the whole of
14+ * what the surface can tell them to do. Excluding it here would collapse the
15+ * second into the first — which is exactly what a scope-policy change does to
16+ * every enrolled credential at once. `resolveManagedOAuthToken` classifies it,
17+ * and an active credential is preferred when a person somehow holds several.
18+ *
19+ * The group must belong to this workspace as well as the credential: the two
20+ * are set together today, and requiring both keeps a workspace's search inside
21+ * its own groups even if they ever diverge.
1622 */
1723export async function findViewerSlackCredentialId ( params : {
1824 workspaceId : string
@@ -35,6 +41,7 @@ export async function findViewerSlackCredentialId(params: {
3541 credentialGroup ,
3642 and (
3743 eq ( credentialGroup . id , credentialGroupEnrollment . credentialGroupId ) ,
44+ eq ( credentialGroup . workspaceId , params . workspaceId ) ,
3845 eq ( credentialGroup . status , 'active' )
3946 )
4047 )
@@ -44,7 +51,6 @@ export async function findViewerSlackCredentialId(params: {
4451 eq ( credential . credentialGroupEnrollmentId , credentialGroupEnrollment . id ) ,
4552 eq ( credential . workspaceId , params . workspaceId ) ,
4653 eq ( credential . type , 'managed_oauth' ) ,
47- eq ( credential . managedOauthStatus , 'active' ) ,
4854 eq ( credential . providerId , getCredentialGroupProviderId ( 'slack' ) ) ,
4955 sql `EXISTS (
5056 SELECT 1 FROM jsonb_array_elements(${ credentialGroup . options } ) AS option
@@ -54,6 +60,7 @@ export async function findViewerSlackCredentialId(params: {
5460 )
5561 )
5662 . where ( and ( eq ( user . id , params . userId ) , eq ( user . emailVerified , true ) ) )
63+ . orderBy ( sql `CASE WHEN ${ credential . managedOauthStatus } = 'active' THEN 0 ELSE 1 END` )
5764 . limit ( 1 )
5865
5966 return row ?. credentialId ?? null
0 commit comments