Skip to content
Open
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
33 changes: 33 additions & 0 deletions apps/web/__tests__/unit/auth-options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ const CONTEXT: SsoAuthContext = {
},
};
const AUTHENTICATED_USER = { id: "authenticated-user", email: PROFILE.email };
const VERIFIED_GOOGLE_PROFILE = { email: PROFILE.email, email_verified: true };

function callbacksFor(options: NextAuthOptions) {
const signIn = options.callbacks?.signIn;
Expand Down Expand Up @@ -305,6 +306,33 @@ describe("authOptions", () => {
},
);

it("lets Google sign-in link an existing account with the same email", () => {
const google = authOptions().providers.find(
(provider) => provider.id === "google",
);
expect(
(google?.options as { allowDangerousEmailAccountLinking?: boolean })
?.allowDangerousEmailAccountLinking,
).toBe(true);
});

it("only accepts Google sign-ins whose email Google has verified", async () => {
const { signIn } = callbacksFor(authOptions());
const account: Account = {
provider: "google",
providerAccountId: "google-user",
type: "oauth",
};
for (const email_verified of [undefined, false, true]) {
const profile = { email: PROFILE.email, email_verified };
await expect(
signIn({ user: AUTHENTICATED_USER, account, profile }),
).resolves.toBe(
email_verified === true ? true : "/login?error=GoogleEmailUnverified",
);
}
});

describe("trusted-proxy authorize", () => {
type Authorize = (
credentials: Record<string, string> | undefined,
Expand Down Expand Up @@ -477,6 +505,7 @@ describe("authOptions", () => {
callbacks.signIn({
user: { id: "u1", email: "Anyone@Blocked.example" },
account: { provider: "google", providerAccountId: "g1", type: "oauth" },
profile: VERIFIED_GOOGLE_PROFILE,
}),
).resolves.toBe("/login?error=SignupBlocked");
await expect(
Expand All @@ -494,6 +523,7 @@ describe("authOptions", () => {
callbacks.signIn({
user: { id: "u3", email: "else@other.example" },
account: { provider: "google", providerAccountId: "g3", type: "oauth" },
profile: VERIFIED_GOOGLE_PROFILE,
}),
).resolves.toBe(true);
});
Expand Down Expand Up @@ -544,12 +574,14 @@ describe("authOptions", () => {
callbacks.signIn({
user: { id: "u1", email: "new@throwaway.example" },
account: { provider: "google", providerAccountId: "g1", type: "oauth" },
profile: VERIFIED_GOOGLE_PROFILE,
}),
).resolves.toBe("/login?error=DisposableEmail");
await expect(
callbacks.signIn({
user: { id: "u2", email: "person@company.example" },
account: { provider: "google", providerAccountId: "g2", type: "oauth" },
profile: VERIFIED_GOOGLE_PROFILE,
}),
).resolves.toBe(true);
mocks.disposableSignup.mockReset();
Expand All @@ -574,6 +606,7 @@ describe("authOptions", () => {
callbacks.signIn({
user: { id: "u1", email: "anyone@blocked.example" },
account: { provider: "google", providerAccountId: "g1", type: "oauth" },
profile: VERIFIED_GOOGLE_PROFILE,
}),
).resolves.toBe(true);
});
Expand Down
47 changes: 47 additions & 0 deletions apps/web/__tests__/unit/sso-auth-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,3 +655,50 @@ describe("SSO auth request boundary", () => {
expect(response.headers.get("set-cookie")).not.toContain("cap-sso-intent");
});
});

describe("Google sign-in refused for an unverified email", () => {
const refused = () =>
mocks.nextAuth.mockResolvedValueOnce(
new Response(null, {
status: 302,
headers: {
location: `${env.WEB_URL}/login?error=GoogleEmailUnverified`,
},
}),
);

it("keeps the return path so the email-code fallback can finish the flow", async () => {
refused();
const { request, context } = makeRequest({
action: "callback",
provider: "google",
intent: null,
callbackCookie: `${env.WEB_URL}/s/video123?t=42`,
});

const location = new URL(
(await GET(request, context)).headers.get("location") ?? "",
);

expect(location.pathname).toBe("/login");
expect(location.searchParams.get("error")).toBe("GoogleEmailUnverified");
expect(location.searchParams.get("next")).toBe("/s/video123?t=42");
});

it("drops a return path that leaves the Cap origin", async () => {
refused();
const { request, context } = makeRequest({
action: "callback",
provider: "google",
intent: null,
callbackCookie: "https://attacker.example/steal",
});

const location = new URL(
(await GET(request, context)).headers.get("location") ?? "",
);

expect(location.searchParams.get("error")).toBe("GoogleEmailUnverified");
expect(location.searchParams.has("next")).toBe(false);
});
});
4 changes: 4 additions & 0 deletions apps/web/app/(org)/login/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ export function LoginForm() {
} else if (error === "SsoMissingProfileAttributes") {
setShowOrgInput(true);
return;
} else if (error === "GoogleEmailUnverified") {
return toast.error(
"Your Google account's email isn't verified. Verify it with Google or sign in with an email code.",
);
} else if (error === "SignupBlocked") {
return;
} else if (error === "DisposableEmail") {
Expand Down
30 changes: 29 additions & 1 deletion apps/web/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,30 @@ function withSignInEmailIdentifier(request: NextRequest, nextauth: string[]) {
return new NextRequest(url, request);
}

// The signIn callback can't see the request, so a refused Google sign-in loses
// the destination kept in the callback-url cookie. Without it, the email-code
// fallback lands on /dashboard and a mobile sign-in never hands off its session.
function keepGoogleErrorReturnPath(request: NextRequest, response: Response) {
const location = response.headers.get("location");
if (!location) return;
const webUrl = serverEnv().WEB_URL;
const redirectUrl = new URL(location, webUrl);
if (
redirectUrl.origin !== new URL(webUrl).origin ||
redirectUrl.pathname !== "/login" ||
redirectUrl.searchParams.get("error") !== "GoogleEmailUnverified" ||
redirectUrl.searchParams.has("next")
)
return;
const returnTo = getSafeNextPath(
request.cookies.get("next-auth.callback-url")?.value,
webUrl,
);
if (returnTo === "/dashboard") return;
redirectUrl.searchParams.set("next", returnTo);
response.headers.set("location", redirectUrl.toString());
}

async function handler(
request: NextRequest,
context: { params: Promise<{ nextauth: string[] }> },
Expand All @@ -137,11 +161,15 @@ async function handler(
const limitedResponse = await emailCodeLimitResponse(request, nextauth);
if (limitedResponse) return limitedResponse;
if (nextauth[1] !== "workos") {
return NextAuth(
const response: Response = await NextAuth(
withSignInEmailIdentifier(request, nextauth),
context,
authOptions(),
);
if (nextauth[0] === "callback" && nextauth[1] === "google") {
keepGoogleErrorReturnPath(request, response);
}
return response;
}
const env = serverEnv();
const cookie = ssoIntentCookie(new URL(env.WEB_URL).protocol === "https:");
Expand Down
10 changes: 10 additions & 0 deletions packages/database/auth/auth-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {
prompt: "select_account",
},
},
// Lets people who first signed up with an email code use Google
// with the same address. Gated on Google's `email_verified` in the
// signIn callback, like OIDC.
allowDangerousEmailAccountLinking: true,
}),
...(serverEnv().WORKOS_CLIENT_ID && serverEnv().WORKOS_API_KEY
? [
Expand Down Expand Up @@ -399,6 +403,12 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {
return "/login?error=OidcEmailUnverified";
}
}
if (account?.provider === "google") {
const claims = profile as { email_verified?: boolean } | undefined;
if (claims?.email_verified !== true) {
return "/login?error=GoogleEmailUnverified";
Comment thread
hjescalona marked this conversation as resolved.
Resolved
}
}
if (account?.provider === "workos") {
validatedSsoIdentity = null;
try {
Expand Down