mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-21 20:38:47 +00:00
chore(login): Extract auth flow utilities and eliminate RSC request interference (#10644)
The /login route was experiencing issues with React Server Component
(RSC) requests interfering with one-time authentication callbacks. When
users navigated to /login via client-side routing (router.push()),
Next.js automatically triggered _rsc requests that could consume
single-use createCallback tokens, breaking OIDC and SAML authentication
flows.
# Which Problems Are Solved
When users attempt to log in, Next.js automatically makes requests with
the `_rsc=1` query parameter for React Server Components. The current
implementation treats these as server errors:
```typescript
// Before
if (_rsc) {
return NextResponse.json({ error: "No _rsc supported" }, { status: 500 });
}
```
This results in:
- Spurious 500 error logs polluting monitoring systems
- False alerts for server failures
- Difficulty distinguishing real issues from benign RSC requests
# How the Problems Are Solved
This PR implements a comprehensive refactoring that:
- Eliminates RSC interference by providing server actions for internal
auth flow completion
- Separates concerns between external flow initiation and internal flow
completion
- Extracts shared utilities to improve code maintainability and
reusability
- Maintains full backward compatibility for external applications
# Additional Context
## New Architecture
- auth-flow.ts: Shared utilities for auth flow completion with RSC
protection
- flow-initiation.ts: Extracted OIDC/SAML flow initiation logic (~400
lines)
- auth.ts: Server actions for internal components
## Route Handler Simplification
- route.ts: Reduced from ~350 lines to ~75 lines
- External-only focus: Now handles only flow initiation for external
applications
- Removed completion logic: External apps use their own callback URLs
- Enhanced validation: Early RSC blocking and parameter validation
## Flow Logic Improvements
- Early return patterns: Guard clauses eliminate deep nesting
- Better error handling: Specific error messages for different failure
modes
- Fixed SAML flow: Addressed incomplete logic
- Consistent session handling: Unified approach across OIDC and SAML
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Unit tests for the isSessionValid function.
|
||||
*
|
||||
*
|
||||
* This test suite covers the comprehensive session validation logic including:
|
||||
* - Session expiration checks
|
||||
* - User presence validation
|
||||
@@ -113,10 +113,7 @@ describe("isSessionValid", () => {
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Session is expired",
|
||||
expect.any(String)
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith("Session is expired", expect.any(String));
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -147,7 +144,7 @@ describe("isSessionValid", () => {
|
||||
});
|
||||
|
||||
describe("MFA validation with configured authentication methods", () => {
|
||||
test("should return true when TOTP is configured and verified", async () => {
|
||||
test("should return true when TOTP is configured and verified with MFA required", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
@@ -167,8 +164,9 @@ describe("isSessionValid", () => {
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.listAuthenticationMethodTypes).mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.TOTP],
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: true,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
@@ -176,7 +174,35 @@ describe("isSessionValid", () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false when TOTP is configured but not verified", async () => {
|
||||
test("should return true when TOTP is configured but not verified and MFA is not required", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// No TOTP verification
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: false,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false when TOTP is configured but not verified and MFA is required", async () => {
|
||||
const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
@@ -195,28 +221,19 @@ describe("isSessionValid", () => {
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.listAuthenticationMethodTypes).mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.TOTP],
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: true,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Session has no valid MFA factor. Configured methods:",
|
||||
[AuthenticationMethodType.TOTP],
|
||||
"Session factors:",
|
||||
expect.objectContaining({
|
||||
totp: undefined,
|
||||
otpEmail: undefined,
|
||||
otpSms: undefined,
|
||||
webAuthN: undefined,
|
||||
})
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith("Session has no valid multifactor", expect.any(Object));
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("should return true when OTP Email is configured and verified", async () => {
|
||||
test("should return true when OTP Email is configured and verified with MFA required", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
@@ -274,7 +291,7 @@ describe("isSessionValid", () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return true when multiple auth methods are configured and one is verified", async () => {
|
||||
test("should return true when multiple auth methods are configured and one is verified with MFA required", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
@@ -295,6 +312,11 @@ describe("isSessionValid", () => {
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: true,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(zitadelModule.listAuthenticationMethodTypes).mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.TOTP, AuthenticationMethodType.OTP_EMAIL],
|
||||
} as any);
|
||||
@@ -303,6 +325,195 @@ describe("isSessionValid", () => {
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return true when session has only password and MFA is not required by policy", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// No MFA factors verified
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: false,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return true when user has PASSWORD and TOTP configured but only password verified and MFA not required", async () => {
|
||||
// This test specifically covers the original bug scenario:
|
||||
// - User has PASSWORD and TOTP configured (would show up in listAuthenticationMethodTypes)
|
||||
// - User has only verified password, not TOTP
|
||||
// - MFA is not required by policy
|
||||
// - Session should be valid (this was the bug - it was returning false)
|
||||
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// TOTP is configured but NOT verified - this is the key part
|
||||
// totp: undefined (no verifiedAt)
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: false,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false when user has PASSWORD and TOTP configured but only password verified and MFA IS required", async () => {
|
||||
// This is the counterpart test to ensure MFA is still enforced when required
|
||||
|
||||
const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// TOTP is configured but NOT verified
|
||||
// totp: undefined (no verifiedAt)
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: true,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
vi.mocked(zitadelModule.listAuthenticationMethodTypes).mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.TOTP],
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Session has no valid MFA factor. Configured methods:",
|
||||
[AuthenticationMethodType.TOTP],
|
||||
"Session factors:",
|
||||
expect.objectContaining({
|
||||
totp: undefined,
|
||||
otpEmail: undefined,
|
||||
otpSms: undefined,
|
||||
webAuthN: undefined,
|
||||
}),
|
||||
);
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("REGRESSION TEST: user with only PASSWORD factor should be valid when MFA not required", async () => {
|
||||
// This test specifically verifies the original bug is fixed
|
||||
// Original bug: A user with only PASSWORD authentication would be invalid
|
||||
// because the code checked if authMethods.length > 0 (which included PASSWORD)
|
||||
// and then required MFA verification even when MFA was not required by policy
|
||||
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// Explicitly no MFA factors at all
|
||||
totp: undefined,
|
||||
otpEmail: undefined,
|
||||
otpSms: undefined,
|
||||
webAuthN: undefined,
|
||||
intent: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: false,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
// This should be true - if it's false, the original bug still exists
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("DEMONSTRATION: how the original bug would manifest with old logic", async () => {
|
||||
// This test demonstrates the original problematic scenario:
|
||||
// 1. listAuthenticationMethodTypes returns [PASSWORD, TOTP]
|
||||
// 2. Old logic would check authMethods.length > 0 (true because PASSWORD is included)
|
||||
// 3. Old logic would then require MFA verification regardless of policy
|
||||
// 4. User has only password verified, no TOTP
|
||||
// 5. Session would be marked invalid even though MFA is not required
|
||||
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
password: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// User has TOTP configured but not verified
|
||||
totp: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// MFA is NOT required by policy
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: false,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
// With our fix, this should be true (session is valid)
|
||||
// With the old logic, this would have been false (bug)
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MFA validation with login settings (no configured auth methods)", () => {
|
||||
@@ -368,10 +579,7 @@ describe("isSessionValid", () => {
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Session has no valid multifactor",
|
||||
expect.any(Object)
|
||||
);
|
||||
expect(consoleSpy).toHaveBeenCalledWith("Session has no valid multifactor", expect.any(Object));
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
@@ -493,7 +701,7 @@ describe("isSessionValid", () => {
|
||||
expect(result).toBe(false);
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"Session invalid: Email not verified and EMAIL_VERIFICATION is enabled",
|
||||
mockUserId
|
||||
mockUserId,
|
||||
);
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
@@ -647,6 +855,44 @@ describe("isSessionValid", () => {
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return true when authenticated with IDP intent even with forced MFA", async () => {
|
||||
const verifiedTimestamp = createMockTimestamp();
|
||||
const session = createMockSession({
|
||||
factors: {
|
||||
user: {
|
||||
id: mockUserId,
|
||||
organizationId: mockOrganizationId,
|
||||
loginName: "[email protected]",
|
||||
displayName: "Test User",
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
intent: {
|
||||
verifiedAt: verifiedTimestamp,
|
||||
},
|
||||
// No password factor, no MFA factors
|
||||
},
|
||||
});
|
||||
|
||||
// Organization enforces MFA
|
||||
vi.mocked(zitadelModule.getLoginSettings).mockResolvedValue({
|
||||
forceMfa: true,
|
||||
forceMfaLocalOnly: false,
|
||||
} as any);
|
||||
|
||||
// User has MFA methods configured but none verified
|
||||
vi.mocked(zitadelModule.listAuthenticationMethodTypes).mockResolvedValue({
|
||||
authMethodTypes: [AuthenticationMethodType.TOTP, AuthenticationMethodType.OTP_EMAIL],
|
||||
} as any);
|
||||
|
||||
// Should still return true because IDP bypasses MFA requirements
|
||||
const result = await isSessionValid({ serviceUrl: mockServiceUrl, session });
|
||||
|
||||
expect(result).toBe(true);
|
||||
// Verify that getLoginSettings was not called since IDP should bypass MFA check entirely
|
||||
expect(zitadelModule.getLoginSettings).not.toHaveBeenCalled();
|
||||
expect(zitadelModule.listAuthenticationMethodTypes).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
@@ -682,4 +928,4 @@ describe("isSessionValid", () => {
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user