Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions apps/sim/app/api/cron/people-directory-sync/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { authInternalMock, authInternalMockFns } from '@sim/testing/mocks/auth-internal.mock'
import { createMockRequest } from '@sim/testing/mocks/request.mock'
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { syncDueDirectories, refreshDueSlackIdentities } = vi.hoisted(() => ({
syncDueDirectories: vi.fn(),
refreshDueSlackIdentities: vi.fn(),
}))
vi.mock('@/lib/auth/internal', () => authInternalMock)
vi.mock('@/lib/people/sync/runner', () => ({ syncDueDirectories }))
vi.mock('@/lib/people/slack-identities', () => ({ refreshDueSlackIdentities }))

import { GET } from '@/app/api/cron/people-directory-sync/route'

function sweep() {
return GET(
createMockRequest('GET', undefined, {}, 'http://localhost:3000/api/cron/people-directory-sync'),
undefined
)
}

describe('people directory sync cron', () => {
beforeEach(() => {
authInternalMockFns.mockVerifyCronAuth.mockReturnValue(null)
syncDueDirectories.mockReset().mockResolvedValue({ attempted: 3 })
refreshDueSlackIdentities.mockReset().mockResolvedValue({ refreshed: 2 })
})

it('reports a directory sync that succeeded when only the Slack identity sweep failed', async () => {
refreshDueSlackIdentities.mockRejectedValue(new Error('connection terminated'))
const response = await sweep()
expect(response.status).toBe(200)
expect(await response.json()).toEqual({
attempted: 3,
slackIdentitiesRefreshed: 0,
failed: ['slackIdentities'],
})
})

it('fails the invocation for a failed directory sweep, still reporting the Slack refresh', async () => {
syncDueDirectories.mockRejectedValue(new Error('connection terminated'))
const response = await sweep()
expect(response.status).toBe(500)
expect(await response.json()).toEqual({
attempted: 0,
slackIdentitiesRefreshed: 2,
failed: ['directories'],
})
})
})
30 changes: 24 additions & 6 deletions apps/sim/app/api/cron/people-directory-sync/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { sweepPeopleDirectoriesContract } from '@/lib/api/contracts/people-sync-cron'
import { parseRequest } from '@/lib/api/server'
Expand All @@ -8,6 +9,13 @@ import { syncDueDirectories } from '@/lib/people/sync/runner'

export const maxDuration = 300

const logger = createLogger('PeopleDirectorySyncCron')

/**
* Syncs due directories and refreshes due Slack identities, each on its own: either sweep's
* failure is logged and named in `failed`, and the other's result is still reported. Only a
* directory sweep that failed fails the invocation, since a Slack refresh retries on its own.
*/
export const GET = withRouteHandler(async (request: NextRequest) => {
const authError = verifyCronAuth(request, 'People directory synchronization')
if (authError) return authError
Expand All @@ -17,10 +25,20 @@ export const GET = withRouteHandler(async (request: NextRequest) => {
syncDueDirectories(),
refreshDueSlackIdentities(),
])
if (directories.status === 'rejected') throw directories.reason
if (slack.status === 'rejected') throw slack.reason
return NextResponse.json({
...directories.value,
slackIdentitiesRefreshed: slack.value.refreshed,
})
if (directories.status === 'rejected')
logger.error('People directory sweep failed', { error: directories.reason })
if (slack.status === 'rejected')
logger.error('Slack identity sweep failed', { error: slack.reason })
const failed = [
...(directories.status === 'rejected' ? (['directories'] as const) : []),
...(slack.status === 'rejected' ? (['slackIdentities'] as const) : []),
]
return NextResponse.json(
{
attempted: directories.status === 'fulfilled' ? directories.value.attempted : 0,
slackIdentitiesRefreshed: slack.status === 'fulfilled' ? slack.value.refreshed : 0,
...(failed.length ? { failed } : {}),
},
{ status: directories.status === 'rejected' ? 500 : 200 }
)
})
2 changes: 2 additions & 0 deletions apps/sim/lib/api/contracts/people-sync-cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export const sweepPeopleDirectoriesContract = defineRouteContract({
schema: z.object({
attempted: z.number().int().nonnegative(),
slackIdentitiesRefreshed: z.number().int().nonnegative(),
/** The sweeps that failed; each is logged, and the other's count still reported. */
failed: z.array(z.enum(['directories', 'slackIdentities'])).optional(),
}),
},
})
46 changes: 44 additions & 2 deletions apps/sim/lib/core/config/block-visibility.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { envFlagsMockFns, resetEnvFlagsMock, resetEnvMock, setEnv, setEnvFlags } from '@sim/testing'
import {
knowledgeAvailabilityMock,
knowledgeAvailabilityMockFns,
} from '@sim/testing/mocks/knowledge-availability.mock'
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'

const { mockFetch, mockIsPlatformAdmin } = vi.hoisted(() => ({
mockFetch: vi.fn(),
mockIsPlatformAdmin: vi.fn(),
}))
/** Organizations with Search on; every other owner lacks it. */
const searchOrganizations = new Set<string>()

beforeAll(() => {
setEnv({ APPCONFIG_APPLICATION: 'sim-staging', APPCONFIG_ENVIRONMENT: 'staging' })
Expand All @@ -18,6 +24,8 @@ vi.mock('@/lib/permissions/super-user', () => ({
isPlatformAdmin: mockIsPlatformAdmin,
}))

vi.mock('@/lib/knowledge/access/availability', () => knowledgeAvailabilityMock)

import { getBlockVisibility } from '@/lib/core/config/block-visibility'

/** Make `getBlockVisibility` resolve `doc` via the AppConfig path (also exercises parsing). */
Expand All @@ -33,14 +41,20 @@ afterAll(() => {

describe('getBlockVisibility', () => {
beforeEach(() => {
searchOrganizations.clear()
searchOrganizations.add('search-org')
knowledgeAvailabilityMockFns.mockIsKnowledgeMemberAccessAvailable.mockImplementation(
async ({ organizationId }) =>
Boolean(organizationId && searchOrganizations.has(organizationId))
)
setEnvFlags({ isAppConfigEnabled: false })
envFlagsMockFns.getPreviewBlocksFromEnv.mockReturnValue([])
})

describe('off-AppConfig (env fallback)', () => {
it('reveals and preview-tags the PREVIEW_BLOCKS types without fetching', async () => {
envFlagsMockFns.getPreviewBlocksFromEnv.mockReturnValue(['gmail_v2', 'notion_v3'])
const vis = await getBlockVisibility({ userId: 'u1' })
const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' })
expect(vis.revealed).toEqual(new Set(['gmail_v2', 'notion_v3']))
expect(vis.previewTagged).toEqual(new Set(['gmail_v2', 'notion_v3']))
expect(vis.disabled.size).toBe(0)
Expand Down Expand Up @@ -101,7 +115,7 @@ describe('getBlockVisibility', () => {
c: { enabled: false },
})
mockIsPlatformAdmin.mockResolvedValue(true)
const vis = await getBlockVisibility({ userId: 'u1' })
const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' })
expect(mockIsPlatformAdmin).toHaveBeenCalledTimes(1)
expect(vis.revealed).toEqual(new Set(['a', 'b']))
expect(vis.previewTagged).toEqual(new Set(['a', 'b']))
Expand All @@ -126,4 +140,32 @@ describe('getBlockVisibility', () => {
expect(mockIsPlatformAdmin).not.toHaveBeenCalled()
})
})

it.each([
['an organization without Search', { appConfig: true, orgId: 'other-org' }],
['a workspace outside any organization', { appConfig: false, orgId: undefined }],
])(
'hides the Organization Search block for %s, and only it',
async (_owner, { appConfig, orgId }) => {
if (appConfig) withAppConfig({})
const vis = await getBlockVisibility({ userId: 'u1', orgId })
expect(vis.disabled).toEqual(new Set(['organization']))
}
)

it('offers the Organization Search block where its organization has Search', async () => {
withAppConfig({})
const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' })
expect(vis.disabled.has('organization')).toBe(false)
})

it('hides only the Organization Search block when its Search availability cannot be read', async () => {
withAppConfig({ gmail_v2: { enabled: true } })
knowledgeAvailabilityMockFns.mockIsKnowledgeMemberAccessAvailable.mockRejectedValueOnce(
new Error('billing read failed')
)
const vis = await getBlockVisibility({ userId: 'u1', orgId: 'search-org' })
expect(vis.disabled).toEqual(new Set(['organization']))
expect(vis.revealed.has('gmail_v2')).toBe(true)
})
})
33 changes: 30 additions & 3 deletions apps/sim/lib/core/config/block-visibility.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { fetchAppConfigProfile } from '@/lib/core/config/appconfig'
import type { AppConfigGateContext, AppConfigGateRule } from '@/lib/core/config/appconfig-rules'
import { matchesRule, parseGateConfig } from '@/lib/core/config/appconfig-rules'
import { env } from '@/lib/core/config/env'
import { getPreviewBlocksFromEnv, isAppConfigEnabled } from '@/lib/core/config/env-flags'
import type { DbOrTx } from '@/lib/db/types'
import { isKnowledgeMemberAccessAvailable } from '@/lib/knowledge/access/availability'

/**
* Name of the AppConfig configuration profile holding per-block visibility rules.
Expand All @@ -12,6 +15,8 @@ import type { DbOrTx } from '@/lib/db/types'
*/
const BLOCK_VISIBILITY_PROFILE = 'block-visibility'

const logger = createLogger('BlockVisibility')

/**
* Custom (deploy-as-block) block types are org-scoped and managed by their own
* enabled/disabled lifecycle — the visibility document must never gate them.
Expand Down Expand Up @@ -60,12 +65,33 @@ async function resolveAdmin(userId: string, executor?: DbOrTx): Promise<boolean>
return isPlatformAdmin(userId, executor)
}

/**
* Blocks that work only where their organization has a feature, hidden like a kill switch
* everywhere else: the Organization Search block needs Search on in the workspace's organization,
* so a personal workspace or an organization without Search never offers a block that would fail.
*/
async function unavailableOrganizationBlocks(orgId: string | null | undefined): Promise<string[]> {
if (!orgId) return ['organization']
try {
return (await isKnowledgeMemberAccessAvailable({ organizationId: orgId }))
? []
: ['organization']
} catch (error) {
// An unknown answer hides only the block it is about; every other block stays offered.
logger.warn('Could not resolve Search availability for block visibility', {
organizationId: orgId,
error: getErrorMessage(error),
})
return ['organization']
}
}

/**
* Evaluate the block-visibility document for a viewer.
*
* On hosted deployments the rules come from the AppConfig profile (cached,
* ~30s TTL); off-AppConfig the `PREVIEW_BLOCKS` env allowlist is the only
* reveal path and nothing is disabled.
* reveal path. Either way, a block its organization lacks the feature for is disabled.
*
* Unlike feature-flags (one rule per call, admin resolved lazily per rule),
* this evaluates the whole document, so platform-admin status is resolved at
Expand All @@ -76,9 +102,10 @@ export async function getBlockVisibility(
ctx: BlockVisibilityContext = {},
executor?: DbOrTx
): Promise<BlockVisibilityState> {
const unavailable = await unavailableOrganizationBlocks(ctx.orgId)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (!isAppConfigEnabled) {
const revealed = new Set(getPreviewBlocksFromEnv())
return { revealed, disabled: new Set(), previewTagged: new Set(revealed) }
return { revealed, disabled: new Set(unavailable), previewTagged: new Set(revealed) }
}

const rules =
Expand All @@ -100,7 +127,7 @@ export async function getBlockVisibility(
ctx.isAdmin ?? (needsAdmin ? await resolveAdmin(ctx.userId as string, executor) : false)

const revealed = new Set<string>()
const disabled = new Set<string>()
const disabled = new Set<string>(unavailable)
const previewTagged = new Set<string>()
for (const [type, rule] of Object.entries(rules)) {
if (matchesRule(rule, ctx, isAdmin)) {
Expand Down
Loading