From 2c68cd55081c1309cc22f33bb8a8bd7a6572cebb Mon Sep 17 00:00:00 2001 From: Andres Contreras Date: Sat, 31 Oct 2026 17:39:56 -0700 Subject: [PATCH] Check current token state after verified JWT admission --- .../security/api/domain/BearerToken.java | 5 + .../api/domain/BearerTokenRenderingTest.java | 24 ++ .../docs/live-active-state-admission.md | 41 ++++ modules/security-resource-server/pom.xml | 6 + .../security/rs/LiveActiveJwtDecoder.java | 189 ++++++++++++++++ .../rs/LiveIntrospectionResponseGuard.java | 142 ++++++++++++ .../rs/ResourceServerAutoConfiguration.java | 38 ++++ .../security/rs/ResourceServerProperties.java | 19 ++ .../rs/SpringLiveTokenValidationAdapter.java | 205 ++++++++++++++++++ .../security/rs/LiveActiveJwtDecoderTest.java | 60 +++++ .../rs/LiveIntrospectionPrivacyTest.java | 104 +++++++++ .../LiveIntrospectionResponseGuardTest.java | 189 ++++++++++++++++ .../security/rs/LiveJwtChainAdoptionTest.java | 127 +++++++++++ .../rs/LiveJwtNativeVerificationTest.java | 70 ++++++ .../security/spi/TokenValidationPort.java | 8 + .../LiveValidationDefaultContractTest.java | 26 +++ 16 files changed, 1253 insertions(+) create mode 100644 modules/security-api/src/test/java/org/fireflyframework/security/api/domain/BearerTokenRenderingTest.java create mode 100644 modules/security-resource-server/docs/live-active-state-admission.md create mode 100644 modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveActiveJwtDecoder.java create mode 100644 modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuard.java create mode 100644 modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/SpringLiveTokenValidationAdapter.java create mode 100644 modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveActiveJwtDecoderTest.java create mode 100644 modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionPrivacyTest.java create mode 100644 modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuardTest.java create mode 100644 modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtChainAdoptionTest.java create mode 100644 modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtNativeVerificationTest.java create mode 100644 modules/security-spi/src/test/java/org/fireflyframework/security/spi/LiveValidationDefaultContractTest.java diff --git a/modules/security-api/src/main/java/org/fireflyframework/security/api/domain/BearerToken.java b/modules/security-api/src/main/java/org/fireflyframework/security/api/domain/BearerToken.java index 38757b055..29fd82b43 100644 --- a/modules/security-api/src/main/java/org/fireflyframework/security/api/domain/BearerToken.java +++ b/modules/security-api/src/main/java/org/fireflyframework/security/api/domain/BearerToken.java @@ -40,6 +40,11 @@ private static TokenType classify(String value) { return dots == 2 ? TokenType.JWT : TokenType.OPAQUE; } + @Override + public final String toString() { + return "BearerToken[REDACTED]"; + } + /** @return the token value masked for safe logging. */ public String masked() { if (value == null || value.length() <= 8) { diff --git a/modules/security-api/src/test/java/org/fireflyframework/security/api/domain/BearerTokenRenderingTest.java b/modules/security-api/src/test/java/org/fireflyframework/security/api/domain/BearerTokenRenderingTest.java new file mode 100644 index 000000000..654701198 --- /dev/null +++ b/modules/security-api/src/test/java/org/fireflyframework/security/api/domain/BearerTokenRenderingTest.java @@ -0,0 +1,24 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.api.domain; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +class BearerTokenRenderingTest { + @Test void diagnosticRenderingNeverExposesCredentialOrFragments(){var token=BearerToken.of("PRIVATE_ACCESS_TOKEN_HEAD.middle.PRIVATE_TAIL");assertEquals("BearerToken[REDACTED]",token.toString());assertFalse(token.toString().contains("PRIVATE"));} + @Test void credentialComponentsAndClassificationRemainAvailableToTheInternalPort(){var token=BearerToken.of("a.b.c");assertEquals("a.b.c",token.value());assertEquals(BearerToken.TokenType.JWT,token.type());assertEquals("****",token.masked());} + @Test void redactedOverrideRetainsPublishedFinalModifier()throws Exception{assertTrue(java.lang.reflect.Modifier.isFinal(BearerToken.class.getDeclaredMethod("toString").getModifiers()));} +} diff --git a/modules/security-resource-server/docs/live-active-state-admission.md b/modules/security-resource-server/docs/live-active-state-admission.md new file mode 100644 index 000000000..b3b987138 --- /dev/null +++ b/modules/security-resource-server/docs/live-active-state-admission.md @@ -0,0 +1,41 @@ +# Optional LIVE JWT admission + +This source addition requires a matching qualified whole-framework release. It is not included in version 26.10.23. + +LIVE adds optional current-state admission after local JWT verification. Confirm the provider response contract and qualify the application security chain before enabling this mode in a deployment. + +`LOCAL_JWT` remains the general default. It retains signature, issuer, audience and time validation. An unexpired locally verified JWT does not by itself establish that its provider account or session is currently active. + +Explicit `LIVE` first uses the existing JWT decoder and then calls `TokenValidationPort.validateLive` for the same credential on each subscription. Existing port implementations refuse this additive method by default. The owned implementation uses Spring Security's native remote introspector, standard JDK HTTPS transport and managed Jackson3 codecs. No IdP name, adapter class, client alias, cache health or local token parser implies LIVE support. + +```yaml +firefly: + security: + resource-server: + admission-mode: LIVE + issuer: ${OIDC_EXPECTED_ISSUER} + audiences: [${OIDC_RESOURCE_AUDIENCE}] + live-state: + introspection-uri: ${OIDC_INTROSPECTION_HTTPS_URI} + introspection-client-id: ${OIDC_INTROSPECTION_CLIENT_ID} + introspection-client-secret: ${OIDC_INTROSPECTION_CLIENT_SECRET} + token-client-claim: ${OIDC_SIGNED_CLIENT_CLAIM} + allowed-clients: [${OIDC_ALLOWED_CLIENT}] + timeout: 5s +``` + +Use one explicitly configured signed client claim, such as the exact `azp` or `client_id` defined by the trusted issuer. There is no automatic alias or token-derived endpoint discovery. Configuration and credentials are snapshotted when the adapter/decorator is constructed. Rotate them through a newly constructed configured instance. + +The active response must contain actual Boolean `active` and correctly typed issuer, opaque subject, client_id, audience and integral expiration. The verified issuer, subject, client, audience set and expiration must match exactly; a signed token ID must also match. Opaque identifiers are not UUIDs and are not trimmed or normalized. Missing, malformed, duplicate, ambiguous or mismatched metadata refuses. Active=false may omit identity metadata and still refuses. Identity metadata is used only for the check: the exact locally verified Jwt continues to the existing principal converter, without provider role, claim or tenant merging. + +The original per-subscription authentication window includes local verification and live admission. It is at most 5 seconds and additionally clipped to the verified token's original expiration. Timeout, empty, unsupported or failed results cannot become local/stale success. There is no positive cache or retry. Response bytes, including error bodies, are limited to 16 KiB before native coercion; duplicate keys, invalid UTF-8 and wrong wire types refuse. Errors have fixed messages without raw causes. The native Jackson codec receives Spring's supported suppress-logging hint. The existing internal BearerToken carrier renders a constant redaction; its value/type/masked APIs remain available and must not be logged. + +The owned client uses an explicit HTTPS endpoint with ordinary platform trust/hostname validation, redirects disabled and finite connect/read timeouts. It owns only the client it constructs. A supplied custom introspector remains caller-owned and must actually implement the uncached current-state contract. Close/cancel propagate through supported APIs; no guarantee of physical socket/thread termination or provider revocation follows from this mode. + +## Custom security chains + +The default Jafly chain wraps its injected decoder in LIVE mode. An application that completely replaces SecurityWebFilterChain must explicitly use `new LiveActiveJwtDecoder(localDecoder, livePort, properties)` in its own native Spring JWT DSL and qualify actual protected routes. A property or port bean alone cannot prove arbitrary custom-chain adoption. The retained direct five-argument default-chain factory supports LOCAL_JWT; it refuses a LIVE request without the explicit port. + +## Deployment verification + +Verify actual protected routes with the configured issuer, audience, signed client claim and current-state response. Provider acceptance must prove the required disable, logout and permanent-account-block behavior with old unexpired credentials and new session attempts. RFC 7662 active-state semantics alone do not establish that behavior. Account locking, SCA recovery, delegation and token exchange require their own application and identity-service contracts. diff --git a/modules/security-resource-server/pom.xml b/modules/security-resource-server/pom.xml index 5b18064e0..7b377e900 100644 --- a/modules/security-resource-server/pom.xml +++ b/modules/security-resource-server/pom.xml @@ -53,6 +53,12 @@ provided + + + tools.jackson.core + jackson-databind + + org.springframework.boot diff --git a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveActiveJwtDecoder.java b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveActiveJwtDecoder.java new file mode 100644 index 000000000..7e0da935d --- /dev/null +++ b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveActiveJwtDecoder.java @@ -0,0 +1,189 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import org.fireflyframework.security.api.domain.BearerToken; +import org.fireflyframework.security.api.domain.SecurityPrincipal; +import org.fireflyframework.security.spi.TokenValidationPort; +import org.springframework.security.oauth2.jwt.BadJwtException; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; +import reactor.core.publisher.Mono; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.LongSupplier; + +/** Adds uncached current-state admission to a locally verified JWT without replacing its claims. */ +public final class LiveActiveJwtDecoder implements ReactiveJwtDecoder { + private final ReactiveJwtDecoder local; + private final TokenValidationPort live; + private final Settings settings; + private final Clock clock; + private final LongSupplier nanos; + + public LiveActiveJwtDecoder(ReactiveJwtDecoder local, TokenValidationPort live, + ResourceServerProperties properties) { + this(local, live, properties, Clock.systemUTC(), System::nanoTime); + } + + public LiveActiveJwtDecoder(ReactiveJwtDecoder local, TokenValidationPort live, + ResourceServerProperties properties, Clock clock, LongSupplier nanos) { + this.local = Objects.requireNonNull(local); + this.live = Objects.requireNonNull(live); + this.settings = Settings.from(properties); + this.clock = Objects.requireNonNull(clock); + this.nanos = Objects.requireNonNull(nanos); + } + + @Override + public Mono decode(String token) { + return Mono.defer(() -> { + long start = nanos.getAsLong(); + return Mono.defer(() -> local.decode(token)) + .switchIfEmpty(Mono.error(refused())) + .flatMap(jwt -> { + Binding original = Binding.local(jwt, settings); + Duration remaining = remaining(start, original.expiration()); + return Mono.defer(() -> live.validateLive(BearerToken.of(token))) + .switchIfEmpty(Mono.error(refused())) + .timeout(remaining) + .map(principal -> { + Binding observed = Binding.remote(principal, settings); + if (!original.matches(observed)) { + throw refused(); + } + if (!original.equals(Binding.local(jwt, settings))) { + throw refused(); + } + remaining(start, original.expiration()); + return jwt; + }); + }) + .timeout(settings.timeout()) + .onErrorMap(error -> refused()); + }).onErrorMap(error -> refused()); + } + + private Duration remaining(long start, Instant expiration) { + long elapsed = nanos.getAsLong() - start; + if (elapsed < 0 || elapsed >= settings.timeout().toNanos()) { + throw refused(); + } + Duration untilExpiration = Duration.between(clock.instant(), expiration); + Duration work = Duration.ofNanos(settings.timeout().toNanos() - elapsed); + Duration remaining = work.compareTo(untilExpiration) < 0 ? work : untilExpiration; + if (remaining.isNegative() || remaining.isZero()) { + throw refused(); + } + return remaining; + } + + private static BadJwtException refused() { + return new BadJwtException("Live token admission refused"); + } + + static String text(Object value) { + if (!(value instanceof String text) || text.isBlank() || text.length() > 2048) { + throw new IllegalArgumentException("Invalid live token metadata"); + } + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (Character.isISOControl(c) || Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Invalid live token metadata"); + } + if (Character.isHighSurrogate(c)) { + if (++i == text.length() || !Character.isLowSurrogate(text.charAt(i))) { + throw new IllegalArgumentException("Invalid live token metadata"); + } + } + } + return text; + } + + static Set audience(Object value) { + if (!(value instanceof List list) || list.isEmpty() || list.size() > 32) { + throw new IllegalArgumentException("Invalid live token audience"); + } + Set result = new HashSet<>(); + for (Object item : list) { + if (!result.add(text(item))) { + throw new IllegalArgumentException("Invalid live token audience"); + } + } + return Set.copyOf(result); + } + + record Settings(String issuer, Set audiences, Set clients, String clientClaim, + Duration timeout) { + static Settings from(ResourceServerProperties properties) { + if (properties == null || properties.getAdmissionMode() != ResourceServerProperties.JwtAdmissionMode.LIVE + || properties.getLiveState() == null) { + throw new IllegalArgumentException("Live admission configuration is required"); + } + var live = properties.getLiveState(); + Duration timeout = live.getTimeout(); + if (timeout == null || timeout.isZero() || timeout.isNegative() + || timeout.compareTo(Duration.ofSeconds(5)) > 0) { + throw new IllegalArgumentException("Live admission timeout must be positive and at most five seconds"); + } + return new Settings(text(properties.getIssuer()), audience(properties.getAudiences()), + audience(live.getAllowedClients()), text(live.getTokenClientClaim()), timeout); + } + @Override public String toString() { return "LiveSettings[REDACTED]"; } + } + + record Binding(String issuer, String subject, Set audiences, String client, + Instant expiration, String tokenId) { + static Binding local(Jwt jwt, Settings settings) { + return read(jwt.getClaims(), settings.clientClaim(), settings); + } + static Binding remote(SecurityPrincipal principal, Settings settings) { + Binding binding = read(principal.claims(), "client_id", settings); + if (!binding.issuer().equals(principal.issuer()) || !binding.subject().equals(principal.subject())) { + throw refused(); + } + return binding; + } + private static Binding read(Map claims, String clientClaim, Settings settings) { + String issuer = text(claims.get("iss")); + String subject = text(claims.get("sub")); + Set audiences = audience(claims.get("aud")); + String client = text(claims.get(clientClaim)); + if (!(claims.get("exp") instanceof Instant expiration) + || !issuer.equals(settings.issuer()) || !settings.clients().contains(client) + || audiences.stream().noneMatch(settings.audiences()::contains)) { + throw refused(); + } + String tokenId = claims.containsKey("jti") ? text(claims.get("jti")) : null; + return new Binding(issuer, subject, audiences, client, expiration, tokenId); + } + boolean matches(Binding observed) { + return issuer.equals(observed.issuer) && subject.equals(observed.subject) + && audiences.equals(observed.audiences) && client.equals(observed.client) + && expiration.equals(observed.expiration) + && (tokenId == null || tokenId.equals(observed.tokenId)); + } + @Override public String toString() { return "LiveBinding[REDACTED]"; } + } +} diff --git a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuard.java b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuard.java new file mode 100644 index 000000000..b048b7190 --- /dev/null +++ b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuard.java @@ -0,0 +1,142 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import org.springframework.web.reactive.function.client.ExchangeFunction; +import reactor.core.publisher.Mono; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.HashSet; + +/** Validates bounded wire types before the native introspector performs claim coercion. */ +public final class LiveIntrospectionResponseGuard implements ExchangeFilterFunction { + public static final int MAX_RESPONSE_BYTES = 16 * 1024; + private final JsonMapper mapper = JsonMapper.builder(JsonFactory.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .streamReadConstraints(StreamReadConstraints.builder() + .maxDocumentLength(MAX_RESPONSE_BYTES).maxNestingDepth(16).maxTokenCount(4096) + .maxNameLength(256).maxStringLength(MAX_RESPONSE_BYTES).maxNumberLength(32).build()) + .build()).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build(); + + @Override + public Mono filter(ClientRequest request, ExchangeFunction next) { + return Mono.defer(() -> next.exchange(request)) + .flatMap(response -> DataBufferUtils.join(response.bodyToFlux(org.springframework.core.io.buffer.DataBuffer.class), + MAX_RESPONSE_BYTES) + .switchIfEmpty(Mono.error(refused())) + .map(buffer -> { + byte[] bytes; + try { + bytes = new byte[buffer.readableByteCount()]; + buffer.read(bytes); + } finally { + DataBufferUtils.release(buffer); + } + try { + if (response.statusCode().value() != 200) { + throw refused(); + } + MediaType type = response.headers().contentType().orElseThrow(LiveIntrospectionResponseGuard::refused); + if (!MediaType.APPLICATION_JSON.isCompatibleWith(type) + || (type.getCharset() != null && !StandardCharsets.UTF_8.equals(type.getCharset()))) { + throw refused(); + } + String body = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)).toString(); + validate(mapper.readTree(body)); + return response.mutate().body(body).build(); + } catch (Exception error) { + throw refused(); + } + })) + .onErrorMap(error -> refused()); + } + + private static void validate(JsonNode root) { + if (!root.isObject() || root.get("active") == null || !root.get("active").isBoolean()) { + throw refused(); + } + if (!root.get("active").asBoolean()) { + return; + } + string(root.get("iss")); + string(root.get("sub")); + string(root.get("client_id")); + JsonNode audience = root.get("aud"); + if (audience == null) { + throw refused(); + } + if (audience.isString()) { + string(audience); + } else if (audience.isArray() && audience.size() > 0 && audience.size() <= 32) { + var seen = new HashSet(); + for (int i = 0; i < audience.size(); i++) { + if (!seen.add(string(audience.get(i)))) { + throw refused(); + } + } + } else { + throw refused(); + } + time(root.get("exp")); + for (String optional : new String[]{"iat", "nbf"}) { + if (root.get(optional) != null) { + time(root.get(optional)); + } + } + for (String optional : new String[]{"jti", "scope"}) { + if (root.get(optional) != null) { + string(root.get(optional)); + } + } + } + + private static String string(JsonNode node) { + if (node == null || !node.isString()) { + throw refused(); + } + return LiveActiveJwtDecoder.text(node.stringValue()); + } + + private static void time(JsonNode node) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong() || node.asLong() <= 0) { + throw refused(); + } + Instant.ofEpochSecond(node.asLong()); + } + + private static OAuth2IntrospectionException refused() { + return new OAuth2IntrospectionException("Live introspection response refused"); + } +} diff --git a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerAutoConfiguration.java b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerAutoConfiguration.java index ce3da6b46..b10ab3263 100644 --- a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerAutoConfiguration.java +++ b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerAutoConfiguration.java @@ -31,6 +31,7 @@ import org.fireflyframework.security.spi.KeyManagementPort; import org.fireflyframework.security.spi.PolicyDecisionPort; import org.fireflyframework.security.spi.SecurityContextPort; +import org.fireflyframework.security.spi.TokenValidationPort; import org.fireflyframework.security.webflux.authentication.FireflyAuthenticationToken; import org.fireflyframework.security.webflux.authz.PolicyAuthorizationManager; import org.fireflyframework.security.webflux.context.ReactorSecurityContextAdapter; @@ -188,9 +189,46 @@ private static List> buildValidators(ResourceServerPro return validators; } + @Bean(destroyMethod = "close") + @ConditionalOnMissingBean(TokenValidationPort.class) + @ConditionalOnProperty(prefix = "firefly.security.resource-server", name = "admission-mode", havingValue = "LIVE") + public SpringLiveTokenValidationAdapter fireflyLiveTokenValidationPort(ResourceServerProperties properties) { + return SpringLiveTokenValidationAdapter.create(properties); + } + + /** Retains the direct LOCAL factory API; LIVE callers must supply the explicit port. */ + public SecurityWebFilterChain fireflySecurityWebFilterChain( + ServerHttpSecurity http, + ReactiveJwtDecoder jwtDecoder, + Converter> jwtAuthenticationConverter, + PolicyDecisionPort policyDecisionPort, + ResourceServerProperties properties) { + if (properties.getAdmissionMode() != ResourceServerProperties.JwtAdmissionMode.LOCAL_JWT) { + throw new IllegalArgumentException("An explicit live validation port is required"); + } + return buildSecurityWebFilterChain(http, jwtDecoder, jwtAuthenticationConverter, policyDecisionPort, properties); + } + @Bean @ConditionalOnMissingBean public SecurityWebFilterChain fireflySecurityWebFilterChain( + ServerHttpSecurity http, + ReactiveJwtDecoder jwtDecoder, + Converter> jwtAuthenticationConverter, + PolicyDecisionPort policyDecisionPort, + ResourceServerProperties properties, + ObjectProvider livePorts) { + ReactiveJwtDecoder selected = jwtDecoder; + if (properties.getAdmissionMode() == ResourceServerProperties.JwtAdmissionMode.LIVE) { + TokenValidationPort live = livePorts.getObject(); + selected = new LiveActiveJwtDecoder(jwtDecoder, live, properties); + } else if (properties.getAdmissionMode() != ResourceServerProperties.JwtAdmissionMode.LOCAL_JWT) { + throw new IllegalArgumentException("A valid JWT admission mode is required"); + } + return buildSecurityWebFilterChain(http, selected, jwtAuthenticationConverter, policyDecisionPort, properties); + } + + private SecurityWebFilterChain buildSecurityWebFilterChain( ServerHttpSecurity http, ReactiveJwtDecoder jwtDecoder, Converter> jwtAuthenticationConverter, diff --git a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerProperties.java b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerProperties.java index e21ea5d35..ef42c7a5d 100644 --- a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerProperties.java +++ b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/ResourceServerProperties.java @@ -31,6 +31,25 @@ @ConfigurationProperties(prefix = "firefly.security.resource-server") public class ResourceServerProperties { + public enum JwtAdmissionMode { LOCAL_JWT, LIVE } + + /** Existing local verification remains the general default. */ + private JwtAdmissionMode admissionMode = JwtAdmissionMode.LOCAL_JWT; + private LiveState liveState = new LiveState(); + + /** No generated toString: these settings include an introspection credential. */ + @lombok.Getter + @lombok.Setter + public static class LiveState { + private String introspectionUri; + private String introspectionClientId; + private String introspectionClientSecret; + private String tokenClientClaim; + private List allowedClients = new ArrayList<>(); + private java.time.Duration timeout = java.time.Duration.ofSeconds(5); + } + + /** Ant-style path patterns that are publicly accessible without authentication. */ private List permitMatchers = new ArrayList<>(); diff --git a/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/SpringLiveTokenValidationAdapter.java b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/SpringLiveTokenValidationAdapter.java new file mode 100644 index 000000000..8bed1f5b2 --- /dev/null +++ b/modules/security-resource-server/src/main/java/org/fireflyframework/security/rs/SpringLiveTokenValidationAdapter.java @@ -0,0 +1,205 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import org.fireflyframework.security.api.domain.BearerToken; +import org.fireflyframework.security.api.domain.SecurityPrincipal; +import org.fireflyframework.security.api.exception.TokenValidationException; +import org.fireflyframework.security.spi.TokenValidationPort; +import org.springframework.http.client.reactive.JdkClientHttpConnector; +import org.springframework.http.client.reactive.ClientHttpConnector; +import org.reactivestreams.Publisher; +import org.springframework.core.ResolvableType; +import org.springframework.core.codec.Hints; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.util.MimeType; +import reactor.core.publisher.Flux; +import org.springframework.http.codec.json.JacksonJsonDecoder; +import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; +import org.springframework.security.oauth2.server.resource.introspection.SpringReactiveOpaqueTokenIntrospector; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** An uncached native Spring introspection client. Provider revocation behavior needs separate acceptance. */ +public final class SpringLiveTokenValidationAdapter implements TokenValidationPort, AutoCloseable { + private final ReactiveOpaqueTokenIntrospector introspector; + private final LiveActiveJwtDecoder.Settings settings; + private final Clock clock; + private final HttpClient ownedClient; + private final AtomicBoolean closed = new AtomicBoolean(); + + /** The supplied introspector must perform an uncached current-state exchange for each call. */ + public SpringLiveTokenValidationAdapter(ReactiveOpaqueTokenIntrospector introspector, + ResourceServerProperties properties) { + this(introspector, properties, Clock.systemUTC()); + } + + public SpringLiveTokenValidationAdapter(ReactiveOpaqueTokenIntrospector introspector, + ResourceServerProperties properties, Clock clock) { + this(introspector, LiveActiveJwtDecoder.Settings.from(properties), clock, null); + } + + private SpringLiveTokenValidationAdapter(ReactiveOpaqueTokenIntrospector introspector, + LiveActiveJwtDecoder.Settings settings, Clock clock, HttpClient ownedClient) { + this.introspector = Objects.requireNonNull(introspector); + this.settings = settings; + this.clock = Objects.requireNonNull(clock); + this.ownedClient = ownedClient; + } + + public static SpringLiveTokenValidationAdapter create(ResourceServerProperties properties) { + var settings = LiveActiveJwtDecoder.Settings.from(properties); + var live = properties.getLiveState(); + URI endpoint; + String clientId; + String secret; + try { + endpoint = URI.create(LiveActiveJwtDecoder.text(live.getIntrospectionUri())); + clientId = LiveActiveJwtDecoder.text(live.getIntrospectionClientId()); + secret = LiveActiveJwtDecoder.text(live.getIntrospectionClientSecret()); + if (!"https".equals(endpoint.getScheme()) || endpoint.getHost() == null + || endpoint.getRawUserInfo() != null || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null || endpoint.getPort() == 0 || endpoint.getPort() > 65535) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException error) { + throw new IllegalArgumentException("Valid explicit HTTPS introspection configuration is required"); + } + HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER) + .connectTimeout(settings.timeout()).build(); + try { + JdkClientHttpConnector connector = new JdkClientHttpConnector(client); + connector.setReadTimeout(settings.timeout()); + WebClient webClient = ownedWebClientBuilder(connector, clientId, secret).build(); + return new SpringLiveTokenValidationAdapter(new SpringReactiveOpaqueTokenIntrospector(endpoint.toASCIIString(), webClient), + settings, Clock.systemUTC(), client); + } catch (RuntimeException error) { + client.shutdownNow(); + throw new IllegalArgumentException("Live introspection client configuration refused"); + } + } + + @Override + public Mono validate(BearerToken token) { + return validateLive(token); + } + + @Override + public Mono validateLive(BearerToken token) { + return Mono.defer(() -> { + long started = System.nanoTime(); + if (closed.get() || token == null || token.type() != BearerToken.TokenType.JWT + || token.value() == null || token.value().isBlank()) { + return Mono.error(refused()); + } + return Mono.defer(() -> introspector.introspect(token.value())) + .switchIfEmpty(Mono.error(refused())) + .timeout(settings.timeout()) + .map(observed -> { + Map claims = new HashMap<>(); + Map remote = observed.getAttributes(); + if (!Boolean.TRUE.equals(remote.get("active"))) { + throw refused(); + } + for (String name : new String[]{"iss", "sub", "aud", "exp", "client_id", "jti"}) { + if (remote.containsKey(name)) { + claims.put(name, remote.get(name)); + } + } + // Copy and validate the allowed tuple; arbitrary provider attributes never become authentication claims. + var principal = SecurityPrincipal.builder() + .issuer(LiveActiveJwtDecoder.text(claims.get("iss"))) + .subject(LiveActiveJwtDecoder.text(claims.get("sub"))) + .claims(claims).build(); + var binding = LiveActiveJwtDecoder.Binding.remote(principal, settings); + if (!clock.instant().isBefore(binding.expiration()) || closed.get()) { + throw refused(); + } + claims.put("aud", java.util.List.copyOf(binding.audiences())); + SecurityPrincipal result = principal.toBuilder().claims(claims).build(); + long elapsed = System.nanoTime() - started; + if (elapsed < 0 || elapsed >= settings.timeout().toNanos() + || !clock.instant().isBefore(binding.expiration()) || closed.get()) { + throw refused(); + } + return result; + }); + }).onErrorMap(error -> refused()); + } + + @Override + public void close() { + if (closed.compareAndSet(false, true) && ownedClient != null) { + ownedClient.shutdownNow(); + } + } + + static WebClient.Builder ownedWebClientBuilder(ClientHttpConnector connector, String clientId, String secret) { + return WebClient.builder().clientConnector(connector) + .codecs(codecs -> { + codecs.defaultCodecs().maxInMemorySize(LiveIntrospectionResponseGuard.MAX_RESPONSE_BYTES); + codecs.defaultCodecs().enableLoggingRequestDetails(false); + codecs.defaultCodecs().jacksonJsonDecoder(nativeJsonDecoder()); + }) + .defaultHeaders(headers -> headers.setBasicAuth( + URLEncoder.encode(clientId, StandardCharsets.UTF_8), + URLEncoder.encode(secret, StandardCharsets.UTF_8))) + .filter(new LiveIntrospectionResponseGuard()); + } + + static JacksonJsonDecoder nativeJsonDecoder() { + return new QuietJacksonJsonDecoder(); + } + + /** The native codec honors this public hint before rendering decoded identity attributes. */ + private static final class QuietJacksonJsonDecoder extends JacksonJsonDecoder { + @Override + public Flux decode(Publisher input, ResolvableType type, MimeType mimeType, + Map hints) { + return super.decode(input, type, mimeType, Hints.merge(hints, Hints.SUPPRESS_LOGGING_HINT, true)) + .onErrorMap(error -> refused()); + } + @Override + public Mono decodeToMono(Publisher input, ResolvableType type, MimeType mimeType, + Map hints) { + return super.decodeToMono(input, type, mimeType, Hints.merge(hints, Hints.SUPPRESS_LOGGING_HINT, true)) + .onErrorMap(error -> refused()); + } + @Override + public Object decode(DataBuffer input, ResolvableType type, MimeType mimeType, Map hints) { + try { + return super.decode(input, type, mimeType, Hints.merge(hints, Hints.SUPPRESS_LOGGING_HINT, true)); + } catch (RuntimeException error) { + throw refused(); + } + } + } + + private static TokenValidationException refused() { + return new TokenValidationException("Live token validation refused"); + } +} diff --git a/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveActiveJwtDecoderTest.java b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveActiveJwtDecoderTest.java new file mode 100644 index 000000000..b8a989f20 --- /dev/null +++ b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveActiveJwtDecoderTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; +import static org.junit.jupiter.api.Assertions.*; +import java.time.*;import java.util.*;import java.util.concurrent.atomic.*; +import org.fireflyframework.security.api.domain.*;import org.fireflyframework.security.spi.TokenValidationPort; +import org.junit.jupiter.api.Test;import org.springframework.security.oauth2.jwt.*;import reactor.core.publisher.Mono;import reactor.test.StepVerifier; +class LiveActiveJwtDecoderTest { + static final Instant NOW=Instant.parse("2026-10-31T12:00:00Z");static final String ISSUER="https://issuer.invalid"; + final AtomicLong nanos=new AtomicLong();final AtomicInteger liveCalls=new AtomicInteger(); + ResourceServerProperties properties(){var p=new ResourceServerProperties();p.setAdmissionMode(ResourceServerProperties.JwtAdmissionMode.LIVE);p.setIssuer(ISSUER);p.setAudiences(List.of("resource"));p.getLiveState().setAllowedClients(List.of("workforce-client"));p.getLiveState().setTokenClientClaim("azp");return p;} + Jwt jwt(){return Jwt.withTokenValue("a.b.c").header("alg","RS256").issuer(ISSUER).subject("opaque:staff/subject").audience(List.of("resource")).issuedAt(NOW.minusSeconds(1)).expiresAt(NOW.plusSeconds(120)).claim("azp","workforce-client").claim("jti","opaque-token-id").build();} + SecurityPrincipal live(Map changed){var c=new HashMap(Map.of("iss",ISSUER,"sub","opaque:staff/subject","aud",List.of("resource"),"exp",NOW.plusSeconds(120),"client_id","workforce-client","jti","opaque-token-id"));c.putAll(changed);return SecurityPrincipal.builder().issuer((String)c.get("iss")).subject((String)c.get("sub")).claims(c).authorities(Set.of()).scopes(Set.of()).attributes(Map.of()).build();} + TokenValidationPort port(java.util.function.Function> answer){return new TokenValidationPort(){public Mono validate(BearerToken token){throw new AssertionError("Legacy validation is not LIVE");}public Mono validateLive(BearerToken token){liveCalls.incrementAndGet();assertEquals("a.b.c",token.value());return answer.apply(token);}};} + LiveActiveJwtDecoder decoder(ReactiveJwtDecoder local,TokenValidationPort port){return new LiveActiveJwtDecoder(local,port,properties(),Clock.fixed(NOW,ZoneOffset.UTC),nanos::get);} + @Test void returnsTheExactLocallyVerifiedJwtWithoutClaimOrRoleMerge(){var verified=jwt();var d=decoder(token->Mono.just(verified),port(token->Mono.just(live(Map.of()))));assertSame(verified,d.decode("a.b.c").block());assertFalse(verified.getClaims().containsKey("client_id"));assertEquals(1,liveCalls.get());} + @Test void localFailureNeverInvokesTheLiveProvider(){var d=decoder(token->Mono.error(new BadJwtException("PRIVATE_LOCAL_FAILURE")),port(token->Mono.just(live(Map.of()))));StepVerifier.create(d.decode("a.b.c")).expectErrorSatisfies(e->{assertInstanceOf(BadJwtException.class,e);assertNull(e.getCause());assertFalse(e.toString().contains("PRIVATE"));}).verify();assertEquals(0,liveCalls.get());} + @Test void emptyLocalOrLivePublisherCannotAuthenticate(){StepVerifier.create(decoder(token->Mono.empty(),port(token->Mono.just(live(Map.of())))).decode("a.b.c")).expectError(BadJwtException.class).verify();assertEquals(0,liveCalls.get());StepVerifier.create(decoder(token->Mono.just(jwt()),port(token->Mono.empty())).decode("a.b.c")).expectError(BadJwtException.class).verify();} + @Test void everySubscriptionQueriesLiveAndCannotReuseAnEarlierPermit(){var calls=new AtomicInteger();var d=decoder(token->Mono.just(jwt()),port(token->calls.getAndIncrement()==0?Mono.just(live(Map.of())):Mono.error(new IllegalStateException("PRIVATE_PROVIDER_BODY"))));assertNotNull(d.decode("a.b.c").block());StepVerifier.create(d.decode("a.b.c")).expectError(BadJwtException.class).verify();assertEquals(2,liveCalls.get());} + @Test void boundIssuerSubjectClientAudienceExpiryAndTokenIdMustMatch(){for(var changed:List.>of(Map.of("iss","https://other.invalid"),Map.of("sub","other-subject"),Map.of("client_id","other-client"),Map.of("aud",List.of("other-resource")),Map.of("exp",NOW.plusSeconds(121)),Map.of("jti","other-token"))){StepVerifier.create(decoder(token->Mono.just(jwt()),port(token->Mono.just(live(changed)))).decode("a.b.c")).expectError(BadJwtException.class).verify();}} + @Test void originalMonotonicWindowCannotBeResetByLateLiveSuccess(){var d=decoder(token->Mono.just(jwt()),port(token->Mono.fromSupplier(()->{nanos.set(Duration.ofSeconds(6).toNanos());return live(Map.of());})));StepVerifier.create(d.decode("a.b.c")).expectError(BadJwtException.class).verify();} + @Test void unsupportedLegacyPortCannotFallBackToTheLocalJwt(){TokenValidationPort legacy=token->Mono.just(live(Map.of()));StepVerifier.create(decoder(token->Mono.just(jwt()),legacy).decode("a.b.c")).expectError(BadJwtException.class).verify();} + @Test void missingOrOversizeLiveConfigurationRefuses(){var p=properties();p.getLiveState().setTimeout(Duration.ofSeconds(6));assertThrows(IllegalArgumentException.class,()->new LiveActiveJwtDecoder(token->Mono.just(jwt()),port(token->Mono.just(live(Map.of()))),p));} + @Test void propertiesAreSnapshottedInsteadOfChangingAnInflightAdmission(){var p=properties();var verified=jwt();var d=new LiveActiveJwtDecoder(token->Mono.just(verified),port(token->Mono.just(live(Map.of()))),p,Clock.fixed(NOW,ZoneOffset.UTC),nanos::get);p.getLiveState().setAllowedClients(List.of("other-client"));p.setIssuer("https://other.invalid");assertSame(verified,d.decode("a.b.c").block());} + @Test void cancellationCannotPublishALateAuthentication(){var sink=reactor.core.publisher.Sinks.one();var subscribed=new AtomicBoolean();var cancelled=new AtomicBoolean();var authenticated=new AtomicInteger();var d=decoder(token->Mono.just(jwt()),port(token->sink.asMono().doOnSubscribe(ignored->subscribed.set(true)).doOnCancel(()->cancelled.set(true))));StepVerifier.create(d.decode("a.b.c").doOnNext(ignored->authenticated.incrementAndGet()),0).thenRequest(1).then(()->{assertTrue(subscribed.get());assertEquals(1,liveCalls.get());}).thenCancel().verify();assertTrue(cancelled.get());sink.tryEmitValue(live(Map.of()));assertEquals(0,authenticated.get());} + + @Test void originalVerifiedExpirationStillBoundsALateLiveReply(){ + var clock=new AtomicReference<>(NOW);Clock advancing=new Clock(){public ZoneId getZone(){return ZoneOffset.UTC;}public Clock withZone(ZoneId zone){return this;}public Instant instant(){return clock.get();}}; + var d=new LiveActiveJwtDecoder(token->Mono.just(jwt()),port(token->Mono.fromSupplier(()->{clock.set(NOW.plusSeconds(121));return live(Map.of());})),properties(),advancing,nanos::get); + StepVerifier.create(d.decode("a.b.c")).expectError(BadJwtException.class).verify(); + } + @Test void wrongClaimAliasMissingIssuerAndMalformedOpaqueIdentityCannotBeInferred(){ + for(var change:List.>of(p->p.getLiveState().setTokenClientClaim("client_id"),p->p.setIssuer(null),p->p.getLiveState().setAllowedClients(List.of()))){var p=properties();change.accept(p);try{var d=new LiveActiveJwtDecoder(token->Mono.just(jwt()),port(token->Mono.just(live(Map.of()))),p,Clock.fixed(NOW,ZoneOffset.UTC),nanos::get);StepVerifier.create(d.decode("a.b.c")).expectError(BadJwtException.class).verify();}catch(IllegalArgumentException expected){assertNotNull(expected.getMessage());}} + StepVerifier.create(decoder(token->Mono.just(jwt()),port(token->Mono.just(live(Map.of("sub","opaque\nsubject"))))).decode("a.b.c")).expectError(BadJwtException.class).verify(); + } + @Test void nonCompletingLivePublisherUsesTheOriginalTimeoutAndCancels(){ + var fixture=properties();fixture.getLiveState().setTimeout(Duration.ofSeconds(1));var cancelled=new AtomicBoolean(); + StepVerifier.withVirtualTime(()->new LiveActiveJwtDecoder(token->Mono.just(jwt()),port(token->Mono.never().doOnCancel(()->cancelled.set(true))),fixture,Clock.fixed(NOW,ZoneOffset.UTC),nanos::get).decode("a.b.c")) + .thenAwait(Duration.ofSeconds(2)).expectError(BadJwtException.class).verify();assertTrue(cancelled.get()); + } + + @Test void timeSpentInLocalVerificationDoesNotCreateANewLiveWindow(){ + StepVerifier.withVirtualTime(()->decoder(token->Mono.delay(Duration.ofSeconds(3)).map(ignored->jwt()),port(token->Mono.delay(Duration.ofSeconds(3)).map(ignored->live(Map.of())))).decode("a.b.c")) + .thenAwait(Duration.ofSeconds(5)).expectError(BadJwtException.class).verify(); + } +} diff --git a/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionPrivacyTest.java b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionPrivacyTest.java new file mode 100644 index 000000000..cf57bda73 --- /dev/null +++ b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionPrivacyTest.java @@ -0,0 +1,104 @@ +package org.fireflyframework.security.rs; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.fireflyframework.security.api.domain.BearerToken; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.core.ResolvableType; +import org.springframework.core.io.buffer.DefaultDataBufferFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.server.resource.introspection.SpringReactiveOpaqueTokenIntrospector; +import org.springframework.web.reactive.function.client.*; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.time.*; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; + +class LiveIntrospectionPrivacyTest { + @Test void nativeCodecDelegationSuppressesAllDecodeEntryPointValueLogsAtTrace() { + var logger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + var capture = new ListAppender(); capture.start(); + var previous = logger.getLevel(); logger.setLevel(Level.TRACE); logger.addAppender(capture); + try { + var codec = SpringLiveTokenValidationAdapter.nativeJsonDecoder(); + var type = ResolvableType.forClass(Map.class); + var factory = DefaultDataBufferFactory.sharedInstance; + byte[] bytes = "{\"private-key\":\"PRIVATE_PROVIDER_BODY\"}".getBytes(StandardCharsets.UTF_8); + assertNotNull(codec.decode(factory.wrap(bytes), type, MediaType.APPLICATION_JSON, Map.of())); + assertNotNull(codec.decodeToMono(Flux.just(factory.wrap(bytes)), type, MediaType.APPLICATION_JSON, Map.of()).block()); + assertEquals(1, codec.decode(Flux.just(factory.wrap(bytes)), type, MediaType.APPLICATION_JSON, Map.of()).collectList().block().size()); + assertFalse(messages(capture).contains("PRIVATE_PROVIDER_BODY")); + assertFalse(messages(capture).contains("private-key")); + } finally { logger.detachAppender(capture); logger.setLevel(previous); capture.stop(); } + } + @Test void nativeClientAndAdapterNeverExposeCredentialResponseOrErrorCauseInCompleteLogAndStackBytes() { + var logger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + var capture = new ListAppender(); capture.start(); + var previous = logger.getLevel(); logger.setLevel(Level.TRACE); logger.addAppender(capture); + try { + int successes = 0; + int failures = 0; + for (String body : List.of(LiveIntrospectionResponseGuardTest.VALID.substring(0, LiveIntrospectionResponseGuardTest.VALID.length()-1) + + ",\"extra\":\"PRIVATE_PROVIDER_BODY\"}", "{\"active\":\"PRIVATE_PROVIDER_ERROR\"}")) { + var originalStrategies = new java.util.concurrent.atomic.AtomicReference(); + var constructed = new java.util.concurrent.atomic.AtomicBoolean(); + org.springframework.http.client.reactive.ClientHttpConnector connector = (method, uri, writer) -> { + var request = new org.springframework.mock.http.client.reactive.MockClientHttpRequest(method, uri); + return writer.apply(request).then(Mono.defer(request::getBodyAsString)).map(form -> { + assertEquals("POST", method.name()); + assertEquals("https://issuer.invalid/introspect", uri.toString()); + assertEquals("token=PRIVATE_RAW_TOKEN.x.y", form); + assertEquals("Basic " + Base64.getEncoder().encodeToString("PRIVATE_CLIENT:PRIVATE_SECRET".getBytes(StandardCharsets.UTF_8)), request.getHeaders().getFirst("Authorization")); + constructed.set(true); + var response = new org.springframework.mock.http.client.reactive.MockClientHttpResponse(HttpStatus.OK); + response.getHeaders().setContentType(MediaType.APPLICATION_JSON); + response.setBody(body); + return (org.springframework.http.client.reactive.ClientHttpResponse)response; + }); + }; + WebClient.Builder builder = SpringLiveTokenValidationAdapter.ownedWebClientBuilder(connector, "PRIVATE_CLIENT", "PRIVATE_SECRET"); + builder.filter((request, next) -> next.exchange(request).doOnNext(response -> originalStrategies.set(response.strategies()))); + builder.filters(filters -> filters.addFirst((request, next) -> next.exchange(request) + .doOnNext(response -> assertSame(originalStrategies.get(), response.strategies())))); + WebClient webClient = builder.build(); + var adapter = new SpringLiveTokenValidationAdapter(new SpringReactiveOpaqueTokenIntrospector("https://issuer.invalid/introspect", webClient), + new LiveActiveJwtDecoderTest().properties(), Clock.fixed(LiveActiveJwtDecoderTest.NOW, ZoneOffset.UTC)); + try { + var principal = adapter.validateLive(BearerToken.of("PRIVATE_RAW_TOKEN.x.y")).block(); + assertNotNull(principal); + assertFalse(principal.claims().containsKey("extra")); + successes++; + } catch (RuntimeException error) { + var writer = new StringWriter(); error.printStackTrace(new PrintWriter(writer)); + assertNoSensitiveValues(writer.toString()); assertNull(error.getCause()); + failures++; + } finally { adapter.close(); } + assertTrue(constructed.get()); + } + assertEquals(1, successes); + assertEquals(1, failures); + assertNoSensitiveValues(messages(capture)); + } finally { logger.detachAppender(capture); logger.setLevel(previous); capture.stop(); } + } + void assertNoSensitiveValues(String rendered) { + for (String value : List.of(Base64.getEncoder().encodeToString("PRIVATE_CLIENT:PRIVATE_SECRET".getBytes(StandardCharsets.UTF_8)), "PRIVATE_RAW_TOKEN", "PRIVATE_CLIENT", "PRIVATE_SECRET", "PRIVATE_PROVIDER_BODY", "PRIVATE_PROVIDER_ERROR")) { + assertFalse(rendered.contains(value), value); + } + } + String messages(ListAppender capture) { + var text = new StringBuilder(); + for (var event : capture.list) { + text.append(event.getFormattedMessage()); + if (event.getThrowableProxy() != null) text.append(ch.qos.logback.classic.spi.ThrowableProxyUtil.asString(event.getThrowableProxy())); + } + return text.toString(); + } +} diff --git a/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuardTest.java b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuardTest.java new file mode 100644 index 000000000..a70cdf7e7 --- /dev/null +++ b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveIntrospectionResponseGuardTest.java @@ -0,0 +1,189 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import io.netty.buffer.PooledByteBufAllocator; +import org.fireflyframework.security.api.domain.BearerToken; +import org.junit.jupiter.api.Test; +import org.springframework.core.io.buffer.*; +import org.springframework.http.*; +import org.springframework.security.oauth2.server.resource.introspection.SpringReactiveOpaqueTokenIntrospector; +import org.springframework.web.reactive.function.client.*; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.*; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +class LiveIntrospectionResponseGuardTest { + static final String VALID = "{\"active\":true,\"iss\":\"https://issuer.invalid\",\"sub\":\"opaque:staff/subject\",\"aud\":[\"resource\"],\"client_id\":\"workforce-client\",\"exp\":1793448120,\"jti\":\"opaque-token-id\"}"; + final NettyDataBufferFactory buffers = new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); + final LiveIntrospectionResponseGuard guard = new LiveIntrospectionResponseGuard(); + final ClientRequest request = ClientRequest.create(HttpMethod.POST, URI.create("https://issuer.invalid/introspect")).build(); + + Mono guard(byte[] bytes, HttpStatus status, List allocated) { + NettyDataBuffer buffer = buffers.allocateBuffer(bytes.length).write(bytes); + allocated.add(buffer); + ClientResponse response = ClientResponse.create(status).header("Content-Type", "application/json") + .body(Flux.just(buffer)).build(); + return guard.filter(request, unused -> Mono.just(response)); + } + Mono guard(String body, List allocated) { + return guard(body.getBytes(StandardCharsets.UTF_8), HttpStatus.OK, allocated); + } + void released(List allocated) { + for (var buffer : allocated) assertEquals(0, buffer.getNativeBuffer().refCnt()); + } + void refused(String body) { + var allocated = new ArrayList(); + StepVerifier.create(guard(body, allocated)).expectErrorSatisfies(error -> { + assertNull(error.getCause()); + assertEquals("Live introspection response refused", error.getMessage()); + }).verify(); + released(allocated); + } + + @Test void validBytesReachTheNativeCodecUnchangedAndOriginalPooledBufferIsReleased() { + var allocated = new ArrayList(); + String body = " \n" + VALID + " \n"; + assertEquals(body, guard(body, allocated).flatMap(response -> response.bodyToMono(String.class)).block()); + released(allocated); + } + @Test void duplicateIdentityAndActiveKeysRefuseBeforeNativeLastValueCoercion() { + refused(VALID.replace("\"active\":true", "\"active\":false,\"active\":true")); + refused(VALID.replace("\"sub\":", "\"sub\":\"PRIVATE_PROVIDER_BODY\",\"sub\":")); + } + @Test void exactRawTypesRefuseStringBooleansNumericClientsAndFractionalTimes() { + for (String body : List.of(VALID.replace("true", "\"true\""), + VALID.replace("\"workforce-client\"", "42"), + VALID.replace("1793448120", "1793448120.5"), + VALID.replace("1793448120", "\"1793448120\""), + VALID.replace("[\"resource\"]", "[42]"), + VALID.replace("[\"resource\"]", "[\"resource\",\"resource\"]"))) refused(body); + } + @Test void missingIdentityNullArraysEscapedSurrogatesAndTrailingDocumentsRefuse() { + for (String body : List.of("[]", "null", "{}", VALID + "{}", + VALID.replace("\"sub\":\"opaque:staff/subject\",", ""), + VALID.replace("\"sub\":\"opaque:staff/subject\"", "\"sub\":null"), + VALID.replace("opaque:staff/subject", "\\uD800"))) refused(body); + } + @Test void inactiveMayOmitBindingMetadataButTheGenuineNativeClientRefusesIt() { + WebClient client = client(() -> ClientResponse.create(HttpStatus.OK).header("Content-Type", "application/json").body("{\"active\":false}").build()); + var nativeClient = new SpringReactiveOpaqueTokenIntrospector("https://issuer.invalid/introspect", client); + StepVerifier.create(nativeClient.introspect("a.b.c")).expectError().verify(); + } + @Test void successAndErrorBodiesAreBothBoundedAndReleasePooledBuffers() { + for (HttpStatus status : List.of(HttpStatus.OK, HttpStatus.BAD_REQUEST, HttpStatus.INTERNAL_SERVER_ERROR)) { + var allocated = new ArrayList(); + StepVerifier.create(guard(new byte[16 * 1024 + 1], status, allocated)).expectError().verify(); + released(allocated); + } + } + @Test void nonSuccessAndMalformedUtf8NeverExposeResponseOrTransportErrors() { + var allocated = new ArrayList(); + StepVerifier.create(guard("PRIVATE_BODY".getBytes(StandardCharsets.UTF_8), HttpStatus.BAD_REQUEST, allocated)) + .expectErrorSatisfies(error -> { assertNull(error.getCause()); assertFalse(error.toString().contains("PRIVATE")); }).verify(); + released(allocated); + var invalid = new ArrayList(); + StepVerifier.create(guard(new byte[]{(byte)0xc3, 0x28}, HttpStatus.OK, invalid)).expectError().verify(); + released(invalid); + StepVerifier.create(guard.filter(request, ignored -> Mono.error(new IllegalStateException("PRIVATE_TRANSPORT")))) + .expectErrorSatisfies(error -> { assertNull(error.getCause()); assertFalse(error.toString().contains("PRIVATE")); }).verify(); + } + @Test void cancellationReleasesAccumulatedBodyAndCancelsUpstream() { + NettyDataBuffer first = buffers.allocateBuffer().write("{\"active\":".getBytes(StandardCharsets.UTF_8)); + var cancelled = new AtomicBoolean(); + var received = new AtomicBoolean(); + var response = ClientResponse.create(HttpStatus.OK).header("Content-Type", "application/json") + .body(Flux.concat(Flux.just(first), Flux.never()).doOnNext(buffer -> received.set(true)).doOnCancel(() -> cancelled.set(true))).build(); + StepVerifier.create(guard.filter(request, ignored -> Mono.just(response)), 0) + .thenRequest(1).then(() -> assertTrue(received.get())).thenCancel().verify(); + assertTrue(cancelled.get()); + assertEquals(0, first.getNativeBuffer().refCnt()); + } + @Test void bodyErrorReleasesPreviouslyReceivedPooledBufferAndDropsRawCause() { + NettyDataBuffer first = buffers.allocateBuffer().write("{".getBytes(StandardCharsets.UTF_8)); + var response = ClientResponse.create(HttpStatus.OK).body(Flux.concat(Flux.just(first), + Flux.error(new IllegalStateException("PRIVATE_STREAM_ERROR")))).build(); + StepVerifier.create(guard.filter(request, ignored -> Mono.just(response))) + .expectErrorSatisfies(error -> { assertNull(error.getCause()); assertFalse(error.toString().contains("PRIVATE")); }).verify(); + assertEquals(0, first.getNativeBuffer().refCnt()); + } + @Test void nativeSpringIntrospectorAndJackson3CodecRunForEverySubscriptionWithoutAttributeMerge() { + AtomicInteger exchanges = new AtomicInteger(); + WebClient client = client(() -> { + exchanges.incrementAndGet(); + return ClientResponse.create(HttpStatus.OK).header("Content-Type", "application/json") + .body(VALID.substring(0, VALID.length()-1) + ",\"scope\":\"admin\",\"PRIVATE_EXTRA\":\"PRIVATE_BODY\"}").build(); + }); + var p = new LiveActiveJwtDecoderTest().properties(); + var adapter = new SpringLiveTokenValidationAdapter(new SpringReactiveOpaqueTokenIntrospector("https://issuer.invalid/introspect", client), p, + Clock.fixed(LiveActiveJwtDecoderTest.NOW, ZoneOffset.UTC)); + for (int i = 0; i < 2; i++) { + var principal = adapter.validateLive(BearerToken.of("a.b.c")).block(); + assertNotNull(principal); + assertTrue(principal.authorities().isEmpty()); assertTrue(principal.scopes().isEmpty()); + assertFalse(principal.claims().containsKey("PRIVATE_EXTRA")); assertFalse(principal.claims().containsKey("scope")); + assertEquals(Instant.ofEpochSecond(1793448120), principal.claims().get("exp")); + } + assertEquals(2, exchanges.get()); + adapter.close(); + StepVerifier.create(adapter.validateLive(BearerToken.of("a.b.c"))).expectError().verify(); + assertEquals(2, exchanges.get()); + } + + @Test void exactByteCapAllowsOnlyTheValidBoundedDocumentAndReleasesAllFragments() { + var allocated = new ArrayList(); + String document = VALID + " ".repeat(16 * 1024 - VALID.getBytes(StandardCharsets.UTF_8).length); + assertEquals(document, guard(document, allocated).flatMap(response -> response.bodyToMono(String.class)).block()); + released(allocated); + } + @Test void fragmentedUtf8PreservesItsActualBytesAcrossPooledBuffers() { + byte[] document = VALID.replace("opaque:staff/subject", "opaque:é/subject").getBytes(StandardCharsets.UTF_8); + int split = 0; + while ((document[split] & 0xff) != 0xc3) split++; + split++; + var first = buffers.allocateBuffer(split).write(Arrays.copyOfRange(document, 0, split)); + var last = buffers.allocateBuffer(document.length-split).write(Arrays.copyOfRange(document, split, document.length)); + var response = ClientResponse.create(HttpStatus.OK).header("Content-Type", "application/json").body(Flux.just(first,last)).build(); + String observed = guard.filter(request, unused -> Mono.just(response)).flatMap(value -> value.bodyToMono(String.class)).block(); + assertArrayEquals(document, observed.getBytes(StandardCharsets.UTF_8)); + assertEquals(0, first.getNativeBuffer().refCnt()); assertEquals(0, last.getNativeBuffer().refCnt()); + } + @Test void adapterInactiveEmptyAndProviderFailureCannotProduceAPrincipal() { + var p = new LiveActiveJwtDecoderTest().properties(); + var cases = List.of( + token -> Mono.empty(), token -> Mono.error(new IllegalStateException("PRIVATE_PROVIDER_ERROR")), + token -> Mono.just(new org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal(Map.of("active",false),List.of()))); + for (var nativePort : cases) { + var adapter = new SpringLiveTokenValidationAdapter(nativePort,p,Clock.fixed(LiveActiveJwtDecoderTest.NOW,ZoneOffset.UTC)); + try { StepVerifier.create(adapter.validateLive(BearerToken.of("a.b.c"))).expectErrorSatisfies(error -> {assertNull(error.getCause());assertFalse(error.toString().contains("PRIVATE"));}).verify(); } + finally { adapter.close(); } + } + } + WebClient client(java.util.function.Supplier response) { + return WebClient.builder().codecs(codecs -> codecs.defaultCodecs().jacksonJsonDecoder(SpringLiveTokenValidationAdapter.nativeJsonDecoder())) + .exchangeFunction(unused -> Mono.fromSupplier(response)).filter(guard).build(); + } +} diff --git a/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtChainAdoptionTest.java b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtChainAdoptionTest.java new file mode 100644 index 000000000..3550afd59 --- /dev/null +++ b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtChainAdoptionTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import org.fireflyframework.security.api.domain.*; +import org.fireflyframework.security.core.authority.*; +import org.fireflyframework.security.core.context.PrincipalFactory; +import org.fireflyframework.security.spi.*; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; +import org.springframework.context.annotation.*; +import org.springframework.http.HttpHeaders; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.oauth2.jwt.*; +import org.springframework.security.web.server.*; +import org.springframework.test.web.reactive.server.WebTestClient; +import reactor.core.publisher.Mono; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; + +class LiveJwtChainAdoptionTest { + @Test void existingDefaultRemainsLocalAndOldFactorySignatureWorks() { + var p = new ResourceServerProperties(); + assertEquals(ResourceServerProperties.JwtAdmissionMode.LOCAL_JWT, p.getAdmissionMode()); + var calls = new AtomicInteger(); + var chain = oldChain(p, raw -> Mono.just(new LiveActiveJwtDecoderTest().jwt())); + request(chain).get().uri("/private").header(HttpHeaders.AUTHORIZATION, "Bearer a.b.c") + .exchange().expectStatus().isOk(); + assertEquals(0, calls.get()); + } + @Test void defaultChainWrapsAnInjectedDecoderAndDeniesRemoteFailureBeforeBusinessHandler() { + var fixture = new LiveActiveJwtDecoderTest(); var p = fixture.properties(); var effects = new AtomicInteger(); + TokenValidationPort port = new TokenValidationPort() { + public Mono validate(BearerToken token) { throw new AssertionError(); } + public Mono validateLive(BearerToken token) { return Mono.error(new IllegalStateException("PRIVATE_PROVIDER_RESPONSE")); } + }; + var beans = new StaticListableBeanFactory(); beans.addBean("live", port); + var chain = new ResourceServerAutoConfiguration().fireflySecurityWebFilterChain(ServerHttpSecurity.http(), + raw -> Mono.just(currentJwt()), converter(), (principal, action, resource, context) -> Mono.just(Decision.permit()), p, + beans.getBeanProvider(TokenValidationPort.class)); + request(chain, effects).get().uri("/private").header(HttpHeaders.AUTHORIZATION, "Bearer a.b.c") + .exchange().expectStatus().isUnauthorized().expectBody().consumeWith(response -> { + assertFalse(new String(response.getResponseBody() == null ? new byte[0] : response.getResponseBody(), java.nio.charset.StandardCharsets.UTF_8).contains("PRIVATE")); + }); + assertEquals(0, effects.get()); + } + @Test void oldDirectFactoryCannotSilentlyDowngradeRequestedLiveMode() { + assertThrows(IllegalArgumentException.class, () -> oldChain(new LiveActiveJwtDecoderTest().properties(), raw -> Mono.just(currentJwt()))); + } + @Test void missingAndAmbiguousPortsFailDefaultChainConstruction() { + var properties = new LiveActiveJwtDecoderTest().properties(); + var beans = new StaticListableBeanFactory(); + assertThrows(RuntimeException.class, () -> new ResourceServerAutoConfiguration().fireflySecurityWebFilterChain( + ServerHttpSecurity.http(), raw -> Mono.just(currentJwt()), converter(), (p,a,r,c)->Mono.just(Decision.permit()), properties, + beans.getBeanProvider(TokenValidationPort.class))); + beans.addBean("first", (TokenValidationPort)token -> Mono.empty()); + beans.addBean("second", (TokenValidationPort)token -> Mono.empty()); + assertThrows(RuntimeException.class, () -> new ResourceServerAutoConfiguration().fireflySecurityWebFilterChain( + ServerHttpSecurity.http(), raw -> Mono.just(currentJwt()), converter(), (p,a,r,c)->Mono.just(Decision.permit()), properties, + beans.getBeanProvider(TokenValidationPort.class))); + } + @Test void customChainsMustExplicitlyUseThePublicDecorator() { + var fixture = new LiveActiveJwtDecoderTest(); var properties = fixture.properties(); + TokenValidationPort legacyOnly = token -> Mono.just(fixture.live(Map.of())); + var live = new LiveActiveJwtDecoder(raw -> Mono.just(currentJwt()), legacyOnly, properties); + var chain = oldChain(new ResourceServerProperties(), live); + request(chain).get().uri("/private").header(HttpHeaders.AUTHORIZATION, "Bearer a.b.c") + .exchange().expectStatus().isUnauthorized(); + // A fully custom local-only chain remains local; a LIVE property elsewhere cannot mutate it. + request(oldChain(new ResourceServerProperties(), raw -> Mono.just(currentJwt()))) + .get().uri("/private").header(HttpHeaders.AUTHORIZATION, "Bearer a.b.c").exchange().expectStatus().isOk(); + } + @Test void propertyBindingUsesProjectExplicitLivePortAndDoesNotCreateAnOwnedNativeClient() { + new ReactiveWebApplicationContextRunner().withConfiguration(AutoConfigurations.of(ResourceServerAutoConfiguration.class)) + .withUserConfiguration(ProjectPort.class).withPropertyValues( + "firefly.security.resource-server.admission-mode=LIVE", "firefly.security.resource-server.issuer=https://issuer.invalid", + "firefly.security.resource-server.audiences[0]=resource", + "firefly.security.resource-server.live-state.allowed-clients[0]=workforce-client", + "firefly.security.resource-server.live-state.token-client-claim=azp") + .run(context -> { assertThat(context).hasNotFailed().hasSingleBean(TokenValidationPort.class); + assertThat(context).doesNotHaveBean(SpringLiveTokenValidationAdapter.class); }); + } + @Test void missingNativeClientSettingsFailBeforeTransportAllocation() { + assertThrows(IllegalArgumentException.class, () -> SpringLiveTokenValidationAdapter.create(new LiveActiveJwtDecoderTest().properties())); + } + static class ProjectPort { + @Bean ReactiveJwtDecoder customDecoder() { return raw -> Mono.just(currentJwt()); } + @Bean TokenValidationPort explicitPort() { return token -> Mono.empty(); } + } + static Jwt currentJwt() { + var now = java.time.Instant.now(); + return Jwt.withTokenValue("a.b.c").header("alg","RS256").issuer(LiveActiveJwtDecoderTest.ISSUER) + .subject("opaque:staff/subject").audience(List.of("resource")).expiresAt(now.plusSeconds(120)).claim("azp","workforce-client").build(); + } + static org.springframework.core.convert.converter.Converter> converter() { + return new ResourceServerAutoConfiguration().fireflyJwtAuthenticationConverter(new PrincipalFactory( + new ConfigurableAuthorityMapper(new AuthorityMappingProperties(List.of(), List.of(), "")))); + } + SecurityWebFilterChain oldChain(ResourceServerProperties p, ReactiveJwtDecoder decoder) { + return new ResourceServerAutoConfiguration().fireflySecurityWebFilterChain(ServerHttpSecurity.http(), decoder, + converter(), (principal,action,resource,context)->Mono.just(Decision.permit()), p); + } + WebTestClient request(SecurityWebFilterChain chain) { return request(chain, new AtomicInteger()); } + WebTestClient request(SecurityWebFilterChain chain, AtomicInteger effects) { + return WebTestClient.bindToWebHandler(exchange -> { effects.incrementAndGet(); exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.OK); return exchange.getResponse().setComplete(); }) + .webFilter(new WebFilterChainProxy(chain)).build(); + } +} diff --git a/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtNativeVerificationTest.java b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtNativeVerificationTest.java new file mode 100644 index 000000000..66b728bfd --- /dev/null +++ b/modules/security-resource-server/src/test/java/org/fireflyframework/security/rs/LiveJwtNativeVerificationTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.rs; + +import com.nimbusds.jose.*; +import com.nimbusds.jose.crypto.RSASSASigner; +import com.nimbusds.jwt.*; +import org.fireflyframework.security.api.domain.SecurityPrincipal; +import org.fireflyframework.security.spi.TokenValidationPort; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.jwt.*; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.security.*; +import java.security.interfaces.*; +import java.time.*; +import java.util.*; +import java.util.concurrent.atomic.*; +import static org.junit.jupiter.api.Assertions.*; + +class LiveJwtNativeVerificationTest { + @Test void genuineNimbusSignatureAndIssuerValidationPrecedeEveryLiveExchange() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); + var pair = generator.generateKeyPair(); var foreign = generator.generateKeyPair(); + var properties = new LiveActiveJwtDecoderTest().properties(); + var local = NimbusReactiveJwtDecoder.withPublicKey((RSAPublicKey)pair.getPublic()).build(); + local.setJwtValidator(JwtValidators.createDefaultWithIssuer(LiveActiveJwtDecoderTest.ISSUER)); + var received = new AtomicReference(); var calls = new AtomicInteger(); + TokenValidationPort live = new TokenValidationPort() { + public Mono validate(org.fireflyframework.security.api.domain.BearerToken token) { throw new AssertionError(); } + public Mono validateLive(org.fireflyframework.security.api.domain.BearerToken token) { + calls.incrementAndGet(); var jwt = received.get(); + return Mono.just(SecurityPrincipal.builder().issuer(jwt.getClaimAsString("iss")).subject(jwt.getSubject()) + .claims(Map.of("iss", jwt.getClaimAsString("iss"), "sub", jwt.getSubject(), "aud", jwt.getAudience(), + "exp", jwt.getExpiresAt(), "client_id", "workforce-client", "jti", "opaque-token-id")).build()); + } + }; + var decoder = new LiveActiveJwtDecoder(raw -> local.decode(raw).doOnNext(received::set), live, properties); + String valid = sign(pair, LiveActiveJwtDecoderTest.ISSUER, Instant.now().plusSeconds(120)); + assertSame(receivedValue(decoder, valid), received.get()); assertEquals(1, calls.get()); + for (String invalid : List.of(sign(foreign, LiveActiveJwtDecoderTest.ISSUER, Instant.now().plusSeconds(120)), + sign(pair, "https://other.invalid", Instant.now().plusSeconds(120)), + sign(pair, LiveActiveJwtDecoderTest.ISSUER, Instant.now().minusSeconds(180)))) { + StepVerifier.create(decoder.decode(invalid)).expectError(BadJwtException.class).verify(); + } + assertEquals(1, calls.get()); + } + Jwt receivedValue(LiveActiveJwtDecoder decoder, String token) { return decoder.decode(token).block(); } + String sign(KeyPair key, String issuer, Instant expires) throws Exception { + var claims = new JWTClaimsSet.Builder().issuer(issuer).subject("opaque:staff/subject").audience("resource") + .expirationTime(Date.from(expires)).claim("azp", "workforce-client").jwtID("opaque-token-id").build(); + var signed = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claims); + signed.sign(new RSASSASigner((RSAPrivateKey)key.getPrivate())); return signed.serialize(); + } +} diff --git a/modules/security-spi/src/main/java/org/fireflyframework/security/spi/TokenValidationPort.java b/modules/security-spi/src/main/java/org/fireflyframework/security/spi/TokenValidationPort.java index 19bd805eb..3cb9f5526 100644 --- a/modules/security-spi/src/main/java/org/fireflyframework/security/spi/TokenValidationPort.java +++ b/modules/security-spi/src/main/java/org/fireflyframework/security/spi/TokenValidationPort.java @@ -29,4 +29,12 @@ public interface TokenValidationPort { Mono validate(BearerToken token); + + /** + * Performs an uncached current-state check. Implementations must explicitly support this + * stronger contract; ordinary local validation must never be used as a fallback. + */ + default Mono validateLive(BearerToken token) { + return Mono.error(new UnsupportedOperationException("Live token validation is not supported")); + } } diff --git a/modules/security-spi/src/test/java/org/fireflyframework/security/spi/LiveValidationDefaultContractTest.java b/modules/security-spi/src/test/java/org/fireflyframework/security/spi/LiveValidationDefaultContractTest.java new file mode 100644 index 000000000..3331f9fc7 --- /dev/null +++ b/modules/security-spi/src/test/java/org/fireflyframework/security/spi/LiveValidationDefaultContractTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2024-2026 Firefly Software Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.fireflyframework.security.spi; +import static org.junit.jupiter.api.Assertions.*; +import java.util.concurrent.atomic.AtomicInteger; +import org.fireflyframework.security.api.domain.*; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +class LiveValidationDefaultContractTest { + @Test void existingValidationCannotImplicitlySatisfyLiveAdmission(){var calls=new AtomicInteger();TokenValidationPort port=token->{calls.incrementAndGet();return Mono.empty();};assertThrows(UnsupportedOperationException.class,()->port.validateLive(BearerToken.of("a.b.c")).block());assertEquals(0,calls.get());} +}