From 2a8e7a303501d327ed7076eca15b3d1199294e51 Mon Sep 17 00:00:00 2001 From: Doug Cain Date: Sat, 7 Nov 2026 11:28:17 +0000 Subject: [PATCH] fix: refresh SAML signing certificates and fail logins cleanly when the IdP is unreachable The provider read its federation metadata once per application lifetime, so an IdP certificate rotation broke every login until a restart. It now re-reads the metadata every certificateRefreshMinutes (default 60) and keeps the held certificates when a refresh fails. OpenSAML initialisation and the metadata fetch moved to first use, so an unreachable metadata URL surfaced as an unhandled error from both entry points. processAuthorizationEvent now reports a failed login, and Auth.start redirects to errorRedirect. --- changelog.md | 8 ++ handlers/Auth.cfc | 21 +++- models/providers/MicrosoftSAMLProvider.cfc | 60 ++++++++-- readme.md | 7 ++ test-harness/tests/specs/AuthHandlerSpec.cfc | 22 ++++ .../tests/specs/MicrosoftSAMLProviderSpec.cfc | 109 ++++++++++++++++++ 6 files changed, 216 insertions(+), 11 deletions(-) create mode 100644 test-harness/tests/specs/MicrosoftSAMLProviderSpec.cfc diff --git a/changelog.md b/changelog.md index 2871a05..e8169b0 100644 --- a/changelog.md +++ b/changelog.md @@ -9,6 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- Re-read the SAML provider's federation metadata every `certificateRefreshMinutes` (default 60) instead of once per application lifetime. After an IdP rotated its signing certificate, every login failed until the application restarted. A failed refresh keeps the certificates already held and retries after 5 minutes. + +- Report a failed login, rather than an unhandled error, when the SAML provider cannot initialise OpenSAML or fetch its metadata in `processAuthorizationEvent`. + +- Redirect to `errorRedirect` when a provider cannot build its authentication request in `Auth.start`, instead of an unhandled error. Since OpenSAML initialisation and the metadata fetch moved to first use, an unreachable metadata URL surfaced here. + ## [3.3.0] - 2026-11-07 ### Fixed diff --git a/handlers/Auth.cfc b/handlers/Auth.cfc index e1f9fbb..182c4f1 100644 --- a/handlers/Auth.cfc +++ b/handlers/Auth.cfc @@ -22,8 +22,27 @@ component { prc.ssoProvider = variables.ProviderService.get( providerName ); } + /** + * A provider that cannot build its request - an unreachable IdP metadata URL, a missing jar - sends the + * user to the configured error page rather than an unhandled error. The relocate stays outside the try + * because relocate() aborts the request, which a catch would swallow. + */ function start( event, rc, prc ){ - relocate( url = prc.ssoProvider.startAuthenticationWorflow( event ) ); + var authorizationURL = ""; + + try { + authorizationURL = prc.ssoProvider.startAuthenticationWorflow( event ); + } catch ( any e ) { + log.error( + "Could not start SSO with provider [#prc.ssoProvider.getName()#]", + { "error" : e.message, "detail" : e.detail ?: "" } + ); + + relocate( variables.moduleSettings.errorRedirect ); + return; + } + + relocate( url = authorizationURL ); } function authorize( event, rc, prc ){ diff --git a/models/providers/MicrosoftSAMLProvider.cfc b/models/providers/MicrosoftSAMLProvider.cfc index 7cd9de5..8f050bd 100644 --- a/models/providers/MicrosoftSAMLProvider.cfc +++ b/models/providers/MicrosoftSAMLProvider.cfc @@ -11,6 +11,7 @@ component property name="redirectUri"; property name="federationMetadataURL"; property name="expectedIssuer"; + property name="certificateRefreshMinutes"; property name="wirebox" inject="wirebox"; property name="javaLoader" inject="loader@cbjavaloader"; @@ -18,11 +19,17 @@ component property name="responseValidator"; property name="SAMLParsingService" inject="SAMLParsingService@cbsso"; property name="SAMLRequestTracker" inject="SAMLRequestTracker@cbsso"; - - variables.name = "Entra"; - variables.federationMetadataURL = ""; - variables.maxDecodedResponseChars = 1048576; - variables.certificatesCached = false; + property name="log" inject="logbox:logger:{this}"; + + variables.name = "Entra"; + variables.federationMetadataURL = ""; + variables.maxDecodedResponseChars = 1048576; + variables.certificatesCached = false; + // Signing certificates rotate, so the metadata is re-read on this interval rather than once per + // application lifetime; a failed refresh keeps the certificates already held and retries sooner. + variables.certificateRefreshMinutes = 60; + variables.certificateRetryMinutes = 5; + variables.certificatesRefreshAfter = ""; public string function getName(){ return variables.name; @@ -51,9 +58,10 @@ component public any function processAuthorizationEvent( required any event ){ var authResponse = wirebox.getInstance( "SSOAuthorizationResponse@cbsso" ); - initializeOpenSAMLLib(); - try { + // Inside the try so an unreachable metadata URL fails this login rather than the request + initializeOpenSAMLLib(); + var decoded = binaryDecode( event.getValue( "SAMLResponse" ), "base64" ); var data = charsetEncode( decoded, "utf-8" ); @@ -197,7 +205,7 @@ component } ); } - if ( variables.certificatesCached ) { + if ( certificatesAreFresh() ) { return; } @@ -212,9 +220,41 @@ component ); } - variables.responseValidator.cacheCerts( variables.federationMetadataURL ); + lock name="cbsso-saml-certificates-#variables.name#" type="exclusive" timeout="30" { + if ( certificatesAreFresh() ) { + return; + } + + try { + variables.responseValidator.cacheCerts( variables.federationMetadataURL ); + } catch ( any e ) { + if ( !variables.certificatesCached ) { + rethrow; + } + + // cacheCerts only replaces the certificates once new ones have parsed, so the IdP being + // briefly unreachable must not stop every login that the held certificates still verify. + variables.log.warn( + "Could not refresh signing certificates for SAML provider [#variables.name#]; keeping the current ones", + { "error" : e.message } + ); + variables.certificatesRefreshAfter = dateAdd( "n", variables.certificateRetryMinutes, now() ); + return; + } + + variables.certificatesCached = true; + variables.certificatesRefreshAfter = dateAdd( + "n", + variables.certificateRefreshMinutes, + now() + ); + } + } - variables.certificatesCached = true; + private boolean function certificatesAreFresh(){ + return variables.certificatesCached + && isDate( variables.certificatesRefreshAfter ) + && dateCompare( now(), variables.certificatesRefreshAfter ) < 0; } /** diff --git a/readme.md b/readme.md index aa41edd..5b9b0dd 100644 --- a/readme.md +++ b/readme.md @@ -71,6 +71,13 @@ component { When `samlRequestCacheName` is set, the named cache must already be registered with CacheBox when cbSSO activates; otherwise module activation fails rather than silently falling back to local memory. +### SAML signing certificates + +The Microsoft SAML provider reads its signing certificates from `federationMetadataURL` on first use and +re-reads them every 60 minutes, so a rotated IdP certificate is picked up without a restart. Set +`certificateRefreshMinutes` on the provider definition to change the interval. If a refresh fails, the +certificates already held stay in use and the refresh is retried after 5 minutes. + For more complete documentation covering features and implementation check out our documentation site [cbsso.ortusbooks.com](https://cbsso.ortusbooks.com). diff --git a/test-harness/tests/specs/AuthHandlerSpec.cfc b/test-harness/tests/specs/AuthHandlerSpec.cfc index 566cd16..649107c 100644 --- a/test-harness/tests/specs/AuthHandlerSpec.cfc +++ b/test-harness/tests/specs/AuthHandlerSpec.cfc @@ -59,6 +59,28 @@ component extends="coldbox.system.testing.BaseTestCase" { expect( event.getValue( "relocate_URL", "" ) ).toInclude( "/main/fakeIdentityProvider" ); } ); + it( "redirects start() to the error page when the provider cannot build its request", function(){ + var providers = getInstance( "ProviderService@cbsso" ).getProviders(); + var original = providers[ "CustomProvider" ]; + + providers[ "CustomProvider" ] = createStub() + .$( "getName", "CustomProvider" ) + .$( + method = "startAuthenticationWorflow", + throwException = true, + throwMessage = "metadata unreachable" + ); + + try { + var event = execute( route = "/cbsso/auth/CustomProvider/start", renderResults = false ); + } finally { + providers[ "CustomProvider" ] = original; + } + + expect( event.getValue( "relocate_event", "__none__" ) ).toBe( moduleSettings.errorRedirect ); + expect( event.getValue( "relocate_URL", "" ) ).toBeEmpty(); + } ); + it( "does not announce CBSSOAuthorization for a missing provider", function(){ execute( route = "/cbsso/auth/notaprovider", renderResults = false ); diff --git a/test-harness/tests/specs/MicrosoftSAMLProviderSpec.cfc b/test-harness/tests/specs/MicrosoftSAMLProviderSpec.cfc new file mode 100644 index 0000000..7f9e737 --- /dev/null +++ b/test-harness/tests/specs/MicrosoftSAMLProviderSpec.cfc @@ -0,0 +1,109 @@ +component extends="coldbox.system.testing.BaseTestCase" { + + this.loadColdbox = true; + this.unLoadColdBox = false; + + function run( testResults, testBox ){ + describe( "MicrosoftSAMLProvider", function(){ + beforeEach( function(){ + setup(); + variables.provider = prepareMock( getInstance( "MicrosoftSAMLProvider@cbsso" ) ); + variables.validator = createStub().$( "cacheCerts" ); + variables.logger = createStub().$( "warn" ); + + // A non-null generator skips OpenSAML initialisation, leaving only the certificate handling + variables.provider.$property( propertyName = "AuthNRequestGenerator", mock = createStub() ); + variables.provider.$property( propertyName = "responseValidator", mock = variables.validator ); + variables.provider.$property( propertyName = "log", mock = variables.logger ); + variables.provider.setFederationMetadataURL( "https://idp.example.com/federationmetadata.xml" ); + makePublic( variables.provider, "initializeOpenSAMLLib" ); + } ); + + describe( "processAuthorizationEvent", function(){ + it( "reports a failed login when the IdP metadata cannot be fetched", function(){ + variables.provider.$( + method = "initializeOpenSAMLLib", + throwException = true, + throwType = "MicrosoftSAMLProvider.CertificateCachingError", + throwMessage = "metadata unreachable" + ); + + var response = variables.provider.processAuthorizationEvent( createStub().$( "getValue", "" ) ); + + expect( response.wasSuccessful() ).toBeFalse(); + expect( response.getErrorMessage() ).toBe( "metadata unreachable" ); + } ); + } ); + + describe( "signing certificates", function(){ + it( "fetches them once and reuses them while they are fresh", function(){ + variables.provider.initializeOpenSAMLLib(); + variables.provider.initializeOpenSAMLLib(); + + expect( variables.validator.$count( "cacheCerts" ) ).toBe( 1 ); + } ); + + it( "re-reads the metadata once the refresh interval has passed", function(){ + variables.provider.initializeOpenSAMLLib(); + variables.provider.$property( + propertyName = "certificatesRefreshAfter", + mock = dateAdd( "n", -1, now() ) + ); + + variables.provider.initializeOpenSAMLLib(); + + expect( variables.validator.$count( "cacheCerts" ) ).toBe( 2 ); + } ); + + it( "honours a configured refresh interval", function(){ + variables.provider.setCertificateRefreshMinutes( 1440 ); + + variables.provider.initializeOpenSAMLLib(); + + var refreshAfter = variables.provider.$getProperty( "certificatesRefreshAfter" ); + expect( dateDiff( "n", now(), refreshAfter ) ).toBeBetween( 1430, 1440 ); + } ); + + it( "keeps the held certificates when a refresh fails, and retries sooner", function(){ + variables.provider.initializeOpenSAMLLib(); + variables.provider.$property( + propertyName = "certificatesRefreshAfter", + mock = dateAdd( "n", -1, now() ) + ); + variables.validator.$( + method = "cacheCerts", + throwException = true, + throwMessage = "metadata unreachable" + ); + + expect( () => variables.provider.initializeOpenSAMLLib() ).notToThrow(); + + var refreshAfter = variables.provider.$getProperty( "certificatesRefreshAfter" ); + expect( dateDiff( "n", now(), refreshAfter ) ).toBeBetween( 3, 5 ); + expect( variables.logger.$count( "warn" ) ).toBe( 1 ); + } ); + + it( "fails when the first fetch fails, since there is nothing to verify with", function(){ + variables.validator.$( + method = "cacheCerts", + throwException = true, + throwType = "MetadataFetchError", + throwMessage = "metadata unreachable" + ); + + expect( () => variables.provider.initializeOpenSAMLLib() ).toThrow( "MetadataFetchError" ); + } ); + + it( "fetches again when the metadata URL changes", function(){ + variables.provider.initializeOpenSAMLLib(); + variables.provider.setFederationMetadataURL( "https://idp.example.com/other.xml" ); + + variables.provider.initializeOpenSAMLLib(); + + expect( variables.validator.$count( "cacheCerts" ) ).toBe( 2 ); + } ); + } ); + } ); + } + +}