Skip to content

Beautiful Open-Source Form Builder

OIDC (#963)

Julien Nahum2eade7eef364
diff --git a/.cursor/rules/back-end-testing.mdc b/.cursor/rules/back-end-testing.mdc
index 76a3c38ff..40bebbe8d 100644
--- a/.cursor/rules/back-end-testing.mdc
+++ b/.cursor/rules/back-end-testing.mdc
@@ -6,28 +6,79 @@ globs: api/tests/**/*.php
You are an expert in Laravel testing, particularly with Pest PHP for the Laravel back-end.
Key Principles
-- Write concise, isolated tests that verify specific functionality.
-- Follow the Arrange-Act-Assert pattern for test structure.
-- Use descriptive test names that explain what is being tested.
-- Prefer Pest PHP's expressive syntax over traditional PHPUnit syntax.
-- Use mocking and test doubles appropriately to isolate components.
-- Organize tests by the component they are testing.
+
+- Write concise, isolated tests that verify specific functionality.
+- Follow the Arrange-Act-Assert pattern for test structure.
+- Use descriptive test names that explain what is being tested.
+- Prefer Pest PHP's expressive syntax over traditional PHPUnit syntax.
+- Use mocking and test doubles appropriately to isolate components.
+- Organize tests by the component they are testing.
Test Structure
-- `tests/Feature/`: Contains feature tests that test the application as a whole.
-- `tests/Unit/`: Contains unit tests that test individual components in isolation.
- - `Unit/Rules/`: Tests for validation rules.
- - `Unit/Service/`: Tests for service classes.
- - `Unit/Services/`: Tests for service classes (alternative structure).
-- `tests/Helpers/`: Contains helper classes used across tests.
-- `tests/Browser/`: Contains browser tests using Laravel Dusk.
+
+- `tests/Feature/`: Contains feature tests that test the application as a whole.
+- `tests/Unit/`: Contains unit tests that test individual components in isolation.
+ - `Unit/Rules/`: Tests for validation rules.
+ - `Unit/Service/`: Tests for service classes.
+ - `Unit/Services/`: Tests for service classes (alternative structure).
+- `tests/Helpers/`: Contains helper classes used across tests.
+- `tests/Browser/`: Contains browser tests using Laravel Dusk.
Test Configuration
-- Use `tests/Pest.php` for Pest PHP configuration.
-- Use `tests/TestCase.php` as the base test case class.
-- Use `tests/TestHelpers.php` for common helper methods.
+
+- Use `tests/Pest.php` for Pest PHP configuration.
+- Use `tests/TestCase.php` as the base test case class.
+- Use `tests/TestHelpers.php` for common helper methods.
+
+Test Helpers
+The `TestHelpers` trait provides convenient methods for creating test data and authenticating users in tests. All test classes should use this trait.
+
+User Creation
+
+- `createUser(array $data = [])`: Creates a standard user with factory defaults. Override attributes via `$data`.
+- `createProUser()`: Creates a user with an active Pro subscription.
+- `createTrialingUser()`: Creates a user with a trialing subscription.
+
+User Authentication
+
+- `actingAsUser(?User $user = null)`: Authenticates as a user via login endpoint. Creates a user if none provided.
+- `actingAsProUser(?User $user = null)`: Authenticates as a Pro user. Creates a Pro user if none provided.
+- `actingAsTrialingUser(?User $user = null)`: Authenticates as a trialing user. Creates a trialing user if none provided.
+- `actingAsGuest()`: Logs out and asserts guest status.
+- `actingAsAdmin(?User $user = null)`: Authenticates as an admin user. Creates an admin user (via config) if none provided.
+
+Workspace Creation
+
+- `createUserWorkspace(User $user)`: Creates a workspace named "Form Testing" and associates it with the user as admin.
+
+Form Creation
+
+- `makeForm(User $user, Workspace $workspace, array $data = [])`: Creates a form model instance without saving to database. Includes default properties (text, number, rating, scale, slider, select, multi_select, date, checkbox, URL, email, phone_number, files).
+- `createForm(User $user, Workspace $workspace, array $data = [])`: Creates and saves a form with default properties. Override attributes via `$data`.
+
+Form Integrations
+
+- `createFormIntegration($integrationId, $formId, $settings = [])`: Creates a form integration via API endpoint. Returns the created integration data.
+
+Form Submissions
+
+- `generateFormSubmissionData(Form $form, array $data = [], bool $asFormSubmissionData = false)`: Generates fake form submission data based on form properties. Use `$asFormSubmissionData = true` to format as stored in FormSubmission model.
+
+Example Usage
+
+```php
+it('can create a form submission', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->createForm($user, $workspace);
+
+ $submissionData = $this->generateFormSubmissionData($form);
+ // ... test submission creation
+});
+```
Unit Testing Best Practices
+
1. **Test in Isolation**: Mock dependencies to ensure true unit testing.
2. **Single Responsibility**: Each test should verify one specific behavior.
3. **Descriptive Names**: Use descriptive test names that explain what is being tested.
@@ -40,82 +91,91 @@ Unit Testing Best Practices
10. **Consistent Patterns**: Follow consistent patterns for similar types of tests.
Writing Unit Tests
-- Use Pest PHP's expressive syntax:
- ```php
- it('can parse filenames', function () {
- $fileName = 'example_85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png';
- $parsedFilename = StorageFileNameParser::parse($fileName);
- expect($parsedFilename->fileName)->toBe('example');
- });
- ```
-
-- Group related tests with describe():
- ```php
- describe('StorageFile validation', function () {
- it('accepts valid URLs without validation', function () {
- $validator = new StorageFile();
- expect($validator->passes('file', 'https://example.com/file.pdf'))->toBeTrue();
- });
-
- it('rejects files with invalid UUID format', function () {
- $validator = new StorageFile();
- expect($validator->passes('file', 'invalid-uuid.jpg'))->toBeFalse();
- });
- });
- ```
-
-- Use beforeEach() for common setup:
- ```php
- beforeEach(function () {
- Storage::fake('local');
- });
- ```
-
-- Mock dependencies:
- ```php
- it('rejects non-existent files', function () {
- $uuid = Str::uuid();
- $fileName = 'file-name_' . $uuid . '.jpg';
-
- Storage::shouldReceive('exists')
- ->with('tmp/' . $uuid)
- ->andReturn(false);
-
- $validator = new StorageFile();
- expect($validator->passes('file', $fileName))->toBeFalse();
- });
- ```
-
-- Test edge cases:
- ```php
- it('can clean non-utf characters', function () {
- $fileName = 'Образец_для_заполнения_85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png';
- $parsedFilename = StorageFileNameParser::parse($fileName);
- expect($parsedFilename->getMovedFileName())->toBe('___85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png');
- });
- ```
+
+- Use Pest PHP's expressive syntax:
+
+ ```php
+ it('can parse filenames', function () {
+ $fileName = 'example_85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png';
+ $parsedFilename = StorageFileNameParser::parse($fileName);
+ expect($parsedFilename->fileName)->toBe('example');
+ });
+ ```
+
+- Group related tests with describe():
+
+ ```php
+ describe('StorageFile validation', function () {
+ it('accepts valid URLs without validation', function () {
+ $validator = new StorageFile();
+ expect($validator->passes('file', 'https://example.com/file.pdf'))->toBeTrue();
+ });
+
+ it('rejects files with invalid UUID format', function () {
+ $validator = new StorageFile();
+ expect($validator->passes('file', 'invalid-uuid.jpg'))->toBeFalse();
+ });
+ });
+ ```
+
+- Use beforeEach() for common setup:
+
+ ```php
+ beforeEach(function () {
+ Storage::fake('local');
+ });
+ ```
+
+- Mock dependencies:
+
+ ```php
+ it('rejects non-existent files', function () {
+ $uuid = Str::uuid();
+ $fileName = 'file-name_' . $uuid . '.jpg';
+
+ Storage::shouldReceive('exists')
+ ->with('tmp/' . $uuid)
+ ->andReturn(false);
+
+ $validator = new StorageFile();
+ expect($validator->passes('file', $fileName))->toBeFalse();
+ });
+ ```
+
+- Test edge cases:
+ ```php
+ it('can clean non-utf characters', function () {
+ $fileName = 'Образец_для_заполнения_85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png';
+ $parsedFilename = StorageFileNameParser::parse($fileName);
+ expect($parsedFilename->getMovedFileName())->toBe('___85e16d7b-58ed-43bc-8dce-7d3ff7d69f41.png');
+ });
+ ```
Testing Validation Rules
-- Create instances of the rule class.
-- Test both valid and invalid inputs.
-- Verify error messages for invalid inputs.
-- Test edge cases and boundary conditions.
+
+- Create instances of the rule class.
+- Test both valid and invalid inputs.
+- Verify error messages for invalid inputs.
+- Test edge cases and boundary conditions.
Testing Service Classes
-- Mock dependencies using Mockery.
-- Test each public method in isolation.
-- Verify correct behavior for both success and failure cases.
-- Test edge cases and error handling.
+
+- Mock dependencies using Mockery.
+- Test each public method in isolation.
+- Verify correct behavior for both success and failure cases.
+- Test edge cases and error handling.
Running Tests
-- Run all tests: `php artisan test`
-- Run unit tests only: `php artisan test --testsuite=Unit`
-- Run a specific test file: `php artisan test --filter=StorageFileTest`
-- Run tests with coverage: `php artisan test --coverage`
+
+- Run all tests: `php artisan test`
+- Run unit tests only: `php artisan test --testsuite=Unit`
+- Run a specific test file: `php artisan test --filter=StorageFileTest`
+- Run tests with coverage: `php artisan test --coverage`
Debugging Tests
-- Use ray() for debugging test execution.
-- Use dd() or dump() for quick inspection of variables.
-- Check for race conditions in asynchronous tests.
-- Verify that the database is being properly reset between tests.
-- Ensure that tests are not dependent on each other.
\ No newline at end of file
+
+- Use ray() for debugging test execution.
+- Use dd() or dump() for quick inspection of variables.
+- Check for race conditions in asynchronous tests.
+- Verify that the database is being properly reset between tests.
+- Ensure that tests are not dependent on each other.
diff --git a/LICENSE b/LICENSE
index 0ad25db4b..25eaeb6b9 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,178 +1,188 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
+OpnForm licensing
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
+Copyright (c) 2025 OpnForm
+
+Portions of this software are licensed as follows:
+
+- All content that resides under the "api/app/Enterprise" directory of this repository, if this directory exists, is licensed under the license defined in "api/app/Enterprise/LICENSE".
+- All third party components incorporated into the OpnForm software are licensed under the original license provided by the owner of the applicable component.
+- Content outside of the above-mentioned directories or restrictions is available under the "AGPLv3" license as defined below.
+
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
Preamble
- The GNU Affero General Public License is a free, copyleft license for
+The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
- Developers that use our General Public Licenses protect your rights
+Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
- A secondary benefit of defending all users' freedom is that
+A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
- The GNU Affero General Public License is designed specifically to
+The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
+to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
+users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
+An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
- The precise terms and conditions for copying, distribution and
+The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
- 0. Definitions.
+0. Definitions.
- "This License" refers to version 3 of the GNU Affero General Public License.
+"This License" refers to version 3 of the GNU Affero General Public License.
- "Copyright" also means copyright-like laws that apply to other kinds of
+"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
+"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
- To "modify" a work means to copy from or adapt all or part of the work
+To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
+exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
- A "covered work" means either the unmodified Program or a work based
+A "covered work" means either the unmodified Program or a work based
on the Program.
- To "propagate" a work means to do anything with it that, without
+To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
+computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
+To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
- An interactive user interface displays "Appropriate Legal Notices"
+An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
+work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
- 1. Source Code.
+1. Source Code.
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
+The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
form of a work.
- A "Standard Interface" means an interface that either is an official
+A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
- The "System Libraries" of an executable work include anything, other
+The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
+implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
- The "Corresponding Source" for a work in object code form means all
+The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
+control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
+which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
- The Corresponding Source need not include anything that users
+The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
- The Corresponding Source for a work in source code form is that
+The Corresponding Source for a work in source code form is that
same work.
- 2. Basic Permissions.
+2. Basic Permissions.
- All rights granted under this License are granted for the term of
+All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
+content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
- You may make, run and propagate covered works that you do not
+You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
+in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
+not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
+Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
- No covered work shall be deemed part of an effective technological
+No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
- When you convey a covered work, you waive any legal power to forbid
+When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
@@ -180,9 +190,9 @@ modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
- 4. Conveying Verbatim Copies.
+4. Conveying Verbatim Copies.
- You may convey verbatim copies of the Program's source code as you
+You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
@@ -190,12 +200,12 @@ non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
- You may charge any price or no price for each copy that you convey,
+You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
- 5. Conveying Modified Source Versions.
+5. Conveying Modified Source Versions.
- You may convey a work based on the Program, or the modifications to
+You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
@@ -220,19 +230,19 @@ terms of section 4, provided that you also meet all of these conditions:
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
- A compilation of a covered work with other separate and independent
+A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
+beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
- 6. Conveying Non-Source Forms.
+6. Conveying Non-Source Forms.
- You may convey a covered work in object code form under the terms
+You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
@@ -278,75 +288,75 @@ in one of these ways:
Source of the work are being offered to the general public at no
charge under subsection 6d.
- A separable portion of the object code, whose source code is excluded
+A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
- A "User Product" is either (1) a "consumer product", which means any
+A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
+actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
- "Installation Information" for a User Product means any methods,
+"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
+a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
- If you convey an object code work under this section in, or with, or
+If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
+by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
- The requirement to provide Installation Information does not include a
+The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
+the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
- Corresponding Source conveyed, and Installation Information provided,
+Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
- 7. Additional Terms.
+7. Additional Terms.
- "Additional permissions" are terms that supplement the terms of this
+"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
+that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
- When you convey a copy of a covered work, you may at your option
+When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
- Notwithstanding any other provision of this License, for material you
+Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
@@ -373,74 +383,74 @@ that material) supplement the terms of this License with terms:
any liability that these contractual assumptions directly impose on
those licensors and authors.
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
+All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
+restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
- If you add terms to a covered work in accord with this section, you
+If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
- Additional terms, permissive or non-permissive, may be stated in the
+Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
- 8. Termination.
+8. Termination.
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
- However, if you cease all violation of this License, then your
+However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
- Moreover, your license from a particular copyright holder is
+Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
- Termination of your rights under this section does not terminate the
+Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
+this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
- 9. Acceptance Not Required for Having Copies.
+9. Acceptance Not Required for Having Copies.
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
+You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
+to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
- 10. Automatic Licensing of Downstream Recipients.
+10. Automatic Licensing of Downstream Recipients.
- Each time you convey a covered work, the recipient automatically
+Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
+propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
- An "entity transaction" is a transaction transferring control of an
+An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
+organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
@@ -448,43 +458,43 @@ give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
- 11. Patents.
+11. Patents.
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
+A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
- A contributor's "essential patent claims" are all patent claims
+A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
+consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
- Each contributor grants you a non-exclusive, worldwide, royalty-free
+Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
- In the following three paragraphs, a "patent license" is any express
+In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
+sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
- If you convey a covered work, knowingly relying on a patent license,
+If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -492,13 +502,13 @@ then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
+license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
- If, pursuant to or in connection with a single transaction or
+If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
@@ -506,10 +516,10 @@ or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
- A patent license is "discriminatory" if it does not include within
+A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
+specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
@@ -521,83 +531,83 @@ for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
- Nothing in this License shall be construed as excluding or limiting
+Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
- 12. No Surrender of Others' Freedom.
+12. No Surrender of Others' Freedom.
- If conditions are imposed on you (whether by court order, agreement or
+If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
+excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
+not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
- 13. Remote Network Interaction; Use with the GNU General Public License.
+13. Remote Network Interaction; Use with the GNU General Public License.
- Notwithstanding any other provision of this License, if you modify the
+Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
+means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
- Notwithstanding any other provision of this License, you have
+Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
+combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
- 14. Revised Versions of this License.
+14. Revised Versions of this License.
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
+The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
- Each version is given a distinguishing version number. If the
+Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
+Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
- If the Program specifies that a proxy can decide which future
+If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
- 15. Disclaimer of Warranty.
+15. Disclaimer of Warranty.
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
- 16. Limitation of Liability.
+16. Limitation of Liability.
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -607,9 +617,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
- 17. Interpretation of Sections 15 and 16.
+17. Interpretation of Sections 15 and 16.
- If the disclaimer of warranty and limitation of liability provided
+If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
@@ -620,11 +630,11 @@ copy of the Program in return for a fee.
How to Apply These Terms to Your New Programs
- If you develop a new program, and you want it to be of the greatest
+If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
- To do so, attach the following notices to the program. It is safest
+To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
@@ -647,15 +657,15 @@ the "copyright" line and a pointer to where the full notice is found.
Also add information on how to contact you by electronic and paper mail.
- If your software can interact with users remotely through a computer
+If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
+get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
+of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
- You should also get your employer (if you work as a programmer) or school,
+You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
diff --git a/LICENSE-MIT b/LICENSE-MIT
deleted file mode 100644
index 3a2f6d059..000000000
--- a/LICENSE-MIT
+++ /dev/null
@@ -1,26 +0,0 @@
-MIT License
-
-Copyright (c) 2025 OpnForm
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-This license applies to the `/integrations` directory only. The rest of the
-OpnForm codebase is licensed under AGPL-3.0. See the main LICENSE file for
-details.
-
diff --git a/README.md b/README.md
index 7d68b2f1b..3a973c24c 100644
--- a/README.md
+++ b/README.md
@@ -52,6 +52,13 @@ If you need help or have questions, please join our [Discord community](https://
## License
-OpnForm is open-source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can find it [here](https://github.com/OpnForm/OpnForm/blob/main/LICENSE).
+OpnForm is **open-source** under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. You can find it [here](https://github.com/OpnForm/OpnForm/blob/main/LICENSE).
-**Note**: The `/integrations` directory is licensed under MIT License to comply with third-party platform requirements (e.g., n8n requires MIT-licensed community nodes). See [integrations/LICENSE](integrations/LICENSE) for details.
+### Dual Licensing
+
+OpnForm uses a dual-license model to make the project sustainable:
+
+- **Core OpnForm** (AGPL-3.0): The main application is free and open-source under AGPLv3, giving you the freedom to use, modify, and distribute it.
+- **Enterprise Edition** (Proprietary): Advanced features under `api/app/Enterprise/` are available under our [Enterprise License](https://github.com/OpnForm/OpnForm/blob/main/api/app/Enterprise/LICENSE) and [Enterprise Terms](https://opnform.com/terms-conditions). These features help fund ongoing development and keep OpnForm sustainable.
+
+By offering Enterprise features alongside our open-source core, we can continue to invest in making OpnForm better for everyone while keeping the project financially sustainable.
diff --git a/api/app/Enterprise/LICENSE b/api/app/Enterprise/LICENSE
new file mode 100644
index 000000000..2971e6e0b
--- /dev/null
+++ b/api/app/Enterprise/LICENSE
@@ -0,0 +1,39 @@
+The OpnForm Enterprise Edition (EE) license (the “EE License”)
+Copyright (c) 2025 OpnForm
+
+With regard to the OpnForm Software:
+
+This software and associated documentation files (the "Software") may only be
+used in production if you (and any entity that you represent) have agreed to,
+and are in compliance with, the OpnForm Enterprise Terms of Service, available
+at https://opnform.com/terms-conditions (the “Enterprise Terms”), or another
+written agreement governing the use of the Software, as agreed by you and
+OpnForm, and otherwise have a valid OpnForm Enterprise license for the
+correct number of user seats. Subject to the foregoing sentence, you are free
+to modify this Software and publish patches to the Software. You agree that
+OpnForm and/or its licensors (as applicable) retain all right, title and
+interest in and to all such modifications and/or patches, and all such
+modifications and/or patches may only be used, copied, modified, displayed,
+distributed, or otherwise exploited with a valid OpnForm Enterprise
+subscription or other written enterprise agreement for the correct number of
+user seats.
+
+Notwithstanding the foregoing, you may copy and modify the Software for
+development and testing purposes, without requiring a subscription. You agree
+that OpnForm and/or its licensors (as applicable) retain all right, title and
+interest in and to all such modifications. You are not granted any other
+rights beyond what is expressly stated herein. Subject to the foregoing, it
+is forbidden to copy, merge, publish, distribute, sublicense, and/or sell the
+Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+For all third party components incorporated into the OpnForm Software, those
+components are licensed under the original license provided by the owner of
+the applicable component.
diff --git a/api/app/Enterprise/Oidc/Adapters/OAuthOidcDriver.php b/api/app/Enterprise/Oidc/Adapters/OAuthOidcDriver.php
new file mode 100644
index 000000000..c4f70052b
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Adapters/OAuthOidcDriver.php
@@ -0,0 +1,119 @@
+<?php
+
+namespace App\Enterprise\Oidc\Adapters;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Adapters\Socialite\OidcProvider;
+use App\Integrations\OAuth\Drivers\Contracts\OAuthDriver;
+use Laravel\Socialite\Contracts\User;
+
+class OAuthOidcDriver implements OAuthDriver
+{
+ private ?string $redirectUrl = null;
+ private ?array $scopes = [];
+ private ?string $state = null;
+ private IdentityConnection $connection;
+ private ?string $idToken = null;
+
+ protected OidcProvider $provider;
+
+ public function __construct(IdentityConnection $connection)
+ {
+ $this->connection = $connection;
+
+ // Create a custom OIDC provider instance
+ $redirectUrl = $connection->redirect_url;
+ $this->provider = new OidcProvider(
+ request(),
+ $connection->client_id,
+ $connection->client_secret,
+ $redirectUrl
+ );
+
+ $this->provider->setIssuer($connection->issuer);
+ }
+
+ public function getRedirectUrl(): string
+ {
+ $parameters = [];
+
+ if ($this->state) {
+ $parameters['state'] = $this->state;
+ }
+
+ $scopes = $this->scopes ?? $this->connection->scopes ?? config('oidc.default_scopes');
+
+ return $this->provider
+ ->scopes($scopes)
+ ->stateless()
+ ->redirectUrl($this->redirectUrl ?? $this->connection->redirect_url)
+ ->with($parameters)
+ ->redirect()
+ ->getTargetUrl();
+ }
+
+ public function getUser(): User
+ {
+ $user = $this->provider
+ ->stateless()
+ ->redirectUrl($this->redirectUrl ?? $this->connection->redirect_url)
+ ->user();
+
+ // Extract ID token from provider's token response
+ $this->idToken = $this->provider->getIdToken();
+
+ return $user;
+ }
+
+ public function canCreateUser(): bool
+ {
+ return true;
+ }
+
+ public function setRedirectUrl(string $url): self
+ {
+ $this->redirectUrl = $url;
+ return $this;
+ }
+
+ public function setScopes(array $scopes): self
+ {
+ $this->scopes = $scopes;
+ return $this;
+ }
+
+ public function setState(string $state): self
+ {
+ $this->state = $state;
+ return $this;
+ }
+
+ public function getScopesForIntent(string $intent): array
+ {
+ return match ($intent) {
+ 'auth' => $this->connection->scopes ?? config('oidc.default_scopes'),
+ default => $this->connection->scopes ?? config('oidc.default_scopes'),
+ };
+ }
+
+ public function getIdToken(): ?string
+ {
+ return $this->idToken;
+ }
+
+ /**
+ * Get the access token from provider's token response.
+ */
+ public function getAccessToken(): ?string
+ {
+ return $this->provider->getAccessToken();
+ }
+
+ /**
+ * Get the full token response from provider.
+ */
+ public function getTokenResponse(): array
+ {
+ return $this->provider->getTokenResponse();
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Adapters/Socialite/OidcProvider.php b/api/app/Enterprise/Oidc/Adapters/Socialite/OidcProvider.php
new file mode 100644
index 000000000..62b11f29e
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Adapters/Socialite/OidcProvider.php
@@ -0,0 +1,257 @@
+<?php
+
+namespace App\Enterprise\Oidc\Adapters\Socialite;
+
+use Exception;
+use GuzzleHttp\RequestOptions;
+use Illuminate\Http\RedirectResponse;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Str;
+use Laravel\Socialite\Two\AbstractProvider;
+use Laravel\Socialite\Two\User;
+
+class OidcProvider extends AbstractProvider
+{
+ public const IDENTIFIER = 'OIDC';
+
+ protected $scopes = ['openid', 'profile', 'email'];
+
+ protected $scopeSeparator = ' ';
+
+ protected bool $usesNonce = true;
+
+ protected ?string $issuer = null;
+
+ protected ?array $openIdConfig = null;
+
+ protected ?string $nonce = null;
+
+ /**
+ * Store token response for later use.
+ */
+ protected array $tokenResponse = [];
+
+ /**
+ * Get the token response (including id_token and access_token).
+ */
+ public function getTokenResponse(): array
+ {
+ return $this->tokenResponse;
+ }
+
+ /**
+ * Get the ID token from token response.
+ */
+ public function getIdToken(): ?string
+ {
+ return $this->tokenResponse['id_token'] ?? null;
+ }
+
+ /**
+ * Get the access token from token response.
+ */
+ public function getAccessToken(): ?string
+ {
+ return $this->tokenResponse['access_token'] ?? null;
+ }
+
+ public function setIssuer(string $issuer): self
+ {
+ $this->issuer = $issuer;
+ return $this;
+ }
+
+ protected function getOpenIdConfig(): array
+ {
+ if ($this->openIdConfig !== null) {
+ return $this->openIdConfig;
+ }
+
+ $cacheKey = "oidc_config_{$this->issuer}";
+
+ return Cache::remember($cacheKey, 3600, function () {
+ $wellKnownUrl = rtrim($this->issuer, '/') . '/.well-known/openid-configuration';
+
+ $response = $this->getHttpClient()->get($wellKnownUrl, [
+ RequestOptions::HEADERS => ['Accept' => 'application/json'],
+ ]);
+
+ return json_decode((string) $response->getBody(), true);
+ });
+ }
+
+ public function redirect(): RedirectResponse
+ {
+ $state = null;
+
+ if ($this->usesState()) {
+ $state = $this->getState();
+ if (!$state) {
+ $state = bin2hex(random_bytes(16));
+ }
+ Cache::put("oidc_state_{$state}", $state, 600);
+ } elseif ($this->usesNonce) {
+ $state = bin2hex(random_bytes(16));
+ Cache::put("oidc_state_{$state}", $state, 600);
+ }
+
+ if ($this->usesNonce) {
+ $nonce = Str::random(40);
+ $this->nonce = $nonce;
+ if ($state) {
+ Cache::put("oidc_nonce_{$state}", $nonce, 600);
+ }
+ Cache::put("oidc_nonce_value_{$nonce}", $nonce, 600);
+ }
+
+ return new RedirectResponse($this->getAuthUrl($state));
+ }
+
+ protected function getAuthUrl($state): string
+ {
+ return $this->buildAuthUrlFromBase(
+ $this->getOpenIdConfig()['authorization_endpoint'],
+ $state
+ );
+ }
+
+ protected function buildAuthUrlFromBase($url, $state): string
+ {
+ return $url . '?' . http_build_query($this->getCodeFields($state), '', '&', $this->encodingType);
+ }
+
+ protected function getCodeFields($state = null): array
+ {
+ $fields = [
+ 'client_id' => $this->clientId,
+ 'redirect_uri' => $this->redirectUrl,
+ 'scope' => $this->formatScopes($this->getScopes(), $this->scopeSeparator),
+ 'response_type' => 'code',
+ ];
+
+ if ($this->usesState() && $state) {
+ $fields['state'] = $state;
+ }
+
+ if ($this->usesNonce && $this->nonce) {
+ $fields['nonce'] = $this->nonce;
+ }
+
+ return array_merge($fields, $this->parameters);
+ }
+
+ protected function getTokenUrl()
+ {
+ return $this->getOpenIdConfig()['token_endpoint'];
+ }
+
+ protected function getUserInfoUrl(): string
+ {
+ return $this->getOpenIdConfig()['userinfo_endpoint'] ?? '';
+ }
+
+ protected function getUserByToken($token)
+ {
+ if (!empty($this->tokenResponse['id_token'])) {
+ return $this->decodeIdToken($this->tokenResponse['id_token']);
+ }
+
+ $userInfoUrl = $this->getUserInfoUrl();
+ if (!empty($userInfoUrl)) {
+ $response = $this->getHttpClient()->get(
+ $userInfoUrl,
+ [
+ RequestOptions::HEADERS => [
+ 'Accept' => 'application/json',
+ 'Authorization' => 'Bearer ' . $token,
+ ],
+ ]
+ );
+
+ return json_decode((string) $response->getBody(), true);
+ }
+
+ throw new Exception('Unable to retrieve user information: no ID token or userinfo endpoint');
+ }
+
+ public function getAccessTokenResponse($code)
+ {
+ $response = $this->getHttpClient()->post($this->getTokenUrl(), [
+ RequestOptions::HEADERS => ['Accept' => 'application/json'],
+ RequestOptions::FORM_PARAMS => array_merge(
+ $this->getTokenFields($code),
+ [
+ 'grant_type' => 'authorization_code',
+ ]
+ ),
+ ]);
+
+ $this->tokenResponse = json_decode((string) $response->getBody(), true);
+
+ return $this->tokenResponse;
+ }
+
+ protected function decodeIdToken(string $idToken): array
+ {
+ try {
+ [$header, $payload, $signature] = explode('.', $idToken);
+ $decoded = json_decode($this->base64UrlDecode($payload), true);
+
+ if ($this->usesNonce && isset($decoded['nonce'])) {
+ $storedNonce = null;
+ $state = $this->request->input('state');
+ $idTokenNonce = $decoded['nonce'];
+
+ if ($state) {
+ $cacheKey = "oidc_nonce_{$state}";
+ $storedNonce = Cache::get($cacheKey);
+
+ if ($storedNonce) {
+ Cache::forget($cacheKey);
+ Cache::forget("oidc_nonce_value_{$storedNonce}");
+ }
+ }
+
+ if (!$storedNonce) {
+ $nonceCacheKey = "oidc_nonce_value_{$idTokenNonce}";
+ $storedNonce = Cache::get($nonceCacheKey);
+
+ if ($storedNonce) {
+ Cache::forget($nonceCacheKey);
+ }
+ }
+
+ if (!$storedNonce || $storedNonce !== $idTokenNonce) {
+ throw new Exception('Invalid nonce in ID token');
+ }
+ }
+
+ return $decoded;
+ } catch (Exception $e) {
+ throw new Exception('Failed to decode ID token: ' . $e->getMessage());
+ }
+ }
+
+ protected function base64UrlDecode(string $data): string
+ {
+ return base64_decode(str_pad(
+ strtr($data, '-_', '+/'),
+ strlen($data) % 4,
+ '=',
+ STR_PAD_RIGHT
+ ));
+ }
+
+ protected function mapUserToObject(array $user)
+ {
+ return (new User())->setRaw($user)->map([
+ 'id' => $user['sub'] ?? $user['id'] ?? null,
+ 'email' => $user['email'] ?? null,
+ 'name' => $user['name'] ?? null,
+ 'nickname' => $user['nickname'] ?? null,
+ 'given_name' => $user['given_name'] ?? null,
+ 'family_name' => $user['family_name'] ?? null,
+ 'groups' => $user['groups'] ?? $user['group'] ?? [],
+ ]);
+ }
+}
diff --git a/api/app/Enterprise/Oidc/ConnectionManager.php b/api/app/Enterprise/Oidc/ConnectionManager.php
new file mode 100644
index 000000000..e149d9e39
--- /dev/null
+++ b/api/app/Enterprise/Oidc/ConnectionManager.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Enterprise\Oidc\Adapters\OAuthOidcDriver;
+use App\Enterprise\Oidc\Models\IdentityConnection;
+
+class ConnectionManager
+{
+ /**
+ * Build an OIDC driver instance for the given connection.
+ */
+ public function buildDriver(IdentityConnection $connection): OAuthOidcDriver
+ {
+ return new OAuthOidcDriver($connection);
+ }
+
+ /**
+ * Get a connection by slug.
+ */
+ public function getConnectionBySlug(string $slug): ?IdentityConnection
+ {
+ return IdentityConnection::where('slug', $slug)
+ ->where('enabled', true)
+ ->where('type', IdentityConnection::TYPE_OIDC)
+ ->first();
+ }
+}
diff --git a/api/app/Enterprise/Oidc/DomainJoiner.php b/api/app/Enterprise/Oidc/DomainJoiner.php
new file mode 100644
index 000000000..dea56ebed
--- /dev/null
+++ b/api/app/Enterprise/Oidc/DomainJoiner.php
@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Models\User;
+use App\Models\Workspace;
+
+class DomainJoiner
+{
+ /**
+ * Find workspace that should auto-join a user based on email domain.
+ *
+ * Checks settings.oidc.allowed_domain (dedicated OIDC domain field).
+ *
+ * @return Workspace|null
+ */
+ public function findWorkspaceForDomain(string $email): ?Workspace
+ {
+ $domain = $this->extractDomain($email);
+ if (!$domain) {
+ return null;
+ }
+
+ return Workspace::whereJsonContains('settings->oidc->allowed_domain', $domain)
+ ->first();
+ }
+
+ /**
+ * Extract domain from email address.
+ */
+ protected function extractDomain(string $email): ?string
+ {
+ $parts = explode('@', strtolower(trim($email)));
+ return count($parts) === 2 ? $parts[1] : null;
+ }
+
+ /**
+ * Ensure user is a member of the workspace with the given role.
+ */
+ public function ensureWorkspaceMembership(User $user, Workspace $workspace, string $role = 'member'): void
+ {
+ if (!$user->workspaces()->where('workspaces.id', $workspace->id)->exists()) {
+ $user->workspaces()->attach($workspace->id, ['role' => $role]);
+ } else {
+ // Update role if already a member
+ $user->workspaces()->updateExistingPivot($workspace->id, ['role' => $role]);
+ }
+ }
+}
diff --git a/api/app/Enterprise/Oidc/DomainValidator.php b/api/app/Enterprise/Oidc/DomainValidator.php
new file mode 100644
index 000000000..2f25c69a8
--- /dev/null
+++ b/api/app/Enterprise/Oidc/DomainValidator.php
@@ -0,0 +1,129 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Models\User;
+
+class DomainValidator
+{
+ /**
+ * Validate domain for a user.
+ *
+ * Checks that:
+ * 1. Domain is not a blocked email provider
+ * 2. Domain matches the user's email domain (exact or root domain)
+ *
+ * @param string $domain
+ * @param User $user
+ * @return bool
+ */
+ public function validateDomainForUser(string $domain, User $user): bool
+ {
+ // Check if domain is blocked
+ if ($this->isBlockedProvider($domain)) {
+ return false;
+ }
+
+ // Check if domain matches user's email domain
+ return $this->matchesUserDomain($domain, $user->email);
+ }
+
+ /**
+ * Extract root domain from a domain string.
+ *
+ * Example: mail.company.com -> company.com
+ *
+ * @param string $domain
+ * @return string
+ */
+ public function extractRootDomain(string $domain): string
+ {
+ $domain = strtolower(trim($domain));
+ $parts = explode('.', $domain);
+
+ // If domain has 2 or fewer parts, it's already a root domain
+ if (count($parts) <= 2) {
+ return $domain;
+ }
+
+ // Return last two parts (e.g., company.com from mail.company.com)
+ return implode('.', array_slice($parts, -2));
+ }
+
+ /**
+ * Check if domain is a blocked email provider.
+ *
+ * @param string $domain
+ * @return bool
+ */
+ public function isBlockedProvider(string $domain): bool
+ {
+ $domain = strtolower(trim($domain));
+ $blockedProviders = config('oidc.blocked_email_providers', []);
+
+ // Check exact match
+ if (in_array($domain, $blockedProviders, true)) {
+ return true;
+ }
+
+ // Check root domain (e.g., mail.gmail.com -> gmail.com)
+ $rootDomain = $this->extractRootDomain($domain);
+ return in_array($rootDomain, $blockedProviders, true);
+ }
+
+ /**
+ * Check if domain matches user's email domain (exact or root domain).
+ *
+ * @param string $domain
+ * @param string $userEmail
+ * @return bool
+ */
+ public function matchesUserDomain(string $domain, string $userEmail): bool
+ {
+ $userDomain = $this->extractDomainFromEmail($userEmail);
+ if (!$userDomain) {
+ return false;
+ }
+
+ $domain = strtolower(trim($domain));
+ $userDomain = strtolower(trim($userDomain));
+
+ // Exact match
+ if ($domain === $userDomain) {
+ return true;
+ }
+
+ // Root domain match
+ $domainRoot = $this->extractRootDomain($domain);
+ $userDomainRoot = $this->extractRootDomain($userDomain);
+
+ return $domainRoot === $userDomainRoot;
+ }
+
+ /**
+ * Get email domain from user's email address.
+ *
+ * @param User $user
+ * @return string|null
+ */
+ public function getUserEmailDomain(User $user): ?string
+ {
+ return $this->extractDomainFromEmail($user->email);
+ }
+
+ /**
+ * Extract domain from email address.
+ *
+ * @param string $email
+ * @return string|null
+ */
+ protected function extractDomainFromEmail(string $email): ?string
+ {
+ if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
+ return null;
+ }
+
+ $parts = explode('@', strtolower(trim($email)));
+ return count($parts) === 2 ? $parts[1] : null;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/ExternalUserFactory.php b/api/app/Enterprise/Oidc/ExternalUserFactory.php
new file mode 100644
index 000000000..de69e8801
--- /dev/null
+++ b/api/app/Enterprise/Oidc/ExternalUserFactory.php
@@ -0,0 +1,72 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Models\User;
+use Illuminate\Support\Facades\Hash;
+use Illuminate\Support\Str;
+
+/**
+ * ExternalUserFactory
+ *
+ * Shared factory for creating users coming from external identity providers
+ * (OAuth providers, OIDC connections, etc.).
+ *
+ * Responsibilities:
+ * - Normalize email casing
+ * - Apply UTM data when available
+ * - Populate common meta fields (signup provider, provider user id, registration IP)
+ * - Optionally set a random password for passwordless accounts
+ */
+class ExternalUserFactory
+{
+ /**
+ * Create a verified external user.
+ *
+ * @param string $name
+ * @param string $email
+ * @param string $provider Logical provider key (e.g. 'google', 'stripe', 'oidc')
+ * @param string|null $providerUserId Provider-side user identifier (sub, provider_user_id, etc.)
+ * @param mixed|null $utmData UTM payload (array or JSON string)
+ * @param array $extraMeta Additional meta fields to merge
+ * @param bool $setRandomPassword Whether to set a random password (for SSO-only accounts)
+ */
+ public function createVerifiedExternalUser(
+ string $name,
+ string $email,
+ string $provider,
+ ?string $providerUserId = null,
+ mixed $utmData = null,
+ array $extraMeta = [],
+ bool $setRandomPassword = false,
+ ): User {
+ $normalizedEmail = strtolower($email);
+
+ $meta = array_merge([
+ 'signup_provider' => $provider,
+ 'signup_provider_user_id' => $providerUserId,
+ 'registration_ip' => app()->bound('request') ? request()->ip() : null,
+ ], $extraMeta);
+
+ $attributes = [
+ 'name' => $name,
+ 'email' => $normalizedEmail,
+ 'email_verified_at' => now(),
+ 'utm_data' => is_string($utmData) ? json_decode($utmData, true) : $utmData,
+ 'meta' => $meta,
+ ];
+
+ if ($setRandomPassword) {
+ // Prevent password-based login for SSO accounts
+ $attributes['password'] = Hash::make(Str::random(64));
+ }
+
+ // Use forceFill to bypass fillable restrictions for email_verified_at
+ $user = new User();
+ $user->forceFill($attributes);
+ $user->email_verified_at = now();
+ $user->save();
+
+ return $user;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/IdTokenVerifier.php b/api/app/Enterprise/Oidc/IdTokenVerifier.php
new file mode 100644
index 000000000..0e31307dc
--- /dev/null
+++ b/api/app/Enterprise/Oidc/IdTokenVerifier.php
@@ -0,0 +1,228 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use Firebase\JWT\JWK;
+use Firebase\JWT\JWT;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * ID Token Verifier for OIDC.
+ *
+ * Verifies ID token signatures using JWKS (JSON Web Key Set) from the provider.
+ * Uses firebase/php-jwt library for JWT signature verification.
+ *
+ * How signature verification works:
+ * 1. Extract the JWT header to get the key ID (kid) and algorithm (alg)
+ * 2. Fetch the provider's public keys from JWKS endpoint
+ * 3. Find the matching key using the kid from the token header
+ * 4. Verify the token signature using the public key
+ * 5. If signature is valid, the token was signed by the provider's private key
+ *
+ * JWKS URI resolution (in order):
+ * - Custom jwks_uri from connection.options (for non-standard providers)
+ * - jwks_uri from OpenID configuration discovery (/.well-known/openid-configuration)
+ * - Standard fallback: {issuer}/.well-known/jwks.json
+ */
+class IdTokenVerifier
+{
+ /**
+ * Verify ID token signature using JWKS from the provider.
+ *
+ * @throws \Exception
+ */
+ public function verifySignature(IdentityConnection $connection, string $idToken): void
+ {
+ try {
+ // Decode header to get key ID (kid) and algorithm
+ $parts = explode('.', $idToken);
+ if (count($parts) !== 3) {
+ throw new \Exception('Invalid ID token format');
+ }
+
+ [$headerB64] = $parts;
+ $header = json_decode($this->base64UrlDecode($headerB64), true);
+
+ if (!$header || !isset($header['alg'])) {
+ throw new \Exception('Invalid ID token header');
+ }
+
+ if (!isset($header['kid'])) {
+ throw new \Exception('Missing key ID (kid) in ID token header');
+ }
+
+ // Get JWKS from provider
+ $jwks = $this->getJwks($connection);
+
+ // Parse JWKS and find the matching key
+ $keys = JWK::parseKeySet($jwks, $header['alg']);
+ $kid = $header['kid'];
+
+ if (!isset($keys[$kid])) {
+ throw new \Exception("No matching key found in JWKS for kid: {$kid}");
+ }
+
+ $key = $keys[$kid];
+
+ // Verify signature using firebase/php-jwt
+ // This will throw an exception if signature is invalid
+ $decoded = JWT::decode($idToken, $key);
+
+ Log::debug('OIDC ID token signature verified', [
+ 'connection_id' => $connection->id,
+ 'algorithm' => $header['alg'],
+ 'kid' => $kid,
+ ]);
+ } catch (\Exception $e) {
+ Log::warning('OIDC ID token signature verification failed', [
+ 'connection_id' => $connection->id,
+ 'error' => $e->getMessage(),
+ ]);
+
+ throw new \Exception('ID token signature verification failed: ' . $e->getMessage());
+ }
+ }
+
+ /**
+ * Get JWKS from provider's well-known endpoint.
+ *
+ * Caches the JWKS for 1 hour to reduce network requests.
+ * JWKS typically don't change frequently, but providers may rotate keys.
+ *
+ * JWKS URI resolution order:
+ * 1. Custom jwks_uri from connection options (for non-standard providers)
+ * 2. jwks_uri from OpenID configuration discovery
+ * 3. Standard fallback: /.well-known/jwks.json
+ */
+ protected function getJwks(IdentityConnection $connection): array
+ {
+ $cacheKey = "oidc_jwks_{$connection->issuer}_{$connection->id}";
+
+ return Cache::remember($cacheKey, 3600, function () use ($connection) {
+ // Try multiple methods to find JWKS URI
+ $jwksUri = $this->resolveJwksUri($connection);
+
+ $response = Http::timeout(10)->get($jwksUri);
+
+ if (!$response->successful()) {
+ throw new \Exception("Failed to fetch JWKS from provider: {$jwksUri} (HTTP {$response->status()})");
+ }
+
+ $jwks = $response->json();
+
+ if (!isset($jwks['keys']) || !is_array($jwks['keys']) || empty($jwks['keys'])) {
+ throw new \Exception('Invalid JWKS format: missing or empty keys array');
+ }
+
+ Log::debug('OIDC JWKS fetched', [
+ 'connection_id' => $connection->id,
+ 'jwks_uri' => $jwksUri,
+ 'key_count' => count($jwks['keys']),
+ 'source' => $this->getJwksUriSource($connection),
+ ]);
+
+ return $jwks;
+ });
+ }
+
+ /**
+ * Resolve JWKS URI using multiple fallback strategies.
+ */
+ protected function resolveJwksUri(IdentityConnection $connection): string
+ {
+ // 1. Check for custom jwks_uri in connection options (for non-standard providers)
+ $customJwksUri = $connection->options['jwks_uri'] ?? null;
+ if ($customJwksUri && filter_var($customJwksUri, FILTER_VALIDATE_URL)) {
+ Log::debug('Using custom JWKS URI from connection options', [
+ 'connection_id' => $connection->id,
+ 'jwks_uri' => $customJwksUri,
+ ]);
+ return $customJwksUri;
+ }
+
+ // 2. Try to get JWKS URI from OpenID configuration discovery
+ try {
+ $openIdConfig = $this->getOpenIdConfig($connection);
+ $jwksUri = $openIdConfig['jwks_uri'] ?? null;
+
+ if ($jwksUri && filter_var($jwksUri, FILTER_VALIDATE_URL)) {
+ Log::debug('Using JWKS URI from OpenID configuration', [
+ 'connection_id' => $connection->id,
+ 'jwks_uri' => $jwksUri,
+ ]);
+ return $jwksUri;
+ }
+ } catch (\Exception $e) {
+ Log::warning('Failed to fetch OpenID configuration, using fallback', [
+ 'connection_id' => $connection->id,
+ 'error' => $e->getMessage(),
+ ]);
+ }
+
+ // 3. Standard fallback: construct JWKS URI from issuer
+ $jwksUri = rtrim($connection->issuer, '/') . '/.well-known/jwks.json';
+ Log::debug('Using standard JWKS URI fallback', [
+ 'connection_id' => $connection->id,
+ 'jwks_uri' => $jwksUri,
+ ]);
+
+ return $jwksUri;
+ }
+
+ /**
+ * Get the source of the JWKS URI for logging purposes.
+ */
+ protected function getJwksUriSource(IdentityConnection $connection): string
+ {
+ if (!empty($connection->options['jwks_uri'])) {
+ return 'custom';
+ }
+
+ try {
+ $openIdConfig = $this->getOpenIdConfig($connection);
+ if (!empty($openIdConfig['jwks_uri'])) {
+ return 'openid_config';
+ }
+ } catch (\Exception $e) {
+ // Ignore
+ }
+
+ return 'fallback';
+ }
+
+ /**
+ * Get OpenID configuration from provider.
+ */
+ protected function getOpenIdConfig(IdentityConnection $connection): array
+ {
+ $cacheKey = "oidc_config_{$connection->issuer}";
+
+ return Cache::remember($cacheKey, 3600, function () use ($connection) {
+ $wellKnownUrl = rtrim($connection->issuer, '/') . '/.well-known/openid-configuration';
+
+ $response = Http::timeout(10)->get($wellKnownUrl);
+
+ if (!$response->successful()) {
+ throw new \Exception("Failed to fetch OpenID configuration from: {$wellKnownUrl}");
+ }
+
+ return $response->json();
+ });
+ }
+
+ /**
+ * Base64 URL decode.
+ */
+ protected function base64UrlDecode(string $data): string
+ {
+ return base64_decode(str_pad(
+ strtr($data, '-_', '+/'),
+ strlen($data) % 4,
+ '=',
+ STR_PAD_RIGHT
+ ));
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Models/IdentityConnection.php b/api/app/Enterprise/Oidc/Models/IdentityConnection.php
new file mode 100644
index 000000000..6708d880f
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Models/IdentityConnection.php
@@ -0,0 +1,97 @@
+<?php
+
+namespace App\Enterprise\Oidc\Models;
+
+use App\Models\Workspace;
+use Database\Factories\IdentityConnectionFactory;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+
+class IdentityConnection extends Model
+{
+ use HasFactory;
+
+ /**
+ * Create a new factory instance for the model.
+ */
+ protected static function newFactory()
+ {
+ return IdentityConnectionFactory::new();
+ }
+
+ public const TYPE_OIDC = 'oidc';
+ public const TYPE_SAML = 'saml';
+
+ public const TYPES = [
+ self::TYPE_OIDC,
+ self::TYPE_SAML,
+ ];
+
+ protected $fillable = [
+ 'workspace_id',
+ 'name',
+ 'slug',
+ 'domain',
+ 'type',
+ 'issuer',
+ 'client_id',
+ 'client_secret',
+ 'scopes',
+ 'options',
+ 'redirect_path',
+ 'enabled',
+ ];
+
+ protected $hidden = [
+ 'client_secret',
+ ];
+
+ protected function casts(): array
+ {
+ return [
+ 'scopes' => 'array',
+ 'options' => 'array',
+ 'enabled' => 'boolean',
+ 'client_secret' => 'encrypted',
+ ];
+ }
+
+ public function workspace(): BelongsTo
+ {
+ return $this->belongsTo(Workspace::class);
+ }
+
+ public function userIdentities(): HasMany
+ {
+ return $this->hasMany(UserIdentity::class, 'connection_id');
+ }
+
+ public function getRedirectUrlAttribute(): string
+ {
+ if ($this->redirect_path) {
+ return $this->redirect_path;
+ }
+
+ return front_url("/auth/{$this->slug}/callback");
+ }
+
+ public function scopeEnabled($query)
+ {
+ return $query->where('enabled', true);
+ }
+
+ public function scopeForWorkspace($query, ?int $workspaceId)
+ {
+ return $query->where(function ($q) use ($workspaceId) {
+ $q->whereNull('workspace_id')
+ ->orWhere('workspace_id', $workspaceId);
+ });
+ }
+
+ public function scopeGlobal($query)
+ {
+ return $query->whereNull('workspace_id');
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Models/UserIdentity.php b/api/app/Enterprise/Oidc/Models/UserIdentity.php
new file mode 100644
index 000000000..ed7ff2b92
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Models/UserIdentity.php
@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Enterprise\Oidc\Models;
+
+use App\Models\User;
+use Database\Factories\UserIdentityFactory;
+use Illuminate\Database\Eloquent\Factories\HasFactory;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+class UserIdentity extends Model
+{
+ use HasFactory;
+
+ /**
+ * Create a new factory instance for the model.
+ */
+ protected static function newFactory()
+ {
+ return UserIdentityFactory::new();
+ }
+
+ protected $fillable = [
+ 'user_id',
+ 'connection_id',
+ 'subject',
+ 'email',
+ 'claims',
+ ];
+
+ protected function casts(): array
+ {
+ return [
+ 'claims' => 'array',
+ ];
+ }
+
+ public function user(): BelongsTo
+ {
+ return $this->belongsTo(User::class);
+ }
+
+ public function connection(): BelongsTo
+ {
+ return $this->belongsTo(IdentityConnection::class, 'connection_id');
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Policies/IdentityConnectionPolicy.php b/api/app/Enterprise/Oidc/Policies/IdentityConnectionPolicy.php
new file mode 100644
index 000000000..e96968a09
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Policies/IdentityConnectionPolicy.php
@@ -0,0 +1,110 @@
+<?php
+
+namespace App\Enterprise\Oidc\Policies;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Policies\WorkspacePolicy;
+use Illuminate\Auth\Access\HandlesAuthorization;
+
+class IdentityConnectionPolicy
+{
+ use HandlesAuthorization;
+
+ /**
+ * Determine whether the user can view any models.
+ */
+ public function viewAny(User $user, ?\App\Models\Workspace $workspace = null): bool
+ {
+ if ($workspace === null) {
+ // Global connections - only admins can view
+ return $user->admin;
+ }
+
+ // Workspace-scoped connections - check if user is workspace admin
+ return (new WorkspacePolicy())->adminAction($user, $workspace);
+ }
+
+ /**
+ * Determine whether the user can view the model.
+ */
+ public function view(User $user, IdentityConnection $identityConnection): bool
+ {
+ if ($identityConnection->workspace_id === null) {
+ // Global connection - only admins can view
+ return $user->admin;
+ }
+
+ // Workspace-scoped connection - check if user is workspace admin
+ return (new WorkspacePolicy())->adminAction($user, $identityConnection->workspace);
+ }
+
+ /**
+ * Determine whether the user can create models.
+ */
+ public function create(User $user, ?\App\Models\Workspace $workspace = null): bool
+ {
+ if ($workspace === null) {
+ // Global connection - only admins can create
+ return $user->admin;
+ }
+
+ // Workspace-scoped connection - check if user is workspace admin
+ if (!(new WorkspacePolicy())->adminAction($user, $workspace)) {
+ return false;
+ }
+
+ // For cloud (non-self-hosted), require Pro subscription for creation
+ return $this->hasProAccess($workspace);
+ }
+
+ /**
+ * Determine whether the user can update the model.
+ */
+ public function update(User $user, IdentityConnection $identityConnection): bool
+ {
+ return $this->canModify($user, $identityConnection);
+ }
+
+ /**
+ * Determine whether the user can delete the model.
+ */
+ public function delete(User $user, IdentityConnection $identityConnection): bool
+ {
+ return $this->canModify($user, $identityConnection);
+ }
+
+ /**
+ * Check if user can modify (update/delete) a workspace-scoped connection.
+ */
+ protected function canModify(User $user, IdentityConnection $identityConnection): bool
+ {
+ if ($identityConnection->workspace_id === null) {
+ // Global connection - only admins can modify
+ return $user->admin;
+ }
+
+ // Workspace-scoped connection - check if user is workspace admin
+ if (!(new WorkspacePolicy())->adminAction($user, $identityConnection->workspace)) {
+ return false;
+ }
+
+ // For cloud (non-self-hosted), require Pro subscription for modifications
+ return $this->hasProAccess($identityConnection->workspace);
+ }
+
+ /**
+ * Check if workspace has Pro access (always true for self-hosted).
+ */
+ protected function hasProAccess(Workspace $workspace): bool
+ {
+ // Self-hosted installations don't require Pro
+ if (!pricing_enabled()) {
+ return true;
+ }
+
+ // Cloud installations require Pro subscription
+ return $workspace->is_pro;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/ProvisioningService.php b/api/app/Enterprise/Oidc/ProvisioningService.php
new file mode 100644
index 000000000..5c4832dbd
--- /dev/null
+++ b/api/app/Enterprise/Oidc/ProvisioningService.php
@@ -0,0 +1,277 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Models\UserIdentity;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Laravel\Socialite\Contracts\User as SocialiteUser;
+
+class ProvisioningService
+{
+ public function __construct(
+ private RoleMapper $roleMapper,
+ private DomainJoiner $domainJoiner,
+ private ExternalUserFactory $userFactory,
+ ) {
+ }
+
+ /**
+ * Provision or authenticate a user from OIDC claims.
+ *
+ * @throws \Exception
+ */
+ public function provisionUser(
+ IdentityConnection $connection,
+ SocialiteUser $socialiteUser,
+ array $idTokenClaims
+ ): User {
+ return DB::transaction(function () use ($connection, $socialiteUser, $idTokenClaims) {
+ // Validate ID token claims
+ $this->validateIdToken($connection, $idTokenClaims);
+
+ $subject = $idTokenClaims['sub'];
+
+ // Extract email and name from claims
+ $email = $this->extractEmail($socialiteUser, $idTokenClaims, $connection);
+ $name = $this->extractName($socialiteUser, $idTokenClaims, $connection);
+
+ if (!$email) {
+ throw new \Exception('Email is required for OIDC authentication. Check your field mappings configuration.');
+ }
+
+ // Check for existing UserIdentity
+ $userIdentity = UserIdentity::where('connection_id', $connection->id)
+ ->where('subject', $subject)
+ ->first();
+
+ if ($userIdentity) {
+ // Update claims and email if changed
+ $userIdentity->update([
+ 'email' => $email,
+ 'claims' => $idTokenClaims,
+ ]);
+
+ $user = $userIdentity->user;
+
+ Log::info('OIDC user authenticated', [
+ 'connection_id' => $connection->id,
+ 'user_id' => $user->id,
+ 'subject' => $subject,
+ 'email' => $email,
+ ]);
+ } else {
+ // Check if user with same email exists
+ $existingUser = User::where('email', strtolower($email))->first();
+
+ if ($existingUser) {
+ // Account linking - require explicit action for security
+ Log::warning('OIDC account linking required', [
+ 'connection_id' => $connection->id,
+ 'existing_user_id' => $existingUser->id,
+ 'subject' => $subject,
+ 'email' => $email,
+ ]);
+
+ throw new \Exception(
+ 'An account with this email already exists. Please contact your administrator to link your accounts.'
+ );
+ }
+
+ // Create new user
+ $userName = $name ?? $socialiteUser->getName() ?? explode('@', $email)[0];
+ $user = $this->userFactory->createVerifiedExternalUser(
+ name: $userName,
+ email: $email,
+ provider: 'oidc',
+ providerUserId: $subject,
+ utmData: null,
+ extraMeta: [],
+ setRandomPassword: true,
+ );
+
+ // Create UserIdentity
+ UserIdentity::create([
+ 'user_id' => $user->id,
+ 'connection_id' => $connection->id,
+ 'subject' => $subject,
+ 'email' => $email,
+ 'claims' => $idTokenClaims,
+ ]);
+
+ Log::info('OIDC user provisioned', [
+ 'connection_id' => $connection->id,
+ 'user_id' => $user->id,
+ 'subject' => $subject,
+ 'email' => $email,
+ ]);
+ }
+
+ // Handle workspace membership
+ $this->handleWorkspaceMembership($connection, $user, $idTokenClaims);
+
+ return $user;
+ });
+ }
+
+ /**
+ * Validate ID token claims.
+ *
+ * @throws \Exception
+ */
+ protected function validateIdToken(IdentityConnection $connection, array $claims): void
+ {
+ // Validate issuer
+ if (isset($claims['iss']) && $claims['iss'] !== $connection->issuer) {
+ throw new \Exception('Invalid issuer in ID token');
+ }
+
+ // Validate audience (client_id)
+ $aud = $claims['aud'] ?? null;
+ if (!$aud) {
+ throw new \Exception('Missing audience in ID token');
+ }
+
+ $audArray = is_array($aud) ? $aud : [$aud];
+ if (!in_array($connection->client_id, $audArray)) {
+ throw new \Exception('Invalid audience in ID token');
+ }
+
+ // Validate expiration
+ if (isset($claims['exp']) && $claims['exp'] < time()) {
+ throw new \Exception('ID token has expired');
+ }
+
+ // Validate subject
+ if (empty($claims['sub'])) {
+ throw new \Exception('Missing subject in ID token');
+ }
+ }
+
+ /**
+ * Handle workspace membership based on connection and claims.
+ */
+ protected function handleWorkspaceMembership(
+ IdentityConnection $connection,
+ User $user,
+ array $claims
+ ): void {
+ // Get role from group mapping or default to member
+ $groups = $claims['groups'] ?? $claims['group'] ?? [];
+ $groupsArray = is_array($groups) ? $groups : [$groups];
+ $role = $this->roleMapper->mapGroupsToRole($connection, $groupsArray) ?? 'member';
+
+ // If connection has a workspace_id, ensure membership
+ if ($connection->workspace_id) {
+ $workspace = Workspace::find($connection->workspace_id);
+ if (!$workspace) {
+ return;
+ }
+
+ $wasMember = $user->workspaces()->where('workspaces.id', $workspace->id)->exists();
+ $this->domainJoiner->ensureWorkspaceMembership($user, $workspace, $role);
+
+ Log::info('OIDC workspace membership ensured', [
+ 'connection_id' => $connection->id,
+ 'user_id' => $user->id,
+ 'workspace_id' => $workspace->id,
+ 'role' => $role,
+ 'was_member' => $wasMember,
+ 'groups' => $groupsArray,
+ ]);
+
+ return;
+ }
+
+ // No workspace_id - use domain-based auto-join for global connections
+ $email = $user->email;
+ $workspace = $this->domainJoiner->findWorkspaceForDomain($email);
+
+ if (!$workspace) {
+ return;
+ }
+
+ $wasMember = $user->workspaces()->where('workspaces.id', $workspace->id)->exists();
+ $this->domainJoiner->ensureWorkspaceMembership($user, $workspace, $role);
+
+ Log::info('OIDC workspace membership ensured via domain', [
+ 'connection_id' => $connection->id,
+ 'user_id' => $user->id,
+ 'workspace_id' => $workspace->id,
+ 'role' => $role,
+ 'was_member' => $wasMember,
+ 'email_domain' => $this->extractDomain($email),
+ 'groups' => $groupsArray,
+ ]);
+ }
+
+ /**
+ * Extract email from socialite user or ID token claims.
+ */
+ protected function extractEmail(SocialiteUser $socialiteUser, array $idTokenClaims, IdentityConnection $connection): ?string
+ {
+ // Try socialite user first
+ $email = $socialiteUser->getEmail();
+ if ($email) {
+ return $email;
+ }
+
+ // Get field mappings from connection options
+ $fieldMappings = $connection->options['field_mappings'] ?? [];
+ $emailField = !empty($fieldMappings['email']) ? $fieldMappings['email'] : null;
+
+ // Try mapped field first (if configured)
+ if ($emailField && isset($idTokenClaims[$emailField])) {
+ return $idTokenClaims[$emailField];
+ }
+
+ // Fallback to standard fields
+ return $idTokenClaims['email']
+ ?? $idTokenClaims['email_address']
+ ?? $idTokenClaims['mail']
+ ?? $idTokenClaims['preferred_username'] // Common Keycloak field
+ ?? null;
+ }
+
+ /**
+ * Extract name from socialite user or ID token claims.
+ */
+ protected function extractName(SocialiteUser $socialiteUser, array $idTokenClaims, IdentityConnection $connection): ?string
+ {
+ // Try socialite user first
+ $name = $socialiteUser->getName();
+ if (!empty($name)) {
+ return $name;
+ }
+
+ // Get field mappings from connection options
+ $fieldMappings = $connection->options['field_mappings'] ?? [];
+ $nameField = !empty($fieldMappings['name']) ? $fieldMappings['name'] : null;
+
+ // Try mapped field first (if configured)
+ if ($nameField && isset($idTokenClaims[$nameField]) && !empty($idTokenClaims[$nameField])) {
+ return $idTokenClaims[$nameField];
+ }
+
+ // Fallback to standard fields
+ $trimmedName = trim(($idTokenClaims['given_name'] ?? '') . ' ' . ($idTokenClaims['family_name'] ?? ''));
+
+ return $idTokenClaims['name']
+ ?? $idTokenClaims['display_name']
+ ?? (!empty($trimmedName) ? $trimmedName : null)
+ ?? $idTokenClaims['preferred_username']
+ ?? null;
+ }
+
+ /**
+ * Extract domain from email address.
+ */
+ protected function extractDomain(string $email): ?string
+ {
+ $parts = explode('@', strtolower(trim($email)));
+ return count($parts) === 2 ? $parts[1] : null;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php
new file mode 100644
index 000000000..971453935
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Requests/StoreOidcConnectionRequest.php
@@ -0,0 +1,78 @@
+<?php
+
+namespace App\Enterprise\Oidc\Requests;
+
+use App\Enterprise\Oidc\Rules\ValidOidcDomain;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+class StoreOidcConnectionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ // Authorization handled at controller level
+ return true;
+ }
+
+ public function rules(): array
+ {
+ $workspaceId = $this->route('workspace');
+ $workspaceId = $workspaceId instanceof \App\Models\Workspace ? $workspaceId->id : $workspaceId;
+
+ return [
+ 'name' => ['required', 'string', 'max:255'],
+ 'slug' => [
+ 'required',
+ 'string',
+ 'max:255',
+ 'regex:/^[a-z0-9-]+$/',
+ Rule::unique('identity_connections', 'slug'),
+ ],
+ 'domain' => [
+ 'required',
+ 'string',
+ 'max:255',
+ new ValidOidcDomain(),
+ Rule::unique('identity_connections', 'domain')->where(function ($query) use ($workspaceId) {
+ // Domain must be unique per workspace (or globally if workspace_id is null)
+ if ($workspaceId) {
+ return $query->where(function ($q) use ($workspaceId) {
+ $q->where('workspace_id', $workspaceId)
+ ->orWhereNull('workspace_id');
+ });
+ }
+ return $query->whereNull('workspace_id');
+ }),
+ ],
+ 'issuer' => ['required', 'url'],
+ 'client_id' => ['required', 'string'],
+ 'client_secret' => ['required', 'string'],
+ 'scopes' => ['nullable', 'array'],
+ 'scopes.*' => ['string'],
+ 'options' => ['nullable', 'array'],
+ 'options.field_mappings' => ['nullable', 'array'],
+ 'options.field_mappings.email' => ['nullable', 'string', 'max:255'],
+ 'options.field_mappings.name' => ['nullable', 'string', 'max:255'],
+ 'options.group_role_mappings' => ['nullable', 'array'],
+ 'options.group_role_mappings.*.idp_group' => ['required_with:options.group_role_mappings', 'string', 'max:255'],
+ 'options.group_role_mappings.*.role' => ['required_with:options.group_role_mappings', 'string', Rule::in(['owner', 'admin', 'editor', 'member'])],
+ 'redirect_path' => ['nullable', 'string', 'max:255'],
+ 'enabled' => ['boolean'],
+ ];
+ }
+
+ public function prepareForValidation(): void
+ {
+ // Set default scopes if not provided
+ if (!$this->has('scopes')) {
+ $this->merge([
+ 'scopes' => config('oidc.default_scopes'),
+ ]);
+ }
+
+ // Set default enabled to true
+ if (!$this->has('enabled')) {
+ $this->merge(['enabled' => true]);
+ }
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php
new file mode 100644
index 000000000..c410a21dd
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Requests/UpdateOidcConnectionRequest.php
@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Enterprise\Oidc\Requests;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Rules\ValidOidcDomain;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+class UpdateOidcConnectionRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ // Authorization handled at controller level
+ return true;
+ }
+
+ public function rules(): array
+ {
+ $connection = $this->route('connection');
+ $connectionId = $connection instanceof IdentityConnection ? $connection->id : null;
+ $workspaceId = $connection instanceof IdentityConnection ? $connection->workspace_id : null;
+
+ return [
+ 'name' => ['sometimes', 'required', 'string', 'max:255'],
+ 'slug' => [
+ 'sometimes',
+ 'required',
+ 'string',
+ 'max:255',
+ 'regex:/^[a-z0-9-]+$/',
+ Rule::unique('identity_connections', 'slug')->ignore($connectionId),
+ ],
+ 'domain' => [
+ 'sometimes',
+ 'required',
+ 'string',
+ 'max:255',
+ new ValidOidcDomain(),
+ Rule::unique('identity_connections', 'domain')->ignore($connectionId)->where(function ($query) use ($workspaceId) {
+ // Domain must be unique per workspace (or globally if workspace_id is null)
+ if ($workspaceId) {
+ return $query->where(function ($q) use ($workspaceId) {
+ $q->where('workspace_id', $workspaceId)
+ ->orWhereNull('workspace_id');
+ });
+ }
+ return $query->whereNull('workspace_id');
+ }),
+ ],
+ 'issuer' => ['sometimes', 'required', 'url'],
+ 'client_id' => ['sometimes', 'required', 'string'],
+ 'client_secret' => ['sometimes', 'required', 'string'],
+ 'scopes' => ['nullable', 'array'],
+ 'scopes.*' => ['string'],
+ 'options' => ['nullable', 'array'],
+ 'options.field_mappings' => ['nullable', 'array'],
+ 'options.field_mappings.email' => ['nullable', 'string', 'max:255'],
+ 'options.field_mappings.name' => ['nullable', 'string', 'max:255'],
+ 'options.group_role_mappings' => ['nullable', 'array'],
+ 'options.group_role_mappings.*.idp_group' => ['required_with:options.group_role_mappings', 'string', 'max:255'],
+ 'options.group_role_mappings.*.role' => ['required_with:options.group_role_mappings', 'string', Rule::in(['owner', 'admin', 'editor', 'member'])],
+ 'redirect_path' => ['nullable', 'string', 'max:255'],
+ 'enabled' => ['sometimes', 'boolean'],
+ ];
+ }
+}
diff --git a/api/app/Enterprise/Oidc/RoleMapper.php b/api/app/Enterprise/Oidc/RoleMapper.php
new file mode 100644
index 000000000..5f45f1eda
--- /dev/null
+++ b/api/app/Enterprise/Oidc/RoleMapper.php
@@ -0,0 +1,57 @@
+<?php
+
+namespace App\Enterprise\Oidc;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+
+class RoleMapper
+{
+ /**
+ * Map IdP groups to workspace role based on connection options.
+ *
+ * Role mappings are stored in connection.options.group_role_mappings.
+ *
+ * Returns the highest privilege role found, or null if no match.
+ */
+ public function mapGroupsToRole(IdentityConnection $connection, array $groups): ?string
+ {
+ if (empty($groups)) {
+ return null;
+ }
+
+ $mappings = $connection->options['group_role_mappings'] ?? [];
+ if (empty($mappings)) {
+ return null;
+ }
+
+ // Priority order: owner > admin > editor > member
+ $priority = [
+ 'owner' => 4,
+ 'admin' => 3,
+ 'editor' => 2,
+ 'member' => 1,
+ ];
+
+ $highestRole = null;
+ $highestPriority = 0;
+
+ foreach ($mappings as $mapping) {
+ if (!isset($mapping['idp_group']) || !isset($mapping['role'])) {
+ continue;
+ }
+
+ // Check if this IdP group matches any of the user's groups
+ if (!in_array($mapping['idp_group'], $groups, true)) {
+ continue;
+ }
+
+ $rolePriority = $priority[$mapping['role']] ?? 0;
+ if ($rolePriority > $highestPriority) {
+ $highestPriority = $rolePriority;
+ $highestRole = $mapping['role'];
+ }
+ }
+
+ return $highestRole;
+ }
+}
diff --git a/api/app/Enterprise/Oidc/Rules/ValidOidcDomain.php b/api/app/Enterprise/Oidc/Rules/ValidOidcDomain.php
new file mode 100644
index 000000000..8213a1c34
--- /dev/null
+++ b/api/app/Enterprise/Oidc/Rules/ValidOidcDomain.php
@@ -0,0 +1,96 @@
+<?php
+
+namespace App\Enterprise\Oidc\Rules;
+
+use App\Enterprise\Oidc\DomainValidator;
+use Illuminate\Contracts\Validation\Rule;
+use Illuminate\Support\Facades\Auth;
+
+class ValidOidcDomain implements Rule
+{
+ protected DomainValidator $validator;
+ protected ?string $userDomain = null;
+ protected string $reason = '';
+
+ /**
+ * Create a new rule instance.
+ */
+ public function __construct()
+ {
+ $this->validator = new DomainValidator();
+ }
+
+ /**
+ * Determine if the validation rule passes.
+ *
+ * @param string $attribute
+ * @param mixed $value
+ * @return bool
+ */
+ public function passes($attribute, $value): bool
+ {
+ $user = Auth::user();
+ if (!$user) {
+ $this->reason = 'User not authenticated.';
+ return false;
+ }
+
+ $domain = (string) $value;
+
+ // Validate domain format first
+ if (!$this->isValidDomainFormat($domain)) {
+ $this->reason = 'invalid_format';
+ return false;
+ }
+
+ $this->userDomain = $this->validator->getUserEmailDomain($user);
+
+ // Check if blocked provider
+ if ($this->validator->isBlockedProvider($domain)) {
+ $this->reason = 'blocked_provider';
+ return false;
+ }
+
+ // Check if matches user domain
+ if (!$this->validator->matchesUserDomain($domain, $user->email)) {
+ $this->reason = 'domain_mismatch';
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Validate domain format (structure, label length, valid characters).
+ */
+ protected function isValidDomainFormat(string $domain): bool
+ {
+ // Domain must match proper format: alphanumeric labels separated by dots
+ // Each label: 1-63 chars, alphanumeric or hyphen, can't start/end with hyphen
+ $pattern = '/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/';
+ return preg_match($pattern, $domain) === 1;
+ }
+
+ /**
+ * Get the validation error message.
+ *
+ * @return string
+ */
+ public function message(): string
+ {
+ if ($this->reason === 'invalid_format') {
+ return 'The domain format is invalid.';
+ }
+
+ if ($this->reason === 'blocked_provider') {
+ return 'Common email providers like gmail.com are not allowed. Please contact support if you need assistance.';
+ }
+
+ if ($this->reason === 'domain_mismatch') {
+ $domainHint = $this->userDomain ? " ({$this->userDomain})" : '';
+ return "The domain must match your email domain{$domainHint}.";
+ }
+
+ return 'The domain is invalid.';
+ }
+}
diff --git a/api/app/Http/Controllers/Auth/LoginController.php b/api/app/Http/Controllers/Auth/LoginController.php
index 9042a06be..7fd079a27 100644
--- a/api/app/Http/Controllers/Auth/LoginController.php
+++ b/api/app/Http/Controllers/Auth/LoginController.php
@@ -30,6 +30,19 @@ class LoginController extends Controller
*/
protected function attemptLogin(Request $request)
{
+ // Block password-based login if OIDC force_login is enabled
+ if (config('oidc.force_login', false)) {
+ $hasOidcConnection = \App\Enterprise\Oidc\Models\IdentityConnection::enabled()
+ ->where('type', \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC)
+ ->exists();
+
+ if ($hasOidcConnection) {
+ throw ValidationException::withMessages([
+ $this->username() => ['Password-based login is disabled. Please use OIDC authentication.'],
+ ]);
+ }
+ }
+
// Only set custom TTL if remember me is checked
$guard = $this->guard();
diff --git a/api/app/Http/Controllers/Auth/SsoController.php b/api/app/Http/Controllers/Auth/SsoController.php
new file mode 100644
index 000000000..908c60b8d
--- /dev/null
+++ b/api/app/Http/Controllers/Auth/SsoController.php
@@ -0,0 +1,268 @@
+<?php
+
+namespace App\Http\Controllers\Auth;
+
+use App\Enterprise\Oidc\ConnectionManager;
+use App\Enterprise\Oidc\IdTokenVerifier;
+use App\Http\Controllers\Controller;
+use App\Enterprise\Oidc\ProvisioningService;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Log;
+use Tymon\JWTAuth\JWTGuard;
+
+class SsoController extends Controller
+{
+ public function __construct(
+ private ConnectionManager $connectionManager,
+ private ProvisioningService $provisioningService,
+ private IdTokenVerifier $idTokenVerifier
+ ) {
+ }
+
+ /**
+ * Get redirect URL for OIDC provider authentication.
+ * Returns JSON response so frontend can handle redirect and errors.
+ */
+ public function redirect(string $slug)
+ {
+ $connection = $this->connectionManager->getConnectionBySlug($slug);
+
+ if (!$connection || !$connection->enabled) {
+ return response()->json([
+ 'error' => 'OIDC connection not found or disabled',
+ ], 404);
+ }
+
+ // Verify HTTPS in production
+ if (config('app.env') === 'production' && !request()->secure()) {
+ return response()->json([
+ 'error' => 'HTTPS is required for OIDC authentication',
+ ], 400);
+ }
+
+ try {
+ $driver = $this->connectionManager->buildDriver($connection);
+ $redirectUrl = $driver->getRedirectUrl();
+
+ return response()->json([
+ 'redirect_url' => $redirectUrl,
+ ]);
+ } catch (\Exception $e) {
+ Log::error('OIDC redirect failed', [
+ 'slug' => $slug,
+ 'error' => $e->getMessage(),
+ ]);
+
+
+ return response()->json([
+ 'error' => 'Failed to initiate OIDC authentication',
+ 'message' => $e->getMessage(),
+ ], 500);
+ }
+ }
+
+ /**
+ * Handle OIDC callback from provider.
+ */
+ public function callback(Request $request, string $slug)
+ {
+ $connection = $this->connectionManager->getConnectionBySlug($slug);
+
+ if (!$connection || !$connection->enabled) {
+ abort(404, 'OIDC connection not found or disabled');
+ }
+
+ // Verify HTTPS in production
+ if (config('app.env') === 'production' && !request()->secure()) {
+ abort(400, 'HTTPS is required for OIDC authentication');
+ }
+
+ try {
+ $driver = $this->connectionManager->buildDriver($connection);
+ $driver->setRedirectUrl($connection->redirect_url);
+
+ // Get user from OIDC provider
+ $socialiteUser = $driver->getUser();
+
+ // Get ID token claims from provider's token response
+ $idToken = $driver->getIdToken();
+ $idTokenClaims = [];
+ if ($idToken) {
+ // Verify ID token signature before processing
+ $this->idTokenVerifier->verifySignature($connection, $idToken);
+
+ // Decode ID token payload
+ [$header, $payload, $signature] = explode('.', $idToken);
+ $idTokenClaims = json_decode(base64_decode(str_pad(
+ strtr($payload, '-_', '+/'),
+ strlen($payload) % 4,
+ '=',
+ STR_PAD_RIGHT
+ )), true) ?? [];
+ }
+
+ // Also get claims from socialite user's raw data if available
+ // The ID token claims should already be in the user object from OidcProvider
+ if (is_object($socialiteUser)) {
+ // Try to get raw data if method exists (Socialite User objects have getRaw())
+ if (method_exists($socialiteUser, 'getRaw')) {
+ /** @var \Laravel\Socialite\Two\User $socialiteUser */
+ $raw = $socialiteUser->getRaw();
+ if ($raw && is_array($raw)) {
+ // Merge raw data into ID token claims (raw takes precedence for missing fields)
+ $idTokenClaims = array_merge($idTokenClaims, $raw);
+ }
+ }
+ }
+
+ // If email is missing from ID token, try fetching from userinfo endpoint
+ if (empty($idTokenClaims['email']) && !$socialiteUser->getEmail()) {
+ try {
+ $accessToken = $driver->getAccessToken();
+
+ if ($accessToken) {
+ // Get OpenID config from provider (we need to access it via the provider)
+ // For now, construct userinfo URL from issuer
+ $issuer = rtrim($connection->issuer, '/');
+ $userInfoUrl = $issuer . '/userinfo';
+
+ $userInfoResponse = \Illuminate\Support\Facades\Http::withHeaders([
+ 'Accept' => 'application/json',
+ 'Authorization' => 'Bearer ' . $accessToken,
+ ])->get($userInfoUrl);
+
+ if ($userInfoResponse->successful()) {
+ $userInfo = $userInfoResponse->json();
+ // Merge userinfo claims into ID token claims
+ $idTokenClaims = array_merge($idTokenClaims, $userInfo);
+ }
+ }
+ } catch (\Exception $e) {
+ Log::warning('OIDC callback failed to fetch userinfo', [
+ 'slug' => $slug,
+ 'error' => $e->getMessage(),
+ ]);
+ }
+ }
+
+ // Check if user already exists before provisioning
+ $email = $socialiteUser->getEmail() ?? $idTokenClaims['email'] ?? null;
+ $existingUser = null;
+ if ($email) {
+ $existingUser = \App\Models\User::where('email', strtolower($email))->first();
+ }
+
+ // Provision or authenticate user
+ $user = $this->provisioningService->provisionUser(
+ $connection,
+ $socialiteUser,
+ $idTokenClaims
+ );
+
+ // Determine if this is a new user
+ $isNewUser = !$existingUser || $existingUser->id !== $user->id;
+
+ // Check if user is blocked
+ if ($user->is_blocked) {
+ abort(403, 'Your account has been blocked. Please contact support.');
+ }
+
+ // Login user using JWT guard (same as LoginController)
+ /** @var JWTGuard $guard */
+ $guard = Auth::guard('api');
+ $token = (string) $guard->login($user);
+ $expiration = $guard->getPayload()->get('exp');
+
+ // Get intended URL or default to home
+ $intendedUrl = $request->cookie('intended_url') ?? '/home';
+
+ // Return JSON response for API (when Accept: application/json header is present)
+ if ($request->expectsJson() || $request->wantsJson() || $request->header('Accept') === 'application/json') {
+ return response()->json([
+ 'token' => $token,
+ 'token_type' => 'bearer',
+ 'expires_in' => $expiration - time(),
+ 'user' => $user,
+ 'new_user' => $isNewUser,
+ 'redirect_url' => $intendedUrl,
+ ]);
+ }
+
+ // For web requests, redirect with token in cookie or session
+ return redirect($intendedUrl)->with('auth_token', $token);
+ } catch (\Exception $e) {
+ Log::error('OIDC callback failed', [
+ 'slug' => $slug,
+ 'error' => $e->getMessage(),
+ 'trace' => $e->getTraceAsString(),
+ ]);
+
+ $errorMessage = $e->getMessage();
+
+ // Preserve HTTP exception status codes (e.g., 403 for blocked users)
+ $statusCode = 400;
+ if ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
+ $statusCode = $e->getStatusCode();
+ }
+
+ if ($request->expectsJson()) {
+ return response()->json([
+ 'message' => $errorMessage,
+ ], $statusCode);
+ }
+
+ // Redirect to login with error
+ return redirect()->route('login')
+ ->withErrors(['oidc' => $errorMessage]);
+ }
+ }
+
+ /**
+ * Get OIDC connection options for an email address.
+ * Used by login form to determine if OIDC is available and should redirect.
+ */
+ public function getOptionsForEmail(Request $request)
+ {
+ $request->validate([
+ 'email' => ['required', 'email'],
+ ]);
+
+ $email = strtolower($request->input('email'));
+ $domain = $this->extractDomain($email);
+
+ if (!$domain) {
+ return response()->json([
+ 'action' => 'fallback',
+ ]);
+ }
+
+ // Find enabled OIDC connection matching domain
+ // Domain is stored directly on the connection record
+ $connection = \App\Enterprise\Oidc\Models\IdentityConnection::enabled()
+ ->where('type', \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC)
+ ->where('domain', $domain)
+ ->first();
+
+ if (!$connection) {
+ $forced = config('oidc.force_login', false);
+ return response()->json([
+ 'action' => $forced ? 'blocked' : 'fallback',
+ ]);
+ }
+
+ return response()->json([
+ 'action' => 'redirect',
+ 'slug' => $connection->slug,
+ ]);
+ }
+
+ /**
+ * Extract domain from email address.
+ */
+ protected function extractDomain(string $email): ?string
+ {
+ $parts = explode('@', strtolower(trim($email)));
+ return count($parts) === 2 ? $parts[1] : null;
+ }
+}
diff --git a/api/app/Http/Controllers/Content/FeatureFlagsController.php b/api/app/Http/Controllers/Content/FeatureFlagsController.php
index 86772efa2..8109ee7d5 100644
--- a/api/app/Http/Controllers/Content/FeatureFlagsController.php
+++ b/api/app/Http/Controllers/Content/FeatureFlagsController.php
@@ -45,12 +45,26 @@ class FeatureFlagsController extends Controller
'custom_code' => [
'enable_self_hosted' => (bool) config('opnform.custom_code.enable_self_hosted', false),
],
+ 'oidc' => [
+ 'available' => $this->isOidcAvailable(),
+ 'forced' => config('oidc.force_login', false) && $this->isOidcAvailable(),
+ ],
];
});
return response()->json($featureFlags);
}
+ /**
+ * Check if OIDC is available (at least one enabled connection exists).
+ */
+ private function isOidcAvailable(): bool
+ {
+ return \App\Enterprise\Oidc\Models\IdentityConnection::enabled()
+ ->where('type', \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC)
+ ->exists();
+ }
+
/**
* Get the application version from Docker environment or fallback
*/
diff --git a/api/app/Http/Controllers/Settings/OidcConnectionController.php b/api/app/Http/Controllers/Settings/OidcConnectionController.php
new file mode 100644
index 000000000..fd7253ba9
--- /dev/null
+++ b/api/app/Http/Controllers/Settings/OidcConnectionController.php
@@ -0,0 +1,135 @@
+<?php
+
+namespace App\Http\Controllers\Settings;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Requests\StoreOidcConnectionRequest;
+use App\Enterprise\Oidc\Requests\UpdateOidcConnectionRequest;
+use App\Http\Controllers\Controller;
+use App\Models\Workspace;
+
+class OidcConnectionController extends Controller
+{
+ /**
+ * List OIDC connections for a workspace.
+ */
+ public function index(Workspace $workspace)
+ {
+ $this->authorize('viewAny', [IdentityConnection::class, $workspace]);
+
+ // Show workspace-scoped and global connections
+ // Eager load workspace relationship to prevent N+1 queries
+ $connections = IdentityConnection::with('workspace')
+ ->where(function ($q) use ($workspace) {
+ $q->where('workspace_id', $workspace->id)
+ ->orWhereNull('workspace_id');
+ })
+ ->get()
+ ->map(function ($connection) {
+ return $this->formatConnection($connection);
+ });
+
+ return response()->json($connections);
+ }
+
+ /**
+ * Store a new OIDC connection.
+ */
+ public function store(StoreOidcConnectionRequest $request, Workspace $workspace)
+ {
+ $this->authorize('create', [IdentityConnection::class, $workspace]);
+
+ $data = $request->validated();
+
+ // Enforce single OIDC connection per workspace
+ $existing = IdentityConnection::where('workspace_id', $workspace->id)
+ ->where('type', IdentityConnection::TYPE_OIDC)
+ ->first();
+
+ if ($existing) {
+ abort(422, 'This workspace already has an OIDC connection. Please update or delete the existing one.');
+ }
+
+ $data['workspace_id'] = $workspace->id;
+
+ // Generate redirect URL if not provided
+ if (empty($data['redirect_path'])) {
+ $data['redirect_path'] = front_url("/auth/{$data['slug']}/callback");
+ }
+
+ $connection = IdentityConnection::create($data);
+
+ return response()->json($this->formatConnection($connection), 201);
+ }
+
+ /**
+ * Show a specific OIDC connection.
+ */
+ public function show(Workspace $workspace, IdentityConnection $connection)
+ {
+ $this->authorize('view', $connection);
+
+ return response()->json($this->formatConnection($connection));
+ }
+
+ /**
+ * Update an OIDC connection.
+ */
+ public function update(UpdateOidcConnectionRequest $request, Workspace $workspace, IdentityConnection $connection)
+ {
+ $this->authorize('update', $connection);
+
+ $data = $request->validated();
+
+ // Don't update client_secret if not provided
+ if (!isset($data['client_secret'])) {
+ unset($data['client_secret']);
+ }
+
+ // Merge options if provided (to preserve other options)
+ if (isset($data['options']) && is_array($data['options'])) {
+ $existingOptions = $connection->options ?? [];
+ $data['options'] = array_merge($existingOptions, $data['options']);
+ }
+
+ $connection->update($data);
+
+ return response()->json($this->formatConnection($connection));
+ }
+
+ /**
+ * Delete an OIDC connection.
+ */
+ public function destroy(Workspace $workspace, IdentityConnection $connection)
+ {
+ $this->authorize('delete', $connection);
+
+ $connection->delete();
+
+ return response()->json([], 204);
+ }
+
+ /**
+ * Format connection for API response (hide sensitive data).
+ */
+ protected function formatConnection(IdentityConnection $connection): array
+ {
+ return [
+ 'id' => $connection->id,
+ 'workspace_id' => $connection->workspace_id,
+ 'name' => $connection->name,
+ 'slug' => $connection->slug,
+ 'domain' => $connection->domain,
+ 'type' => $connection->type,
+ 'issuer' => $connection->issuer,
+ 'client_id' => $connection->client_id,
+ // Never expose client_secret
+ 'scopes' => $connection->scopes,
+ 'options' => $connection->options, // Includes group_role_mappings
+ 'redirect_url' => $connection->redirect_url,
+ 'enabled' => $connection->enabled,
+ 'created_at' => $connection->created_at,
+ 'updated_at' => $connection->updated_at,
+ ];
+ }
+}
diff --git a/api/app/Models/User.php b/api/app/Models/User.php
index 04a5dd816..92997f787 100644
--- a/api/app/Models/User.php
+++ b/api/app/Models/User.php
@@ -326,6 +326,16 @@ class User extends Authenticatable implements JWTSubject, CachableAttributes
return $this->hasMany(OAuthProvider::class);
}
+ /**
+ * Get the OIDC user identities.
+ *
+ * @return \Illuminate\Database\Eloquent\Relations\HasMany
+ */
+ public function userIdentities()
+ {
+ return $this->hasMany(\App\Enterprise\Oidc\Models\UserIdentity::class, 'user_id');
+ }
+
/**
* @return int
*/
diff --git a/api/app/Models/Workspace.php b/api/app/Models/Workspace.php
index cd60e8963..915b7af7b 100644
--- a/api/app/Models/Workspace.php
+++ b/api/app/Models/Workspace.php
@@ -238,6 +238,16 @@ class Workspace extends Model implements CachableAttributes
return $this->hasMany(Form::class);
}
+ /**
+ * Get the OIDC identity connections for this workspace.
+ *
+ * @return \Illuminate\Database\Eloquent\Relations\HasMany
+ */
+ public function identityConnections()
+ {
+ return $this->hasMany(\App\Enterprise\Oidc\Models\IdentityConnection::class);
+ }
+
/**
* Check if the given OAuthProvider ID belongs to any user in this workspace.
*
diff --git a/api/app/Providers/AppServiceProvider.php b/api/app/Providers/AppServiceProvider.php
index 675e8d118..fd23b2916 100644
--- a/api/app/Providers/AppServiceProvider.php
+++ b/api/app/Providers/AppServiceProvider.php
@@ -65,6 +65,12 @@ class AppServiceProvider extends ServiceProvider
Route::bind('user', function ($value) {
return \App\Models\User::findOrFail((int) $value);
});
+
+ // OIDC connection binding - load with workspace relationship for policy checks
+ Route::bind('connection', function ($value) {
+ return \App\Enterprise\Oidc\Models\IdentityConnection::with('workspace')
+ ->findOrFail((int) $value);
+ });
}
/**
diff --git a/api/app/Providers/AuthServiceProvider.php b/api/app/Providers/AuthServiceProvider.php
index 974e95449..04c2c89c1 100644
--- a/api/app/Providers/AuthServiceProvider.php
+++ b/api/app/Providers/AuthServiceProvider.php
@@ -33,6 +33,7 @@ class AuthServiceProvider extends ServiceProvider
Template::class => TemplatePolicy::class,
OAuthProvider::class => OAuthProviderPolicy::class,
PersonalAccessToken::class => PersonalAccessTokenPolicy::class,
+ \App\Enterprise\Oidc\Models\IdentityConnection::class => \App\Enterprise\Oidc\Policies\IdentityConnectionPolicy::class,
];
/**
diff --git a/api/app/Service/OAuth/OAuthUserService.php b/api/app/Service/OAuth/OAuthUserService.php
index 9fc0e2e81..460d989da 100644
--- a/api/app/Service/OAuth/OAuthUserService.php
+++ b/api/app/Service/OAuth/OAuthUserService.php
@@ -4,6 +4,7 @@ namespace App\Service\OAuth;
use App\Integrations\OAuth\OAuthProviderService;
use App\Models\User;
+use App\Enterprise\Oidc\ExternalUserFactory;
use App\Service\WorkspaceInviteService;
use Illuminate\Http\Exceptions\HttpResponseException;
@@ -24,7 +25,8 @@ use Illuminate\Http\Exceptions\HttpResponseException;
class OAuthUserService
{
public function __construct(
- private OAuthContextService $contextService
+ private OAuthContextService $contextService,
+ private ExternalUserFactory $userFactory,
) {
}
@@ -75,17 +77,13 @@ class OAuthUserService
// For widget flows: gets from session context
$utmData = $this->contextService->getUtmData() ?? $this->contextService->getWidgetContext()['utm_data'] ?? null;
- $user = User::create([
- 'name' => $userData['name'],
- 'email' => $email,
- 'email_verified_at' => now(),
- 'utm_data' => is_string($utmData) ? json_decode($utmData, true) : $utmData,
- 'meta' => [
- 'signup_provider' => $providerService->value,
- 'signup_provider_user_id' => $userData['provider_user_id'],
- 'registration_ip' => request()->ip()
- ],
- ]);
+ $user = $this->userFactory->createVerifiedExternalUser(
+ name: $userData['name'],
+ email: $email,
+ provider: $providerService->value,
+ providerUserId: $userData['provider_user_id'] ?? null,
+ utmData: $utmData,
+ );
// Get workspace and role using WorkspaceInviteService
$workspaceInviteService = app(WorkspaceInviteService::class);
diff --git a/api/config/oidc.php b/api/config/oidc.php
new file mode 100644
index 000000000..4b6ff272d
--- /dev/null
+++ b/api/config/oidc.php
@@ -0,0 +1,79 @@
+<?php
+
+return [
+ /*
+ |--------------------------------------------------------------------------
+ | Default OIDC Scopes
+ |--------------------------------------------------------------------------
+ |
+ | Default scopes to request from the identity provider.
+ |
+ */
+ 'default_scopes' => ['openid', 'profile', 'email'],
+
+ /*
+ |--------------------------------------------------------------------------
+ | Force OIDC Login
+ |--------------------------------------------------------------------------
+ |
+ | When enabled and at least one OIDC connection exists, password-based
+ | login will be disabled.
+ |
+ */
+ 'force_login' => env('OIDC_FORCE_LOGIN', false),
+
+ /*
+ |--------------------------------------------------------------------------
+ | Blocked Email Providers
+ |--------------------------------------------------------------------------
+ |
+ | List of common email provider domains that are not allowed for OIDC
+ | connections. Users must use their own organization's email domain.
+ |
+ */
+ 'blocked_email_providers' => [
+ // Google
+ 'gmail.com',
+ 'googlemail.com',
+ // Microsoft
+ 'outlook.com',
+ 'hotmail.com',
+ 'live.com',
+ 'msn.com',
+ // Yahoo
+ 'yahoo.com',
+ 'yahoo.co.uk',
+ 'ymail.com',
+ 'rocketmail.com',
+ // Apple
+ 'icloud.com',
+ 'me.com',
+ 'mac.com',
+ // AOL
+ 'aol.com',
+ // ProtonMail
+ 'protonmail.com',
+ 'proton.me',
+ // Other consumer providers
+ 'mail.com',
+ 'gmx.com',
+ 'gmx.de',
+ 'gmx.net',
+ 'zoho.com',
+ 'yandex.com',
+ 'yandex.ru',
+ 'mail.ru',
+ 'inbox.ru',
+ 'bk.ru',
+ 'list.ru',
+ 'fastmail.com',
+ 'fastmail.fm',
+ // Chinese providers
+ '163.com',
+ 'qq.com',
+ 'sina.com',
+ 'sohu.com',
+ '126.com',
+ 'aliyun.com',
+ ],
+];
diff --git a/api/database/factories/IdentityConnectionFactory.php b/api/database/factories/IdentityConnectionFactory.php
new file mode 100644
index 000000000..f644d7d83
--- /dev/null
+++ b/api/database/factories/IdentityConnectionFactory.php
@@ -0,0 +1,82 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Models\Workspace;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Enterprise\Oidc\Models\IdentityConnection>
+ */
+class IdentityConnectionFactory extends Factory
+{
+ protected $model = IdentityConnection::class;
+
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array
+ {
+ return [
+ 'workspace_id' => null,
+ 'name' => 'Test Connection ' . $this->faker->randomNumber(4) . ' SSO',
+ 'slug' => 'test-connection-' . $this->faker->randomNumber(4),
+ 'domain' => 'example' . $this->faker->randomNumber(3) . '.com',
+ 'type' => IdentityConnection::TYPE_OIDC,
+ 'issuer' => 'https://idp.example' . $this->faker->randomNumber(3) . '.com',
+ 'client_id' => \Illuminate\Support\Str::uuid()->toString(),
+ 'client_secret' => \Illuminate\Support\Str::random(32),
+ 'scopes' => ['openid', 'profile', 'email'],
+ 'options' => [],
+ 'redirect_path' => null,
+ 'enabled' => true,
+ ];
+ }
+
+ /**
+ * Indicate that the connection is for a workspace.
+ */
+ public function forWorkspace(?Workspace $workspace = null): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'workspace_id' => $workspace?->id ?? Workspace::factory(),
+ ]);
+ }
+
+ /**
+ * Indicate that the connection is disabled.
+ */
+ public function disabled(): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'enabled' => false,
+ ]);
+ }
+
+ /**
+ * Set role mappings.
+ */
+ public function withRoleMappings(array $mappings): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'options' => array_merge($attributes['options'] ?? [], [
+ 'group_role_mappings' => $mappings,
+ ]),
+ ]);
+ }
+
+ /**
+ * Set field mappings.
+ */
+ public function withFieldMappings(array $mappings): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'options' => array_merge($attributes['options'] ?? [], [
+ 'field_mappings' => $mappings,
+ ]),
+ ]);
+ }
+}
diff --git a/api/database/factories/UserIdentityFactory.php b/api/database/factories/UserIdentityFactory.php
new file mode 100644
index 000000000..5a333c525
--- /dev/null
+++ b/api/database/factories/UserIdentityFactory.php
@@ -0,0 +1,36 @@
+<?php
+
+namespace Database\Factories;
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Models\UserIdentity;
+use App\Models\User;
+use Illuminate\Database\Eloquent\Factories\Factory;
+
+/**
+ * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Enterprise\Oidc\Models\UserIdentity>
+ */
+class UserIdentityFactory extends Factory
+{
+ protected $model = UserIdentity::class;
+
+ /**
+ * Define the model's default state.
+ *
+ * @return array<string, mixed>
+ */
+ public function definition(): array
+ {
+ return [
+ 'user_id' => User::factory(),
+ 'connection_id' => IdentityConnection::factory(),
+ 'subject' => $this->faker->uuid(),
+ 'email' => $this->faker->email(),
+ 'claims' => [
+ 'sub' => $this->faker->uuid(),
+ 'email' => $this->faker->email(),
+ 'name' => $this->faker->name,
+ ],
+ ];
+ }
+}
diff --git a/api/database/factories/WorkspaceFactory.php b/api/database/factories/WorkspaceFactory.php
index 2bf3de9d5..6d8734fad 100644
--- a/api/database/factories/WorkspaceFactory.php
+++ b/api/database/factories/WorkspaceFactory.php
@@ -17,7 +17,7 @@ class WorkspaceFactory extends Factory
public function definition()
{
return [
- 'name' => $this->faker->company,
+ 'name' => 'Test Workspace ' . $this->faker->randomNumber(4),
'icon' => '🧪',
];
}
diff --git a/api/database/migrations/2025_11_17_105202_create_identity_connections_table.php b/api/database/migrations/2025_11_17_105202_create_identity_connections_table.php
new file mode 100644
index 000000000..b517296ef
--- /dev/null
+++ b/api/database/migrations/2025_11_17_105202_create_identity_connections_table.php
@@ -0,0 +1,53 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('identity_connections', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('workspace_id')->nullable()->constrained()->cascadeOnDelete();
+ $table->string('name');
+ $table->string('slug')->unique();
+ $table->string('domain'); // Email domain for routing users to this connection
+ $table->string('type')->default('oidc'); // 'oidc' or 'saml' for future
+ $table->string('issuer');
+ $table->string('client_id');
+ $table->text('client_secret'); // Use text to accommodate encrypted values
+ $table->json('scopes')->nullable();
+ $table->json('options')->nullable(); // Stores role mappings: { "group_role_mappings": [...] }
+ $table->string('redirect_path')->nullable();
+ $table->boolean('enabled')->default(true);
+ $table->timestamps();
+
+ $table->index(['workspace_id', 'enabled']);
+ $table->index('slug');
+ $table->index('domain');
+
+ // Enforce single OIDC connection per workspace
+ // Note: NULL workspace_id values are allowed multiple times (for global connections)
+ // Only non-NULL workspace_id values are enforced to be unique per type
+ $table->unique(['workspace_id', 'type'], 'unique_workspace_type');
+
+ // Domain uniqueness: per workspace OR globally
+ // For workspace-scoped: domain must be unique within that workspace
+ // For global (NULL workspace_id): domain must be globally unique
+ // This is enforced via application-level validation, as DB unique constraints
+ // don't handle NULL workspace_id well (PostgreSQL treats NULLs as distinct)
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('identity_connections');
+ }
+};
diff --git a/api/database/migrations/2025_11_17_105205_create_user_identities_table.php b/api/database/migrations/2025_11_17_105205_create_user_identities_table.php
new file mode 100644
index 000000000..1fd4b0e83
--- /dev/null
+++ b/api/database/migrations/2025_11_17_105205_create_user_identities_table.php
@@ -0,0 +1,36 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ // Drop table if it exists (from failed migration) to ensure clean state
+ Schema::dropIfExists('user_identities');
+
+ Schema::create('user_identities', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('user_id')->constrained()->cascadeOnDelete();
+ $table->foreignId('connection_id')->constrained('identity_connections')->cascadeOnDelete();
+ $table->string('subject');
+ $table->string('email')->index();
+ $table->json('claims')->nullable();
+ $table->timestamps();
+
+ $table->unique(['connection_id', 'subject']);
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('user_identities');
+ }
+};
diff --git a/api/routes/api.php b/api/routes/api.php
index 0c2280598..b8e71a91f 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -140,6 +140,15 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::put('/', [WorkspaceController::class, 'update'])->name('update');
Route::delete('/', [WorkspaceController::class, 'delete'])->name('delete');
+ // OIDC Connections
+ Route::prefix('oidc-connections')->name('oidc-connections.')->group(function () {
+ Route::get('/', [\App\Http\Controllers\Settings\OidcConnectionController::class, 'index'])->name('index');
+ Route::post('/', [\App\Http\Controllers\Settings\OidcConnectionController::class, 'store'])->name('store');
+ Route::get('/{connection}', [\App\Http\Controllers\Settings\OidcConnectionController::class, 'show'])->name('show');
+ Route::patch('/{connection}', [\App\Http\Controllers\Settings\OidcConnectionController::class, 'update'])->name('update');
+ Route::delete('/{connection}', [\App\Http\Controllers\Settings\OidcConnectionController::class, 'destroy'])->name('destroy');
+ });
+
Route::middleware('pro-form')->group(function () {
Route::get('form-stats/{form}', [FormStatsController::class, 'getFormStats'])->name('form.stats');
Route::get('form-stats-details/{form}', [FormStatsController::class, 'getFormStatsDetails'])->name('form.stats-details');
@@ -288,6 +297,9 @@ Route::group(['middleware' => 'guest:api'], function () {
Route::post('email/verify/{user}', [VerificationController::class, 'verify'])->name('verification.verify');
Route::post('email/resend', [VerificationController::class, 'resend']);
+
+ // OIDC email lookup endpoint (for login flow)
+ Route::post('auth/oidc/options', [\App\Http\Controllers\Auth\SsoController::class, 'getOptionsForEmail'])->name('sso.options');
});
Route::group(['prefix' => 'appsumo'], function () {
@@ -304,6 +316,14 @@ Route::prefix('oauth')->name('oauth.')->group(function () {
Route::post('/widget-callback/{provider}', [OAuthController::class, 'handleWidgetCallback'])->name('widget.callback');
});
+/*
+ * 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::get('/{slug}/callback', [\App\Http\Controllers\Auth\SsoController::class, 'callback'])->name('callback');
+});
+
/*
* Public Forms related routes
*/
diff --git a/api/tests/Feature/Enterprise/Oidc/ConnectionManagerTest.php b/api/tests/Feature/Enterprise/Oidc/ConnectionManagerTest.php
new file mode 100644
index 000000000..a44d1dab5
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/ConnectionManagerTest.php
@@ -0,0 +1,65 @@
+<?php
+
+use App\Enterprise\Oidc\Adapters\OAuthOidcDriver;
+use App\Enterprise\Oidc\ConnectionManager;
+use App\Enterprise\Oidc\Models\IdentityConnection;
+
+uses()->group('oidc', 'feature');
+
+describe('ConnectionManager', function () {
+ it('builds OAuthOidcDriver instance', function () {
+ $connection = IdentityConnection::factory()->create();
+ $manager = new ConnectionManager();
+
+ $driver = $manager->buildDriver($connection);
+
+ expect($driver)->toBeInstanceOf(OAuthOidcDriver::class);
+ });
+
+ it('gets connection by slug when enabled', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-connection',
+ 'enabled' => true,
+ 'type' => IdentityConnection::TYPE_OIDC,
+ ]);
+
+ $manager = new ConnectionManager();
+ $found = $manager->getConnectionBySlug('test-connection');
+
+ expect($found)->not->toBeNull();
+ expect($found->id)->toBe($connection->id);
+ });
+
+ it('returns null for disabled connection', function () {
+ IdentityConnection::factory()->create([
+ 'slug' => 'disabled-connection',
+ 'enabled' => false,
+ 'type' => IdentityConnection::TYPE_OIDC,
+ ]);
+
+ $manager = new ConnectionManager();
+ $found = $manager->getConnectionBySlug('disabled-connection');
+
+ expect($found)->toBeNull();
+ });
+
+ it('returns null for non-existent slug', function () {
+ $manager = new ConnectionManager();
+ $found = $manager->getConnectionBySlug('non-existent');
+
+ expect($found)->toBeNull();
+ });
+
+ it('only returns OIDC type connections', function () {
+ IdentityConnection::factory()->create([
+ 'slug' => 'saml-connection',
+ 'enabled' => true,
+ 'type' => IdentityConnection::TYPE_SAML,
+ ]);
+
+ $manager = new ConnectionManager();
+ $found = $manager->getConnectionBySlug('saml-connection');
+
+ expect($found)->toBeNull();
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/DomainJoinerTest.php b/api/tests/Feature/Enterprise/Oidc/DomainJoinerTest.php
new file mode 100644
index 000000000..97dc88a75
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/DomainJoinerTest.php
@@ -0,0 +1,115 @@
+<?php
+
+use App\Enterprise\Oidc\DomainJoiner;
+use App\Models\User;
+use App\Models\Workspace;
+use Tests\TestHelpers;
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+describe('DomainJoiner', function () {
+ it('extracts domain from email', function () {
+ $joiner = new DomainJoiner();
+
+ // Use reflection to access protected method
+ $reflection = new ReflectionClass(DomainJoiner::class);
+ $method = $reflection->getMethod('extractDomain');
+ $method->setAccessible(true);
+
+ expect($method->invoke($joiner, '[email protected]'))->toBe('example.com');
+ expect($method->invoke($joiner, '[email protected]'))->toBe('subdomain.example.com');
+ expect($method->invoke($joiner, '[email protected]'))->toBe('example.com'); // Lowercase
+ });
+
+ it('returns null for invalid email', function () {
+ $joiner = new DomainJoiner();
+
+ $reflection = new ReflectionClass(DomainJoiner::class);
+ $method = $reflection->getMethod('extractDomain');
+ $method->setAccessible(true);
+
+ expect($method->invoke($joiner, 'invalid-email'))->toBeNull();
+ // 'user@' splits to ['user', ''] which has count 2, so returns '' (empty string)
+ expect($method->invoke($joiner, 'user@'))->toBe('');
+ // '@example.com' actually extracts to 'example.com' - this is expected behavior
+ // The method splits by '@' and takes the second part if count is 2
+ // So '@example.com' becomes ['', 'example.com'] which has count 2
+ // This is acceptable behavior - invalid emails should be validated elsewhere
+ });
+
+ it('finds workspace by domain from settings', function () {
+ $workspace = Workspace::factory()->create([
+ 'settings' => [
+ 'oidc' => [
+ 'allowed_domain' => 'example.com',
+ ],
+ ],
+ ]);
+
+ $joiner = new DomainJoiner();
+ $found = $joiner->findWorkspaceForDomain('[email protected]');
+
+ expect($found)->not->toBeNull();
+ expect($found->id)->toBe($workspace->id);
+ });
+
+ it('returns null when no workspace matches domain', function () {
+ Workspace::factory()->create([
+ 'settings' => [
+ 'oidc' => [
+ 'allowed_domain' => 'other.com',
+ ],
+ ],
+ ]);
+
+ $joiner = new DomainJoiner();
+ $found = $joiner->findWorkspaceForDomain('[email protected]');
+
+ expect($found)->toBeNull();
+ });
+
+ it('ensures workspace membership for new user', function () {
+ $user = $this->createUser();
+ $workspace = Workspace::factory()->create();
+
+ $joiner = new DomainJoiner();
+ $joiner->ensureWorkspaceMembership($user, $workspace, 'admin');
+
+ $user->refresh();
+ // Load pivot with role column
+ $workspaceRelation = $user->workspaces()->withPivot('role')->where('workspaces.id', $workspace->id)->first();
+ expect($workspaceRelation)->not->toBeNull();
+ expect($workspaceRelation->pivot->role)->toBe('admin');
+ });
+
+ it('updates role for existing workspace member', function () {
+ $user = $this->createUser();
+ $workspace = Workspace::factory()->create();
+
+ // Add user as member first
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ $joiner = new DomainJoiner();
+ $joiner->ensureWorkspaceMembership($user, $workspace, 'admin');
+
+ $user->refresh();
+ // Load pivot with role column
+ $workspaceRelation = $user->workspaces()->withPivot('role')->where('workspaces.id', $workspace->id)->first();
+ expect($workspaceRelation)->not->toBeNull();
+ expect($workspaceRelation->pivot->role)->toBe('admin');
+ });
+
+ it('does not duplicate membership when already exists', function () {
+ $user = $this->createUser();
+ $workspace = Workspace::factory()->create();
+
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ $joiner = new DomainJoiner();
+ $joiner->ensureWorkspaceMembership($user, $workspace, 'admin');
+
+ // Should still be only one membership
+ expect($user->workspaces()->where('workspaces.id', $workspace->id)->count())->toBe(1);
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/ExternalUserFactoryTest.php b/api/tests/Feature/Enterprise/Oidc/ExternalUserFactoryTest.php
new file mode 100644
index 000000000..b9c5c0655
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/ExternalUserFactoryTest.php
@@ -0,0 +1,109 @@
+<?php
+
+use App\Enterprise\Oidc\ExternalUserFactory;
+use Tests\TestHelpers;
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+describe('ExternalUserFactory', function () {
+
+ it('creates verified user with normalized email', function () {
+ $factory = new ExternalUserFactory();
+
+ $user = $factory->createVerifiedExternalUser(
+ name: 'John Doe',
+ email: '[email protected]',
+ provider: 'google',
+ );
+
+ expect($user->email)->toBe('[email protected]');
+ expect($user->email_verified_at)->not->toBeNull();
+ expect($user->name)->toBe('John Doe');
+ });
+
+ it('sets provider metadata', function () {
+ $factory = new ExternalUserFactory();
+
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Jane Doe',
+ email: '[email protected]',
+ provider: 'oidc',
+ providerUserId: 'sub-123',
+ );
+
+ expect($user->meta['signup_provider'])->toBe('oidc');
+ expect($user->meta['signup_provider_user_id'])->toBe('sub-123');
+ // registration_ip may be null in unit tests without request context
+ expect($user->meta)->toHaveKey('registration_ip');
+ });
+
+ it('handles UTM data as array', function () {
+ $factory = new ExternalUserFactory();
+
+ $utmData = ['source' => 'google', 'medium' => 'cpc'];
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Test User',
+ email: '[email protected]',
+ provider: 'google',
+ utmData: $utmData,
+ );
+
+ expect($user->utm_data)->toEqual($utmData);
+ });
+
+ it('handles UTM data as JSON string', function () {
+ $factory = new ExternalUserFactory();
+
+ $utmData = json_encode(['source' => 'google', 'medium' => 'cpc']);
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Test User',
+ email: '[email protected]',
+ provider: 'google',
+ utmData: $utmData,
+ );
+
+ expect($user->utm_data)->toEqual(['source' => 'google', 'medium' => 'cpc']);
+ });
+
+ it('sets random password when requested', function () {
+ $factory = new ExternalUserFactory();
+
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Test User',
+ email: '[email protected]',
+ provider: 'oidc',
+ setRandomPassword: true,
+ );
+
+ expect($user->password)->not->toBeNull();
+ expect(strlen($user->password))->toBeGreaterThan(50); // Hashed password length
+ });
+
+ it('does not set password when not requested', function () {
+ $factory = new ExternalUserFactory();
+
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Test User',
+ email: '[email protected]',
+ provider: 'google',
+ setRandomPassword: false,
+ );
+
+ expect($user->password)->toBeNull();
+ });
+
+ it('merges extra meta fields', function () {
+ $factory = new ExternalUserFactory();
+
+ $user = $factory->createVerifiedExternalUser(
+ name: 'Test User',
+ email: '[email protected]',
+ provider: 'google',
+ extraMeta: ['custom_field' => 'custom_value'],
+ );
+
+ expect($user->meta['signup_provider'])->toBe('google');
+ expect($user->meta['custom_field'])->toBe('custom_value');
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/IdTokenVerifierTest.php b/api/tests/Feature/Enterprise/Oidc/IdTokenVerifierTest.php
new file mode 100644
index 000000000..3cb933560
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/IdTokenVerifierTest.php
@@ -0,0 +1,280 @@
+<?php
+
+use App\Enterprise\Oidc\IdTokenVerifier;
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Http;
+use Tests\TestHelpers;
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+afterEach(function () {
+ Cache::flush();
+ Http::fake();
+});
+
+describe('IdTokenVerifier', function () {
+ it('verifies valid ID token signature', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+
+ // Create a valid JWT token with proper structure
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'test-kid',
+ ]));
+ $payload = base64_encode(json_encode([
+ 'sub' => 'user-123',
+ 'iss' => $connection->issuer,
+ 'aud' => $connection->client_id,
+ 'exp' => time() + 3600,
+ ]));
+ $signature = 'valid-signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock OpenID configuration
+ Http::fake([
+ "{$connection->issuer}/.well-known/openid-configuration" => Http::response([
+ 'jwks_uri' => "{$connection->issuer}/.well-known/jwks.json",
+ ]),
+ ]);
+
+ // Mock JWKS with a test key
+ Http::fake([
+ "{$connection->issuer}/.well-known/jwks.json" => Http::response([
+ 'keys' => [
+ [
+ 'kty' => 'RSA',
+ 'kid' => 'test-kid',
+ 'use' => 'sig',
+ 'n' => 'test-modulus',
+ 'e' => 'AQAB',
+ ],
+ ],
+ ]),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ // This will fail because we can't actually verify without real keys,
+ // but we can test the structure validation
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class);
+ });
+
+ it('throws exception for invalid token format', function () {
+ $connection = IdentityConnection::factory()->create();
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, 'invalid-token'))
+ ->toThrow(\Exception::class, 'Invalid ID token format');
+ });
+
+ it('throws exception for missing kid in header', function () {
+ $connection = IdentityConnection::factory()->create();
+
+ $header = base64_encode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class, 'Missing key ID (kid) in ID token header');
+ });
+
+ it('throws exception for missing alg in header', function () {
+ $connection = IdentityConnection::factory()->create();
+
+ $header = base64_encode(json_encode(['typ' => 'JWT', 'kid' => 'test-kid']));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class, 'Invalid ID token header');
+ });
+
+ it('uses custom jwks_uri from connection options', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ 'options' => [
+ 'jwks_uri' => 'https://custom-jwks.example.com/keys',
+ ],
+ ]);
+
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'test-kid',
+ ]));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock custom JWKS endpoint
+ Http::fake([
+ 'https://custom-jwks.example.com/keys' => Http::response([
+ 'keys' => [
+ [
+ 'kty' => 'RSA',
+ 'kid' => 'test-kid',
+ 'use' => 'sig',
+ 'n' => 'test-modulus',
+ 'e' => 'AQAB',
+ ],
+ ],
+ ]),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ // Will fail on signature verification but should use custom URI
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class);
+
+ // Verify custom URI was called
+ Http::assertSent(
+ fn ($request) =>
+ $request->url() === 'https://custom-jwks.example.com/keys'
+ );
+ });
+
+ it('falls back to standard jwks.json when OpenID config fails', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'test-kid',
+ ]));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock OpenID config to fail
+ Http::fake([
+ "{$connection->issuer}/.well-known/openid-configuration" => Http::response([], 404),
+ "{$connection->issuer}/.well-known/jwks.json" => Http::response([
+ 'keys' => [
+ [
+ 'kty' => 'RSA',
+ 'kid' => 'test-kid',
+ 'use' => 'sig',
+ 'n' => 'test-modulus',
+ 'e' => 'AQAB',
+ ],
+ ],
+ ]),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ // Will fail on signature verification but should use fallback
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class);
+
+ // Verify fallback URI was called
+ Http::assertSent(
+ fn ($request) =>
+ $request->url() === "{$connection->issuer}/.well-known/jwks.json"
+ );
+ });
+
+ it('throws exception when JWKS fetch fails', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'test-kid',
+ ]));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock all endpoints to fail
+ Http::fake([
+ "{$connection->issuer}/.well-known/openid-configuration" => Http::response([], 404),
+ "{$connection->issuer}/.well-known/jwks.json" => Http::response([], 500),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class, 'Failed to fetch JWKS');
+ });
+
+ it('throws exception when JWKS has no keys', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'test-kid',
+ ]));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock JWKS with empty keys
+ Http::fake([
+ "{$connection->issuer}/.well-known/jwks.json" => Http::response([
+ 'keys' => [],
+ ]),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class, 'Invalid JWKS format');
+ });
+
+ it('throws exception when kid not found in JWKS', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => 'non-existent-kid',
+ ]));
+ $payload = base64_encode(json_encode(['sub' => 'user-123']));
+ $signature = 'signature';
+ $idToken = "{$header}.{$payload}.{$signature}";
+
+ // Mock JWKS with different kid
+ Http::fake([
+ "{$connection->issuer}/.well-known/jwks.json" => Http::response([
+ 'keys' => [
+ [
+ 'kty' => 'RSA',
+ 'kid' => 'different-kid',
+ 'use' => 'sig',
+ 'n' => 'test-modulus',
+ 'e' => 'AQAB',
+ ],
+ ],
+ ]),
+ ]);
+
+ $verifier = new IdTokenVerifier();
+
+ expect(fn () => $verifier->verifySignature($connection, $idToken))
+ ->toThrow(\Exception::class, 'No matching key found in JWKS');
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/IdentityConnectionPolicyTest.php b/api/tests/Feature/Enterprise/Oidc/IdentityConnectionPolicyTest.php
new file mode 100644
index 000000000..61ec8e0c4
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/IdentityConnectionPolicyTest.php
@@ -0,0 +1,157 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Policies\IdentityConnectionPolicy;
+use App\Models\User;
+use App\Models\Workspace;
+
+uses()->group('oidc', 'feature');
+
+describe('IdentityConnectionPolicy', function () {
+ beforeEach(function () {
+ // Set up admin email config
+ config(['opnform.admin_emails' => ['[email protected]']]);
+ // Set self-hosted mode to bypass Pro checks in tests
+ config(['app.self_hosted' => true]);
+ });
+
+ it('allows workspace admin to view workspace connections', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->viewAny($user, $workspace))->toBeTrue();
+ });
+
+ it('prevents non-admin from viewing workspace connections', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->viewAny($user, $workspace))->toBeFalse();
+ });
+
+ it('allows admin to view global connections', function () {
+ $admin = User::factory()->create(['email' => '[email protected]']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->viewAny($admin, null))->toBeTrue();
+ });
+
+ it('prevents non-admin from viewing global connections', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->viewAny($user, null))->toBeFalse();
+ });
+
+ it('allows admin to view global connection', function () {
+ $admin = User::factory()->create(['email' => '[email protected]']);
+ $connection = IdentityConnection::factory()->create(['workspace_id' => null]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->view($admin, $connection))->toBeTrue();
+ });
+
+ it('prevents non-admin from viewing global connection', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $connection = IdentityConnection::factory()->create(['workspace_id' => null]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->view($user, $connection))->toBeFalse();
+ });
+
+ it('allows workspace admin to view workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create(['workspace_id' => $workspace->id]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->view($user, $connection))->toBeTrue();
+ });
+
+ it('prevents non-admin workspace member from viewing workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ $connection = IdentityConnection::factory()->create(['workspace_id' => $workspace->id]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->view($user, $connection))->toBeFalse();
+ });
+
+ it('allows admin to create global connection', function () {
+ $admin = User::factory()->create(['email' => '[email protected]']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->create($admin, null))->toBeTrue();
+ });
+
+ it('prevents non-admin from creating global connection', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->create($user, null))->toBeFalse();
+ });
+
+ it('allows workspace admin to create workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->create($user, $workspace))->toBeTrue();
+ });
+
+ it('prevents non-admin from creating workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->create($user, $workspace))->toBeFalse();
+ });
+
+ it('allows admin to update global connection', function () {
+ $admin = User::factory()->create(['email' => '[email protected]']);
+ $connection = IdentityConnection::factory()->create(['workspace_id' => null]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->update($admin, $connection))->toBeTrue();
+ });
+
+ it('allows workspace admin to update workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create(['workspace_id' => $workspace->id]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->update($user, $connection))->toBeTrue();
+ });
+
+ it('allows admin to delete global connection', function () {
+ $admin = User::factory()->create(['email' => '[email protected]']);
+ $connection = IdentityConnection::factory()->create(['workspace_id' => null]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->delete($admin, $connection))->toBeTrue();
+ });
+
+ it('allows workspace admin to delete workspace connection', function () {
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create(['workspace_id' => $workspace->id]);
+ $policy = new IdentityConnectionPolicy();
+
+ expect($policy->delete($user, $connection))->toBeTrue();
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/OAuthOidcDriverTest.php b/api/tests/Feature/Enterprise/Oidc/OAuthOidcDriverTest.php
new file mode 100644
index 000000000..eef87450c
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/OAuthOidcDriverTest.php
@@ -0,0 +1,218 @@
+<?php
+
+use App\Enterprise\Oidc\Adapters\OAuthOidcDriver;
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use Laravel\Socialite\Contracts\User as SocialiteUser;
+use Tests\TestHelpers;
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+afterEach(function () {
+ Mockery::close();
+});
+
+describe('OAuthOidcDriver - Initialization', function () {
+ it('initializes with connection', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ 'client_id' => 'test-client',
+ 'client_secret' => 'test-secret',
+ ]);
+
+ $driver = new OAuthOidcDriver($connection);
+
+ expect($driver)->toBeInstanceOf(OAuthOidcDriver::class);
+ });
+
+ it('sets issuer on provider', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://custom-idp.com',
+ ]);
+
+ $driver = new OAuthOidcDriver($connection);
+
+ // Use reflection to verify provider was initialized
+ $reflection = new ReflectionClass($driver);
+ $providerProperty = $reflection->getProperty('provider');
+ $providerProperty->setAccessible(true);
+ $provider = $providerProperty->getValue($driver);
+
+ expect($provider)->toBeInstanceOf(\App\Enterprise\Oidc\Adapters\Socialite\OidcProvider::class);
+ });
+});
+
+describe('OAuthOidcDriver - Redirect URL', function () {
+ it('uses connection scopes when available', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'scopes' => ['openid', 'profile', 'email', 'groups'],
+ ]);
+
+ $driver = new OAuthOidcDriver($connection);
+
+ // Verify scopes are set correctly (we can't easily test getRedirectUrl without mocking Socialite)
+ $reflection = new ReflectionClass($driver);
+ $scopesProperty = $reflection->getProperty('scopes');
+ $scopesProperty->setAccessible(true);
+ $scopes = $scopesProperty->getValue($driver);
+
+ // Initially empty, will use connection scopes
+ expect($scopes)->toBe([]);
+ });
+
+ it('uses default scopes when connection has no scopes', function () {
+ config(['oidc.default_scopes' => ['openid', 'profile']]);
+ $connection = IdentityConnection::factory()->create([
+ 'scopes' => null,
+ ]);
+
+ $driver = new OAuthOidcDriver($connection);
+
+ // The driver should use config defaults
+ expect($connection->scopes)->toBeNull();
+ });
+
+ it('uses custom redirect URL when set', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'redirect_path' => 'https://default-callback.com',
+ ]);
+
+ $driver = new OAuthOidcDriver($connection);
+ $driver->setRedirectUrl('https://custom-callback.com');
+
+ // Verify redirect URL was set
+ $reflection = new ReflectionClass($driver);
+ $redirectUrlProperty = $reflection->getProperty('redirectUrl');
+ $redirectUrlProperty->setAccessible(true);
+ $customUrl = $redirectUrlProperty->getValue($driver);
+
+ expect($customUrl)->toBe('https://custom-callback.com');
+ });
+
+ it('includes state parameter when set', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+ $driver->setState('test-state-123');
+
+ $reflection = new ReflectionClass($driver);
+ $stateProperty = $reflection->getProperty('state');
+ $stateProperty->setAccessible(true);
+ $state = $stateProperty->getValue($driver);
+
+ expect($state)->toBe('test-state-123');
+ });
+});
+
+describe('OAuthOidcDriver - Scopes', function () {
+ it('sets custom scopes', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ $driver->setScopes(['openid', 'custom_scope']);
+
+ $reflection = new ReflectionClass($driver);
+ $scopesProperty = $reflection->getProperty('scopes');
+ $scopesProperty->setAccessible(true);
+ $scopes = $scopesProperty->getValue($driver);
+
+ expect($scopes)->toEqual(['openid', 'custom_scope']);
+ });
+
+ it('returns scopes for auth intent', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'scopes' => ['openid', 'profile', 'email'],
+ ]);
+ $driver = new OAuthOidcDriver($connection);
+
+ $scopes = $driver->getScopesForIntent('auth');
+
+ expect($scopes)->toEqual(['openid', 'profile', 'email']);
+ });
+
+ it('returns default scopes when connection has no scopes', function () {
+ config(['oidc.default_scopes' => ['openid', 'profile']]);
+ $connection = IdentityConnection::factory()->create([
+ 'scopes' => null,
+ ]);
+ $driver = new OAuthOidcDriver($connection);
+
+ $scopes = $driver->getScopesForIntent('auth');
+
+ expect($scopes)->toEqual(['openid', 'profile']);
+ });
+});
+
+describe('OAuthOidcDriver - User Methods', function () {
+ it('can create user', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ expect($driver->canCreateUser())->toBeTrue();
+ });
+
+ it('extracts ID token from provider token response', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ // Mock provider with token response
+ $reflection = new ReflectionClass($driver);
+ $providerProperty = $reflection->getProperty('provider');
+ $providerProperty->setAccessible(true);
+ $provider = $providerProperty->getValue($driver);
+
+ // Set token response using reflection
+ $providerReflection = new ReflectionClass($provider);
+ $tokenResponseProperty = $providerReflection->getProperty('tokenResponse');
+ $tokenResponseProperty->setAccessible(true);
+ $tokenResponseProperty->setValue($provider, [
+ 'access_token' => 'access-token-123',
+ 'id_token' => 'id-token-456',
+ ]);
+
+ // Mock getUser to return a user
+ $mockUser = Mockery::mock(SocialiteUser::class);
+ $mockProvider = Mockery::mock($provider);
+ $mockProvider->shouldReceive('stateless')->andReturnSelf();
+ $mockProvider->shouldReceive('redirectUrl')->andReturnSelf();
+ $mockProvider->shouldReceive('user')->andReturn($mockUser);
+
+ $providerProperty->setValue($driver, $mockProvider);
+
+ $user = $driver->getUser();
+ expect($user)->toBeInstanceOf(SocialiteUser::class);
+
+ // After getUser, idToken should be extracted
+ $idToken = $driver->getIdToken();
+ // Note: In real scenario, this would be extracted from tokenResponse
+ // But with mocked provider, we can't easily test this without more complex setup
+ });
+});
+
+describe('OAuthOidcDriver - Fluent Interface', function () {
+ it('setRedirectUrl returns self for method chaining', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ $result = $driver->setRedirectUrl('https://test.com');
+
+ expect($result)->toBe($driver);
+ });
+
+ it('setScopes returns self for method chaining', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ $result = $driver->setScopes(['openid']);
+
+ expect($result)->toBe($driver);
+ });
+
+ it('setState returns self for method chaining', function () {
+ $connection = IdentityConnection::factory()->create();
+ $driver = new OAuthOidcDriver($connection);
+
+ $result = $driver->setState('test-state');
+
+ expect($result)->toBe($driver);
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php b/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php
new file mode 100644
index 000000000..15eb10fe9
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/OidcConnectionControllerTest.php
@@ -0,0 +1,473 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Models\User;
+use App\Models\Workspace;
+
+uses()->group('oidc', 'feature');
+
+describe('OidcConnectionController - List Connections', function () {
+ it('lists workspace-scoped connections for workspace admin', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ ]);
+
+ $response = $this->getJson("/open/workspaces/{$workspace->id}/oidc-connections");
+
+ $response->assertSuccessful();
+ $response->assertJsonCount(1);
+ expect($response->json('0.id'))->toBe($connection->id);
+ });
+
+ it('prevents workspace member from listing connections', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ ]);
+
+ $response = $this->getJson("/open/workspaces/{$workspace->id}/oidc-connections");
+
+ // Only workspace admins can view connections
+ $response->assertForbidden();
+ });
+
+ it('includes workspace-scoped and global connections for workspace', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $workspaceConnection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ ]);
+
+ $globalConnection = IdentityConnection::factory()->create([
+ 'workspace_id' => null,
+ ]);
+
+ $otherWorkspace = Workspace::factory()->create();
+ IdentityConnection::factory()->create([
+ 'workspace_id' => $otherWorkspace->id,
+ ]);
+
+ $response = $this->getJson("/open/workspaces/{$workspace->id}/oidc-connections");
+
+ $response->assertSuccessful();
+ $response->assertJsonCount(2);
+ $ids = collect($response->json())->pluck('id')->toArray();
+ expect($ids)->toContain($workspaceConnection->id);
+ expect($ids)->toContain($globalConnection->id);
+ });
+});
+
+describe('OidcConnectionController - Create Connection', function () {
+ beforeEach(function () {
+ // Set self-hosted mode to bypass Pro checks in tests
+ config(['app.self_hosted' => true]);
+ });
+
+ it('creates workspace-scoped connection', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Company SSO',
+ 'slug' => 'company-sso',
+ 'domain' => 'company.com',
+ 'issuer' => 'https://idp.company.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ 'enabled' => true,
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(201);
+ $response->assertJsonStructure([
+ 'id',
+ 'name',
+ 'slug',
+ 'domain',
+ 'issuer',
+ 'client_id',
+ 'redirect_url',
+ 'enabled',
+ ]);
+
+ expect($response->json('name'))->toBe('Company SSO');
+ expect($response->json('workspace_id'))->toBe($workspace->id);
+ expect($response->json('client_secret'))->toBeNull(); // Should not expose secret
+ });
+
+ it('validates required fields', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", []);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['name', 'slug', 'domain', 'issuer', 'client_id', 'client_secret']);
+ });
+
+ it('validates unique slug', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ IdentityConnection::factory()->create(['slug' => 'existing-slug']);
+
+ $data = [
+ 'name' => 'Test',
+ 'slug' => 'existing-slug',
+ 'domain' => 'test.com',
+ 'issuer' => 'https://idp.test.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['slug']);
+ });
+
+ it('validates unique domain per workspace', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'domain' => 'company.com',
+ ]);
+
+ $data = [
+ 'name' => 'Test',
+ 'slug' => 'test-slug',
+ 'domain' => 'company.com',
+ 'issuer' => 'https://idp.test.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['domain']);
+ });
+
+ it('enforces single connection per workspace', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'type' => IdentityConnection::TYPE_OIDC,
+ 'domain' => 'company.com',
+ ]);
+
+ // Try to create second connection with different domain (should still fail)
+ $data = [
+ 'name' => 'Second Connection',
+ 'slug' => 'second-connection',
+ 'domain' => 'mail.company.com', // Different domain, but same workspace
+ 'issuer' => 'https://idp.company.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(422);
+ expect($response->json('message'))->toContain('already has an OIDC connection');
+ });
+
+ it('validates domain matches user email domain', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Company SSO',
+ 'slug' => 'company-sso',
+ 'domain' => 'company.com',
+ 'issuer' => 'https://idp.company.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(201);
+ });
+
+ it('rejects domain that does not match user email domain', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Test SSO',
+ 'slug' => 'test-sso',
+ 'domain' => 'other.com',
+ 'issuer' => 'https://idp.other.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['domain']);
+ expect($response->json('errors.domain.0'))->toContain('must match your email domain');
+ });
+
+ it('rejects blocked email providers', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Test SSO',
+ 'slug' => 'test-sso',
+ 'domain' => 'gmail.com',
+ 'issuer' => 'https://idp.gmail.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['domain']);
+ expect($response->json('errors.domain.0'))->toContain('Common email providers');
+ });
+
+ it('allows root domain match when user has subdomain email', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Company SSO',
+ 'slug' => 'company-sso',
+ 'domain' => 'company.com',
+ 'issuer' => 'https://idp.company.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(201);
+ });
+
+ it('allows subdomain match when user has root domain email', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $data = [
+ 'name' => 'Company SSO',
+ 'slug' => 'company-sso',
+ 'domain' => 'mail.company.com',
+ 'issuer' => 'https://idp.company.com',
+ 'client_id' => 'client-123',
+ 'client_secret' => 'secret-456',
+ ];
+
+ $response = $this->postJson("/open/workspaces/{$workspace->id}/oidc-connections", $data);
+
+ $response->assertStatus(201);
+ });
+
+ it('validates domain on update', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'domain' => 'company.com',
+ ]);
+
+ // Try to update to a different domain
+ $response = $this->patchJson(
+ "/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",
+ ['domain' => 'other.com']
+ );
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['domain']);
+ });
+
+ it('allows updating to matching domain', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'domain' => 'company.com',
+ ]);
+
+ // Update to subdomain of same root domain
+ $response = $this->patchJson(
+ "/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",
+ ['domain' => 'mail.company.com']
+ );
+
+ $response->assertSuccessful();
+ expect($connection->fresh()->domain)->toBe('mail.company.com');
+ });
+});
+
+describe('OidcConnectionController - Update Connection', function () {
+ beforeEach(function () {
+ // Set self-hosted mode to bypass Pro checks in tests
+ config(['app.self_hosted' => true]);
+ });
+
+ it('updates workspace-scoped connection', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'name' => 'Old Name',
+ 'domain' => 'company.com',
+ ]);
+
+ $response = $this->patchJson(
+ "/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",
+ ['name' => 'New Name']
+ );
+
+ $response->assertSuccessful();
+ expect($response->json('name'))->toBe('New Name');
+ expect($connection->fresh()->name)->toBe('New Name');
+ });
+
+ it('does not update client_secret if not provided', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'client_secret' => 'old-secret',
+ 'domain' => 'company.com',
+ ]);
+
+ $response = $this->patchJson(
+ "/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",
+ ['name' => 'Updated Name']
+ );
+
+ $response->assertSuccessful();
+ expect($connection->fresh()->client_secret)->toBe('old-secret');
+ });
+
+ it('merges options instead of replacing', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'domain' => 'company.com',
+ 'options' => [
+ 'field_mappings' => ['email' => 'mail'],
+ 'custom_field' => 'custom_value',
+ ],
+ ]);
+
+ $response = $this->patchJson(
+ "/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}",
+ [
+ 'options' => [
+ 'field_mappings' => ['email' => 'email_address'],
+ ],
+ ]
+ );
+
+ $response->assertSuccessful();
+ $options = $connection->fresh()->options;
+ expect($options['field_mappings']['email'])->toBe('email_address');
+ expect($options['custom_field'])->toBe('custom_value'); // Should be preserved
+ });
+});
+
+describe('OidcConnectionController - Delete Connection', function () {
+ beforeEach(function () {
+ // Set self-hosted mode to bypass Pro checks in tests
+ config(['app.self_hosted' => true]);
+ });
+
+ it('deletes workspace-scoped connection', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'admin']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'domain' => 'company.com',
+ ]);
+
+ $response = $this->deleteJson("/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}");
+
+ $response->assertStatus(204);
+ expect(IdentityConnection::find($connection->id))->toBeNull();
+ });
+
+ it('prevents deletion by non-admin', function () {
+ $user = $this->actingAsUser();
+ $workspace = Workspace::factory()->create();
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'workspace_id' => $workspace->id,
+ ]);
+
+ $response = $this->deleteJson("/open/workspaces/{$workspace->id}/oidc-connections/{$connection->id}");
+
+ $response->assertStatus(403);
+ expect(IdentityConnection::find($connection->id))->not->toBeNull();
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/ProvisioningServiceTest.php b/api/tests/Feature/Enterprise/Oidc/ProvisioningServiceTest.php
new file mode 100644
index 000000000..76ba3c2f2
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/ProvisioningServiceTest.php
@@ -0,0 +1,383 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\Models\UserIdentity;
+use App\Enterprise\Oidc\ProvisioningService;
+use App\Models\User;
+use App\Models\Workspace;
+use Tests\TestHelpers;
+
+require_once __DIR__ . '/../../../TestHelpers/OidcTestHelpers.php';
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+afterEach(function () {
+ Mockery::close();
+});
+
+describe('ProvisioningService - New User Creation', function () {
+ it('creates new user and UserIdentity when no existing user found', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'New User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-123');
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user)->toBeInstanceOf(User::class);
+ expect($user->email)->toBe('[email protected]');
+ expect($user->name)->toBe('New User');
+ expect($user->email_verified_at)->not->toBeNull();
+
+ // Check UserIdentity was created
+ $userIdentity = UserIdentity::where('user_id', $user->id)
+ ->where('connection_id', $connection->id)
+ ->first();
+ expect($userIdentity)->not->toBeNull();
+ expect($userIdentity->subject)->toBe('sub-123');
+ expect($userIdentity->email)->toBe('[email protected]');
+ });
+
+ it('creates user with random password for SSO-only accounts', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'SSO User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-456');
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->password)->not->toBeNull();
+ expect(strlen($user->password))->toBeGreaterThan(50); // Hashed password length
+ });
+
+ it('uses email prefix as name when name is not provided', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: null
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-789');
+ // Remove all name-related fields to test fallback to email prefix
+ // Note: We need to ensure given_name and family_name are not set, otherwise
+ // trim(' ') becomes empty string which is truthy
+ unset($idTokenClaims['name']);
+ unset($idTokenClaims['display_name']);
+ unset($idTokenClaims['given_name']);
+ unset($idTokenClaims['family_name']);
+ unset($idTokenClaims['preferred_username']);
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ // The service should fall back to email prefix when name is null/empty
+ // Current implementation: $name ?? $socialiteUser->getName() ?? explode('@', $email)[0]
+ // Since $name will be null (all fields unset), it should use email prefix
+ expect($user->name)->toBe('noname');
+ });
+});
+
+describe('ProvisioningService - Existing User Login', function () {
+ it('returns existing user when UserIdentity exists', function () {
+ $connection = IdentityConnection::factory()->create();
+ $existingUser = $this->createUser(['email' => '[email protected]']);
+
+ $userIdentity = UserIdentity::factory()->create([
+ 'user_id' => $existingUser->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-existing',
+ 'email' => '[email protected]',
+ ]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Existing User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-existing');
+ $idTokenClaims['name'] = 'Updated Name';
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->id)->toBe($existingUser->id);
+ expect($user->email)->toBe('[email protected]');
+
+ // Check UserIdentity was updated
+ $userIdentity->refresh();
+ expect($userIdentity->claims)->toHaveKey('name', 'Updated Name');
+ });
+
+ it('updates UserIdentity email if changed', function () {
+ $connection = IdentityConnection::factory()->create();
+ $existingUser = $this->createUser(['email' => '[email protected]']);
+
+ $userIdentity = UserIdentity::factory()->create([
+ 'user_id' => $existingUser->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-update',
+ 'email' => '[email protected]',
+ ]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Updated User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-update');
+ $idTokenClaims['email'] = '[email protected]';
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ $userIdentity->refresh();
+ expect($userIdentity->email)->toBe('[email protected]');
+ });
+});
+
+describe('ProvisioningService - Account Linking', function () {
+ it('throws exception when user with email exists but no UserIdentity', function () {
+ $connection = IdentityConnection::factory()->create();
+ $existingUser = $this->createUser(['email' => '[email protected]']);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Existing User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-new');
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'An account with this email already exists');
+ });
+});
+
+describe('ProvisioningService - Field Mappings', function () {
+ it('uses custom email field mapping when configured', function () {
+ $connection = IdentityConnection::factory()->withFieldMappings([
+ 'email' => 'mail',
+ 'name' => 'display_name',
+ ])->create();
+
+ $socialiteUser = createMockSocialiteUser(
+ email: null, // Not provided by Socialite
+ name: null
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-mapped');
+ $idTokenClaims['mail'] = '[email protected]';
+ $idTokenClaims['display_name'] = 'Mapped Name';
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->email)->toBe('[email protected]');
+ expect($user->name)->toBe('Mapped Name');
+ });
+
+ it('falls back to standard fields when mapped field not found', function () {
+ $connection = IdentityConnection::factory()->withFieldMappings([
+ 'email' => 'nonexistent_field',
+ ])->create();
+
+ $socialiteUser = createMockSocialiteUser(
+ email: null,
+ name: null
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-fallback');
+ $idTokenClaims['email'] = '[email protected]';
+ $idTokenClaims['name'] = 'Fallback Name';
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->email)->toBe('[email protected]');
+ expect($user->name)->toBe('Fallback Name');
+ });
+
+ it('throws exception when email cannot be extracted', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser(
+ email: null,
+ name: null
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-no-email');
+ unset($idTokenClaims['email']);
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'Email is required for OIDC authentication');
+ });
+});
+
+describe('ProvisioningService - Workspace Membership', function () {
+ it('adds user to workspace for workspace-scoped connection', function () {
+ $workspace = Workspace::factory()->create();
+ $connection = IdentityConnection::factory()->forWorkspace($workspace)->create();
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Workspace User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-workspace');
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->workspaces()->where('workspaces.id', $workspace->id)->exists())->toBeTrue();
+
+ $pivot = $user->workspaces()->withPivot('role')->where('workspaces.id', $workspace->id)->first();
+ expect($pivot->pivot->role)->toBe('member'); // Default role
+ });
+
+ it('applies role mapping from groups for workspace-scoped connection', function () {
+ $workspace = Workspace::factory()->create();
+ $connection = IdentityConnection::factory()
+ ->forWorkspace($workspace)
+ ->withRoleMappings([
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ['idp_group' => 'users', 'role' => 'member'],
+ ])
+ ->create();
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Admin User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-admin');
+ $idTokenClaims['groups'] = ['admins', 'users'];
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ $pivot = $user->workspaces()->withPivot('role')->where('workspaces.id', $workspace->id)->first();
+ expect($pivot->pivot->role)->toBe('admin'); // Highest privilege role
+ });
+
+ it('finds workspace by domain for global connection', function () {
+ $workspace = Workspace::factory()->create([
+ 'settings' => [
+ 'oidc' => [
+ 'allowed_domain' => 'example.com',
+ ],
+ ],
+ ]);
+ $connection = IdentityConnection::factory()->create(['workspace_id' => null]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Global User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-global');
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user->workspaces()->where('workspaces.id', $workspace->id)->exists())->toBeTrue();
+ });
+
+ it('updates role for existing workspace member', function () {
+ $workspace = Workspace::factory()->create();
+ $user = $this->createUser(['email' => '[email protected]']);
+ $user->workspaces()->attach($workspace->id, ['role' => 'member']);
+
+ $connection = IdentityConnection::factory()
+ ->forWorkspace($workspace)
+ ->withRoleMappings([
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ])
+ ->create();
+
+ $userIdentity = UserIdentity::factory()->create([
+ 'user_id' => $user->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-member',
+ ]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Member User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-member');
+ $idTokenClaims['groups'] = ['admins'];
+
+ $service = app(ProvisioningService::class);
+ $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ $pivot = $user->workspaces()->withPivot('role')->where('workspaces.id', $workspace->id)->first();
+ expect($pivot->pivot->role)->toBe('admin'); // Role updated
+ });
+});
+
+describe('ProvisioningService - ID Token Validation', function () {
+ it('validates issuer matches connection issuer', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'issuer' => 'https://idp.example.com',
+ ]);
+ $socialiteUser = createMockSocialiteUser();
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-invalid');
+ $idTokenClaims['iss'] = 'https://wrong-issuer.com';
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'Invalid issuer');
+ });
+
+ it('validates audience contains client_id', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'client_id' => 'correct-client-id',
+ ]);
+ $socialiteUser = createMockSocialiteUser();
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-invalid');
+ $idTokenClaims['aud'] = 'wrong-client-id';
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'Invalid audience');
+ });
+
+ it('validates audience when it is an array', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'client_id' => 'correct-client-id',
+ ]);
+ $socialiteUser = createMockSocialiteUser();
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-array');
+ $idTokenClaims['aud'] = ['other-client', 'correct-client-id'];
+
+ $service = app(ProvisioningService::class);
+ $user = $service->provisionUser($connection, $socialiteUser, $idTokenClaims);
+
+ expect($user)->toBeInstanceOf(User::class);
+ });
+
+ it('validates token expiration', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser();
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-expired');
+ $idTokenClaims['exp'] = time() - 3600; // Expired 1 hour ago
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'ID token has expired');
+ });
+
+ it('validates subject is present', function () {
+ $connection = IdentityConnection::factory()->create();
+ $socialiteUser = createMockSocialiteUser();
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-missing');
+ unset($idTokenClaims['sub']);
+
+ $service = app(ProvisioningService::class);
+
+ expect(fn () => $service->provisionUser($connection, $socialiteUser, $idTokenClaims))
+ ->toThrow(Exception::class, 'Missing subject');
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/RoleMapperTest.php b/api/tests/Feature/Enterprise/Oidc/RoleMapperTest.php
new file mode 100644
index 000000000..19342585e
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/RoleMapperTest.php
@@ -0,0 +1,122 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Enterprise\Oidc\RoleMapper;
+
+uses()->group('oidc', 'feature');
+
+describe('RoleMapper', function () {
+ it('returns null when no groups provided', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ expect($mapper->mapGroupsToRole($connection, []))->toBeNull();
+ });
+
+ it('returns null when no mappings configured', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [],
+ ]);
+
+ $mapper = new RoleMapper();
+ expect($mapper->mapGroupsToRole($connection, ['admins']))->toBeNull();
+ });
+
+ it('returns null when groups do not match any mapping', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ expect($mapper->mapGroupsToRole($connection, ['users']))->toBeNull();
+ });
+
+ it('maps single group to role', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ expect($mapper->mapGroupsToRole($connection, ['admins']))->toBe('admin');
+ });
+
+ it('returns highest privilege role when multiple groups match', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'users', 'role' => 'member'],
+ ['idp_group' => 'editors', 'role' => 'editor'],
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ['idp_group' => 'owners', 'role' => 'owner'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ // User has multiple groups - should return highest privilege (owner)
+ expect($mapper->mapGroupsToRole($connection, ['users', 'editors', 'owners']))->toBe('owner');
+ });
+
+ it('prioritizes roles correctly', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'group1', 'role' => 'member'],
+ ['idp_group' => 'group2', 'role' => 'admin'],
+ ['idp_group' => 'group3', 'role' => 'editor'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ // Should return admin (higher than editor and member)
+ expect($mapper->mapGroupsToRole($connection, ['group1', 'group2', 'group3']))->toBe('admin');
+ });
+
+ it('handles invalid mapping entries gracefully', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'admins', 'role' => 'admin'],
+ ['invalid' => 'mapping'], // Missing required fields
+ ['idp_group' => 'users'], // Missing role
+ ['role' => 'member'], // Missing idp_group
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ // Should still work with valid mappings
+ expect($mapper->mapGroupsToRole($connection, ['admins']))->toBe('admin');
+ expect($mapper->mapGroupsToRole($connection, ['users']))->toBeNull();
+ });
+
+ it('handles case-sensitive group matching', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'options' => [
+ 'group_role_mappings' => [
+ ['idp_group' => 'Admins', 'role' => 'admin'],
+ ],
+ ],
+ ]);
+
+ $mapper = new RoleMapper();
+ // Should be case-sensitive
+ expect($mapper->mapGroupsToRole($connection, ['Admins']))->toBe('admin');
+ expect($mapper->mapGroupsToRole($connection, ['admins']))->toBeNull();
+ });
+});
diff --git a/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php
new file mode 100644
index 000000000..120cb0bfb
--- /dev/null
+++ b/api/tests/Feature/Enterprise/Oidc/SsoControllerTest.php
@@ -0,0 +1,418 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use App\Models\User;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\URL;
+use Tests\TestHelpers;
+
+require_once __DIR__ . '/../../../TestHelpers/OidcTestHelpers.php';
+
+uses(TestHelpers::class);
+uses()->group('oidc', 'feature');
+
+afterEach(function () {
+ Mockery::close();
+ Cache::flush();
+});
+
+describe('SsoController - Redirect', function () {
+ it('returns redirect URL for enabled connection', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'enabled' => true,
+ ]);
+
+ // Mock the driver to return a redirect URL
+ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);
+ $mockDriver->shouldReceive('getRedirectUrl')->andReturn('https://idp.example.com/authorize');
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('test-sso')
+ ->andReturn($connection);
+ $mockConnectionManager->shouldReceive('buildDriver')
+ ->with($connection)
+ ->andReturn($mockDriver);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+
+ $response = $this->postJson("/auth/test-sso/redirect");
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'redirect_url' => 'https://idp.example.com/authorize',
+ ]);
+ });
+
+ it('returns 404 for non-existent connection', function () {
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('non-existent')
+ ->andReturn(null);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+
+ $response = $this->postJson("/auth/non-existent/redirect");
+
+ $response->assertNotFound();
+ $response->assertJson([
+ 'error' => 'OIDC connection not found or disabled',
+ ]);
+ });
+
+ it('returns 404 for disabled connection', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'disabled-sso',
+ 'enabled' => false,
+ ]);
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('disabled-sso')
+ ->andReturn($connection);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+
+ $response = $this->postJson("/auth/disabled-sso/redirect");
+
+ $response->assertNotFound();
+ $response->assertJson([
+ 'error' => 'OIDC connection not found or disabled',
+ ]);
+ });
+
+ it('requires HTTPS in production', function () {
+ $originalEnv = config('app.env');
+ config(['app.env' => 'production']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'enabled' => true,
+ ]);
+
+ // Mock driver to avoid initialization issues
+ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);
+ $mockDriver->shouldReceive('getRedirectUrl')->andReturn('https://idp.example.com/authorize');
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('test-sso')
+ ->andReturn($connection);
+ $mockConnectionManager->shouldReceive('buildDriver')
+ ->with($connection)
+ ->andReturn($mockDriver);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+
+ // Force HTTP scheme and simulate non-HTTPS request
+ URL::forceScheme('http');
+ $response = $this->postJson("/auth/test-sso/redirect", [
+ 'HTTP_X_FORWARDED_PROTO' => 'http',
+ ]);
+
+ $response->assertStatus(400);
+ $response->assertJson([
+ 'error' => 'HTTPS is required for OIDC authentication',
+ ]);
+
+ // Restore original env and scheme
+ config(['app.env' => $originalEnv]);
+ URL::forceScheme('https');
+ });
+});
+
+describe('SsoController - Get Options For Email', function () {
+ it('returns redirect action when connection exists for domain', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'company-sso',
+ 'domain' => 'company.com',
+ 'enabled' => true,
+ ]);
+
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => '[email protected]',
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'action' => 'redirect',
+ 'slug' => 'company-sso',
+ ]);
+ });
+
+ it('returns fallback action when no connection exists for domain', function () {
+ IdentityConnection::factory()->create([
+ 'domain' => 'other.com',
+ 'enabled' => true,
+ ]);
+
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => '[email protected]',
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'action' => 'fallback',
+ ]);
+ });
+
+ it('returns blocked action when force login is enabled and no connection', function () {
+ config(['oidc.force_login' => true]);
+
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => '[email protected]',
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'action' => 'blocked',
+ ]);
+ });
+
+ it('returns fallback action for invalid email', function () {
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => 'invalid-email',
+ ]);
+
+ $response->assertStatus(422);
+ $response->assertJsonValidationErrors(['email']);
+ });
+
+ it('only matches enabled connections', function () {
+ IdentityConnection::factory()->create([
+ 'slug' => 'disabled-sso',
+ 'domain' => 'company.com',
+ 'enabled' => false,
+ ]);
+
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => '[email protected]',
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'action' => 'fallback',
+ ]);
+ });
+
+ it('extracts domain correctly from email', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'domain' => 'example.com',
+ 'enabled' => true,
+ ]);
+
+ $response = $this->postJson('/auth/oidc/options', [
+ 'email' => '[email protected]', // Test case normalization
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJson([
+ 'action' => 'redirect',
+ ]);
+ });
+});
+
+describe('SsoController - Callback', function () {
+ it('returns JSON response with token and user for new user', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'enabled' => true,
+ ]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'New User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-123');
+ $idToken = createMockIdToken($idTokenClaims);
+
+ // Mock driver
+ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);
+ $mockDriver->shouldReceive('setRedirectUrl')->andReturnSelf();
+ $mockDriver->shouldReceive('getUser')->andReturn($socialiteUser);
+ $mockDriver->shouldReceive('getIdToken')->andReturn($idToken);
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('test-sso')
+ ->andReturn($connection);
+ $mockConnectionManager->shouldReceive('buildDriver')
+ ->with($connection)
+ ->andReturn($mockDriver);
+
+ // Mock IdTokenVerifier to skip signature verification in tests
+ $mockIdTokenVerifier = Mockery::mock(\App\Enterprise\Oidc\IdTokenVerifier::class);
+ $mockIdTokenVerifier->shouldReceive('verifySignature')
+ ->with($connection, $idToken)
+ ->andReturnNull();
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+ $this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);
+
+ $response = $this->getJson("/auth/test-sso/callback", [
+ 'Accept' => 'application/json',
+ ]);
+
+ $response->assertSuccessful();
+ $response->assertJsonStructure([
+ 'token',
+ 'token_type',
+ 'expires_in',
+ 'user' => [
+ 'id',
+ 'email',
+ 'name',
+ ],
+ 'new_user',
+ 'redirect_url',
+ ]);
+ expect($response->json('new_user'))->toBeTrue();
+ });
+
+ it('returns 404 for non-existent connection', function () {
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('non-existent')
+ ->andReturn(null);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+
+ $response = $this->getJson("/auth/non-existent/callback", [
+ 'Accept' => 'application/json',
+ ]);
+
+ $response->assertNotFound();
+ });
+
+ it('returns error JSON when provisioning fails', function () {
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'enabled' => true,
+ ]);
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]', // Provide email to avoid early failure
+ name: 'Test User'
+ );
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-error');
+ $idToken = createMockIdToken($idTokenClaims);
+
+ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);
+ $mockDriver->shouldReceive('setRedirectUrl')->andReturnSelf();
+ $mockDriver->shouldReceive('getUser')->andReturn($socialiteUser);
+ $mockDriver->shouldReceive('getIdToken')->andReturn($idToken);
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('test-sso')
+ ->andReturn($connection);
+ $mockConnectionManager->shouldReceive('buildDriver')
+ ->with($connection)
+ ->andReturn($mockDriver);
+
+ // Mock IdTokenVerifier to skip signature verification in tests
+ $mockIdTokenVerifier = Mockery::mock(\App\Enterprise\Oidc\IdTokenVerifier::class);
+ $mockIdTokenVerifier->shouldReceive('verifySignature')
+ ->with($connection, $idToken)
+ ->andReturnNull();
+
+ // Mock ProvisioningService to throw exception (simulating provisioning error)
+ $mockProvisioningService = Mockery::mock(\App\Enterprise\Oidc\ProvisioningService::class);
+ $mockProvisioningService->shouldReceive('provisionUser')
+ ->andThrow(new \Exception('Provisioning failed: Invalid claims'));
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+ $this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);
+ $this->app->instance(\App\Enterprise\Oidc\ProvisioningService::class, $mockProvisioningService);
+
+ $response = $this->getJson("/auth/test-sso/callback", [
+ 'Accept' => 'application/json',
+ ]);
+
+ $response->assertStatus(400);
+ $response->assertJsonStructure([
+ 'message',
+ ]);
+ expect($response->json('message'))->toContain('Provisioning failed');
+ });
+
+ it('blocks blocked users', function () {
+ // Ensure we're not in production mode (which requires HTTPS)
+ $originalEnv = config('app.env');
+ config(['app.env' => 'testing']);
+
+ $connection = IdentityConnection::factory()->create([
+ 'slug' => 'test-sso',
+ 'enabled' => true,
+ ]);
+ $connection->refresh(); // Ensure all fields are loaded
+
+ $user = $this->createUser([
+ 'email' => '[email protected]',
+ 'blocked_at' => now(),
+ ]);
+ $user->refresh(); // Ensure blocked_at is loaded
+
+ $socialiteUser = createMockSocialiteUser(
+ email: '[email protected]',
+ name: 'Blocked User'
+ );
+ // Create ID token claims AFTER connection is created and refreshed
+ $idTokenClaims = createValidIdTokenClaims($connection, 'sub-blocked');
+ $idTokenClaims['email'] = '[email protected]'; // Ensure email is in claims
+ $idToken = createMockIdToken($idTokenClaims);
+
+ // Create UserIdentity for existing user - this should allow provisioning to find the user
+ $userIdentity = \App\Enterprise\Oidc\Models\UserIdentity::factory()->create([
+ 'user_id' => $user->id,
+ 'connection_id' => $connection->id,
+ 'subject' => 'sub-blocked',
+ 'email' => '[email protected]',
+ 'claims' => $idTokenClaims,
+ ]);
+ // Ensure the relationship is loaded
+ $userIdentity->load('user');
+
+ $mockDriver = Mockery::mock(\App\Enterprise\Oidc\Adapters\OAuthOidcDriver::class);
+ $mockDriver->shouldReceive('setRedirectUrl')->andReturnSelf();
+ $mockDriver->shouldReceive('getUser')->andReturn($socialiteUser);
+ $mockDriver->shouldReceive('getIdToken')->andReturn($idToken);
+
+ $mockConnectionManager = Mockery::mock(\App\Enterprise\Oidc\ConnectionManager::class);
+ $mockConnectionManager->shouldReceive('getConnectionBySlug')
+ ->with('test-sso')
+ ->andReturn($connection);
+ $mockConnectionManager->shouldReceive('buildDriver')
+ ->with($connection)
+ ->andReturn($mockDriver);
+
+ // Mock IdTokenVerifier to skip signature verification in tests
+ $mockIdTokenVerifier = Mockery::mock(\App\Enterprise\Oidc\IdTokenVerifier::class);
+ $mockIdTokenVerifier->shouldReceive('verifySignature')
+ ->with($connection, $idToken)
+ ->andReturnNull();
+
+ // Mock ProvisioningService to return the blocked user directly
+ // Refresh user to ensure blocked_at is loaded
+ $user->refresh();
+ $mockProvisioningService = Mockery::mock(\App\Enterprise\Oidc\ProvisioningService::class);
+ $mockProvisioningService->shouldReceive('provisionUser')
+ ->andReturn($user);
+
+ $this->app->instance(\App\Enterprise\Oidc\ConnectionManager::class, $mockConnectionManager);
+ $this->app->instance(\App\Enterprise\Oidc\IdTokenVerifier::class, $mockIdTokenVerifier);
+ $this->app->instance(\App\Enterprise\Oidc\ProvisioningService::class, $mockProvisioningService);
+
+ $response = $this->getJson("/auth/test-sso/callback", [
+ 'Accept' => 'application/json',
+ ]);
+
+ $response->assertForbidden();
+ expect($response->json('message'))->toContain('blocked');
+
+ // Restore original env
+ config(['app.env' => $originalEnv]);
+ });
+});
diff --git a/api/tests/Feature/LoginTest.php b/api/tests/Feature/LoginTest.php
index f2727ab6f..6ffc6e393 100644
--- a/api/tests/Feature/LoginTest.php
+++ b/api/tests/Feature/LoginTest.php
@@ -50,3 +50,44 @@ it('cannot login if user is blocked', function () {
$this->assertGuest();
});
+
+it('blocks password login when OIDC force_login is enabled', function () {
+ // Create an OIDC connection
+ \App\Enterprise\Oidc\Models\IdentityConnection::factory()->create([
+ 'enabled' => true,
+ 'type' => \App\Enterprise\Oidc\Models\IdentityConnection::TYPE_OIDC,
+ ]);
+
+ // Enable force_login
+ config(['oidc.force_login' => true]);
+
+ $user = User::factory()->create();
+
+ $this->postJson('/login', [
+ 'email' => $user->email,
+ 'password' => 'Abcd@1234',
+ ])
+ ->assertStatus(422)
+ ->assertJsonValidationErrors(['email' => 'Password-based login is disabled. Please use OIDC authentication.']);
+
+ $this->assertGuest();
+
+ // Restore config
+ 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 connections
+ config(['oidc.force_login' => true]);
+
+ $user = User::factory()->create();
+
+ $this->postJson('/login', [
+ 'email' => $user->email,
+ 'password' => 'Abcd@1234',
+ ])
+ ->assertSuccessful();
+
+ // Restore config
+ config(['oidc.force_login' => false]);
+});
diff --git a/api/tests/TestHelpers.php b/api/tests/TestHelpers.php
index 70116a0e9..2dc560976 100644
--- a/api/tests/TestHelpers.php
+++ b/api/tests/TestHelpers.php
@@ -251,6 +251,18 @@ trait TestHelpers
$this->assertGuest();
}
+ public function actingAsAdmin(?User $user = null)
+ {
+ if ($user == null) {
+ // Create admin user by setting email in admin config
+ $adminEmail = '[email protected]';
+ config(['opnform.admin_emails' => [$adminEmail]]);
+ $user = $this->createUser(['email' => $adminEmail]);
+ }
+
+ return $this->actingAsUser($user);
+ }
+
public function createFormIntegration($integrationId, $formId, $settings = [])
{
$data = [
diff --git a/api/tests/TestHelpers/OidcTestHelpers.php b/api/tests/TestHelpers/OidcTestHelpers.php
new file mode 100644
index 000000000..1b514252e
--- /dev/null
+++ b/api/tests/TestHelpers/OidcTestHelpers.php
@@ -0,0 +1,44 @@
+<?php
+
+use App\Enterprise\Oidc\Models\IdentityConnection;
+use Laravel\Socialite\Contracts\User as SocialiteUser;
+
+if (!function_exists('createMockSocialiteUser')) {
+ function createMockSocialiteUser(?string $email = null, ?string $name = null): SocialiteUser
+ {
+ $mock = Mockery::mock(SocialiteUser::class);
+ $mock->shouldReceive('getEmail')->andReturn($email);
+ $mock->shouldReceive('getName')->andReturn($name);
+ return $mock;
+ }
+}
+
+if (!function_exists('createValidIdTokenClaims')) {
+ function createValidIdTokenClaims(IdentityConnection $connection, string $subject): array
+ {
+ return [
+ 'sub' => $subject,
+ 'iss' => $connection->issuer,
+ 'aud' => $connection->client_id,
+ 'exp' => time() + 3600, // Valid for 1 hour
+ 'email' => '[email protected]',
+ 'name' => 'Test User',
+ ];
+ }
+}
+
+if (!function_exists('createMockIdToken')) {
+ function createMockIdToken(array $claims, ?string $kid = 'test-kid'): string
+ {
+ // Create a simple mock JWT token (header.payload.signature)
+ // Include kid in header for signature verification
+ $header = base64_encode(json_encode([
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => $kid,
+ ]));
+ $payload = base64_encode(json_encode($claims));
+ $signature = 'mock-signature';
+ return "{$header}.{$payload}.{$signature}";
+ }
+}
diff --git a/api/tests/Unit/Enterprise/Oidc/DomainValidatorTest.php b/api/tests/Unit/Enterprise/Oidc/DomainValidatorTest.php
new file mode 100644
index 000000000..b1d58c27e
--- /dev/null
+++ b/api/tests/Unit/Enterprise/Oidc/DomainValidatorTest.php
@@ -0,0 +1,165 @@
+<?php
+
+use App\Enterprise\Oidc\DomainValidator;
+use App\Models\User;
+use Tests\TestCase;
+
+uses(TestCase::class);
+uses()->group('oidc', 'unit');
+
+describe('DomainValidator', function () {
+ $validator = new DomainValidator();
+
+ describe('extractRootDomain', function () use ($validator) {
+ it('returns domain as-is when it has 2 or fewer parts', function () use ($validator) {
+ expect($validator->extractRootDomain('company.com'))->toBe('company.com');
+ expect($validator->extractRootDomain('com'))->toBe('com');
+ });
+
+ it('extracts root domain from subdomain', function () use ($validator) {
+ expect($validator->extractRootDomain('mail.company.com'))->toBe('company.com');
+ expect($validator->extractRootDomain('subdomain.example.org'))->toBe('example.org');
+ });
+
+ it('handles multiple subdomains', function () use ($validator) {
+ expect($validator->extractRootDomain('mail.subdomain.company.com'))->toBe('company.com');
+ });
+
+ it('normalizes to lowercase', function () use ($validator) {
+ expect($validator->extractRootDomain('MAIL.COMPANY.COM'))->toBe('company.com');
+ });
+
+ it('trims whitespace', function () use ($validator) {
+ expect($validator->extractRootDomain(' mail.company.com '))->toBe('company.com');
+ });
+ });
+
+ describe('isBlockedProvider', function () use ($validator) {
+ it('blocks exact matches of blocked providers', function () use ($validator) {
+ expect($validator->isBlockedProvider('gmail.com'))->toBeTrue();
+ expect($validator->isBlockedProvider('yahoo.com'))->toBeTrue();
+ expect($validator->isBlockedProvider('outlook.com'))->toBeTrue();
+ });
+
+ it('blocks subdomains of blocked providers', function () use ($validator) {
+ expect($validator->isBlockedProvider('mail.gmail.com'))->toBeTrue();
+ expect($validator->isBlockedProvider('smtp.yahoo.com'))->toBeTrue();
+ });
+
+ it('allows non-blocked domains', function () use ($validator) {
+ expect($validator->isBlockedProvider('company.com'))->toBeFalse();
+ expect($validator->isBlockedProvider('example.org'))->toBeFalse();
+ expect($validator->isBlockedProvider('mail.company.com'))->toBeFalse();
+ });
+
+ it('is case-insensitive', function () use ($validator) {
+ expect($validator->isBlockedProvider('GMAIL.COM'))->toBeTrue();
+ expect($validator->isBlockedProvider('Gmail.Com'))->toBeTrue();
+ });
+
+ it('blocks all configured providers', function () use ($validator) {
+ $blockedProviders = [
+ 'gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com',
+ 'msn.com', 'yahoo.com', 'yahoo.co.uk', 'ymail.com', 'rocketmail.com',
+ 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'protonmail.com',
+ 'proton.me', 'mail.com', 'gmx.com', 'gmx.de', 'gmx.net', 'zoho.com',
+ ];
+
+ foreach ($blockedProviders as $provider) {
+ expect($validator->isBlockedProvider($provider))->toBeTrue("Failed to block: {$provider}");
+ }
+ });
+ });
+
+ describe('matchesUserDomain', function () use ($validator) {
+ it('matches exact domain', function () use ($validator) {
+ expect($validator->matchesUserDomain('company.com', '[email protected]'))->toBeTrue();
+ expect($validator->matchesUserDomain('example.org', '[email protected]'))->toBeTrue();
+ });
+
+ it('matches root domain when user has subdomain email', function () use ($validator) {
+ expect($validator->matchesUserDomain('company.com', '[email protected]'))->toBeTrue();
+ expect($validator->matchesUserDomain('example.org', '[email protected]'))->toBeTrue();
+ });
+
+ it('matches subdomain when user has root domain email', function () use ($validator) {
+ expect($validator->matchesUserDomain('mail.company.com', '[email protected]'))->toBeTrue();
+ expect($validator->matchesUserDomain('subdomain.example.org', '[email protected]'))->toBeTrue();
+ });
+
+ it('does not match different domains', function () use ($validator) {
+ expect($validator->matchesUserDomain('other.com', '[email protected]'))->toBeFalse();
+ expect($validator->matchesUserDomain('company.com', '[email protected]'))->toBeFalse();
+ });
+
+ it('is case-insensitive', function () use ($validator) {
+ expect($validator->matchesUserDomain('COMPANY.COM', '[email protected]'))->toBeTrue();
+ expect($validator->matchesUserDomain('company.com', '[email protected]'))->toBeTrue();
+ });
+
+ it('returns false for invalid email', function () use ($validator) {
+ expect($validator->matchesUserDomain('company.com', 'invalid-email'))->toBeFalse();
+ expect($validator->matchesUserDomain('company.com', ''))->toBeFalse();
+ });
+
+ it('handles complex subdomain scenarios', function () use ($validator) {
+ // User has mail.company.com, domain is company.com
+ expect($validator->matchesUserDomain('company.com', '[email protected]'))->toBeTrue();
+
+ // User has company.com, domain is mail.company.com
+ expect($validator->matchesUserDomain('mail.company.com', '[email protected]'))->toBeTrue();
+
+ // Both have same subdomain
+ expect($validator->matchesUserDomain('mail.company.com', '[email protected]'))->toBeTrue();
+ });
+ });
+
+ describe('getUserEmailDomain', function () use ($validator) {
+ it('extracts domain from user email', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->getUserEmailDomain($user))->toBe('company.com');
+ });
+
+ it('handles subdomain emails', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->getUserEmailDomain($user))->toBe('mail.company.com');
+ });
+
+ it('returns null for invalid email', function () use ($validator) {
+ $user = new User(['email' => 'invalid-email']);
+ expect($validator->getUserEmailDomain($user))->toBeNull();
+ });
+
+ it('returns null for empty email', function () use ($validator) {
+ $user = new User(['email' => '']);
+ expect($validator->getUserEmailDomain($user))->toBeNull();
+ });
+ });
+
+ describe('validateDomainForUser', function () use ($validator) {
+ it('validates domain matches user email domain', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->validateDomainForUser('company.com', $user))->toBeTrue();
+ });
+
+ it('rejects blocked providers', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->validateDomainForUser('gmail.com', $user))->toBeFalse();
+ });
+
+ it('rejects domains that do not match user email', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->validateDomainForUser('other.com', $user))->toBeFalse();
+ });
+
+ it('allows root domain match', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->validateDomainForUser('company.com', $user))->toBeTrue();
+ });
+
+ it('allows subdomain match', function () use ($validator) {
+ $user = new User(['email' => '[email protected]']);
+ expect($validator->validateDomainForUser('mail.company.com', $user))->toBeTrue();
+ });
+ });
+});
diff --git a/api/tests/Unit/Enterprise/Oidc/ValidOidcDomainTest.php b/api/tests/Unit/Enterprise/Oidc/ValidOidcDomainTest.php
new file mode 100644
index 000000000..5a4d85b84
--- /dev/null
+++ b/api/tests/Unit/Enterprise/Oidc/ValidOidcDomainTest.php
@@ -0,0 +1,122 @@
+<?php
+
+use App\Enterprise\Oidc\Rules\ValidOidcDomain;
+use App\Models\User;
+use Illuminate\Support\Facades\Validator;
+use Tests\TestCase;
+
+uses(TestCase::class);
+uses()->group('oidc', 'unit');
+
+describe('ValidOidcDomain Rule', function () {
+ it('passes when domain matches user email domain', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'company.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('fails when domain does not match user email domain', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'other.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeFalse();
+ expect($validator->errors()->first('domain'))->toContain('must match your email domain');
+ });
+
+ it('fails when domain is a blocked provider', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'gmail.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeFalse();
+ expect($validator->errors()->first('domain'))->toContain('Common email providers');
+ });
+
+ it('fails when user is not authenticated', function () {
+ // Don't authenticate any user
+ $validator = Validator::make(
+ ['domain' => 'company.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeFalse();
+ });
+
+ it('allows root domain match when user has subdomain email', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'company.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('allows subdomain match when user has root domain email', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'mail.company.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeTrue();
+ });
+
+ it('includes user domain in error message when available', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $validator = Validator::make(
+ ['domain' => 'other.com'],
+ ['domain' => [new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeFalse();
+ $errorMessage = $validator->errors()->first('domain');
+ expect($errorMessage)->toContain('company.com');
+ });
+
+ it('rejects invalid domain format', function () {
+ $user = User::factory()->create(['email' => '[email protected]']);
+ $this->actingAs($user);
+
+ $invalidDomains = [
+ '-invalid.com', // Starts with hyphen
+ 'invalid-.com', // Ends with hyphen
+ 'invalid..com', // Double dots
+ '.invalid.com', // Starts with dot
+ 'invalid.com.', // Ends with dot
+ 'a' . str_repeat('b', 64) . '.com', // Label too long (>63 chars)
+ 'invalid com', // Space
+ ];
+
+ foreach ($invalidDomains as $invalidDomain) {
+ $validator = Validator::make(
+ ['domain' => $invalidDomain],
+ ['domain' => ['required', new ValidOidcDomain()]]
+ );
+
+ expect($validator->passes())->toBeFalse("Domain '{$invalidDomain}' should be rejected");
+ expect($validator->errors()->first('domain'))->toContain('format');
+ }
+ });
+});
diff --git a/api/tests/Unit/Rules/StorageFileTest.php b/api/tests/Unit/Rules/StorageFileTest.php
index ad11084bd..fcde276fb 100644
--- a/api/tests/Unit/Rules/StorageFileTest.php
+++ b/api/tests/Unit/Rules/StorageFileTest.php
@@ -1,42 +1,71 @@
<?php
+use App\Service\Storage\FileUploadPathService;
+use App\Service\Storage\StorageFileNameParser;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+afterEach(function () {
+ Storage::clearResolvedInstances();
+ \Mockery::close();
+});
it('can validate file types', function () {
- Storage::shouldReceive('exists')
- ->andReturn(true);
- Storage::shouldReceive('size')
- ->andReturn(1000000);
+ Storage::fake();
$validator = new \App\Rules\StorageFile(1000000, ['jpg', 'JPEG', 'png']);
+
+ // Create valid files in fake storage
collect([
'file_name_' . Str::uuid() . '.jpg',
'file_name_' . Str::uuid() . '.png',
'file_name_' . Str::uuid() . '.JPG',
'file_name_' . Str::uuid() . '.JPEG'
])->each(function ($file) use ($validator) {
+ // Extract UUID from filename
+ $parser = StorageFileNameParser::parse($file);
+ $uuid = $parser->uuid;
+
+ // Create file in fake storage at tmp/{uuid} path
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+ Storage::put($path, str_repeat('x', 100)); // Small file
+
$this->assertTrue($validator->passes('file', $file));
});
- $this->assertFalse($validator->passes('file', 'file_name_' . Str::uuid() . '.pdf'));
+ // Test invalid file type
+ $invalidFile = 'file_name_' . Str::uuid() . '.pdf';
+ $parser = StorageFileNameParser::parse($invalidFile);
+ $uuid = $parser->uuid;
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+ Storage::put($path, str_repeat('x', 100));
+
+ $this->assertFalse($validator->passes('file', $invalidFile));
});
it('can validate file size', function () {
- Storage::shouldReceive('exists')
- ->andReturn(true);
- Storage::shouldReceive('size')
- ->andReturn(1000000);
+ Storage::fake();
$validator = new \App\Rules\StorageFile(1000000);
- $this->assertTrue($validator->passes('file', 'file_name_' . Str::uuid() . '.jpg'));
- Storage::clearResolvedInstances();
- Storage::shouldReceive('exists')
- ->andReturn(true)
- ->shouldReceive('size')
- ->andReturn(2000000);
+ // Create file with valid size (1MB)
+ $validFile = 'file_name_' . Str::uuid() . '.jpg';
+ $parser = StorageFileNameParser::parse($validFile);
+ $uuid = $parser->uuid;
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+ Storage::put($path, str_repeat('x', 1000000)); // Exactly 1MB
+
+ $this->assertTrue($validator->passes('file', $validFile));
+
+ // Create file with invalid size (2MB, exceeds limit)
+ $invalidFile = 'file_name_' . Str::uuid() . '.pdf';
+ $parser = StorageFileNameParser::parse($invalidFile);
+ $uuid = $parser->uuid;
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+ Storage::put($path, str_repeat('x', 2000000)); // 2MB file
- // Fake pdf with 2 times the authorized size
- $this->assertFalse($validator->passes('file', 'file_name_' . Str::uuid() . '.pdf'));
+ $this->assertFalse($validator->passes('file', $invalidFile));
});
diff --git a/client/api/index.js b/client/api/index.js
index fd6b7d6d4..90501b055 100644
--- a/client/api/index.js
+++ b/client/api/index.js
@@ -5,6 +5,7 @@ export { formsApi } from './forms'
export { templatesApi } from './templates'
export { billingApi } from './billing'
export { oauthApi } from './oauth'
+export { oidcApi } from './oidc'
export { tokensApi } from './tokens'
export { adminApi } from './admin'
export { uploadsApi } from './uploads'
diff --git a/client/api/oidc.js b/client/api/oidc.js
new file mode 100644
index 000000000..f2be935e2
--- /dev/null
+++ b/client/api/oidc.js
@@ -0,0 +1,36 @@
+import { apiService } from './base'
+
+const BASE_PATH = '/open/workspaces'
+
+export const oidcApi = {
+ // Workspace-scoped OIDC connections
+ list: (workspaceId, options) => apiService.get(`${BASE_PATH}/${workspaceId}/oidc-connections`, options),
+ get: (workspaceId, connectionId) => apiService.get(`${BASE_PATH}/${workspaceId}/oidc-connections/${connectionId}`),
+ create: (workspaceId, data) => apiService.post(`${BASE_PATH}/${workspaceId}/oidc-connections`, data),
+ update: (workspaceId, connectionId, data) => apiService.patch(`${BASE_PATH}/${workspaceId}/oidc-connections/${connectionId}`, data),
+ delete: (workspaceId, connectionId) => apiService.delete(`${BASE_PATH}/${workspaceId}/oidc-connections/${connectionId}`),
+
+ // Global OIDC connections
+ listGlobal: (options) => apiService.get('/oidc-connections', options),
+ getGlobal: (connectionId) => apiService.get(`/oidc-connections/${connectionId}`),
+ createGlobal: (data) => apiService.post('/oidc-connections', data),
+ updateGlobal: (connectionId, data) => apiService.patch(`/oidc-connections/${connectionId}`, data),
+ deleteGlobal: (connectionId) => apiService.delete(`/oidc-connections/${connectionId}`),
+
+ // Email-based OIDC lookup (for login flow)
+ getOptionsForEmail: (email) => apiService.post('/auth/oidc/options', { email }),
+
+ // OIDC callback - processes authorization code and returns token/user
+ callback: (slug, queryParams) => {
+ // Build query string from params
+ const queryString = new URLSearchParams(queryParams).toString()
+ const url = `/auth/${slug}/callback${queryString ? '?' + queryString : ''}`
+ // Use GET with Accept: application/json header to get JSON response
+ return apiService.get(url, {
+ headers: {
+ 'Accept': 'application/json'
+ }
+ })
+ },
+}
+
diff --git a/client/components/forms/core/VForm.vue b/client/components/forms/core/VForm.vue
index d173187df..7ec8b559a 100644
--- a/client/components/forms/core/VForm.vue
+++ b/client/components/forms/core/VForm.vue
@@ -1,5 +1,5 @@
<template>
- <form>
+ <form class="flex flex-col">
<slot />
</form>
</template>
@@ -12,11 +12,13 @@
const props = defineProps({
theme: { type: String, default: 'default' },
size: { type: String, default: "md" },
- borderRadius: { type: String, default: "small" }
+ borderRadius: { type: String, default: "small" },
+ form: { type: Object, default: null }
})
// Provide individual theme props for tailwind-variants approach
provide('formTheme', computed(() => props.theme))
provide('formSize', computed(() => props.size))
provide('formBorderRadius', computed(() => props.borderRadius))
+provide('form', computed(() => props.form))
</script>
diff --git a/client/components/forms/core/components/InputLabel.vue b/client/components/forms/core/components/InputLabel.vue
index 36ac2b368..65391fa2d 100644
--- a/client/components/forms/core/components/InputLabel.vue
+++ b/client/components/forms/core/components/InputLabel.vue
@@ -4,13 +4,13 @@
:class="ui.label({ class: props.ui?.slots?.label })"
>
<slot>
- <span class="align-baseline">{{ label }}</span>
+ <span>{{ label }}</span>
<span
v-if="required"
:class="ui.requiredDot({ class: props.ui?.slots?.requiredDot })"
aria-hidden="true"
>
- <Icon name="i-ix-mandatory" />
+ <Icon :class="ui.star({ class: props.ui?.slots?.star })" name="i-ix-mandatory" />
</span>
</slot>
</label>
@@ -42,5 +42,4 @@ const ui = computed(() => {
uppercaseLabels: props.uppercaseLabels
})
})
-
</script>
diff --git a/client/components/forms/core/components/InputWrapper.vue b/client/components/forms/core/components/InputWrapper.vue
index fb7cd77ca..6944456be 100644
--- a/client/components/forms/core/components/InputWrapper.vue
+++ b/client/components/forms/core/components/InputWrapper.vue
@@ -12,7 +12,7 @@
:native-for="id ? id : name"
:uppercase-labels="uppercaseLabels"
:theme="theme"
- :size="resolvedSize"
+ :size="size"
:presentation="presentationStyle"
:ui="ui?.label"
/>
@@ -77,6 +77,7 @@
</template>
<script setup>
+import { computed, inject, ref } from 'vue'
import InputLabel from './InputLabel.vue'
import InputHelp from './InputHelp.vue'
import {twMerge} from "tailwind-merge"
@@ -100,24 +101,11 @@ const props = defineProps({
media: { type: Object, default: null },
// Theme configuration as strings for tailwind-variants
theme: {type: String, default: 'default'},
- size: {type: String, default: null},
- borderRadius: {type: String, default: null},
+ size: {type: String, default: 'md'},
+ borderRadius: {type: String, default: 'small'},
ui: {type: Object, default: () => ({})}
})
-// Inject theme values for centralized resolution
-const injectedSize = inject('formSize', null)
-const injectedBorderRadius = inject('formBorderRadius', null)
-
-// Resolve size with proper reactivity
-const resolvedSize = computed(() => {
- return props.size || injectedSize?.value || 'md'
-})
-
-const resolvedBorderRadius = computed(() => {
- return props.borderRadius || injectedBorderRadius?.value || 'small'
-})
-
const injectedPresentationStyle = computed(() => {
return inject('formPresentationStyle', ref('classic'))?.value || 'classic'
})
@@ -125,8 +113,8 @@ const injectedPresentationStyle = computed(() => {
// OPTIMIZED: Single computed following Nuxt UI pattern
const ui = computed(() => {
return tv(inputWrapperTheme, props.ui)({
- size: resolvedSize.value,
- borderRadius: resolvedBorderRadius.value,
+ size: props.size,
+ borderRadius: props.borderRadius,
mediaStyle: 'intrinsic',
presentation: injectedPresentationStyle.value
})
diff --git a/client/components/forms/core/validation/HasError.vue b/client/components/forms/core/validation/HasError.vue
index 7b2246d90..7e1a92557 100644
--- a/client/components/forms/core/validation/HasError.vue
+++ b/client/components/forms/core/validation/HasError.vue
@@ -14,7 +14,8 @@ export default {
props: {
form: {
type: Object,
- required: true,
+ required: false,
+ default: null,
},
fieldId: {
type: String,
@@ -26,12 +27,12 @@ export default {
},
errorClasses: {
type: String,
- default: 'has-error text-xs text-red-500 mt-1 break-words whitespace-break-spaces',
+ default: 'has-error text-xs text-red-500 break-words whitespace-break-spaces',
},
},
computed: {
errorMessage() {
- if (!this.form.errors || !this.form.errors.any())
+ if (!this.form || !this.form.errors || !this.form.errors.any())
return null
const subErrorsKeys = Object.keys(this.form.errors.all()).filter(
(key) => {
diff --git a/client/components/forms/useFormInput.js b/client/components/forms/useFormInput.js
index 1f8941414..07e250fe3 100644
--- a/client/components/forms/useFormInput.js
+++ b/client/components/forms/useFormInput.js
@@ -44,6 +44,7 @@ export function useFormInput(props, context, options = {}) {
const injectedTheme = inject('formTheme', null)
const injectedSize = inject('formSize', null)
const injectedBorderRadius = inject('formBorderRadius', null)
+ const injectedForm = inject('form', null)
// Resolve theme values with proper reactivity
const resolvedTheme = computed(() => {
@@ -58,6 +59,10 @@ export function useFormInput(props, context, options = {}) {
return props.borderRadius || injectedBorderRadius?.value || 'small'
})
+ const resolvedForm = computed(() => {
+ return props.form || injectedForm?.value || null
+ })
+
const inputStyle = computed(() => {
return {
"--tw-ring-color": props.color,
@@ -66,25 +71,25 @@ export function useFormInput(props, context, options = {}) {
const hasValidation = computed(() => {
return (
- props.form !== null &&
- props.form !== undefined &&
- _has(props.form, "errors")
+ resolvedForm.value !== null &&
+ resolvedForm.value !== undefined &&
+ _has(resolvedForm.value, "errors")
)
})
const hasError = computed(() => {
- return hasValidation.value && props.form?.errors?.has(props.name)
+ return hasValidation.value && resolvedForm.value?.errors?.has(props.name)
})
const compVal = computed({
get: () => {
- if (props.form) {
- return _get(props.form, (composableOptions.formPrefixKey || "") + props.name)
+ if (resolvedForm.value) {
+ return _get(resolvedForm.value, (composableOptions.formPrefixKey || "") + props.name)
}
return content.value
},
set: (val) => {
- if (props.form) {
+ if (resolvedForm.value) {
const fullPath = (composableOptions.formPrefixKey || "") + props.name
const pathParts = fullPath.split('.')
@@ -98,7 +103,7 @@ export function useFormInput(props, context, options = {}) {
// replaced with an empty object so the nested structure can be created.
// - This ensures the form data structure is always valid for deeply nested fields.
if (pathParts.length > 1) {
- let current = props.form
+ let current = resolvedForm.value
for (let i = 0; i < pathParts.length - 1; i++) {
const part = pathParts[i]
if (!current[part] || typeof current[part] !== 'object') {
@@ -108,13 +113,13 @@ export function useFormInput(props, context, options = {}) {
}
}
- _set(props.form, fullPath, val)
+ _set(resolvedForm.value, fullPath, val)
} else {
content.value = val
}
if (hasValidation.value) {
- props.form.errors.clear(props.name)
+ resolvedForm.value.errors.clear(props.name)
}
context.emit("update:modelValue", compVal.value)
@@ -128,8 +133,11 @@ export function useFormInput(props, context, options = {}) {
wrapperProps[key] = props[key]
}
})
- // Add resolved theme to wrapper props
+ // Add resolved theme values to wrapper props
wrapperProps.theme = resolvedTheme.value
+ wrapperProps.size = resolvedSize.value
+ wrapperProps.borderRadius = resolvedBorderRadius.value
+ wrapperProps.form = resolvedForm.value
return wrapperProps
})
@@ -183,6 +191,7 @@ export function useFormInput(props, context, options = {}) {
resolvedTheme,
resolvedSize,
resolvedBorderRadius,
+ resolvedForm,
// Centralized UI variants - ready to use in templates
ui,
}
diff --git a/client/components/open/forms/components/templates/FormTemplateModal.vue b/client/components/open/forms/components/templates/FormTemplateModal.vue
index 669ba4158..20a25c479 100644
--- a/client/components/open/forms/components/templates/FormTemplateModal.vue
+++ b/client/components/open/forms/components/templates/FormTemplateModal.vue
@@ -26,9 +26,11 @@
<span class="font-semibold">{{ form.title }}</span>.
</p>
- <form
+ <v-form
v-if="templateForm"
+ :form="templateForm"
@submit.prevent="onSubmit"
+ @keydown="templateForm.onKeydown($event)"
>
<div class="space-y-4">
<toggle-switch-input
@@ -98,7 +100,7 @@
label="Frequently asked questions"
/>
</div>
- </form>
+ </v-form>
</template>
<template #footer>
diff --git a/client/components/open/tables/OpenTable.vue b/client/components/open/tables/OpenTable.vue
index 8049a4e58..4d73c1a5a 100644
--- a/client/components/open/tables/OpenTable.vue
+++ b/client/components/open/tables/OpenTable.vue
@@ -230,7 +230,6 @@ const tableState = useTableState(
const { tableColumns: allColumns, columnVisibility, columnPinning, columnSizing, columnWrapping, columnOrder, handleColumnResize: handleColumnResizeState } = tableState
const tableColumns = computed(() => {
- console.log('tableColumns changed')
return allColumns.value.filter(column => !['actions', 'select'].includes(column.id))
})
diff --git a/client/components/pages/auth/components/LoginForm.vue b/client/components/pages/auth/components/LoginForm.vue
index cd834fa5f..39c03fb18 100644
--- a/client/components/pages/auth/components/LoginForm.vue
+++ b/client/components/pages/auth/components/LoginForm.vue
@@ -5,34 +5,37 @@
@close="showForgotModal = false"
/>
- <form
+ <v-form
method="POST"
- class="mt-4"
+ :form="form"
@submit.prevent="login"
>
<!-- Email -->
<text-input
name="email"
- :form="form"
label="Email"
- :required="true"
+ required
placeholder="Your email address"
+ @blur="checkOidcOptions"
/>
- <!-- Password -->
+ <!-- Password - hidden if OIDC available and not forced to show -->
+ <VTransition name="fadeHeight">
<text-input
+ v-if="showPasswordField"
+ ref="passwordInputRef"
native-type="password"
placeholder="Your password"
name="password"
- :form="form"
label="Password"
- :required="true"
+ required
+ @input-filled="login"
/>
+ </VTransition>
- <!-- Remember Me -->
- <div class="relative flex items-center mt-3">
+ <!-- Remember Me & Forgot Password - only show when password field is visible -->
+ <div v-if="showPasswordField" class="relative flex items-center mt-1.5">
<CheckboxInput
- :form="form"
class="w-full md:w-1/2"
name="remember"
size="small"
@@ -57,7 +60,7 @@
size="lg"
:loading="form.busy"
type="submit"
- label="Log in to continue"
+ :label="oidcAvailable && !showPasswordField ? 'Continue' : 'Log in to continue'"
/>
<UButton
@@ -93,7 +96,7 @@
Sign Up
</NuxtLink>
</p>
- </form>
+ </v-form>
<!-- Google One Tap -->
<ClientOnly>
@@ -124,6 +127,10 @@ const oAuth = useOAuth()
const router = useRouter()
const { login: loginMutationFactory } = useAuth()
+// Feature flags
+const oidcAvailable = computed(() => useFeatureFlag('oidc.available', false))
+const oidcForced = computed(() => useFeatureFlag('oidc.forced', false))
+
// Reactive data
const form = useForm({
email: "",
@@ -133,6 +140,20 @@ const form = useForm({
const loginMutation = loginMutationFactory()
const showForgotModal = ref(false)
+const showPasswordField = ref(!oidcAvailable.value || oidcForced.value)
+const passwordInputRef = ref(null)
+
+// Watch for password field visibility to focus it
+watch(showPasswordField, async (newValue) => {
+ if (newValue) {
+ await nextTick()
+ // Find the password input element by name/id
+ const passwordInput = document.querySelector('input[name="password"][type="password"]')
+ if (passwordInput) {
+ passwordInput.focus()
+ }
+ }
+})
// Lifecycle
onMounted(() => {
@@ -146,7 +167,66 @@ onMounted(() => {
})
// Methods
+const checkOidcOptions = async () => {
+ if (!oidcAvailable.value || !form.email || form.busy) {
+ return
+ }
+
+ form.post('/auth/oidc/options', { body: { email: form.email } })
+ .then(async (response) => {
+ if (response.action === 'redirect') {
+ // Get the redirect URL from the backend
+ try {
+ const redirectResponse = await form.post(`/auth/${response.slug}/redirect`)
+
+ if (redirectResponse.redirect_url) {
+ // Redirect to OIDC provider
+ window.location.href = redirectResponse.redirect_url
+ return
+ } else if (redirectResponse.error) {
+ // Handle error from redirect endpoint
+ useAlert().error(redirectResponse.error || 'Failed to initiate OIDC authentication')
+ showPasswordField.value = true
+ return
+ }
+ } catch (error) {
+ // Handle network or server errors
+ const errorMessage = error.response?._data?.error || error.response?._data?.message || 'Failed to initiate OIDC authentication'
+ useAlert().error(errorMessage)
+ showPasswordField.value = true
+ return
+ }
+ } else if (response.action === 'blocked') {
+ // OIDC is forced but no connection found
+ useAlert().error('OIDC authentication is required. Please contact your administrator.')
+ return
+ } else {
+ // Fallback to password login
+ showPasswordField.value = true
+ }
+ })
+ .catch((error) => {
+ // Form automatically handles 422 validation errors (invalid email, etc.)
+ // Only show password field as fallback for non-validation errors
+ if (error.response?.status !== 422) {
+ showPasswordField.value = true
+ }
+ })
+}
+
const login = () => {
+ // If OIDC is available and password field is hidden, check OIDC options first
+ if (oidcAvailable.value && !showPasswordField.value && form.email) {
+ checkOidcOptions()
+ return
+ }
+
+ // Normal password login
+ if (!form.password && showPasswordField.value) {
+ useAlert().error('Password is required')
+ return
+ }
+
form.mutate(loginMutation).then(() => {
redirect()
}).catch((error) => {
diff --git a/client/components/pages/auth/components/RegisterForm.vue b/client/components/pages/auth/components/RegisterForm.vue
index e210f809c..52d0ed522 100644
--- a/client/components/pages/auth/components/RegisterForm.vue
+++ b/client/components/pages/auth/components/RegisterForm.vue
@@ -1,24 +1,22 @@
<template>
- <VForm size="sm"
+ <VForm size="md"
method="POST"
+ :form="form"
@submit.prevent="register"
- class="flex flex-col gap-1"
>
<!-- Name -->
<text-input
name="name"
- :form="form"
label="Name"
placeholder="Your name"
- :required="true"
+ required
/>
<!-- Email -->
<text-input
name="email"
- :form="form"
label="Email"
- :required="true"
+ required
:disabled="disableEmail"
placeholder="Your email address"
/>
@@ -27,10 +25,9 @@
v-if="!disableEmail && !isSetup"
name="hear_about_us"
:options="hearAboutUsOptions"
- :form="form"
placeholder="Select option"
label="How did you hear about us?"
- :required="true"
+ required
/>
<!-- Password -->
@@ -38,9 +35,8 @@
native-type="password"
placeholder="Enter password"
name="password"
- :form="form"
label="Password"
- :required="true"
+ required
@focus="isPasswordFocused = true"
@blur="isPasswordFocused = false"
/>
@@ -52,8 +48,7 @@
<!-- Password Confirmation-->
<text-input
native-type="password"
- :form="form"
- :required="true"
+ required
placeholder="Enter confirm password"
name="password_confirmation"
label="Confirm Password"
@@ -62,7 +57,7 @@
<!-- Captcha -->
<div
v-if="reCaptchaSiteKey"
- class="my-4 px-2 mx-auto w-max"
+ class="my-2 px-2 mx-auto w-max"
>
<CaptchaInput
ref="captcha"
@@ -73,10 +68,9 @@
</div>
<checkbox-input
- :form="form"
name="agree_terms"
- class="my-3"
- :required="true"
+ class="my-2"
+ required
v-if="!useFeatureFlag('self_hosted')"
>
<template #label>
@@ -104,7 +98,7 @@
<!-- Submit Button -->
<UButton
- class="mt-4"
+ class="mt-2"
block
size="lg"
:loading="form.busy"
@@ -113,7 +107,7 @@
/>
<template v-if="useFeatureFlag('services.google.auth') && !useFeatureFlag('self_hosted') && !isSetup">
- <p class="text-neutral-500 text-sm text-center my-4">
+ <p class="text-neutral-500 text-sm text-center my-2">
OR
</p>
<UButton
@@ -129,7 +123,7 @@
/>
</template>
- <p v-if="!isSetup" class="text-neutral-500 mt-4 text-sm text-center">
+ <p v-if="!isSetup" class="text-neutral-500 mt-2 text-sm text-center">
Already have an account?
<a
v-if="isQuick"
diff --git a/client/components/workspaces/settings/Modal.vue b/client/components/workspaces/settings/Modal.vue
index e87e39c27..e65a43d4d 100644
--- a/client/components/workspaces/settings/Modal.vue
+++ b/client/components/workspaces/settings/Modal.vue
@@ -15,7 +15,15 @@
</SettingsModalPage>
<SettingsModalPage
- v-if="workspace && !workspace.is_readonly"
+ id="members"
+ label="Members"
+ icon="i-heroicons-user-group"
+ >
+ <LazyWorkspacesSettingsMembers />
+ </SettingsModalPage>
+
+ <SettingsModalPage
+ v-if="workspace && workspace.is_admin"
id="domains"
label="Domains"
icon="i-heroicons-globe-alt"
@@ -24,7 +32,7 @@
</SettingsModalPage>
<SettingsModalPage
- v-if="workspace && !workspace.is_readonly"
+ v-if="workspace && workspace.is_admin"
id="emails"
label="Emails"
icon="i-heroicons-envelope"
@@ -33,11 +41,12 @@
</SettingsModalPage>
<SettingsModalPage
- id="members"
- label="Members"
- icon="i-heroicons-user-group"
+ v-if="workspace && workspace.is_admin"
+ id="sso"
+ label="SSO"
+ icon="i-heroicons-shield-check"
>
- <LazyWorkspacesSettingsMembers />
+ <LazyWorkspacesSettingsOidc />
</SettingsModalPage>
</SettingsModal>
diff --git a/client/components/workspaces/settings/Oidc.vue b/client/components/workspaces/settings/Oidc.vue
new file mode 100644
index 000000000..9ad7c8a48
--- /dev/null
+++ b/client/components/workspaces/settings/Oidc.vue
@@ -0,0 +1,267 @@
+<template>
+ <div class="space-y-4">
+
+ <UAlert
+ :icon="alertConfig.icon"
+ :color="alertConfig.color"
+ variant="subtle"
+ :title="alertConfig.title"
+ :description="alertConfig.description"
+ :actions="alertConfig.actions"
+ />
+
+ <div class="flex flex-col flex-wrap items-start justify-between gap-4 sm:flex-row sm:items-center">
+ <div>
+ <h3 class="text-lg font-medium text-neutral-900">SSO Settings</h3>
+ <p class="mt-1 text-sm text-neutral-500">
+ Configure OpenID Connect (OIDC) single sign-on for your workspace.
+ </p>
+ </div>
+
+ <UButton
+ v-if="canManageConnections && canAccessFeature"
+ label="Add Connection"
+ icon="i-heroicons-plus"
+ @click="showCreateModal = true"
+ />
+ <UButton
+ v-else-if="canManageConnections && !canAccessFeature"
+ label="Add Connection"
+ icon="i-heroicons-plus"
+ @click="openUpgradeModal"
+ />
+ </div>
+
+ <!-- Connections List -->
+ <div v-if="connectionsData && connectionsData.length > 0" class="space-y-3">
+ <p class="text-sm text-neutral-500 max-w-xl">
+ Each connection can be tied to one verified email domain, which we use to route incoming users to the
+ correct workspace when they start login. Manage multiple clients from here and toggle them on or off without
+ losing their configuration details.
+ </p>
+ <div class="grid gap-3 sm:grid-cols-2">
+ <OidcConnectionCard
+ v-for="connection in connectionsData"
+ :key="connection.id"
+ :connection="connection"
+ :can-edit="canManageConnections && canAccessFeature"
+ @edit="editConnection"
+ @delete="deleteConnection"
+ />
+ </div>
+ </div>
+
+ <!-- Empty State -->
+ <div v-else-if="!isConnectionsLoading" class="text-center py-12">
+ <UIcon
+ name="i-heroicons-key"
+ class="w-12 h-12 text-neutral-400 mx-auto mb-4"
+ />
+ <h4 class="text-lg font-medium text-neutral-900 mb-2">
+ No OIDC connections yet
+ </h4>
+ <p class="text-neutral-500 mb-4">
+ Configure your first OIDC connection to enable single sign-on for your workspace.
+ </p>
+ <UButton
+ v-if="canManageConnections && canAccessFeature"
+ label="Add Your First Connection"
+ icon="i-heroicons-plus"
+ @click="showCreateModal = true"
+ />
+ <UButton
+ v-else-if="canManageConnections && !canAccessFeature"
+ label="Add Your First Connection"
+ icon="i-heroicons-plus"
+ @click="openUpgradeModal"
+ />
+ </div>
+
+ <!-- Create/Edit Modal -->
+ <OidcConnectionModal
+ :model-value="showCreateModal"
+ :connection="editingConnection"
+ :form="connectionForm"
+ :is-busy="connectionForm.busy"
+ @update:model-value="showCreateModal = $event"
+ @save="saveConnection"
+ @cancel="cancelEdit"
+ />
+ </div>
+</template>
+
+<script setup>
+import { useOidcConnections } from '~/composables/query/useOidcConnections'
+import OidcConnectionCard from './OidcConnectionCard.vue'
+import OidcConnectionModal from './OidcConnectionModal.vue'
+
+const { current: workspace } = useCurrentWorkspace()
+const alert = useAlert()
+const { openSubscriptionModal } = useAppModals()
+
+const workspaceId = computed(() => workspace.value?.id)
+
+const canManageConnections = computed(() => !!workspace.value && workspace.value.is_admin)
+
+// Check if feature is accessible (Pro required for cloud, free for self-hosted)
+const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))
+const billingEnabled = computed(() => useFeatureFlag('billing.enabled'))
+const canAccessFeature = computed(() => {
+ // Self-hosted: always accessible
+ if (isSelfHosted.value) {
+ return true
+ }
+ // Cloud: requires Pro subscription
+ return billingEnabled.value && workspace.value?.is_pro
+})
+
+const { connections, create, update, remove } = useOidcConnections(workspaceId)
+
+// Allow viewing connections even without Pro (Pro only required for create/update/delete)
+const { data: connectionsData, isLoading: isConnectionsLoading } = connections()
+
+const alertConfig = computed(() => {
+ // Cloud + Free: Beta alert with upgrade button
+ if (!isSelfHosted.value && !canAccessFeature.value) {
+ return {
+ icon: 'i-heroicons-information-circle',
+ color: 'info',
+ title: 'Beta Feature - Pro Plan Required',
+ description: 'OIDC SSO is currently in beta and requires a Pro plan. This feature will soon be part of our Enterprise plan. Upgrade now to start using it.',
+ actions: [
+ {
+ label: 'Upgrade to Pro',
+ onClick: openUpgradeModal
+ }
+ ]
+ }
+ }
+
+ // Cloud + Paid: Warning about upcoming Enterprise plan
+ if (!isSelfHosted.value && canAccessFeature.value) {
+ return {
+ icon: 'i-heroicons-exclamation-triangle',
+ color: 'warning',
+ title: 'Beta Feature - Pricing Change Coming',
+ description: 'OIDC SSO is currently in beta and available on Pro plans. In the coming weeks, when we release our new pricing, this feature will move to our Enterprise plan.',
+ actions: []
+ }
+ }
+
+ // Self-hosted: Warning about future enterprise license requirement
+ return {
+ icon: 'i-heroicons-exclamation-triangle',
+ color: 'warning',
+ title: 'Beta Feature - Future Changes',
+ description: 'OIDC SSO is currently in beta and free for self-hosted installations. Future updates of OpnForm will require an enterprise license to use this feature.',
+ actions: []
+ }
+})
+
+const openUpgradeModal = () => {
+ openSubscriptionModal({
+ modal_title: 'Upgrade to Pro to use OIDC SSO',
+ modal_description: 'OIDC SSO is a Pro feature. Upgrade your plan to configure single sign-on for your workspace.'
+ })
+}
+
+const showCreateModal = ref(false)
+const editingConnection = ref(null)
+
+const connectionForm = useForm({
+ name: '',
+ slug: '',
+ issuer: '',
+ client_id: '',
+ client_secret: '',
+ domain: '',
+ enabled: true,
+ options: {
+ field_mappings: {
+ email: '',
+ name: ''
+ },
+ group_role_mappings: []
+ }
+})
+
+// Create mutations following useWorkspaces.js pattern
+const createMutation = create()
+const deleteMutation = remove()
+
+const saveConnection = () => {
+ if (editingConnection.value) {
+ // Update existing connection
+ const updateMutation = update(editingConnection.value.id)
+ connectionForm.mutate(updateMutation)
+ .then(() => {
+ alert.success('OIDC connection updated successfully')
+ showCreateModal.value = false
+ cancelEdit()
+ })
+ .catch((error) => {
+ // Form handles validation errors automatically
+ if (error.response?.status !== 422) {
+ alert.error(error.response?._data?.message ?? 'Failed to update connection')
+ }
+ })
+ } else {
+ // Create new connection
+ connectionForm.mutate(createMutation)
+ .then(() => {
+ alert.success('OIDC connection created successfully')
+ showCreateModal.value = false
+ connectionForm.reset()
+ })
+ .catch((error) => {
+ // Form handles validation errors automatically
+ if (error.response?.status !== 422) {
+ alert.error(error.response?._data?.message ?? 'Failed to create connection')
+ }
+ })
+ }
+}
+
+const editConnection = (connection) => {
+ editingConnection.value = connection
+ connectionForm.resetAndFill({
+ name: connection.name,
+ slug: connection.slug,
+ issuer: connection.issuer,
+ client_id: connection.client_id,
+ client_secret: '', // Don't pre-fill secret
+ enabled: connection.enabled,
+ domain: connection.domain ?? '',
+ options: {
+ field_mappings: {
+ email: connection.options?.field_mappings?.email ?? '',
+ name: connection.options?.field_mappings?.name ?? ''
+ },
+ group_role_mappings: connection.options?.group_role_mappings ?? []
+ }
+ })
+ showCreateModal.value = true
+}
+
+const deleteConnection = (connection) => {
+ alert.confirm(
+ `Are you sure you want to delete "${connection.name}"?`,
+ () => {
+ deleteMutation.mutateAsync(connection.id)
+ .then(() => {
+ alert.success('OIDC connection deleted successfully')
+ })
+ .catch((error) => {
+ alert.error(error.response?._data?.message ?? 'Failed to delete connection')
+ })
+ }
+ )
+}
+
+const cancelEdit = () => {
+ editingConnection.value = null
+ connectionForm.reset()
+ showCreateModal.value = false
+}
+</script>
+
diff --git a/client/components/workspaces/settings/OidcConnectionCard.vue b/client/components/workspaces/settings/OidcConnectionCard.vue
new file mode 100644
index 000000000..c8097d5bf
--- /dev/null
+++ b/client/components/workspaces/settings/OidcConnectionCard.vue
@@ -0,0 +1,64 @@
+<template>
+ <div class="group h-full rounded-xl border border-neutral-200 bg-white p-4 shadow-sm transition hover:shadow-md">
+ <div class="flex items-center justify-between gap-2">
+ <div>
+ <p class="text-sm font-semibold text-neutral-900">{{ connection.name }}</p>
+ <p class="text-xs uppercase tracking-wide text-neutral-400">{{ connection.slug }}</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <UButton
+ v-if="canEdit"
+ icon="i-heroicons-trash"
+ color="error"
+ variant="ghost"
+ size="xs"
+ square
+ class="opacity-0 transition group-hover:opacity-100"
+ @click="emit('delete', connection)"
+ />
+ <UButton
+ v-if="canEdit"
+ icon="i-heroicons-pencil"
+ color="neutral"
+ variant="ghost"
+ size="xs"
+ square
+ @click="emit('edit', connection)"
+ />
+ <UBadge :color="connection.enabled ? 'success' : 'neutral'" variant="subtle" size="sm">
+ {{ connection.enabled ? 'Enabled' : 'Disabled' }}
+ </UBadge>
+ </div>
+ </div>
+
+ <p class="mt-3 text-sm text-neutral-600">
+ Issuer URL
+ <span class="block font-medium text-neutral-900 truncate">{{ connection.issuer }}</span>
+ </p>
+
+ <p class="mt-2 text-sm text-neutral-600">
+ Redirect URL
+ <span class="block text-xs text-neutral-500 truncate">{{ connection.redirect_url }}</span>
+ </p>
+
+ <p class="mt-2 text-sm text-neutral-600">
+ Email domain
+ <span class="block font-medium text-neutral-900">{{ connection.domain ?? '—' }}</span>
+ </p>
+ </div>
+</template>
+
+<script setup>
+import { toRef } from 'vue'
+
+const props = defineProps({
+ connection: { type: Object, required: true },
+ canEdit: { type: Boolean, default: false },
+})
+
+const connection = toRef(props, 'connection')
+const canEdit = toRef(props, 'canEdit')
+
+const emit = defineEmits(['edit', 'delete'])
+</script>
+
diff --git a/client/components/workspaces/settings/OidcConnectionModal.vue b/client/components/workspaces/settings/OidcConnectionModal.vue
new file mode 100644
index 000000000..06373f15a
--- /dev/null
+++ b/client/components/workspaces/settings/OidcConnectionModal.vue
@@ -0,0 +1,326 @@
+<template>
+ <UModal v-model:open="isOpen" @close="handleCancel">
+ <template #header>
+ <h3 class="text-lg font-semibold">{{ modalTitle }}</h3>
+ </template>
+
+ <template #body>
+ <div class="flex justify-center">
+ <VForm :form="form" size="sm" @submit.prevent="handleSave" class="w-full max-w-md space-y-6">
+ <div class="space-y-4 rounded-xl border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-600">
+ <p class="text-xs uppercase tracking-wide text-neutral-500">General</p>
+ <TextInput
+ name="name"
+ :form="form"
+ label="Connection Name"
+ :required="true"
+ placeholder="Company SSO"
+ />
+
+ <TextInput
+ name="slug"
+ :form="form"
+ label="Slug"
+ :required="true"
+ placeholder="company-sso"
+ help="Lowercase, hyphens-only identifier that shows up in the redirect URLs."
+ />
+
+ <TextInput
+ name="domain"
+ :form="form"
+ label="Email Domain"
+ :required="true"
+ :placeholder="userEmailDomain || 'example.com'"
+ >
+ <template #help>
+ <div class="space-y-1">
+ <p v-if="userEmailDomain" class="text-xs text-neutral-500">
+ Must match your email domain ('{{ userEmailDomain }}' or another subdomain of it).
+ </p>
+ <p v-else class="text-xs text-neutral-500">
+ Must match your email domain (e.g., if your email is [email protected], use 'company.com' or another subdomain of it).
+ </p>
+ <p class="text-xs text-neutral-500">
+ Common email providers are not allowed.
+ <button
+ type="button"
+ class="text-blue-600 hover:text-blue-700 underline"
+ @click="openSupportChat"
+ >
+ Contact support
+ </button>
+ if you need help.
+ </p>
+ </div>
+ </template>
+ </TextInput>
+ </div>
+
+ <div class="space-y-4 rounded-xl border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-600">
+ <p class="text-xs uppercase tracking-wide text-neutral-500">Security</p>
+
+ <!-- Redirect URI Display -->
+ <div v-if="redirectUri" class="rounded-lg border border-blue-200 bg-blue-50 p-3">
+ <p class="text-xs font-medium text-blue-900 mb-1">Redirect URI</p>
+ <p class="text-xs text-blue-700 mb-2">
+ Copy this URL and add it to your OIDC provider's allowed redirect URIs:
+ </p>
+ <CopyContent
+ :content="redirectUri"
+ label="Copy"
+ />
+ </div>
+
+ <TextInput
+ name="issuer"
+ :form="form"
+ label="Issuer URL"
+ :required="true"
+ placeholder="https://idp.example.com"
+ help="Issued by your OIDC provider. Must match the redirect registered in that provider."
+ />
+
+ <TextInput
+ name="client_id"
+ :form="form"
+ label="Client ID"
+ :required="true"
+ placeholder="your-client-id"
+ />
+
+ <TextInput
+ name="client_secret"
+ :form="form"
+ label="Client Secret"
+ :required="true"
+ type="password"
+ placeholder="your-client-secret"
+ />
+
+ <ToggleSwitchInput
+ name="enabled"
+ class="mt-2"
+ :form="form"
+ label="Enabled"
+ />
+ </div>
+
+ <Collapse v-model="showFieldMappings" class="rounded-xl border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-600">
+ <template #title>
+ <p class="text-xs uppercase tracking-wide text-neutral-500">Field Mappings</p>
+ </template>
+ <div class="space-y-4 pt-2">
+ <p class="text-xs text-neutral-500">
+ Map IdP claim field names to OpnForm fields. Use this if your IdP uses different field names (e.g., "preferred_username" for email).
+ </p>
+
+ <div class="space-y-2">
+ <TextInput
+ name="options.field_mappings.email"
+ :form="form"
+ label="Email Field"
+ placeholder="email"
+ help="IdP claim name for email (e.g., 'email', 'preferred_username', 'mail'). Leave empty to use default 'email'."
+ size="sm"
+ />
+ <TextInput
+ name="options.field_mappings.name"
+ :form="form"
+ label="Name Field"
+ placeholder="name"
+ help="IdP claim name for full name (e.g., 'name', 'display_name'). Leave empty to use default 'name'."
+ size="sm"
+ />
+ </div>
+ </div>
+ </Collapse>
+
+ <Collapse v-model="showRoleMapping" class="rounded-xl border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-600">
+ <template #title>
+ <p class="text-xs uppercase tracking-wide text-neutral-500">Role Mapping</p>
+ </template>
+ <div class="space-y-4 pt-2">
+ <p class="text-xs text-neutral-500">
+ Map IdP groups to workspace roles. Users will be assigned the highest privilege role from their groups.
+ </p>
+
+ <div v-if="roleMappings.length === 0" class="text-center py-4 text-sm text-neutral-400">
+ No role mappings configured. Users will be assigned the default "member" role.
+ </div>
+
+ <div v-else class="space-y-2">
+ <div
+ v-for="(mapping, index) in roleMappings"
+ :key="index"
+ class="flex items-start gap-2 p-2 rounded-md border border-neutral-200 bg-white"
+ >
+ <div class="flex-1 grid grid-cols-2 gap-2">
+ <TextInput
+ :name="`options.group_role_mappings.${index}.idp_group`"
+ :form="form"
+ label="IdP Group"
+ placeholder="opnform_admins"
+ :required="true"
+ size="sm"
+ />
+ <SelectInput
+ :name="`options.group_role_mappings.${index}.role`"
+ :form="form"
+ label="Role"
+ :required="true"
+ size="sm"
+ :options="roleOptions"
+ />
+ </div>
+ <UButton
+ size="xs"
+ variant="ghost"
+ color="red"
+ icon="i-heroicons-trash"
+ square
+ class="mt-6"
+ @click="removeRoleMapping(index)"
+ />
+ </div>
+ </div>
+
+ <div v-if="showRoleMapping" class="flex justify-end">
+ <UButton
+ size="xs"
+ variant="ghost"
+ icon="i-heroicons-plus"
+ @click="addRoleMapping"
+ >
+ Add Mapping
+ </UButton>
+ </div>
+ </div>
+ </Collapse>
+ </VForm>
+ </div>
+ </template>
+
+ <template #footer>
+ <div class="flex justify-between gap-2 w-full">
+ <UButton variant="ghost" color="neutral" @click="handleCancel">Cancel</UButton>
+ <UButton type="submit" :loading="isBusy" :disabled="isBusy" @click="handleSave">
+ {{ actionLabel }}
+ </UButton>
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup>
+import Collapse from '@/components/app/Collapse.vue'
+import CopyContent from '@/components/open/forms/components/CopyContent.vue'
+import { appUrl } from '~/lib/utils.js'
+
+const props = defineProps({
+ modelValue: { type: Boolean, default: false },
+ form: { type: Object, required: true },
+ connection: { type: Object, default: null },
+ isBusy: { type: Boolean, default: false },
+})
+
+const emit = defineEmits(['update:modelValue', 'save', 'cancel'])
+
+const isEditing = computed(() => !!props.connection)
+const modalTitle = computed(() => (isEditing.value ? 'Edit OIDC Connection' : 'Add OIDC Connection'))
+const actionLabel = computed(() => (isEditing.value ? 'Update' : 'Create'))
+
+const isOpen = computed({
+ get: () => props.modelValue,
+ set: (value) => emit('update:modelValue', value),
+})
+
+// Get user email domain
+const { data: user } = useAuth().user()
+const userEmailDomain = computed(() => {
+ if (!user.value?.email) return null
+ const email = user.value.email
+ const parts = email.split('@')
+ return parts.length === 2 ? parts[1] : null
+})
+
+// Pre-fill domain field with user's email domain when creating new connection
+watch([isOpen, userEmailDomain], ([isOpenVal, domain]) => {
+ if (isOpenVal && !isEditing.value && domain && !props.form.domain) {
+ props.form.domain = domain
+ }
+})
+
+// Open Crisp chat for support
+const openSupportChat = () => {
+ useCrisp().openChat()
+}
+
+const roleOptions = [
+ { value: 'member', name: 'Member' },
+ { value: 'editor', name: 'Editor' },
+ { value: 'admin', name: 'Admin' },
+ { value: 'owner', name: 'Owner' },
+]
+
+const roleMappings = computed({
+ get: () => {
+ return props.form.options?.group_role_mappings || []
+ },
+ set: (value) => {
+ if (!props.form.options) {
+ props.form.options = {}
+ }
+ props.form.options.group_role_mappings = value
+ }
+})
+
+const hasFieldMappings = computed(() => {
+ const mappings = props.form.options?.field_mappings || {}
+ return !!(mappings.email || mappings.name)
+})
+
+const showFieldMappings = ref(hasFieldMappings.value)
+
+const showRoleMapping = ref(roleMappings.value.length > 0)
+
+const redirectUri = computed(() => {
+ const slug = props.form.slug
+ if (!slug) return null
+
+ // Use appUrl helper to construct the redirect URI
+ return appUrl(`/auth/${slug}/callback`)
+})
+
+watch(hasFieldMappings, (newVal) => {
+ if (!showFieldMappings.value && newVal) {
+ showFieldMappings.value = true
+ }
+})
+
+watch(roleMappings, (newVal) => {
+ if (!showRoleMapping.value && newVal.length > 0) {
+ showRoleMapping.value = true
+ }
+}, { deep: true })
+
+const addRoleMapping = () => {
+ const current = roleMappings.value || []
+ roleMappings.value = [...current, { idp_group: '', role: 'member' }]
+ if (!showRoleMapping.value) {
+ showRoleMapping.value = true
+ }
+}
+
+const removeRoleMapping = (index) => {
+ const current = roleMappings.value || []
+ roleMappings.value = current.filter((_, i) => i !== index)
+}
+
+const handleSave = () => emit('save')
+const handleCancel = () => {
+ emit('cancel')
+ emit('update:modelValue', false)
+}
+</script>
+
diff --git a/client/composables/query/useOidcConnections.js b/client/composables/query/useOidcConnections.js
new file mode 100644
index 000000000..16e8c112f
--- /dev/null
+++ b/client/composables/query/useOidcConnections.js
@@ -0,0 +1,136 @@
+import { useQueryClient, useQuery, useMutation } from '@tanstack/vue-query'
+import { oidcApi } from '~/api/oidc'
+
+export function useOidcConnections(workspaceId) {
+ const queryClient = useQueryClient()
+
+ // Resolve workspaceId value (handles both refs and plain values)
+ const workspaceIdValue = computed(() => {
+ return typeof workspaceId === 'function' ? workspaceId.value : workspaceId?.value ?? workspaceId
+ })
+
+ // Queries
+ const connections = (options = {}) => {
+ return useQuery({
+ queryKey: ['oidc-connections', workspaceIdValue],
+ queryFn: () => {
+ const id = workspaceIdValue.value
+ return id
+ ? oidcApi.list(id, options)
+ : oidcApi.listGlobal(options)
+ },
+ enabled: computed(() => !!workspaceIdValue.value || workspaceIdValue.value === null),
+ ...options
+ })
+ }
+
+ const connection = (connectionId, options = {}) => {
+ return useQuery({
+ queryKey: ['oidc-connections', workspaceIdValue, connectionId],
+ queryFn: () => {
+ const id = workspaceIdValue.value
+ return id
+ ? oidcApi.get(id, connectionId)
+ : oidcApi.getGlobal(connectionId)
+ },
+ enabled: computed(() => !!connectionId && (!!workspaceIdValue.value || workspaceIdValue.value === null)),
+ ...options
+ })
+ }
+
+ // Mutations - following useWorkspaces.js pattern
+ const create = (options = {}) => {
+ return useMutation({
+ mutationFn: (data) => {
+ const id = workspaceIdValue.value
+ return id
+ ? oidcApi.create(id, data)
+ : oidcApi.createGlobal(data)
+ },
+ onSuccess: (newConnection) => {
+ const queryKey = ['oidc-connections', workspaceIdValue]
+
+ // Cache individual connection
+ queryClient.setQueryData(['oidc-connections', workspaceIdValue, newConnection.id], newConnection)
+
+ // Optimistically update list cache
+ queryClient.setQueryData(queryKey, (old) => {
+ if (!old) return [newConnection]
+ if (!Array.isArray(old)) return old
+ return [...old, newConnection]
+ })
+ },
+ ...options
+ })
+ }
+
+ const update = (connectionId, options = {}) => {
+ return useMutation({
+ mutationFn: (data) => {
+ const id = workspaceIdValue.value
+ return id
+ ? oidcApi.update(id, toValue(connectionId), data)
+ : oidcApi.updateGlobal(toValue(connectionId), data)
+ },
+ onSuccess: (updatedConnection) => {
+ const connId = toValue(connectionId)
+ const queryKey = ['oidc-connections', workspaceIdValue]
+
+ // Update individual connection cache
+ queryClient.setQueryData(['oidc-connections', workspaceIdValue, connId], updatedConnection)
+
+ // Optimistically update list cache
+ queryClient.setQueryData(queryKey, (old) => {
+ if (!Array.isArray(old)) return old
+ return old.map(conn =>
+ conn.id === connId ? { ...conn, ...updatedConnection } : conn
+ )
+ })
+ },
+ ...options
+ })
+ }
+
+ const remove = (options = {}) => {
+ return useMutation({
+ mutationFn: (connectionId) => {
+ const id = workspaceIdValue.value
+ return id
+ ? oidcApi.delete(id, connectionId)
+ : oidcApi.deleteGlobal(connectionId)
+ },
+ onSuccess: (_, deletedConnectionId) => {
+ const queryKey = ['oidc-connections', workspaceIdValue]
+
+ // Remove from individual cache
+ queryClient.removeQueries({ queryKey: ['oidc-connections', workspaceIdValue, deletedConnectionId] })
+
+ // Remove from list cache
+ queryClient.setQueryData(queryKey, (old) => {
+ if (!Array.isArray(old)) return old
+ return old.filter(conn => conn.id !== deletedConnectionId)
+ })
+ },
+ ...options
+ })
+ }
+
+ const invalidate = () => {
+ queryClient.invalidateQueries({ queryKey: ['oidc-connections', workspaceIdValue] })
+ }
+
+ return {
+ // Queries
+ connections,
+ connection,
+
+ // Mutations
+ create,
+ update,
+ remove,
+
+ // Utilities
+ invalidate,
+ }
+}
+
diff --git a/client/lib/forms/themes/input-label.theme.js b/client/lib/forms/themes/input-label.theme.js
index f8518e141..844a3a548 100644
--- a/client/lib/forms/themes/input-label.theme.js
+++ b/client/lib/forms/themes/input-label.theme.js
@@ -8,7 +8,8 @@ export const inputLabelTheme = {
'input-label inline align-baseline',
'text-neutral-700 dark:text-neutral-300'
],
- requiredDot: 'text-red-500 dark:text-red-400 rounded-full bg-red-500/20 dark:bg-red-500/20 required-dot inline-flex items-center align-middle ml-1 *:size-4 *:-m-0.5'
+ requiredDot: 'relative size-[12px] text-red-500 dark:text-red-400 rounded-full bg-red-500/20 dark:bg-red-500/20 required-dot inline-flex items-center justify-center ml-1 align-middle',
+ star: 'absolute size-4 left-1/2 top-1/2 -translate-y-1/2 -translate-x-1/2'
},
variants: {
presentation: {
@@ -37,6 +38,7 @@ export const inputLabelTheme = {
},
sm: {
label: 'text-xs',
+ requiredDot: 'mb-[2px]!'
},
md: {
label: 'text-sm',
@@ -44,7 +46,7 @@ export const inputLabelTheme = {
},
lg: {
label: 'text-base',
- requiredDot: '*:size-5 mt-[-3px]!'
+ requiredDot: 'mt-[-3px]!'
}
},
uppercaseLabels: {
diff --git a/client/lib/forms/themes/input-wrapper.theme.js b/client/lib/forms/themes/input-wrapper.theme.js
index 9e3887ced..4d2ed4c26 100644
--- a/client/lib/forms/themes/input-wrapper.theme.js
+++ b/client/lib/forms/themes/input-wrapper.theme.js
@@ -8,7 +8,7 @@ export const inputWrapperTheme = {
'relative flex flex-col gap-1'
],
help: 'text-neutral-500',
- error: 'has-error text-xs text-red-500 mt-1 break-words whitespace-break-spaces',
+ error: 'has-error text-xs text-red-500 break-words whitespace-break-spaces',
media: '',
// classes for the media component root (e.g., <BlockMediaLayout />)
mediaComponent: '',
@@ -62,10 +62,10 @@ export const inputWrapperTheme = {
{ mediaStyle: 'intrinsic', borderRadius: 'full', class: { mediaImg: 'rounded-[20px]' } },
// Text size adjustments for focused presentation (help and error)
- { presentation: 'focused', size: 'xs', class: { help: 'text-sm', error: 'text-sm text-red-500 mt-0 leading-none' } },
- { presentation: 'focused', size: 'sm', class: { help: 'text-sm', error: 'text-sm mt-0 leading-none' } },
- { presentation: 'focused', size: 'md', class: { help: 'text-base', error: 'text-sm mt-0 leading-none' } },
- { presentation: 'focused', size: 'lg', class: { help: 'text-lg', error: 'text-base mt-0 leading-none' } }
+ { presentation: 'focused', size: 'xs', class: { help: 'text-sm', error: 'text-sm text-red-500 leading-none' } },
+ { presentation: 'focused', size: 'sm', class: { help: 'text-sm', error: 'text-sm leading-none' } },
+ { presentation: 'focused', size: 'md', class: { help: 'text-base', error: 'text-sm leading-none' } },
+ { presentation: 'focused', size: 'lg', class: { help: 'text-lg', error: 'text-base leading-none' } }
],
defaultVariants: {
size: 'md',
diff --git a/client/package-lock.json b/client/package-lock.json
index 9c19f69fd..967654a62 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -67,6 +67,7 @@
"@iconify-json/heroicons": "^1.2.2",
"@iconify-json/ic": "^1.2.1",
"@iconify-json/ix": "^1.2.10",
+ "@iconify-json/lucide": "^1.2.74",
"@iconify-json/octicon": "^1.2.1",
"@iconify-json/tabler": "^1.2.1",
"@nuxt/eslint-config": "^1.3.0",
@@ -1833,6 +1834,16 @@
"@iconify/types": "*"
}
},
+ "node_modules/@iconify-json/lucide": {
+ "version": "1.2.74",
+ "resolved": "https://registry.npmjs.org/@iconify-json/lucide/-/lucide-1.2.74.tgz",
+ "integrity": "sha512-vDoGHcDZdWgUbt9J3TCJlxFzX/Mw0vUIAoZdkfI2mINOi1/cgVZHivgZ8QtiGlepskTL3PcG8t93Ky/vtQgXGA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "@iconify/types": "*"
+ }
+ },
"node_modules/@iconify-json/material-symbols": {
"version": "1.2.29",
"resolved": "https://registry.npmjs.org/@iconify-json/material-symbols/-/material-symbols-1.2.29.tgz",
diff --git a/client/package.json b/client/package.json
index f711384b6..9c024abc9 100644
--- a/client/package.json
+++ b/client/package.json
@@ -19,6 +19,7 @@
"@iconify-json/heroicons": "^1.2.2",
"@iconify-json/ic": "^1.2.1",
"@iconify-json/ix": "^1.2.10",
+ "@iconify-json/lucide": "^1.2.74",
"@iconify-json/octicon": "^1.2.1",
"@iconify-json/tabler": "^1.2.1",
"@nuxt/eslint-config": "^1.3.0",
diff --git a/client/pages/auth/[slug]/callback.vue b/client/pages/auth/[slug]/callback.vue
new file mode 100644
index 000000000..4024e96d4
--- /dev/null
+++ b/client/pages/auth/[slug]/callback.vue
@@ -0,0 +1,105 @@
+<template>
+ <div class="flex flex-grow mt-6 mb-10">
+ <div class="w-full md:w-2/3 md:mx-auto md:max-w-md px-4">
+ <div
+ v-if="loading"
+ class="m-10"
+ >
+ <h3 class="my-6 text-center">
+ Completing sign in...
+ </h3>
+ <Loader class="h-6 w-6 mx-auto m-10" />
+ </div>
+ <div
+ v-else-if="error"
+ class="m-6 flex flex-col items-center space-y-4"
+ >
+ <UAlert
+ icon="i-lucide-alert-triangle"
+ color="error"
+ variant="subtle"
+ class="w-full"
+ :description="error"
+ />
+ <UButton
+ :to="{ name: 'login' }"
+ label="Back to login"
+ />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { oidcApi } from "~/api"
+
+const router = useRouter()
+const route = useRoute()
+const loading = ref(true)
+const error = ref(null)
+const authFlow = useAuthFlow()
+
+const handleCallback = async () => {
+ const slug = route.params.slug
+
+ try {
+ // Build query params object from route
+ const queryParams = {}
+ Object.keys(route.query).forEach(key => {
+ if (route.query[key]) {
+ queryParams[key] = route.query[key]
+ }
+ })
+
+ // Call the OIDC callback endpoint to process authorization code
+ const response = await oidcApi.callback(slug, queryParams)
+
+ // Response should contain token and user
+ if (response.token && response.user) {
+ // Handle authentication success (response already has the right structure)
+ await authFlow.handleAuthSuccess(response, 'oidc', response.new_user)
+
+ // Redirect based on user status (aligned with OAuth callback pattern)
+ if (response.new_user) {
+ router.push({ name: "forms-create" })
+ useAlert().success("Success! You're now registered with OIDC. Welcome to OpnForm.")
+ } else {
+ // For existing users, redirect to intended URL or home (aligned with OAuth)
+ router.push({ name: "home" })
+ useAlert().success("Successfully signed in!")
+ }
+ } else {
+ throw new Error("Unexpected response format from OIDC callback")
+ }
+ } catch (err) {
+ console.error("[OIDC Callback] Authentication error:", err)
+
+ const errorMessage = err.response?._data?.message || err.message || "Authentication failed"
+ error.value = errorMessage
+
+ // Handle specific error cases
+ if (errorMessage.includes('account with this email already exists')) {
+ error.value = 'An account with this email already exists. Please contact your administrator to link your accounts.'
+ } else if (errorMessage.includes('blocked')) {
+ error.value = 'Your account has been blocked. Please contact support.'
+ }
+
+ loading.value = false
+ }
+}
+
+onMounted(() => {
+ // Set a timeout to ensure we don't get stuck in loading state
+ const timeoutId = setTimeout(() => {
+ if (loading.value) {
+ loading.value = false
+ error.value = 'Authentication timed out. Please try again.'
+ }
+ }, 10000) // 10 second timeout
+
+ handleCallback().finally(() => {
+ clearTimeout(timeoutId)
+ })
+})
+</script>
+
diff --git a/docs/configuration/environment-variables.mdx b/docs/configuration/environment-variables.mdx
index e359592a9..a8d1c7a0f 100644
--- a/docs/configuration/environment-variables.mdx
+++ b/docs/configuration/environment-variables.mdx
@@ -14,6 +14,7 @@ The following environment variables are used to [configure the Laravel](https://
There are dedicated configuration pages available for more detailed setup instructions on specific topics:
- [OAuth Integration Setup](../configuration/oauth-setup)
+- [OIDC SSO Configuration](../configuration/oidc-sso)
- [File Storage (S3)](../configuration/aws-s3)
- [Email Configuration (SMTP)](../configuration/email-setup)
- [Custom Domain](../configuration/custom-domain)
@@ -21,21 +22,22 @@ There are dedicated configuration pages available for more detailed setup instru
### Configuration Environment Variables
-| Variable Name | Description |
-| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
-| `H_CAPTCHA_SITE_KEY` | Site key for hCaptcha integration. |
-| `H_CAPTCHA_SECRET_KEY` | Secret key for hCaptcha integration. |
-| `RE_CAPTCHA_SITE_KEY` | Site key for reCAPTCHA integration. |
-| `RE_CAPTCHA_SECRET_KEY` | Secret key for reCAPTCHA integration. |
-| `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. |
-| `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). |
-| `JWT_SECRET` | Secret key used to sign JWTs. |
-| `JWT_SKIP_IP_UA_VALIDATION` | Set to `true` to disable JWT IP and User Agent validation (defaults to `false`). Useful for dynamic IPs. |
-| `CUSTOM_CODE_ENABLE_SELF_HOSTED` | Enables execution of user-provided custom code on self-hosted deployments. Defaults to `false` for safety reasons (XSS etc.). |
+| Variable Name | Description |
+| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `H_CAPTCHA_SITE_KEY` | Site key for hCaptcha integration. |
+| `H_CAPTCHA_SECRET_KEY` | Secret key for hCaptcha integration. |
+| `RE_CAPTCHA_SITE_KEY` | Site key for reCAPTCHA integration. |
+| `RE_CAPTCHA_SECRET_KEY` | Secret key for reCAPTCHA integration. |
+| `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. |
+| `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). |
+| `JWT_SECRET` | Secret key used to sign JWTs. |
+| `JWT_SKIP_IP_UA_VALIDATION` | Set to `true` to disable JWT IP and User Agent validation (defaults to `false`). Useful for dynamic IPs. |
+| `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. |
+| `CUSTOM_CODE_ENABLE_SELF_HOSTED` | Enables execution of user-provided custom code on self-hosted deployments. Defaults to `false` for safety reasons (XSS etc.). |
### OAuth Integration Environment Variables
diff --git a/docs/configuration/oidc-sso.mdx b/docs/configuration/oidc-sso.mdx
new file mode 100644
index 000000000..86346620e
--- /dev/null
+++ b/docs/configuration/oidc-sso.mdx
@@ -0,0 +1,281 @@
+---
+title: OIDC SSO Configuration
+description: Complete guide to configuring OpenID Connect Single Sign-On for your workspace
+---
+
+<Info>
+ **Enterprise Feature**: OIDC SSO is part of our Enterprise Edition. During
+ the beta period: - **Self-hosted**: Free to use (no subscription required) -
+ **Cloud**: Available on Pro plan (will move to Enterprise plan soon) This
+ feature helps fund ongoing development and keeps OpnForm sustainable. For
+ more information about Enterprise licensing, see our [Enterprise
+ Terms](https://opnform.com/terms-conditions).
+</Info>
+
+OpnForm supports OpenID Connect (OIDC) based Single Sign-On (SSO), allowing users to authenticate using their organization's identity provider (IdP) such as Azure Entra ID, Authentik, Okta, or any OIDC-compliant provider.
+
+<Info>
+ OpnForm handles OIDC redirect URLs automatically. You don't need to manually
+ configure redirect URLs in your OIDC provider - the system generates them
+ dynamically and displays them in the connection settings.
+</Info>
+
+## Features
+
+- **Domain-Based Routing**: Automatically routes users to the correct OIDC provider based on their email domain
+- **Group-to-Role Mapping**: Automatically assign workspace roles based on IdP groups
+- **Custom Field Mappings**: Support for custom claim field names from your IdP
+- **Automatic User Provisioning**: Creates users automatically on first login
+- **Force Login Mode**: Optionally require all users to authenticate via OIDC
+
+## Prerequisites
+
+Before setting up OIDC SSO, ensure you have:
+
+1. An OIDC-compliant identity provider (IdP) configured
+2. OAuth client credentials (Client ID and Client Secret) from your IdP
+3. Admin access to the workspace where you want to configure SSO
+4. The issuer URL from your IdP (typically found in the `.well-known/openid-configuration` endpoint)
+
+## Setup Steps
+
+<Steps>
+<Step title="Get OIDC Provider Information">
+ From your identity provider, collect the following information:
+
+ - **Issuer URL**: The base URL of your IdP (e.g., `https://idp.company.com` or `https://login.microsoftonline.com/{tenant-id}/v2.0`)
+ - **Client ID**: OAuth client identifier
+ - **Client Secret**: OAuth client secret
+ - **Email Domain**: The domain you want to use for routing (e.g., `company.com`)
+
+ <Tip>
+ The issuer URL is typically found in your IdP's OpenID configuration endpoint:
+ `{issuer}/.well-known/openid-configuration`
+ </Tip>
+
+</Step>
+
+<Step title="Create OIDC Connection">
+ 1. Navigate to your workspace settings
+ 2. Go to the **SSO** section
+ 3. Click **Add Connection**
+ 4. Fill in the connection details:
+
+ - **Name**: Display name for this connection (e.g., "Company SSO")
+ - **Slug**: Unique identifier used in URLs (e.g., `company-sso`)
+ - **Email Domain**: Domain for routing users (e.g., `company.com`)
+ - **Issuer URL**: Your IdP's issuer URL
+ - **Client ID**: OAuth client ID from your IdP
+ - **Client Secret**: OAuth client secret from your IdP
+
+ <Check>
+ The redirect URI will be displayed automatically. Copy this URL and add it to your IdP's allowed redirect URIs.
+ </Check>
+
+</Step>
+
+<Step title="Configure Redirect URI in IdP">
+ 1. Copy the redirect URI shown in the connection form
+ 2. In your IdP's application settings, add this redirect URI to the allowed redirect URIs list
+ 3. Save the configuration in your IdP
+
+ <Warning>
+ **Important**: The redirect URI must match exactly. Ensure you copy the full URL including the protocol (https://) and path.
+ </Warning>
+
+</Step>
+
+<Step title="Configure Group-to-Role Mapping (Optional)">
+ If your IdP provides group information in the ID token, you can map IdP groups to workspace roles:
+
+ 1. In the connection settings, expand **Role Mappings**
+ 2. Click **Add Mapping**
+ 3. Enter the IdP group name (as it appears in your ID token)
+ 4. Select the corresponding workspace role (owner, admin, editor, or member)
+ 5. Repeat for each group you want to map
+
+ <Info>
+ If a user belongs to multiple groups, the highest privilege role will be assigned. Role priority: owner > admin > editor > member.
+ </Info>
+
+</Step>
+
+<Step title="Configure Field Mappings (Optional)">
+ If your IdP uses non-standard claim names for email or name:
+
+ 1. In the connection settings, expand **Field Mappings**
+ 2. Enter the custom claim field name for email (if different from `email`)
+ 3. Enter the custom claim field name for name (if different from `name`)
+ 4. Save the connection
+
+ <Note>
+ If field mappings are not configured, OpnForm will use standard OIDC claim names (`email`, `name`, etc.).
+ </Note>
+
+</Step>
+
+<Step title="Enable and Test">
+ 1. Ensure the connection is **Enabled**
+ 2. Save the connection
+ 3. Test the login flow:
+ - Navigate to the login page
+ - Enter an email address matching your configured domain
+ - You should be redirected to your IdP for authentication
+ - After successful authentication, you'll be redirected back and logged in
+
+ <Check>
+ If everything is configured correctly, users with emails from your domain will automatically be routed to your IdP for authentication.
+ </Check>
+
+</Step>
+</Steps>
+
+## Force Login Mode
+
+Force Login Mode requires all users to authenticate via OIDC, disabling password-based login.
+
+### Configuration
+
+Set the `OIDC_FORCE_LOGIN` environment variable to `true` in your backend `.env` file:
+
+```bash
+OIDC_FORCE_LOGIN=true
+```
+
+<Warning>
+ **Important**: Ensure at least one OIDC connection is configured and enabled
+ before enabling `force_login`. If no connections exist, password login will
+ remain available as a fallback.
+</Warning>
+
+### Behavior
+
+When enabled:
+
+- Password-based login attempts are blocked
+- 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
+
+### Use Cases
+
+- Organizations requiring all users to authenticate via corporate SSO
+- Security policies mandating centralized identity management
+- Compliance requirements for authentication methods
+
+For more details, see the [Environment Variables](../configuration/environment-variables#oidc_force_login) documentation.
+
+## Supported Providers
+
+OpnForm is compatible with any OIDC-compliant identity provider, including:
+
+- **Azure Entra ID** (formerly Azure AD)
+- **Authentik**
+- **Okta**
+- **Keycloak**
+- **Google Workspace** (via OIDC)
+- Any other OIDC-compliant provider
+
+### Azure Entra ID Specific Notes
+
+- May require additional scopes (e.g., `groups`) to include groups in the ID token
+- Configure group claims in Azure AD app registration → Token configuration
+- Choose "Security groups" or "Directory roles" as needed
+
+### Authentik Specific Notes
+
+- Groups are typically included automatically in ID tokens
+- Standard OIDC configuration works out of the box
+
+## Troubleshooting
+
+<AccordionGroup>
+<Accordion title="Users Not Being Redirected to IdP">
+ **Possible causes:**
+
+ - Email domain doesn't match the configured domain
+ - Connection is disabled
+ - Domain not properly configured in connection settings
+
+ **Solution**: Verify the domain matches exactly (case-insensitive) and the connection is enabled.
+
+</Accordion>
+
+<Accordion title="Redirect URI Mismatch Error">
+ **Possible causes:**
+
+ - Redirect URI not added to IdP's allowed list
+ - Redirect URI copied incorrectly
+ - HTTPS/HTTP mismatch
+
+ **Solution**: Copy the exact redirect URI from the connection settings and ensure it's added to your IdP's allowed redirect URIs. Verify HTTPS is used in production.
+
+</Accordion>
+
+<Accordion title="Groups Not Mapping to Roles">
+ **Possible causes:**
+
+ - Groups not included in ID token
+ - Group names don't match exactly
+ - Group claim not configured in IdP
+
+ **Solution**: Verify groups are included in your ID token. Check group names match exactly (case-sensitive). For Azure AD, configure group claims in app registration settings.
+
+</Accordion>
+
+<Accordion title="User Creation Fails">
+ **Possible causes:**
+
+ - Email claim missing from ID token
+ - Field mappings incorrect
+ - Account with same email already exists (account linking blocked for security)
+
+ **Solution**: Verify email is present in ID token. Check field mappings if using custom claim names. For existing accounts, contact administrator to link accounts.
+
+</Accordion>
+
+<Accordion title="Force Login Not Working">
+ **Possible causes:**
+
+ - `OIDC_FORCE_LOGIN` not set to `true`
+ - No OIDC connections configured
+ - Environment variable not loaded (restart required)
+
+ **Solution**: Verify environment variable is set correctly. Ensure at least one OIDC connection exists and is enabled. Restart application after changing environment variables.
+
+</Accordion>
+</AccordionGroup>
+
+## Security Considerations
+
+### HTTPS Requirement
+
+In production, all OIDC redirects require HTTPS. Ensure your application is served over HTTPS before configuring OIDC.
+
+### 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.
+
+### SSO-Only Accounts
+
+Users created via OIDC SSO are created with:
+
+- Random 64-character password (prevents password-based login)
+- Email automatically verified
+- Provider metadata stored for tracking
+
+These accounts can only authenticate via OIDC, not with passwords.
+
+## Best Practices
+
+- **Test First**: Always test with a small group before rolling out to all users
+- **Monitor Logs**: Check application logs for OIDC-related errors during initial setup
+- **Backup Access**: Ensure at least one admin account can still access the system if OIDC fails
+- **Regular Updates**: Keep your IdP configuration in sync with OpnForm connection settings
+- **Documentation**: Document your IdP configuration for future reference
+
+<Check>
+ With properly configured OIDC SSO, your users can seamlessly authenticate
+ using their organization's identity provider, improving security and user
+ experience.
+</Check>
diff --git a/docs/docs.json b/docs/docs.json
index b630725fe..6b96b85ad 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -37,7 +37,8 @@
"configuration/aws-s3",
"configuration/email-setup",
"configuration/custom-domain",
- "configuration/subdomain-redirect"
+ "configuration/subdomain-redirect",
+ "configuration/oidc-sso"
]
}
]