Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion handlers/Auth.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -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 ){
Expand Down
60 changes: 50 additions & 10 deletions models/providers/MicrosoftSAMLProvider.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,25 @@ component
property name="redirectUri";
property name="federationMetadataURL";
property name="expectedIssuer";
property name="certificateRefreshMinutes";

property name="wirebox" inject="wirebox";
property name="javaLoader" inject="loader@cbjavaloader";
property name="AuthNRequestGenerator";
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;
Expand Down Expand Up @@ -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" );

Expand Down Expand Up @@ -197,7 +205,7 @@ component
} );
}

if ( variables.certificatesCached ) {
if ( certificatesAreFresh() ) {
return;
}

Expand All @@ -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;
}

/**
Expand Down
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).


Expand Down
22 changes: 22 additions & 0 deletions test-harness/tests/specs/AuthHandlerSpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -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 );

Expand Down
109 changes: 109 additions & 0 deletions test-harness/tests/specs/MicrosoftSAMLProviderSpec.cfc
Original file line number Diff line number Diff line change
@@ -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 );
} );
} );
} );
}

}
Loading