Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬
Ruby actioncablechat-widgetconversationcustomer-supportdashboarddesigndockerdocker-imageherokuintercomjavascriptlivechatopensourcerailsrubysassvuejswhatsappzendesk
feat: support an IdP metadata URL for SAML (#16240)
Shivam Mishra642205c5c84f
diff --git a/app/javascript/dashboard/api/samlSettings.js b/app/javascript/dashboard/api/samlSettings.jsindex 7c0f5b266bb..b0116999342 100644--- a/app/javascript/dashboard/api/samlSettings.js+++ b/app/javascript/dashboard/api/samlSettings.js@@ -21,6 +21,10 @@ class SamlSettingsAPI extends ApiClient {delete() {return axios.delete(this.url);}++ refresh() {+ return axios.post(`${this.url}/refresh`);+ }}export default new SamlSettingsAPI();diff --git a/app/javascript/dashboard/i18n/locale/en/settings.json b/app/javascript/dashboard/i18n/locale/en/settings.jsonindex 114eb9ba976..bea5fcab7fe 100644--- a/app/javascript/dashboard/i18n/locale/en/settings.json+++ b/app/javascript/dashboard/i18n/locale/en/settings.json@@ -695,6 +695,15 @@"LABEL": "ACS URL","TOOLTIP": "Assertion Consumer Service URL - Configure this URL in your IdP as the destination for SAML responses"},+ "SOURCE": {+ "METADATA_URL": "Metadata URL",+ "MANUAL": "Manual"+ },+ "METADATA_URL": {+ "LABEL": "Metadata URL",+ "HELP": "The SSO URL, Entity ID and signing certificate are read from this URL. They update automatically when your certificate is about to expire. If your identity provider changes them earlier, click Refresh metadata.",+ "PLACEHOLDER": "https://sso.example.com/saml/metadata"+ },"SSO_URL": {"LABEL": "SSO URL","HELP": "The URL where SAML authentication requests will be sent",@@ -721,14 +730,18 @@"PLACEHOLDER": "https://sso.example.com/saml"},"UPDATE_BUTTON": "Update SAML Settings",+ "REFRESH_BUTTON": "Refresh metadata","API": {"SUCCESS": "SAML settings updated successfully",+ "REFRESH_SUCCESS": "Metadata refreshed from your identity provider",+ "REFRESH_ERROR": "Failed to refresh metadata","ERROR": "Failed to update SAML settings","ERROR_LOADING": "Failed to load SAML settings","DISABLED": "SAML settings disabled successfully"},"VALIDATION": {"REQUIRED_FIELDS": "SSO URL, Identity Provider Entity ID, and Certificate are required fields",+ "METADATA_URL_ERROR": "Please enter a valid metadata URL","SSO_URL_ERROR": "Please enter a valid SSO URL","CERTIFICATE_ERROR": "Certificate is required","IDP_ENTITY_ID_ERROR": "Identity Provider Entity ID is required"diff --git a/app/javascript/dashboard/routes/dashboard/settings/security/components/SamlSettings.vue b/app/javascript/dashboard/routes/dashboard/settings/security/components/SamlSettings.vueindex f7128d54eba..585d3c58b64 100644--- a/app/javascript/dashboard/routes/dashboard/settings/security/components/SamlSettings.vue+++ b/app/javascript/dashboard/routes/dashboard/settings/security/components/SamlSettings.vue@@ -2,13 +2,14 @@import { ref, computed, onMounted, reactive } from 'vue';import { useI18n } from 'vue-i18n';import { useVuelidate } from '@vuelidate/core';-import { required } from '@vuelidate/validators';+import { requiredIf } from '@vuelidate/validators';import { useAlert } from 'dashboard/composables';import { useAccount } from 'dashboard/composables/useAccount';import samlSettingsAPI from 'dashboard/api/samlSettings';import SettingsToggleSection from 'dashboard/components-next/Settings/SettingsToggleSection.vue';import Spinner from 'dashboard/components-next/spinner/Spinner.vue';+import TabBar from 'dashboard/components-next/tabbar/TabBar.vue';import WithLabel from 'v3/components/Form/WithLabel.vue';import TextInput from 'next/input/Input.vue';import TextArea from 'next/textarea/TextArea.vue';@@ -16,6 +17,9 @@ import NextButton from 'next/button/Button.vue';import SamlInfoSection from './SamlInfoSection.vue';import SamlAttributeMap from './SamlAttributeMap.vue';+const METADATA_URL_TAB = 0;+const MANUAL_TAB = 1;+const { t } = useI18n();const { isCloudFeatureEnabled } = useAccount();@@ -25,23 +29,47 @@ const spEntityId = ref('');const isEnabled = ref(false);const isSubmitting = ref(false);const isLoading = ref(true);+const isRefreshing = ref(false);+const savedMetadataUrl = ref('');+const activeTab = ref(METADATA_URL_TAB);const formState = reactive({+ metadataUrl: '',ssoUrl: '',certificate: '',idpEntityId: '',});+const tabs = computed(() => [+ {+ label: t('SECURITY_SETTINGS.SAML.SOURCE.METADATA_URL'),+ index: METADATA_URL_TAB,+ },+ { label: t('SECURITY_SETTINGS.SAML.SOURCE.MANUAL'), index: MANUAL_TAB },+]);++// The server reads the identity provider fields from the metadata URL when one is set+const usesMetadataUrl = computed(() => activeTab.value === METADATA_URL_TAB);+const requiredWithMetadataUrl = requiredIf(usesMetadataUrl);+const requiredWithoutMetadataUrl = requiredIf(() => !usesMetadataUrl.value);+const validations = {- ssoUrl: { required },- certificate: { required },- idpEntityId: { required },+ metadataUrl: { required: requiredWithMetadataUrl },+ ssoUrl: { required: requiredWithoutMetadataUrl },+ certificate: { required: requiredWithoutMetadataUrl },+ idpEntityId: { required: requiredWithoutMetadataUrl },};const v$ = useVuelidate(validations, formState);const hasFeature = computed(() => isCloudFeatureEnabled('saml'));+const metadataUrlError = computed(() =>+ v$.value.metadataUrl.$error+ ? t('SECURITY_SETTINGS.SAML.VALIDATION.METADATA_URL_ERROR')+ : ''+);+const ssoUrlError = computed(() =>v$.value.ssoUrl.$error? t('SECURITY_SETTINGS.SAML.VALIDATION.SSO_URL_ERROR')@@ -60,6 +88,20 @@ const idpEntityIdError = computed(() =>: '');+const setIdpFields = settings => {+ formState.metadataUrl = settings.metadata_url || '';+ savedMetadataUrl.value = formState.metadataUrl;+ formState.ssoUrl = settings.sso_url || '';+ formState.certificate = settings.certificate || '';+ formState.idpEntityId = settings.idp_entity_id || '';+ activeTab.value = formState.metadataUrl ? METADATA_URL_TAB : MANUAL_TAB;+};++const selectTab = tab => {+ activeTab.value = tab.index;+ v$.value.$reset();+};+const loadSamlSettings = async () => {if (!hasFeature.value) return;@@ -70,10 +112,8 @@ const loadSamlSettings = async () => {if (settings.sso_url) {id.value = settings.id;- formState.ssoUrl = settings.sso_url;- formState.certificate = settings.certificate || '';+ setIdpFields(settings);spEntityId.value = settings.sp_entity_id || '';- formState.idpEntityId = settings.idp_entity_id || '';fingerprint.value = settings.fingerprint || '';isEnabled.value = formState.ssoUrl !== '';}@@ -91,7 +131,7 @@ const saveSamlSettings = async settings => {try {isSubmitting.value = true;- if (isEnabled.value && formState.ssoUrl) {+ if (isEnabled.value && (formState.ssoUrl || formState.metadataUrl)) {// Create or update settings based on existing idlet response;if (id.value) {@@ -103,6 +143,7 @@ const saveSamlSettings = async settings => {// Update local state with response data including fingerprint and idif (response?.data) {id.value = response.data.id;+ setIdpFields(response.data);fingerprint.value = response.data.fingerprint || '';spEntityId.value = response.data.sp_entity_id || '';}@@ -130,26 +171,48 @@ const saveSamlSettings = async settings => {}};+const refreshMetadata = async () => {+ try {+ isRefreshing.value = true;+ const { data } = await samlSettingsAPI.refresh();+ setIdpFields(data);+ fingerprint.value = data.fingerprint || '';+ useAlert(t('SECURITY_SETTINGS.SAML.API.REFRESH_SUCCESS'));+ } catch (error) {+ useAlert(+ error.response?.data?.errors?.[0] ||+ t('SECURITY_SETTINGS.SAML.API.REFRESH_ERROR')+ );+ } finally {+ isRefreshing.value = false;+ }+};+const handleSubmit = async () => {v$.value.$touch();if (v$.value.$invalid) return;- const settings = {- sso_url: formState.ssoUrl,- certificate: formState.certificate,- idp_entity_id: formState.idpEntityId,- role_mappings: {},- };+ const settings = usesMetadataUrl.value+ ? { metadata_url: formState.metadataUrl, role_mappings: {} }+ : {+ metadata_url: '',+ sso_url: formState.ssoUrl,+ certificate: formState.certificate,+ idp_entity_id: formState.idpEntityId,+ role_mappings: {},+ };await saveSamlSettings(settings);};const handleDisable = async () => {id.value = null;+ formState.metadataUrl = '';formState.ssoUrl = '';formState.certificate = '';spEntityId.value = '';formState.idpEntityId = '';+ activeTab.value = METADATA_URL_TAB;fingerprint.value = '';// the empty save will delete the SAML settings item@@ -189,52 +252,79 @@ onMounted(() => {<SamlAttributeMap class="mb-5" /><form class="grid gap-5" @submit.prevent="handleSubmit">+ <TabBar+ :tabs="tabs"+ :initial-active-tab="activeTab"+ @tab-changed="selectTab"+ />+<WithLabel- name="ssoUrl"- :label="t('SECURITY_SETTINGS.SAML.SSO_URL.LABEL')"- :help-message="t('SECURITY_SETTINGS.SAML.SSO_URL.HELP')"- :has-error="v$.ssoUrl.$error"- :error-message="ssoUrlError"+ v-if="usesMetadataUrl"+ name="metadataUrl"+ :label="t('SECURITY_SETTINGS.SAML.METADATA_URL.LABEL')"+ :help-message="t('SECURITY_SETTINGS.SAML.METADATA_URL.HELP')"+ :has-error="v$.metadataUrl.$error"+ :error-message="metadataUrlError"required><TextInput- v-model="formState.ssoUrl"+ v-model.trim="formState.metadataUrl"class="w-full"type="url"- :placeholder="t('SECURITY_SETTINGS.SAML.SSO_URL.PLACEHOLDER')"+ :placeholder="t('SECURITY_SETTINGS.SAML.METADATA_URL.PLACEHOLDER')"/></WithLabel>- <WithLabel- name="idpEntityId"- :label="t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.LABEL')"- :help-message="t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.HELP')"- :has-error="v$.idpEntityId.$error"- :error-message="idpEntityIdError"- required- >- <TextInput- v-model="formState.idpEntityId"- class="w-full"- :placeholder="t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.PLACEHOLDER')"- />- </WithLabel>+ <template v-else>+ <WithLabel+ name="ssoUrl"+ :label="t('SECURITY_SETTINGS.SAML.SSO_URL.LABEL')"+ :help-message="t('SECURITY_SETTINGS.SAML.SSO_URL.HELP')"+ :has-error="v$.ssoUrl.$error"+ :error-message="ssoUrlError"+ required+ >+ <TextInput+ v-model="formState.ssoUrl"+ class="w-full"+ type="url"+ :placeholder="t('SECURITY_SETTINGS.SAML.SSO_URL.PLACEHOLDER')"+ />+ </WithLabel>- <WithLabel- name="certificate"- :label="t('SECURITY_SETTINGS.SAML.CERTIFICATE.LABEL')"- :help-message="t('SECURITY_SETTINGS.SAML.CERTIFICATE.HELP')"- :has-error="v$.certificate.$error"- :error-message="certificateError"- required- >- <TextArea- v-model="formState.certificate"- class="w-full"- rows="8"- :placeholder="t('SECURITY_SETTINGS.SAML.CERTIFICATE.PLACEHOLDER')"- />- </WithLabel>+ <WithLabel+ name="idpEntityId"+ :label="t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.LABEL')"+ :help-message="t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.HELP')"+ :has-error="v$.idpEntityId.$error"+ :error-message="idpEntityIdError"+ required+ >+ <TextInput+ v-model="formState.idpEntityId"+ class="w-full"+ :placeholder="+ t('SECURITY_SETTINGS.SAML.IDP_ENTITY_ID.PLACEHOLDER')+ "+ />+ </WithLabel>++ <WithLabel+ name="certificate"+ :label="t('SECURITY_SETTINGS.SAML.CERTIFICATE.LABEL')"+ :help-message="t('SECURITY_SETTINGS.SAML.CERTIFICATE.HELP')"+ :has-error="v$.certificate.$error"+ :error-message="certificateError"+ required+ >+ <TextArea+ v-model="formState.certificate"+ class="w-full"+ rows="8"+ :placeholder="t('SECURITY_SETTINGS.SAML.CERTIFICATE.PLACEHOLDER')"+ />+ </WithLabel>+ </template><div class="flex gap-2"><NextButton@@ -243,6 +333,15 @@ onMounted(() => {:is-loading="isSubmitting":label="t('SECURITY_SETTINGS.SAML.UPDATE_BUTTON')"/>+ <NextButton+ v-if="usesMetadataUrl && savedMetadataUrl"+ slate+ faded+ type="button"+ :is-loading="isRefreshing"+ :label="t('SECURITY_SETTINGS.SAML.REFRESH_BUTTON')"+ @click="refreshMetadata"+ /></div></form></template>diff --git a/config/locales/en.yml b/config/locales/en.ymlindex 68d7cb184db..2236fd8d86b 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -83,6 +83,15 @@ en:cannot_revoke_current: You cannot revoke the current session.errors:+ account_saml_settings:+ invalid_certificate: must be a valid X.509 certificate in PEM format+ metadata_url:+ invalid_url: must be a valid HTTPS URL+ blocked_address: points to an address that cannot be reached. Use a public host name for your identity provider+ http_error: returned an error. Check that it is the metadata URL from your identity provider+ unreachable: could not be reached. Check that your identity provider is online and has a valid TLS certificate+ too_large: returned a response too large to be SAML metadata+ not_metadata: did not return SAML identity provider metadatanotification_subscription:voip_attributes_required: A VoIP push subscription needs a device_id and a push_tokenaccount:@@ -267,8 +276,6 @@ en:mfa:enabled: MFA enabled successfullydisabled: MFA disabled successfully- account_saml_settings:- invalid_certificate: must be a valid X.509 certificate in PEM formatreports:period: Reporting period %{since} to %{until}utc_warning: The report generated is in UTC timezonediff --git a/config/routes.rb b/config/routes.rbindex e678b880827..4ea579a599b 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -135,7 +135,9 @@ Rails.application.routes.draw dopost :follow_upendend- resource :saml_settings, only: [:show, :create, :update, :destroy]+ resource :saml_settings, only: [:show, :create, :update, :destroy] do+ post :refresh+ endresources :agent_bots, only: [:index, :create, :show, :update, :destroy] dodelete :avatar, on: :memberpost :reset_access_token, on: :memberdiff --git a/db/migrate/20261013072916_add_metadata_url_to_account_saml_settings.rb b/db/migrate/20261013072916_add_metadata_url_to_account_saml_settings.rbnew file mode 100644index 00000000000..082c0c565e4--- /dev/null+++ b/db/migrate/20261013072916_add_metadata_url_to_account_saml_settings.rb@@ -0,0 +1,6 @@+class AddMetadataUrlToAccountSamlSettings < ActiveRecord::Migration[7.2]+ def change+ add_column :account_saml_settings, :metadata_url, :string+ add_column :account_saml_settings, :metadata_refreshed_at, :datetime+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 0536acb1861..b17aff61210 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -37,6 +37,8 @@ ActiveRecord::Schema[7.1].define(version: 2026_10_19_143116) dot.json "role_mappings", default: {}t.datetime "created_at", null: falset.datetime "updated_at", null: false+ t.string "metadata_url"+ t.datetime "metadata_refreshed_at"t.index ["account_id"], name: "index_account_saml_settings_on_account_id"enddiff --git a/enterprise/app/controllers/api/v1/accounts/saml_settings_controller.rb b/enterprise/app/controllers/api/v1/accounts/saml_settings_controller.rbindex e708040731c..86603e53fec 100644--- a/enterprise/app/controllers/api/v1/accounts/saml_settings_controller.rb+++ b/enterprise/app/controllers/api/v1/accounts/saml_settings_controller.rb@@ -28,6 +28,14 @@ class Api::V1::Accounts::SamlSettingsController < Api::V1::Accounts::BaseControlhead :no_contentend+ def refresh+ if @saml_settings.refresh_metadata+ render :show+ else+ render json: { errors: @saml_settings.errors.full_messages }, status: :unprocessable_entity+ end+ end+privatedef set_saml_settings@@ -41,6 +49,7 @@ class Api::V1::Accounts::SamlSettingsController < Api::V1::Accounts::BaseControl:certificate,:idp_entity_id,:sp_entity_id,+ :metadata_url,role_mappings: {})enddiff --git a/enterprise/app/models/account_saml_settings.rb b/enterprise/app/models/account_saml_settings.rbindex 9e37f1c8219..9b81d6e555f 100644--- a/enterprise/app/models/account_saml_settings.rb+++ b/enterprise/app/models/account_saml_settings.rb@@ -2,21 +2,26 @@## Table name: account_saml_settings#-# id :bigint not null, primary key-# certificate :text-# role_mappings :json-# sso_url :string-# created_at :datetime not null-# updated_at :datetime not null-# account_id :bigint not null-# idp_entity_id :string-# sp_entity_id :string+# id :bigint not null, primary key+# certificate :text+# metadata_refreshed_at :datetime+# metadata_url :string+# role_mappings :json+# sso_url :string+# created_at :datetime not null+# updated_at :datetime not null+# account_id :bigint not null+# idp_entity_id :string+# sp_entity_id :string## Indexes## index_account_saml_settings_on_account_id (account_id)#class AccountSamlSettings < ApplicationRecord+ # Some IdPs, such as ZITADEL, switch to a new certificate only minutes before the current one expires+ CERTIFICATE_EXPIRY_WINDOW = 15.minutes+ METADATA_REFRESH_INTERVAL = 5.minutesbelongs_to :accountvalidates :account_id, presence: true@@ -26,6 +31,7 @@ class AccountSamlSettings < ApplicationRecordvalidate :certificate_must_be_valid_x509before_validation :set_sp_entity_id, if: :sp_entity_id_needs_generation?+ before_validation :assign_idp_metadata, if: -> { metadata_url.present? && metadata_url_changed? }after_create_commit :update_account_users_providerafter_destroy_commit :reset_account_users_provider@@ -34,20 +40,76 @@ class AccountSamlSettings < ApplicationRecordsso_url.present? && certificate.present?end+ # Admins compare this with the IdP to confirm a refresh picked up a rotated certificate.+ # When the IdP lists several certificates, it shows the newest one, the same certificate certificate_expiring? uses.def certificate_fingerprintreturn nil if certificate.blank?begin- cert = OpenSSL::X509::Certificate.new(certificate)- OpenSSL::Digest::SHA1.new(cert.to_der).hexdigest+ OpenSSL::Digest::SHA1.new(newest_certificate.to_der).hexdigest.upcase.gsub(/(.{2})(?=.)/, '\1:')rescue OpenSSL::X509::CertificateErrornilendend+ # Metadata can list more than one signing certificate while the IdP rotates its key.+ def signing_certificates+ parsed_certificates.map(&:to_pem)+ end++ def signing_certificates=(certificates)+ self.certificate = certificates.join("\n")+ end++ def refresh_metadata_if_needed+ return if metadata_url.blank? || !certificate_expiring? || metadata_refreshed_at&.after?(METADATA_REFRESH_INTERVAL.ago)++ # Claim the refresh before fetching, so concurrent logins use the stored values instead of all waiting on the IdP+ claimed = self.class.where(id: id)+ .where('metadata_refreshed_at IS NULL OR metadata_refreshed_at < ?', METADATA_REFRESH_INTERVAL.ago)+ .update_all(metadata_refreshed_at: Time.current) # rubocop:disable Rails/SkipsModelValidations+ return if claimed.zero? || refresh_metadata++ Rails.logger.warn "SAML metadata refresh failed for account #{account_id}: #{errors.full_messages.to_sentence}"+ # The login that called this uses these values, so drop the rejected ones and keep the stored ones+ restore_attributes+ end++ # Reads the metadata again right away, for the refresh button in the settings form+ def refresh_metadata+ if metadata_url.blank?+ errors.add(:metadata_url, :blank)+ return false+ end++ assign_idp_metadata+ errors.empty? && save+ end+private+ def certificate_expiring?+ newest_certificate.not_after < CERTIFICATE_EXPIRY_WINDOW.from_now+ end++ # During a rotation the IdP lists the outgoing and incoming certificates in no fixed order, so the newest is the+ # one picked by expiry date. An expired certificate the IdP still lists then does not keep triggering refreshes.+ def newest_certificate+ parsed_certificates.max_by(&:not_after)+ end++ # Reads every certificate in the stored value, and raises if any block is malformed or none is found+ def parsed_certificates+ OpenSSL::X509::Certificate.load(certificate.to_s)+ end++ def assign_idp_metadata+ assign_attributes(Saml::IdpMetadataService.new(metadata_url).perform.merge(metadata_refreshed_at: Time.current))+ rescue Saml::IdpMetadataService::Error => e+ errors.add(:metadata_url, I18n.t("errors.account_saml_settings.metadata_url.#{e.reason}"))+ end+def set_sp_entity_idbase_url = GlobalConfigService.load('FRONTEND_URL', 'http://localhost:3000')self.sp_entity_id = "#{base_url}/saml/sp/#{account_id}"@@ -72,7 +134,8 @@ class AccountSamlSettings < ApplicationRecorddef certificate_must_be_valid_x509return if certificate.blank?- OpenSSL::X509::Certificate.new(certificate)+ # ruby-saml parses every block when the value holds more than one certificate+ parsed_certificatesrescue OpenSSL::X509::CertificateErrorerrors.add(:certificate, I18n.t('errors.account_saml_settings.invalid_certificate'))enddiff --git a/enterprise/app/policies/account_saml_settings_policy.rb b/enterprise/app/policies/account_saml_settings_policy.rbindex fc141893512..233e1513b8d 100644--- a/enterprise/app/policies/account_saml_settings_policy.rb+++ b/enterprise/app/policies/account_saml_settings_policy.rb@@ -14,4 +14,8 @@ class AccountSamlSettingsPolicy < ApplicationPolicydef destroy?@account_user.administrator?end++ def refresh?+ @account_user.administrator?+ endenddiff --git a/enterprise/app/services/saml/idp_metadata_service.rb b/enterprise/app/services/saml/idp_metadata_service.rbnew file mode 100644index 00000000000..58e384e81f8--- /dev/null+++ b/enterprise/app/services/saml/idp_metadata_service.rb@@ -0,0 +1,61 @@+class Saml::IdpMetadataService+ # The reason picks the message shown to admins, from errors.account_saml_settings.metadata_url.+ # The message keeps the underlying cause, which can include host names and IP addresses, so admins never see it.+ class Error < StandardError+ attr_reader :reason++ def initialize(reason, message = reason.to_s)+ @reason = reason+ super(message)+ end+ end++ MAX_METADATA_BYTES = 1.megabyte+ READ_TIMEOUT = 5+ FETCH_ERROR_REASONS = {+ URI::InvalidURIError => :invalid_url,+ SafeFetch::InvalidUrlError => :invalid_url,+ SafeFetch::UnsafeUrlError => :blocked_address,+ SafeFetch::HttpError => :http_error,+ SafeFetch::FetchError => :unreachable,+ SafeFetch::FileTooLargeError => :too_large+ }.freeze++ def initialize(metadata_url)+ @metadata_url = metadata_url+ end++ def perform+ metadata = parse_metadata(fetch_metadata)+ # AccountSamlSettings validates these values, so missing fields and malformed certificates are rejected there+ certificates = Array(metadata[:idp_cert_multi]&.dig(:signing))++ {+ sso_url: metadata[:idp_sso_service_url],+ idp_entity_id: metadata[:idp_entity_id],+ signing_certificates: certificates.map { |certificate| OneLogin::RubySaml::Utils.format_cert(certificate) }+ }+ end++ private++ def fetch_metadata+ # Chatwoot does not check the metadata signature, so only TLS protects the certificates it returns.+ # This checks only the entered URL. SafeFetch follows redirects, including to HTTP, and has no option to stop that.+ raise Error, :invalid_url unless URI.parse(@metadata_url).is_a?(URI::HTTPS)++ SafeFetch.fetch(@metadata_url, validate_content_type: false, max_bytes: MAX_METADATA_BYTES, read_timeout: READ_TIMEOUT) do |result|+ result.tempfile.read+ end+ rescue *FETCH_ERROR_REASONS.keys => e+ raise Error.new(FETCH_ERROR_REASONS.fetch(e.class), e.message)+ end++ # ruby-saml raises ArgumentError when the document has no IDPSSODescriptor.+ # It raises CertificateError when it fingerprints a lone signing certificate that OpenSSL cannot read.+ def parse_metadata(xml)+ OneLogin::RubySaml::IdpMetadataParser.new.parse_to_hash(xml, sso_binding: [OneLogin::RubySaml::Utils::BINDINGS[:redirect]])+ rescue REXML::ParseException, ArgumentError, OpenSSL::X509::CertificateError => e+ raise Error.new(:not_metadata, e.message)+ end+enddiff --git a/enterprise/app/views/api/v1/models/_account_saml_settings.json.jbuilder b/enterprise/app/views/api/v1/models/_account_saml_settings.json.jbuilderindex b179446056e..d9247d9de96 100644--- a/enterprise/app/views/api/v1/models/_account_saml_settings.json.jbuilder+++ b/enterprise/app/views/api/v1/models/_account_saml_settings.json.jbuilder@@ -5,6 +5,7 @@ json.certificate account_saml_settings.certificatejson.fingerprint account_saml_settings.certificate_fingerprintjson.idp_entity_id account_saml_settings.idp_entity_idjson.sp_entity_id account_saml_settings.sp_entity_id+json.metadata_url account_saml_settings.metadata_urljson.role_mappings account_saml_settings.role_mappings || {}json.created_at account_saml_settings.created_atjson.updated_at account_saml_settings.updated_atdiff --git a/enterprise/config/initializers/omniauth_saml.rb b/enterprise/config/initializers/omniauth_saml.rbindex d43a534a517..083a87c8c5f 100644--- a/enterprise/config/initializers/omniauth_saml.rb+++ b/enterprise/config/initializers/omniauth_saml.rb@@ -21,6 +21,11 @@ SAML_SETUP_PROC = proc do |env|settings = AccountSamlSettings.find_by(account_id: account_id)if settings+ # Refreshes during login so the triggering login uses a rotated certificate. It fetches only within 15 minutes+ # of certificate expiry, at most every 5 minutes, so earlier rotations need the "Refresh metadata" button.+ # Future: move this to a scheduled job (config/schedule.yml) for all accounts with a metadata URL. That covers+ # early rotations, keeps the fetch off logins, and removes the claim on metadata_refreshed_at.+ settings.refresh_metadata_if_needed# Configure the strategy options dynamicallyenv['omniauth.strategy'].options[:idp_sso_service_url_runtime_params] = { RelayState: :RelayState }base_url = GlobalConfigService.load('FRONTEND_URL', 'http://localhost:3000')@@ -29,6 +34,8 @@ SAML_SETUP_PROC = proc do |env|env['omniauth.strategy'].options[:idp_entity_id] = settings.idp_entity_idenv['omniauth.strategy'].options[:idp_sso_service_url] = settings.sso_urlenv['omniauth.strategy'].options[:idp_cert] = settings.certificate+ signing_certificates = settings.signing_certificates+ env['omniauth.strategy'].options[:idp_cert_multi] = { signing: signing_certificates } if signing_certificates.many?env['omniauth.strategy'].options[:name_identifier_format] = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'else# Set a dummy certificate to avoid the errordiff --git a/spec/enterprise/controllers/api/v1/accounts/saml_settings_controller_spec.rb b/spec/enterprise/controllers/api/v1/accounts/saml_settings_controller_spec.rbindex 14bf0ebb0fb..e2c47073e50 100644--- a/spec/enterprise/controllers/api/v1/accounts/saml_settings_controller_spec.rb+++ b/spec/enterprise/controllers/api/v1/accounts/saml_settings_controller_spec.rb@@ -132,6 +132,39 @@ RSpec.describe 'Api::V1::Accounts::SamlSettings', type: :request doendend+ context 'with a metadata URL' do+ let(:metadata_url) { 'https://idp.example.com/saml/v2/metadata' }+ let(:certificate) { build(:account_saml_settings).certificate }+ let(:metadata) { { sso_url: 'https://idp.example.com/saml/v2/SSO', idp_entity_id: metadata_url, signing_certificates: [certificate] } }+ let(:metadata_service) { instance_double(Saml::IdpMetadataService, perform: metadata) }++ before do+ allow(Saml::IdpMetadataService).to receive(:new).with(metadata_url).and_return(metadata_service)+ end++ it 'creates SAML settings from the metadata' do+ post "/api/v1/accounts/#{account.id}/saml_settings",+ params: { saml_settings: { metadata_url: metadata_url } },+ headers: administrator.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:success)+ expect(json_response).to include(metadata_url: metadata_url, sso_url: metadata[:sso_url], certificate: certificate)+ end++ it 'returns unprocessable entity when the metadata cannot be read' do+ allow(metadata_service).to receive(:perform).and_raise(Saml::IdpMetadataService::Error.new(:unreachable))++ post "/api/v1/accounts/#{account.id}/saml_settings",+ params: { saml_settings: { metadata_url: metadata_url } },+ headers: administrator.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:unprocessable_entity)+ expect(json_response[:errors].first).to start_with('Metadata url could not be reached')+ end+ end+context 'with invalid parameters' dolet(:invalid_params) dovalid_params.tap do |params|@@ -262,4 +295,64 @@ RSpec.describe 'Api::V1::Accounts::SamlSettings', type: :request doendendend++ describe 'POST /api/v1/accounts/{account.id}/saml_settings/refresh' do+ let(:metadata_url) { 'https://idp.example.com/saml/v2/metadata' }+ let(:certificate) { build(:account_saml_settings).certificate.strip }+ let(:rotated_certificate) { build(:account_saml_settings).certificate.strip }+ let(:metadata) { { sso_url: 'https://idp.example.com/saml/v2/SSO', idp_entity_id: metadata_url, signing_certificates: [certificate] } }+ let(:metadata_service) { instance_double(Saml::IdpMetadataService, perform: metadata) }++ before do+ allow(Saml::IdpMetadataService).to receive(:new).with(metadata_url).and_return(metadata_service)+ AccountSamlSettings.create!(account: account, metadata_url: metadata_url)+ end++ context 'when authenticated as administrator' do+ it 'stores the certificate from the metadata' do+ allow(metadata_service).to receive(:perform).and_return(metadata.merge(signing_certificates: [rotated_certificate]))++ post "/api/v1/accounts/#{account.id}/saml_settings/refresh",+ headers: administrator.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:success)+ expect(json_response[:certificate]).to eq(rotated_certificate)+ expect(account.saml_settings.reload.certificate).to eq(rotated_certificate)+ end++ it 'keeps the stored values when the metadata cannot be read' do+ allow(metadata_service).to receive(:perform).and_raise(Saml::IdpMetadataService::Error.new(:unreachable))++ post "/api/v1/accounts/#{account.id}/saml_settings/refresh",+ headers: administrator.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:unprocessable_entity)+ expect(json_response[:errors].first).to start_with('Metadata url could not be reached')+ expect(account.saml_settings.reload.certificate).to eq(certificate)+ end++ it 'returns unprocessable entity without a metadata URL' do+ account.saml_settings.update!(metadata_url: nil)++ post "/api/v1/accounts/#{account.id}/saml_settings/refresh",+ headers: administrator.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:unprocessable_entity)+ expect(json_response[:errors]).to eq(["Metadata url can't be blank"])+ end+ end++ context 'when authenticated as agent' do+ it 'returns unauthorized' do+ post "/api/v1/accounts/#{account.id}/saml_settings/refresh",+ headers: agent.create_new_auth_token,+ as: :json++ expect(response).to have_http_status(:unauthorized)+ end+ end+ endenddiff --git a/spec/enterprise/controllers/enterprise/devise_overrides/omniauth_callbacks_controller_spec.rb b/spec/enterprise/controllers/enterprise/devise_overrides/omniauth_callbacks_controller_spec.rbindex df0ef2eadd0..56612406226 100644--- a/spec/enterprise/controllers/enterprise/devise_overrides/omniauth_callbacks_controller_spec.rb+++ b/spec/enterprise/controllers/enterprise/devise_overrides/omniauth_callbacks_controller_spec.rb@@ -40,6 +40,26 @@ RSpec.describe 'Enterprise SAML OmniAuth Callbacks', type: :request doendend+ it 'reads the rotated certificate from the IdP metadata URL' do+ with_modified_env FRONTEND_URL: 'http://www.example.com' do+ metadata_url = 'https://idp.example.com/saml/v2/metadata'+ rotated_certificate = build(:account_saml_settings).certificate+ metadata = { sso_url: saml_settings.sso_url, idp_entity_id: saml_settings.idp_entity_id, signing_certificates: [saml_settings.certificate] }+ metadata_service = instance_double(Saml::IdpMetadataService, perform: metadata)+ allow(Saml::IdpMetadataService).to receive(:new).with(metadata_url).and_return(metadata_service)+ saml_settings.update!(metadata_url: metadata_url)+ allow(metadata_service).to receive(:perform).and_return(metadata.merge(signing_certificates: [rotated_certificate]))+ set_saml_config('[email protected]')++ travel_to(OpenSSL::X509::Certificate.new(saml_settings.certificate).not_after - 10.minutes) do+ get "/omniauth/saml/callback?account_id=#{account.id}"+ end++ expect(response).to redirect_to(%r{/app/login\?email=.+&sso_auth_token=.+$})+ expect(saml_settings.reload.certificate).to eq(rotated_certificate)+ end+ end+it 'logs in existing user' dowith_modified_env FRONTEND_URL: 'http://www.example.com' docreate(:user, email: '[email protected]', account: account)diff --git a/spec/enterprise/initializers/omniauth_saml_spec.rb b/spec/enterprise/initializers/omniauth_saml_spec.rbnew file mode 100644index 00000000000..9cb16b4a6d9--- /dev/null+++ b/spec/enterprise/initializers/omniauth_saml_spec.rb@@ -0,0 +1,39 @@+require 'rails_helper'++# rubocop:disable RSpec/DescribeClass+RSpec.describe 'SAML OmniAuth setup' do+ let(:strategy) { OmniAuth::Strategies::SAML.new(->(_env) { [404, {}, []] }, setup: SAML_SETUP_PROC) }+ let(:rotating_account) { create(:account) }+ let(:single_certificate_account) { create(:account) }++ def run_callback(account)+ env = Rack::MockRequest.env_for("/omniauth/saml/callback?account_id=#{account.id}", method: 'POST')+ env['rack.session'] = {}+ strategy.call(env)+ env['omniauth.strategy']+ end++ before do+ allow(OmniAuth.config).to receive_messages(test_mode: false, on_failure: ->(_env) { [401, {}, []] })+ certificates = Array.new(2) { build(:account_saml_settings).certificate }+ create(:account_saml_settings, account: rotating_account, certificate: certificates.join)+ create(:account_saml_settings, account: single_certificate_account)+ end++ it 'runs each request on its own copy of the strategy options' do+ request_strategy = run_callback(rotating_account)++ expect(request_strategy).not_to equal(strategy)+ expect(request_strategy.options).not_to equal(strategy.options)+ expect(strategy.options[:idp_cert_multi]).to be_nil+ end++ it 'does not carry one account certificates into the next request' do+ rotating_request = run_callback(rotating_account)+ single_certificate_request = run_callback(single_certificate_account)++ expect(rotating_request.options[:idp_cert_multi][:signing].size).to eq(2)+ expect(single_certificate_request.options[:idp_cert_multi]).to be_nil+ end+end+# rubocop:enable RSpec/DescribeClassdiff --git a/spec/enterprise/models/account_saml_settings_spec.rb b/spec/enterprise/models/account_saml_settings_spec.rbindex ac35eb486a6..1386af41a1d 100644--- a/spec/enterprise/models/account_saml_settings_spec.rb+++ b/spec/enterprise/models/account_saml_settings_spec.rb@@ -23,6 +23,15 @@ RSpec.describe AccountSamlSettings, type: :model doexpect(settings.errors[:certificate]).to include("can't be blank")end+ it 'rejects a malformed certificate after a valid one' do+ valid_certificate = build(:account_saml_settings).certificate+ malformed_certificate = "-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----"+ settings = build(:account_saml_settings, account: account, certificate: "#{valid_certificate}#{malformed_certificate}")++ expect(settings).not_to be_valid+ expect(settings.errors[:certificate]).to include('must be a valid X.509 certificate in PEM format')+ end+it 'requires idp_entity_id' dosettings = build(:account_saml_settings, account: account, idp_entity_id: nil)expect(settings).not_to be_valid@@ -113,6 +122,168 @@ RSpec.describe AccountSamlSettings, type: :model doexpect(fingerprint).to match(/^[A-F0-9:]+$/)expect(fingerprint.count(':')).to eq(19) # 20 bytes = 19 colonsend++ it 'returns the fingerprint of the certificate that expires last when several are stored' do+ key = OpenSSL::PKey::RSA.new(2048)+ rotated = OpenSSL::X509::Certificate.new+ rotated.version = 2+ rotated.serial = 2+ rotated.subject = OpenSSL::X509::Name.parse('/CN=rotated.example.com')+ rotated.issuer = rotated.subject+ rotated.public_key = key.public_key+ rotated.not_before = Time.zone.now+ rotated.not_after = 2.years.from_now+ rotated.sign(key, OpenSSL::Digest.new('SHA256'))+ settings = build(:account_saml_settings, account: account)+ settings.signing_certificates = [valid_cert_pem.strip, rotated.to_pem.strip]++ expect(settings.certificate_fingerprint).to eq(OpenSSL::Digest::SHA1.hexdigest(rotated.to_der).upcase.scan(/../).join(':'))+ end+ end++ describe 'IdP metadata' do+ let(:metadata_url) { 'https://idp.example.com/saml/v2/metadata' }+ let(:certificate) { build(:account_saml_settings).certificate }+ let(:rotated_certificate) { build(:account_saml_settings).certificate }+ let(:metadata) { { sso_url: 'https://idp.example.com/saml/v2/SSO', idp_entity_id: metadata_url, signing_certificates: [certificate] } }+ let(:metadata_service) { instance_double(Saml::IdpMetadataService, perform: metadata) }++ before do+ allow(Saml::IdpMetadataService).to receive(:new).with(metadata_url).and_return(metadata_service)+ end++ describe 'saving with a metadata URL' do+ it 'fills the IdP fields from the metadata' do+ settings = described_class.create!(account: account, metadata_url: metadata_url)++ expect(settings).to have_attributes(metadata)+ expect(settings.metadata_refreshed_at).to be_within(1.second).of(Time.current)+ end++ it 'adds an error when the metadata cannot be read' do+ allow(metadata_service).to receive(:perform).and_raise(Saml::IdpMetadataService::Error.new(:unreachable))+ settings = described_class.new(account: account, metadata_url: metadata_url)++ expect(settings).not_to be_valid+ expect(settings.errors[:metadata_url]).to include(I18n.t('errors.account_saml_settings.metadata_url.unreachable'))+ end++ it 'adds a certificate error when the metadata has a malformed certificate' do+ malformed_certificate = "-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----"+ allow(metadata_service).to receive(:perform).and_return(metadata.merge(signing_certificates: [certificate, malformed_certificate]))+ settings = described_class.new(account: account, metadata_url: metadata_url)++ expect(settings).not_to be_valid+ expect(settings.errors[:certificate]).to include('must be a valid X.509 certificate in PEM format')+ end++ it 'does not fetch the metadata when the URL is unchanged' do+ settings = described_class.create!(account: account, metadata_url: metadata_url)+ settings.update!(role_mappings: { 'Admins' => { 'role' => 1 } })++ expect(metadata_service).to have_received(:perform).once+ end+ end++ describe '#refresh_metadata_if_needed' do+ let(:settings) { described_class.create!(account: account, metadata_url: metadata_url) }+ let(:near_expiry) { OpenSSL::X509::Certificate.new(certificate).not_after - 10.minutes }++ before { settings }++ it 'does not fetch while a newer certificate is stored next to an expired one' do+ key = OpenSSL::PKey::RSA.new(2048)+ expired = OpenSSL::X509::Certificate.new+ expired.version = 2+ expired.serial = 1+ expired.subject = OpenSSL::X509::Name.parse('/CN=idp.example.com')+ expired.issuer = expired.subject+ expired.public_key = key.public_key+ expired.not_before = 2.years.ago+ expired.not_after = 1.year.ago+ expired.sign(key, OpenSSL::Digest.new('SHA256'))+ settings.update!(signing_certificates: [expired.to_pem.strip, certificate])++ travel_to(1.day.from_now) do+ settings.refresh_metadata_if_needed++ expect(metadata_service).to have_received(:perform).once+ end+ end++ it 'does not fetch while the certificate is far from expiry' do+ travel_to(near_expiry - 1.day) do+ settings.refresh_metadata_if_needed++ expect(metadata_service).to have_received(:perform).once+ end+ end++ it 'stores the rotated certificate when the certificate is close to expiry' do+ allow(metadata_service).to receive(:perform).and_return(metadata.merge(signing_certificates: [rotated_certificate]))++ travel_to(near_expiry) do+ settings.refresh_metadata_if_needed++ expect(settings.reload.certificate).to eq(rotated_certificate)+ expect(settings.metadata_refreshed_at).to be_within(1.second).of(Time.current)+ end+ end++ it 'does not fetch again within the refresh interval' do+ travel_to(near_expiry) do+ settings.refresh_metadata_if_needed+ settings.refresh_metadata_if_needed++ expect(metadata_service).to have_received(:perform).twice+ end+ end++ it 'does not fetch when another request already claimed the refresh' do+ travel_to(near_expiry) do+ described_class.where(id: settings.id).update_all(metadata_refreshed_at: Time.current) # rubocop:disable Rails/SkipsModelValidations+ settings.refresh_metadata_if_needed++ expect(metadata_service).to have_received(:perform).once+ end+ end++ it 'keeps the stored values when the fetch fails' do+ allow(metadata_service).to receive(:perform).and_raise(Saml::IdpMetadataService::Error.new(:unreachable))++ travel_to(near_expiry) do+ settings.refresh_metadata_if_needed++ expect(settings.reload.certificate).to eq(certificate)+ expect(settings.metadata_refreshed_at).to be_within(1.second).of(Time.current)+ end+ end++ it 'keeps the stored values when the fetched metadata is invalid' do+ allow(metadata_service).to receive(:perform).and_return(metadata.merge(sso_url: nil))++ travel_to(near_expiry) do+ settings.refresh_metadata_if_needed++ expect(settings.sso_url).to eq(metadata[:sso_url])+ expect(settings.reload.sso_url).to eq(metadata[:sso_url])+ end+ end++ it 'does nothing without a metadata URL' do+ manual_settings = create(:account_saml_settings, account: create(:account))++ expect { manual_settings.refresh_metadata_if_needed }.not_to(change { manual_settings.reload.updated_at })+ end+ end++ describe '#signing_certificates' do+ it 'returns every certificate in the stored value' do+ settings = build(:account_saml_settings, account: account, certificate: "#{certificate}\n#{rotated_certificate}")++ expect(settings.signing_certificates).to eq([certificate, rotated_certificate])+ end+ endenddescribe 'callbacks' dodiff --git a/spec/enterprise/services/saml/idp_metadata_service_spec.rb b/spec/enterprise/services/saml/idp_metadata_service_spec.rbnew file mode 100644index 00000000000..b768ac03260--- /dev/null+++ b/spec/enterprise/services/saml/idp_metadata_service_spec.rb@@ -0,0 +1,119 @@+# frozen_string_literal: true++require 'rails_helper'++RSpec.describe Saml::IdpMetadataService do+ let(:metadata_url) { 'https://idp.example.com/saml/v2/metadata' }+ let(:certificate) { build(:account_saml_settings).certificate }+ let(:rotated_certificate) { build(:account_saml_settings).certificate }+ let(:key_descriptors) { key_descriptor(certificate) }+ let(:sso_binding) { 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect' }+ let(:metadata_xml) do+ <<~XML+ <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" entityID="https://idp.example.com/saml/v2/metadata">+ <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">+ #{key_descriptors}+ <md:SingleSignOnService Binding="#{sso_binding}" Location="https://idp.example.com/saml/v2/SSO"/>+ </md:IDPSSODescriptor>+ </md:EntityDescriptor>+ XML+ end++ def key_descriptor(pem)+ body = pem.gsub(/-----(BEGIN|END) CERTIFICATE-----|\s/, '')+ <<~XML+ <md:KeyDescriptor use="signing">+ <ds:KeyInfo><ds:X509Data><ds:X509Certificate>#{body}</ds:X509Certificate></ds:X509Data></ds:KeyInfo>+ </md:KeyDescriptor>+ XML+ end++ before do+ allow(Resolv).to receive(:getaddresses).and_call_original+ allow(Resolv).to receive(:getaddresses).with('idp.example.com').and_return(['93.184.216.34'])+ stub_request(:get, metadata_url).to_return(status: 200, body: metadata_xml, headers: { 'Content-Type' => 'application/xml' })+ end++ describe '#perform' do+ it 'returns the SSO URL, entity ID and signing certificate' do+ expect(described_class.new(metadata_url).perform).to eq(+ sso_url: 'https://idp.example.com/saml/v2/SSO',+ idp_entity_id: 'https://idp.example.com/saml/v2/metadata',+ signing_certificates: [certificate.strip]+ )+ end++ context 'when the metadata lists two signing certificates' do+ let(:key_descriptors) { key_descriptor(certificate) + key_descriptor(rotated_certificate) }++ it 'returns both certificates' do+ expect(described_class.new(metadata_url).perform[:signing_certificates]).to eq([certificate.strip, rotated_certificate.strip])+ end+ end++ context 'when the metadata has no signing certificate' do+ let(:key_descriptors) { '' }++ it 'returns no certificates for the model to reject' do+ expect(described_class.new(metadata_url).perform[:signing_certificates]).to eq([])+ end+ end++ context 'when the metadata has no redirect SSO URL' do+ let(:sso_binding) { 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' }++ it 'returns no SSO URL for the model to reject' do+ expect(described_class.new(metadata_url).perform[:sso_url]).to be_nil+ end+ end++ context 'when the only signing certificate cannot be read' do+ let(:key_descriptors) { key_descriptor("-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----\n") }++ it 'raises an error' do+ expect { described_class.new(metadata_url).perform }.to raise_error(described_class::Error) { |error|+ expect(error.reason).to eq(:not_metadata)+ }+ end+ end++ context 'when the response is not IdP metadata' do+ let(:metadata_xml) { '<html><body>Not found</body></html>' }++ it 'raises an error' do+ expect { described_class.new(metadata_url).perform }.to raise_error(described_class::Error) { |error|+ expect(error.reason).to eq(:not_metadata)+ }+ end+ end++ context 'when the URL uses HTTP' do+ let(:http_url) { 'http://idp.example.com/saml/v2/metadata' }++ it 'raises an error without fetching the URL' do+ expect { described_class.new(http_url).perform }.to raise_error(described_class::Error) { |error| expect(error.reason).to eq(:invalid_url) }+ expect(a_request(:get, http_url)).not_to have_been_made+ end+ end++ context 'when the fetch fails' do+ before { stub_request(:get, metadata_url).to_return(status: 500) }++ it 'raises an error' do+ expect { described_class.new(metadata_url).perform }.to raise_error(described_class::Error) { |error|+ expect(error.reason).to eq(:http_error)+ }+ end+ end++ context 'when the URL points to a private address' do+ before { allow(Resolv).to receive(:getaddresses).with('idp.example.com').and_return(['10.0.0.5']) }++ it 'raises an error' do+ expect { described_class.new(metadata_url).perform }.to raise_error(described_class::Error) { |error|+ expect(error.reason).to eq(:blocked_address)+ }+ end+ end+ end+end