Skip to content

Commit af9befb

Browse files
committed
fix(auth): report the enforced two-factor requirement, cover desktop session reads, fail closed on check errors
1 parent 86847a9 commit af9befb

11 files changed

Lines changed: 55 additions & 23 deletions

File tree

‎apps/sim/app/api/desktop/auth/handoff/route.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
33
import { headers } from 'next/headers'
44
import { type NextRequest, NextResponse } from 'next/server'
5-
import { auth } from '@/lib/auth'
5+
import { auth, enforceTwoFactorRequirement } from '@/lib/auth'
66
import { getBetterAuthClientErrorStatus } from '@/lib/auth/better-auth-error'
77
import { createDesktopHandoffToken } from '@/lib/auth/desktop-handoff'
88
import { enforceIpRateLimit } from '@/lib/core/rate-limiter'
@@ -32,10 +32,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
3232
// Force a database-backed read. A cookie-cached session can outlive its row
3333
// after a sign-out or revoke, and minting against one would hand the desktop
3434
// a token that can never be redeemed.
35-
const session = await auth.api.getSession({
36-
headers: hdrs,
37-
query: { disableCookieCache: true },
38-
})
35+
const session = await enforceTwoFactorRequirement(
36+
await auth.api.getSession({
37+
headers: hdrs,
38+
query: { disableCookieCache: true },
39+
})
40+
)
3941
if (!session?.user) {
4042
return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
4143
}

‎apps/sim/app/desktop/auth/page.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { Metadata } from 'next'
22
import { headers } from 'next/headers'
33
import { redirect } from 'next/navigation'
4-
import { auth } from '@/lib/auth'
4+
import { auth, enforceTwoFactorRequirement } from '@/lib/auth'
55
import { isSsoEnabled } from '@/lib/core/config/env-flags'
66
import { getOAuthProviderStatus } from '@/app/(auth)/components/oauth-provider-checker'
77
import { AuthorizeHandoff } from '@/app/desktop/auth/authorize-handoff'
@@ -57,7 +57,9 @@ export default async function DesktopAuthPage({ searchParams }: DesktopAuthPageP
5757
// sends the user to re-login instead of rendering a confirm screen whose
5858
// token mint is doomed to fail.
5959
const hdrs = await headers()
60-
const session = await auth.api.getSession({ headers: hdrs, query: { disableCookieCache: true } })
60+
const session = await enforceTwoFactorRequirement(
61+
await auth.api.getSession({ headers: hdrs, query: { disableCookieCache: true } })
62+
)
6163
if (!session?.user) {
6264
const callbackUrl = buildDesktopAuthPath(state, port)
6365
// The app passes along the sign-in method the user already picked there,

‎apps/sim/app/desktop/connect/page.tsx‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { Metadata } from 'next'
22
import { headers } from 'next/headers'
33
import { redirect } from 'next/navigation'
4-
import { auth } from '@/lib/auth'
4+
import { auth, enforceTwoFactorRequirement } from '@/lib/auth'
55
import { getBaseUrl } from '@/lib/core/utils/urls'
66
import { isValidHandoffState, parseLoopbackPort } from '@/app/desktop/auth/validation'
77
import { DesktopHandoffShell } from '@/app/desktop/components/desktop-handoff-shell'
@@ -92,10 +92,12 @@ export default async function DesktopConnectPage({ searchParams }: DesktopConnec
9292
// Force a DB-backed session read (bypass the cookie cache) so a revoked
9393
// browser session goes to login instead of starting a doomed link flow.
9494
const hdrs = await headers()
95-
const session = await auth.api.getSession({
96-
headers: hdrs,
97-
query: { disableCookieCache: true },
98-
})
95+
const session = await enforceTwoFactorRequirement(
96+
await auth.api.getSession({
97+
headers: hdrs,
98+
query: { disableCookieCache: true },
99+
})
100+
)
99101
if (!session?.user) {
100102
redirect(
101103
`/login?callbackUrl=${encodeURIComponent(

‎apps/sim/app/workspace/[workspaceId]/settings/components/general/components/two-factor-settings.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ export function TwoFactorSettings() {
5151
const organizationId = getActiveOrganizationId(session) ?? undefined
5252
const passwordAccount = useHasPasswordAccount(userId)
5353
const policy = useOrganizationTwoFactorPolicy(organizationId)
54-
const requiredByOrganization = policy.data?.requireTwoFactor === true
54+
const requiredByOrganization = policy.data?.isEnforced === true
5555
const hasPassword = passwordAccount.data === true
5656

5757
const startSetup = useStartTwoFactorSetup()

‎apps/sim/components/settings/organization-security.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ function membersPhrase(count: number): string {
4949
}
5050

5151
function describeTwoFactorPolicy(policy: OrganizationTwoFactorPolicy, canManage: boolean): string {
52+
if (!policy.isEntitled) {
53+
return policy.requireTwoFactor
54+
? 'Not enforced: requiring two-factor authentication is available on Enterprise plans.'
55+
: 'Requiring two-factor authentication is available on Enterprise plans.'
56+
}
5257
if (canManage && !policy.requireTwoFactor && !policy.viewerHasTwoFactor) {
5358
return 'Set up two-factor authentication on your own account in General settings before requiring it.'
5459
}
@@ -136,7 +141,7 @@ function OrganizationTwoFactorSection({ organizationId }: OrganizationSecuritySe
136141
disabled={
137142
!canManage ||
138143
updatePolicy.isPending ||
139-
(!data.requireTwoFactor && !data.viewerHasTwoFactor)
144+
(!data.requireTwoFactor && (!data.isEntitled || !data.viewerHasTwoFactor))
140145
}
141146
/>
142147
</div>

‎apps/sim/lib/api/contracts/organization.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,12 @@ const updateOrganizationTwoFactorPolicyBodySchema = z.object({
192192
})
193193

194194
const organizationTwoFactorPolicyDataSchema = z.object({
195-
/** Whether members must use two-factor authentication. */
195+
/** The stored setting. */
196196
requireTwoFactor: z.boolean(),
197+
/** Whether the organization's plan includes the requirement (always true when self-hosted). */
198+
isEntitled: z.boolean(),
199+
/** Whether sign-in actually enforces it — false once the organization leaves Enterprise. */
200+
isEnforced: z.boolean(),
197201
/**
198202
* Members who have not set up two-factor and would be asked to on their next sign-in. Shown to
199203
* owners and admins only; null for everyone else.

‎apps/sim/lib/auth/auth.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2030,7 +2030,7 @@ async function getSessionImpl() {
20302030

20312031
const hdrs = await headers()
20322032
return recordSessionAuth(
2033-
await withoutUnenrolledSession(
2033+
await enforceTwoFactorRequirement(
20342034
await auth.api.getSession({
20352035
headers: hdrs,
20362036
})
@@ -2046,9 +2046,12 @@ type ResolvedSession = Awaited<ReturnType<typeof auth.api.getSession>>
20462046
* requirement or the membership: someone who joined, or whose organization turned the requirement
20472047
* on, while signed in. Revoking rather than only hiding it means the session also stops working on
20482048
* Better Auth's own endpoints; the app's stale-session recovery then sends them to sign in, where
2049-
* they are asked to enroll.
2049+
* they are asked to enroll. Every server read of the current session goes through this — `getSession`
2050+
* and the desktop pages that read the session directly to bypass the cookie cache.
20502051
*/
2051-
async function withoutUnenrolledSession(session: ResolvedSession): Promise<ResolvedSession> {
2052+
export async function enforceTwoFactorRequirement(
2053+
session: ResolvedSession
2054+
): Promise<ResolvedSession> {
20522055
if (!session?.user?.id) return session
20532056
/** Better Auth's inferred session type omits plugin fields; read them untyped. */
20542057
const user: Record<string, unknown> = session.user
@@ -2062,13 +2065,16 @@ async function withoutUnenrolledSession(session: ResolvedSession): Promise<Resol
20622065
/** The cookie cache may predate an enrollment; only a fresh read can condemn the session. */
20632066
if (!needsTwoFactorSetup(await getTwoFactorState(session.user.id))) return session
20642067
} catch (error) {
2065-
/** Sign-in is the strict gate; a billing read failing here must not take every request down. */
2068+
/**
2069+
* Fails closed for this request only: a member whose requirement cannot be read is treated as
2070+
* signed out, without revoking a session that may well be compliant.
2071+
*/
20662072
logger.error('Could not check the organization two-factor requirement', {
20672073
userId: session.user.id,
20682074
organizationId,
20692075
error,
20702076
})
2071-
return session
2077+
return null
20722078
}
20732079

20742080
logger.warn('Revoking a session that does not meet its organization two-factor requirement', {

‎apps/sim/lib/auth/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
export { auth, getSession } from './auth'
1+
export { auth, enforceTwoFactorRequirement, getSession } from './auth'

‎apps/sim/lib/auth/two-factor/guard.integration.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -611,7 +611,11 @@ describe('two-factor authentication in PostgreSQL', () => {
611611
input: { organizationId, requireTwoFactor: true },
612612
})
613613

614-
expect(result).toMatchObject({ requireTwoFactor: true, membersWithoutTwoFactor: 1 })
614+
expect(result).toMatchObject({
615+
requireTwoFactor: true,
616+
isEnforced: true,
617+
membersWithoutTwoFactor: 1,
618+
})
615619
expect(await sessionCount(teammate.id)).toBe(0)
616620
expect(await sessionCount(admin.id)).toBeGreaterThan(0)
617621
})

‎apps/sim/lib/organizations/application/two-factor-policy.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ async function loadPolicy(
4242
.limit(1)
4343
if (!org) throw new OrchestrationError('not_found', 'Organization not found')
4444

45-
const [[unenrolled], [viewer]] = await Promise.all([
45+
const [[unenrolled], [viewer], isEntitled] = await Promise.all([
4646
viewerIsAdministrator
4747
? db
4848
.select({ total: count() })
@@ -57,11 +57,16 @@ async function loadPolicy(
5757
.where(eq(user.id, viewerUserId))
5858
.limit(1)
5959
: Promise.resolve([]),
60+
/** Read fresh rather than through the sign-in cache: an admin is waiting on this answer. */
61+
isOrganizationFeatureEntitled(organizationId, true),
6062
])
6163

6264
return {
6365
organizationName: org.name,
6466
requireTwoFactor: org.requireTwoFactor,
67+
isEntitled,
68+
/** The same terms sign-in checks, so the surface reports what is actually enforced. */
69+
isEnforced: org.requireTwoFactor && isEntitled,
6570
membersWithoutTwoFactor: viewerIsAdministrator ? (unenrolled?.total ?? 0) : null,
6671
viewerHasTwoFactor: viewer?.enabled === true,
6772
}

0 commit comments

Comments
 (0)