Beautiful Open-Source Form Builder
Improve self-hosted OIDC sign-in recovery (#1204)
Julien Nahum05cd7f7e5a8e
diff --git a/api/.env.example b/api/.env.exampleindex 71811de97..3e2549af9 100644--- a/api/.env.example+++ b/api/.env.example@@ -60,6 +60,15 @@ JWT_SKIP_IP_UA_VALIDATION=falsePUBLIC_UPLOADS_RATE_LIMIT_PER_MINUTE=30PUBLIC_UPLOADS_RATE_LIMIT_PER_HOUR=300+# OIDC self-hosted sign-in+OIDC_FORCE_LOGIN=false+# Maximum OIDC sign-in initiations per client IP and connection per minute+OIDC_RATE_LIMIT_PER_MINUTE=100++# Comma-separated IP addresses or CIDRs for a reverse proxy in front of OpnForm.+# Leave empty for a direct Docker deployment. Never use *.+TRUSTED_PROXIES=+STRIPE_KEY=STRIPE_SECRET=diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.phpindex e4c6e26ff..5c04774e1 100644--- a/api/app/Providers/RouteServiceProvider.php+++ b/api/app/Providers/RouteServiceProvider.php@@ -51,6 +51,24 @@ class RouteServiceProvider extends ServiceProviderreturn Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());});+ RateLimiter::for('oidc-init', function (Request $request) {+ $connection = (string) ($request->route('slug') ?? 'unknown');+ $key = hash('sha256', $request->ip() . '|' . $connection);+ $limit = max(1, (int) config('oidc.rate_limit_per_minute', 30));++ return Limit::perMinute($limit)+ ->by('oidc-init:' . $key)+ ->response(function (Request $request, array $headers) {+ $retryAfter = max(1, (int) ($headers['Retry-After'] ?? 60));++ return response()->json([+ 'error' => 'oidc_rate_limited',+ 'message' => "Too many sign-in requests. Please try again in {$retryAfter} seconds.",+ 'retry_after' => $retryAfter,+ ], 429, $headers);+ });+ });+// Rate limit for summary endpoints: 30 requests per minute per userRateLimiter::for('summary', function (Request $request) {return Limit::perMinute(30)->by($request->user()?->id ?: $request->ip());diff --git a/api/config/oidc.php b/api/config/oidc.phpindex 4b6ff272d..b7f3e7b61 100644--- a/api/config/oidc.php+++ b/api/config/oidc.php@@ -22,6 +22,20 @@ return [*/'force_login' => env('OIDC_FORCE_LOGIN', false),+ /*+ |--------------------------------------------------------------------------+ | OIDC Sign-in Initiation Rate Limit+ |--------------------------------------------------------------------------+ |+ | Limits how often one client IP address can start a sign-in for a given+ | connection. When OpnForm is behind a reverse proxy, configure+ | TRUSTED_PROXIES so Laravel can determine the real client IP safely. The+ | callback is protected by its single-use state verifier and deliberately+ | does not share this bucket.+ |+ */+ 'rate_limit_per_minute' => env('OIDC_RATE_LIMIT_PER_MINUTE', 100),+/*|--------------------------------------------------------------------------| Blocked Email Providersdiff --git a/api/config/trustedproxy.php b/api/config/trustedproxy.phpnew file mode 100644index 000000000..e9cffe6ee--- /dev/null+++ b/api/config/trustedproxy.php@@ -0,0 +1,17 @@+<?php++return [+ /*+ |--------------------------------------------------------------------------+ | Trusted Reverse Proxies+ |--------------------------------------------------------------------------+ |+ | Comma-separated IP addresses or CIDR ranges for reverse proxies in front+ | of OpnForm. Laravel only accepts X-Forwarded-* headers when the direct+ | caller is in this list, so clients cannot spoof their IP address.+ |+ | Leave this empty when users connect directly to the Docker ingress.+ |+ */+ 'proxies' => env('TRUSTED_PROXIES'),+];diff --git a/api/routes/api.php b/api/routes/api.phpindex dc074564e..0cff3c2de 100644--- a/api/routes/api.php+++ b/api/routes/api.php@@ -423,8 +423,16 @@ Route::prefix('oauth')->name('oauth.')->group(function () {/** OIDC SSO routes (public - authentication handled in controller)*/-Route::prefix('auth')->name('sso.')->middleware('throttle:10,1')->group(function () {- Route::post('/{slug}/redirect', [\App\Http\Controllers\Auth\SsoController::class, 'redirect'])->name('redirect');+Route::prefix('auth')->name('sso.')->group(function () {+ // Starting an authorization request allocates server-side state. Keep this+ // separate from the callback so a stale callback cannot lock out a user.+ Route::post('/{slug}/redirect', [\App\Http\Controllers\Auth\SsoController::class, 'redirect'])+ ->middleware('throttle:oidc-init')+ ->name('redirect');++ // The callback remains behind the API limit. With the default connection+ // settings, it validates a single-use state and verifier before exchanging+ // the authorization code, so it must not share the smaller bucket above.Route::get('/{slug}/callback', [\App\Http\Controllers\Auth\SsoController::class, 'callback'])->name('callback');});diff --git a/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.phpindex c620fbbf4..cc0d06610 100644--- a/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php+++ b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php@@ -2,6 +2,7 @@use App\Enterprise\Oidc\Models\IdentityConnection;use App\Models\User;+use Illuminate\Routing\Middleware\ThrottleRequests;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\URL;use Tests\TestHelpers;@@ -196,6 +197,89 @@ describe('SsoController - Redirect', function () {});});+describe('SsoController - Rate limiting', function () {+ it('limits OIDC sign-in initiation per connection and returns the retry delay', function () {+ config(['oidc.rate_limit_per_minute' => 2]);+ $this->withMiddleware(ThrottleRequests::class);+ $this->withServerVariables(['REMOTE_ADDR' => '192.0.2.20']);++ $this->postJson('/auth/company-sso/redirect')->assertNotFound();+ $this->postJson('/auth/company-sso/redirect')->assertNotFound();++ $response = $this->postJson('/auth/company-sso/redirect');++ $retryAfter = (int) $response->headers->get('Retry-After');+ $response->assertStatus(429)+ ->assertJson([+ 'error' => 'oidc_rate_limited',+ 'retry_after' => $retryAfter,+ ]);++ expect($retryAfter)->toBeGreaterThan(0)+ ->and($response->json('message'))->toContain("{$retryAfter} seconds");++ $this->postJson('/auth/another-company-sso/redirect')->assertNotFound();+ });++ it('does not put callbacks in the OIDC initiation bucket', function () {+ config(['oidc.rate_limit_per_minute' => 1]);+ $this->withMiddleware(ThrottleRequests::class);+ $this->withServerVariables(['REMOTE_ADDR' => '192.0.2.21']);++ $this->getJson('/auth/company-sso/callback')->assertNotFound();+ $this->getJson('/auth/company-sso/callback')->assertNotFound();++ $this->postJson('/auth/company-sso/redirect')->assertNotFound();+ $this->postJson('/auth/company-sso/redirect')->assertStatus(429);+ });++ it('uses the forwarded client IP when the reverse proxy is explicitly trusted', function () {+ config([+ 'oidc.rate_limit_per_minute' => 1,+ 'trustedproxy.proxies' => '192.0.2.30',+ ]);+ $this->withMiddleware(ThrottleRequests::class);++ $this->withServerVariables([+ 'REMOTE_ADDR' => '192.0.2.30',+ 'HTTP_X_FORWARDED_FOR' => '198.51.100.30',+ ]);+ $this->postJson('/auth/company-sso/redirect')->assertNotFound();++ $this->withServerVariables([+ 'REMOTE_ADDR' => '192.0.2.30',+ 'HTTP_X_FORWARDED_FOR' => '198.51.100.31',+ ]);+ $this->postJson('/auth/company-sso/redirect')->assertNotFound();++ $this->withServerVariables([+ 'REMOTE_ADDR' => '192.0.2.30',+ 'HTTP_X_FORWARDED_FOR' => '198.51.100.30',+ ]);+ $this->postJson('/auth/company-sso/redirect')->assertStatus(429);+ });++ it('does not trust a forwarded client IP from an untrusted sender', function () {+ config([+ 'oidc.rate_limit_per_minute' => 1,+ 'trustedproxy.proxies' => '192.0.2.40',+ ]);+ $this->withMiddleware(ThrottleRequests::class);++ $this->withServerVariables([+ 'REMOTE_ADDR' => '192.0.2.41',+ 'HTTP_X_FORWARDED_FOR' => '198.51.100.40',+ ]);+ $this->postJson('/auth/company-sso/redirect')->assertNotFound();++ $this->withServerVariables([+ 'REMOTE_ADDR' => '192.0.2.41',+ 'HTTP_X_FORWARDED_FOR' => '198.51.100.41',+ ]);+ $this->postJson('/auth/company-sso/redirect')->assertStatus(429);+ });+});+describe('SsoController - Get Options For Email', function () {it('returns redirect action when connection exists for domain', function () {$connection = IdentityConnection::factory()->create([diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vueindex d938e7564..adb8d3ecc 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="isOidcSignIn && isOidcRateLimited"+ class="mt-3"+ icon="i-lucide-clock-3"+ color="warning"+ variant="subtle"+ title="Please wait before trying again"+ :description="oidcRateLimitMessage(oidcRetryAfterSeconds)"+ />+<!-- Password - hidden if OIDC available and not forced to show --><VTransition name="fadeHeight"><text-input@@ -67,8 +77,9 @@blocksize="lg":loading="form.busy"+ :disabled="form.busy || (isOidcSignIn && isOidcRateLimited)"type="submit"- :label="oidcAvailable && !showPasswordField ? 'Continue' : 'Log in to continue'"+ :label="submitButtonLabel"/><UButton@@ -117,6 +128,11 @@import ForgotPasswordModal from "../ForgotPasswordModal.vue"import GoogleOneTap from "~/components/vendor/GoogleOneTap.vue"import { WindowMessageTypes } from "~/composables/useWindowMessage"+import {+ getOidcRetryAfterSeconds,+ isOidcRateLimitedError,+ oidcRateLimitMessage,+} from "~/lib/oidc/rate-limit"import { clearOidcAutomaticRetry, storeOidcStateVerifier } from "~/lib/oidc/state-verifier"// Props@@ -152,8 +168,48 @@ const form = useForm({const loginMutation = loginMutationFactory()const showForgotModal = ref(false)-const showPasswordField = ref(!oidcAvailable.value || oidcForced.value)+const showPasswordField = ref(!oidcAvailable.value)const passwordInputRef = ref(null)+const oidcRetryAfterSeconds = ref(0)+let oidcRateLimitTimer = null++const isOidcSignIn = computed(() => oidcAvailable.value && !showPasswordField.value)+const isOidcRateLimited = computed(() => oidcRetryAfterSeconds.value > 0)+const submitButtonLabel = computed(() => {+ if (isOidcSignIn.value && isOidcRateLimited.value) {+ return `Try again in ${oidcRetryAfterSeconds.value}s`+ }++ return isOidcSignIn.value ? 'Continue' : 'Log in to continue'+})++const clearOidcRateLimitTimer = () => {+ if (oidcRateLimitTimer) {+ clearInterval(oidcRateLimitTimer)+ oidcRateLimitTimer = null+ }+}++const startOidcRateLimitTimer = (error) => {+ oidcRetryAfterSeconds.value = getOidcRetryAfterSeconds(error)+ clearOidcRateLimitTimer()++ oidcRateLimitTimer = setInterval(() => {+ oidcRetryAfterSeconds.value -= 1++ if (oidcRetryAfterSeconds.value <= 0) {+ oidcRetryAfterSeconds.value = 0+ clearOidcRateLimitTimer()+ }+ }, 1000)+}++const handleOidcRateLimitError = (error) => {+ if (!isOidcRateLimitedError(error)) return false++ startOidcRateLimitTimer(error)+ return true+}// Watch for password field visibility to focus itwatch(showPasswordField, async (newValue) => {@@ -178,9 +234,13 @@ onMounted(() => {})})+onBeforeUnmount(() => {+ clearOidcRateLimitTimer()+})+// Methodsconst checkOidcOptions = async () => {- if (!oidcAvailable.value || !form.email || form.busy) {+ if (!oidcAvailable.value || !form.email || form.busy || isOidcRateLimited.value) {return}@@ -200,14 +260,16 @@ const checkOidcOptions = async () => {} else if (redirectResponse.error) {// Handle error from redirect endpointuseAlert().error(redirectResponse.error || 'Failed to initiate OIDC authentication')- showPasswordField.value = true+ if (!oidcForced.value) showPasswordField.value = truereturn}} catch (error) {+ if (handleOidcRateLimitError(error)) return+// Handle network or server errorsconst errorMessage = error.response?._data?.error || error.response?._data?.message || 'Failed to initiate OIDC authentication'useAlert().error(errorMessage)- showPasswordField.value = true+ if (!oidcForced.value) showPasswordField.value = truereturn}} else if (response.action === 'blocked') {@@ -216,13 +278,15 @@ const checkOidcOptions = async () => {return} else {// Fallback to password login- showPasswordField.value = true+ if (!oidcForced.value) showPasswordField.value = true}}).catch((error) => {+ if (handleOidcRateLimitError(error)) return+// Form automatically handles 422 validation errors (invalid email, etc.)// Only show password field as fallback for non-validation errors- if (error.response?.status !== 422) {+ if (error.response?.status !== 422 && !oidcForced.value) {showPasswordField.value = true}})diff --git a/client/lib/oidc/rate-limit.js b/client/lib/oidc/rate-limit.jsnew file mode 100644index 000000000..6f7faf226--- /dev/null+++ b/client/lib/oidc/rate-limit.js@@ -0,0 +1,17 @@+export const isOidcRateLimitedError = (error) => {+ return error?.response?.status === 429 || error?.status === 429+}++export const getOidcRetryAfterSeconds = (error) => {+ const response = error?.response+ const retryAfter = response?.headers?.get?.('retry-after')+ ?? response?.headers?.['retry-after']+ ?? response?._data?.retry_after+ const seconds = Number.parseInt(retryAfter, 10)++ return Number.isFinite(seconds) && seconds > 0 ? seconds : 60+}++export const oidcRateLimitMessage = (seconds) => {+ return `Too many sign-in requests. Please try again in ${seconds} second${seconds === 1 ? '' : 's'}.`+}diff --git a/client/pages/auth/[slug]/callback.vue b/client/pages/auth/[slug]/callback.vueindex 704837f45..b9bda8471 100644--- a/client/pages/auth/[slug]/callback.vue+++ b/client/pages/auth/[slug]/callback.vue@@ -48,6 +48,11 @@<script setup>import { oidcApi } from "~/api"import { redirectToOidcProvider } from "~/lib/oidc/redirect"+import {+ getOidcRetryAfterSeconds,+ isOidcRateLimitedError,+ oidcRateLimitMessage,+} from "~/lib/oidc/rate-limit"import {canAutomaticallyRetryOidcSignIn,clearOidcAutomaticRetry,@@ -78,14 +83,14 @@ const retryOidcSignIn = (slug) => {return oidcApi.redirect(slug).then((response) => {if (!response.redirect_url) {- return false+ return { started: false }}storeOidcStateVerifier(slug, response.state, response.state_verifier)redirectToOidcProvider(response.redirect_url)- return true+ return { started: true }})- .catch(() => false)+ .catch((error) => ({ started: false, error }))}const handleCallback = async () => {@@ -159,14 +164,18 @@ const handleCallback = async () => {if (errorResponse.error === 'oidc_account_link_required' && errorResponse.link_token) {error.value = 'An account with this email already exists. Please link your existing account to continue.'linkToken.value = errorResponse.link_token+ } else if (isOidcRateLimitedError(err)) {+ error.value = oidcRateLimitMessage(getOidcRetryAfterSeconds(err))} else if (authorizationCodeWasAlreadyUsed(providerError)) {if (canAutomaticallyRetryOidcSignIn(slug)) {return retryOidcSignIn(slug)- .then((retryStarted) => {- if (retryStarted) return+ .then(({ started, error: retryError }) => {+ if (started) returnisRetrying.value = false- error.value = 'We could not reconnect automatically. Return to sign in to try again, or contact your administrator if the problem continues.'+ error.value = isOidcRateLimitedError(retryError)+ ? oidcRateLimitMessage(getOidcRetryAfterSeconds(retryError))+ : 'We could not reconnect automatically. Return to sign in to try again, or contact your administrator if the problem continues.'loading.value = false})}diff --git a/client/test/nuxt/oidc-link-flow.spec.ts b/client/test/nuxt/oidc-link-flow.spec.tsindex b31453949..b9830a70b 100644--- a/client/test/nuxt/oidc-link-flow.spec.ts+++ b/client/test/nuxt/oidc-link-flow.spec.ts@@ -11,6 +11,7 @@ const {canAutomaticallyRetryOidcSignInSpy,clearOidcAutomaticRetrySpy,consumeOidcStateVerifierSpy,+ featureFlagValues,markOidcAutomaticRetrySpy,storeOidcStateVerifierSpy,} = vi.hoisted(() => ({@@ -20,6 +21,7 @@ const {canAutomaticallyRetryOidcSignInSpy: vi.fn(() => true),clearOidcAutomaticRetrySpy: vi.fn(),consumeOidcStateVerifierSpy: vi.fn(() => null),+ featureFlagValues: {},markOidcAutomaticRetrySpy: vi.fn(),storeOidcStateVerifierSpy: vi.fn(),}))@@ -90,8 +92,12 @@ vi.mock('~/lib/oidc/state-verifier', () => ({storeOidcStateVerifier: storeOidcStateVerifierSpy,}))+vi.mock('~/composables/useFeatureFlag.js', () => ({+ useFeatureFlag: (flag, defaultValue = null) => featureFlagValues[flag] ?? defaultValue,+}))+describe('OIDC link flow', () => {- const setupGlobals = (routeOverrides = {}) => {+ const setupGlobals = (routeOverrides = {}, { featureFlags = {}, formOverrides = {} } = {}) => {const router = {push: vi.fn(),replace: vi.fn(),@@ -102,6 +108,16 @@ describe('OIDC link flow', () => {query: {},...routeOverrides,}+ const form = {+ email: '',+ password: '',+ remember: false,+ busy: false,+ post: vi.fn(),+ mutate: vi.fn(),+ ...formOverrides,+ }+ Object.assign(featureFlagValues, featureFlags)vi.stubGlobal('useRouter', () => router)vi.stubGlobal('useRoute', () => route)@@ -131,15 +147,8 @@ describe('OIDC link flow', () => {vi.stubGlobal('useWorkspaces', () => ({list: () => ({ suspense: vi.fn() }),}))- vi.stubGlobal('useFeatureFlag', () => false)- vi.stubGlobal('useForm', () => ({- email: '',- password: '',- remember: false,- busy: false,- post: vi.fn(),- mutate: vi.fn(),- }))+ vi.stubGlobal('useFeatureFlag', (flag) => featureFlags[flag] ?? false)+ vi.stubGlobal('useForm', () => form)vi.stubGlobal('useAuth', () => ({login: () => vi.fn(),}))@@ -148,11 +157,12 @@ describe('OIDC link flow', () => {send: vi.fn(),}))- return { router, route }+ return { router, route, form }}beforeEach(() => {vi.clearAllMocks()+ Object.keys(featureFlagValues).forEach((key) => delete featureFlagValues[key])canAutomaticallyRetryOidcSignInSpy.mockReturnValue(true)})@@ -287,6 +297,158 @@ describe('OIDC link flow', () => {vi.useRealTimers()})+ it('shows the retry delay instead of retrying a throttled callback', async () => {+ vi.useFakeTimers()+ const apiModule = await import('~/api') as { oidcApi: any }+ const oidcApi = apiModule.oidcApi+ setupGlobals()++ oidcApi.callback.mockRejectedValue({+ response: {+ status: 429,+ headers: { 'retry-after': '42' },+ _data: { retry_after: 42 },+ },+ })++ const wrapper = mount(OidcCallbackPage, {+ global: {+ stubs: {+ TwoFactorVerificationModal: true,+ Loader: true,+ UAlert: {+ template: '<div class="alert">{{ title }} {{ description }}</div>',+ props: ['title', 'description'],+ },+ UButton: {+ template: '<button>{{ label }}<slot /></button>',+ props: ['label', 'color', 'variant', 'to'],+ emits: ['click'],+ },+ },+ },+ })++ await flushPromises()+ vi.runAllTimers()+ await flushPromises()++ expect(oidcApi.redirect).not.toHaveBeenCalled()+ expect(wrapper.text()).toContain('Too many sign-in requests. Please try again in 42 seconds.')+ vi.useRealTimers()+ })++ it('shows the retry delay when the automatic OIDC recovery is rate limited', async () => {+ vi.useFakeTimers()+ const apiModule = await import('~/api') as { oidcApi: any }+ const oidcApi = apiModule.oidcApi+ setupGlobals()++ oidcApi.callback.mockRejectedValue({+ message: 'AADSTS54005: Authorization code was already redeemed',+ })+ oidcApi.redirect.mockRejectedValue({+ response: {+ status: 429,+ headers: { 'retry-after': '30' },+ _data: { retry_after: 30 },+ },+ })++ const wrapper = mount(OidcCallbackPage, {+ global: {+ stubs: {+ TwoFactorVerificationModal: true,+ Loader: true,+ UAlert: {+ template: '<div class="alert">{{ title }} {{ description }}</div>',+ props: ['title', 'description'],+ },+ UButton: {+ template: '<button>{{ label }}<slot /></button>',+ props: ['label', 'color', 'variant', 'to'],+ emits: ['click'],+ },+ },+ },+ })++ await flushPromises()+ vi.runAllTimers()+ await flushPromises()++ expect(oidcApi.redirect).toHaveBeenCalledOnce()+ expect(wrapper.text()).toContain('Too many sign-in requests. Please try again in 30 seconds.')+ vi.useRealTimers()+ })++ it('disables the SSO continue action until the rate-limit delay expires', async () => {+ vi.useFakeTimers()+ 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: {+ template: '<button :disabled="disabled">{{ label }}</button>',+ props: ['label', 'disabled', 'color', 'variant', 'to'],+ },+ VTransition: {+ template: '<div><slot /></div>',+ },+ NuxtLink: true,+ ClientOnly: true,+ GoogleOneTap: true,+ },+ },+ })++ const form = (wrapper.vm as any).form+ form.email = '[email protected]'+ form.post = vi.fn()+ .mockResolvedValueOnce({ action: 'redirect', slug: 'company-sso' })+ .mockRejectedValueOnce({+ response: {+ status: 429,+ headers: { 'retry-after': '30' },+ _data: { retry_after: 30 },+ },+ })++ await (wrapper.vm as any).checkOidcOptions()+ await flushPromises()++ expect(wrapper.text()).toContain('Please wait before trying again')+ expect(wrapper.text()).toContain('Try again in 30s')+ expect(wrapper.find('button').attributes('disabled')).toBeDefined()+ expect(wrapper.find('input[name="password"]').exists()).toBe(false)++ vi.advanceTimersByTime(1000)+ await flushPromises()+ expect(wrapper.text()).toContain('Try again in 29s')+ vi.useRealTimers()+ })+it('links account after two-factor verification when token is present', async () => {setupGlobals({query: { oidc_link_token: 'link-token-123' },diff --git a/docker/nginx.conf b/docker/nginx.confindex bd81466cd..559a0f1c4 100644--- a/docker/nginx.conf+++ b/docker/nginx.conf@@ -36,6 +36,12 @@ server {include fastcgi_params;fastcgi_param SCRIPT_FILENAME $document_root/index.php;fastcgi_param REQUEST_URI $api_uri;+ # Laravel accepts these headers only from IPs listed in TRUSTED_PROXIES.+ # This preserves the client IP behind an explicitly trusted reverse proxy.+ fastcgi_param HTTP_X_FORWARDED_FOR $proxy_add_x_forwarded_for;+ fastcgi_param HTTP_X_FORWARDED_HOST $http_x_forwarded_host;+ fastcgi_param HTTP_X_FORWARDED_PORT $http_x_forwarded_port;+ fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;}# Deny access to . files@@ -43,4 +49,3 @@ server {deny all;}}-diff --git a/docker/nginx.dev.conf b/docker/nginx.dev.confindex f33a9ccd0..136c53a87 100644--- a/docker/nginx.dev.conf+++ b/docker/nginx.dev.conf@@ -29,6 +29,11 @@ server {include fastcgi_params;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;fastcgi_param PATH_INFO $fastcgi_path_info;+ # Kept consistent with the production ingress for proxy-aware tests.+ fastcgi_param HTTP_X_FORWARDED_FOR $proxy_add_x_forwarded_for;+ fastcgi_param HTTP_X_FORWARDED_HOST $http_x_forwarded_host;+ fastcgi_param HTTP_X_FORWARDED_PORT $http_x_forwarded_port;+ fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;fastcgi_read_timeout 300;}@@ -36,4 +41,4 @@ server {location ~ /\. {deny all;}-}\ No newline at end of file+}diff --git a/docs/configuration/environment-variables.mdx b/docs/configuration/environment-variables.mdxindex 2b52fe682..0df747661 100644--- a/docs/configuration/environment-variables.mdx+++ b/docs/configuration/environment-variables.mdx@@ -5,6 +5,37 @@ description: Detailed guide on configuring environment variables for OpnFormOpnForm uses two `.env` files for configuration: one for the Laravel backend located in the `api` directory, and one for the Nuxt front-end located in the `client` directory.+## Public instance URL (self-hosted)++Set these variables before exposing a self-hosted instance publicly or+configuring OIDC, OAuth, emails, or any feature that generates links back to+your OpnForm instance. They must use the real public URL, never `localhost` in+production.++For a standard Docker deployment available at `https://forms.example.com`:++| File | Variable | Value |+| --- | --- | --- |+| `api/.env` | `APP_URL` | `https://forms.example.com` |+| `api/.env` | `FRONT_URL` | `https://forms.example.com` |+| `client/.env` | `NUXT_PUBLIC_APP_URL` | `https://forms.example.com` |+| `client/.env` | `NUXT_PUBLIC_API_BASE` | `https://forms.example.com/api` |++`APP_URL`, `FRONT_URL`, and `NUXT_PUBLIC_APP_URL` normally have the same+public origin. In the standard Docker setup, the API is served through that+same origin under `/api`, which is why `NUXT_PUBLIC_API_BASE` ends in `/api`.+If your API is exposed on a separate public origin, use that browser-accessible+API URL instead.++<Warning>+ After changing either `.env` file in Docker, recreate the affected+ containers. `docker compose restart` does not reload environment values.+ See [Updating Environment Variables](#updating-environment-variables).+</Warning>++For the deployment workflow, see [Docker Deployment](../deployment/docker#configure-your-public-instance-url).+For the OIDC-specific checklist, see [OIDC SSO Configuration](./oidc-sso#prerequisites).+## Backend Environment VariablesThe following environment variables are used to [configure the Laravel](https://laravel.com/docs/11.x/configuration) application (OpnForm's API).@@ -31,6 +62,7 @@ There are dedicated configuration pages available for more detailed setup instru| `OPEN_AI_API_KEY` | API key for accessing OpenAI services. || `UNSPLASH_ACCESS_KEY` | Access key for Unsplash API. || `UNSPLASH_SECRET_KEY` | Secret key for Unsplash API. |+| `APP_URL` | Public URL of the Laravel application. For a standard self-hosted deployment, set it to the public OpnForm URL. || `FRONT_URL` | Public facing URL of the front-end. || `FRONT_API_SECRET` | Shared secret with the front-end. || `JWT_TTL` | Time to live for JSON Web Tokens (JWT). |@@ -39,6 +71,8 @@ There are dedicated configuration pages available for more detailed setup instru| `PUBLIC_UPLOADS_RATE_LIMIT_PER_MINUTE` | Maximum public upload requests allowed per client IP or authenticated user per route each minute. Defaults to `30`. || `PUBLIC_UPLOADS_RATE_LIMIT_PER_HOUR` | Maximum public upload requests allowed per client IP or authenticated user per route each hour. Defaults to `300`. || `OIDC_FORCE_LOGIN` | When set to `true`, password-based authentication is disabled and users must authenticate via OIDC SSO. See [Force Login Mode](../configuration/oidc-sso#7-force-login-mode) for details. |+| `OIDC_RATE_LIMIT_PER_MINUTE` | Maximum OIDC sign-in initiations allowed per client IP and OIDC connection each minute. Defaults to `100`. OIDC callbacks use the normal API limit and are protected by their single-use state verifier. |+| `TRUSTED_PROXIES` | Comma-separated IP addresses or CIDR ranges of reverse proxies allowed to provide `X-Forwarded-*` headers. Leave empty for a direct Docker deployment. Never use `*`; it would allow a direct client to spoof its IP. || `CUSTOM_CODE_ENABLE_SELF_HOSTED` | Enables execution of user-provided custom code on self-hosted deployments. Defaults to `false` for safety reasons (XSS etc.). || `LICENSE_API_ENDPOINT` | Cloud API endpoint used by self-hosted instances for Enterprise license validation. Defaults to `https://api.opnform.com`. || `LICENSE_CHECKOUT_SUCCESS_URL` | Cloud checkout success URL used when creating self-hosted Enterprise license Stripe sessions. |diff --git a/docs/configuration/oidc-sso.mdx b/docs/configuration/oidc-sso.mdxindex e9ecdccc0..c6c365591 100644--- a/docs/configuration/oidc-sso.mdx+++ b/docs/configuration/oidc-sso.mdx@@ -35,6 +35,34 @@ Before setting up OIDC SSO, ensure you have:3. Admin access to the workspace where you want to configure SSO4. The issuer URL from your IdP (typically found in the `.well-known/openid-configuration` endpoint)+### Self-hosted instance setup++Before creating an OIDC connection, make sure that OpnForm is configured with+its real public URL. This is a deployment prerequisite: it determines the+callback URL shown in the OIDC connection form.++For the standard Docker deployment where OpnForm is available at+`https://forms.example.com`, the person who manages the deployment must set:++| File | Variables |+| --- | --- |+| `api/.env` | `APP_URL=https://forms.example.com`<br />`FRONT_URL=https://forms.example.com` |+| `client/.env` | `NUXT_PUBLIC_APP_URL=https://forms.example.com`<br />`NUXT_PUBLIC_API_BASE=https://forms.example.com/api` |++<Warning>+ Do not configure the callback URI at your IdP if the value displayed in+ OpnForm contains `localhost`. Ask the person who manages the deployment to+ set the public instance URL, then recreate the containers before continuing.+</Warning>++<Note>+ If deployment and OIDC configuration are handled by different people, share+ this checklist with the person who manages the instance. See [Public+ instance URL](./environment-variables#public-instance-url-self-hosted) for+ the full reference and [Docker Deployment](../deployment/docker#configure-your-public-instance-url)+ for the Docker steps.+</Note>+<Note>On self-hosted Community instances, OIDC can provision users until theinstance reaches the free 2-user limit. Existing linked users can continue@@ -191,8 +219,9 @@ You can edit an existing OIDC connection without deleting it.- Leave **Client Secret** empty to retain the current secret. Enter a value onlywhen rotating or replacing it.- After changing the public URL of a self-hosted instance, update both the- backend `APP_URL` and `FRONT_URL`, plus the frontend `NUXT_PUBLIC_APP_URL`.- Recreate the relevant containers so the new environment values are loaded.+ backend `APP_URL` and `FRONT_URL`, plus the frontend `NUXT_PUBLIC_APP_URL`+ and `NUXT_PUBLIC_API_BASE`. Recreate the relevant containers so the new+ environment values are loaded.- Edit the connection, click **Use current app URL** below its redirect URI,then save. Copy the refreshed URL into your IdP's allowed redirect URIs.diff --git a/docs/deployment/docker.mdx b/docs/deployment/docker.mdxindex 4885e9bb5..81185c29f 100644--- a/docs/deployment/docker.mdx+++ b/docs/deployment/docker.mdx@@ -46,6 +46,51 @@ import CloudVersion from "/snippets/cloud-version.mdx";3. Access your OpnForm instance at `http://localhost`+### Configure your public instance URL++The setup script creates the environment files, but it cannot know the public+domain where your instance will be available. Before configuring OIDC, OAuth,+or using the instance in production, set the public URL in both files:++| File | Required variables |+| --- | --- |+| `api/.env` | `APP_URL` and `FRONT_URL` |+| `client/.env` | `NUXT_PUBLIC_APP_URL` and `NUXT_PUBLIC_API_BASE` |++For example, an instance available at `https://forms.example.com` uses+`https://forms.example.com` for `APP_URL`, `FRONT_URL`, and+`NUXT_PUBLIC_APP_URL`, plus `https://forms.example.com/api` for+`NUXT_PUBLIC_API_BASE`.++After changing these variables, recreate the containers; `docker compose+restart` does not load new environment values.++```bash+docker compose down+docker compose up -d+```++See [Public instance URL](/configuration/environment-variables#public-instance-url-self-hosted)+for the complete example and [OIDC SSO Configuration](/configuration/oidc-sso#prerequisites)+before setting up SSO.++### If a reverse proxy is in front of OpnForm++When Caddy, Traefik, Cloudflare, or another reverse proxy forwards traffic to+the Docker ingress, set `TRUSTED_PROXIES` in `api/.env` to the IP address or+CIDR range from which that proxy connects to the ingress. This lets OpnForm use+the real client IP for OIDC and other rate limits.++```bash+# Example only: use the actual address or CIDR of your own reverse proxy.+TRUSTED_PROXIES=192.0.2.10,2001:db8:1234::/48+```++Leave it empty when users connect directly to the Docker ingress. Do not set+it to `*`: doing so would make a direct client-provided forwarding header+trustworthy and allow rate-limit bypasses. Recreate the API container after+changing it.+### Initial SetupAfter deployment, OpnForm will automatically redirect you to a setup page where you can create your admin account. Simply visit `http://localhost` and you'll be guided through the setup process.