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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/context/module-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,15 @@ 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`

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.

Expand Down
3 changes: 1 addition & 2 deletions docs/context/risk-register.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
|---|---|---|---|---|
| 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 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 |
Expand Down
41 changes: 41 additions & 0 deletions docs/context/session-management.md
Original file line number Diff line number Diff line change
@@ -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-<federation>` |
| 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://<publicHost>/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.
14 changes: 14 additions & 0 deletions src/main/java/hbp/mip/algorithm/AnalysisRequestDTO.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -11,6 +15,16 @@ public record AnalysisRequestDTO(
AnalysisAlgorithmDTO algorithm,
Map<String, Object> 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<String> datasets,
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/hbp/mip/algorithm/AnalysisService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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());
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/hbp/mip/algorithm/SpecificationsService.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public class SpecificationsService {
private static final Type ALGORITHM_SPECIFICATIONS_TYPE = new TypeToken<List<AlgorithmSpecificationDTO>>() {
}.getType();

@Value("${services.exaflow.apiToken:}")
private String exaflowApiToken;

@Value("${services.exaflow.inputdataSpecUrl}")
private String inputdataSpecUrl;

Expand All @@ -44,7 +47,7 @@ public List<AlgorithmSpecificationDTO> getAlgorithmSpecifications(Logger logger)
private <T> 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.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {

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

Expand All @@ -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) {
Expand Down Expand Up @@ -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);
}
}
Loading
Loading