-
Notifications
You must be signed in to change notification settings - Fork 3.9k
feat(sso): open Sim from an identity provider's app dashboard #7865
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
46ce7f5
feat(sso): open Sim from an identity provider's app dashboard
waleedlatif1 16f3177
improvement(sso): skip re-authentication when signed in and limit das…
waleedlatif1 ab848f6
improvement(sso): redirect straight to the identity provider from the…
waleedlatif1 2cb6d3c
fix(sso): keep a signed-in visitor going to the app when the launch a…
waleedlatif1 73dec08
fix(sso): report a failed launch sign-in on the provider's sign-in link
waleedlatif1 be4db0b
chore(sso): normalize the caught error when a launch sign-in fails
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
136 changes: 136 additions & 0 deletions
136
apps/sim/app/(auth)/sso/launch/[providerId]/route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { createMockRequest, setEnvFlags } from '@sim/testing' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockGetSession, mockSignInSSO, mockIsAllowed, mockEnforceIpRateLimit } = vi.hoisted(() => ({ | ||
| mockGetSession: vi.fn(), | ||
| mockSignInSSO: vi.fn(), | ||
| mockIsAllowed: vi.fn(), | ||
| mockEnforceIpRateLimit: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/auth', () => ({ | ||
| getSession: mockGetSession, | ||
| auth: { api: { signInSSO: mockSignInSSO } }, | ||
| })) | ||
| vi.mock('@/lib/auth/sso/idp-initiated-login', () => ({ isIdpInitiatedLoginAllowed: mockIsAllowed })) | ||
| vi.mock('@/lib/core/rate-limiter', () => ({ enforceIpRateLimit: mockEnforceIpRateLimit })) | ||
|
|
||
| import { GET } from '@/app/(auth)/sso/launch/[providerId]/route' | ||
|
|
||
| const context = { params: Promise.resolve({ providerId: 'acme-okta' }) } | ||
| const ISSUER = 'https://acme.okta.test' | ||
| const SIGN_IN_LINK = 'https://test.sim.ai/sso?provider=acme-okta' | ||
|
|
||
| function open(search = `?iss=${encodeURIComponent(ISSUER)}`) { | ||
| return GET( | ||
| createMockRequest('GET', undefined, {}, `https://test.sim.ai/sso/launch/acme-okta${search}`), | ||
| context | ||
| ) | ||
| } | ||
|
|
||
| /** Better Auth answers with the authorization URL and the signed `state` cookie for it. */ | ||
| function authorizationResponse() { | ||
| return new Response(JSON.stringify({ url: 'https://acme.okta.test/oauth2/v1/authorize?x=1' }), { | ||
| status: 200, | ||
| headers: { 'content-type': 'application/json', 'set-cookie': 'sso_state=abc; Path=/' }, | ||
| }) | ||
| } | ||
|
|
||
| describe('GET /sso/launch/[providerId]', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| setEnvFlags({ isSsoEnabled: true }) | ||
| mockGetSession.mockResolvedValue(null) | ||
| mockIsAllowed.mockResolvedValue(true) | ||
| mockEnforceIpRateLimit.mockResolvedValue(null) | ||
| mockSignInSSO.mockResolvedValue(authorizationResponse()) | ||
| }) | ||
|
|
||
| it("redirects to the identity provider and carries Better Auth's state cookie", async () => { | ||
| const response = await open() | ||
|
|
||
| expect(response.status).toBe(307) | ||
| expect(response.headers.get('location')).toBe('https://acme.okta.test/oauth2/v1/authorize?x=1') | ||
| expect(response.headers.get('set-cookie')).toContain('sso_state=abc') | ||
| expect(mockIsAllowed).toHaveBeenCalledWith('acme-okta', ISSUER) | ||
| const [{ body }] = mockSignInSSO.mock.calls[0] | ||
| expect(body.providerId).toBe('acme-okta') | ||
| expect(body).not.toHaveProperty('email') | ||
| /** The plugin appends `?error=…`, which must not corrupt the provider on the way back. */ | ||
| const retry = new URL(`${body.errorCallbackURL}?error=invalid_provider`) | ||
| expect(retry.pathname).toBe('/sso') | ||
| expect(retry.searchParams.get('provider')).toBe('acme-okta') | ||
| }) | ||
|
|
||
| it('sends someone already signed in to the app without signing in again', async () => { | ||
| mockGetSession.mockResolvedValue({ user: { id: 'user-1' } }) | ||
|
|
||
| const response = await open() | ||
|
|
||
| expect(response.headers.get('location')).toBe('https://test.sim.ai/home') | ||
| expect(mockIsAllowed).not.toHaveBeenCalled() | ||
| expect(mockSignInSSO).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('keeps sending a signed-in visitor to the app when the address is rate limited', async () => { | ||
| mockGetSession.mockResolvedValue({ user: { id: 'user-1' } }) | ||
| mockEnforceIpRateLimit.mockResolvedValue(new Response(null, { status: 429 })) | ||
|
|
||
| const response = await open() | ||
|
|
||
| expect(response.headers.get('location')).toBe('https://test.sim.ai/home') | ||
| expect(mockEnforceIpRateLimit).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it.each([ | ||
| ['no issuer', '', () => undefined], | ||
| [ | ||
| 'an issuer the provider does not use', | ||
| `?iss=${encodeURIComponent('https://other.test')}`, | ||
| () => mockIsAllowed.mockResolvedValue(false), | ||
| ], | ||
| ])("sends a visitor with %s to the provider's sign-in link", async (_label, search, arrange) => { | ||
| arrange() | ||
|
|
||
| const response = await open(search) | ||
|
|
||
| expect(response.headers.get('location')).toBe(SIGN_IN_LINK) | ||
| expect(mockSignInSSO).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it.each([ | ||
| ['refuses', () => mockSignInSSO.mockResolvedValue(new Response('{}', { status: 400 }))], | ||
| ['throws', () => mockSignInSSO.mockRejectedValue(new Error('network'))], | ||
| ])("reports the failure on the provider's sign-in link when sign-in %s", async (_l, arrange) => { | ||
| arrange() | ||
|
|
||
| const response = await open() | ||
|
|
||
| const failure = new URL(response.headers.get('location') ?? '') | ||
| expect(failure.pathname).toBe('/sso') | ||
| expect(failure.searchParams.get('error')).toBe('sso_failed') | ||
| expect(failure.searchParams.get('provider')).toBe('acme-okta') | ||
| }) | ||
|
|
||
| it('sends a rate-limited visitor to the sign-in link before any lookup', async () => { | ||
| mockEnforceIpRateLimit.mockResolvedValue(new Response(null, { status: 429 })) | ||
|
|
||
| const response = await open() | ||
|
|
||
| expect(response.headers.get('location')).toBe(SIGN_IN_LINK) | ||
| expect(mockIsAllowed).not.toHaveBeenCalled() | ||
| expect(mockSignInSSO).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('leaves SSO off when the deployment has not enabled it', async () => { | ||
| setEnvFlags({ isSsoEnabled: false }) | ||
|
|
||
| const response = await open() | ||
|
|
||
| expect(response.headers.get('location')).toBe('https://test.sim.ai/login') | ||
| expect(mockEnforceIpRateLimit).not.toHaveBeenCalled() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { toError } from '@sim/utils/errors' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { auth, getSession } from '@/lib/auth' | ||
| import { isIdpInitiatedLoginAllowed } from '@/lib/auth/sso/idp-initiated-login' | ||
| import { isSsoEnabled } from '@/lib/core/config/env-flags' | ||
| import { enforceIpRateLimit } from '@/lib/core/rate-limiter' | ||
| import { getBaseUrl } from '@/lib/core/utils/urls' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { DEFAULT_POST_AUTH_ROUTE } from '@/app/(auth)/auth-redirect' | ||
|
|
||
| const logger = createLogger('SSOLaunchRoute') | ||
|
|
||
| type RouteContext = { params: Promise<{ providerId: string }> } | ||
|
|
||
| /** | ||
| * The initiate login URL an identity provider's app dashboard opens (OpenID Connect third-party | ||
| * initiated login). The dashboard adds its issuer as `iss`, so the URL carries no query of its own. | ||
| * | ||
| * Sign-in starts here rather than on the sign-in page: the visitor arrives to be sent onward, and a | ||
| * redirect spares them a page load and a hydration wait first. Someone already signed in goes | ||
| * straight to the app, so a link cannot replace their session. Anything else — an unknown issuer, a | ||
| * provider this deployment does not serve, a refused sign-in — falls back to the provider's ordinary | ||
| * sign-in link, which asks for an email. | ||
| */ | ||
| export const GET = withRouteHandler(async (request: NextRequest, context: RouteContext) => { | ||
| const { providerId } = await context.params | ||
| const signInLink = new URL( | ||
| `/sso?provider=${encodeURIComponent(providerId)}`, | ||
| getBaseUrl() | ||
| ).toString() | ||
| if (!isSsoEnabled) return NextResponse.redirect(new URL('/login', getBaseUrl()).toString()) | ||
|
|
||
| const session = await getSession() | ||
| if (session?.user) { | ||
| return NextResponse.redirect(new URL(DEFAULT_POST_AUTH_ROUTE, getBaseUrl()).toString()) | ||
| } | ||
|
|
||
| /** Admitted per address, after the session, so a busy shared address never strands a signed-in visitor. */ | ||
| const rateLimited = await enforceIpRateLimit('sso-launch', request, { | ||
| maxTokens: 30, | ||
| refillRate: 30, | ||
| refillIntervalMs: 60_000, | ||
| }) | ||
| if (rateLimited) return NextResponse.redirect(signInLink) | ||
|
|
||
| const issuer = request.nextUrl.searchParams.get('iss') | ||
| if (!issuer || !(await isIdpInitiatedLoginAllowed(providerId, issuer))) { | ||
| return NextResponse.redirect(signInLink) | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /** | ||
| * A failed sign-in returns to the provider's sign-in link with the error. `callbackUrl` comes | ||
| * last because the SSO plugin appends its own error with a raw `?`, which runs into whichever | ||
| * parameter is last — there it is harmless, on `provider` it would corrupt the retry. | ||
| */ | ||
| const errorCallbackURL = new URL( | ||
| `/sso?error=sso_failed&provider=${encodeURIComponent(providerId)}&callbackUrl=${encodeURIComponent(DEFAULT_POST_AUTH_ROUTE)}`, | ||
| getBaseUrl() | ||
| ).toString() | ||
| /** A sign-in that never starts is a failure, so it carries the error rather than a blank form. */ | ||
| let signIn: Response | ||
| try { | ||
| signIn = await auth.api.signInSSO({ | ||
| body: { providerId, callbackURL: DEFAULT_POST_AUTH_ROUTE, errorCallbackURL }, | ||
| headers: request.headers, | ||
| asResponse: true, | ||
| }) | ||
| } catch (error) { | ||
| logger.error('SSO sign-in could not be started', { providerId, error: toError(error) }) | ||
| return NextResponse.redirect(errorCallbackURL) | ||
| } | ||
| const payload = (await signIn.json().catch(() => null)) as { url?: string } | null | ||
| if (!signIn.ok || !payload?.url) { | ||
| logger.error('SSO sign-in did not return an authorization URL', { | ||
| providerId, | ||
| status: signIn.status, | ||
| }) | ||
| return NextResponse.redirect(errorCallbackURL) | ||
| } | ||
|
|
||
| const response = NextResponse.redirect(payload.url) | ||
| /** Better Auth's signed `state` cookie has to reach the browser before the identity provider does. */ | ||
| const signInHeaders = signIn.headers as Headers & { getSetCookie?: () => string[] } | ||
| for (const cookie of signInHeaders.getSetCookie?.() ?? []) { | ||
| response.headers.append('set-cookie', cookie) | ||
| } | ||
| return response | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { dbChainMock, queueTableRows, resetDbChainMock, schemaMock } from '@sim/testing' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| vi.mock('@sim/db', () => ({ ...dbChainMock, ...schemaMock })) | ||
|
|
||
| import { isIdpInitiatedLoginAllowed } from '@/lib/auth/sso/idp-initiated-login' | ||
|
|
||
| function queueProvider(issuer: string) { | ||
| queueTableRows(schemaMock.ssoProvider, [{ issuer }]) | ||
| } | ||
|
|
||
| describe('isIdpInitiatedLoginAllowed', () => { | ||
| beforeEach(() => { | ||
| resetDbChainMock() | ||
| }) | ||
|
|
||
| it.each([ | ||
| ['the issuer it is configured with', 'https://acme.okta.test', 'https://acme.okta.test'], | ||
| ['that issuer with a trailing slash', 'https://acme.okta.test', 'https://acme.okta.test/'], | ||
| [ | ||
| 'the organization URL of its custom authorization server', | ||
| 'https://acme.okta.test/oauth2/default', | ||
| 'https://acme.okta.test', | ||
| ], | ||
| ])('allows a provider opened by %s', async (_label, configured, opened) => { | ||
| queueProvider(configured) | ||
| await expect(isIdpInitiatedLoginAllowed('acme-okta', opened)).resolves.toBe(true) | ||
| }) | ||
|
|
||
| it.each([ | ||
| ['another identity provider', 'https://attacker.example.test'], | ||
| ['a value that is not a URL', 'not-a-url'], | ||
| ])('refuses a link opened by %s', async (_label, opened) => { | ||
| queueProvider('https://acme.okta.test') | ||
| await expect(isIdpInitiatedLoginAllowed('acme-okta', opened)).resolves.toBe(false) | ||
| }) | ||
|
|
||
| it('refuses a provider that is unknown, unverified, or SAML', async () => { | ||
| queueTableRows(schemaMock.ssoProvider, []) | ||
| await expect(isIdpInitiatedLoginAllowed('acme-okta', 'https://acme.okta.test')).resolves.toBe( | ||
| false | ||
| ) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.