From c84bfc96a0a839e2d5c179c817a7ddae7846eb4c Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Mon, 9 Nov 2026 13:51:08 +0200 Subject: [PATCH 1/4] feat(security): log the Keycloak client of each token sign-in Every Bearer authentication already fires a success event (ProviderManager's DefaultAuthenticationEventPublisher), so each API request logs a login line at info with no way to tell the portal from the laptop client apart. A JwtAuthenticationToken now appends client= to that line; nothing about the token, sid or jti is logged. Portal sessions (OIDC login) log as before. The chain test now records success events and proves the premise: one event per Bearer request, carrying the subject and never the token value. --- .../AuthenticationEventListener.java | 14 +++++++++- .../AuthenticationEventListenerTest.java | 22 +++++++++++++++ .../TermsOfUseSecurityChainTest.java | 28 +++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java b/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java index 0e100e2e..47c36e15 100644 --- a/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java +++ b/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java @@ -5,6 +5,7 @@ import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; @@ -16,7 +17,10 @@ public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) { Authentication authentication = event.getAuthentication(); String username = authentication.getName(); Logger logger = new Logger(username, "LOGGING IN"); - logger.info("User " + username + " has logged in successfully from " + remoteAddress(authentication)); + // This event fires for every Bearer (and DPoP) request too, not only for portal sessions; the client + // tells the portal and the laptop client apart. Never the token, sid or jti. + logger.info("User " + username + " has logged in successfully from " + remoteAddress(authentication) + + clientSuffix(authentication)); // If you need to log additional details: authentication.getAuthorities().forEach(authority -> @@ -43,6 +47,14 @@ static boolean isExpiredToken(Exception exception) { return exception.getMessage() != null && exception.getMessage().contains("Jwt expired at"); } + static String clientSuffix(Authentication authentication) { + if (!(authentication instanceof JwtAuthenticationToken jwtAuthentication)) { + return ""; + } + String client = jwtAuthentication.getToken().getClaimAsString("azp"); + return " client=" + (client != null ? client : "none"); + } + private static String remoteAddress(Authentication authentication) { return authentication.getDetails() instanceof WebAuthenticationDetails details ? details.getRemoteAddress() diff --git a/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java b/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java index 384a3942..e6208426 100644 --- a/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java +++ b/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java @@ -2,7 +2,11 @@ import org.junit.jupiter.api.Test; import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; + +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -16,4 +20,22 @@ void onlyAnExpiredTokenCountsAsRoutine() { "An error occurred while attempting to decode the Jwt: Signed JWT rejected"))).isFalse(); assertThat(AuthenticationEventListener.isExpiredToken(new BadCredentialsException(null))).isFalse(); } + + @Test + void aBearerLoginLogsItsClientButNeverTheToken() { + Jwt token = Jwt.withTokenValue("token-value-never-log") + .header("alg", "RS256") + .claim("azp", "mip-cli-x") + .build(); + JwtAuthenticationToken authentication = new JwtAuthenticationToken(token, List.of()); + + assertThat(AuthenticationEventListener.clientSuffix(authentication)).isEqualTo(" client=mip-cli-x"); + } + + @Test + void aJwtWithoutAClientLogsNone() { + Jwt token = Jwt.withTokenValue("t").header("alg", "RS256").claim("sub", "alice").build(); + assertThat(AuthenticationEventListener.clientSuffix(new JwtAuthenticationToken(token, List.of()))) + .isEqualTo(" client=none"); + } } diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index c4076b65..4f4715d2 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -18,6 +18,7 @@ import org.springframework.context.annotation.Import; import org.springframework.context.event.EventListener; import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; +import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; @@ -144,6 +145,22 @@ void rejectedBearerTokenPublishesAFailureEventWithoutTheToken() throws Exception .doesNotContain("alice")); } + // B1's premise: every Bearer (and DPoP) authentication publishes a success event, so the per-request + // login log line with its client is produced for API clients too, and no operator decision is needed. + @Test + void everyBearerAuthenticationPublishesASuccessEvent() throws Exception { + storedUser("alice", true); + failures.successes.clear(); + + mvc.perform(withBearer(get("/services/experiments"), "alice")) + .andExpect(status().isOk()); + + assertThat(failures.successes).singleElement().satisfies(event -> { + assertThat(event.getAuthentication().getName()).isEqualTo("alice"); + assertThat(event.getAuthentication().getPrincipal()).isInstanceOf(Jwt.class); + }); + } + @Test void bearerTokenOfTheLaptopClientIsAccepted() throws Exception { storedUser("alice", true); @@ -348,6 +365,11 @@ private static MockHttpSession session(String username) { AuthConfigAPI.class, StandInAPI.class, FailureEvents.class}) static class Config { + @Bean + public AuthenticationEventListener authenticationEventListener() { + return new AuthenticationEventListener(); + } + @Bean UserRepository userRepository() { return mock(UserRepository.class); @@ -395,11 +417,17 @@ ClientRegistrationRepository clientRegistrationRepository() { static class FailureEvents { final List events = new ArrayList<>(); + final List successes = new ArrayList<>(); @EventListener void record(AbstractAuthenticationFailureEvent event) { events.add(event); } + + @EventListener + void recordSuccess(AuthenticationSuccessEvent event) { + successes.add(event); + } } @RestController From 8aa50dc819d1a40dfe6e6079faedf8ad64f6c0ba Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Mon, 9 Nov 2026 13:51:31 +0200 Subject: [PATCH 2/4] feat(security): optionally require DPoP for the laptop client With KEYCLOAK_CLI_REQUIRE_DPOP on, Spring's resource-server DPoP support handles "Authorization: DPoP " plus a DPoP proof header and verifies the proof (signature, htu/htm, iat, jti replay in an in-memory cache, and the token's cnf.jkt against the proof's key). A new validator refuses a laptop-client token without the cnf binding or one arriving over Bearer; platform-client tokens (portal, notebooks) keep working over Bearer. DPoP requests are exempt from CSRF like Bearer ones: an Authorization header is never cookie-authenticated. htu is the request URL, so nginx must pass X-Forwarded-Proto/Host for the backend location (platform-ui's nginx.conf.template does not yet); the native forward-headers strategy already reads them. The flag lets this ship before Keycloak and the mip client switch; remove it once every federation has. --- docs/context/session-management.md | 1 + .../configurations/SecurityConfiguration.java | 70 +++- src/main/resources/application.yml | 3 + .../configurations/DpopSecurityChainTest.java | 311 ++++++++++++++++++ .../KeycloakClientValidatorTest.java | 56 ++++ .../TermsOfUseSecurityChainTest.java | 13 + 6 files changed, 451 insertions(+), 3 deletions(-) create mode 100644 src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java diff --git a/docs/context/session-management.md b/docs/context/session-management.md index a4491fda..373dc9b8 100644 --- a/docs/context/session-management.md +++ b/docs/context/session-management.md @@ -34,6 +34,7 @@ Not limited. One account may hold several portal sessions, laptop sign-ins and a - The back-channel session registry is in memory: this works with one backend replica. - Any back-channel logout ends all of that user's portal sessions: Keycloak's user logout names only one session. - Set `KEYCLOAK_REQUIRED_AUDIENCE` once all of a federation's clients issue tokens naming it in `aud`. Empty means `aud` is not checked; `azp` always is. +- Turn on `KEYCLOAK_CLI_REQUIRE_DPOP` once a federation's Keycloak issues DPoP-bound tokens for `mip-cli-` and the mip client has switched: the laptop client's tokens must then be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `iat`, replay and the token's `cnf.jkt` against the proof's key). The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location. Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. ## Not available diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index b181f392..5f832a15 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -14,6 +14,7 @@ import org.springframework.security.authentication.DefaultAuthenticationEventPublisher; import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.GrantedAuthority; @@ -24,6 +25,7 @@ import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; @@ -43,6 +45,9 @@ import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.HandlerExceptionResolver; import java.net.URI; @@ -80,6 +85,15 @@ public class SecurityConfiguration { @Value("${authentication.session_max_age:8h}") private String sessionMaxAge; + // The public Keycloak client (device flow) of the mip client on users' own computers. + @Value("${authentication.cli_client_id:}") + private String cliClientId; + + // Require the laptop client's tokens to be DPoP-bound (RFC 9449). ponytail: remove the flag once + // every federation has switched its Keycloak and laptop clients over. + @Value("${authentication.cli_require_dpop:false}") + private boolean cliRequireDpop; + @Value("${server.port:8080}") private int serverPort; @@ -123,8 +137,18 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, // Allow API clients (e.g. notebooks) to authenticate with Bearer JWTs. // This runs alongside oauth2Login (session-based) authentication. - http.oauth2ResourceServer(oauth2 -> oauth2 - .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter(keycloakClientId)))); + http.oauth2ResourceServer(oauth2 -> { + oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter(keycloakClientId))); + if (cliRequireDpop) { + // Spring's DPoP filter takes "Authorization: DPoP " plus a DPoP proof header and + // verifies the proof: its signature, htm/htu against this request, iat, jti replay and + // the token's cnf.jkt against the proof's key. It reads request.getRequestURL(), which + // the native forward-headers strategy builds from X-Forwarded-Proto/Host, so nginx must + // send those for the backend location (platform-ui's nginx.conf.template does not yet). + // ponytail: Spring keeps proof replays in an in-memory jti cache, one backend replica. + oauth2.dPoP(Customizer.withDefaults()); + } + }); // Terms of use (NDA) apply to session and Bearer clients alike, not only to the portal UI. http.addFilterAfter(new TermsOfUseFilter(activeUserService, handlerExceptionResolver, PUBLIC_PATHS), @@ -165,7 +189,10 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, // Bearer-token clients should not need CSRF (they are not cookie-authenticated). .ignoringRequestMatchers((request) -> { String authz = request.getHeader("Authorization"); - return authz != null && authz.startsWith("Bearer "); + // Same prefix test Spring's DPoP filter uses, so no request that filter handles + // still gets 403 for CSRF. + return authz != null && (StringUtils.startsWithIgnoreCase(authz, "Bearer ") + || StringUtils.startsWithIgnoreCase(authz, "DPoP")); }) // Only this instance's own call: Spring's back-channel logout posts here without a token. .ignoringRequestMatchers(SecurityConfiguration::isLocalLogout)); @@ -258,6 +285,43 @@ OAuth2TokenValidator requiredAudienceValidator(@Value("${authentication.req return audienceValidator(audience); } + // The laptop client's tokens must be DPoP-bound: Spring's DPoP filter verifies the proof, and this + // validator refuses a laptop-client token without the binding or one that arrives over the Bearer + // scheme. Platform-client tokens (portal, notebooks) stay Bearer. Only meaningful together with the + // dPoP() configurer above, which the same flag turns on. + @Bean + OAuth2TokenValidator cliDpopValidator( + @Value("${authentication.cli_client_id:}") String cliClientId, + @Value("${authentication.cli_require_dpop:false}") boolean requireDpop) { + return dpopValidator(cliClientId, requireDpop); + } + + static OAuth2TokenValidator dpopValidator(String cliClientId, boolean requireDpop) { + return jwt -> !requireDpop || !StringUtils.hasText(cliClientId) + || !cliClientId.equals(jwt.getClaimAsString("azp")) + || (isDpopBound(jwt) && arrivedWithDpopScheme()) + ? OAuth2TokenValidatorResult.success() + : OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, + "The laptop client's token must be DPoP-bound and used with the DPoP scheme", null)); + } + + private static boolean isDpopBound(Jwt jwt) { + Object confirmation = jwt.getClaims().get("cnf"); + return confirmation instanceof Map claims && claims.get("jkt") != null; + } + + // The validators only see the JWT; the request tells Bearer and DPoP apart. Spring Boot registers its + // RequestContextFilter before the security chain, so the request is in scope here; without it (tests) + // this fails closed. + static boolean arrivedWithDpopScheme() { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + if (!(attributes instanceof ServletRequestAttributes servlet)) { + return false; + } + String authz = servlet.getRequest().getHeader("Authorization"); + return authz != null && StringUtils.startsWithIgnoreCase(authz, OAuth2AccessToken.TokenType.DPOP.getValue()); + } + static OAuth2TokenValidator audienceValidator(String audience) { return jwt -> !StringUtils.hasText(audience) || (jwt.getAudience() != null && jwt.getAudience().contains(audience)) ? OAuth2TokenValidatorResult.success() diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 409a6dfd..964a015d 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -65,6 +65,9 @@ authentication: cli_client_id: ${KEYCLOAK_CLI_CLIENT_ID:} # When set, Bearer tokens must also name this in aud; set it once every client's tokens do. required_audience: ${KEYCLOAK_REQUIRED_AUDIENCE:} + # Require the laptop client's tokens to be DPoP-bound (RFC 9449) and used with the DPoP scheme. + # Turn on once Keycloak and the mip client have switched; remove once every federation has. + cli_require_dpop: ${KEYCLOAK_CLI_REQUIRE_DPOP:false} # Portal sessions end at this age however active they are (8h or PT8H). session_max_age: ${SESSION_MAX_AGE:8h} diff --git a/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java b/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java new file mode 100644 index 00000000..23ba8c73 --- /dev/null +++ b/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java @@ -0,0 +1,311 @@ +package hbp.mip.configurations; + +import com.nimbusds.jose.JOSEObjectType; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import hbp.mip.user.ActiveUserAPI; +import hbp.mip.user.ActiveUserService; +import hbp.mip.user.AuthConfigAPI; +import hbp.mip.user.UserDAO; +import hbp.mip.user.UserRepository; +import hbp.mip.utils.ControllerExceptionHandler; +import jakarta.servlet.Filter; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidator; +import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtValidationException; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * The laptop client over the DPoP scheme (RFC 9449) through the real SecurityConfiguration filter chain with + * {@code authentication.cli_require_dpop=1}. The DPoP proof is signed here with a throwaway RSA key; the + * access token's {@code cnf.jkt} claim carries that key's thumbprint, as Keycloak would set it. A Bearer + * token's value is {@code [.[.[.[.]]]]}}. + */ +@SpringJUnitWebConfig(DpopSecurityChainTest.Config.class) +@TestPropertySource(properties = {"authentication.enabled=1", "authentication.cli_client_id=mip-cli", + "authentication.cli_require_dpop=true", "authentication.session_max_age=8h", + "spring.security.oauth2.client.registration.keycloak.client-id=client", + "spring.security.oauth2.resourceserver.jwt.issuer-uri=https://idp.example.org/realms/MIP"}) +class DpopSecurityChainTest { + + // The proof is signed with a throwaway key; the access token names its thumbprint in cnf.jkt. + private static final RSAKey PROOF_JWK = proofKey(); + private static final String THUMBPRINT = thumbprint(PROOF_JWK); + + private static String thumbprint(RSAKey key) { + try { + return key.computeThumbprint().toString(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static RSAKey proofKey() { + try { + KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); + rsa.initialize(2048); + KeyPair keyPair = rsa.generateKeyPair(); + return new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()) + .privateKey((RSAPrivateKey) keyPair.getPrivate()) + .build(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + @Autowired + private WebApplicationContext context; + + @Autowired + private UserRepository userRepository; + + private MockMvc mvc; + + @BeforeEach + void setUp() { + reset(userRepository); + mvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(context.getBean("springSecurityFilterChain", Filter.class)) + .build(); + } + + @AfterEach + void forgetTheRequest() { + RequestContextHolder.resetRequestAttributes(); + } + + @Test + void aDpopBoundLaptopTokenOverTheDpopSchemeIsNotBlockedByCsrfAndGetsThrough() throws Exception { + storedUser("alice", true); + + mvc.perform(withDpop(post("/services/experiments"), laptopToken("alice"))) + .andExpect(status().isOk()) + .andExpect(content().string("experiments")); + } + + @Test + void theSameProofIsAReplay() throws Exception { + storedUser("alice", true); + + String proof = proof(laptopToken("alice")); + MockHttpServletRequestBuilder request = post("/services/experiments").contextPath("/services") + .header("Authorization", "DPoP " + laptopToken("alice")) + .header("DPoP", proof) + .with(inRequestScope()); + + assertThat(mvc.perform(request).andReturn().getResponse().getStatus()).isEqualTo(200); + assertThat(mvc.perform(request).andReturn().getResponse().getStatus()).isEqualTo(401); + } + + @Test + void aDpopBoundLaptopTokenIsRefusedOverBearer() throws Exception { + storedUser("alice", true); + + mvc.perform(withBearer(get("/services/experiments"), laptopToken("alice"))) + .andExpect(status().isUnauthorized()); + } + + @Test + void aLaptopTokenWithoutTheBindingIsRefused() throws Exception { + storedUser("alice", true); + String unbound = laptopToken("alice").replace("." + THUMBPRINT, ""); + + assertThat(mvc.perform(withBearer(get("/services/experiments"), unbound)) + .andReturn().getResponse().getStatus()).isEqualTo(401); + assertThat(mvc.perform(withDpop(post("/services/experiments"), unbound)) + .andReturn().getResponse().getStatus()).isEqualTo(401); + } + + @Test + void aPlatformTokenOverBearerIsUnaffected() throws Exception { + storedUser("alice", true); + + mvc.perform(withBearer(get("/services/experiments"), "alice")) + .andExpect(status().isOk()); + } + + // The proof's htu is the request URL as the backend sees it; MockMvc serves http://localhost/services. + private static String proof(String accessToken) { + try { + SignedJWT proof = new SignedJWT( + new JWSHeader.Builder(JWSAlgorithm.RS256) + .type(new JOSEObjectType("dpop+jwt")) + .jwk(PROOF_JWK.toPublicJWK()) + .build(), + new JWTClaimsSet.Builder() + .claim("htm", "POST") + .claim("htu", "http://localhost/services/experiments") + .claim("iat", Instant.now().getEpochSecond()) + .claim("jti", UUID.randomUUID().toString()) + .claim("ath", sha256UrlSafe(accessToken)) + .build()); + try { + proof.sign(new RSASSASigner(PROOF_JWK)); + } catch (com.nimbusds.jose.JOSEException e) { + throw new IllegalStateException(e); + } + return proof.serialize(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String sha256UrlSafe(String value) { + try { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String laptopToken(String username) { + return username + ".mip-cli.Bearer." + username + "." + THUMBPRINT; + } + + private MockHttpServletRequestBuilder withDpop(MockHttpServletRequestBuilder request, String token) { + return request.contextPath("/services") + .header("Authorization", "DPoP " + token) + .header("DPoP", proof(token)) + // The validators read the request from RequestContextHolder, which only the real + // RequestContextFilter would set; MockMvc does not. + .with(inRequestScope()); + } + + private MockHttpServletRequestBuilder withBearer(MockHttpServletRequestBuilder request, String username) { + return request.contextPath("/services").header("Authorization", "Bearer " + username); + } + + private static RequestPostProcessor inRequestScope() { + return request -> { + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + return request; + }; + } + + private void storedUser(String username, boolean agreeNDA) { + UserDAO user = new UserDAO(username, username, username + "@example.org", username); + user.setAgreeNDA(agreeNDA); + when(userRepository.findByUsername(username)).thenReturn(user); + } + + @Configuration + @EnableWebMvc + @Import({SecurityConfiguration.class, SpaRedirectAuthenticationSuccessHandler.class, + FrontendRedirectCaptureFilter.class, ControllerExceptionHandler.class, ActiveUserAPI.class, + AuthConfigAPI.class, StandInAPI.class}) + static class Config { + + @Bean + UserRepository userRepository() { + return mock(UserRepository.class); + } + + @Bean + ActiveUserService activeUserService(UserRepository userRepository) { + return new ActiveUserService(userRepository); + } + + // Applies every OAuth2TokenValidator bean, as Spring Boot's issuer-uri JwtDecoder does. + @Bean + JwtDecoder jwtDecoder(ObjectProvider> validators) { + OAuth2TokenValidator validator = new DelegatingOAuth2TokenValidator<>(validators.orderedStream().toList()); + return token -> { + String[] parts = token.split("\\."); + Jwt.Builder builder = Jwt.withTokenValue(token) + .header("alg", "none") + .subject(parts.length > 3 ? parts[3] : parts[0]) + .claim("preferred_username", parts[0]) + .claim("azp", parts.length > 1 ? parts[1] : "client") + .claim("typ", parts.length > 2 ? parts[2] : "Bearer") + .issuedAt(Instant.now()) + .expiresAt(Instant.now().plusSeconds(300)); + if (parts.length > 4) { + builder.claim("cnf", Map.of("jkt", parts[4])); + } + Jwt jwt = builder.build(); + OAuth2TokenValidatorResult result = validator.validate(jwt); + if (result.hasErrors()) { + throw new JwtValidationException("invalid token", result.getErrors()); + } + return jwt; + }; + } + + @Bean + ClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryClientRegistrationRepository(ClientRegistration.withRegistrationId("keycloak") + .clientId("client") + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .authorizationUri("https://idp.example.org/auth") + .tokenUri("https://idp.example.org/token") + .build()); + } + } + + @RestController + static class StandInAPI { + @GetMapping("/experiments") + String experiments() { + return "experiments"; + } + + @PostMapping("/experiments") + String runExperiments() { + return "experiments"; + } + } +} diff --git a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java index 04ddf8e0..abcc3797 100644 --- a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java +++ b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java @@ -1,8 +1,13 @@ package hbp.mip.configurations; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import java.util.List; import java.util.Map; @@ -64,4 +69,55 @@ void requiredAudienceIsCheckedOnlyWhenSet() { void rejectsEverythingWithoutAClientId() { assertThat(SecurityConfiguration.clientValidator("", "").validate(token(Map.of("azp", ""))).hasErrors()).isTrue(); } + + // The validator only sees the JWT; the request tells Bearer and DPoP apart. + @AfterEach + void forgetTheRequest() { + RequestContextHolder.resetRequestAttributes(); + } + + private static void requestArrivedWith(String scheme) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("Authorization", scheme + " the-token"); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + } + + @Test + void whenRequiredEveryLaptopTokenMustBeDpopBoundAndArriveWithTheDpopScheme() { + OAuth2TokenValidator validator = SecurityConfiguration.dpopValidator("mip-cli", true); + + assertThat(validator.validate(token(Map.of("azp", "mip-cli"))).hasErrors()).isTrue(); + assertThat(validator.validate(token(Map.of("azp", "mip-cli", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isTrue(); + + requestArrivedWith("DPoP"); + assertThat(validator.validate(token(Map.of("azp", "mip-cli"))).hasErrors()).isTrue(); + assertThat(validator.validate(token(Map.of("azp", "mip-cli", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isFalse(); + } + + @Test + void platformTokensKeepWorkingOverBearerWhenDpopIsRequired() { + OAuth2TokenValidator validator = SecurityConfiguration.dpopValidator("mip-cli", true); + + assertThat(validator.validate(token(Map.of("azp", "mippublic", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isFalse(); + assertThat(validator.validate(token(Map.of("azp", "mippublic"))).hasErrors()).isFalse(); + } + + @Test + void withoutTheFlagOrTheLaptopClientTheValidatorAdmitsEverything() { + assertThat(SecurityConfiguration.dpopValidator("mip-cli", false) + .validate(token(Map.of("azp", "mip-cli"))).hasErrors()).isFalse(); + assertThat(SecurityConfiguration.dpopValidator("", true) + .validate(token(Map.of("azp", "mip-cli"))).hasErrors()).isFalse(); + } + + @Test + void withoutARequestScopeTheValidatorFailsClosed() { + OAuth2TokenValidator validator = SecurityConfiguration.dpopValidator("mip-cli", true); + + assertThat(validator.validate(token(Map.of("azp", "mip-cli", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isTrue(); + } } diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 4f4715d2..14ba2e25 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -161,6 +161,19 @@ void everyBearerAuthenticationPublishesASuccessEvent() throws Exception { }); } + // A DPoP-scheme request carries an Authorization header, so it is never cookie-authenticated and needs + // no CSRF token; without this exemption Spring would 403 every DPoP POST. + @Test + void aDpopSchemePostIsExemptFromCsrf() throws Exception { + int status = mvc.perform(post("/services/experiments").contextPath("/services") + .header("Authorization", "DPoP some-token")) + .andReturn().getResponse().getStatus(); + + // The DPoP filter itself is off while cli_require_dpop is, so this stays unauthenticated (302 or + // 401, as for any unauthenticated request); what matters is that it is not 403 CSRF. + assertThat(status).isIn(302, 401); + } + @Test void bearerTokenOfTheLaptopClientIsAccepted() throws Exception { storedUser("alice", true); From c00c5f328f376eed8264d17525b37e744feaa5ce Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Mon, 9 Nov 2026 14:15:13 +0200 Subject: [PATCH 3/4] fix(security): accept DPoP-typed tokens and note the DPoP turn-on order Review follow-ups on PR #53: - Drop the unused authentication.cli_client_id field; both validator beans take the value as a parameter. - accessTokenValidator now also accepts typ "DPoP" when the token carries cnf.jkt: Keycloak may name DPoP-bound access tokens that way (RFC 9449), and the binding claim is what keeps an ID token out. Still refuses typ "ID" and unbound DPoP-typed tokens, with tests. - Document the DPoP turn-on order (Keycloak, flag and client release in one change window) and that the proof replay cache is per backend replica. --- docs/context/session-management.md | 4 +++- .../configurations/SecurityConfiguration.java | 22 ++++++++++--------- .../KeycloakClientValidatorTest.java | 13 +++++++++++ 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/docs/context/session-management.md b/docs/context/session-management.md index 373dc9b8..4a678664 100644 --- a/docs/context/session-management.md +++ b/docs/context/session-management.md @@ -34,7 +34,9 @@ Not limited. One account may hold several portal sessions, laptop sign-ins and a - The back-channel session registry is in memory: this works with one backend replica. - Any back-channel logout ends all of that user's portal sessions: Keycloak's user logout names only one session. - Set `KEYCLOAK_REQUIRED_AUDIENCE` once all of a federation's clients issue tokens naming it in `aud`. Empty means `aud` is not checked; `azp` always is. -- Turn on `KEYCLOAK_CLI_REQUIRE_DPOP` once a federation's Keycloak issues DPoP-bound tokens for `mip-cli-` and the mip client has switched: the laptop client's tokens must then be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `iat`, replay and the token's `cnf.jkt` against the proof's key). The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location. Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. +- DPoP for the laptop client: with `KEYCLOAK_CLI_REQUIRE_DPOP` on, the laptop client's (`mip-cli-`) tokens must be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `iat`, replay and the token's `cnf.jkt` against the proof's key). Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location. +- Turn-on order: while the flag is off, a DPoP-bound token sent with `Bearer` is accepted without a proof (the binding is not enforced). With the flag on before clients send DPoP, every laptop user fails. Turn on Keycloak DPoP for the laptop client, this flag, and a DPoP-capable mip client release in one change window. +- The proof replay check keeps recent `jti` values in memory, per backend replica: with more than one replica, a proof can be replayed on another replica within the short `iat` window (it stays bound to one method and URL). Acceptable for now; use a shared cache if it matters later. ## Not available diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index 5f832a15..d8e4ff61 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -85,12 +85,8 @@ public class SecurityConfiguration { @Value("${authentication.session_max_age:8h}") private String sessionMaxAge; - // The public Keycloak client (device flow) of the mip client on users' own computers. - @Value("${authentication.cli_client_id:}") - private String cliClientId; - - // Require the laptop client's tokens to be DPoP-bound (RFC 9449). ponytail: remove the flag once - // every federation has switched its Keycloak and laptop clients over. + // The public Keycloak client (device flow) of the mip client on users' own computers is named by the + // validator beans below; the chain itself only needs the DPoP flag. @Value("${authentication.cli_require_dpop:false}") private boolean cliRequireDpop; @@ -330,12 +326,18 @@ static OAuth2TokenValidator audienceValidator(String audience) { } // Keycloak signs ID tokens with the same key and the same azp, so only its typ claim tells them from access tokens. + // DPoP-bound access tokens may carry typ "DPoP" instead of "Bearer" (RFC 9449); then cnf.jkt must be + // present, which is what makes such a token a bound access token and not an ID token. Keycloak's exact + // typ for DPoP tokens is still to be confirmed on a DPoP-enabled realm. @Bean OAuth2TokenValidator accessTokenValidator() { - return jwt -> "Bearer".equals(jwt.getClaimAsString("typ")) - ? OAuth2TokenValidatorResult.success() - : OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, - "The token is not an access token", null)); + return jwt -> { + String typ = jwt.getClaimAsString("typ"); + return "Bearer".equals(typ) || ("DPoP".equals(typ) && isDpopBound(jwt)) + ? OAuth2TokenValidatorResult.success() + : OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, + "The token is not an access token", null)); + }; } static JwtAuthenticationConverter jwtAuthenticationConverter(String clientId) { diff --git a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java index abcc3797..0c45dc16 100644 --- a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java +++ b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java @@ -55,6 +55,19 @@ void acceptsOnlyAccessTokens() { assertThat(accessTokens.validate(token(Map.of())).hasErrors()).isTrue(); } + @Test + void aDpopTypedTokenCountsAsAccessTokenOnlyWhenItIsDpopBound() { + OAuth2TokenValidator accessTokens = new SecurityConfiguration(null, null, null, null).accessTokenValidator(); + + // Keycloak may name DPoP-bound access tokens typ "DPoP"; the binding claim is what proves it. + assertThat(accessTokens.validate(token(Map.of("typ", "DPoP", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isFalse(); + assertThat(accessTokens.validate(token(Map.of("typ", "DPoP"))).hasErrors()).isTrue(); + // A DPoP-typed token is never an ID token, whatever its claims say. + assertThat(accessTokens.validate(token(Map.of("typ", "ID", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isTrue(); + } + @Test void requiredAudienceIsCheckedOnlyWhenSet() { OAuth2TokenValidator required = SecurityConfiguration.audienceValidator("mippublic"); From 83ef8cf2bc4c8f8b05f121fbec57979eda6557c6 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Mon, 9 Nov 2026 16:48:09 +0200 Subject: [PATCH 4/4] fix(security): address PR #53 review findings - The Bearer refusal is now tested with the request actually in scope: the unit test sets an Authorization: Bearer header on a bound laptop token and the chain test puts its Bearer request into RequestContextHolder, so the tests exercise the scheme check, not the fail-closed fallback. - The CSRF exemption is scheme-plus-space for both schemes ("DPoP " like "Bearer "), so a header that names no token stays CSRF-protected; tested. - The chain test gains the two turn-on footguns: a proof naming another URL (missing nginx forwarded headers) and a DPoP request without a proof are both 401. - The session doc names ath (SHA-256 of the access token) among the proof claims Spring requires, so a client without it can be diagnosed. --- docs/context/session-management.md | 2 +- .../configurations/SecurityConfiguration.java | 6 ++-- .../configurations/DpopSecurityChainTest.java | 36 +++++++++++++++++-- .../KeycloakClientValidatorTest.java | 5 +++ .../TermsOfUseSecurityChainTest.java | 7 ++++ 5 files changed, 50 insertions(+), 6 deletions(-) diff --git a/docs/context/session-management.md b/docs/context/session-management.md index 4a678664..f4f069e3 100644 --- a/docs/context/session-management.md +++ b/docs/context/session-management.md @@ -34,7 +34,7 @@ Not limited. One account may hold several portal sessions, laptop sign-ins and a - The back-channel session registry is in memory: this works with one backend replica. - Any back-channel logout ends all of that user's portal sessions: Keycloak's user logout names only one session. - Set `KEYCLOAK_REQUIRED_AUDIENCE` once all of a federation's clients issue tokens naming it in `aud`. Empty means `aud` is not checked; `azp` always is. -- DPoP for the laptop client: with `KEYCLOAK_CLI_REQUIRE_DPOP` on, the laptop client's (`mip-cli-`) tokens must be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `iat`, replay and the token's `cnf.jkt` against the proof's key). Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location. +- DPoP for the laptop client: with `KEYCLOAK_CLI_REQUIRE_DPOP` on, the laptop client's (`mip-cli-`) tokens must be DPoP-bound (RFC 9449) and arrive with the `DPoP` scheme, and Spring verifies the DPoP proof (signature, `htu`/`htm`, `ath` — the SHA-256 of the access token, `iat`, replay and the token's `cnf.jkt` against the proof's key). Platform-client tokens (portal, notebooks) keep working over `Bearer`; remove the flag once every federation has switched. The proof's `htu` is the request URL, so nginx must pass `X-Forwarded-Proto`/`X-Forwarded-Host` for the backend location. - Turn-on order: while the flag is off, a DPoP-bound token sent with `Bearer` is accepted without a proof (the binding is not enforced). With the flag on before clients send DPoP, every laptop user fails. Turn on Keycloak DPoP for the laptop client, this flag, and a DPoP-capable mip client release in one change window. - The proof replay check keeps recent `jti` values in memory, per backend replica: with more than one replica, a proof can be replayed on another replica within the short `iat` window (it stays bound to one method and URL). Acceptable for now; use a shared cache if it matters later. diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index d8e4ff61..6393253a 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -185,10 +185,10 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, // Bearer-token clients should not need CSRF (they are not cookie-authenticated). .ignoringRequestMatchers((request) -> { String authz = request.getHeader("Authorization"); - // Same prefix test Spring's DPoP filter uses, so no request that filter handles - // still gets 403 for CSRF. + // Same scheme-plus-space test for both: the request must actually carry a token, + // and one with an Authorization header is never cookie-authenticated. return authz != null && (StringUtils.startsWithIgnoreCase(authz, "Bearer ") - || StringUtils.startsWithIgnoreCase(authz, "DPoP")); + || StringUtils.startsWithIgnoreCase(authz, "DPoP ")); }) // Only this instance's own call: Spring's back-channel logout posts here without a token. .ignoringRequestMatchers(SecurityConfiguration::isLocalLogout)); diff --git a/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java b/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java index 23ba8c73..b9aa14fa 100644 --- a/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/DpopSecurityChainTest.java @@ -152,7 +152,8 @@ void theSameProofIsAReplay() throws Exception { void aDpopBoundLaptopTokenIsRefusedOverBearer() throws Exception { storedUser("alice", true); - mvc.perform(withBearer(get("/services/experiments"), laptopToken("alice"))) + // In request scope, so the refusal tests the Bearer scheme, not the missing request scope. + mvc.perform(withBearer(get("/services/experiments"), laptopToken("alice")).with(inRequestScope())) .andExpect(status().isUnauthorized()); } @@ -175,8 +176,39 @@ void aPlatformTokenOverBearerIsUnaffected() throws Exception { .andExpect(status().isOk()); } + @Test + void aProofForAnotherUrlIsRefused() throws Exception { + storedUser("alice", true); + String token = laptopToken("alice"); + + // What a request looks like when nginx does not pass X-Forwarded-Proto/Host: the proof names the + // public https URL, but the backend still sees its own http one. + String proofForPublicUrl = proof(token, "https://portal.example.org/services/experiments"); + int status = mvc.perform(post("/services/experiments").contextPath("/services") + .header("Authorization", "DPoP " + token) + .header("DPoP", proofForPublicUrl) + .with(inRequestScope())) + .andReturn().getResponse().getStatus(); + + assertThat(status).isEqualTo(401); + } + + @Test + void aDpopRequestWithoutAProofIsRefused() throws Exception { + storedUser("alice", true); + + mvc.perform(post("/services/experiments").contextPath("/services") + .header("Authorization", "DPoP " + laptopToken("alice")) + .with(inRequestScope())) + .andExpect(status().isUnauthorized()); + } + // The proof's htu is the request URL as the backend sees it; MockMvc serves http://localhost/services. private static String proof(String accessToken) { + return proof(accessToken, "http://localhost/services/experiments"); + } + + private static String proof(String accessToken, String htu) { try { SignedJWT proof = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256) @@ -185,7 +217,7 @@ private static String proof(String accessToken) { .build(), new JWTClaimsSet.Builder() .claim("htm", "POST") - .claim("htu", "http://localhost/services/experiments") + .claim("htu", htu) .claim("iat", Instant.now().getEpochSecond()) .claim("jti", UUID.randomUUID().toString()) .claim("ath", sha256UrlSafe(accessToken)) diff --git a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java index 0c45dc16..663a2b43 100644 --- a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java +++ b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java @@ -107,6 +107,11 @@ void whenRequiredEveryLaptopTokenMustBeDpopBoundAndArriveWithTheDpopScheme() { assertThat(validator.validate(token(Map.of("azp", "mip-cli"))).hasErrors()).isTrue(); assertThat(validator.validate(token(Map.of("azp", "mip-cli", "cnf", Map.of("jkt", "thumbprint")))) .hasErrors()).isFalse(); + + // The Bearer scheme must be told apart from DPoP by the request, not by "any Authorization header". + requestArrivedWith("Bearer"); + assertThat(validator.validate(token(Map.of("azp", "mip-cli", "cnf", Map.of("jkt", "thumbprint")))) + .hasErrors()).isTrue(); } @Test diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 14ba2e25..a29528ac 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -174,6 +174,13 @@ void aDpopSchemePostIsExemptFromCsrf() throws Exception { assertThat(status).isIn(302, 401); } + @Test + void aDpopSchemeWithoutATokenIsNotExemptFromCsrf() throws Exception { + // The exemption is scheme-plus-space, like Bearer: a header that names no token gets no exemption. + mvc.perform(post("/services/experiments").contextPath("/services").header("Authorization", "DPoP")) + .andExpect(status().isForbidden()); + } + @Test void bearerTokenOfTheLaptopClientIsAccepted() throws Exception { storedUser("alice", true);