diff --git a/README.md b/README.md index b80567c..6162d82 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ This slice provides an internal, bounded authentication foundation: - container and Helm packaging for local Kubernetes SIT; - `POST /api/v1/auth/login` with validated credentials and signed JWT issuance; - `POST /api/v1/auth/logout` with server-side, idempotent session revocation; +- `GET /api/v1/auth/session` with bearer-protected validation against signed JWT claims and PostgreSQL session state; - configurable `REVOKE_PREVIOUS` or `ALLOW_MULTIPLE` session policy, defaulting conservatively to `REVOKE_PREVIOUS`; - PostgreSQL-backed session persistence with Flyway migrations, durable token lookup, and replica-safe same-user session policy; - Maven verification with Spotless, JaCoCo, Surefire, and Failsafe. @@ -85,6 +86,7 @@ The current integration tests start the application on a random port and verify: - `/actuator/health` returns `200` and `UP`; - `/v3/api-docs` returns the explicit service title, internal description, contract version `1.0.0`, and both auth paths; +- session validation returns the authenticated subject and session ID only while the signed token and server-side session remain valid; - login returns a JWT with signed `sub`, `sid`, `active`, `iss`, `iat`, and `exp` claims, plus the configured space-delimited `scope` claim when scopes are configured; - logout revokes the session server-side and is idempotent; - Flyway creates the session table, and concurrent `REVOKE_PREVIOUS` opens leave only one session active. @@ -139,7 +141,16 @@ Authorization: Bearer Logout returns `204 No Content`. Repeating the request with the same valid token returns `204` again. A valid token alone is not sufficient for future protected-service authorization after its session is revoked; consumers must use the session validation application port until a later gateway/service authorization slice exists. -Errors use RFC 7807 `ProblemDetail`: validation failures are `400` with `type` ending in `validation-error`; invalid credentials are `401` with `type` ending in `authentication-failed`; malformed, missing, expired, or revoked bearer tokens are `401` with `type` ending in `invalid-token`. +### Session validation + +```http +GET /api/v1/auth/session +Authorization: Bearer +``` + +An active session returns `200 OK` with `username` and `sessionId`. The endpoint checks the signed JWT and authoritative PostgreSQL session state, so a token from a later `REVOKE_PREVIOUS` login or logout returns the existing RFC 7807 `401` authentication failure. This endpoint is service-local and does not add an API Gateway route. + +Errors use RFC 7807 `ProblemDetail`: validation failures are `400` with `type` ending in `validation-error`; invalid credentials and revoked session state during validation are `401` with `type` ending in `authentication-failed`; malformed, missing, or expired bearer tokens are `401` with `type` ending in `invalid-token`. ## Container diff --git a/docs/insomnia/auth-service.md b/docs/insomnia/auth-service.md index d9173d4..5f70989 100644 --- a/docs/insomnia/auth-service.md +++ b/docs/insomnia/auth-service.md @@ -27,6 +27,15 @@ Content-Type: application/json Expected response: `200 OK` with `accessToken`, `tokenType`, `sessionId`, and `expiresAt`. Copy the returned access token to `auth_access_token` for the logout request. The decoded JWT contains signed `sub`, `sid`, `active`, `iss`, `iat`, and `exp` claims, plus the configured space-delimited `scope` claim when scopes are configured; `active` is `true` when issued and `sid` matches `sessionId`. Current authorization still requires the server-side session to remain active. +## Session validation + +```http +GET {{ auth_base_url }}/api/v1/auth/session +Authorization: Bearer {{ auth_access_token }} +``` + +Expected response: `200 OK` with the authenticated `username` and `sessionId`. Validation checks both the signed token and the authoritative PostgreSQL session state. A token revoked by logout or a later `REVOKE_PREVIOUS` login returns the existing RFC 7807 `401` authentication failure. + ## Logout ```http diff --git a/src/main/java/com/digitalbank/authservice/adapter/in/web/AuthController.java b/src/main/java/com/digitalbank/authservice/adapter/in/web/AuthController.java index 78f5d59..7d542a3 100644 --- a/src/main/java/com/digitalbank/authservice/adapter/in/web/AuthController.java +++ b/src/main/java/com/digitalbank/authservice/adapter/in/web/AuthController.java @@ -4,6 +4,8 @@ import com.digitalbank.authservice.application.port.in.LoginInputPort; import com.digitalbank.authservice.application.port.in.LogoutCommand; import com.digitalbank.authservice.application.port.in.LogoutInputPort; +import com.digitalbank.authservice.application.port.in.ValidateSessionCommand; +import com.digitalbank.authservice.application.port.in.ValidateSessionInputPort; import com.digitalbank.authservice.domain.exception.InvalidTokenException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; @@ -16,6 +18,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -29,10 +32,15 @@ class AuthController { private final LoginInputPort loginInputPort; private final LogoutInputPort logoutInputPort; + private final ValidateSessionInputPort validateSessionInputPort; - AuthController(LoginInputPort loginInputPort, LogoutInputPort logoutInputPort) { + AuthController( + LoginInputPort loginInputPort, + LogoutInputPort logoutInputPort, + ValidateSessionInputPort validateSessionInputPort) { this.loginInputPort = loginInputPort; this.logoutInputPort = logoutInputPort; + this.validateSessionInputPort = validateSessionInputPort; } @PostMapping( @@ -72,11 +80,28 @@ ResponseEntity login(@Valid @RequestBody LoginRequest request) { mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetail.class))) ResponseEntity logout(@RequestHeader(name = "Authorization", required = false) String authorization) { - logoutInputPort.logout(new LogoutCommand(extractBearerToken(authorization))); + logoutInputPort.logout(new LogoutCommand(bearerToken(authorization))); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } - private String extractBearerToken(String authorization) { + @GetMapping(value = "/api/v1/auth/session", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(summary = "Validate the current authentication session") + @SecurityRequirement(name = "bearerAuth") + @ApiResponse(responseCode = "200", description = "Authentication session is active") + @ApiResponse( + responseCode = "401", + description = "Bearer token is missing, invalid, or revoked", + content = + @Content( + mediaType = "application/problem+json", + schema = @Schema(implementation = ProblemDetail.class))) + ResponseEntity validateSession( + @RequestHeader(name = "Authorization", required = false) String authorization) { + var result = validateSessionInputPort.validate(new ValidateSessionCommand(bearerToken(authorization))); + return ResponseEntity.ok(SessionValidationResponse.from(result)); + } + + private String bearerToken(String authorization) { if (authorization == null || !authorization.startsWith(BEARER_PREFIX) || authorization.substring(BEARER_PREFIX.length()).isBlank()) { diff --git a/src/main/java/com/digitalbank/authservice/adapter/in/web/SessionValidationResponse.java b/src/main/java/com/digitalbank/authservice/adapter/in/web/SessionValidationResponse.java new file mode 100644 index 0000000..8813108 --- /dev/null +++ b/src/main/java/com/digitalbank/authservice/adapter/in/web/SessionValidationResponse.java @@ -0,0 +1,12 @@ +package com.digitalbank.authservice.adapter.in.web; + +import com.digitalbank.authservice.application.port.in.SessionValidationResult; +import java.util.UUID; + +record SessionValidationResponse(String username, UUID sessionId) { + + static SessionValidationResponse from(SessionValidationResult result) { + return new SessionValidationResponse( + result.username(), result.sessionId().value()); + } +} diff --git a/src/test/java/com/digitalbank/authservice/AuthApiIT.java b/src/test/java/com/digitalbank/authservice/AuthApiIT.java index af920fb..548e362 100644 --- a/src/test/java/com/digitalbank/authservice/AuthApiIT.java +++ b/src/test/java/com/digitalbank/authservice/AuthApiIT.java @@ -63,6 +63,38 @@ void loginReturnsSignedTokenWithSessionId() throws Exception { .isGreaterThan(payload.path("iat").asLong()); } + @Test + void sessionValidationReturnsActiveSessionAndRejectsRevokedPriorToken() throws Exception { + var firstLogin = postJson( + "/api/v1/auth/login", "{\"username\":\"alice@example.com\",\"password\":\"correct-password\"}"); + var firstBody = objectMapper.readTree(firstLogin.body()); + var firstToken = firstBody.path("accessToken").asText(); + + var activeSession = getWithBearer("/api/v1/auth/session", firstToken); + var activeBody = objectMapper.readTree(activeSession.body()); + + assertThat(activeSession.statusCode()).isEqualTo(200); + assertThat(activeBody.path("username").asText()).isEqualTo("alice@example.com"); + assertThat(activeBody.path("sessionId").asText()) + .isEqualTo(firstBody.path("sessionId").asText()); + + var secondLogin = postJson( + "/api/v1/auth/login", "{\"username\":\"alice@example.com\",\"password\":\"correct-password\"}"); + var secondToken = + objectMapper.readTree(secondLogin.body()).path("accessToken").asText(); + + var revokedPriorSession = getWithBearer("/api/v1/auth/session", firstToken); + var currentSession = getWithBearer("/api/v1/auth/session", secondToken); + + assertThat(revokedPriorSession.statusCode()).isEqualTo(401); + assertThat(objectMapper + .readTree(revokedPriorSession.body()) + .path("type") + .asText()) + .isEqualTo("https://digital-bank-java.local/problems/authentication-failed"); + assertThat(currentSession.statusCode()).isEqualTo(200); + } + @Test void unknownAndWrongPasswordReturnSameUnauthorizedProblem() throws Exception { var unknown = postJson( @@ -129,6 +161,15 @@ private HttpResponse postWithBearer(String path, String token) throws Ex return httpClient.send(request, HttpResponse.BodyHandlers.ofString()); } + private HttpResponse getWithBearer(String path, String token) throws Exception { + var request = HttpRequest.newBuilder() + .uri(URI.create("http://localhost:" + port + path)) + .header("Authorization", "Bearer " + token) + .GET() + .build(); + return httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } + private JsonNode decodeJwtPayload(String token) throws Exception { var encodedPayload = token.split("\\.", -1)[1]; return objectMapper.readTree(java.util.Base64.getUrlDecoder().decode(encodedPayload)); diff --git a/src/test/java/com/digitalbank/authservice/AuthServiceApplicationIT.java b/src/test/java/com/digitalbank/authservice/AuthServiceApplicationIT.java index 59113c7..1cae9f3 100644 --- a/src/test/java/com/digitalbank/authservice/AuthServiceApplicationIT.java +++ b/src/test/java/com/digitalbank/authservice/AuthServiceApplicationIT.java @@ -79,6 +79,12 @@ void openApiEndpointReturnsExplicitMetadata() throws Exception { .path("responses") .has("204")) .isTrue(); + assertThat(document.path("paths") + .path("/api/v1/auth/session") + .path("get") + .path("responses") + .has("200")) + .isTrue(); } private HttpResponse get(String path) throws Exception {