OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(auth): an OAuth provider without a client secret cannot start a sign-in (#631)
Carl-Gerhard Lindesvärdf0cbd531da2d
diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.tsindex 0be5374d8..6639684c8 100644--- a/packages/core/src/modules/auth/auth.rpc.test.ts+++ b/packages/core/src/modules/auth/auth.rpc.test.ts@@ -18,19 +18,12 @@ const COOKIE_OPTIONS: CookieOptions = {// `TrpcContext.session` is never literally `null`, only its `userId` is.const EMPTY_SESSION = { session: null, user: null, userId: null };-/** Capture response cookies so failed sign-ins cannot silently mutate auth state. */-async function anonCallerWithHeaders(config = testCoreConfig()) {+async function anonCaller(config = testCoreConfig()) {const { ctx } = stubHttpCtx({ config }, EMPTY_SESSION);- const responseHeaders = new Headers();- const trpcCtx = await makeTrpcContext(ctx, responseHeaders, {+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {cookieOptions: COOKIE_OPTIONS,});- return { caller: authRouter.createCaller(trpcCtx), responseHeaders };-}--/** Use the same anonymous context for RPC cases that do not inspect cookies. */-async function anonCaller(config = testCoreConfig()) {- return (await anonCallerWithHeaders(config)).caller;+ return authRouter.createCaller(trpcCtx);}test('providers reports which OAuth features are configured, as booleans only', async () => {@@ -72,7 +65,7 @@ test('providers reports which OAuth features are configured, as booleans only',expect(JSON.stringify(providers)).not.toContain('secret');});-test('incomplete OAuth credentials hide the provider and reject sign-in', async () => {+test('incomplete OAuth credentials hide the provider', async () => {for (const provider of ['github', 'google'] as const) {for (const missing of ['clientId',@@ -86,12 +79,9 @@ test('incomplete OAuth credentials hide the provider and reject sign-in', asyncredirectUri: `https://api.example.com/oauth/${provider}/callback`,};config.auth[provider][missing] = '';- const { caller, responseHeaders } = await anonCallerWithHeaders(config);- expect((await caller.providers())[provider]).toBe(false);- await expect(caller.signInOAuth({ provider })).rejects.toMatchObject({- code: 'BAD_REQUEST',- });- expect(responseHeaders.getSetCookie()).toEqual([]);+ expect((await (await anonCaller(config)).providers())[provider]).toBe(+ false+ );}}});diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 5a7f2f44e..00fe88c4e 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -28,6 +28,7 @@ import {} from './src/better-auth';import { deleteSessionTokenCookie } from './src/cookie';import { parseCookieDomain } from './src/cookie-domain';+import { isOAuthClientConfigured } from './src/oauth';import { hashPassword, verifyPasswordHash } from './src/password';import { decodeSessionToken, hashSessionToken } from './src/token';@@ -245,15 +246,9 @@ export function getConfiguredProviders(): ConfiguredProviders {const { google, github, googleGsc, devLogin } = config.auth;return {- google: Boolean(- google.clientId && google.clientSecret && google.redirectUri- ),- github: Boolean(- github.clientId && github.clientSecret && github.redirectUri- ),- gsc: Boolean(- googleGsc.clientId && googleGsc.clientSecret && googleGsc.redirectUri- ),+ google: isOAuthClientConfigured(google),+ github: isOAuthClientConfigured(github),+ gsc: isOAuthClientConfigured(googleGsc),devLogin: devLogin !== undefined,};}diff --git a/packages/core/src/modules/auth/src/better-auth.test.ts b/packages/core/src/modules/auth/src/better-auth.test.tsindex 3a368e39a..f4a113327 100644--- a/packages/core/src/modules/auth/src/better-auth.test.ts+++ b/packages/core/src/modules/auth/src/better-auth.test.ts@@ -508,6 +508,18 @@ test('an unverified Google email cannot sign up', async () => {expect(await deps.db.user.findUnique({ where: { email } })).toBeNull();});+test('a provider missing any credential cannot start a sign-in', async () => {+ for (const missing of ['clientId', 'clientSecret', 'redirectUri'] as const) {+ const google = { ...GOOGLE, [missing]: '' };+ const start = await call(authWith({ google }), '/sign-in/social', {+ provider: 'google',+ callbackURL: DASHBOARD_URL,+ });+ expect(start.status).toBe(404);+ expect(cookieNames(start)).toEqual([]);+ }+});+test('GitHub asks only for the scope users already granted', async () => {const github = {clientId: 'github-client',diff --git a/packages/core/src/modules/auth/src/better-auth.ts b/packages/core/src/modules/auth/src/better-auth.tsindex d29480e60..380546e4a 100644--- a/packages/core/src/modules/auth/src/better-auth.ts+++ b/packages/core/src/modules/auth/src/better-auth.ts@@ -22,6 +22,7 @@ import type { ISetCookie } from '../../../shared/cookie';import { connectUserToOrganization } from '../../organization/organization.service';import { INVITE_HEADER } from '../auth.constants';import { cookieOptions } from './constants';+import { isOAuthClientConfigured } from './oauth';import { hashPassword, verifyPasswordHash } from './password';import { getIsRegistrationAllowed } from './registration';import { generateSessionToken } from './token';@@ -227,24 +228,22 @@ function socialProviders(config: CoreConfig) {}),};return {- ...(google.clientId &&- google.redirectUri && {- google: {- ...googleOptions,- getUserInfo: requireVerifiedEmail(- googleProvider(googleOptions).getUserInfo- ),- },- }),- ...(github.clientId &&- github.redirectUri && {- github: {- ...githubOptions,- getUserInfo: requireVerifiedEmail(- githubProvider(githubOptions).getUserInfo- ),- },- }),+ ...(isOAuthClientConfigured(google) && {+ google: {+ ...googleOptions,+ getUserInfo: requireVerifiedEmail(+ googleProvider(googleOptions).getUserInfo+ ),+ },+ }),+ ...(isOAuthClientConfigured(github) && {+ github: {+ ...githubOptions,+ getUserInfo: requireVerifiedEmail(+ githubProvider(githubOptions).getUserInfo+ ),+ },+ }),};}diff --git a/packages/core/src/modules/auth/src/oauth.ts b/packages/core/src/modules/auth/src/oauth.tsindex 24ba87c67..7f454c86f 100644--- a/packages/core/src/modules/auth/src/oauth.ts+++ b/packages/core/src/modules/auth/src/oauth.ts@@ -1,5 +1,5 @@import * as Arctic from 'arctic';-import type { CoreConfig } from '../../../config';+import type { CoreConfig, OAuthClientConfig } from '../../../config';export type { OAuth2Tokens } from 'arctic';// Re-exported from source: `Arctic` is also used below, so `export { Arctic }`@@ -11,3 +11,8 @@ export function googleGscClient(config: CoreConfig): Arctic.Google {const { clientId, clientSecret, redirectUri } = config.auth.googleGsc;return new Arctic.Google(clientId, clientSecret, redirectUri);}++/** A client missing any credential cannot complete a sign-in, so it counts as absent. */+export function isOAuthClientConfigured(client: OAuthClientConfig): boolean {+ return Boolean(client.clientId && client.clientSecret && client.redirectUri);+}