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:
Max Peintner
2025-09-22 16:09:20 +00:00
committed by GitHub
parent 0a31f4ba2b
commit 637b370c17
23 changed files with 1334 additions and 1146 deletions
+44 -65
View File
@@ -1,9 +1,6 @@
"use server";
import {
createSessionAndUpdateCookie,
setSessionAndUpdateCookie,
} from "@/lib/server/cookie";
import { createSessionAndUpdateCookie, setSessionAndUpdateCookie } from "@/lib/server/cookie";
import {
getLockoutSettings,
getLoginSettings,
@@ -18,18 +15,12 @@ import {
} from "@/lib/zitadel";
import { ConnectError, create, Duration } from "@zitadel/client";
import { createUserServiceClient } from "@zitadel/client/v2";
import {
Checks,
ChecksSchema,
} from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { Checks, ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { LoginSettings } from "@zitadel/proto/zitadel/settings/v2/login_settings_pb";
import { User, UserState } from "@zitadel/proto/zitadel/user/v2/user_pb";
import {
AuthenticationMethodType,
SetPasswordRequestSchema,
} from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { AuthenticationMethodType, SetPasswordRequestSchema } from "@zitadel/proto/zitadel/user/v2/user_service_pb";
import { headers } from "next/headers";
import { getNextUrl } from "../client";
import { completeFlowOrGetUrl } from "../client";
import { getSessionCookieById, getSessionCookieByLoginName } from "../cookies";
import { getServiceUrlFromHeaders } from "../service-url";
import {
@@ -61,11 +52,7 @@ export async function resetPassword(command: ResetPasswordCommand) {
organizationId: command.organization,
});
if (
!users.details ||
users.details.totalResult !== BigInt(1) ||
!users.result[0].userId
) {
if (!users.details || users.details.totalResult !== BigInt(1) || !users.result[0].userId) {
return { error: "Could not send Password Reset Link" };
}
const userId = users.result[0].userId;
@@ -88,7 +75,7 @@ export type UpdateSessionCommand = {
requestId?: string;
};
export async function sendPassword(command: UpdateSessionCommand) {
export async function sendPassword(command: UpdateSessionCommand): Promise<{ error: string } | { redirect: string }> {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
@@ -139,18 +126,17 @@ export async function sendPassword(command: UpdateSessionCommand) {
return {
error:
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
(lockoutSettings?.maxPasswordAttempts &&
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
(lockoutSettings?.maxPasswordAttempts && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
? "Contact your administrator to unlock your account"
: ""),
};
}
return { error: "Could not create session for user" };
}
} else {
// this is a fake error message to hide that the user does not even exist
return { error: "Could not verify password" };
}
// this is a fake error message to hide that the user does not even exist
return { error: "Could not verify password" };
} else {
loginSettings = await getLoginSettings({
serviceUrl,
@@ -188,8 +174,7 @@ export async function sendPassword(command: UpdateSessionCommand) {
return {
error:
`Failed to authenticate. You had ${error.failedAttempts} of ${lockoutSettings?.maxPasswordAttempts} password attempts.` +
(lockoutSettings?.maxPasswordAttempts &&
error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
(lockoutSettings?.maxPasswordAttempts && error.failedAttempts >= lockoutSettings?.maxPasswordAttempts
? " Contact your administrator to unlock your account"
: ""),
};
@@ -216,12 +201,11 @@ export async function sendPassword(command: UpdateSessionCommand) {
if (!loginSettings) {
loginSettings = await getLoginSettings({
serviceUrl,
organization:
command.organization ?? session.factors?.user?.organizationId,
organization: command.organization ?? session.factors?.user?.organizationId,
});
}
if (!session?.factors?.user?.id || !sessionCookie) {
if (!session?.factors?.user?.id) {
return { error: "Could not create session for user" };
}
@@ -251,12 +235,7 @@ export async function sendPassword(command: UpdateSessionCommand) {
}
// check to see if user was verified
const emailVerificationCheck = checkEmailVerification(
session,
humanUser,
command.organization,
command.requestId,
);
const emailVerificationCheck = checkEmailVerification(session, humanUser, command.organization, command.requestId);
if (emailVerificationCheck?.redirect) {
return emailVerificationCheck;
@@ -292,36 +271,49 @@ export async function sendPassword(command: UpdateSessionCommand) {
}
if (command.requestId && session.id) {
const nextUrl = await getNextUrl(
// OIDC/SAML flow - use completeFlowOrGetUrl for proper handling
console.log("Password auth: OIDC/SAML flow with requestId:", command.requestId, "sessionId:", session.id);
const result = await completeFlowOrGetUrl(
{
sessionId: session.id,
requestId: command.requestId,
organization:
command.organization ?? session.factors?.user?.organizationId,
organization: command.organization ?? session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
console.log("Password auth: OIDC/SAML flow result:", result);
return { redirect: nextUrl };
// Safety net - ensure we always return a valid object
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
console.error("Password auth: Invalid result from completeFlowOrGetUrl (OIDC/SAML):", result);
return { error: "Authentication completed but navigation failed" };
}
return result;
}
const url = await getNextUrl(
// Regular flow (no requestId) - return URL for client-side navigation
console.log("Password auth: Regular flow with loginName:", session.factors.user.loginName);
const result = await completeFlowOrGetUrl(
{
loginName: session.factors.user.loginName,
organization: session.factors?.user?.organizationId,
},
loginSettings?.defaultRedirectUri,
);
console.log("Password auth: Regular flow result:", result);
return { redirect: url };
// Safety net - ensure we always return a valid object
if (!result || typeof result !== "object" || (!("redirect" in result) && !("error" in result))) {
console.error("Password auth: Invalid result from completeFlowOrGetUrl:", result);
return { error: "Authentication completed but navigation failed" };
}
return result;
}
// this function lets users with code set a password or users with valid User Verification Check
export async function changePassword(command: {
code?: string;
userId: string;
password: string;
}) {
export async function changePassword(command: { code?: string; userId: string; password: string }) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
@@ -350,15 +342,12 @@ export async function changePassword(command: {
// if the user has no authmethods set, we need to check if the user was verified
if (authmethods.authMethodTypes.length !== 0) {
return {
error:
"You have to provide a code or have a valid User Verification Check",
error: "You have to provide a code or have a valid User Verification Check",
};
}
// check if a verification was done earlier
const hasValidUserVerificationCheck = await checkUserVerification(
user.userId,
);
const hasValidUserVerificationCheck = await checkUserVerification(user.userId);
if (!hasValidUserVerificationCheck) {
return { error: "User Verification Check has to be done" };
@@ -378,10 +367,7 @@ type CheckSessionAndSetPasswordCommand = {
password: string;
};
export async function checkSessionAndSetPassword({
sessionId,
password,
}: CheckSessionAndSetPasswordCommand) {
export async function checkSessionAndSetPassword({ sessionId, password }: CheckSessionAndSetPasswordCommand) {
const _headers = await headers();
const { serviceUrl } = getServiceUrlFromHeaders(_headers);
@@ -421,18 +407,14 @@ export async function checkSessionAndSetPassword({
AuthenticationMethodType.U2F,
];
const hasNoMFAMethods = requiredAuthMethodsForForceMFA.every(
(method) => !authmethods.authMethodTypes.includes(method),
);
const hasNoMFAMethods = requiredAuthMethodsForForceMFA.every((method) => !authmethods.authMethodTypes.includes(method));
const loginSettings = await getLoginSettings({
serviceUrl,
organization: session.factors.user.organizationId,
});
const forceMfa = !!(
loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly
);
const forceMfa = !!(loginSettings?.forceMfa || loginSettings?.forceMfaLocalOnly);
// if the user has no MFA but MFA is enforced, we can set a password otherwise we use the token of the user
if (forceMfa && hasNoMFAMethods) {
@@ -454,10 +436,7 @@ export async function checkSessionAndSetPassword({
return createUserServiceClient(transportPromise);
};
const selfService = await myUserService(
serviceUrl,
`${sessionCookie.token}`,
);
const selfService = await myUserService(serviceUrl, `${sessionCookie.token}`);
return selfService
.setPassword(