mirror of
https://github.com/andwati/zitadel.git
synced 2026-11-26 14:28:46 +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:
+22
-48
@@ -5,9 +5,7 @@ import { create } from "@zitadel/client";
|
||||
import { CreateResponseRequestSchema } from "@zitadel/proto/zitadel/saml/v2/saml_service_pb";
|
||||
import { Session } from "@zitadel/proto/zitadel/session/v2/session_pb";
|
||||
import { cookies } from "next/headers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { constructUrl } from "./service-url";
|
||||
import { isSessionValid } from "./session";
|
||||
|
||||
type LoginWithSAMLAndSession = {
|
||||
@@ -16,7 +14,6 @@ type LoginWithSAMLAndSession = {
|
||||
sessionId: string;
|
||||
sessions: Session[];
|
||||
sessionCookies: Cookie[];
|
||||
request: NextRequest;
|
||||
};
|
||||
|
||||
export async function getSAMLFormUID() {
|
||||
@@ -30,15 +27,11 @@ export async function setSAMLFormCookie(value: string): Promise<string> {
|
||||
try {
|
||||
// Check cookie size limits (typical limit is 4KB)
|
||||
if (value.length > 4000) {
|
||||
console.warn(
|
||||
`SAML form cookie value is large (${value.length} characters), may exceed browser limits`,
|
||||
);
|
||||
console.warn(`SAML form cookie value is large (${value.length} characters), may exceed browser limits`);
|
||||
}
|
||||
|
||||
// Log the attempt
|
||||
console.log(
|
||||
`Setting SAML form cookie with uid: ${uid}, value length: ${value.length}`,
|
||||
);
|
||||
console.log(`Setting SAML form cookie with uid: ${uid}, value length: ${value.length}`);
|
||||
|
||||
await cookiesList.set({
|
||||
name: uid,
|
||||
@@ -61,9 +54,7 @@ export async function setSAMLFormCookie(value: string): Promise<string> {
|
||||
valueLength: value.length,
|
||||
uid,
|
||||
});
|
||||
throw new Error(
|
||||
`Failed to set SAML form cookie: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
throw new Error(`Failed to set SAML form cookie: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +74,7 @@ export async function getSAMLFormCookie(uid: string): Promise<string | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Successfully retrieved SAML form cookie for uid: ${uid}, value length: ${cookie.value.length}`,
|
||||
);
|
||||
console.log(`Successfully retrieved SAML form cookie for uid: ${uid}, value length: ${cookie.value.length}`);
|
||||
return cookie.value;
|
||||
} catch (error) {
|
||||
console.error(`Error retrieving SAML form cookie for uid: ${uid}`, error);
|
||||
@@ -99,11 +88,8 @@ export async function loginWithSAMLAndSession({
|
||||
sessionId,
|
||||
sessions,
|
||||
sessionCookies,
|
||||
request,
|
||||
}: LoginWithSAMLAndSession) {
|
||||
console.log(
|
||||
`Login with session: ${sessionId} and samlRequest: ${samlRequest}`,
|
||||
);
|
||||
}: LoginWithSAMLAndSession): Promise<{ error: string } | { redirect: string }> {
|
||||
console.log(`Login with session: ${sessionId} and samlRequest: ${samlRequest}`);
|
||||
|
||||
const selectedSession = sessions.find((s) => s.id === sessionId);
|
||||
|
||||
@@ -129,14 +115,11 @@ export async function loginWithSAMLAndSession({
|
||||
const res = await sendLoginname(command);
|
||||
|
||||
if (res && "redirect" in res && res?.redirect) {
|
||||
const absoluteUrl = constructUrl(request, res.redirect);
|
||||
return NextResponse.redirect(absoluteUrl.toString());
|
||||
return { redirect: res.redirect };
|
||||
}
|
||||
}
|
||||
|
||||
const cookie = sessionCookies.find(
|
||||
(cookie) => cookie.id === selectedSession?.id,
|
||||
);
|
||||
const cookie = sessionCookies.find((cookie) => cookie.id === selectedSession?.id);
|
||||
|
||||
if (cookie && cookie.id && cookie.token) {
|
||||
const session = {
|
||||
@@ -157,50 +140,41 @@ export async function loginWithSAMLAndSession({
|
||||
}),
|
||||
});
|
||||
if (url) {
|
||||
return NextResponse.redirect(url);
|
||||
return { redirect: url };
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: "An error occurred!" },
|
||||
{ status: 500 },
|
||||
);
|
||||
return { error: "An error occurred!" };
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// handle already handled gracefully as these could come up if old emails with requestId are used (reset password, register emails etc.)
|
||||
console.error(error);
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"code" in error &&
|
||||
error?.code === 9
|
||||
) {
|
||||
|
||||
if (error && typeof error === "object" && "code" in error && error?.code === 9) {
|
||||
const loginSettings = await getLoginSettings({
|
||||
serviceUrl,
|
||||
organization: selectedSession.factors?.user?.organizationId,
|
||||
});
|
||||
|
||||
if (loginSettings?.defaultRedirectUri) {
|
||||
return NextResponse.redirect(loginSettings.defaultRedirectUri);
|
||||
return { redirect: loginSettings.defaultRedirectUri };
|
||||
}
|
||||
|
||||
const signedinUrl = constructUrl(request, "/signedin");
|
||||
const signedinUrl = "/signedin";
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (selectedSession.factors?.user?.loginName) {
|
||||
signedinUrl.searchParams.set(
|
||||
"loginName",
|
||||
selectedSession.factors?.user?.loginName,
|
||||
);
|
||||
params.append("loginName", selectedSession.factors?.user?.loginName);
|
||||
}
|
||||
if (selectedSession.factors?.user?.organizationId) {
|
||||
signedinUrl.searchParams.set(
|
||||
"organization",
|
||||
selectedSession.factors?.user?.organizationId,
|
||||
);
|
||||
params.append("organization", selectedSession.factors?.user?.organizationId);
|
||||
}
|
||||
return NextResponse.redirect(signedinUrl);
|
||||
return { redirect: signedinUrl + "?" + params.toString() };
|
||||
} else {
|
||||
return NextResponse.json({ error }, { status: 500 });
|
||||
return { error: "Unknown error occurred" };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no session found or no valid cookie, return error
|
||||
return { error: "Session not found or invalid" };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user