From 182ece248a8cec09435691d6242beba3f4ca93f0 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:30 +0200 Subject: [PATCH 01/14] fix(security)!: accept only access tokens as Bearer tokens Keycloak signs ID tokens with the same key and the same azp as access tokens, so an ID token passed the Bearer checks. Require its typ claim to be Bearer (ASVS 5 9.2.2). KEYCLOAK_REQUIRED_AUDIENCE, off by default, also requires aud. BREAKING CHANGE: tokens without typ=Bearer are rejected with 401. --- .../configurations/SecurityConfiguration.java | 22 +++++++++++++++++++ src/main/resources/application.yml | 2 ++ .../KeycloakClientValidatorTest.java | 19 ++++++++++++++++ .../TermsOfUseSecurityChainTest.java | 12 +++++++++- 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index f6d5bc58..6195eaa1 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -160,6 +160,28 @@ static OAuth2TokenValidator clientValidator(String... clientIds) { "The token was not issued for this MIP platform", null)); } + // Optional, because not every federation's tokens name this service in aud yet: set it once they do. + @Bean + OAuth2TokenValidator requiredAudienceValidator(@Value("${authentication.required_audience:}") String audience) { + return audienceValidator(audience); + } + + static OAuth2TokenValidator audienceValidator(String audience) { + return jwt -> !StringUtils.hasText(audience) || (jwt.getAudience() != null && jwt.getAudience().contains(audience)) + ? OAuth2TokenValidatorResult.success() + : OAuth2TokenValidatorResult.failure(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, + "The token is not meant for this MIP platform", null)); + } + + // Keycloak signs ID tokens with the same key and the same azp, so only its typ claim tells them from access tokens. + @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)); + } + static JwtAuthenticationConverter jwtAuthenticationConverter(String clientId) { JwtGrantedAuthoritiesConverter fallback = new JwtGrantedAuthoritiesConverter(); // Do not force ROLE_ prefix; the app expects raw authority strings (e.g. research_dataset_*). diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3bc75110..a9ef68e3 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -52,6 +52,8 @@ authentication: dataset_claim_prefix: research_dataset_ # Public Keycloak client (device flow) for `mip login` on users' own computers; empty = not offered. 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:} ### EXTERNAL SERVICES ### services: diff --git a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java index c86c3d82..04ddf8e0 100644 --- a/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java +++ b/src/test/java/hbp/mip/configurations/KeycloakClientValidatorTest.java @@ -41,6 +41,25 @@ void anUnsetLaptopClientAdmitsNothingExtra() { assertThat(platformOnly.validate(token(Map.of("azp", ""))).hasErrors()).isTrue(); } + @Test + void acceptsOnlyAccessTokens() { + OAuth2TokenValidator accessTokens = new SecurityConfiguration(null, null, null, null).accessTokenValidator(); + assertThat(accessTokens.validate(token(Map.of("typ", "Bearer"))).hasErrors()).isFalse(); + assertThat(accessTokens.validate(token(Map.of("typ", "ID"))).hasErrors()).isTrue(); + assertThat(accessTokens.validate(token(Map.of("typ", "Refresh"))).hasErrors()).isTrue(); + assertThat(accessTokens.validate(token(Map.of())).hasErrors()).isTrue(); + } + + @Test + void requiredAudienceIsCheckedOnlyWhenSet() { + OAuth2TokenValidator required = SecurityConfiguration.audienceValidator("mippublic"); + assertThat(required.validate(token(Map.of("aud", List.of("account", "mippublic")))).hasErrors()).isFalse(); + assertThat(required.validate(token(Map.of("aud", List.of("account")))).hasErrors()).isTrue(); + assertThat(required.validate(token(Map.of())).hasErrors()).isTrue(); + + assertThat(SecurityConfiguration.audienceValidator("").validate(token(Map.of())).hasErrors()).isFalse(); + } + @Test void rejectsEverythingWithoutAClientId() { assertThat(SecurityConfiguration.clientValidator("", "").validate(token(Map.of("azp", ""))).hasErrors()).isTrue(); diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 84fd8ac2..2eac7785 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -67,7 +67,8 @@ * The terms-of-use gate through the real SecurityConfiguration filter chain, so moving the filter to a point * where the session or Bearer authentication is not yet known fails here. The real ActiveUserAPI and * ControllerExceptionHandler render the responses; /experiments is a stand-in. No datasource, Keycloak or - * Exaflow. A Bearer token's value is {@code [.]}; azp defaults to the platform client. + * Exaflow. A Bearer token's value is {@code [.[.[.]]]}; azp defaults to the platform + * client, typ to Bearer and sub to the username. */ @SpringJUnitWebConfig(TermsOfUseSecurityChainTest.Config.class) @TestPropertySource(properties = {"authentication.enabled=1", "authentication.cli_client_id=mip-cli", @@ -129,6 +130,14 @@ void bearerTokenOfTheLaptopClientIsAccepted() throws Exception { .andExpect(status().isOk()); } + @Test + void idTokenOfThisFederationIsRejectedAsBearerToken() throws Exception { + storedUser("alice", true); + + mvc.perform(withBearer(get("/services/experiments"), "alice.client.ID")) + .andExpect(status().isUnauthorized()); + } + @Test void bearerClientCannotAcceptTheTerms() throws Exception { storedUser("alice", false); @@ -246,6 +255,7 @@ JwtDecoder jwtDecoder(ObjectProvider> validators) { .subject(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)) .build(); From 6b62f525c9d031f2258b73e51f987e000757ee86 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:30 +0200 Subject: [PATCH 02/14] fix(user)!: remove the endpoint that returned access tokens GET /activeUser/token handed the session's access token to browser JavaScript, which undoes the session cookie's HttpOnly. Nothing in platform-ui, mip-jupyter or the deployment repository calls it. BREAKING CHANGE: GET /activeUser/token now answers 404. --- docs/context/module-index.md | 2 +- docs/context/risk-register.md | 1 - src/main/java/hbp/mip/user/ActiveUserAPI.java | 39 +------------------ .../TermsOfUseSecurityChainTest.java | 13 ++----- 4 files changed, 5 insertions(+), 50 deletions(-) diff --git a/docs/context/module-index.md b/docs/context/module-index.md index e10aae65..4c1fe38c 100644 --- a/docs/context/module-index.md +++ b/docs/context/module-index.md @@ -115,7 +115,7 @@ Purpose: Active user resolution, persistence, and NDA state. Key files: `ActiveUserAPI.java`, `ActiveUserService.java`, `UserRepository.java`, `UserDAO.java`, `UserDTO.java`. -Used by: Controllers needing user context and endpoints exposing active user/token behavior. +Used by: Controllers needing user context and the endpoints exposing the active user. Rules: Treat token exposure and user identity mapping as security-sensitive. diff --git a/docs/context/risk-register.md b/docs/context/risk-register.md index 685b69e0..3ac399fc 100644 --- a/docs/context/risk-register.md +++ b/docs/context/risk-register.md @@ -4,7 +4,6 @@ |---|---|---|---|---| | Authentication and OAuth2 | Login, logout, JWT, CSRF, and session behavior can lock users out or weaken protection | `SecurityConfiguration.java`, `SpaRedirectAuthenticationSuccessHandler.java`, `FrontendRedirectCaptureFilter.java` | Add focused tests and manually review auth flows before changing | Yes | | Authority and claim mapping | Dataset/experiment access depends on raw authority strings and Keycloak claims | `SecurityConfiguration.java`, `ClaimUtils.java` | Do not add `ROLE_` prefixes or rename claims without migration/compat notes | Yes | -| Active user token endpoint | `/activeUser/token` can expose access tokens to authenticated callers | `ActiveUserAPI.java` | Do not broaden access, log token values, or change response semantics without review | Yes | | Dataset authorization | Users may see unauthorized pathologies or datasets if filtering changes | `DataModelService.java`, `ClaimUtils.java` | Cover authenticated and authentication-disabled behavior | Yes | | Experiment authorization | Owners/shared/admin-like access rules protect experiment read/update/delete | `ExperimentService.java`, `ExperimentSpecifications.java` | Test owner, shared, not-owner, and all-experiments authority cases | Yes | | Experiment deletion | Deletion is destructive and authorization-sensitive | `ExperimentAPI.java`, `ExperimentService.java` | Require focused tests and rollback/restore discussion for behavior changes | Yes | diff --git a/src/main/java/hbp/mip/user/ActiveUserAPI.java b/src/main/java/hbp/mip/user/ActiveUserAPI.java index bc0c2466..832cc5a9 100644 --- a/src/main/java/hbp/mip/user/ActiveUserAPI.java +++ b/src/main/java/hbp/mip/user/ActiveUserAPI.java @@ -3,12 +3,7 @@ import hbp.mip.utils.Logger; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; -import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; -import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.*; -import org.springframework.util.StringUtils; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @@ -17,11 +12,9 @@ public class ActiveUserAPI { private final ActiveUserService activeUserService; - private final OAuth2AuthorizedClientService authorizedClientService; - public ActiveUserAPI(ActiveUserService activeUserService, OAuth2AuthorizedClientService authorizedClientService) { + public ActiveUserAPI(ActiveUserService activeUserService) { this.activeUserService = activeUserService; - this.authorizedClientService = authorizedClientService; } @GetMapping @@ -39,34 +32,4 @@ public ResponseEntity activeUserServiceAgreesToNDA(Authentication authe logger.info("User agreed to the NDA."); return ResponseEntity.ok(user); } - - @GetMapping(value = "/token") - public ResponseEntity getActiveUserToken(Authentication authentication) { - if (authentication == null) { - Logger logger = new Logger("anonymous", "(GET) /activeUser/token"); - logger.warn("Authentication is missing."); - return ResponseEntity.status(401).body("Unauthorized"); - } - - // Bearer-token flow: JWT presented directly to this API. - if (authentication instanceof JwtAuthenticationToken jwtAuth) { - return ResponseEntity.ok(jwtAuth.getToken().getTokenValue()); - } - - // Browser session flow: return OAuth2 access token from authorized client. - if (authentication instanceof OAuth2AuthenticationToken oauth2Auth) { - OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient( - oauth2Auth.getAuthorizedClientRegistrationId(), - oauth2Auth.getName() - ); - if (client != null && client.getAccessToken() != null - && StringUtils.hasText(client.getAccessToken().getTokenValue())) { - return ResponseEntity.ok(client.getAccessToken().getTokenValue()); - } - } - - Logger logger = new Logger("unknown", "(GET) /activeUser/token"); - logger.warn("Could not extract access token from authentication object: " + authentication.getClass().getName()); - return ResponseEntity.status(404).body("Token not found"); - } } diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 2eac7785..481a4996 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -17,8 +17,6 @@ import org.springframework.context.annotation.Import; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.core.context.SecurityContextImpl; -import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; @@ -149,11 +147,11 @@ void bearerClientCannotAcceptTheTerms() throws Exception { } @Test - void tokenEndpointIsBlockedUntilTheTermsAreAccepted() throws Exception { - storedUser("alice", false); + void tokenEndpointNoLongerExists() throws Exception { + storedUser("alice", true); mvc.perform(withBearer(get("/services/activeUser/token"), "alice")) - .andExpect(status().isForbidden()); + .andExpect(status().isNotFound()); } @Test @@ -239,11 +237,6 @@ ActiveUserService activeUserService(UserRepository userRepository) { return new ActiveUserService(userRepository); } - @Bean - OAuth2AuthorizedClientService authorizedClientService(ClientRegistrationRepository registrations) { - return new InMemoryOAuth2AuthorizedClientService(registrations); - } - // Applies every OAuth2TokenValidator bean, as Spring Boot's issuer-uri JwtDecoder does. @Bean JwtDecoder jwtDecoder(ObjectProvider> validators) { From 0551b4c736555e04f19934f964c937d8236ffabd Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:30 +0200 Subject: [PATCH 03/14] fix(api)!: answer 403 on denied access and hide internal error text Access denials returned 401, which the portal reads as a lost session and answers with a new login. Unexpected errors returned raw exception text to the client; they now return a generic message and stay in the log. BREAKING CHANGE: UnauthorizedException responses change from 401 to 403. --- docs/context/module-index.md | 2 +- .../mip/utils/ControllerExceptionHandler.java | 18 +++++------------- .../mip/folder/ExperimentFolderAPITest.java | 6 +++--- 3 files changed, 9 insertions(+), 17 deletions(-) diff --git a/docs/context/module-index.md b/docs/context/module-index.md index 4c1fe38c..9f1288e2 100644 --- a/docs/context/module-index.md +++ b/docs/context/module-index.md @@ -107,7 +107,7 @@ Rules: Scope every read and write to the user resolved from the token; a folder Tests: `ExperimentFolderServiceTest` (Mockito) covers naming, ownership, membership, ordering, and the lost-race 409; `ExperimentFolderDTOTest` covers the three orderings in the response; `ExperimentFolderAPITest` (standalone MockMvc) pins the wire contract — body field names, response field names, and the status of every failure. -Notes: Folders hold experiment ids, never experiment copies, so nothing here can go stale by carrying a run's data. Statuses: 200 reads and mutations that leave a folder behind, 201 new folder or set, 204 only `DELETE /{folderId}`, 400 blank name or malformed id, 404 folder/set not the caller's or run not readable, 401 run not readable, 409 duplicate name (pre-check or lost database race). +Notes: Folders hold experiment ids, never experiment copies, so nothing here can go stale by carrying a run's data. Statuses: 200 reads and mutations that leave a folder behind, 201 new folder or set, 204 only `DELETE /{folderId}`, 400 blank name or malformed id, 404 folder/set not the caller's or run not readable, 403 run not readable, 409 duplicate name (pre-check or lost database race). ## `src/main/java/hbp/mip/user` diff --git a/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java b/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java index cbac03a1..92e05c7e 100644 --- a/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java +++ b/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java @@ -50,18 +50,9 @@ public ResponseEntity handleBadRequestException(BadRequestException ex, return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST); } - @ExceptionHandler(UnauthorizedException.class) - public ResponseEntity handleUnauthorizedException(UnauthorizedException ex, WebRequest request) { - ErrorMessage message = new ErrorMessage( - HttpStatus.UNAUTHORIZED.value(), - new Date(), - ex.getMessage(), - request.getDescription(false)); - - return new ResponseEntity<>(message, HttpStatus.UNAUTHORIZED); - } - - @ExceptionHandler({NoAuthorizedPathologiesException.class, TermsOfUseNotAcceptedException.class}) + // UnauthorizedException means a signed-in user was denied: 403. A 401 would make the portal sign in again. + @ExceptionHandler({UnauthorizedException.class, NoAuthorizedPathologiesException.class, + TermsOfUseNotAcceptedException.class}) public ResponseEntity handleForbiddenException( RuntimeException ex, WebRequest request @@ -103,7 +94,8 @@ public ResponseEntity globalExceptionHandler(Exception ex, WebRequ ErrorMessage message = new ErrorMessage( HttpStatus.INTERNAL_SERVER_ERROR.value(), new Date(), - ex.getMessage(), + // The details are in the log above: exception text can name hosts, SQL or schema. + "An internal error occurred.", request.getDescription(false)); return new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/test/java/hbp/mip/folder/ExperimentFolderAPITest.java b/src/test/java/hbp/mip/folder/ExperimentFolderAPITest.java index 7f563959..c7f7ab6a 100644 --- a/src/test/java/hbp/mip/folder/ExperimentFolderAPITest.java +++ b/src/test/java/hbp/mip/folder/ExperimentFolderAPITest.java @@ -272,14 +272,14 @@ void foreignFoldersAndForeignSetsAreBothNotFound() throws Exception { /** A run the caller may not read must not become a folder membership, and must not say 404 either. */ @Test - void unreadableRunIsUnauthorized() throws Exception { + void unreadableRunIsForbidden() throws Exception { when(service.addExperiment(any(), eq(FOLDER_ID), any(AddExperimentFoldersMemberDTO.class), any(Logger.class))) .thenThrow(new UnauthorizedException("You don't have access to that experiment.")); mvc.perform(post("/experiment-folders/" + FOLDER_ID + "/members").contentType("application/json") .content("{\"experimentUuid\":\"" + RUN_ID + "\"}").principal(principal)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.statusCode").value(401)); + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.statusCode").value(403)); } private ExperimentFolderDTO folderDto() { From 72f75d1c05db0e906ba7649e0bd23e8931fb75e4 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 04/14] fix(user)!: refuse a username held by another Keycloak subject Users are stored by username, and subject_id was never compared, so a reused preferred_username inherited the previous holder's experiments and accepted terms. Answer 403 with a message naming the conflict, on every route. Rows with no real subject get it filled in. A renamed user still gets a new row, as before. BREAKING CHANGE: a stored user whose subject differs from the token's gets 403. A realm whose subjects changed needs subject_id cleared first. --- .../mip/configurations/TermsOfUseFilter.java | 14 ++- .../java/hbp/mip/user/ActiveUserService.java | 32 +++++- .../mip/utils/ControllerExceptionHandler.java | 2 +- .../UserIdentityConflictException.java | 10 ++ .../configurations/TermsOfUseFilterTest.java | 15 +++ .../TermsOfUseSecurityChainTest.java | 16 ++- .../user/ActiveUserServiceSubjectTest.java | 97 +++++++++++++++++++ 7 files changed, 180 insertions(+), 6 deletions(-) create mode 100644 src/main/java/hbp/mip/utils/Exceptions/UserIdentityConflictException.java create mode 100644 src/test/java/hbp/mip/user/ActiveUserServiceSubjectTest.java diff --git a/src/main/java/hbp/mip/configurations/TermsOfUseFilter.java b/src/main/java/hbp/mip/configurations/TermsOfUseFilter.java index 280213b1..b9106957 100644 --- a/src/main/java/hbp/mip/configurations/TermsOfUseFilter.java +++ b/src/main/java/hbp/mip/configurations/TermsOfUseFilter.java @@ -2,6 +2,7 @@ import hbp.mip.user.ActiveUserService; import hbp.mip.utils.Exceptions.TermsOfUseNotAcceptedException; +import hbp.mip.utils.Exceptions.UserIdentityConflictException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -61,12 +62,21 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse throws ServletException, IOException { // Runs after AuthorizationFilter, so every request that gets here is authenticated. Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (activeUserService.hasAgreedToNDA(authentication)) { + RuntimeException exception; + try { + if (activeUserService.hasAgreedToNDA(authentication)) { + exception = null; + } else { + exception = new TermsOfUseNotAcceptedException(); + } + } catch (UserIdentityConflictException conflict) { + exception = conflict; + } + if (exception == null) { filterChain.doFilter(request, response); return; } - TermsOfUseNotAcceptedException exception = new TermsOfUseNotAcceptedException(); if (handlerExceptionResolver.resolveException(request, response, null, exception) == null) { // ControllerExceptionHandler could not render it (e.g. the client does not accept JSON). response.sendError(HttpStatus.FORBIDDEN.value(), exception.getMessage()); diff --git a/src/main/java/hbp/mip/user/ActiveUserService.java b/src/main/java/hbp/mip/user/ActiveUserService.java index 158a465c..ecdc0995 100644 --- a/src/main/java/hbp/mip/user/ActiveUserService.java +++ b/src/main/java/hbp/mip/user/ActiveUserService.java @@ -1,6 +1,8 @@ package hbp.mip.user; import hbp.mip.utils.Exceptions.TermsOfUseNotAcceptedException; +import hbp.mip.utils.Exceptions.UserIdentityConflictException; +import hbp.mip.utils.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; @@ -40,6 +42,7 @@ public UserDTO getActiveUser(Authentication authentication) { UserDAO activeUserDatabaseDetails = userRepository.findByUsername(activeUserDAO.getUsername()); if (activeUserDatabaseDetails != null) { + refuseAnotherSubject(activeUserDatabaseDetails, activeUserDAO); boolean changed = false; if ((!Objects.equals(activeUserDAO.getEmail(), activeUserDatabaseDetails.getEmail())) || !Objects.equals(activeUserDAO.getFullname(), activeUserDatabaseDetails.getFullname())) { @@ -49,6 +52,10 @@ public UserDTO getActiveUser(Authentication authentication) { activeUserDatabaseDetails.setEmail(activeUserDAO.getEmail()); changed = true; } + if (!isKnownSubject(activeUserDatabaseDetails) && isKnownSubject(activeUserDAO)) { + activeUserDatabaseDetails.setSubjectId(activeUserDAO.getSubjectId()); + changed = true; + } if (changed) { userRepository.save(activeUserDatabaseDetails); } @@ -98,8 +105,29 @@ public UserDTO agreeToNDA(Authentication authentication) { * A user who has never called GET /activeUser does not exist yet, so has not agreed. */ public boolean hasAgreedToNDA(Authentication authentication) { - UserDAO user = userRepository.findByUsername(buildUserFromAuthentication(authentication).getUsername()); - return user != null && Boolean.TRUE.equals(user.getAgreeNDA()); + UserDAO authenticated = buildUserFromAuthentication(authentication); + UserDAO user = userRepository.findByUsername(authenticated.getUsername()); + if (user == null) { + return false; + } + refuseAnotherSubject(user, authenticated); + return Boolean.TRUE.equals(user.getAgreeNDA()); + } + + // A username Keycloak gave to someone else must not inherit the previous holder's experiments or accepted terms. + private static void refuseAnotherSubject(UserDAO stored, UserDAO authenticated) { + if (isKnownSubject(stored) && isKnownSubject(authenticated) + && !stored.getSubjectId().equals(authenticated.getSubjectId())) { + new Logger(authenticated.getUsername(), "ActiveUserService") + .warn("Refused: the stored user has another Keycloak subject."); + throw new UserIdentityConflictException(); + } + } + + // buildUserFromAuthentication falls back to the username when a token has no subject, and older rows may be empty. + private static boolean isKnownSubject(UserDAO user) { + String subject = user.getSubjectId(); + return subject != null && !subject.isBlank() && !subject.equals(user.getUsername()); } private static UserDAO buildUserFromAuthentication(Authentication authentication) { diff --git a/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java b/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java index 92e05c7e..16b50a8e 100644 --- a/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java +++ b/src/main/java/hbp/mip/utils/ControllerExceptionHandler.java @@ -52,7 +52,7 @@ public ResponseEntity handleBadRequestException(BadRequestException ex, // UnauthorizedException means a signed-in user was denied: 403. A 401 would make the portal sign in again. @ExceptionHandler({UnauthorizedException.class, NoAuthorizedPathologiesException.class, - TermsOfUseNotAcceptedException.class}) + TermsOfUseNotAcceptedException.class, UserIdentityConflictException.class}) public ResponseEntity handleForbiddenException( RuntimeException ex, WebRequest request diff --git a/src/main/java/hbp/mip/utils/Exceptions/UserIdentityConflictException.java b/src/main/java/hbp/mip/utils/Exceptions/UserIdentityConflictException.java new file mode 100644 index 00000000..aa9802f1 --- /dev/null +++ b/src/main/java/hbp/mip/utils/Exceptions/UserIdentityConflictException.java @@ -0,0 +1,10 @@ +package hbp.mip.utils.Exceptions; + +public class UserIdentityConflictException extends RuntimeException { + + public static final String MESSAGE = "This username belongs to another account. Contact the MIP operators."; + + public UserIdentityConflictException() { + super(MESSAGE); + } +} diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java index 9b860cce..76aab5e2 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java @@ -4,6 +4,7 @@ import hbp.mip.user.UserDAO; import hbp.mip.user.UserRepository; import hbp.mip.utils.Exceptions.TermsOfUseNotAcceptedException; +import hbp.mip.utils.Exceptions.UserIdentityConflictException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -109,6 +110,20 @@ void fallsBackToAPlain403WhenTheResolverCannotRender() throws Exception { assertThat(response.getErrorMessage()).isEqualTo(TermsOfUseNotAcceptedException.MESSAGE); } + @Test + void usernameOfAnotherSubjectIsToldAboutTheConflictNotTheTerms() throws Exception { + UserDAO previousHolder = new UserDAO("alice", "alice", "alice@example.org", "subject-previous-holder"); + previousHolder.setAgreeNDA(true); + when(userRepository.findByUsername("alice")).thenReturn(previousHolder); + authenticate(bearer("alice")); + + MockHttpServletResponse response = run("GET", "/experiments"); + + assertThat(response.getHeader("X-Passed")).isNull(); + assertThat(response.getStatus()).isEqualTo(403); + assertThat(resolved).singleElement().isInstanceOf(UserIdentityConflictException.class); + } + // ------------------------------------------------------------------ exempt // agreeNDA passes the gate for every client; ActiveUserService.agreeToNDA accepts portal sessions only. diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 481a4996..f228fde1 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -7,6 +7,7 @@ import hbp.mip.user.UserRepository; import hbp.mip.utils.ControllerExceptionHandler; import hbp.mip.utils.Exceptions.TermsOfUseNotAcceptedException; +import hbp.mip.utils.Exceptions.UserIdentityConflictException; import jakarta.servlet.Filter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -162,6 +163,19 @@ void bearerUserWhoHasNotAgreedCanStillReadTheActiveUser() throws Exception { .andExpect(jsonPath("$.agreeNDA").value(false)); } + @Test + void usernameHeldByAnotherSubjectIsForbidden() throws Exception { + UserDAO previousHolder = new UserDAO("alice", "alice", "alice@example.org", "sub-1"); + previousHolder.setAgreeNDA(true); + when(userRepository.findByUsername("alice")).thenReturn(previousHolder); + + mvc.perform(withBearer(get("/services/activeUser"), "alice.client.Bearer.sub-2")) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.message").value(UserIdentityConflictException.MESSAGE)); + mvc.perform(withBearer(get("/services/experiments"), "alice.client.Bearer.sub-2")) + .andExpect(status().isForbidden()); + } + @Test void sessionUserWhoHasNotAgreedIsBlocked() throws Exception { storedUser("alice", false); @@ -245,7 +259,7 @@ JwtDecoder jwtDecoder(ObjectProvider> validators) { String[] parts = token.split("\\."); Jwt jwt = Jwt.withTokenValue(token) .header("alg", "none") - .subject(parts[0]) + .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") diff --git a/src/test/java/hbp/mip/user/ActiveUserServiceSubjectTest.java b/src/test/java/hbp/mip/user/ActiveUserServiceSubjectTest.java new file mode 100644 index 00000000..7d2e9fe8 --- /dev/null +++ b/src/test/java/hbp/mip/user/ActiveUserServiceSubjectTest.java @@ -0,0 +1,97 @@ +package hbp.mip.user; + +import hbp.mip.utils.Exceptions.UserIdentityConflictException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Users are stored by username, which Keycloak may give to someone else later: the stored subject must match. + */ +@ExtendWith(MockitoExtension.class) +class ActiveUserServiceSubjectTest { + + @Mock + private UserRepository userRepository; + + private ActiveUserService service; + + @BeforeEach + void setUp() { + service = new ActiveUserService(userRepository); + ReflectionTestUtils.setField(service, "authenticationIsEnabled", true); + } + + @Test + void sameSubjectGetsItsStoredUser() { + storedUser("sub-1"); + + assertThat(service.getActiveUser(token("sub-1")).agreeNDA()).isTrue(); + assertThat(service.hasAgreedToNDA(token("sub-1"))).isTrue(); + } + + @Test + void anotherSubjectIsRefusedAndChangesNothing() { + storedUser("sub-1"); + + assertThatThrownBy(() -> service.getActiveUser(token("sub-2"))) + .isInstanceOf(UserIdentityConflictException.class); + verify(userRepository, never()).save(any()); + } + + @Test + void anotherSubjectDoesNotInheritTheAcceptedTerms() { + storedUser("sub-1"); + + assertThatThrownBy(() -> service.hasAgreedToNDA(token("sub-2"))) + .isInstanceOf(UserIdentityConflictException.class); + } + + @Test + void rowWithoutARealSubjectIsFilledIn() { + // Empty, or the username fallback buildUserFromAuthentication writes for a token without a subject. + for (String legacySubject : new String[] {null, "", "alice"}) { + storedUser(legacySubject); + + assertThat(service.getActiveUser(token("sub-2")).subjectId()).isEqualTo("sub-2"); + } + verify(userRepository, org.mockito.Mockito.times(3)) + .save(argThat(user -> "sub-2".equals(user.getSubjectId()))); + } + + @Test + void tokenWithoutASubjectIsNotAConflict() { + storedUser("sub-1"); + + Jwt jwt = Jwt.withTokenValue("t").header("alg", "RS256").claim("preferred_username", "alice") + .claim("email", "alice@example.org").claim("name", "alice").build(); + + assertThat(service.getActiveUser(new JwtAuthenticationToken(jwt)).subjectId()).isEqualTo("sub-1"); + } + + private void storedUser(String subject) { + UserDAO user = new UserDAO("alice", "alice", "alice@example.org", subject); + user.setAgreeNDA(true); + when(userRepository.findByUsername("alice")).thenReturn(user); + } + + private static Authentication token(String subject) { + return new JwtAuthenticationToken(Jwt.withTokenValue("t").header("alg", "RS256").subject(subject) + .claim("preferred_username", "alice").claim("email", "alice@example.org").claim("name", "alice") + .build()); + } +} From 39b25fd68a9b926b1a808b79c904aaed6d6ccd2b Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 05/14] fix(logging): log failed authentication and stop logging request bodies Failed Bearer and OIDC authentication left no trace, because the default publisher sends no event for OAuth2 exceptions. Log them with the source address and exception type, never the token. An expired token is routine for a polling client, so it logs at DEBUG. Authorities and request bodies move to DEBUG. --- .../AuthenticationEventListener.java | 31 +++++++++++++++++-- .../configurations/SecurityConfiguration.java | 12 +++++++ .../hbp/mip/experiment/ExperimentAPI.java | 4 +-- .../hbp/mip/folder/ExperimentFolderAPI.java | 12 +++---- .../AuthenticationEventListenerTest.java | 19 ++++++++++++ .../TermsOfUseSecurityChainTest.java | 29 ++++++++++++++++- 6 files changed, 96 insertions(+), 11 deletions(-) create mode 100644 src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java diff --git a/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java b/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java index 8d56fb2e..0e100e2e 100644 --- a/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java +++ b/src/main/java/hbp/mip/configurations/AuthenticationEventListener.java @@ -2,8 +2,10 @@ import hbp.mip.utils.Logger; import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; @Component @@ -14,11 +16,36 @@ 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"); + logger.info("User " + username + " has logged in successfully from " + remoteAddress(authentication)); // If you need to log additional details: authentication.getAuthorities().forEach(authority -> - logger.info("User " + username + " has authority " + authority.getAuthority()) + logger.debug("User " + username + " has authority " + authority.getAuthority()) ); } + + @EventListener + public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) { + // Never the authentication's name: on a failed Bearer request that is the token itself. + Logger logger = new Logger("unknown", "LOGGING IN"); + String message = "Authentication failed from " + remoteAddress(event.getAuthentication()) + + ": " + event.getException().getClass().getSimpleName(); + // A client polling with a stale token is routine and would flood the log; anything else may be an attack. + if (isExpiredToken(event.getException())) { + logger.debug(message); + } else { + logger.warn(message); + } + } + + // Spring Security marks expiry only in the message, written by JwtTimestampValidator. + static boolean isExpiredToken(Exception exception) { + return exception.getMessage() != null && exception.getMessage().contains("Jwt expired at"); + } + + private static String remoteAddress(Authentication authentication) { + return authentication.getDetails() instanceof WebAuthenticationDetails details + ? details.getRemoteAddress() + : "unknown"; + } } diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index 6195eaa1..56a5aba6 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -4,8 +4,12 @@ import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationEventPublisher; +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.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -142,6 +146,14 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, return http.build(); } + // The default publisher sends no event for OAuth2 exceptions, so failed Bearer and OIDC logins would go unlogged. + @Bean + AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) { + DefaultAuthenticationEventPublisher eventPublisher = new DefaultAuthenticationEventPublisher(publisher); + eventPublisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class); + return eventPublisher; + } + // Spring Boot adds this to the issuer-uri JwtDecoder: a Bearer token must have been issued to one of this // federation's own Keycloak clients, not merely by the same realm. Keycloak names the requesting client in azp: // the platform client (shared by the portal and JupyterHub) or the public client of the mip client on users' diff --git a/src/main/java/hbp/mip/experiment/ExperimentAPI.java b/src/main/java/hbp/mip/experiment/ExperimentAPI.java index 71ecd389..4b721efc 100644 --- a/src/main/java/hbp/mip/experiment/ExperimentAPI.java +++ b/src/main/java/hbp/mip/experiment/ExperimentAPI.java @@ -119,7 +119,7 @@ public ResponseEntity previewExperiment(Authentication authentica @RequestBody ExperimentExecutionDTO experimentExecutionDTO) { var logger = new Logger(activeUserService.getActiveUser(authentication).username(), "(POST) /experiments/preview"); - logger.info("Request for experiment preview. RequestBody: " + logger.debug("Request for experiment preview. RequestBody: " + JsonConverters.convertObjectToJsonString(experimentExecutionDTO)); var experimentResponse = experimentService.previewExperiment(authentication, experimentExecutionDTO, logger); @@ -133,7 +133,7 @@ public ResponseEntity runExperiment(Authentication authentication @RequestBody ExperimentExecutionDTO experimentExecutionDTO) { var user = activeUserService.getActiveUser(authentication); var logger = new Logger(user.username(), "(POST) /experiments/runs"); - logger.info("Request for experiment run. RequestBody: " + logger.debug("Request for experiment run. RequestBody: " + JsonConverters.convertObjectToJsonString(experimentExecutionDTO)); var experimentResponse = experimentService.runExperiment(authentication, user, experimentExecutionDTO, diff --git a/src/main/java/hbp/mip/folder/ExperimentFolderAPI.java b/src/main/java/hbp/mip/folder/ExperimentFolderAPI.java index 3570c001..c190f317 100644 --- a/src/main/java/hbp/mip/folder/ExperimentFolderAPI.java +++ b/src/main/java/hbp/mip/folder/ExperimentFolderAPI.java @@ -54,7 +54,7 @@ public ResponseEntity getFolders(Authentication authentica public ResponseEntity createFolder(Authentication authentication, @RequestBody CreateExperimentGroupDTO createExperimentGroupDTO) { var logger = logger(authentication, "(POST) /experiment-folders"); - logger.info("Request for experiment folder creation. RequestBody: " + logger.debug("Request for experiment folder creation. RequestBody: " + JsonConverters.convertObjectToJsonString(createExperimentGroupDTO)); var folder = experimentFolderService.createFolder(authentication, createExperimentGroupDTO, logger); logger.info("Experiment folder created with id: " + folder.id()); @@ -76,7 +76,7 @@ public ResponseEntity renameFolder(Authentication authentic @PathVariable("folderId") String folderId, @RequestBody RenameExperimentGroupDTO renameExperimentGroupDTO) { var logger = logger(authentication, "(PATCH) /experiment-folders/" + folderId); - logger.info("Request for experiment folder rename. RequestBody: " + logger.debug("Request for experiment folder rename. RequestBody: " + JsonConverters.convertObjectToJsonString(renameExperimentGroupDTO)); var folder = experimentFolderService.renameFolder(authentication, folderId, renameExperimentGroupDTO, logger); logger.info("Experiment folder renamed. Id: " + folderId); @@ -99,7 +99,7 @@ public ResponseEntity addExperiment(Authentication authenti @PathVariable("folderId") String folderId, @RequestBody AddExperimentFoldersMemberDTO addExperimentFoldersMemberDTO) { var logger = logger(authentication, "(POST) /experiment-folders/" + folderId + "/members"); - logger.info("Request for experiment addition to a folder. RequestBody: " + logger.debug("Request for experiment addition to a folder. RequestBody: " + JsonConverters.convertObjectToJsonString(addExperimentFoldersMemberDTO)); var folder = experimentFolderService.addExperiment(authentication, folderId, addExperimentFoldersMemberDTO, logger); @@ -124,7 +124,7 @@ public ResponseEntity createSet(Authentication authenticati @PathVariable("folderId") String folderId, @RequestBody CreateExperimentGroupDTO createExperimentGroupDTO) { var logger = logger(authentication, "(POST) /experiment-folders/" + folderId + "/sets"); - logger.info("Request for experiment set creation. RequestBody: " + logger.debug("Request for experiment set creation. RequestBody: " + JsonConverters.convertObjectToJsonString(createExperimentGroupDTO)); var folder = experimentFolderService.createSet(authentication, folderId, createExperimentGroupDTO, logger); logger.info("Experiment set created in folder: " + folderId); @@ -137,7 +137,7 @@ public ResponseEntity renameSet(Authentication authenticati @PathVariable("setId") String setId, @RequestBody RenameExperimentGroupDTO renameExperimentGroupDTO) { var logger = logger(authentication, "(PATCH) /experiment-folders/" + folderId + "/sets/" + setId); - logger.info("Request for experiment set rename. RequestBody: " + logger.debug("Request for experiment set rename. RequestBody: " + JsonConverters.convertObjectToJsonString(renameExperimentGroupDTO)); var folder = experimentFolderService.renameSet(authentication, folderId, setId, renameExperimentGroupDTO, logger); logger.info("Experiment set renamed. Id: " + setId); @@ -167,7 +167,7 @@ public ResponseEntity updateSetMembership(Authentication au @RequestBody UpdateExperimentSetMembershipDTO updateExperimentSetMembershipDTO) { var logger = logger(authentication, "(PATCH) /experiment-folders/" + folderId + "/members/" + experimentUuid + "/set"); - logger.info("Request to change the set of an experiment. RequestBody: " + logger.debug("Request to change the set of an experiment. RequestBody: " + JsonConverters.convertObjectToJsonString(updateExperimentSetMembershipDTO)); var folder = experimentFolderService.updateSetMembership(authentication, folderId, experimentUuid, updateExperimentSetMembershipDTO, logger); diff --git a/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java b/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java new file mode 100644 index 00000000..384a3942 --- /dev/null +++ b/src/test/java/hbp/mip/configurations/AuthenticationEventListenerTest.java @@ -0,0 +1,19 @@ +package hbp.mip.configurations; + +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; + +import static org.assertj.core.api.Assertions.assertThat; + +class AuthenticationEventListenerTest { + + @Test + void onlyAnExpiredTokenCountsAsRoutine() { + assertThat(AuthenticationEventListener.isExpiredToken(new InvalidBearerTokenException( + "An error occurred while attempting to decode the Jwt: Jwt expired at 2026-11-06T10:00:00Z"))).isTrue(); + assertThat(AuthenticationEventListener.isExpiredToken(new InvalidBearerTokenException( + "An error occurred while attempting to decode the Jwt: Signed JWT rejected"))).isFalse(); + assertThat(AuthenticationEventListener.isExpiredToken(new BadCredentialsException(null))).isFalse(); + } +} diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index f228fde1..b6d4f052 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -16,6 +16,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; +import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; @@ -44,6 +46,7 @@ import jakarta.servlet.http.Cookie; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -81,6 +84,9 @@ class TermsOfUseSecurityChainTest { @Autowired private UserRepository userRepository; + @Autowired + private FailureEvents failures; + private MockMvc mvc; @BeforeEach @@ -121,6 +127,18 @@ void bearerTokenOfAnotherClientIsRejected() throws Exception { .andExpect(status().isUnauthorized()); } + @Test + void rejectedBearerTokenPublishesAFailureEventWithoutTheToken() throws Exception { + failures.events.clear(); + + mvc.perform(withBearer(get("/services/experiments"), "alice.other-federation")) + .andExpect(status().isUnauthorized()); + + assertThat(failures.events).singleElement() + .satisfies(event -> assertThat(event.getException().getClass().getSimpleName()) + .doesNotContain("alice")); + } + @Test void bearerTokenOfTheLaptopClientIsAccepted() throws Exception { storedUser("alice", true); @@ -238,7 +256,7 @@ private static MockHttpSession session(String username) { @EnableWebMvc @Import({SecurityConfiguration.class, SpaRedirectAuthenticationSuccessHandler.class, FrontendRedirectCaptureFilter.class, ControllerExceptionHandler.class, ActiveUserAPI.class, - AuthConfigAPI.class, StandInAPI.class}) + AuthConfigAPI.class, StandInAPI.class, FailureEvents.class}) static class Config { @Bean @@ -286,6 +304,15 @@ ClientRegistrationRepository clientRegistrationRepository() { } } + static class FailureEvents { + final List events = new ArrayList<>(); + + @EventListener + void record(AbstractAuthenticationFailureEvent event) { + events.add(event); + } + } + @RestController static class StandInAPI { @GetMapping("/experiments") From ac9730c63f6808b86bf9be96c8b56a7a6208a73e Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 06/14] fix(security)!: take login redirect hosts from config only Login redirects keep only the request's path. The host comes from frontend.base-url, and //host and /\host stay on this site. BREAKING CHANGE: frontend_redirect can no longer choose the host after login. --- .../FrontendRedirectCaptureFilter.java | 53 ++++----------- ...aRedirectAuthenticationSuccessHandler.java | 35 ++-------- .../mip/configurations/LoginRedirectTest.java | 64 +++++++++++++++++++ 3 files changed, 82 insertions(+), 70 deletions(-) create mode 100644 src/test/java/hbp/mip/configurations/LoginRedirectTest.java diff --git a/src/main/java/hbp/mip/configurations/FrontendRedirectCaptureFilter.java b/src/main/java/hbp/mip/configurations/FrontendRedirectCaptureFilter.java index f03bad3b..47129dc0 100644 --- a/src/main/java/hbp/mip/configurations/FrontendRedirectCaptureFilter.java +++ b/src/main/java/hbp/mip/configurations/FrontendRedirectCaptureFilter.java @@ -4,7 +4,6 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpSession; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -13,6 +12,10 @@ import java.net.URI; import java.net.URISyntaxException; +/** + * Remembers where to send the user after login. Only the path: the host comes from frontend.base-url, never from + * the request, or a crafted link would redirect a freshly signed-in user to another site. + */ @Component public class FrontendRedirectCaptureFilter extends OncePerRequestFilter { @@ -23,13 +26,9 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse throws ServletException, IOException { if (isAuthorizationRequest(request)) { - CapturedRedirect redirect = resolveRedirect(request); - if (redirect != null && StringUtils.hasText(redirect.targetPath())) { - HttpSession session = request.getSession(true); - session.setAttribute(SpaRedirectAuthenticationSuccessHandler.REDIRECT_PATH_ATTRIBUTE, redirect.targetPath()); - if (StringUtils.hasText(redirect.frontendBaseUrl())) { - session.setAttribute(SpaRedirectAuthenticationSuccessHandler.PLATFORM_UI_BASE_URL_ATTRIBUTE, redirect.frontendBaseUrl()); - } + String targetPath = resolveTargetPath(request); + if (StringUtils.hasText(targetPath)) { + request.getSession(true).setAttribute(SpaRedirectAuthenticationSuccessHandler.REDIRECT_PATH_ATTRIBUTE, targetPath); } } @@ -43,32 +42,21 @@ private boolean isAuthorizationRequest(HttpServletRequest request) { return requestUri.startsWith(expectedPrefix); } - private CapturedRedirect resolveRedirect(HttpServletRequest request) { + private String resolveTargetPath(HttpServletRequest request) { String explicitValue = request.getParameter("frontend_redirect"); if (StringUtils.hasText(explicitValue)) { URI explicitUri = parseUri(explicitValue); if (explicitUri != null && StringUtils.hasText(explicitUri.getScheme()) && StringUtils.hasText(explicitUri.getRawAuthority())) { // frontend_redirect can be a full URL (e.g. http://localhost:4200/#/home). - String baseUrl = explicitUri.getScheme() + "://" + explicitUri.getRawAuthority(); - String targetPath = buildPathQueryFragment(explicitUri); - return new CapturedRedirect(baseUrl, targetPath); + return buildPathQueryFragment(explicitUri); } // Otherwise treat it as a path (or hash route) and normalize. - return new CapturedRedirect(null, normalizePath(explicitValue)); + return normalizePath(explicitValue); } URI refererUri = parseUri(request.getHeader("Referer")); - if (refererUri != null) { - String baseUrl = null; - if (StringUtils.hasText(refererUri.getScheme()) && StringUtils.hasText(refererUri.getRawAuthority())) { - baseUrl = refererUri.getScheme() + "://" + refererUri.getRawAuthority(); - } - String targetPath = buildPathQueryFragment(refererUri); - return new CapturedRedirect(baseUrl, targetPath); - } - - return null; + return refererUri != null ? buildPathQueryFragment(refererUri) : null; } private URI parseUri(String value) { @@ -103,23 +91,6 @@ private static String buildPathQueryFragment(URI uri) { } private static String normalizePath(String path) { - if (!StringUtils.hasText(path)) { - return "/"; - } - - String trimmed = path.trim(); - - if (!trimmed.startsWith("/")) { - trimmed = "/" + trimmed; - } - - if (!trimmed.equals("/") && trimmed.endsWith("/")) { - trimmed = trimmed.substring(0, trimmed.length() - 1); - } - - return trimmed; - } - - private record CapturedRedirect(String frontendBaseUrl, String targetPath) { + return SpaRedirectAuthenticationSuccessHandler.normalizeRedirectPath(path); } } diff --git a/src/main/java/hbp/mip/configurations/SpaRedirectAuthenticationSuccessHandler.java b/src/main/java/hbp/mip/configurations/SpaRedirectAuthenticationSuccessHandler.java index f4be3d85..a2ff3801 100644 --- a/src/main/java/hbp/mip/configurations/SpaRedirectAuthenticationSuccessHandler.java +++ b/src/main/java/hbp/mip/configurations/SpaRedirectAuthenticationSuccessHandler.java @@ -12,7 +12,6 @@ public class SpaRedirectAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { public static final String REDIRECT_PATH_ATTRIBUTE = "SPA_REDIRECT_TARGET_PATH"; - public static final String PLATFORM_UI_BASE_URL_ATTRIBUTE = "SPA_REDIRECT_PLATFORM_UI_BASE_URL"; private final String frontendBaseUrl; @@ -30,17 +29,16 @@ protected String determineTargetUrl(HttpServletRequest request, HttpServletRespo return request.getContextPath() + "/"; } - String baseUrl = resolveFrontendBaseUrl(request); - if (!StringUtils.hasText(baseUrl)) { + if (frontendBaseUrl == null) { // No frontend base URL available. Fallback to relative redirect on the backend domain. return targetPath; } if ("/".equals(targetPath)) { - return baseUrl + "/"; + return frontendBaseUrl + "/"; } - return baseUrl + targetPath; + return frontendBaseUrl + targetPath; } private String resolveTargetPath(HttpServletRequest request) { @@ -55,34 +53,13 @@ private String resolveTargetPath(HttpServletRequest request) { return null; } - private String resolveFrontendBaseUrl(HttpServletRequest request) { - if (StringUtils.hasText(frontendBaseUrl)) { - return frontendBaseUrl; - } - - // Dev fallback: FrontendRedirectCaptureFilter stores this based on Referer / frontend_redirect. - HttpSession session = request.getSession(false); - if (session != null) { - Object attribute = session.getAttribute(PLATFORM_UI_BASE_URL_ATTRIBUTE); - session.removeAttribute(PLATFORM_UI_BASE_URL_ATTRIBUTE); - if (attribute instanceof String storedUrl && StringUtils.hasText(storedUrl)) { - return normalizeBaseUrl(storedUrl); - } - } - - return null; - } - - private static String normalizeRedirectPath(String path) { + /** A path on this site: exactly one leading slash, because //host and /\host are other sites to a browser. */ + static String normalizeRedirectPath(String path) { if (path == null || path.isBlank()) { return "/"; } - String normalized = path.trim(); - - if (!normalized.startsWith("/")) { - normalized = "/" + normalized; - } + String normalized = "/" + path.trim().replaceFirst("^[/\\\\]+", ""); if (normalized.length() > 1 && normalized.endsWith("/")) { normalized = normalized.substring(0, normalized.length() - 1); diff --git a/src/test/java/hbp/mip/configurations/LoginRedirectTest.java b/src/test/java/hbp/mip/configurations/LoginRedirectTest.java new file mode 100644 index 00000000..79990e4d --- /dev/null +++ b/src/test/java/hbp/mip/configurations/LoginRedirectTest.java @@ -0,0 +1,64 @@ +package hbp.mip.configurations; + +import jakarta.servlet.ServletException; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +/** After login the browser goes to frontend.base-url plus a path; the request can never choose the site. */ +class LoginRedirectTest { + + private static final String ATTRIBUTE = SpaRedirectAuthenticationSuccessHandler.REDIRECT_PATH_ATTRIBUTE; + + @Test + void absoluteFrontendRedirectKeepsOnlyItsPath() throws Exception { + assertThat(targetFor("https://evil.example/steal?x=1", "https://portal.example")) + .isEqualTo("https://portal.example/steal?x=1"); + } + + @Test + void refererKeepsOnlyItsPath() throws Exception { + MockHttpServletRequest request = loginRequest(); + request.addHeader("Referer", "https://evil.example/page"); + + assertThat(redirect(request, "https://portal.example")).isEqualTo("https://portal.example/page"); + } + + @Test + void protocolRelativePathsStayOnThisSite() throws Exception { + assertThat(targetFor("//evil.example/x", "")).isEqualTo("/services/evil.example/x"); + assertThat(targetFor("/\\evil.example/x", "")).isEqualTo("/services/evil.example/x"); + } + + @Test + void ordinaryPathIsKept() throws Exception { + assertThat(targetFor("/experiments?id=1#top", "https://portal.example/")) + .isEqualTo("https://portal.example/experiments?id=1#top"); + } + + private static String targetFor(String frontendRedirect, String baseUrl) throws ServletException, IOException { + MockHttpServletRequest request = loginRequest(); + request.setParameter("frontend_redirect", frontendRedirect); + return redirect(request, baseUrl); + } + + private static MockHttpServletRequest loginRequest() { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/services/oauth2/authorization/keycloak"); + request.setContextPath("/services"); + return request; + } + + private static String redirect(MockHttpServletRequest request, String baseUrl) throws ServletException, IOException { + new FrontendRedirectCaptureFilter().doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); + assertThat(request.getSession().getAttribute(ATTRIBUTE)).isNotNull(); + + MockHttpServletResponse response = new MockHttpServletResponse(); + new SpaRedirectAuthenticationSuccessHandler(baseUrl).onAuthenticationSuccess(request, response, null); + return response.getRedirectedUrl(); + } +} From a0fe686196d880e06514388fa6e6f8146b71dacc Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 07/14] fix(security)!: stop publishing the API description and actuator Swagger and /v3/api-docs are off unless SPRINGDOC_ENABLED is set, and need a login. Only /actuator/health stays public. BREAKING CHANGE: /v3/api-docs and /swagger-ui are off by default. --- .../hbp/mip/configurations/SecurityConfiguration.java | 6 +----- src/main/resources/application.yml | 7 +++++++ .../java/hbp/mip/configurations/TermsOfUseFilterTest.java | 5 ----- .../mip/configurations/TermsOfUseSecurityChainTest.java | 8 ++++++++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index 56a5aba6..d875c17e 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -48,11 +48,7 @@ public class SecurityConfiguration { "/login/**", "/oauth2/**", "/auth-config", - "/actuator/**", - "/v3/api-docs", - "/v3/api-docs/**", - "/swagger-ui/**", - "/swagger-ui.html"}; + "/actuator/health/**"}; private final SpaRedirectAuthenticationSuccessHandler spaRedirectAuthenticationSuccessHandler; private final FrontendRedirectCaptureFilter frontendRedirectCaptureFilter; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a9ef68e3..d3a4d76e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,5 +1,12 @@ # Platform-backend configuration (local defaults; override via environment variables) +### API DOCUMENTATION: off unless asked for, so a deployment does not publish its API description ### +springdoc: + api-docs: + enabled: ${SPRINGDOC_ENABLED:false} + swagger-ui: + enabled: ${SPRINGDOC_ENABLED:false} + ### EMBEDDED SERVER CONFIGURATION ### server: servlet: diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java index 76aab5e2..30e98747 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseFilterTest.java @@ -131,12 +131,7 @@ void usernameOfAnotherSubjectIsToldAboutTheConflictNotTheTerms() throws Exceptio @CsvSource({ "GET, /activeUser", "POST, /activeUser/agreeNDA", - "GET, /actuator", "GET, /actuator/health", - "GET, /v3/api-docs", - "GET, /v3/api-docs/swagger-config", - "GET, /swagger-ui/index.html", - "GET, /swagger-ui.html", "GET, /login/oauth2/code/keycloak", "GET, /oauth2/authorization/keycloak"}) void termsFlowAndPublicEndpointsAreExempt(String method, String path) throws Exception { diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index b6d4f052..b59badfd 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -223,6 +223,14 @@ void authConfigIsPublic() throws Exception { .andExpect(jsonPath("$.clientId").value("mip-cli")); } + @Test + void apiDescriptionAndActuatorRootNeedALogin() throws Exception { + for (String path : List.of("/services/v3/api-docs", "/services/swagger-ui.html", "/services/actuator")) { + assertThat(mvc.perform(get(path).contextPath("/services")).andReturn().getResponse().getStatus()) + .as(path).isIn(302, 401); + } + } + @Test void unauthenticatedRequestIsStillRejectedByAuthentication() throws Exception { int status = mvc.perform(get("/services/experiments").contextPath("/services")) From 0f1845da0bcf3a93c78e50bf4a21ec365d449d4f Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 08/14] fix(security): refuse AUTHENTICATION=0 with a non-local portal URL Every endpoint is open with authentication off, so the backend no longer starts that way unless the portal is local. A URL whose host cannot be read counts as not local: it may still be public. --- .../configurations/SecurityConfiguration.java | 20 +++++++++++++++++++ .../TermsOfUseSecurityChainTest.java | 13 ++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index d875c17e..4d1d8274 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -35,6 +35,8 @@ import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerExceptionResolver; +import java.net.URI; +import java.net.URISyntaxException; import java.util.*; import java.util.stream.Collectors; @@ -133,6 +135,10 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, // <--- XSRF Token handling } else { + if (!isLocalOrUnset(frontendBaseUrl)) { + throw new IllegalStateException("AUTHENTICATION is off but the portal is public at " + frontendBaseUrl + + ": every endpoint would be open. Turn authentication on."); + } http.authorizeHttpRequests(auth -> auth .requestMatchers("/**").permitAll()); http.csrf((csrf) -> csrf @@ -142,6 +148,20 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, return http.build(); } + static boolean isLocalOrUnset(String url) { + if (!StringUtils.hasText(url)) { + return true; + } + // A URL with no host we can read (no scheme, a bad character) may still be public: never count it as local. + String host; + try { + host = new URI(url.trim()).getHost(); + } catch (URISyntaxException e) { + return false; + } + return host != null && (host.equals("localhost") || host.equals("127.0.0.1") || host.equals("[::1]")); + } + // The default publisher sends no event for OAuth2 exceptions, so failed Bearer and OIDC logins would go unlogged. @Bean AuthenticationEventPublisher authenticationEventPublisher(ApplicationEventPublisher publisher) { diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index b59badfd..fc463a6f 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -231,6 +231,19 @@ void apiDescriptionAndActuatorRootNeedALogin() throws Exception { } } + @Test + void authenticationCanOnlyBeOffForALocalPortal() { + assertThat(SecurityConfiguration.isLocalOrUnset("")).isTrue(); + assertThat(SecurityConfiguration.isLocalOrUnset("http://localhost")).isTrue(); + assertThat(SecurityConfiguration.isLocalOrUnset("http://localhost:4200")).isTrue(); + assertThat(SecurityConfiguration.isLocalOrUnset("https://hbpmip.link")).isFalse(); + // No host can be read from these, and each may still be a public portal. + assertThat(SecurityConfiguration.isLocalOrUnset("mip.example.org")).isFalse(); + assertThat(SecurityConfiguration.isLocalOrUnset("mip.example.org:443")).isFalse(); + assertThat(SecurityConfiguration.isLocalOrUnset("https://my_portal.example.org")).isFalse(); + assertThat(SecurityConfiguration.isLocalOrUnset("http://a b")).isFalse(); + } + @Test void unauthenticatedRequestIsStillRejectedByAuthentication() throws Exception { int status = mvc.perform(get("/services/experiments").contextPath("/services")) From 594ac68b00920cae31a9800ebc80137f42aadaaf Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 09/14] fix(experiment)!: require the datasets to read someone else's shared experiment Any signed-in user who accepted the terms could read a shared experiment's results without a role on its datasets. Readers other than the owner and holders of the all-experiments role now need every dataset it ran on. Lists apply the same rule in the query, through the database function experiment_datasets_readable: filtering after paging would let totals and the name and algorithm filters reveal hidden experiments. Datasets live in the analysis text, which can hold an error message instead of JSON, so the function treats anything unreadable as no access. A stored analysis that is not JSON no longer turns a list into a 500: it lists as no analysis. BREAKING CHANGE: users without the datasets get 403 on experiments shared with them and no longer see them in lists. A shared row naming no datasets is readable only by its owner and the all-experiments role. --- docs/context/risk-register.md | 2 +- .../hbp/mip/algorithm/AnalysisRequestDTO.java | 14 ++ .../hbp/mip/experiment/ExperimentDTO.java | 3 +- .../hbp/mip/experiment/ExperimentService.java | 35 +++- .../experiment/ExperimentSpecifications.java | 17 ++ src/main/java/hbp/mip/utils/ClaimUtils.java | 24 +++ ...V5__ExperimentDatasetsReadableFunction.sql | 28 +++ .../ExperimentServiceSharedAccessTest.java | 178 ++++++++++++++++++ 8 files changed, 292 insertions(+), 9 deletions(-) create mode 100644 src/main/resources/db/migration/V5__ExperimentDatasetsReadableFunction.sql create mode 100644 src/test/java/hbp/mip/experiment/ExperimentServiceSharedAccessTest.java diff --git a/docs/context/risk-register.md b/docs/context/risk-register.md index 3ac399fc..5e3f7f60 100644 --- a/docs/context/risk-register.md +++ b/docs/context/risk-register.md @@ -5,7 +5,7 @@ | Authentication and OAuth2 | Login, logout, JWT, CSRF, and session behavior can lock users out or weaken protection | `SecurityConfiguration.java`, `SpaRedirectAuthenticationSuccessHandler.java`, `FrontendRedirectCaptureFilter.java` | Add focused tests and manually review auth flows before changing | Yes | | Authority and claim mapping | Dataset/experiment access depends on raw authority strings and Keycloak claims | `SecurityConfiguration.java`, `ClaimUtils.java` | Do not add `ROLE_` prefixes or rename claims without migration/compat notes | Yes | | Dataset authorization | Users may see unauthorized pathologies or datasets if filtering changes | `DataModelService.java`, `ClaimUtils.java` | Cover authenticated and authentication-disabled behavior | Yes | -| Experiment authorization | Owners/shared/admin-like access rules protect experiment read/update/delete | `ExperimentService.java`, `ExperimentSpecifications.java` | Test owner, shared, not-owner, and all-experiments authority cases | Yes | +| Experiment authorization | Owners/shared/admin-like access rules protect experiment read/update/delete | `ExperimentService.java`, `ExperimentSpecifications.java` | Test owner, shared, not-owner, and all-experiments authority cases. Shared experiments need all their datasets: a row naming none, such as a legacy one, is readable only by its owner and the all-experiments role. Keep `canRead` and the `experiment_datasets_readable` database function (V5) in step | Yes | | Experiment deletion | Deletion is destructive and authorization-sensitive | `ExperimentAPI.java`, `ExperimentService.java` | Require focused tests and rollback/restore discussion for behavior changes | Yes | | Experiment execution | Background thread updates status/result after Exaflow execution | `ExperimentService.java` | Preserve pending/success/error transitions and repository finish behavior | Yes | | Exaflow external APIs | Runtime depends on external service contracts and availability | `AnalysisService.java`, `SpecificationsService.java`, `DataModelService.java`, `ExperimentService.java`, `HTTPUtil.java` | Mock response codes/bodies and avoid unreviewed wire-shape changes | Yes | diff --git a/src/main/java/hbp/mip/algorithm/AnalysisRequestDTO.java b/src/main/java/hbp/mip/algorithm/AnalysisRequestDTO.java index 907b08c9..ab883aee 100644 --- a/src/main/java/hbp/mip/algorithm/AnalysisRequestDTO.java +++ b/src/main/java/hbp/mip/algorithm/AnalysisRequestDTO.java @@ -1,5 +1,9 @@ package hbp.mip.algorithm; +import com.google.gson.JsonParseException; +import hbp.mip.utils.JsonConverters; +import hbp.mip.utils.Logger; + import java.util.List; import java.util.Map; import java.util.stream.Stream; @@ -11,6 +15,16 @@ public record AnalysisRequestDTO( AnalysisAlgorithmDTO algorithm, Map flags) { + /** A stored analysis can be an error message, not JSON (see V2 migration); it then reads as no analysis. */ + public static AnalysisRequestDTO fromStored(String analysis) { + try { + return JsonConverters.convertJsonStringToObject(analysis, AnalysisRequestDTO.class); + } catch (JsonParseException e) { + new Logger("unknown", "AnalysisRequestDTO").warn("Stored analysis is unreadable: " + e.getClass().getSimpleName()); + return null; + } + } + public record AnalysisInputDataDTO( String data_model, List datasets, diff --git a/src/main/java/hbp/mip/experiment/ExperimentDTO.java b/src/main/java/hbp/mip/experiment/ExperimentDTO.java index d4eae6bf..02abec6f 100644 --- a/src/main/java/hbp/mip/experiment/ExperimentDTO.java +++ b/src/main/java/hbp/mip/experiment/ExperimentDTO.java @@ -2,7 +2,6 @@ import hbp.mip.algorithm.AnalysisRequestDTO; import hbp.mip.user.UserDTO; -import hbp.mip.utils.JsonConverters; import hbp.mip.utils.RawJson; import java.util.Date; @@ -33,7 +32,7 @@ public ExperimentDTO(ExperimentDAO experimentDAO, boolean includeResult) { experimentDAO.isViewed(), includeResult && experimentDAO.getResult() != null ? new RawJson(experimentDAO.getResult()) : null, experimentDAO.getStatus(), - JsonConverters.convertJsonStringToObject(experimentDAO.getAnalysis(), AnalysisRequestDTO.class), + AnalysisRequestDTO.fromStored(experimentDAO.getAnalysis()), experimentDAO.getMipVersion()); } } diff --git a/src/main/java/hbp/mip/experiment/ExperimentService.java b/src/main/java/hbp/mip/experiment/ExperimentService.java index 00635e3f..f3f73393 100644 --- a/src/main/java/hbp/mip/experiment/ExperimentService.java +++ b/src/main/java/hbp/mip/experiment/ExperimentService.java @@ -88,12 +88,12 @@ private Specification buildExperimentSpecification(Authentication spec = Specification.where(new ExperimentSpecifications.MyExperiment(user.username())); } else if (notMine) { spec = Specification.where(new ExperimentSpecifications.NotMyExperiment(user.username())) - .and(new ExperimentSpecifications.SharedExperiment(true)); + .and(sharedAndReadable(authentication, true, hasAccessRights, logger)); } else if (hasAccessRights) { spec = (root, query, criteriaBuilder) -> criteriaBuilder.conjunction(); } else { spec = Specification.where(new ExperimentSpecifications.MyExperiment(user.username())) - .or(new ExperimentSpecifications.SharedExperiment(includeShared)); + .or(sharedAndReadable(authentication, includeShared, hasAccessRights, logger)); } return spec @@ -104,6 +104,16 @@ private Specification buildExperimentSpecification(Authentication .and(new ExperimentSpecifications.ExperimentOrderBy(orderBy, descending)); } + // canRead's rule for lists, in the query: filtering afterwards would let totals and filters reveal hidden experiments. + private Specification sharedAndReadable(Authentication authentication, boolean shared, + boolean hasAccessRights, Logger logger) { + Specification spec = new ExperimentSpecifications.SharedExperiment(shared); + List datasets = hasAccessRights ? null : claimUtils.usableDatasets(authentication, logger); + return datasets == null + ? spec + : spec.and(new ExperimentSpecifications.DatasetsReadable(convertObjectToJsonString(datasets))); + } + private ExperimentsDTO createExperimentsDTO(Page pageExperiments) { List experiments = pageExperiments.map(experimentDAO -> new ExperimentDTO(experimentDAO, false)) .getContent(); @@ -134,16 +144,29 @@ public ExperimentDAO assertExperimentAccessible(Authentication authentication, S private void validateExperimentAccess(Authentication authentication, ExperimentDAO experimentDAO, String uuid, Logger logger) { var user = activeUserService.getActiveUser(authentication); - boolean unauthorizedAccess = authenticationIsEnabled && !experimentDAO.isShared() - && !experimentDAO.getCreatedBy().getUsername().equals(user.username()) - && !claimUtils.validateAccessRightsOnALLExperiments(authentication, logger); - if (unauthorizedAccess) { + if (!canRead(authentication, user, experimentDAO, logger)) { logger.warn("User tried to access an unauthorized experiment with id:" + uuid); throw new UnauthorizedException("You don't have access to that experiment."); } } + /** Sharing an experiment does not open its data: others also need the datasets it ran on. */ + private boolean canRead(Authentication authentication, UserDTO user, ExperimentDAO experimentDAO, Logger logger) { + if (!authenticationIsEnabled + || experimentDAO.getCreatedBy().getUsername().equals(user.username()) + || claimUtils.validateAccessRightsOnALLExperiments(authentication, logger)) { + return true; + } + return experimentDAO.isShared() + && claimUtils.hasAccessRightsOnDatasets(authentication, datasetsOf(experimentDAO), logger); + } + + private static List datasetsOf(ExperimentDAO experimentDAO) { + AnalysisRequestDTO analysis = AnalysisRequestDTO.fromStored(experimentDAO.getAnalysis()); + return analysis != null && analysis.inputdata() != null ? analysis.inputdata().allDatasets() : null; + } + private void validateDatasetAccess(Authentication authentication, AnalysisRequestDTO analysis, Logger logger) { if (authenticationIsEnabled) { claimUtils.validateAccessRightsOnDatasets(authentication, analysis.inputdata().allDatasets(), logger); diff --git a/src/main/java/hbp/mip/experiment/ExperimentSpecifications.java b/src/main/java/hbp/mip/experiment/ExperimentSpecifications.java index f1d589e6..74226e30 100644 --- a/src/main/java/hbp/mip/experiment/ExperimentSpecifications.java +++ b/src/main/java/hbp/mip/experiment/ExperimentSpecifications.java @@ -135,6 +135,23 @@ public Predicate toPredicate(@NonNull Root root, @NonNull Criteri } } + /** Every dataset the experiment ran on is in {@code allowedDatasets}, a JSON array of lowercase codes. */ + public static class DatasetsReadable implements Specification { + + private final String allowedDatasets; + + public DatasetsReadable(String allowedDatasets) { + this.allowedDatasets = allowedDatasets; + } + + public Predicate toPredicate(@NonNull Root root, @NonNull CriteriaQuery criteriaQuery, + @NonNull CriteriaBuilder cb) { + // Defined in V5__ExperimentDatasetsReadableFunction.sql. + return cb.isTrue(cb.function("experiment_datasets_readable", Boolean.class, + root.get("analysis"), cb.literal(allowedDatasets))); + } + } + public static class ExperimentOrderBy implements Specification { private final String orderBy; diff --git a/src/main/java/hbp/mip/utils/ClaimUtils.java b/src/main/java/hbp/mip/utils/ClaimUtils.java index 0e98fc34..e2de51e7 100644 --- a/src/main/java/hbp/mip/utils/ClaimUtils.java +++ b/src/main/java/hbp/mip/utils/ClaimUtils.java @@ -67,6 +67,30 @@ public void validateAccessRightsOnDatasets(Authentication authentication, } } + /** True when the user may use every one of the datasets. No datasets named: false, nothing proves access. */ + public boolean hasAccessRightsOnDatasets(Authentication authentication, List datasets, Logger logger) { + if (datasets == null || datasets.isEmpty()) { + return false; + } + ArrayList authorities = getAuthorityRoles(authentication); + return hasRoleAccess(authorities, allDatasetsAllowedClaim, logger) + || datasets.stream().allMatch(dataset -> hasRoleAccess(authorities, getDatasetClaim(dataset), logger)); + } + + /** The dataset codes the user may use, lowercase; null when the all-datasets role covers every dataset. */ + public List usableDatasets(Authentication authentication, Logger logger) { + ArrayList authorities = getAuthorityRoles(authentication); + if (hasRoleAccess(authorities, allDatasetsAllowedClaim, logger)) { + return null; + } + String prefix = datasetClaimPrefix.toLowerCase(); + return authorities.stream() + .map(String::toLowerCase) + .filter(authority -> authority.startsWith(prefix)) + .map(authority -> authority.substring(prefix.length())) + .toList(); + } + public boolean validateAccessRightsOnALLExperiments(Authentication authentication, Logger logger) { ArrayList authorities = getAuthorityRoles(authentication); return hasRoleAccess(authorities, allExperimentsAllowedClaim, logger); diff --git a/src/main/resources/db/migration/V5__ExperimentDatasetsReadableFunction.sql b/src/main/resources/db/migration/V5__ExperimentDatasetsReadableFunction.sql new file mode 100644 index 00000000..24d7a1d0 --- /dev/null +++ b/src/main/resources/db/migration/V5__ExperimentDatasetsReadableFunction.sql @@ -0,0 +1,28 @@ +-- True when every dataset an analysis reads is in allowed, a JSON array of lowercase dataset codes. +-- Lets experiment lists hide shared experiments in the query, so totals and filters cannot reveal them. +-- Same rule as ClaimUtils.hasAccessRightsOnDatasets and AnalysisInputDataDTO.allDatasets: no datasets named, or an +-- analysis that is not valid JSON (JsonConverters stores the error message on a failed write), proves no access. +CREATE FUNCTION experiment_datasets_readable(analysis TEXT, allowed TEXT) RETURNS BOOLEAN AS $$ +DECLARE + input JSONB; + validation JSONB; +BEGIN + input := analysis::jsonb -> 'inputdata'; + IF jsonb_typeof(input -> 'datasets') IS DISTINCT FROM 'array' OR jsonb_array_length(input -> 'datasets') = 0 THEN + RETURN FALSE; + END IF; + + validation := COALESCE(NULLIF(input -> 'validation_datasets', 'null'::jsonb), '[]'::jsonb); + IF jsonb_typeof(validation) <> 'array' THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text((input -> 'datasets') || validation) AS dataset + WHERE (allowed::jsonb ? lower(dataset)) IS NOT TRUE); +EXCEPTION + WHEN data_exception THEN + RETURN FALSE; +END; +$$ LANGUAGE plpgsql STABLE; diff --git a/src/test/java/hbp/mip/experiment/ExperimentServiceSharedAccessTest.java b/src/test/java/hbp/mip/experiment/ExperimentServiceSharedAccessTest.java new file mode 100644 index 00000000..f1e6a0d6 --- /dev/null +++ b/src/test/java/hbp/mip/experiment/ExperimentServiceSharedAccessTest.java @@ -0,0 +1,178 @@ +package hbp.mip.experiment; + +import hbp.mip.algorithm.AnalysisService; +import hbp.mip.user.ActiveUserService; +import hbp.mip.user.UserDAO; +import hbp.mip.user.UserDTO; +import hbp.mip.utils.ClaimUtils; +import hbp.mip.utils.Exceptions.NoContent; +import hbp.mip.utils.Exceptions.UnauthorizedException; +import hbp.mip.utils.Logger; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.test.util.ReflectionTestUtils; + +import java.time.Duration; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Sharing does not open the data: readers of someone else's experiment need its datasets. Real ClaimUtils. */ +@ExtendWith(MockitoExtension.class) +class ExperimentServiceSharedAccessTest { + + private static final String ANALYSIS = "{\"inputdata\":{\"data_model\":\"dm:1\",\"datasets\":[\"ds1\"]}}"; + + @Mock + private ActiveUserService activeUserService; + @Mock + private ExperimentRepository experimentRepository; + @Mock + private ExperimentRunRepository experimentRunRepository; + @Mock + private AnalysisService analysisService; + + private final Logger logger = new Logger("reader", "test"); + private ExperimentService service; + + @BeforeEach + void setUp() { + ClaimUtils claimUtils = new ClaimUtils(); + ReflectionTestUtils.setField(claimUtils, "allDatasetsAllowedClaim", "research_dataset_all"); + ReflectionTestUtils.setField(claimUtils, "allExperimentsAllowedClaim", "research_experiment_all"); + ReflectionTestUtils.setField(claimUtils, "datasetClaimPrefix", "research_dataset_"); + service = new ExperimentService(activeUserService, claimUtils, experimentRepository, experimentRunRepository, + analysisService, true, "9.0.0", Duration.ofHours(24)); + lenient().when(activeUserService.getActiveUser(any())) + .thenReturn(new UserDTO("reader", "Reader", "reader@example.org", "subject", true)); + } + + @Test + void sharedExperimentNeedsItsDatasets() { + ExperimentDAO shared = stored(experiment("owner", true, ANALYSIS)); + + assertThatThrownBy(() -> read(shared, "research_dataset_other")).isInstanceOf(UnauthorizedException.class); + assertThat(read(shared, "research_dataset_ds1")).isSameAs(shared); + assertThat(read(shared, "research_dataset_all")).isSameAs(shared); + } + + @Test + void sharedExperimentWithoutKnownDatasetsIsRefused() { + ExperimentDAO shared = stored(experiment("owner", true, "{}")); + + assertThatThrownBy(() -> read(shared, "research_dataset_ds1")).isInstanceOf(UnauthorizedException.class); + } + + @Test + void ownerAndAllExperimentsRoleNeedNoDatasetRole() { + ExperimentDAO mine = stored(experiment("reader", false, ANALYSIS)); + assertThat(read(mine)).isSameAs(mine); + + ExperimentDAO others = stored(experiment("owner", false, ANALYSIS)); + assertThat(read(others, "research_experiment_all")).isSameAs(others); + } + + @Test + void unsharedExperimentStaysPrivateEvenWithItsDatasets() { + ExperimentDAO others = stored(experiment("owner", false, ANALYSIS)); + + assertThatThrownBy(() -> read(others, "research_dataset_ds1")).isInstanceOf(UnauthorizedException.class); + } + + @Test + void listAsksTheDatabaseOnlyForSharedExperimentsOnTheUsersDatasets() { + CriteriaBuilder cb = listedWith("research_dataset_DS1", "research_dataset_ds2", "other_role"); + + verify(cb).literal("[\"ds1\",\"ds2\"]"); + } + + @Test + void listDoesNotFilterOnDatasetsForTheAllDatasetsOrAllExperimentsRole() { + verify(listedWith("research_dataset_all"), never()).literal(anyString()); + verify(listedWith("research_experiment_all"), never()).literal(anyString()); + } + + @Test + void listWithNothingVisibleIsNoContent() { + when(experimentRepository.findAll(any(Specification.class), any(Pageable.class))).thenReturn(Page.empty()); + + assertThatThrownBy(() -> list()).isInstanceOf(NoContent.class); + } + + @Test + void storedAnalysisThatIsNotJsonListsAsNoAnalysisAndIsRefusedToOthers() { + String errorMessage = "Failed to serialize the analysis"; + when(experimentRepository.findAll(any(Specification.class), any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of(experiment("reader", false, errorMessage)))); + + assertThat(list().experiments()).singleElement().satisfies(listed -> assertThat(listed.analysis()).isNull()); + + ExperimentDAO shared = stored(experiment("owner", true, errorMessage)); + assertThatThrownBy(() -> read(shared, "research_dataset_ds1")).isInstanceOf(UnauthorizedException.class); + } + + private ExperimentsDTO list(String... authorities) { + return service.getExperiments(user(authorities), null, null, null, null, true, false, false, 0, 10, "created", + true, logger); + } + + @SuppressWarnings("unchecked") + private CriteriaBuilder listedWith(String... authorities) { + clearInvocations(experimentRepository); + when(experimentRepository.findAll(any(Specification.class), any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of(experiment("reader", false, ANALYSIS)))); + list(authorities); + + ArgumentCaptor> spec = ArgumentCaptor.forClass(Specification.class); + verify(experimentRepository).findAll(spec.capture(), any(Pageable.class)); + CriteriaBuilder cb = mock(CriteriaBuilder.class, RETURNS_DEEP_STUBS); + spec.getValue().toPredicate(mock(Root.class, RETURNS_DEEP_STUBS), mock(CriteriaQuery.class, RETURNS_DEEP_STUBS), cb); + return cb; + } + + private ExperimentDAO read(ExperimentDAO experiment, String... authorities) { + return service.assertExperimentAccessible(user(authorities), experiment.getUuid().toString(), logger); + } + + private ExperimentDAO stored(ExperimentDAO experiment) { + when(experimentRepository.loadExperiment(experiment.getUuid().toString(), logger)).thenReturn(experiment); + return experiment; + } + + private static Authentication user(String... authorities) { + return new TestingAuthenticationToken("reader", "n/a", authorities); + } + + private static ExperimentDAO experiment(String owner, boolean shared, String analysis) { + ExperimentDAO experiment = new ExperimentDAO(); + experiment.setUuid(UUID.randomUUID()); + experiment.setCreatedBy(new UserDAO(owner, owner, owner + "@example.org", owner)); + experiment.setShared(shared); + experiment.setAnalysis(analysis); + return experiment; + } +} From 3d52b0d3a802ce75884514afaecacce9d20b77fc Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 10/14] feat(security): bound portal sessions Portal sessions end after SESSION_MAX_AGE (8 hours), and idle after SESSION_IDLE_TIMEOUT (30 minutes), so roles taken at login do not live on. The session cookie is SameSite=Lax rather than relying on browser defaults. --- .../configurations/SecurityConfiguration.java | 7 +++ .../configurations/SessionMaxAgeFilter.java | 44 ++++++++++++++++ src/main/resources/application.yml | 6 +++ .../SessionMaxAgeFilterTest.java | 51 +++++++++++++++++++ .../TermsOfUseSecurityChainTest.java | 24 +++++++++ 5 files changed, 132 insertions(+) create mode 100644 src/main/java/hbp/mip/configurations/SessionMaxAgeFilter.java create mode 100644 src/test/java/hbp/mip/configurations/SessionMaxAgeFilterTest.java diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index 4d1d8274..5db24df1 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -4,6 +4,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.convert.DurationStyle; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -28,6 +29,7 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.access.intercept.AuthorizationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler; @@ -67,6 +69,9 @@ public class SecurityConfiguration { @Value("${spring.security.oauth2.client.registration.keycloak.client-id:}") private String keycloakClientId; + @Value("${authentication.session_max_age:8h}") + private String sessionMaxAge; + public SecurityConfiguration(SpaRedirectAuthenticationSuccessHandler spaRedirectAuthenticationSuccessHandler, FrontendRedirectCaptureFilter frontendRedirectCaptureFilter, ActiveUserService activeUserService, @@ -94,6 +99,8 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, http.oauth2Login(login -> login.successHandler(spaRedirectAuthenticationSuccessHandler)); + http.addFilterBefore(new SessionMaxAgeFilter(DurationStyle.detectAndParse(sessionMaxAge)), SecurityContextHolderFilter.class); + // Allow API clients (e.g. notebooks) to authenticate with Bearer JWTs. // This runs alongside oauth2Login (session-based) authentication. http.oauth2ResourceServer(oauth2 -> oauth2 diff --git a/src/main/java/hbp/mip/configurations/SessionMaxAgeFilter.java b/src/main/java/hbp/mip/configurations/SessionMaxAgeFilter.java new file mode 100644 index 00000000..d22ac4a0 --- /dev/null +++ b/src/main/java/hbp/mip/configurations/SessionMaxAgeFilter.java @@ -0,0 +1,44 @@ +package hbp.mip.configurations; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Duration; + +/** + * Ends a portal session once it is older than the maximum, however active it is, so the roles it took from Keycloak + * at login cannot live on. The servlet container only has an idle timeout. + * + * Runs before the security context is loaded, so the request continues as a signed-out one. Not a {@code @Component} + * so Spring Boot does not also register it as a plain servlet filter. + */ +public class SessionMaxAgeFilter extends OncePerRequestFilter { + + private final long maxAgeMillis; + + public SessionMaxAgeFilter(Duration maxAge) { + this.maxAgeMillis = maxAge.toMillis(); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null) { + try { + if (System.currentTimeMillis() - session.getCreationTime() > maxAgeMillis) { + session.invalidate(); + } + } catch (IllegalStateException alreadyInvalidated) { + // A parallel request on the same session got here first: this one also continues signed out. + logger.debug("Session was already invalidated"); + } + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d3a4d76e..8762f1dc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -11,6 +11,10 @@ springdoc: server: servlet: contextPath: "/services" + session: + timeout: ${SESSION_IDLE_TIMEOUT:30m} + cookie: + same-site: lax port: 8080 forward-headers-strategy: native @@ -61,6 +65,8 @@ 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:} + # Portal sessions end at this age however active they are (8h or PT8H). + session_max_age: ${SESSION_MAX_AGE:8h} ### EXTERNAL SERVICES ### services: diff --git a/src/test/java/hbp/mip/configurations/SessionMaxAgeFilterTest.java b/src/test/java/hbp/mip/configurations/SessionMaxAgeFilterTest.java new file mode 100644 index 00000000..1631d9bc --- /dev/null +++ b/src/test/java/hbp/mip/configurations/SessionMaxAgeFilterTest.java @@ -0,0 +1,51 @@ +package hbp.mip.configurations; + +import jakarta.servlet.http.HttpSession; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockHttpSession; + +import java.time.Duration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SessionMaxAgeFilterTest { + + @Test + void sessionOlderThanTheMaximumEnds() throws Exception { + MockHttpSession session = new MockHttpSession(); + + run(session, Duration.ofMillis(-1)); + + assertThat(session.isInvalid()).isTrue(); + } + + @Test + void youngerSessionContinues() throws Exception { + MockHttpSession session = new MockHttpSession(); + + run(session, Duration.ofHours(8)); + + assertThat(session.isInvalid()).isFalse(); + } + + @Test + void sessionAnotherRequestJustInvalidatedStillLetsTheRequestContinue() throws Exception { + HttpSession session = mock(HttpSession.class); + when(session.getCreationTime()).thenThrow(new IllegalStateException("already invalidated")); + + assertThat(run(session, Duration.ofHours(8)).getRequest()).isNotNull(); + } + + private static MockFilterChain run(HttpSession session, Duration maxAge) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setSession(session); + MockFilterChain chain = new MockFilterChain(); + new SessionMaxAgeFilter(maxAge).doFilter(request, new MockHttpServletResponse(), chain); + return chain; + } +} diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index fc463a6f..07090619 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -45,6 +45,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import jakarta.servlet.http.Cookie; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -74,6 +75,7 @@ */ @SpringJUnitWebConfig(TermsOfUseSecurityChainTest.Config.class) @TestPropertySource(properties = {"authentication.enabled=1", "authentication.cli_client_id=mip-cli", + "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 TermsOfUseSecurityChainTest { @@ -223,6 +225,28 @@ void authConfigIsPublic() throws Exception { .andExpect(jsonPath("$.clientId").value("mip-cli")); } + @Test + void sessionPastItsMaximumAgeIsSignedOut() throws Exception { + storedUser("alice", true); + MockHttpSession session = session("alice"); + mvc.perform(get("/services/experiments").contextPath("/services").session(session)) + .andExpect(status().isOk()); + + // MockHttpSession's creation time is fixed: an old session is one created before "now minus the maximum". + MockHttpSession old = new MockHttpSession() { + @Override + public long getCreationTime() { + return System.currentTimeMillis() - Duration.ofHours(9).toMillis(); + } + }; + old.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); + + assertThat(mvc.perform(get("/services/experiments").contextPath("/services").session(old)) + .andReturn().getResponse().getStatus()).isIn(302, 401); + assertThat(old.isInvalid()).isTrue(); + } + @Test void apiDescriptionAndActuatorRootNeedALogin() throws Exception { for (String path : List.of("/services/v3/api-docs", "/services/swagger-ui.html", "/services/actuator")) { From 97804e8918eb661c2b26b12a0db958a3c5696169 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 11/14] feat(security): end all of a user's portal sessions on back-channel logout Lets Keycloak end portal sessions; it needs the client's Backchannel Logout URL. Keycloak's user logout sends one logout token per client, naming one session, so the registry matches on the subject to end the user's other sessions too. A token naming only a session ends that session. Login changes the session id, and the registry only learns of it through HttpSessionEventPublisher. --- .../configurations/SecurityConfiguration.java | 26 +++++++++ .../UserWideOidcSessionRegistry.java | 41 ++++++++++++++ .../TermsOfUseSecurityChainTest.java | 7 +++ .../UserWideOidcSessionRegistryTest.java | 54 +++++++++++++++++++ 4 files changed, 128 insertions(+) create mode 100644 src/main/java/hbp/mip/configurations/UserWideOidcSessionRegistry.java create mode 100644 src/test/java/hbp/mip/configurations/UserWideOidcSessionRegistryTest.java diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index 5db24df1..c0c82977 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -18,6 +18,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.client.oidc.session.OidcSessionRegistry; 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; @@ -30,6 +31,7 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.context.SecurityContextHolderFilter; +import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.security.web.access.intercept.AuthorizationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler; @@ -72,6 +74,12 @@ public class SecurityConfiguration { @Value("${authentication.session_max_age:8h}") private String sessionMaxAge; + @Value("${server.port:8080}") + private int serverPort; + + @Value("${server.servlet.contextPath:/services}") + private String contextPath; + public SecurityConfiguration(SpaRedirectAuthenticationSuccessHandler spaRedirectAuthenticationSuccessHandler, FrontendRedirectCaptureFilter frontendRedirectCaptureFilter, ActiveUserService activeUserService, @@ -101,6 +109,12 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, http.addFilterBefore(new SessionMaxAgeFilter(DurationStyle.detectAndParse(sessionMaxAge)), SecurityContextHolderFilter.class); + // Keycloak ends a disabled user's or a signed-out user's portal session (needs the client's Backchannel + // Logout URL). Spring then calls /logout on this instance with that session's cookie. + // ponytail: the session registry is in memory, one backend replica; a shared registry if that changes. + http.oidcLogout(logout -> logout.backChannel(backChannel -> backChannel + .logoutUri("http://localhost:" + serverPort + contextPath + "/logout"))); + // Allow API clients (e.g. notebooks) to authenticate with Bearer JWTs. // This runs alongside oauth2Login (session-based) authentication. http.oauth2ResourceServer(oauth2 -> oauth2 @@ -155,6 +169,18 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, return http.build(); } + // Back-channel logout keeps session ids in its registry; login changes the id, and the registry only hears of it + // through these events. Without them Keycloak's logout finds no session to end. + @Bean + HttpSessionEventPublisher httpSessionEventPublisher() { + return new HttpSessionEventPublisher(); + } + + @Bean + OidcSessionRegistry oidcSessionRegistry() { + return new UserWideOidcSessionRegistry(); + } + static boolean isLocalOrUnset(String url) { if (!StringUtils.hasText(url)) { return true; diff --git a/src/main/java/hbp/mip/configurations/UserWideOidcSessionRegistry.java b/src/main/java/hbp/mip/configurations/UserWideOidcSessionRegistry.java new file mode 100644 index 00000000..ef829443 --- /dev/null +++ b/src/main/java/hbp/mip/configurations/UserWideOidcSessionRegistry.java @@ -0,0 +1,41 @@ +package hbp.mip.configurations; + +import org.springframework.security.oauth2.client.oidc.authentication.logout.OidcLogoutToken; +import org.springframework.security.oauth2.client.oidc.session.InMemoryOidcSessionRegistry; +import org.springframework.security.oauth2.client.oidc.session.OidcSessionInformation; +import org.springframework.security.oauth2.client.oidc.session.OidcSessionRegistry; + +/** + * Ends all of a user's portal sessions on any back-channel logout. Keycloak's "sign out this user" sends one logout + * token per client, naming one session, however many are open; following that sid would leave the others alive. The + * cost is that signing out at Keycloak in one browser also ends the portal in the user's other browsers. + */ +class UserWideOidcSessionRegistry implements OidcSessionRegistry { + + private final OidcSessionRegistry delegate = new InMemoryOidcSessionRegistry(); + + @Override + public void saveSessionInformation(OidcSessionInformation info) { + delegate.saveSessionInformation(info); + } + + @Override + public OidcSessionInformation removeSessionInformation(String clientSessionId) { + return delegate.removeSessionInformation(clientSessionId); + } + + @Override + public Iterable removeSessionInformation(OidcLogoutToken logoutToken) { + // A token may name only a session: there is no subject to widen the match to. + if (logoutToken.getSubject() == null) { + return delegate.removeSessionInformation(logoutToken); + } + // Without a sid, the registry matches on the token's subject. + return delegate.removeSessionInformation(OidcLogoutToken.withTokenValue(logoutToken.getTokenValue()) + .claims(claims -> { + claims.putAll(logoutToken.getClaims()); + claims.remove("sid"); + }) + .build()); + } +} diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index 07090619..e021d333 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -247,6 +247,13 @@ public long getCreationTime() { assertThat(old.isInvalid()).isTrue(); } + @Test + void backChannelLogoutIsReachableWithoutASessionAndRefusesABadToken() throws Exception { + mvc.perform(post("/services/logout/connect/back-channel/keycloak").contextPath("/services") + .contentType("application/x-www-form-urlencoded").param("logout_token", "not-a-token")) + .andExpect(status().isBadRequest()); + } + @Test void apiDescriptionAndActuatorRootNeedALogin() throws Exception { for (String path : List.of("/services/v3/api-docs", "/services/swagger-ui.html", "/services/actuator")) { diff --git a/src/test/java/hbp/mip/configurations/UserWideOidcSessionRegistryTest.java b/src/test/java/hbp/mip/configurations/UserWideOidcSessionRegistryTest.java new file mode 100644 index 00000000..c21e6592 --- /dev/null +++ b/src/test/java/hbp/mip/configurations/UserWideOidcSessionRegistryTest.java @@ -0,0 +1,54 @@ +package hbp.mip.configurations; + +import org.junit.jupiter.api.Test; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.oauth2.client.oidc.authentication.logout.OidcLogoutToken; +import org.springframework.security.oauth2.client.oidc.session.OidcSessionInformation; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +class UserWideOidcSessionRegistryTest { + + private static final String ISSUER = "https://idp.example.org/realms/MIP"; + + @Test + void logoutNamingOneSessionEndsAllOfThatUsersSessionsOnly() { + UserWideOidcSessionRegistry registry = new UserWideOidcSessionRegistry(); + registry.saveSessionInformation(session("portal-1", "keycloak-1", "alice")); + registry.saveSessionInformation(session("portal-2", "keycloak-2", "alice")); + registry.saveSessionInformation(session("portal-3", "keycloak-3", "bob")); + + OidcLogoutToken token = OidcLogoutToken.withTokenValue("t").issuer(ISSUER).subject("alice") + .sessionId("keycloak-1").audience(List.of("mippublic")).issuedAt(Instant.now()).jti("j").build(); + + assertThat(registry.removeSessionInformation(token)).extracting(OidcSessionInformation::getSessionId) + .containsExactlyInAnyOrder("portal-1", "portal-2"); + assertThat(registry.removeSessionInformation("portal-3")).isNotNull(); + } + + @Test + void logoutNamingOnlyASessionEndsThatSession() { + UserWideOidcSessionRegistry registry = new UserWideOidcSessionRegistry(); + registry.saveSessionInformation(session("portal-1", "keycloak-1", "alice")); + registry.saveSessionInformation(session("portal-2", "keycloak-2", "alice")); + + OidcLogoutToken token = OidcLogoutToken.withTokenValue("t").issuer(ISSUER) + .sessionId("keycloak-1").audience(List.of("mippublic")).issuedAt(Instant.now()).jti("j").build(); + + assertThat(registry.removeSessionInformation(token)).extracting(OidcSessionInformation::getSessionId) + .containsExactly("portal-1"); + } + + private static OidcSessionInformation session(String portalSession, String keycloakSession, String subject) { + OidcIdToken idToken = new OidcIdToken("id", Instant.now(), Instant.now().plusSeconds(300), + Map.of("iss", ISSUER, "sub", subject, "sid", keycloakSession, "aud", List.of("mippublic"))); + return new OidcSessionInformation(portalSession, Map.of(), + new DefaultOidcUser(AuthorityUtils.NO_AUTHORITIES, idToken)); + } +} From d4d6657545efdeb69d1c4cc33d308261192030a7 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:31 +0200 Subject: [PATCH 12/14] fix(security)!: keep CSRF on logout and clear browser data on sign-out Only Spring's back-channel logout, which calls /logout from localhost, may skip the token. A portal must now sign out with a POST carrying the XSRF-TOKEN cookie's value. Sign-out sends Clear-Site-Data for cache and storage. It leaves out the cookies directive, which browsers apply to the whole registrable domain and would sign the user out of unrelated services; the session and hub login cookies are expired by name instead. BREAKING CHANGE: needs the platform-ui sign-out form; the default logout page's token is not accepted. --- .../configurations/SecurityConfiguration.java | 35 +++++++++++++++++- .../TermsOfUseSecurityChainTest.java | 37 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java index c0c82977..b181f392 100644 --- a/src/main/java/hbp/mip/configurations/SecurityConfiguration.java +++ b/src/main/java/hbp/mip/configurations/SecurityConfiguration.java @@ -1,6 +1,8 @@ package hbp.mip.configurations; import hbp.mip.user.ActiveUserService; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; @@ -30,8 +32,12 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; import org.springframework.security.web.context.SecurityContextHolderFilter; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; import org.springframework.security.web.session.HttpSessionEventPublisher; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.access.intercept.AuthorizationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler; @@ -131,7 +137,16 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, if (StringUtils.hasText(frontendBaseUrl)) { successHandler.setPostLogoutRedirectUri(frontendBaseUrl); } - http.logout(logout -> logout.logoutSuccessHandler(successHandler)); + http.logout(logout -> logout + // Not its cookies directive: browsers apply that to the whole registrable domain, so signing out + // of a portal on a shared domain would also sign the user out of unrelated services. + .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter( + ClearSiteDataHeaderWriter.Directive.CACHE, + ClearSiteDataHeaderWriter.Directive.STORAGE))) + .addLogoutHandler(new CookieClearingLogoutHandler( + expiredHubCookie("jupyterhub-hub-login"), expiredHubCookie("jupyterhub-session-id"))) + .deleteCookies("JSESSIONID") + .logoutSuccessHandler(successHandler)); // ---> XSRF Token handling // https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#deferred-csrf-token @@ -152,7 +167,8 @@ SecurityFilterChain clientSecurityFilterChain(HttpSecurity http, String authz = request.getHeader("Authorization"); return authz != null && authz.startsWith("Bearer "); }) - .ignoringRequestMatchers("/logout")); + // Only this instance's own call: Spring's back-channel logout posts here without a token. + .ignoringRequestMatchers(SecurityConfiguration::isLocalLogout)); // <--- XSRF Token handling } else { @@ -181,6 +197,21 @@ OidcSessionRegistry oidcSessionRegistry() { return new UserWideOidcSessionRegistry(); } + // ponytail: assumes the hub's default base path; a setting if a deployment moves it. A notebook server's own + // cookie is not cleared, because its path holds the username: it ends at the hub's next token refresh. + private static Cookie expiredHubCookie(String name) { + Cookie cookie = new Cookie(name, null); + cookie.setPath("/notebook/hub/"); + cookie.setMaxAge(0); + return cookie; + } + + private static boolean isLocalLogout(HttpServletRequest request) { + String address = request.getRemoteAddr(); + return PathPatternRequestMatcher.pathPattern("/logout").matches(request) + && ("127.0.0.1".equals(address) || "0:0:0:0:0:0:0:1".equals(address) || "::1".equals(address)); + } + static boolean isLocalOrUnset(String url) { if (!StringUtils.hasText(url)) { return true; diff --git a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java index e021d333..c4076b65 100644 --- a/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java +++ b/src/test/java/hbp/mip/configurations/TermsOfUseSecurityChainTest.java @@ -38,6 +38,7 @@ 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.RestController; @@ -63,6 +64,8 @@ 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.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -262,6 +265,40 @@ void apiDescriptionAndActuatorRootNeedALogin() throws Exception { } } + @Test + void logoutClearsTheSiteDataOverHttps() throws Exception { + mvc.perform(post("/services/logout").contextPath("/services").secure(true).session(session("alice"))) + .andExpect(header().string("Clear-Site-Data", "\"cache\", \"storage\"")) + .andExpect(cookie().maxAge("jupyterhub-hub-login", 0)) + .andExpect(cookie().path("jupyterhub-hub-login", "/notebook/hub/")); + } + + @Test + void loopbackLogoutEndsTheSessionWithoutACsrfToken() throws Exception { + // MockMvc's default remote address is 127.0.0.1: Spring's back-channel logout calls this instance from there. + MockHttpSession session = session("alice"); + + mvc.perform(post("/services/logout").contextPath("/services").session(session)) + .andExpect(status().is3xxRedirection()); + + assertThat(session.isInvalid()).isTrue(); + } + + @Test + void remoteLogoutNeedsTheCsrfToken() throws Exception { + RequestPostProcessor remote = request -> { + request.setRemoteAddr("203.0.113.5"); + return request; + }; + + mvc.perform(post("/services/logout").contextPath("/services").with(remote).session(session("alice"))) + .andExpect(status().isForbidden()); + // What the portal's sign-out form sends: the value of the XSRF-TOKEN cookie. + mvc.perform(post("/services/logout").contextPath("/services").with(remote).session(session("alice")) + .cookie(new Cookie("XSRF-TOKEN", "csrf")).param("_csrf", "csrf")) + .andExpect(status().is3xxRedirection()); + } + @Test void authenticationCanOnlyBeOffForALocalPortal() { assertThat(SecurityConfiguration.isLocalOrUnset("")).isTrue(); From 79672597d52a2c918f18074caf778baa079f6edf Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:32 +0200 Subject: [PATCH 13/14] feat(exaflow): send an API token when EXAFLOW_API_TOKEN is set Exaflow's API has no authentication, so the backend's dataset checks can be bypassed by anything that reaches it. Exaflow can now require this token. --- .../hbp/mip/algorithm/AnalysisService.java | 5 +- .../mip/algorithm/SpecificationsService.java | 5 +- .../hbp/mip/datamodel/DataModelService.java | 9 ++-- src/main/java/hbp/mip/utils/HTTPUtil.java | 13 +++-- src/main/resources/application.yml | 2 + .../hbp/mip/utils/HTTPUtilApiTokenTest.java | 53 +++++++++++++++++++ 6 files changed, 77 insertions(+), 10 deletions(-) create mode 100644 src/test/java/hbp/mip/utils/HTTPUtilApiTokenTest.java diff --git a/src/main/java/hbp/mip/algorithm/AnalysisService.java b/src/main/java/hbp/mip/algorithm/AnalysisService.java index a3348522..020a0fab 100644 --- a/src/main/java/hbp/mip/algorithm/AnalysisService.java +++ b/src/main/java/hbp/mip/algorithm/AnalysisService.java @@ -23,6 +23,9 @@ public class AnalysisService { private final String analysisUrl; + @Value("${services.exaflow.apiToken:}") + private String exaflowApiToken; + public AnalysisService(@Value("${services.exaflow.analysisUrl}") String analysisUrl) { this.analysisUrl = analysisUrl; } @@ -51,7 +54,7 @@ public AnalysisResultDTO runAnalysis(UUID requestId, AnalysisRequestDTO analysis int responseCode; var responseBody = new StringBuilder(); try { - responseCode = HTTPUtil.sendPost(analysisUrl, requestBody, responseBody); + responseCode = HTTPUtil.sendPost(analysisUrl, exaflowApiToken, requestBody, responseBody); } catch (IOException e) { logger.error("Could not run the exaflow analysis: " + e.getMessage()); throw new InternalServerError(e.getMessage()); diff --git a/src/main/java/hbp/mip/algorithm/SpecificationsService.java b/src/main/java/hbp/mip/algorithm/SpecificationsService.java index ff469f35..08b9d453 100644 --- a/src/main/java/hbp/mip/algorithm/SpecificationsService.java +++ b/src/main/java/hbp/mip/algorithm/SpecificationsService.java @@ -20,6 +20,9 @@ public class SpecificationsService { private static final Type ALGORITHM_SPECIFICATIONS_TYPE = new TypeToken>() { }.getType(); + @Value("${services.exaflow.apiToken:}") + private String exaflowApiToken; + @Value("${services.exaflow.inputdataSpecUrl}") private String inputdataSpecUrl; @@ -44,7 +47,7 @@ public List getAlgorithmSpecifications(Logger logger) private T fetch(String url, Type typeOfT, String what, Logger logger) { StringBuilder response = new StringBuilder(); try { - HTTPUtil.sendGet(url, response); + HTTPUtil.sendGet(url, exaflowApiToken, response); T specification = JsonConverters.convertJsonStringToObject(response.toString(), typeOfT); if (specification == null || (specification instanceof List list && list.isEmpty())) { throw new InternalServerError("Exaflow " + what + " response was empty."); diff --git a/src/main/java/hbp/mip/datamodel/DataModelService.java b/src/main/java/hbp/mip/datamodel/DataModelService.java index 40f850bb..920b54fc 100644 --- a/src/main/java/hbp/mip/datamodel/DataModelService.java +++ b/src/main/java/hbp/mip/datamodel/DataModelService.java @@ -24,6 +24,9 @@ public class DataModelService { @Value("${authentication.enabled}") private boolean authenticationIsEnabled; + @Value("${services.exaflow.apiToken:}") + private String exaflowApiToken; + @Value("${services.exaflow.attributesUrl}") private String exaflowAttributesUrl; @@ -72,7 +75,7 @@ private List getAggregatedDataModelDTOs(Logger logger) { try { StringBuilder response = new StringBuilder(); - HTTPUtil.sendGet(exaflowAttributesUrl, response); + HTTPUtil.sendGet(exaflowAttributesUrl, exaflowApiToken, response); Map convertedResponse = JsonConverters.convertJsonStringToObject(response.toString(), pathologyAttributesType); exaflowDataModelAttributes = convertedResponse != null ? convertedResponse : Collections.emptyMap(); @@ -83,7 +86,7 @@ private List getAggregatedDataModelDTOs(Logger logger) { try { StringBuilder response = new StringBuilder(); - HTTPUtil.sendGet(exaflowDatasetsVariables, response); + HTTPUtil.sendGet(exaflowDatasetsVariables, exaflowApiToken, response); Map>> convertedResponse = JsonConverters.convertJsonStringToObject(response.toString(), datasetsVariablesType); datasetsVariablesByDataModel = convertedResponse != null ? convertedResponse : Collections.emptyMap(); } catch (Exception e) { @@ -93,7 +96,7 @@ private List getAggregatedDataModelDTOs(Logger logger) { try { StringBuilder response = new StringBuilder(); - HTTPUtil.sendGet(exaflowCDEsMetadataUrl, response); + HTTPUtil.sendGet(exaflowCDEsMetadataUrl, exaflowApiToken, response); Map> convertedResponse = JsonConverters.convertJsonStringToObject(response.toString(), cdesMetadataType); datasetEnumerationsByDataModel = convertedResponse != null ? extractDatasetEnumerations(convertedResponse) : Collections.emptyMap(); } catch (Exception e) { diff --git a/src/main/java/hbp/mip/utils/HTTPUtil.java b/src/main/java/hbp/mip/utils/HTTPUtil.java index 1f923805..a31a8e10 100644 --- a/src/main/java/hbp/mip/utils/HTTPUtil.java +++ b/src/main/java/hbp/mip/utils/HTTPUtil.java @@ -16,19 +16,22 @@ private HTTPUtil() { throw new IllegalAccessError("HTTPUtil class"); } - public static void sendGet(String url, StringBuilder resp) throws IOException { - sendHTTP(url, "", resp, "GET"); + public static void sendGet(String url, String apiToken, StringBuilder resp) throws IOException { + sendHTTP(url, apiToken, "", resp, "GET"); } - public static int sendPost(String url, String query, StringBuilder resp) throws IOException { - return sendHTTP(url, query, resp, "POST"); + public static int sendPost(String url, String apiToken, String query, StringBuilder resp) throws IOException { + return sendHTTP(url, apiToken, query, resp, "POST"); } - private static int sendHTTP(String url, String query, StringBuilder resp, String httpVerb) + private static int sendHTTP(String url, String apiToken, String query, StringBuilder resp, String httpVerb) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + if (apiToken != null && !apiToken.isBlank()) { + con.setRequestProperty("Authorization", "Bearer " + apiToken); + } if (!"GET".equals(httpVerb)) { con.setRequestMethod(httpVerb); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 8762f1dc..409a6dfd 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -71,6 +71,8 @@ authentication: ### EXTERNAL SERVICES ### services: exaflow: + # Sent as a Bearer token to Exaflow, which requires it when its EXAFLOW_API_TOKEN is set. + apiToken: ${EXAFLOW_API_TOKEN:} analysisUrl: ${EXAFLOW_URL:http://127.0.0.1:5000}/analysis inputdataSpecUrl: ${EXAFLOW_URL:http://127.0.0.1:5000}/specifications/inputdata preprocessingSpecUrl: ${EXAFLOW_URL:http://127.0.0.1:5000}/specifications/preprocessing diff --git a/src/test/java/hbp/mip/utils/HTTPUtilApiTokenTest.java b/src/test/java/hbp/mip/utils/HTTPUtilApiTokenTest.java new file mode 100644 index 00000000..2a3590be --- /dev/null +++ b/src/test/java/hbp/mip/utils/HTTPUtilApiTokenTest.java @@ -0,0 +1,53 @@ +package hbp.mip.utils; + +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Exaflow requires this header when its EXAFLOW_API_TOKEN is set. */ +class HTTPUtilApiTokenTest { + + private final AtomicReference authorization = new AtomicReference<>(); + private HttpServer server; + private String url; + + @BeforeEach + void setUp() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + authorization.set(exchange.getRequestHeaders().getFirst("Authorization")); + exchange.sendResponseHeaders(204, -1); + exchange.close(); + }); + server.start(); + url = "http://127.0.0.1:" + server.getAddress().getPort() + "/analysis"; + } + + @AfterEach + void tearDown() { + server.stop(0); + } + + @Test + void getAndPostSendTheTokenWhenSet() throws IOException { + HTTPUtil.sendGet(url, "secret", new StringBuilder()); + assertThat(authorization.get()).isEqualTo("Bearer secret"); + + authorization.set(null); + HTTPUtil.sendPost(url, "secret", "{}", new StringBuilder()); + assertThat(authorization.get()).isEqualTo("Bearer secret"); + } + + @Test + void noTokenSendsNoHeader() throws IOException { + HTTPUtil.sendGet(url, "", new StringBuilder()); + assertThat(authorization.get()).isNull(); + } +} From 6baeb00ce55b3f53275995136ddb728a34cb3ad2 Mon Sep 17 00:00:00 2001 From: KFilippopolitis Date: Fri, 6 Nov 2026 19:06:32 +0200 Subject: [PATCH 14/14] docs(context): document session lifetimes and how sessions end ASVS 5 V7.1 asks for this. Tested with a local Keycloak: disabling a user sends no logout, so administrators must also use Sign out. --- docs/context/session-management.md | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/context/session-management.md diff --git a/docs/context/session-management.md b/docs/context/session-management.md new file mode 100644 index 00000000..a4491fda --- /dev/null +++ b/docs/context/session-management.md @@ -0,0 +1,41 @@ +# Session Management + +What ASVS 5 V7.1 asks to document. Values are defaults in `application.yml`; operators can override them. + +## Timeouts + +| Session | Idle | Maximum | Set by | +|---|---|---|---| +| Portal (`JSESSIONID`) | 30 minutes (`SESSION_IDLE_TIMEOUT`) | 8 hours (`SESSION_MAX_AGE`) | This backend | +| Bearer access token | None | About 5 minutes | Keycloak realm | +| Laptop sign-in (offline refresh token) | 30 days | 180 days | Keycloak client `mip-cli-` | +| Keycloak SSO | Realm setting | Realm setting | EBRAINS | +| JupyterHub | Not set here | Not set here | JupyterHub defaults | + +Why these values: MIP handles research data, not transactions, and analyses run for a working day. 8 hours bounds how long roles taken at login stay in effect. Because Keycloak SSO usually survives, an ended portal session normally signs in again without a password. MFA and NIST 800-63B re-authentication rules depend on EBRAINS; Unknown / TODO: verify with its operators. + +## Concurrent sessions + +Not limited. One account may hold several portal sessions, laptop sign-ins and a hub session. Reaching a limit therefore has no behaviour to describe. + +## How the systems end sessions + +| Event | Portal | Bearer tokens | Laptop sign-in | JupyterHub | +|---|---|---|---|---| +| Portal sign-out | Ended here and at Keycloak | Expire within minutes | Not affected | Its login cookies are expired on sign-out; a notebook server's own cookie lasts until the next token refresh, which is refused | +| Keycloak ends the session, or an admin uses *Sign out* on the user | All the user's portal sessions end by back-channel logout, if configured below | Expire within minutes | Refused at next renewal | Refused at next token refresh | +| Keycloak disables the user, without *Sign out* | Continues until a timeout (at most 8 hours): Keycloak sends no logout | Refused at next renewal | Refused at next renewal | Refused at next token refresh | +| `mip logout` | Not affected | Expire within minutes | Revoked | Not affected | +| Role removed in Keycloak | At next login, at most 8 hours | Within minutes | At next renewal | At next token refresh | + +## Operator setup + +- Back-channel logout needs the platform client's *Backchannel Logout URL* set to `https:///services/logout/connect/back-channel/keycloak`. Without it, a signed-out user's portal session lasts until one of the timeouts above. +- 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. + +## Not available + +- Administrators cannot end one portal session from an interface. To remove someone at once, disable the user in Keycloak and then use *Sign out* on that user; this needs back-channel logout. Restarting the backend ends all. +- Users cannot list their portal sessions. The Keycloak account console lists its own sessions.