1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-12-02 13:24:20 +01:00

(feat) saml provider

This commit is contained in:
Du Peng 2024-01-26 21:24:33 +01:00
parent f58da357b7
commit bc023011d2
20 changed files with 206 additions and 12 deletions

View File

@ -108,7 +108,7 @@ class API::AuthProvidersController < API::APIController
elsif params['auth_provider']['providable_type'] == SamlProvider.name elsif params['auth_provider']['providable_type'] == SamlProvider.name
params.require(:auth_provider) params.require(:auth_provider)
.permit(:id, :name, :providable_type, .permit(:id, :name, :providable_type,
providable_attributes: [:id, :sp_entity_id, :idp_sso_service_url], providable_attributes: [:id, :sp_entity_id, :idp_sso_service_url, :profile_url, :idp_cert_fingerprint, :idp_cert],
auth_provider_mappings_attributes: [:id, :local_model, :local_field, :api_field, :api_endpoint, :api_data_type, auth_provider_mappings_attributes: [:id, :local_model, :local_field, :api_field, :api_endpoint, :api_data_type,
:_destroy, { transformation: [:type, :format, :true_value, :false_value, :_destroy, { transformation: [:type, :format, :true_value, :false_value,
{ mapping: %i[from to] }] }]) { mapping: %i[from to] }] }])

View File

@ -2,6 +2,7 @@
# Handle authentication actions via OmniAuth (used by SSO providers) # Handle authentication actions via OmniAuth (used by SSO providers)
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
skip_before_action :verify_authenticity_token
require 'sso_logger' require 'sso_logger'
logger = SsoLogger.new logger = SsoLogger.new

View File

@ -12,6 +12,7 @@ import { TypeMappingModal } from './type-mapping-modal';
import { useImmer } from 'use-immer'; import { useImmer } from 'use-immer';
import { Oauth2DataMappingForm } from './oauth2-data-mapping-form'; import { Oauth2DataMappingForm } from './oauth2-data-mapping-form';
import { OpenidConnectDataMappingForm } from './openid-connect-data-mapping-form'; import { OpenidConnectDataMappingForm } from './openid-connect-data-mapping-form';
import { SamlDataMappingForm } from './saml-data-mapping-form';
export interface DataMappingFormProps<TFieldValues, TContext extends object> { export interface DataMappingFormProps<TFieldValues, TContext extends object> {
register: UseFormRegister<TFieldValues>, register: UseFormRegister<TFieldValues>,
@ -164,6 +165,11 @@ export const DataMappingForm = <TFieldValues extends FieldValues, TContext exten
setValue={setValue} setValue={setValue}
formState={formState} formState={formState}
currentFormValues={currentFormValues} />} currentFormValues={currentFormValues} />}
{providerType === 'SamlProvider' && <SamlDataMappingForm register={register}
index={index}
setValue={setValue}
formState={formState}
currentFormValues={currentFormValues} />}
</div> </div>
</div> </div>
<div className="actions"> <div className="actions">

View File

@ -0,0 +1,87 @@
import { Path, UseFormRegister } from 'react-hook-form';
import { FieldValues } from 'react-hook-form/dist/types/fields';
import { FormInput } from '../form/form-input';
import { HtmlTranslate } from '../base/html-translate';
import { useTranslation } from 'react-i18next';
import { UnpackNestedValue, UseFormSetValue, FormState } from 'react-hook-form/dist/types/form';
import { FabButton } from '../base/fab-button';
import { FieldPathValue } from 'react-hook-form/dist/types/path';
import { AuthenticationProviderMapping } from '../../models/authentication-provider';
interface SamlDataMappingFormProps<TFieldValues> {
register: UseFormRegister<TFieldValues>,
setValue: UseFormSetValue<TFieldValues>,
currentFormValues: Array<AuthenticationProviderMapping>,
index: number,
formState: FormState<TFieldValues>
}
/**
* Partial form to set the data mapping for an SAML provider.
* The data mapping is the way to bind data from the SAML to the Fab-manager's database
*/
export const SamlDataMappingForm = <TFieldValues extends FieldValues>({ register, setValue, currentFormValues, index, formState }: SamlDataMappingFormProps<TFieldValues>) => {
const { t } = useTranslation('admin');
const standardConfiguration = {
'user.uid': { api_field: 'email' },
'user.email': { api_field: 'email' },
'user.username': { api_field: 'login' },
'profile.first_name': { api_field: 'firstName' },
'profile.last_name': { api_field: 'lastName' },
'profile.phone': { api_field: 'primaryPhone' },
'profile.address': { api_field: 'postalAddress' }
};
/**
* Set the data mapping according to the standard OpenID Connect specification
*/
const openIdStandardConfiguration = (): void => {
const model = currentFormValues[index]?.local_model;
const field = currentFormValues[index]?.local_field;
const configuration = standardConfiguration[`${model}.${field}`];
if (configuration) {
setValue(
`auth_provider_mappings_attributes.${index}.api_field` as Path<TFieldValues>,
configuration.api_field as UnpackNestedValue<FieldPathValue<TFieldValues, Path<TFieldValues>>>
);
if (configuration.transformation) {
Object.keys(configuration.transformation).forEach((key) => {
setValue(
`auth_provider_mappings_attributes.${index}.transformation.${key}` as Path<TFieldValues>,
configuration.transformation[key] as UnpackNestedValue<FieldPathValue<TFieldValues, Path<TFieldValues>>>
);
});
}
}
};
return (
<div className="saml-data-mapping-form">
<FormInput id={`auth_provider_mappings_attributes.${index}.api_endpoint`}
type="hidden"
register={register}
rules={{ required: true }}
formState={formState}
defaultValue="user_info" />
<FormInput id={`auth_provider_mappings_attributes.${index}.api_data_type`}
type="hidden"
register={register}
rules={{ required: true }}
formState={formState}
defaultValue="json" />
<FormInput id={`auth_provider_mappings_attributes.${index}.api_field`}
register={register}
rules={{ required: true }}
formState={formState}
placeholder="claim..."
tooltip={<HtmlTranslate trKey="app.admin.authentication.saml_data_mapping_form.api_field_help_html" />}
label={t('app.admin.authentication.saml_data_mapping_form.api_field')} />
<FabButton
icon={<i className="fa fa-magic" />}
className="auto-configure-button"
onClick={openIdStandardConfiguration}
tooltip={t('app.admin.authentication.saml_data_mapping_form.openid_standard_configuration')} />
</div>
);
};

View File

@ -30,14 +30,32 @@ export const SamlForm = <TFieldValues extends FieldValues>({ register, strategyN
<FabOutputCopy text={buildCallbackUrl()} label={t('app.admin.authentication.saml_form.authorization_callback_url')} /> <FabOutputCopy text={buildCallbackUrl()} label={t('app.admin.authentication.saml_form.authorization_callback_url')} />
<FormInput id="providable_attributes.sp_entity_id" <FormInput id="providable_attributes.sp_entity_id"
register={register} register={register}
placeholder="https://sso.example.net..."
label={t('app.admin.authentication.saml_form.sp_entity_id')} label={t('app.admin.authentication.saml_form.sp_entity_id')}
tooltip={t('app.admin.authentication.saml_form.sp_entity_id_help')}
rules={{ required: true }} rules={{ required: true }}
formState={formState} /> formState={formState} />
<FormInput id="providable_attributes.idp_sso_service_url" <FormInput id="providable_attributes.idp_sso_service_url"
register={register} register={register}
placeholder="/saml/auth..." placeholder="https://sso.example.net..."
label={t('app.admin.authentication.saml_form.idp_sso_service_url')} label={t('app.admin.authentication.saml_form.idp_sso_service_url')}
tooltip={t('app.admin.authentication.saml_form.idp_sso_service_url_help')}
rules={{ required: true, pattern: ValidationLib.urlRegex }}
formState={formState} />
<FormInput id="providable_attributes.idp_cert_fingerprint"
register={register}
placeholder="E7:91:B2:E1:..."
label={t('app.admin.authentication.saml_form.idp_cert_fingerprint')}
formState={formState} />
<FormInput id="providable_attributes.idp_cert"
register={register}
placeholder="-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----"
label={t('app.admin.authentication.saml_form.idp_cert')}
formState={formState} />
<FormInput id="providable_attributes.profile_url"
register={register}
placeholder="https://exemple.net/user..."
label={t('app.admin.authentication.saml_form.profile_edition_url')}
tooltip={t('app.admin.authentication.saml_form.profile_edition_url_help')}
rules={{ required: true, pattern: ValidationLib.urlRegex }} rules={{ required: true, pattern: ValidationLib.urlRegex }}
formState={formState} /> formState={formState} />
</div> </div>

View File

@ -19,7 +19,8 @@
const METHODS = { const METHODS = {
DatabaseProvider: 'local_database', DatabaseProvider: 'local_database',
OAuth2Provider: 'o_auth2', OAuth2Provider: 'o_auth2',
OpenIdConnectProvider: 'openid_connect' OpenIdConnectProvider: 'openid_connect',
SamlProvider: 'saml'
}; };
/** /**

View File

@ -69,6 +69,9 @@ export interface SamlProvider {
id?: string, id?: string,
sp_entity_id: string, sp_entity_id: string,
idp_sso_service_url: string idp_sso_service_url: string
idp_cert_fingerprint: string,
idp_cert: string,
profile_url: string,
} }
export interface MappingFields { export interface MappingFields {

View File

@ -22,6 +22,7 @@
@import "modules/authentication-provider/array-mapping-form"; @import "modules/authentication-provider/array-mapping-form";
@import "modules/authentication-provider/data-mapping-form"; @import "modules/authentication-provider/data-mapping-form";
@import "modules/authentication-provider/openid-connect-data-mapping-form"; @import "modules/authentication-provider/openid-connect-data-mapping-form";
@import "modules/authentication-provider/saml-data-mapping-form";
@import "modules/authentication-provider/provider-form"; @import "modules/authentication-provider/provider-form";
@import "modules/authentication-provider/type-mapping-modal"; @import "modules/authentication-provider/type-mapping-modal";
@import "modules/base/edit-destroy-buttons"; @import "modules/base/edit-destroy-buttons";

View File

@ -0,0 +1,7 @@
.saml-data-mapping-form {
.auto-configure-button {
align-self: center;
margin-top: 0.8rem;
margin-left: 20px;
}
}

View File

@ -17,7 +17,7 @@ class AuthProvider < ApplicationRecord
end end
end end
PROVIDABLE_TYPES = %w[DatabaseProvider OAuth2Provider OpenIdConnectProvider].freeze PROVIDABLE_TYPES = %w[DatabaseProvider OAuth2Provider OpenIdConnectProvider SamlProvider].freeze
belongs_to :providable, polymorphic: true, dependent: :destroy belongs_to :providable, polymorphic: true, dependent: :destroy
accepts_nested_attributes_for :providable accepts_nested_attributes_for :providable
@ -27,7 +27,7 @@ class AuthProvider < ApplicationRecord
validates :providable_type, inclusion: { in: PROVIDABLE_TYPES } validates :providable_type, inclusion: { in: PROVIDABLE_TYPES }
validates :name, presence: true, uniqueness: true validates :name, presence: true, uniqueness: true
validates_with UserUidMappedValidator, if: -> { %w[OAuth2Provider OpenIdConnectProvider].include?(providable_type) } validates_with UserUidMappedValidator, if: -> { %w[OAuth2Provider OpenIdConnectProvider SamlProvider].include?(providable_type) }
before_create :set_initial_state before_create :set_initial_state
after_update :write_reload_config after_update :write_reload_config

View File

@ -22,6 +22,6 @@ end
if @provider.providable_type == SamlProvider.name if @provider.providable_type == SamlProvider.name
json.providable_attributes do json.providable_attributes do
json.extract! @provider.providable, :id, :sp_entity_id, :idp_sso_service_url json.extract! @provider.providable, :id, :sp_entity_id, :idp_sso_service_url, :profile_url, :idp_cert_fingerprint, :idp_cert
end end
end end

View File

@ -20,3 +20,9 @@ if provider.providable_type == 'OpenIdConnectProvider'
:extra_authorize_params :extra_authorize_params
end end
end end
if provider.providable_type == 'SamlProvider'
json.providable_attributes do
json.extract! provider.providable, :id, :sp_entity_id, :idp_sso_service_url, :profile_url, :idp_cert_fingerprint, :idp_cert
end
end

View File

@ -91,6 +91,8 @@ Rails.application.configure do
config.web_console.permissions = %w[192.168.0.0/16 192.168.99.0/16 10.0.2.2] config.web_console.permissions = %w[192.168.0.0/16 192.168.99.0/16 10.0.2.2]
config.hosts << ENV.fetch('DEFAULT_HOST', 'localhost') config.hosts << ENV.fetch('DEFAULT_HOST', 'localhost')
config.hosts << "37abab1a904d96b727afdf86f2eb4830.serveo.net"
config.action_controller.forgery_protection_origin_check = false
# https://github.com/flyerhzm/bullet # https://github.com/flyerhzm/bullet
# In development, Bullet will find and report N+1 DB requests # In development, Bullet will find and report N+1 DB requests

View File

@ -248,8 +248,10 @@ Devise.setup do |config|
when 'SamlProvider' when 'SamlProvider'
require_relative '../../lib/omni_auth/saml' require_relative '../../lib/omni_auth/saml'
config.omniauth active_provider.strategy_name.to_sym, config.omniauth active_provider.strategy_name.to_sym,
active_provider.providable.sp_entity_id, sp_entity_id: active_provider.providable.sp_entity_id,
active_provider.providable.idp_sso_service_url, idp_sso_service_url: active_provider.providable.idp_sso_service_url,
idp_cert: active_provider.providable.idp_cert,
idp_cert_fingerprint: active_provider.providable.idp_cert_fingerprint,
strategy_class: OmniAuth::Strategies::SsoSamlProvider strategy_class: OmniAuth::Strategies::SsoSamlProvider
end end
end end

View File

@ -1230,6 +1230,7 @@ en:
local_database: "Local database" local_database: "Local database"
o_auth2: "OAuth 2.0" o_auth2: "OAuth 2.0"
openid_connect: "OpenID Connect" openid_connect: "OpenID Connect"
saml: "SAML"
group_form: group_form:
add_a_group: "Add a group" add_a_group: "Add a group"
group_name: "Group name" group_name: "Group name"
@ -1496,6 +1497,10 @@ en:
api_field: "Userinfo claim" api_field: "Userinfo claim"
api_field_help_html: 'Set the field providing the corresponding data through <a href="https://openid.net/specs/openid-connect-core-1_0.html#Claims" target="_blank">the userinfo endpoint</a>.<br> <a href="https://jsonpath.com/" target="_blank">JsonPath</a> syntax is supported. If many fields are selected, the first one will be used.<br> <b>Example</b>: $.data[*].name' api_field_help_html: 'Set the field providing the corresponding data through <a href="https://openid.net/specs/openid-connect-core-1_0.html#Claims" target="_blank">the userinfo endpoint</a>.<br> <a href="https://jsonpath.com/" target="_blank">JsonPath</a> syntax is supported. If many fields are selected, the first one will be used.<br> <b>Example</b>: $.data[*].name'
openid_standard_configuration: "Use the OpenID standard configuration" openid_standard_configuration: "Use the OpenID standard configuration"
saml_data_mapping_form:
api_field: "Userinfo field"
api_field_help_html: "Set the field providing the corresponding data through the SAML assertion.<br> If many fields are selected, the first one will be used.<br> <b>Example</b>: $.data[*].name"
openid_standard_configuration: "Use the SAML standard configuration"
type_mapping_modal: type_mapping_modal:
data_mapping: "Data mapping" data_mapping: "Data mapping"
TYPE_expected: "{TYPE} expected" TYPE_expected: "{TYPE} expected"
@ -1552,6 +1557,16 @@ en:
client__end_session_endpoint_help: "The url to call to log the user out at the authorization server." client__end_session_endpoint_help: "The url to call to log the user out at the authorization server."
extra_authorize_params: "Extra authorize parameters" extra_authorize_params: "Extra authorize parameters"
extra_authorize_params_help: "A hash of extra fixed parameters that will be merged to the authorization request" extra_authorize_params_help: "A hash of extra fixed parameters that will be merged to the authorization request"
saml_form:
authorization_callback_url: "Authorization callback URL"
sp_entity_id: "Service provider entity ID"
sp_entity_id_help: "The name of your application. Some identity providers might need this to establish the identity of the service provider requesting the login."
idp_sso_service_url: "Identity provider SSO service URL"
idp_sso_service_url_help: "The URL to which the authentication request should be sent. This would be on the identity provider."
idp_cert_fingerprint: "Identity provider certificate fingerprint"
idp_cert: "Identity provider certificate"
profile_edition_url: "Profil edition URL"
profile_edition_url_help: "The URL of the page where the user can edit his profile."
provider_form: provider_form:
name: "Name" name: "Name"
authentication_type: "Authentication type" authentication_type: "Authentication type"
@ -1562,6 +1577,7 @@ en:
local_database: "Local database" local_database: "Local database"
oauth2: "OAuth 2.0" oauth2: "OAuth 2.0"
openid_connect: "OpenID Connect" openid_connect: "OpenID Connect"
saml: "SAML"
#create a new authentication provider (SSO) #create a new authentication provider (SSO)
authentication_new: authentication_new:
add_a_new_authentication_provider: "Add a new authentication provider" add_a_new_authentication_provider: "Add a new authentication provider"

View File

@ -0,0 +1,7 @@
# frozen_string_literal:true
class AddProfileUrlToSamlProviders < ActiveRecord::Migration[7.0]
def change
add_column :saml_providers, :profile_url, :string
s end
end

View File

@ -0,0 +1,6 @@
class AddIdpCertToSamlProvider < ActiveRecord::Migration[7.0]
def change
add_column :saml_providers, :idp_cert, :string
add_column :saml_providers, :idp_cert_fingerprint, :string
end
end

View File

@ -3275,7 +3275,10 @@ CREATE TABLE public.saml_providers (
sp_entity_id character varying, sp_entity_id character varying,
idp_sso_service_url character varying, idp_sso_service_url character varying,
created_at timestamp(6) without time zone NOT NULL, created_at timestamp(6) without time zone NOT NULL,
updated_at timestamp(6) without time zone NOT NULL updated_at timestamp(6) without time zone NOT NULL,
profile_url character varying,
idp_cert character varying,
idp_cert_fingerprint character varying
); );
@ -9319,6 +9322,8 @@ INSERT INTO "schema_migrations" (version) VALUES
('20230907124230'), ('20230907124230'),
('20231103093436'), ('20231103093436'),
('20231108094433'), ('20231108094433'),
('20240116163703'); ('20240116163703'),
('20240126145351'),
('20240126192110');

View File

@ -1,3 +1,3 @@
# frozen_string_literal: true # frozen_string_literal: true
require_relative 'strategies/saml_provider' require_relative 'strategies/sso_saml_provider'

View File

@ -1,8 +1,34 @@
# frozen_string_literal: true # frozen_string_literal: true
require 'omniauth-saml' require 'omniauth-saml'
require_relative '../data_mapping/mapper'
# Authentication strategy provided trough SAML # Authentication strategy provided trough SAML
class OmniAuth::Strategies::SsoSamlProvider < OmniAuth::Strategies::SAML class OmniAuth::Strategies::SsoSamlProvider < OmniAuth::Strategies::SAML
include OmniAuth::DataMapping::Mapper include OmniAuth::DataMapping::Mapper
def self.active_provider
active_provider = Rails.configuration.auth_provider
if active_provider.providable_type != 'SamlProvider'
raise "Trying to instantiate the wrong provider: Expected SamlProvider, received #{active_provider.providable_type}"
end
active_provider
end
# Strategy name.
option :name, active_provider.strategy_name
info do
{
mapping: parsed_info
}
end
def parsed_info
mapped_info(
OmniAuth::Strategies::SsoSamlProvider.active_provider.auth_provider_mappings,
user_info: @attributes.attributes.transform_values {|v| v.is_a?(Array) ? v.first : v }
)
end
end end