Beautiful Open-Source Form Builder
fix: complete OIDC account linking (#1220)
Julien Nahum3fdc3068e884
diff --git a/api/app/Http/Controllers/Auth/LoginController.php b/api/app/Http/Controllers/Auth/LoginController.phpindex c11cd9e26..c76fc0eaf 100644--- a/api/app/Http/Controllers/Auth/LoginController.php+++ b/api/app/Http/Controllers/Auth/LoginController.php@@ -2,6 +2,7 @@namespace App\Http\Controllers\Auth;+use App\Enterprise\Oidc\OidcLinkService;use App\Exceptions\VerifyEmailException;use App\Http\Controllers\Auth\Traits\ManagesJWT;use App\Http\Controllers\Controller;@@ -22,7 +23,7 @@ class LoginController extends Controller** @return void*/- public function __construct()+ public function __construct(private OidcLinkService $oidcLinkService){$this->middleware('guest')->except('logout');}@@ -40,7 +41,7 @@ class LoginController extends Controller->where('type', \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC)->exists();- if ($hasOidcConnection) {+ if ($hasOidcConnection && ! $this->canUsePasswordLoginToLinkOidcAccount($request)) {throw ValidationException::withMessages([$this->username() => ['Password-based login is disabled. Please use OIDC authentication.'],]);@@ -72,6 +73,30 @@ class LoginController extends Controllerreturn true;}+ /**+ * A valid, email-bound link token permits one password sign-in so an+ * existing account can be securely linked to its OIDC identity. The token+ * is still consumed by OidcLinkController after authentication succeeds.+ */+ protected function canUsePasswordLoginToLinkOidcAccount(Request $request): bool+ {+ $linkToken = (string) $request->input('oidc_link_token');+ if ($linkToken === '') {+ return false;+ }++ $payload = $this->oidcLinkService->getLinkToken($linkToken);+ $tokenEmail = $payload['email'] ?? null;+ if (! is_string($tokenEmail)) {+ return false;+ }++ return hash_equals(+ strtolower($tokenEmail),+ strtolower((string) $request->input($this->username()))+ );+ }+/*** Get the needed authorization credentials from the request.*diff --git a/api/tests/Feature/LoginTest.php b/api/tests/Feature/LoginTest.phpindex dff532f4e..d516be671 100644--- a/api/tests/Feature/LoginTest.php+++ b/api/tests/Feature/LoginTest.php@@ -1,6 +1,8 @@<?phpuse App\Models\User;+use App\Enterprise\Oidc\Models\IdentityConnection;+use App\Enterprise\Oidc\OidcLinkService;it('can login to Forms', function () {$user = User::factory()->create();@@ -53,9 +55,9 @@ it('cannot login if user is blocked', function () {it('blocks password login when OIDC force_login is enabled', function () {// Create an OIDC connection- \App\Enterprise\Oidc\Models\IdentityConnection::factory()->create([+ IdentityConnection::factory()->create(['enabled' => true,- 'type' => \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC,+ 'type' => IdentityConnection::TYPE_OIDC,]);// Enable force_login@@ -76,6 +78,56 @@ it('blocks password login when OIDC force_login is enabled', function () {config(['oidc.force_login' => false]);});+it('allows an existing account to sign in with a valid OIDC link token when force login is enabled', function () {+ $connection = IdentityConnection::factory()->create([+ 'enabled' => true,+ 'type' => IdentityConnection::TYPE_OIDC,+ ]);+ config(['oidc.force_login' => true]);++ $user = User::factory()->create();+ $linkToken = app(OidcLinkService::class)->createLinkToken(+ connectionId: $connection->id,+ subject: 'existing-account-subject',+ email: $user->email,+ claims: ['email' => $user->email],+ );++ $this->postJson('/login', [+ 'email' => $user->email,+ 'password' => 'Abcd@1234',+ 'oidc_link_token' => $linkToken,+ ])->assertSuccessful();++ config(['oidc.force_login' => false]);+});++it('does not allow a link token for a different account to bypass forced OIDC login', function () {+ $connection = IdentityConnection::factory()->create([+ 'enabled' => true,+ 'type' => IdentityConnection::TYPE_OIDC,+ ]);+ config(['oidc.force_login' => true]);++ $user = User::factory()->create();+ $linkToken = app(OidcLinkService::class)->createLinkToken(+ connectionId: $connection->id,+ subject: 'different-account-subject',+ email: '[email protected]',+ claims: ['email' => '[email protected]'],+ );++ $this->postJson('/login', [+ 'email' => $user->email,+ 'password' => 'Abcd@1234',+ 'oidc_link_token' => $linkToken,+ ])+ ->assertStatus(422)+ ->assertJsonValidationErrors(['email' => 'Password-based login is disabled. Please use OIDC authentication.']);++ config(['oidc.force_login' => false]);+});+it('allows password login when OIDC force_login is enabled but no connections exist', function () {// Enable force_login but no OIDC connectionsconfig(['oidc.force_login' => true]);diff --git a/client/api/oidc.js b/client/api/oidc.jsindex a21ab6181..63cc7b5bb 100644--- a/client/api/oidc.js+++ b/client/api/oidc.js@@ -36,9 +36,11 @@ export const oidcApi = {headers['X-OIDC-State-Verifier'] = stateVerifier}- // Use GET with Accept: application/json header to get JSON response+ // Authorization codes are single-use. Never let the fetch client replay+ // this callback after an error response such as account-linking required.return apiService.get(url, {- headers+ headers,+ retry: false,})},diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vueindex adb8d3ecc..e82dba996 100644--- a/client/components/pages/auth/components/LoginForm.vue+++ b/client/components/pages/auth/components/LoginForm.vue@@ -27,6 +27,16 @@@blur="checkOidcOptions"/>+ <UAlert+ v-if="isLinkingExistingAccount"+ class="mt-3"+ icon="i-lucide-link"+ color="primary"+ variant="subtle"+ title="Link your existing account"+ description="Sign in once with your existing OpnForm password to link it to your SSO account."+ />+<UAlertv-if="isOidcSignIn && isOidcRateLimited"class="mt-3"@@ -153,7 +163,7 @@ const router = useRouter()const { login: loginMutationFactory } = useAuth()const authFlow = useAuthFlow()const { showTwoFactorModal, pendingAuthToken, handleTwoFactorVerified, handleTwoFactorCancel, handleTwoFactorError } = authFlow-const { completeLinkIfNeeded } = useOidcLinking()+const { linkToken, completeLinkIfNeeded } = useOidcLinking()// Feature flagsconst oidcAvailable = computed(() => useFeatureFlag('oidc.available', false))@@ -168,7 +178,8 @@ const form = useForm({const loginMutation = loginMutationFactory()const showForgotModal = ref(false)-const showPasswordField = ref(!oidcAvailable.value)+const isLinkingExistingAccount = computed(() => Boolean(linkToken.value))+const showPasswordField = ref(!oidcAvailable.value || isLinkingExistingAccount.value)const passwordInputRef = ref(null)const oidcRetryAfterSeconds = ref(0)let oidcRateLimitTimer = null@@ -223,6 +234,12 @@ watch(showPasswordField, async (newValue) => {}})+watch(linkToken, (newToken) => {+ if (newToken) {+ showPasswordField.value = true+ }+})+// LifecycleonMounted(() => {// Use the window message composable@@ -305,6 +322,12 @@ const login = () => {return}+ if (linkToken.value) {+ form.oidc_link_token = linkToken.value+ } else {+ delete form.oidc_link_token+ }+form.mutate(loginMutation).then(() => {// If 2FA modal is shown, don't redirect yet (handled in handleTwoFactorVerified)if (!showTwoFactorModal.value) {diff --git a/client/test/nuxt/oidc-link-flow.spec.ts b/client/test/nuxt/oidc-link-flow.spec.tsindex b9830a70b..eae91ce68 100644--- a/client/test/nuxt/oidc-link-flow.spec.ts+++ b/client/test/nuxt/oidc-link-flow.spec.ts@@ -12,6 +12,7 @@ const {clearOidcAutomaticRetrySpy,consumeOidcStateVerifierSpy,featureFlagValues,+ linkTokenValue,markOidcAutomaticRetrySpy,storeOidcStateVerifierSpy,} = vi.hoisted(() => ({@@ -22,6 +23,7 @@ const {clearOidcAutomaticRetrySpy: vi.fn(),consumeOidcStateVerifierSpy: vi.fn(() => null),featureFlagValues: {},+ linkTokenValue: { value: null },markOidcAutomaticRetrySpy: vi.fn(),storeOidcStateVerifierSpy: vi.fn(),}))@@ -65,7 +67,7 @@ vi.mock('~/composables/query/useAuth', () => ({vi.mock('~/composables/useOidcLinking', () => ({useOidcLinking: () => ({- linkToken: ref(null),+ linkToken: ref(linkTokenValue.value),startLink: startLinkSpy,clearLinkToken: vi.fn(),completeLinkIfNeeded: completeLinkIfNeededSpy,@@ -163,6 +165,7 @@ describe('OIDC link flow', () => {beforeEach(() => {vi.clearAllMocks()Object.keys(featureFlagValues).forEach((key) => delete featureFlagValues[key])+ linkTokenValue.value = nullcanAutomaticallyRetryOidcSignInSpy.mockReturnValue(true)})@@ -210,6 +213,7 @@ describe('OIDC link flow', () => {await flushPromises()expect(wrapper.text()).toContain('Link existing account')+ expect(oidcApi.callback).toHaveBeenCalledOnce()vi.useRealTimers()})@@ -479,4 +483,56 @@ describe('OIDC link flow', () => {expect(completeLinkIfNeededSpy).toHaveBeenCalled()})++ it('shows password sign-in for a valid account-linking request even when OIDC is forced', async () => {+ linkTokenValue.value = 'link-token-123'+ setupGlobals({}, {+ featureFlags: {+ 'oidc.available': true,+ 'oidc.forced': true,+ },+ })++ const wrapper = mount(LoginForm, {+ global: {+ stubs: {+ ForgotPasswordModal: true,+ TwoFactorVerificationModal: true,+ VForm: {+ template: '<form><slot /></form>',+ props: ['form'],+ },+ TextInput: {+ template: '<input :name="name" />',+ props: ['name'],+ },+ CheckboxInput: true,+ UAlert: {+ template: '<div class="alert">{{ title }} {{ description }}</div>',+ props: ['title', 'description'],+ },+ UButton: true,+ VTransition: {+ template: '<div><slot /></div>',+ },+ NuxtLink: true,+ ClientOnly: true,+ GoogleOneTap: true,+ },+ },+ })++ const vm = wrapper.vm as any+ vm.form.email = '[email protected]'+ vm.form.password = 'Abcd@1234'+ vm.form.mutate = vi.fn(() => Promise.resolve())++ vm.login()+ await flushPromises()++ expect(wrapper.text()).toContain('Link your existing account')+ expect(wrapper.find('input[name="password"]').exists()).toBe(true)+ expect(vm.form.oidc_link_token).toBe('link-token-123')+ expect(vm.form.mutate).toHaveBeenCalledOnce()+ })})diff --git a/client/test/unit/oidc-api.test.ts b/client/test/unit/oidc-api.test.tsnew file mode 100644index 000000000..56b323d51--- /dev/null+++ b/client/test/unit/oidc-api.test.ts@@ -0,0 +1,32 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const getSpy = vi.hoisted(() => vi.fn())++vi.mock('../../api/base.js', () => ({+ apiService: {+ get: getSpy,+ post: vi.fn(),+ patch: vi.fn(),+ delete: vi.fn(),+ },+}))++import { oidcApi } from '../../api/oidc.js'++describe('oidcApi callback', () => {+ beforeEach(() => {+ getSpy.mockReset()+ })++ it('disables retries because an authorization code can only be redeemed once', () => {+ oidcApi.callback('company-sso', { code: 'single-use-code', state: 'state-token' }, 'state-verifier')++ expect(getSpy).toHaveBeenCalledWith('/auth/company-sso/callback?code=single-use-code&state=state-token', {+ headers: {+ Accept: 'application/json',+ 'X-OIDC-State-Verifier': 'state-verifier',+ },+ retry: false,+ })+ })+})diff --git a/docs/configuration/oidc-sso.mdx b/docs/configuration/oidc-sso.mdxindex c6c365591..7e09c6c69 100644--- a/docs/configuration/oidc-sso.mdx+++ b/docs/configuration/oidc-sso.mdx@@ -203,6 +203,7 @@ When enabled:- Users attempting password login receive: "Password-based login is disabled. Please use OIDC authentication."- The login form automatically redirects users to their OIDC provider based on email domain- If `force_login` is enabled but no OIDC connections exist, password login remains available as a fallback+- A user who is securely linking a pre-existing OpnForm account may sign in with that account's password once. The temporary link request is bound to the same email address and expires after 15 minutes.### Use Cases@@ -310,11 +311,11 @@ In production, all OIDC redirects require HTTPS. Ensure your application is servOpnForm generates and validates an OIDC `state` value by default for login redirects. Callback requests without a valid, unexpired state are rejected to prevent login CSRF.-State validation can be disabled explicitly on an OIDC connection by setting `options.require_state` to `false`, but this is not recommended unless required for a legacy identity provider.+State validation can be disabled explicitly on an OIDC connection by setting `options.require_state` to `false`, but this is not recommended unless required for a legacy identity provider. Keep it enabled for Microsoft Entra ID and other standard OIDC providers.### Account Linking-For security, OpnForm prevents automatic linking of existing accounts. If a user with the same email already exists but isn't linked to the OIDC connection, authentication will fail with a message to contact the administrator.+For security, OpnForm prevents automatic linking of existing accounts. If a user with the same email already exists but is not linked to the OIDC connection, OpnForm asks that user to sign in once with their existing OpnForm password. It then links the SSO identity only when the temporary link request and authenticated account have the same email address. The link request expires after 15 minutes.### SSO-Only Accounts