From 202642702438b876b5f3ed3e7935f80ef3ebb920 Mon Sep 17 00:00:00 2001 From: Rob Ireton Date: Thu, 5 Nov 2026 14:37:12 -0500 Subject: [PATCH 1/2] Add trusted-assertion authentication provider Authenticates users from a short-lived signed JWT that an authenticating reverse proxy adds to each request (e.g. nginx auth_request in front of an SSO service), configured under security.auth.assertion.*. - GET /user/login/assertion verifies the header against a JWKS (ES256 by default; HS* and none refused), pins iss and aud, requires exp, and logs in through LoginService like every other provider. Listed in /auth/providers as an ajax provider, so Atlas needs no changes. - With enforce-on-every-request (default), a filter after Spring Security requires a valid assertion for the same user on every request made with a WebAPI session token. A leaked WebAPI token is useless without a live proxy session, and proxy sign-out takes effect within the assertion's lifetime. API-key requests are not affected. - An unreachable JWKS answers 503, not 401, so an outage doesn't read as everyone being signed out. JWKS fetches have a timeout. - auto-provision (default true) creates the user on first login; otherwise unknown users get 403. New UserOrigin.ASSERTION; origin is stored as a string, so no migration. Tests use a real local JWKS server so the production decoder, including its key fetch, is exercised: valid, expired, no exp, wrong/missing aud, wrong iss, no sub, foreign key, unknown kid, HS256, alg none, garbage, JWKS down, user binding, API-key and anonymous pass-through. Co-Authored-By: Claude Opus 5.5 --- .../webapi/auth/AuthProviderService.java | 21 +++ .../webapi/security/authc/UserOrigin.java | 2 +- .../authc/assertion/AssertionAuthConfig.java | 124 +++++++++++++ .../assertion/AssertionAuthProperties.java | 98 ++++++++++ .../assertion/AssertionBindingFilter.java | 67 +++++++ .../assertion/AssertionLoginController.java | 77 ++++++++ .../authc/assertion/AssertionVerifier.java | 82 +++++++++ src/main/resources/application.yaml | 13 ++ .../assertion/AssertionBindingFilterTest.java | 135 ++++++++++++++ .../authc/assertion/AssertionFixture.java | 112 ++++++++++++ .../AssertionLoginControllerTest.java | 112 ++++++++++++ .../assertion/AssertionVerifierTest.java | 169 ++++++++++++++++++ 12 files changed, 1011 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthConfig.java create mode 100644 src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthProperties.java create mode 100644 src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilter.java create mode 100644 src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginController.java create mode 100644 src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifier.java create mode 100644 src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilterTest.java create mode 100644 src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionFixture.java create mode 100644 src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginControllerTest.java create mode 100644 src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifierTest.java diff --git a/src/main/java/org/ohdsi/webapi/auth/AuthProviderService.java b/src/main/java/org/ohdsi/webapi/auth/AuthProviderService.java index 19a5921fbb..a9c57b705d 100644 --- a/src/main/java/org/ohdsi/webapi/auth/AuthProviderService.java +++ b/src/main/java/org/ohdsi/webapi/auth/AuthProviderService.java @@ -68,6 +68,15 @@ public class AuthProviderService { @Value("${security.auth.oidc.logoutUrl:}") private String oidcLogoutUrl; + @Value("${security.auth.assertion.enabled:false}") + private boolean assertionAuthEnabled; + + @Value("${security.auth.assertion.provider-name:Single Sign-On}") + private String assertionProviderName; + + @Value("${security.auth.assertion.logout-url:}") + private String assertionLogoutUrl; + /** * Get the list of enabled authentication providers. * This endpoint is publicly accessible (no auth required). @@ -76,6 +85,18 @@ public class AuthProviderService { public List getProviders() { List providers = new ArrayList<>(); + // Trusted assertion from an authenticating reverse proxy (no credentials form) + if (assertionAuthEnabled) { + providers.add(new AuthProviderInfo( + assertionProviderName, + "user/login/assertion", + true, + "mdi-shield-account", + false, + assertionLogoutUrl != null && !assertionLogoutUrl.isEmpty() ? assertionLogoutUrl : null + )); + } + // OpenID Connect (e.g., Logto, Keycloak, Okta) if (openidAuthEnabled) { providers.add(new AuthProviderInfo( diff --git a/src/main/java/org/ohdsi/webapi/security/authc/UserOrigin.java b/src/main/java/org/ohdsi/webapi/security/authc/UserOrigin.java index 1d9bd51f0c..bb4885c49c 100644 --- a/src/main/java/org/ohdsi/webapi/security/authc/UserOrigin.java +++ b/src/main/java/org/ohdsi/webapi/security/authc/UserOrigin.java @@ -3,7 +3,7 @@ import org.ohdsi.webapi.security.provisioning.model.LdapProviderType; public enum UserOrigin { - SYSTEM, AD, LDAP, WINDOWS, KERBEROS, GOOGLE, FACEBOOK, DATABASE, OIDC; + SYSTEM, AD, LDAP, WINDOWS, KERBEROS, GOOGLE, FACEBOOK, DATABASE, OIDC, ASSERTION; public static UserOrigin getFrom(LdapProviderType ldapProviderType) { switch (ldapProviderType) { diff --git a/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthConfig.java b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthConfig.java new file mode 100644 index 0000000000..17bd7e6ed6 --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthConfig.java @@ -0,0 +1,124 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import org.ohdsi.webapi.security.authc.HttpSecurityShared; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.security.SecurityProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidator; +import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; +import org.springframework.security.oauth2.jwt.JwtClaimValidator; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtIssuerValidator; +import org.springframework.security.oauth2.jwt.JwtTimestampValidator; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.web.client.RestTemplate; + +/** + * Wires the trusted-assertion provider when {@code security.auth.assertion.enabled} + * is true. See {@link AssertionAuthProperties}. + */ +@Configuration +@ConditionalOnProperty(prefix = "security.auth.assertion", name = "enabled", havingValue = "true") +@EnableConfigurationProperties(AssertionAuthProperties.class) +public class AssertionAuthConfig { + + public static final String LOGIN_PATH = "/user/login/assertion"; + + @Bean + public AssertionVerifier assertionVerifier(AssertionAuthProperties props) { + return new AssertionVerifier(assertionJwtDecoder(props), props); + } + + /** Builds the decoder: JWKS-backed, algorithm-restricted, iss/aud/exp enforced. */ + static JwtDecoder assertionJwtDecoder(AssertionAuthProperties props) { + require(props.getJwkSetUri(), "jwk-set-uri"); + require(props.getIssuer(), "issuer"); + require(props.getAudience(), "audience"); + if (props.getAlgorithms() == null || props.getAlgorithms().isEmpty()) { + throw new IllegalStateException("security.auth.assertion.algorithms must not be empty"); + } + + List algorithms = new ArrayList<>(); + for (String name : props.getAlgorithms()) { + SignatureAlgorithm alg = SignatureAlgorithm.from(name.trim()); + if (alg == null) { + // SignatureAlgorithm has only asymmetric algorithms, so HS* lands here too. + throw new IllegalStateException("security.auth.assertion.algorithms: unsupported " + name); + } + algorithms.add(alg); + } + + // Without explicit timeouts a hung JWKS endpoint would hang every request. + SimpleClientHttpRequestFactory http = new SimpleClientHttpRequestFactory(); + http.setConnectTimeout((int) props.getJwksTimeout().toMillis()); + http.setReadTimeout((int) props.getJwksTimeout().toMillis()); + + NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(props.getJwkSetUri()) + .jwsAlgorithms(set -> { + set.clear(); + set.addAll(algorithms); + }) + .restOperations(new RestTemplate(http)) + .build(); + + String audience = props.getAudience(); + List> validators = List.of( + new JwtTimestampValidator(props.getClockSkew()), + // JwtTimestampValidator only checks exp when present; an assertion without + // one would never expire. + new JwtClaimValidator(JwtClaimNames.EXP, Objects::nonNull), + new JwtIssuerValidator(props.getIssuer()), + new JwtClaimValidator>(JwtClaimNames.AUD, + aud -> aud != null && aud.contains(audience))); + decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(validators)); + return decoder; + } + + private static void require(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("security.auth.assertion." + name + " is required when the provider is enabled"); + } + } + + /** + * The login endpoint must be reachable without a WebAPI token: it is how one is + * obtained. The controller does its own verification. + */ + @Bean + @Order(2) + public SecurityFilterChain assertionLoginChain(HttpSecurity http, HttpSecurityShared shared) throws Exception { + shared.configureDefaults(http); + http.securityMatcher(LOGIN_PATH) + .authorizeHttpRequests(authz -> authz.anyRequest().permitAll()); + return http.build(); + } + + /** + * Runs just after Spring Security, once the WebAPI token has been resolved, so + * it can compare the token's user with the assertion's. + */ + @Bean + @ConditionalOnProperty(prefix = "security.auth.assertion", name = "enforce-on-every-request", + havingValue = "true", matchIfMissing = true) + public FilterRegistrationBean assertionBindingFilter(AssertionVerifier verifier) { + FilterRegistrationBean registration = + new FilterRegistrationBean<>(new AssertionBindingFilter(verifier)); + registration.setOrder(SecurityProperties.DEFAULT_FILTER_ORDER + 1); + registration.addUrlPatterns("/*"); + return registration; + } +} diff --git a/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthProperties.java b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthProperties.java new file mode 100644 index 0000000000..a8e9827ad3 --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionAuthProperties.java @@ -0,0 +1,98 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.time.Duration; +import java.util.List; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Settings for the trusted-assertion provider ({@code security.auth.assertion.*}). + * + *

The provider authenticates a user from a short-lived signed JWT that a + * reverse proxy adds to every request after its own authentication (for example + * nginx {@code auth_request} in front of an SSO service). WebAPI verifies the + * signature against a JWKS and pins the issuer and audience, so the header can't + * be forged by a client, even one that reaches WebAPI directly. + */ +@ConfigurationProperties(prefix = "security.auth.assertion") +public class AssertionAuthProperties { + + /** Turns the provider on. Off by default. */ + private boolean enabled = false; + + /** Request header that carries the assertion. */ + private String header = "sso-assertion"; + + /** JWKS endpoint holding the proxy's public signing keys. Required when enabled. */ + private String jwkSetUri; + + /** Exact {@code iss} the assertion must carry. Required when enabled. */ + private String issuer; + + /** Value the assertion's {@code aud} must contain. Required when enabled. */ + private String audience; + + /** Accepted JWS algorithms. Anything else, including HS* and none, is refused. */ + private List algorithms = List.of("ES256"); + + /** Allowed clock difference when checking {@code exp} and {@code nbf}. */ + private Duration clockSkew = Duration.ofSeconds(30); + + /** Connect and read timeout for fetching the JWKS. */ + private Duration jwksTimeout = Duration.ofSeconds(5); + + /** Claim holding the WebAPI login. */ + private String usernameClaim = "sub"; + + /** Claims used to build the display name; the login is used when both are empty. */ + private String givenNameClaim = "given_name"; + private String familyNameClaim = "family_name"; + + /** Create a WebAPI user on first login. When false, unknown users get 403. */ + private boolean autoProvision = true; + + /** + * Require a valid assertion for the same user on every request made with a + * WebAPI session token, not just at login. A leaked WebAPI token is then useless + * without a live proxy session, and signing out at the proxy takes effect within + * the assertion's lifetime. API-key requests are not affected. + */ + private boolean enforceOnEveryRequest = true; + + /** Name shown for this provider in {@code /auth/providers}. */ + private String providerName = "Single Sign-On"; + + /** Logout URL handed to the client, e.g. the proxy's own sign-out page. */ + private String logoutUrl; + + public boolean isEnabled() { return enabled; } + public void setEnabled(boolean enabled) { this.enabled = enabled; } + public String getHeader() { return header; } + public void setHeader(String header) { this.header = header; } + public String getJwkSetUri() { return jwkSetUri; } + public void setJwkSetUri(String jwkSetUri) { this.jwkSetUri = jwkSetUri; } + public String getIssuer() { return issuer; } + public void setIssuer(String issuer) { this.issuer = issuer; } + public String getAudience() { return audience; } + public void setAudience(String audience) { this.audience = audience; } + public List getAlgorithms() { return algorithms; } + public void setAlgorithms(List algorithms) { this.algorithms = algorithms; } + public Duration getClockSkew() { return clockSkew; } + public void setClockSkew(Duration clockSkew) { this.clockSkew = clockSkew; } + public Duration getJwksTimeout() { return jwksTimeout; } + public void setJwksTimeout(Duration jwksTimeout) { this.jwksTimeout = jwksTimeout; } + public String getUsernameClaim() { return usernameClaim; } + public void setUsernameClaim(String usernameClaim) { this.usernameClaim = usernameClaim; } + public String getGivenNameClaim() { return givenNameClaim; } + public void setGivenNameClaim(String givenNameClaim) { this.givenNameClaim = givenNameClaim; } + public String getFamilyNameClaim() { return familyNameClaim; } + public void setFamilyNameClaim(String familyNameClaim) { this.familyNameClaim = familyNameClaim; } + public boolean isAutoProvision() { return autoProvision; } + public void setAutoProvision(boolean autoProvision) { this.autoProvision = autoProvision; } + public boolean isEnforceOnEveryRequest() { return enforceOnEveryRequest; } + public void setEnforceOnEveryRequest(boolean enforceOnEveryRequest) { this.enforceOnEveryRequest = enforceOnEveryRequest; } + public String getProviderName() { return providerName; } + public void setProviderName(String providerName) { this.providerName = providerName; } + public String getLogoutUrl() { return logoutUrl; } + public void setLogoutUrl(String logoutUrl) { this.logoutUrl = logoutUrl; } +} diff --git a/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilter.java b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilter.java new file mode 100644 index 0000000000..340c21abe6 --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilter.java @@ -0,0 +1,67 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.io.IOException; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.ohdsi.webapi.security.authc.WebApiAuthenticationToken; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +/** + * Binds a WebAPI session token to a live proxy assertion for the same user. + * + *

Applies only to requests authenticated with a WebAPI session token. Anonymous + * requests are left to WebAPI's own authorization, and API-key requests (which + * carry no session) are not touched, so service-to-service calls keep working. + */ +public class AssertionBindingFilter extends OncePerRequestFilter { + + private static final Logger log = LoggerFactory.getLogger(AssertionBindingFilter.class); + + private final AssertionVerifier verifier; + + public AssertionBindingFilter(AssertionVerifier verifier) { + this.verifier = verifier; + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (!(auth instanceof WebApiAuthenticationToken token) || !token.hasSession() || token.isAnonymous()) { + chain.doFilter(request, response); + return; + } + + String tokenLogin = token.getName(); + switch (verifier.verify(request)) { + case AssertionVerifier.Verified v when v.login().equalsIgnoreCase(tokenLogin) -> + chain.doFilter(request, response); + case AssertionVerifier.Verified v -> { + log.warn("SECURITY_AUDIT: token for '{}' presented with assertion for '{}'", tokenLogin, v.login()); + reject(response, HttpServletResponse.SC_UNAUTHORIZED, "Assertion does not match the session user"); + } + case AssertionVerifier.Unavailable u -> + reject(response, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Identity provider unavailable"); + case AssertionVerifier.Missing m -> + reject(response, HttpServletResponse.SC_UNAUTHORIZED, "Assertion required"); + case AssertionVerifier.Invalid i -> + reject(response, HttpServletResponse.SC_UNAUTHORIZED, "Invalid assertion"); + } + } + + private static void reject(HttpServletResponse response, int status, String message) throws IOException { + response.setStatus(status); + response.setHeader("x-auth-error", message); + response.setContentType("application/json"); + response.getWriter().write("{\"message\":\"" + message + "\"}"); + } +} diff --git a/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginController.java b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginController.java new file mode 100644 index 0000000000..13115407a1 --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginController.java @@ -0,0 +1,77 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.util.Collections; + +import jakarta.servlet.http.HttpServletRequest; + +import org.ohdsi.webapi.security.authc.AuthenticatedLogin; +import org.ohdsi.webapi.security.authc.LoginService; +import org.ohdsi.webapi.security.authc.UserOrigin; +import org.ohdsi.webapi.security.authz.AuthorizationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * {@code GET /user/login/assertion}: exchange a verified proxy assertion for a + * WebAPI session and token, through the same {@link LoginService} as every other + * provider. Responds like the other login endpoints, so clients that support an + * "ajax" provider (no credentials form) need nothing special. + */ +@RestController +@ConditionalOnProperty(prefix = "security.auth.assertion", name = "enabled", havingValue = "true") +public class AssertionLoginController { + + private static final Logger log = LoggerFactory.getLogger(AssertionLoginController.class); + + private final AssertionVerifier verifier; + private final LoginService loginService; + private final AuthorizationService authorizationService; + private final AssertionAuthProperties props; + + public AssertionLoginController(AssertionVerifier verifier, LoginService loginService, + AuthorizationService authorizationService, AssertionAuthProperties props) { + this.verifier = verifier; + this.loginService = loginService; + this.authorizationService = authorizationService; + this.props = props; + } + + @GetMapping(value = AssertionAuthConfig.LOGIN_PATH, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity login(HttpServletRequest request) { + return switch (verifier.verify(request)) { + case AssertionVerifier.Verified v -> loginAs(v); + case AssertionVerifier.Missing m -> refuse(HttpStatus.UNAUTHORIZED, "Assertion required"); + case AssertionVerifier.Invalid i -> refuse(HttpStatus.UNAUTHORIZED, "Invalid assertion"); + case AssertionVerifier.Unavailable u -> refuse(HttpStatus.SERVICE_UNAVAILABLE, "Identity provider unavailable"); + }; + } + + private ResponseEntity loginAs(AssertionVerifier.Verified v) { + if (!props.isAutoProvision() && authorizationService.getUserByLogin(v.login()).isEmpty()) { + log.info("Assertion login refused for unknown user '{}' (auto-provision off)", v.login()); + return refuse(HttpStatus.FORBIDDEN, "User is not registered"); + } + + AuthenticatedLogin login = AuthenticatedLogin.builder() + .login(v.login()) + .name(v.name()) + .origin(UserOrigin.ASSERTION) + // Assertions carry no roles; roles are managed in WebAPI. + .roles(Collections.emptySet()) + .attribute("assertion.issuer", v.jwt().getIssuer() == null ? null : v.jwt().getIssuer().toString()) + .build(); + return ResponseEntity.ok(loginService.onSuccess(login)); + } + + private static ResponseEntity refuse(HttpStatus status, String message) { + return ResponseEntity.status(status) + .header("x-auth-error", message) + .body(new LoginService.Result(null, null, null, message)); + } +} diff --git a/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifier.java b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifier.java new file mode 100644 index 0000000000..5771b27dd4 --- /dev/null +++ b/src/main/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifier.java @@ -0,0 +1,82 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.util.Locale; + +import jakarta.servlet.http.HttpServletRequest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.oauth2.jwt.BadJwtException; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtException; + +/** + * Verifies the assertion header on a request. + * + *

Failures are split by cause, because they call for different responses: a + * missing or bad assertion is the client's problem (401), while an unreachable + * JWKS is ours (503). Treating an outage as "bad token" would sign everyone out. + */ +public class AssertionVerifier { + + private static final Logger log = LoggerFactory.getLogger(AssertionVerifier.class); + + /** Result of checking one request. */ + public sealed interface Outcome permits Verified, Missing, Invalid, Unavailable {} + + /** A valid assertion. {@code login} is already lower-cased, as WebAPI stores logins. */ + public record Verified(Jwt jwt, String login, String name) implements Outcome {} + + public record Missing() implements Outcome {} + + public record Invalid(String reason) implements Outcome {} + + public record Unavailable(String reason) implements Outcome {} + + private final JwtDecoder decoder; + private final AssertionAuthProperties props; + + public AssertionVerifier(JwtDecoder decoder, AssertionAuthProperties props) { + this.decoder = decoder; + this.props = props; + } + + public Outcome verify(HttpServletRequest request) { + String token = request.getHeader(props.getHeader()); + if (token == null || token.isBlank()) { + return new Missing(); + } + return verify(token.trim()); + } + + public Outcome verify(String token) { + Jwt jwt; + try { + jwt = decoder.decode(token); + } catch (BadJwtException e) { + // Malformed, wrong algorithm, bad signature, unknown key, or failed + // issuer/audience/time validation. + log.debug("Assertion refused: {}", e.getMessage()); + return new Invalid(e.getMessage()); + } catch (JwtException e) { + // Anything else from the decoder, chiefly a JWKS that couldn't be fetched. + log.warn("Assertion could not be checked: {}", e.getMessage()); + return new Unavailable(e.getMessage()); + } + + String login = jwt.getClaimAsString(props.getUsernameClaim()); + if (login == null || login.isBlank()) { + return new Invalid("assertion has no " + props.getUsernameClaim() + " claim"); + } + login = login.trim().toLowerCase(Locale.ROOT); + return new Verified(jwt, login, displayName(jwt, login)); + } + + private String displayName(Jwt jwt, String login) { + String given = jwt.getClaimAsString(props.getGivenNameClaim()); + String family = jwt.getClaimAsString(props.getFamilyNameClaim()); + String name = ((given == null ? "" : given.trim()) + " " + (family == null ? "" : family.trim())).trim(); + return name.isEmpty() ? login : name; + } +} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 4129e720ba..0188d5034b 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -142,6 +142,19 @@ security: middlenameAttr: initials usernameAttr: cn + assertion: # Trusted assertion: a signed JWT header added by an authenticating reverse proxy + enabled: false + header: sso-assertion + jwk-set-uri: "" # e.g. https://host/auth/.well-known/jwks.json (required when enabled) + issuer: "" # exact iss (required when enabled) + audience: "" # value aud must contain (required when enabled) + algorithms: ES256 + clock-skew: 30s + auto-provision: true + # Also require a matching assertion on every request made with a WebAPI session token + enforce-on-every-request: true + provider-name: Single Sign-On + logout-url: "" cas: # Central Authentication Security (CAS) enabled: false callbackUrl: "" diff --git a/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilterTest.java b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilterTest.java new file mode 100644 index 0000000000..a7386eaa32 --- /dev/null +++ b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionBindingFilterTest.java @@ -0,0 +1,135 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.ohdsi.webapi.security.authc.WebApiAuthenticationToken; +import org.ohdsi.webapi.security.identity.WebApiPrincipal; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; + +public class AssertionBindingFilterTest { + + private AssertionFixture fixture; + private AssertionBindingFilter filter; + + @Before + public void setUp() throws Exception { + fixture = new AssertionFixture(); + filter = new AssertionBindingFilter(fixture.verifier()); + } + + @After + public void tearDown() { + SecurityContextHolder.clearContext(); + fixture.close(); + } + + private static void authenticateAs(String login, UUID sessionId) { + WebApiPrincipal principal = mock(WebApiPrincipal.class); + when(principal.getName()).thenReturn(login); + when(principal.isAnonymous()).thenReturn(false); + SecurityContextHolder.getContext().setAuthentication( + WebApiAuthenticationToken.authenticated(principal, sessionId, List.of())); + } + + /** Runs the filter; returns the response, with the chain's request recorded. */ + private MockHttpServletResponse run(String assertion, MockFilterChain chain) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/cohortdefinition"); + if (assertion != null) { + request.addHeader("sso-assertion", assertion); + } + MockHttpServletResponse response = new MockHttpServletResponse(); + filter.doFilter(request, response, chain); + return response; + } + + @Test + public void sessionTokenWithMatchingAssertionPasses() throws Exception { + authenticateAs("ada", UUID.randomUUID()); + MockFilterChain chain = new MockFilterChain(); + + MockHttpServletResponse response = run(fixture.sign(AssertionFixture.claims("ADA").build()), chain); + + assertEquals(200, response.getStatus()); + assertNotNull("request reached the application", chain.getRequest()); + } + + @Test + public void sessionTokenWithoutAssertionIs401() throws Exception { + authenticateAs("ada", UUID.randomUUID()); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(401, run(null, chain).getStatus()); + assertNull(chain.getRequest()); + } + + @Test + public void sessionTokenWithAnotherUsersAssertionIs401() throws Exception { + authenticateAs("ada", UUID.randomUUID()); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(401, run(fixture.sign(AssertionFixture.claims("mallory").build()), chain).getStatus()); + assertNull(chain.getRequest()); + } + + @Test + public void sessionTokenWithInvalidAssertionIs401() throws Exception { + authenticateAs("ada", UUID.randomUUID()); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(401, run(AssertionFixture.unsigned(AssertionFixture.claims("ada").build()), chain).getStatus()); + assertNull(chain.getRequest()); + } + + @Test + public void unreachableJwksIs503() throws Exception { + String token = fixture.sign(AssertionFixture.claims("ada").build()); + fixture.close(); + authenticateAs("ada", UUID.randomUUID()); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(503, run(token, chain).getStatus()); + assertNull(chain.getRequest()); + } + + @Test + public void apiKeyRequestWithoutSessionIsNotChecked() throws Exception { + authenticateAs("service", null); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(200, run(null, chain).getStatus()); + assertNotNull(chain.getRequest()); + } + + @Test + public void anonymousRequestIsNotChecked() throws Exception { + SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken( + "key", "anonymous", List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")))); + MockFilterChain chain = new MockFilterChain(); + + assertEquals(200, run(null, chain).getStatus()); + assertNotNull(chain.getRequest()); + } + + @Test + public void unauthenticatedRequestIsNotChecked() throws Exception { + MockFilterChain chain = new MockFilterChain(); + + assertEquals(200, run(null, chain).getStatus()); + assertNotNull(chain.getRequest()); + } +} diff --git a/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionFixture.java b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionFixture.java new file mode 100644 index 0000000000..79817c5a23 --- /dev/null +++ b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionFixture.java @@ -0,0 +1,112 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Date; + +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.ECDSASigner; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.gen.ECKeyGenerator; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.PlainJWT; +import com.nimbusds.jwt.SignedJWT; +import com.sun.net.httpserver.HttpServer; + +/** + * Test support: an in-memory ES256 key served as a JWKS from a real local HTTP + * server, so the production decoder (including its JWKS fetch) is exercised. + */ +final class AssertionFixture implements AutoCloseable { + + static final String ISSUER = "https://sso.example.org/auth/"; + static final String AUDIENCE = "sso.example.org"; + static final String KID = "test-key"; + + final ECKey key; + private final HttpServer server; + + AssertionFixture() throws IOException, JOSEException { + key = new ECKeyGenerator(Curve.P_256).keyID(KID).generate(); + byte[] jwks = new JWKSet(key.toPublicJWK()).toString().getBytes(StandardCharsets.UTF_8); + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/jwks.json", exchange -> { + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, jwks.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(jwks); + } + }); + server.start(); + } + + String jwksUri() { + return "http://127.0.0.1:" + server.getAddress().getPort() + "/jwks.json"; + } + + AssertionAuthProperties props() { + return props(jwksUri()); + } + + static AssertionAuthProperties props(String jwksUri) { + AssertionAuthProperties p = new AssertionAuthProperties(); + p.setEnabled(true); + p.setJwkSetUri(jwksUri); + p.setIssuer(ISSUER); + p.setAudience(AUDIENCE); + return p; + } + + AssertionVerifier verifier() { + AssertionAuthProperties p = props(); + return new AssertionVerifier(AssertionAuthConfig.assertionJwtDecoder(p), p); + } + + /** Claims as CHI-style SSO issues them: two minutes, sub + names. */ + static JWTClaimsSet.Builder claims(String sub) { + Instant now = Instant.now(); + return new JWTClaimsSet.Builder() + .issuer(ISSUER) + .audience(AUDIENCE) + .subject(sub) + .claim("email", sub + "@example.org") + .claim("given_name", "Ada") + .claim("family_name", "Lovelace") + .issueTime(Date.from(now)) + .expirationTime(Date.from(now.plusSeconds(120))); + } + + String sign(JWTClaimsSet claims) throws JOSEException { + return sign(key, claims); + } + + static String sign(ECKey signingKey, JWTClaimsSet claims) throws JOSEException { + SignedJWT jwt = new SignedJWT( + new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(signingKey.getKeyID()).build(), claims); + jwt.sign(new ECDSASigner(signingKey)); + return jwt.serialize(); + } + + static String signHs256(JWTClaimsSet claims) throws JOSEException { + SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(KID).build(), claims); + jwt.sign(new MACSigner("0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8))); + return jwt.serialize(); + } + + static String unsigned(JWTClaimsSet claims) { + return new PlainJWT(claims).serialize(); + } + + @Override + public void close() { + server.stop(0); + } +} diff --git a/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginControllerTest.java b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginControllerTest.java new file mode 100644 index 0000000000..8e006ec05a --- /dev/null +++ b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionLoginControllerTest.java @@ -0,0 +1,112 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.ohdsi.webapi.security.authc.AuthenticatedLogin; +import org.ohdsi.webapi.security.authc.LoginService; +import org.ohdsi.webapi.security.authc.UserOrigin; +import org.ohdsi.webapi.security.authz.AuthorizationService; +import org.ohdsi.webapi.security.authz.User; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; + +public class AssertionLoginControllerTest { + + private AssertionFixture fixture; + private LoginService loginService; + private AuthorizationService authorizationService; + private AssertionAuthProperties props; + + @Before + public void setUp() throws Exception { + fixture = new AssertionFixture(); + loginService = mock(LoginService.class); + authorizationService = mock(AuthorizationService.class); + props = fixture.props(); + when(loginService.onSuccess(any())).thenReturn(new LoginService.Result("ada", "webapi-jwt", new String[0], "Login successful")); + } + + @After + public void tearDown() { + fixture.close(); + } + + private ResponseEntity login(String token) { + AssertionLoginController controller = new AssertionLoginController( + new AssertionVerifier(AssertionAuthConfig.assertionJwtDecoder(props), props), + loginService, authorizationService, props); + MockHttpServletRequest request = new MockHttpServletRequest("GET", AssertionAuthConfig.LOGIN_PATH); + if (token != null) { + request.addHeader("sso-assertion", token); + } + return controller.login(request); + } + + @Test + public void validAssertionLogsInThroughLoginService() throws Exception { + ResponseEntity response = login(fixture.sign(AssertionFixture.claims("Ada").build())); + + assertEquals(200, response.getStatusCode().value()); + assertEquals("webapi-jwt", response.getBody().jwt()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AuthenticatedLogin.class); + verify(loginService).onSuccess(captor.capture()); + AuthenticatedLogin login = captor.getValue(); + assertEquals("ada", login.getLogin()); + assertEquals("Ada Lovelace", login.getName()); + assertEquals(UserOrigin.ASSERTION, login.getOrigin()); + assertEquals(0, login.getRoles().size()); + } + + @Test + public void missingAssertionIs401() { + ResponseEntity response = login(null); + assertEquals(401, response.getStatusCode().value()); + assertEquals("Assertion required", response.getHeaders().getFirst("x-auth-error")); + verify(loginService, never()).onSuccess(any()); + } + + @Test + public void invalidAssertionIs401() throws Exception { + ResponseEntity response = + login(fixture.sign(AssertionFixture.claims("ada").audience("other.example.org").build())); + assertEquals(401, response.getStatusCode().value()); + verify(loginService, never()).onSuccess(any()); + } + + @Test + public void unreachableJwksIs503() throws Exception { + String token = fixture.sign(AssertionFixture.claims("ada").build()); + fixture.close(); + assertEquals(503, login(token).getStatusCode().value()); + verify(loginService, never()).onSuccess(any()); + } + + @Test + public void unknownUserIs403WhenAutoProvisionIsOff() throws Exception { + props.setAutoProvision(false); + when(authorizationService.getUserByLogin("ada")).thenReturn(Optional.empty()); + + assertEquals(403, login(fixture.sign(AssertionFixture.claims("ada").build())).getStatusCode().value()); + verify(loginService, never()).onSuccess(any()); + } + + @Test + public void knownUserLogsInWhenAutoProvisionIsOff() throws Exception { + props.setAutoProvision(false); + when(authorizationService.getUserByLogin("ada")).thenReturn(Optional.of(mock(User.class))); + + assertEquals(200, login(fixture.sign(AssertionFixture.claims("ada").build())).getStatusCode().value()); + } +} diff --git a/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifierTest.java b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifierTest.java new file mode 100644 index 0000000000..d9b07e26fd --- /dev/null +++ b/src/test/java/org/ohdsi/webapi/security/authc/assertion/AssertionVerifierTest.java @@ -0,0 +1,169 @@ +package org.ohdsi.webapi.security.authc.assertion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.time.Instant; +import java.util.Date; +import java.util.List; + +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.ECKey; +import com.nimbusds.jose.jwk.gen.ECKeyGenerator; +import com.nimbusds.jwt.JWTClaimsSet; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +public class AssertionVerifierTest { + + private AssertionFixture fixture; + private AssertionVerifier verifier; + + @Before + public void setUp() throws Exception { + fixture = new AssertionFixture(); + verifier = fixture.verifier(); + } + + @After + public void tearDown() { + fixture.close(); + } + + private AssertionVerifier.Outcome verify(String token) { + MockHttpServletRequest request = new MockHttpServletRequest(); + if (token != null) { + request.addHeader("sso-assertion", token); + } + return verifier.verify(request); + } + + private static void assertInvalid(AssertionVerifier.Outcome outcome) { + assertTrue("expected Invalid, got " + outcome, outcome instanceof AssertionVerifier.Invalid); + } + + @Test + public void validAssertionIsVerified() throws Exception { + AssertionVerifier.Outcome outcome = verify(fixture.sign(AssertionFixture.claims("Ada").build())); + + assertTrue(outcome instanceof AssertionVerifier.Verified); + AssertionVerifier.Verified v = (AssertionVerifier.Verified) outcome; + assertEquals("login is lower-cased as WebAPI stores it", "ada", v.login()); + assertEquals("Ada Lovelace", v.name()); + } + + @Test + public void nameFallsBackToLogin() throws Exception { + JWTClaimsSet claims = AssertionFixture.claims("ada").claim("given_name", null).claim("family_name", null).build(); + AssertionVerifier.Verified v = (AssertionVerifier.Verified) verify(fixture.sign(claims)); + assertEquals("ada", v.name()); + } + + @Test + public void missingHeaderIsMissing() { + assertTrue(verify(null) instanceof AssertionVerifier.Missing); + assertTrue(verify(" ") instanceof AssertionVerifier.Missing); + } + + @Test + public void expiredAssertionIsRefused() throws Exception { + Instant past = Instant.now().minusSeconds(600); + JWTClaimsSet claims = AssertionFixture.claims("ada") + .issueTime(Date.from(past)).expirationTime(Date.from(past.plusSeconds(120))).build(); + assertInvalid(verify(fixture.sign(claims))); + } + + @Test + public void assertionWithoutExpiryIsRefused() throws Exception { + assertInvalid(verify(fixture.sign(AssertionFixture.claims("ada").expirationTime(null).build()))); + } + + @Test + public void wrongAudienceIsRefused() throws Exception { + assertInvalid(verify(fixture.sign(AssertionFixture.claims("ada").audience("other.example.org").build()))); + } + + @Test + public void missingAudienceIsRefused() throws Exception { + assertInvalid(verify(fixture.sign(AssertionFixture.claims("ada").audience((List) null).build()))); + } + + @Test + public void wrongIssuerIsRefused() throws Exception { + assertInvalid(verify(fixture.sign(AssertionFixture.claims("ada").issuer("https://evil.example.org/auth/").build()))); + } + + @Test + public void missingSubjectIsRefused() throws Exception { + assertInvalid(verify(fixture.sign(AssertionFixture.claims("ada").subject(null).build()))); + } + + @Test + public void signatureFromAnotherKeyIsRefused() throws Exception { + ECKey impostor = new ECKeyGenerator(Curve.P_256).keyID(AssertionFixture.KID).generate(); + assertInvalid(verify(AssertionFixture.sign(impostor, AssertionFixture.claims("ada").build()))); + } + + @Test + public void unknownKeyIdIsRefused() throws Exception { + ECKey other = new ECKeyGenerator(Curve.P_256).keyID("unknown").generate(); + assertInvalid(verify(AssertionFixture.sign(other, AssertionFixture.claims("ada").build()))); + } + + @Test + public void hs256AssertionIsRefused() throws Exception { + assertInvalid(verify(AssertionFixture.signHs256(AssertionFixture.claims("ada").build()))); + } + + @Test + public void unsignedAssertionIsRefused() { + assertInvalid(verify(AssertionFixture.unsigned(AssertionFixture.claims("ada").build()))); + } + + @Test + public void garbageIsRefused() { + assertInvalid(verify("not-a-jwt")); + } + + @Test + public void unreachableJwksIsUnavailableNotInvalid() throws Exception { + String token = fixture.sign(AssertionFixture.claims("ada").build()); + String uri = fixture.jwksUri(); + fixture.close(); + + AssertionAuthProperties p = AssertionFixture.props(uri); + AssertionVerifier down = new AssertionVerifier(AssertionAuthConfig.assertionJwtDecoder(p), p); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("sso-assertion", token); + + AssertionVerifier.Outcome outcome = down.verify(request); + assertTrue("expected Unavailable, got " + outcome, outcome instanceof AssertionVerifier.Unavailable); + } + + @Test + public void configuredHeaderNameIsUsed() throws Exception { + AssertionAuthProperties p = fixture.props(); + p.setHeader("x-identity"); + AssertionVerifier custom = new AssertionVerifier(AssertionAuthConfig.assertionJwtDecoder(p), p); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("x-identity", fixture.sign(AssertionFixture.claims("ada").build())); + assertTrue(custom.verify(request) instanceof AssertionVerifier.Verified); + } + + @Test + public void missingRequiredSettingsFailAtStartup() { + AssertionAuthProperties p = fixture.props(); + p.setAudience(""); + assertThrows(IllegalStateException.class, () -> AssertionAuthConfig.assertionJwtDecoder(p)); + } + + @Test + public void symmetricAlgorithmCannotBeConfigured() { + AssertionAuthProperties p = fixture.props(); + p.setAlgorithms(List.of("HS256")); + assertThrows(IllegalStateException.class, () -> AssertionAuthConfig.assertionJwtDecoder(p)); + } +} From 4b7889aa918bdf8ba3c9e4ad9d7db61708f4942d Mon Sep 17 00:00:00 2001 From: Rob Ireton Date: Mon, 16 Nov 2026 12:56:47 -0500 Subject: [PATCH 2/2] Document the trusted-assertion provider New articles/TrustedAssertion_HOWTO.md: when to use it, the login and per-request binding flow, property reference (including the optional claim and timeout settings), required claims, roles, proxy setup with an nginx auth_request example, endpoint responses and security notes. README lists security.auth.assertion.enabled with the other providers; LoginPipeline.md gains the flow entry and UserOrigin.ASSERTION. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + articles/LoginPipeline.md | 11 +- articles/TrustedAssertion_HOWTO.md | 281 +++++++++++++++++++++++++++++ 3 files changed, 292 insertions(+), 1 deletion(-) create mode 100644 articles/TrustedAssertion_HOWTO.md diff --git a/README.md b/README.md index fd035ff17a..3e15c78fdc 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,7 @@ Sample IdP and SP metadata configuration files for Okta: The following parameters enable or disable authentication providers: - `security.auth.ad.enabled` +- `security.auth.assertion.enabled` (signed assertion from an authenticating reverse proxy; see [articles/TrustedAssertion_HOWTO.md](articles/TrustedAssertion_HOWTO.md)) - `security.auth.cas.enabled` - `security.auth.jdbc.enabled` - `security.auth.kerberos.enabled` diff --git a/articles/LoginPipeline.md b/articles/LoginPipeline.md index 898bf61945..f239b88e5e 100644 --- a/articles/LoginPipeline.md +++ b/articles/LoginPipeline.md @@ -322,6 +322,14 @@ public void handleSuccess(OAuth2User user, ...) { 6. Handler builds `AuthenticatedLogin` with `origin=OIDC` and mapped roles 7. Returns JSON with new JWT (refreshed expiration) +### Trusted Assertion (Authenticating Reverse Proxy) +1. The proxy signs the user in and adds a signed JWT (`sso-assertion` header) to each request +2. Atlas calls `GET /user/login/assertion` +3. `AssertionVerifier` validates signature (JWKS), `alg`, `iss`, `aud` and `exp` +4. Handler builds `AuthenticatedLogin` with `origin=ASSERTION` +5. No groups (assertions carry no roles); roles come from default roles only +6. Later requests must carry a matching assertion (`AssertionBindingFilter`), see [TrustedAssertion_HOWTO.md](TrustedAssertion_HOWTO.md) + ## UserOrigin Tracking Each user's authentication history is tracked via `UserOrigin` enum: @@ -336,7 +344,8 @@ enum UserOrigin { GOOGLE, // OAuth2 Google FACEBOOK, // OAuth2 Facebook DATABASE, // Local database credentials - OIDC // Generic OIDC provider + OIDC, // Generic OIDC provider + ASSERTION // Signed assertion from an authenticating reverse proxy } ``` diff --git a/articles/TrustedAssertion_HOWTO.md b/articles/TrustedAssertion_HOWTO.md new file mode 100644 index 0000000000..7f0bba66c6 --- /dev/null +++ b/articles/TrustedAssertion_HOWTO.md @@ -0,0 +1,281 @@ +# Trusted Assertion Authentication — Configuration & Setup Guide + +This document describes how to sign users in to WebAPI from an authenticating +reverse proxy. The proxy (nginx `auth_request`, oauth2-proxy, Apache +`mod_auth_openidc`, or an institutional SSO gateway) has already signed the +user in. It adds a short-lived **signed JWT**, the *assertion*, to each request +it forwards. WebAPI verifies the assertion against the proxy's JWKS and logs +the user in through the normal login pipeline. + +Unlike a plain `REMOTE_USER`-style header, an assertion can't be forged by +someone who reaches WebAPI without going through the proxy. WebAPI trusts the +signature, not the network path. + +--- + +## Overview + +When trusted assertion authentication is enabled: + +1. The proxy authenticates the browser and adds the assertion header + (`sso-assertion` by default) to every request it forwards to `/WebAPI/`. +2. Atlas lists the provider from `/auth/providers` and calls + `GET /user/login/assertion`. WebAPI verifies the assertion and returns a + WebAPI JWT, as every other provider does. +3. With `enforce-on-every-request` (the default), every later request made with + that WebAPI JWT must also carry a valid assertion **for the same user**. + +Step 3 ties the WebAPI session to the proxy session: + +- A leaked WebAPI JWT is useless without a live proxy session. +- Signing out at the proxy takes effect within the assertion's lifetime, not + the WebAPI JWT's. + +API-key requests (see [APIKey_HOWTO.md](APIKey_HOWTO.md)) and anonymous +requests are not affected. + +Atlas needs no changes. The provider is listed in `/auth/providers` as an +`ajax` provider with no credentials form. + +--- + +## Architecture + +``` +Browser + │ (signed in at the proxy) + ▼ +Authenticating reverse proxy + │ adds sso-assertion: + ▼ +GET /user/login/assertion (permitAll security chain) + │ + ▼ +AssertionLoginController + │ + ├─▶ AssertionVerifier ──▶ NimbusJwtDecoder ──HTTPS──▶ proxy's JWKS + │ (alg allow-list; iss, aud and exp checks) + ▼ +LoginService.onSuccess(AuthenticatedLogin origin=ASSERTION) + │ + ▼ +WebAPI JWT returned to Atlas + +Later requests (Authorization: Bearer + sso-assertion) + │ + ▼ +Spring Security resolves the WebAPI JWT + │ + ▼ +AssertionBindingFilter ── assertion user must equal the token's user +``` + +### Key classes + +| Class | Package | Responsibility | +|---|---|---| +| `AssertionAuthConfig` | `security.authc.assertion` | Builds the JWT decoder, the permit-all login chain and the binding filter | +| `AssertionAuthProperties` | `security.authc.assertion` | Properties class for `security.auth.assertion.*` | +| `AssertionVerifier` | `security.authc.assertion` | Reads the header, verifies it, and sorts failures into missing, invalid or unavailable | +| `AssertionLoginController` | `security.authc.assertion` | `GET /user/login/assertion`; builds the `AuthenticatedLogin` | +| `AssertionBindingFilter` | `security.authc.assertion` | Per-request check that the assertion user matches the WebAPI JWT user | +| `AuthProviderService` | `auth` | Lists the provider in `/auth/providers` | + +--- + +## Configuration (application.yaml) + +All settings live under `security.auth.assertion`. The provider is disabled by +default. + +```yaml +security: + auth: + assertion: + enabled: true + header: sso-assertion # request header carrying the JWT + jwk-set-uri: https://sso.example.org/.well-known/jwks.json + issuer: https://sso.example.org # exact iss + audience: ohdsi-webapi # value aud must contain + algorithms: ES256 # comma-separated, asymmetric only + clock-skew: 30s + jwks-timeout: 5s + auto-provision: true + enforce-on-every-request: true + provider-name: Single Sign-On # label shown in Atlas + logout-url: https://sso.example.org/logout +``` + +`jwk-set-uri`, `issuer` and `audience` are required when the provider is +enabled. WebAPI refuses to start without them. + +### Property reference + +| Property | Type | Default | Description | +|---|---|---|---| +| `enabled` | boolean | `false` | Turns the provider on | +| `header` | String | `sso-assertion` | Request header that carries the assertion | +| `jwk-set-uri` | String | — | JWKS endpoint with the proxy's public signing keys. **Required** | +| `issuer` | String | — | Exact `iss` the assertion must carry. **Required** | +| `audience` | String | — | Value the assertion's `aud` must contain. **Required** | +| `algorithms` | List | `ES256` | Accepted JWS algorithms. Only asymmetric algorithms are allowed; `HS*` and `none` are refused | +| `clock-skew` | Duration | `30s` | Allowed clock difference when checking `exp` and `nbf` | +| `jwks-timeout` | Duration | `5s` | Connect and read timeout for fetching the JWKS | +| `username-claim` | String | `sub` | Claim holding the WebAPI login. The value is trimmed and lower-cased | +| `given-name-claim` | String | `given_name` | Claim used for the display name | +| `family-name-claim` | String | `family_name` | Claim used for the display name. The login is used when both name claims are empty | +| `auto-provision` | boolean | `true` | Create the WebAPI user on first login. When `false`, unknown users get 403 | +| `enforce-on-every-request` | boolean | `true` | Require a matching assertion on every request made with a WebAPI JWT, not just at login | +| `provider-name` | String | `Single Sign-On` | Name shown for this provider in `/auth/providers` | +| `logout-url` | String | — | Logout URL handed to the client, normally the proxy's own sign-out page | + +### What the assertion must contain + +| Claim / header | Requirement | +|---|---| +| `alg` (header) | One of `algorithms` | +| `kid` (header) | A key present in the JWKS | +| `iss` | Equal to `issuer` | +| `aud` | Contains `audience` | +| `exp` | **Present** and in the future, within `clock-skew`. An assertion without `exp` is refused | +| `nbf` | If present, in the past, within `clock-skew` | +| `sub` (or `username-claim`) | Non-blank; becomes the WebAPI login | +| `given_name`, `family_name` | Optional; used for the display name | + +Keep assertion lifetimes short; one to five minutes is typical. With +`enforce-on-every-request`, the lifetime is the longest a session can outlive +a sign-out at the proxy. + +--- + +## Roles + +Assertions carry no roles. A newly provisioned user gets the roles in +`security.defaultRoles`. Further roles are assigned by an administrator in +Atlas. Role sync on login only touches roles of the login's own origin, so +roles an administrator assigns survive later logins. See +[LoginPipeline.md](LoginPipeline.md). + +--- + +## Proxy Setup + +The proxy must: + +1. **Replace** any `sso-assertion` header sent by the client with its own, + never pass a client's copy through. WebAPI would reject a forged one, but + only the proxy should be supplying it. +2. Send the assertion on **every** request to `/WebAPI/`, not just the login + call, when `enforce-on-every-request` is on. +3. Pass WebAPI's own 401, 403 and 503 responses back to Atlas unchanged. If an + `error_page` or redirect-to-login turns them into an HTML page, Atlas can't + read them. +4. Serve the JWKS somewhere WebAPI can reach over HTTPS. + +An nginx example, where the SSO service answers `auth_request` subrequests +and returns the assertion in a response header: + +```nginx +location = /_sso_check { + internal; + proxy_pass https://sso.example.org/check; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-Original-URI $request_uri; +} + +location /WebAPI/ { + auth_request /_sso_check; + auth_request_set $sso_assertion $upstream_http_sso_assertion; + + # Replaces any sso-assertion header the client sent. + proxy_set_header sso-assertion $sso_assertion; + + # WebAPI's JSON 401/403/503 go back to Atlas as they are. + proxy_intercept_errors off; + + proxy_pass http://webapi:8080/WebAPI/; +} +``` + +Atlas's static files need no assertion; only `/WebAPI/` does. + +--- + +## REST Endpoints + +### `GET /user/login/assertion` — Exchange an assertion for a WebAPI JWT + +No WebAPI token is needed. The endpoint is how one is obtained. + +**Request** + +```http +GET /WebAPI/user/login/assertion +sso-assertion: eyJhbGciOiJFUzI1NiIsImtpZCI6... +``` + +**Success (200 OK):** the same JSON body every login endpoint returns, from +`LoginService`, including the WebAPI JWT. + +**Errors** + +| Status | `x-auth-error` header | Cause | +|---|---|---| +| 401 | `Assertion required` | Header missing or blank | +| 401 | `Invalid assertion` | Bad signature, unknown `kid`, disallowed `alg`, wrong `iss`/`aud`, missing or past `exp`, no username claim, or not a JWT | +| 403 | `User is not registered` | `auto-provision: false` and the user doesn't exist in WebAPI | +| 503 | `Identity provider unavailable` | The JWKS couldn't be fetched | + +### Per-request binding + +With `enforce-on-every-request: true`, any request authenticated by a WebAPI +JWT is checked after Spring Security resolves the token: + +| Status | `x-auth-error` header | Cause | +|---|---|---| +| 401 | `Assertion required` | No assertion on the request | +| 401 | `Invalid assertion` | As above | +| 401 | `Assertion does not match the session user` | The assertion is for a different user. Logged as `SECURITY_AUDIT` | +| 503 | `Identity provider unavailable` | The JWKS couldn't be fetched | + +Requests authenticated by an API key, and anonymous requests, pass through +unchecked. + +--- + +## Security Considerations + +- **Signature, not network path.** Every assertion is verified against the + JWKS. Even so, restrict direct access to WebAPI so the proxy is the only + way in. +- **Algorithm allow-list.** Only the configured asymmetric algorithms are + accepted. Symmetric (`HS*`) and `none` are refused when the configuration is + loaded and again when a token is verified. +- **`exp` is mandatory.** Spring's `JwtTimestampValidator` only checks `exp` + when it is present; this provider also requires it, so no assertion is + valid forever. +- **Outage is not sign-out.** If the JWKS can't be fetched, WebAPI answers + 503, not 401, so an identity-provider outage doesn't look like every user + being signed out. JWKS fetches time out after `jwks-timeout`. +- **Session binding.** Leave `enforce-on-every-request` on unless the proxy + can't add the assertion to every request. With it off, a WebAPI JWT stays + valid for its own lifetime regardless of the proxy session. +- **Provisioning.** With `auto-provision: true`, anyone the proxy lets + through gets a WebAPI account with default roles. Set it to `false` if the + proxy admits a wider population than should use Atlas. +- **User origin.** Users signed in this way are recorded with + `UserOrigin.ASSERTION`. The origin is stored as a string, so no database + migration is needed. + +--- + +## Testing + +`AssertionVerifierTest`, `AssertionLoginControllerTest` and +`AssertionBindingFilterTest` start a real local JWKS server, so the production +decoder, including its key fetch, is exercised. Run them with: + +```sh +./mvnw test -Dtest='Assertion*' +```