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
27 changes: 18 additions & 9 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2045,9 +2045,17 @@ type ResolvedSession = Awaited<ReturnType<typeof auth.api.getSession>>
* up. Sign-in already refuses such a session, so this catches the ones that predate the
* requirement or the membership: someone who joined, or whose organization turned the requirement
* on, while signed in. Revoking rather than only hiding it means the session also stops working on
* Better Auth's own endpoints; the app's stale-session recovery then sends them to sign in, where
* they are asked to enroll. Every server read of the current session goes through this — `getSession`
* and the desktop pages that read the session directly to bypass the cookie cache.
* Better Auth's own endpoints, and the member's OAuth grants go with it so an MCP client
* authorized from the session does not outlive it; the app's stale-session recovery then sends
* them to sign in, where they are asked to enroll. Every server read of the current session
* goes through this — `getSession` and the desktop pages that read the session directly to bypass
* the cookie cache.
*
* A requirement that cannot be read leaves the session as it is. This is a sweep behind the
* controls that fail closed — sign-in refuses an unenrolled member, and turning the requirement on
* revokes their sessions and grants at once — while treating a session as signed out here starts
* the app's stale-session recovery, which signs the person out: a database blip would end sessions
* that comply. The next request that can read the requirement sweeps the session.
*/
export async function enforceTwoFactorRequirement(
session: ResolvedSession
Expand All @@ -2059,29 +2067,30 @@ export async function enforceTwoFactorRequirement(
if (user.twoFactorEnabled === true) return session
/** Platform-admin impersonation stays available for supporting a member who cannot enroll. */
if (current.impersonatedBy) return session
/** Swallows a failed read as "no organization", the same leave-it-be answer the catch gives. */
const organizationId = await getMemberOrganizationId(session.user.id)
try {
if (!(await isTwoFactorRequiredForOrganization(organizationId))) return session
/** The cookie cache may predate an enrollment; only a fresh read can condemn the session. */
if (!needsTwoFactorSetup(await getTwoFactorState(session.user.id))) return session
} catch (error) {
/**
* Fails closed for this request only: a member whose requirement cannot be read is treated as
* signed out, without revoking a session that may well be compliant.
*/
logger.error('Could not check the organization two-factor requirement', {
userId: session.user.id,
organizationId,
error,
})
return null
return session
}

logger.warn('Revoking a session that does not meet its organization two-factor requirement', {
userId: session.user.id,
organizationId,
})
await db.delete(schema.session).where(eq(schema.session.id, session.session.id))
/** Together, so a failed grant revocation cannot leave the grants behind a deleted session. */
await db.transaction(async (tx) => {
await tx.delete(schema.session).where(eq(schema.session.id, session.session.id))
await revokeUserOAuthGrants(session.user.id, tx)
})
return null
}

Expand Down
93 changes: 91 additions & 2 deletions apps/sim/lib/auth/two-factor/guard.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
account,
auditLog,
member,
oauthClient,
oauthTokenFamily,
organization,
session,
twoFactor,
Expand Down Expand Up @@ -32,7 +34,9 @@ vi.mock('@/lib/posthog/server', () => posthogServerMock)
describe('two-factor authentication in PostgreSQL', () => {
let auth: typeof import('@/lib/auth/auth').auth
let prepareSessionForCreation: typeof import('@/lib/auth/session-hooks').prepareSessionForCreation
let enforceTwoFactorRequirement: typeof import('@/lib/auth/auth').enforceTwoFactorRequirement
let invalidateTwoFactorPolicyCache: typeof import('@/lib/auth/two-factor/policy').invalidateTwoFactorPolicyCache
let isTwoFactorRequiredForOrganization: typeof import('@/lib/auth/two-factor/policy').isTwoFactorRequiredForOrganization
let readOrganizationTwoFactorPolicy: typeof import('@/lib/organizations/application/two-factor-policy').readOrganizationTwoFactorPolicy
let setOrganizationTwoFactorPolicy: typeof import('@/lib/organizations/application/two-factor-policy').setOrganizationTwoFactorPolicy
let passwordHash: string
Expand All @@ -41,9 +45,11 @@ describe('two-factor authentication in PostgreSQL', () => {
const password = 'Two-factor-fixture-password-only-41!'

beforeAll(async () => {
;({ auth } = await import('@/lib/auth/auth'))
;({ auth, enforceTwoFactorRequirement } = await import('@/lib/auth/auth'))
;({ prepareSessionForCreation } = await import('@/lib/auth/session-hooks'))
;({ invalidateTwoFactorPolicyCache } = await import('@/lib/auth/two-factor/policy'))
;({ invalidateTwoFactorPolicyCache, isTwoFactorRequiredForOrganization } = await import(
'@/lib/auth/two-factor/policy'
))
;({ readOrganizationTwoFactorPolicy, setOrganizationTwoFactorPolicy } = await import(
'@/lib/organizations/application/two-factor-policy'
))
Expand Down Expand Up @@ -359,6 +365,23 @@ describe('two-factor authentication in PostgreSQL', () => {
expect(row?.enabled).toBe(true)
})

it('challenges enrollment at sign-in even while this instance caches the requirement as off', async () => {
const fixture = await createUser()
const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }])
/** Another instance turned it on: this process still caches "not required" for the TTL. */
expect(await isTwoFactorRequiredForOrganization(organizationId)).toBe(false)
await db
.update(organization)
.set({ requireTwoFactor: true })
.where(eq(organization.id, organizationId))
expect(await isTwoFactorRequiredForOrganization(organizationId)).toBe(false)

const { response } = await signInWithPassword(fixture.email)

expect(await response.json()).toMatchObject({ twoFactorSetupRequired: true })
expect(await sessionCount(fixture.id)).toBe(0)
})

it('never lets a first factor alone replace an existing enrollment', async () => {
const fixture = await createUser()
await enroll(fixture.email)
Expand Down Expand Up @@ -587,6 +610,72 @@ describe('two-factor authentication in PostgreSQL', () => {
expect(recipients).toEqual([fixture.email, fixture.email, fixture.email, fixture.email])
})

it('ends an unenrolled member’s session and OAuth grants once their organization requires it', async () => {
const fixture = await createUser()
const organizationId = await createOrganization([{ userId: fixture.id, role: 'member' }])
const { cookie } = await signInWithPassword(fixture.email)
const [current] = await db
.select({ id: session.id })
.from(session)
.where(eq(session.userId, fixture.id))
.limit(1)
if (!current) throw new Error('session missing')
const clientId = generateId()
const now = new Date()
await db.insert(oauthClient).values({
id: clientId,
clientId,
name: 'Two-factor sweep fixture',
public: true,
tokenEndpointAuthMethod: 'none',
grantTypes: ['authorization_code', 'refresh_token'],
redirectUris: ['http://127.0.0.1/callback'],
})
try {
await db.insert(oauthTokenFamily).values({
id: generateId(),
clientId,
userId: fixture.id,
sessionId: current.id,
createdAt: now,
expiresAt: new Date(now.getTime() + 86_400_000),
})
await setRequirement(organizationId, true)

const swept = await enforceTwoFactorRequirement(
await auth.api.getSession({ headers: new Headers({ cookie }) })
)

expect(swept).toBeNull()
expect(await sessionCount(fixture.id)).toBe(0)
const [grants] = await db
.select({ total: count() })
.from(oauthTokenFamily)
.where(eq(oauthTokenFamily.userId, fixture.id))
expect(grants?.total).toBe(0)
} finally {
await db.delete(oauthClient).where(eq(oauthClient.id, clientId))
}
})

it('signs an administrator-reset member out of cached sessions as well', async () => {
const fixture = await createUser()
const operator = await createUser()
await createOrganization([{ userId: fixture.id, role: 'member' }])
const { cookie } = await enroll(fixture.email)
expect(await auth.api.getSession({ headers: new Headers({ cookie }) })).not.toBeNull()
await db.update(user).set({ role: 'admin' }).where(eq(user.id, operator.id))
const { cookie: adminCookie } = await signInWithPassword(operator.email)

const reset = await auth.handler(
request('/admin/reset-two-factor', { userId: fixture.id }, adminCookie)
)

expect(reset.status).toBe(200)
expect(await sessionCount(fixture.id)).toBe(0)
expect(await auth.api.getSession({ headers: new Headers({ cookie }) })).toBeNull()
})

it('lets only a platform administrator reset someone else’s two-factor', async () => {
const fixture = await createUser()
const operator = await createUser()
Expand Down
3 changes: 2 additions & 1 deletion apps/sim/lib/auth/two-factor/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
import { notifyTwoFactorChange } from '@/lib/auth/two-factor/notify'
import { getTwoFactorState, needsTwoFactorSetup } from '@/lib/auth/two-factor/policy'
import type { DbOrTx } from '@/lib/db/types'
import { revokeAllUserSessions } from '@/lib/organizations/members/revocation'

const logger = createLogger('TwoFactorGuard')

Expand Down Expand Up @@ -428,7 +429,7 @@ export function twoFactorGuardPlugin() {
where: [{ field: 'userId', value: target.id }],
})
await ctx.context.internalAdapter.updateUser(target.id, { twoFactorEnabled: false })
await ctx.context.internalAdapter.deleteUserSessions(target.id)
await revokeAllUserSessions(target.id)
await revokeUserOAuthGrants(target.id)
await forgetTrustedDevices(target.id)
logger.warn('Platform administrator reset two-factor authentication', {
Expand Down
55 changes: 41 additions & 14 deletions apps/sim/lib/auth/two-factor/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,30 @@ const requirementCache = new LRUCache<string, boolean>({
})

/**
* Whether an organization requires its members to use two-factor authentication. On Sim Cloud the
* stored setting enforces only while the organization is on Enterprise, the plan that shows the
* setting: an organization that downgrades stops enforcing rather than being held to a setting
* its administrators can no longer see or turn off. Self-hosted deployments always enforce it.
* Whether a stored requirement enforces. On Sim Cloud it does only while the organization is on
* Enterprise, the plan that shows the setting: an organization that downgrades stops enforcing
* rather than being held to a setting its administrators can no longer see or turn off.
* Self-hosted deployments always enforce it.
*
* A failed entitlement read throws rather than answering "not required": a permissive answer
* would let a sign-in skip enrollment, and would be cached for the whole TTL.
* would let a sign-in skip enrollment.
*/
async function enforcesRequirement(
organizationId: string,
requireTwoFactor: boolean,
executor: DbOrTx
): Promise<boolean> {
return (
requireTwoFactor &&
(await isOrganizationFeatureEntitled(organizationId, true, executor, { onError: 'throw' }))
)
}

/**
* Whether an organization requires its members to use two-factor authentication, through a
* per-process cache, for the check that runs on every session read. A requirement turned on
* reaches it within the TTL on other instances; sign-in and second-factor changes read fresh
* through {@link getTwoFactorState} instead.
*/
export async function isTwoFactorRequiredForOrganization(
organizationId: string | null | undefined,
Expand All @@ -41,10 +58,11 @@ export async function isTwoFactorRequiredForOrganization(
.from(organization)
.where(eq(organization.id, organizationId))
.limit(1)

const required =
row?.requireTwoFactor === true &&
(await isOrganizationFeatureEntitled(organizationId, true, executor, { onError: 'throw' }))
const required = await enforcesRequirement(
organizationId,
row?.requireTwoFactor === true,
executor
)
if (isPrimaryPoolClient(executor)) requirementCache.set(organizationId, required)
return required
}
Expand All @@ -65,24 +83,33 @@ export interface TwoFactorState {
}

/**
* Reads a user's two-factor state fresh from the database. Used where a session is being created
* or a sign-in challenged, where a stale cached answer would be a bypass. Users belong to at most
* one organization, the same assumption every other membership policy makes.
* Reads a user's two-factor state fresh from the database, the organization's requirement
* included. Used where a session is being created, a sign-in challenged or a second factor
* changed, where a cached answer from before an administrator turned the requirement on would let
* a member through without enrolling. Users belong to at most one organization, the same
* assumption every other membership policy makes.
*/
export async function getTwoFactorState(
userId: string,
executor: DbOrTx = db
): Promise<TwoFactorState> {
const [row] = await executor
.select({ enabled: user.twoFactorEnabled, organizationId: member.organizationId })
.select({
enabled: user.twoFactorEnabled,
organizationId: member.organizationId,
requireTwoFactor: organization.requireTwoFactor,
})
.from(user)
.leftJoin(member, eq(member.userId, user.id))
.leftJoin(organization, eq(organization.id, member.organizationId))
.where(eq(user.id, userId))
.limit(1)

return {
enabled: row?.enabled === true,
required: await isTwoFactorRequiredForOrganization(row?.organizationId, executor),
required: row?.organizationId
? await enforcesRequirement(row.organizationId, row.requireTwoFactor === true, executor)
: false,
}
}

Expand Down
35 changes: 34 additions & 1 deletion apps/sim/lib/organizations/members/revocation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { apiKey, organization, session as sessionTable } from '@sim/db/schema'
import { db } from '@sim/db'
import { apiKey, member, organization, session as sessionTable } from '@sim/db/schema'
import { and, eq, isNull, ne, sql } from 'drizzle-orm'
import {
invalidateMembershipCache,
Expand Down Expand Up @@ -59,6 +60,38 @@ export async function revokeUserSessionsTx(
return { revoked: deleted.length }
}

/**
* Ends every session a user holds, whether or not they belong to an organization. A member goes
* through {@link revokeUserSessionsTx}, so their cached session cookies re-read the database on
* the next request; someone in no organization has no cookie-cache version to move, and only the
* cache's own lifetime bounds a cookie they already hold. Impersonation sessions are spared either
* way. Membership is read inside the transaction, so a concurrent join or leave cannot leave the
* wrong organization's version unbumped.
*/
export async function revokeAllUserSessions(userId: string): Promise<RevokeSessionsResult> {
const { organizationId, revoked } = await db.transaction(async (tx) => {
const [membership] = await tx
.select({ organizationId: member.organizationId })
.from(member)
.where(eq(member.userId, userId))
.limit(1)
if (membership) {
const result = await revokeUserSessionsTx(tx, {
userId,
organizationId: membership.organizationId,
})
return { organizationId: membership.organizationId, revoked: result.revoked }
}
const deleted = await tx
.delete(sessionTable)
.where(and(eq(sessionTable.userId, userId), isNull(sessionTable.impersonatedBy)))
.returning({ id: sessionTable.id })
return { organizationId: null, revoked: deleted.length }
})
if (organizationId) invalidateAfterSessionRevocation({ userId, organizationId })
return { revoked }
}

/**
* Drops the caches that make a revocation visible to the next request.
*
Expand Down
Loading