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
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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()));}
}
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions modules/security-resource-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@
<scope>provided</scope>
</dependency>

<!-- Strict bounded introspection JSON validation and native Spring Jackson3 codecs. -->
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<!-- ===== Test: run a real reactive server and sign JWTs ===== -->
<dependency>
<groupId>org.springframework.boot</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Jwt> 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<String> audience(Object value) {
if (!(value instanceof List<?> list) || list.isEmpty() || list.size() > 32) {
throw new IllegalArgumentException("Invalid live token audience");
}
Set<String> 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<String> audiences, Set<String> 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<String> 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<String, Object> claims, String clientClaim, Settings settings) {
String issuer = text(claims.get("iss"));
String subject = text(claims.get("sub"));
Set<String> 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]"; }
}
}
Loading
Loading