From 373f1a75fc305fc85a035a3e709c58b7b47c06be Mon Sep 17 00:00:00 2001 From: Thomas Darimont Date: Fri, 4 Dec 2026 23:26:46 +0100 Subject: [PATCH] SSF: Honor pairwise subject identifier mappers of SSF receiver clients in SET subjects A receiver client with a pairwise subject identifier mapper now receives the pairwise sub instead of the internal user ID in iss_sub and opaque user subjects, for native and emitted events. The rewrite runs at delivery time, so the subject gates keep working on the internal user ID. The rewrite works on copies, via the new copy() methods on SsfSecurityEventToken and ComplexSubjectId, so the original token is never modified. Closes #55812 Signed-off-by: Thomas Darimont --- docs/guides/securing-apps/ssf-support.adoc | 22 + .../event/token/SsfSecurityEventToken.java | 24 + .../ssf/subject/ComplexSubjectId.java | 26 + .../token/SsfSecurityEventTokenTest.java | 67 +++ .../ssf/subject/ComplexSubjectIdTest.java | 70 +++ .../SsfTransmitterPairwiseSubjectTests.java | 460 ++++++++++++++++++ .../SecurityEventTokenDispatcher.java | 43 ++ .../subject/PairwiseSubjectRewriter.java | 226 +++++++++ .../subject/PairwiseSubjectRewriterTest.java | 268 ++++++++++ 9 files changed, 1206 insertions(+) create mode 100644 ssf/core/src/test/java/org/keycloak/ssf/event/token/SsfSecurityEventTokenTest.java create mode 100644 ssf/core/src/test/java/org/keycloak/ssf/subject/ComplexSubjectIdTest.java create mode 100644 ssf/tests/base/src/test/java/org/keycloak/tests/ssf/transmitter/SsfTransmitterPairwiseSubjectTests.java create mode 100644 ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriter.java create mode 100644 ssf/transmitter/src/test/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriterTest.java diff --git a/docs/guides/securing-apps/ssf-support.adoc b/docs/guides/securing-apps/ssf-support.adoc index 861f99917fbb..04f6a35014a3 100644 --- a/docs/guides/securing-apps/ssf-support.adoc +++ b/docs/guides/securing-apps/ssf-support.adoc @@ -368,6 +368,28 @@ Administrators can manage subjects from the *Subjects* sub-tab in the admin cons an *ignore* operation that explicitly excludes a subject (distinct from removing them from the subscription list), and a *check* action that surfaces what the gate would decide for a given user without emitting an event. +=== Pairwise subject identifiers + +When the receiver client has a *Pairwise subject identifier* protocol mapper, the transmitter uses the pairwise +subject wherever a SET would otherwise carry the internal {project_name} user ID. The value is the same `sub` the +client receives in its ID tokens, access tokens and logout tokens, so the receiver can correlate events with the +users it knows. No additional receiver setting is required. + +This applies to `iss_sub` subjects issued by the realm and to `opaque` subjects that identify a user, both as the +top-level `sub_id` and as the `user` member of a complex subject. Other formats, such as `email`, are not changed. +Subjects supplied through the <> are rewritten in the same way, +because a receiver with a pairwise mapper is assumed to understand only the pairwise subject. If the pairwise +subject cannot be computed, the event is not delivered; the internal user ID is never sent as a fallback. + +Only mappers defined directly on the receiver client are considered. If users log in through a different client +than the one that owns the stream, configure a pairwise mapper with the same sector identifier and salt on the +receiver client, so that both clients see the same subject. + +A pairwise subject cannot be mapped back to a user. A receiver with a pairwise mapper therefore cannot subscribe +users through the subject management endpoints with an `iss_sub` subject. Use `default_subjects=ALL`, +*Auto notify on login*, subjects managed by an administrator, or an `email` subject instead. + +[[synthetic-event-emitter]] == Synthetic event emitter Some security signals do not originate inside {project_name}: an LDAP password change against a federated diff --git a/ssf/core/src/main/java/org/keycloak/ssf/event/token/SsfSecurityEventToken.java b/ssf/core/src/main/java/org/keycloak/ssf/event/token/SsfSecurityEventToken.java index e7e6715c9fea..f85e4101a8ab 100644 --- a/ssf/core/src/main/java/org/keycloak/ssf/event/token/SsfSecurityEventToken.java +++ b/ssf/core/src/main/java/org/keycloak/ssf/event/token/SsfSecurityEventToken.java @@ -1,5 +1,7 @@ package org.keycloak.ssf.event.token; +import java.util.LinkedHashMap; + import org.keycloak.ssf.subject.SubjectId; import org.keycloak.ssf.subject.SubjectIdJsonDeserializer; @@ -20,6 +22,28 @@ public class SsfSecurityEventToken extends AbstractSecurityEventToken { @JsonProperty("txn") protected String txn; + /** + * Returns a shallow copy of this token: the copy has its own + * claims, {@code aud} array and {@code events} map, but shares the + * subject and the event payload objects with this token. Callers + * that need a variant of a token copy it and then replace + * individual claims. + * + *

Every claim added to this class or its superclass must be + * copied here. + */ + public SsfSecurityEventToken copy() { + SsfSecurityEventToken copy = new SsfSecurityEventToken(); + copy.setJti(getJti()); + copy.setIss(getIss()); + copy.setIat(getIat()); + copy.setAud(getAud() != null ? getAud().clone() : null); + copy.setEvents(new LinkedHashMap<>(getEvents())); + copy.setSubjectId(subjectId); + copy.setTxn(txn); + return copy; + } + public SubjectId getSubjectId() { return subjectId; } diff --git a/ssf/core/src/main/java/org/keycloak/ssf/subject/ComplexSubjectId.java b/ssf/core/src/main/java/org/keycloak/ssf/subject/ComplexSubjectId.java index 0e107cf2e2f1..f2b77da5add3 100644 --- a/ssf/core/src/main/java/org/keycloak/ssf/subject/ComplexSubjectId.java +++ b/ssf/core/src/main/java/org/keycloak/ssf/subject/ComplexSubjectId.java @@ -1,5 +1,7 @@ package org.keycloak.ssf.subject; +import java.util.HashMap; + import org.keycloak.ssf.event.caep.CaepSessionRevoked; import com.fasterxml.jackson.annotation.JsonProperty; @@ -75,6 +77,30 @@ public ComplexSubjectId() { super(TYPE); } + /** + * Returns a shallow copy of this complex subject: the copy has its + * own member slots and attribute map, but shares the member + * {@link SubjectId} instances with this subject. Callers that need + * a variant of a complex subject copy it and then replace + * individual members. + * + *

Every member added to this class must be copied here. + */ + public ComplexSubjectId copy() { + ComplexSubjectId copy = new ComplexSubjectId(); + copy.setUser(user); + copy.setDevice(device); + copy.setSession(session); + copy.setApplication(application); + copy.setTenant(tenant); + copy.setOrgUnit(orgUnit); + copy.setGroup(group); + if (attributes != null) { + copy.setAttributes(new HashMap<>(attributes)); + } + return copy; + } + public SubjectId getUser() { return user; } diff --git a/ssf/core/src/test/java/org/keycloak/ssf/event/token/SsfSecurityEventTokenTest.java b/ssf/core/src/test/java/org/keycloak/ssf/event/token/SsfSecurityEventTokenTest.java new file mode 100644 index 000000000000..2a5c905dcff3 --- /dev/null +++ b/ssf/core/src/test/java/org/keycloak/ssf/event/token/SsfSecurityEventTokenTest.java @@ -0,0 +1,67 @@ +package org.keycloak.ssf.event.token; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.keycloak.ssf.subject.OpaqueSubjectId; +import org.keycloak.util.JsonSerialization; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +class SsfSecurityEventTokenTest { + + /** + * Compares the serialized form, so a claim that is added later but + * forgotten in {@link SsfSecurityEventToken#copy()} fails this test + * as soon as it is set here. + */ + @Test + void copy_carriesAllClaims() { + SsfSecurityEventToken original = token(); + + SsfSecurityEventToken copy = original.copy(); + + assertNotSame(original, copy); + assertEquals(JsonSerialization.mapper.valueToTree(original), + (JsonNode) JsonSerialization.mapper.valueToTree(copy)); + assertSame(original.getSubjectId(), copy.getSubjectId()); + } + + @Test + void copy_isIndependentOfTheOriginal() { + SsfSecurityEventToken original = token(); + OpaqueSubjectId originalSubject = (OpaqueSubjectId) original.getSubjectId(); + + SsfSecurityEventToken copy = original.copy(); + copy.setSubjectId(new OpaqueSubjectId()); + copy.getEvents().put("urn:example:other-event", Map.of()); + copy.getAud()[0] = "changed"; + + assertSame(originalSubject, original.getSubjectId()); + assertEquals(1, original.getEvents().size()); + assertEquals("https://receiver.example.test", original.getAud()[0]); + } + + private static SsfSecurityEventToken token() { + OpaqueSubjectId subject = new OpaqueSubjectId(); + subject.setId("subject-1"); + + Map events = new LinkedHashMap<>(); + events.put("urn:example:event", Map.of("reason", "test")); + + SsfSecurityEventToken token = new SsfSecurityEventToken(); + token.setJti("jti-1"); + token.setIss("https://kc.example.test/realms/test"); + token.setIat(1700000000); + token.setAud(new String[]{"https://receiver.example.test"}); + token.setTxn("txn-1"); + token.setEvents(events); + token.setSubjectId(subject); + return token; + } +} diff --git a/ssf/core/src/test/java/org/keycloak/ssf/subject/ComplexSubjectIdTest.java b/ssf/core/src/test/java/org/keycloak/ssf/subject/ComplexSubjectIdTest.java new file mode 100644 index 000000000000..5a086029db90 --- /dev/null +++ b/ssf/core/src/test/java/org/keycloak/ssf/subject/ComplexSubjectIdTest.java @@ -0,0 +1,70 @@ +package org.keycloak.ssf.subject; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +class ComplexSubjectIdTest { + + /** + * Guards {@link ComplexSubjectId#copy()} against members that are + * added to the class later but forgotten in the copy: every member + * field is discovered reflectively, so a new one fails this test + * until {@code copy()} handles it. + */ + @Test + void copy_copiesEveryMember() throws Exception { + ComplexSubjectId original = new ComplexSubjectId(); + List memberFields = memberFields(); + assertFalse(memberFields.isEmpty(), "expected ComplexSubjectId to declare subject members"); + for (Field field : memberFields) { + OpaqueSubjectId member = new OpaqueSubjectId(); + member.setId(field.getName()); + field.set(original, member); + } + + ComplexSubjectId copy = original.copy(); + + assertNotSame(original, copy); + for (Field field : memberFields) { + assertSame(field.get(original), field.get(copy), + "copy() must copy the '" + field.getName() + "' member"); + } + } + + @Test + void copy_isIndependentOfTheOriginal() { + ComplexSubjectId original = new ComplexSubjectId(); + OpaqueSubjectId user = new OpaqueSubjectId(); + original.setUser(user); + original.setAttribute("custom", "value"); + + ComplexSubjectId copy = original.copy(); + copy.setUser(new OpaqueSubjectId()); + copy.setAttribute("custom", "changed"); + + assertSame(user, original.getUser(), "replacing a member on the copy must not affect the original"); + assertEquals("value", original.getAttributes().get("custom"), + "changing an attribute on the copy must not affect the original"); + assertEquals(ComplexSubjectId.TYPE, copy.getFormat()); + } + + private static List memberFields() { + List fields = new ArrayList<>(); + for (Field field : ComplexSubjectId.class.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers()) && SubjectId.class.isAssignableFrom(field.getType())) { + field.setAccessible(true); + fields.add(field); + } + } + return fields; + } +} diff --git a/ssf/tests/base/src/test/java/org/keycloak/tests/ssf/transmitter/SsfTransmitterPairwiseSubjectTests.java b/ssf/tests/base/src/test/java/org/keycloak/tests/ssf/transmitter/SsfTransmitterPairwiseSubjectTests.java new file mode 100644 index 000000000000..4744624d968e --- /dev/null +++ b/ssf/tests/base/src/test/java/org/keycloak/tests/ssf/transmitter/SsfTransmitterPairwiseSubjectTests.java @@ -0,0 +1,460 @@ +package org.keycloak.tests.ssf.transmitter; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.resource.ClientResource; +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.common.Profile; +import org.keycloak.http.simple.SimpleHttp; +import org.keycloak.http.simple.SimpleHttpResponse; +import org.keycloak.jose.jws.JWSInput; +import org.keycloak.protocol.oidc.OIDCLoginProtocol; +import org.keycloak.protocol.oidc.mappers.PairwiseSubMapperHelper; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.representations.idm.ClientScopeRepresentation; +import org.keycloak.representations.idm.ProtocolMapperRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.keycloak.ssf.Ssf; +import org.keycloak.ssf.event.caep.CaepSessionRevoked; +import org.keycloak.ssf.event.risc.RiscAccountDisabled; +import org.keycloak.ssf.event.risc.RiscAccountEnabled; +import org.keycloak.ssf.transmitter.DefaultSsfTransmitterProviderFactory; +import org.keycloak.ssf.transmitter.SsfScopes; +import org.keycloak.ssf.transmitter.SsfTransmitterConfig; +import org.keycloak.ssf.transmitter.stream.StreamConfig; +import org.keycloak.ssf.transmitter.stream.StreamDeliveryConfig; +import org.keycloak.ssf.transmitter.stream.storage.client.ClientStreamStore; +import org.keycloak.ssf.transmitter.support.SsfTransmitterUrls; +import org.keycloak.testframework.annotations.InjectAdminClient; +import org.keycloak.testframework.annotations.InjectHttpServer; +import org.keycloak.testframework.annotations.InjectKeycloakUrls; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.InjectSimpleHttp; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.realm.ClientBuilder; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.realm.RealmBuilder; +import org.keycloak.testframework.realm.RealmConfig; +import org.keycloak.testframework.realm.UserBuilder; +import org.keycloak.testframework.server.DefaultKeycloakServerConfig; +import org.keycloak.testframework.server.KeycloakServerConfigBuilder; +import org.keycloak.testframework.server.KeycloakUrls; +import org.keycloak.testframework.util.HttpServerUtil; +import org.keycloak.util.JsonSerialization; + +import com.fasterxml.jackson.databind.JsonNode; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Integration tests proving that a receiver client with a pairwise + * subject identifier mapper receives the same pairwise {@code sub} in + * its Security Event Tokens as in its OIDC tokens — and never the + * internal Keycloak user ID. + * + *

The pairwise receiver runs with {@code default_subjects=NONE} and + * an explicitly subscribed user, so every delivery in this class also + * proves that the subject gates keep resolving the user even though the + * subject on the wire no longer carries the user ID. A second receiver + * without a pairwise mapper guards the unchanged default behavior. + */ +@KeycloakIntegrationTest(config = SsfTransmitterPairwiseSubjectTests.PairwiseServerConfig.class) +public class SsfTransmitterPairwiseSubjectTests { + + static final String PAIRWISE_RECEIVER = "ssf-receiver-pairwise"; + static final String PAIRWISE_RECEIVER_SECRET = "receiver-pairwise-secret"; + + static final String PLAIN_RECEIVER = "ssf-receiver-plain"; + static final String PLAIN_RECEIVER_SECRET = "receiver-plain-secret"; + + static final String TEST_USER = "pairwise-tester"; + static final String TEST_EMAIL = TEST_USER + "@local.test"; + static final String TEST_PASSWORD = "test"; + + static final String PAIRWISE_PUSH_CONTEXT_PATH = "/ssf/push-pairwise"; + static final String PLAIN_PUSH_CONTEXT_PATH = "/ssf/push-plain"; + static final String MOCK_PUSH_BASE_URL = "http://127.0.0.1:8500"; + static final String PUSH_AUTH_HEADER = "Bearer dummy-pairwise-receiver"; + + static final long PUSH_WAIT_SECONDS = 5; + + @InjectRealm(config = PairwiseRealm.class) + ManagedRealm realm; + + @InjectSimpleHttp + SimpleHttp http; + + @InjectAdminClient + Keycloak adminClient; + + @InjectKeycloakUrls + KeycloakUrls keycloakUrls; + + @InjectHttpServer + HttpServer mockReceiverServer; + + private final BlockingQueue pairwisePushes = new LinkedBlockingQueue<>(); + private final BlockingQueue plainPushes = new LinkedBlockingQueue<>(); + + private String testUserId; + + /** The {@code sub} the pairwise receiver sees in its OIDC tokens for the test user. */ + private String pairwiseSubject; + + @BeforeEach + public void setup() throws IOException { + pairwisePushes.clear(); + plainPushes.clear(); + + mockReceiverServer.createContext(PAIRWISE_PUSH_CONTEXT_PATH, collectingHandler(pairwisePushes)); + mockReceiverServer.createContext(PLAIN_PUSH_CONTEXT_PATH, collectingHandler(plainPushes)); + + testUserId = realm.admin().users().searchByUsername(TEST_USER, true).get(0).getId(); + // Start from a known state before the streams exist, so that the + // reset itself does not produce an account-enabled push. + setUserEnabled(true); + + pairwiseSubject = obtainTokenSubject(PAIRWISE_RECEIVER, PAIRWISE_RECEIVER_SECRET); + Assertions.assertNotEquals(testUserId, pairwiseSubject, + "test setup: the pairwise receiver's tokens must not carry the internal user ID"); + Assertions.assertEquals(testUserId, obtainTokenSubject(PLAIN_RECEIVER, PLAIN_RECEIVER_SECRET), + "test setup: the plain receiver's tokens must carry the internal user ID"); + + for (String receiver : List.of(PAIRWISE_RECEIVER, PLAIN_RECEIVER)) { + assignOptionalClientScopes(receiver, SsfScopes.SCOPE_SSF_READ, SsfScopes.SCOPE_SSF_MANAGE); + } + createPushStream(PAIRWISE_RECEIVER, PAIRWISE_RECEIVER_SECRET, PAIRWISE_PUSH_CONTEXT_PATH); + createPushStream(PLAIN_RECEIVER, PLAIN_RECEIVER_SECRET, PLAIN_PUSH_CONTEXT_PATH); + + // default_subjects=NONE on the pairwise receiver: only explicitly + // subscribed users are delivered. + subscribeTestUser(PAIRWISE_RECEIVER); + } + + @AfterEach + public void cleanup() { + bestEffortDeleteStream(PAIRWISE_RECEIVER); + bestEffortDeleteStream(PLAIN_RECEIVER); + for (String contextPath : List.of(PAIRWISE_PUSH_CONTEXT_PATH, PLAIN_PUSH_CONTEXT_PATH)) { + try { + mockReceiverServer.removeContext(contextPath); + } catch (IllegalArgumentException ignored) { + } + } + } + + @Test + public void nativeEvent_pairwiseReceiver_carriesPairwiseSubject() throws Exception { + setUserEnabled(false); + + String push = pairwisePushes.poll(PUSH_WAIT_SECONDS, TimeUnit.SECONDS); + Assertions.assertNotNull(push, + "the subscribed user's event must reach the pairwise receiver under default_subjects=NONE"); + + JsonNode set = decodeSet(push); + Assertions.assertTrue(set.path("events").has(RiscAccountDisabled.TYPE)); + JsonNode subId = set.path("sub_id"); + Assertions.assertEquals("iss_sub", subId.path("format").asText()); + Assertions.assertEquals(set.path("iss").asText(), subId.path("iss").asText()); + Assertions.assertEquals(pairwiseSubject, subId.path("sub").asText(), + "the SET must carry the same sub the receiver sees in its OIDC tokens"); + Assertions.assertFalse(push.contains(testUserId) || set.toString().contains(testUserId), + "the internal user ID must not appear anywhere in the SET"); + } + + @Test + public void nativeEvent_receiverWithoutPairwiseMapper_carriesUserId() throws Exception { + setUserEnabled(false); + + String push = plainPushes.poll(PUSH_WAIT_SECONDS, TimeUnit.SECONDS); + Assertions.assertNotNull(push, "the event must reach the receiver without a pairwise mapper"); + + JsonNode subId = decodeSet(push).path("sub_id"); + Assertions.assertEquals("iss_sub", subId.path("format").asText()); + Assertions.assertEquals(testUserId, subId.path("sub").asText(), + "a receiver without a pairwise mapper keeps receiving the internal user ID"); + } + + @Test + public void emittedEvent_complexSubject_userMemberIsRewritten() throws Exception { + // The emitter names the user by its internal ID; a receiver with a + // pairwise mapper only understands the pairwise sub, so the user + // member is rewritten while the other members pass through. + String sessionId = "fake-session-id-123"; + try (SimpleHttpResponse res = http.doPost(emitEndpointUrl(PAIRWISE_RECEIVER)) + .auth(adminClient.tokenManager().getAccessTokenString()) + .json(Map.of( + "eventType", "CaepSessionRevoked", + "sub_id", Map.of( + "format", "complex", + "user", Map.of("format", "iss_sub", "iss", realm.getBaseUrl(), "sub", testUserId), + "session", Map.of("format", "opaque", "id", sessionId)), + "event", Map.of("event_timestamp", System.currentTimeMillis() / 1000))) + .asResponse()) { + Assertions.assertEquals(200, res.getStatus(), () -> "emit should succeed; body=" + safeBody(res)); + Assertions.assertEquals("dispatched", res.asJson().get("status").asText()); + } + + String push = pairwisePushes.poll(PUSH_WAIT_SECONDS, TimeUnit.SECONDS); + Assertions.assertNotNull(push, "the emitted event must reach the pairwise receiver"); + + JsonNode set = decodeSet(push); + JsonNode subId = set.path("sub_id"); + Assertions.assertEquals("complex", subId.path("format").asText()); + Assertions.assertEquals("iss_sub", subId.path("user").path("format").asText()); + Assertions.assertEquals(pairwiseSubject, subId.path("user").path("sub").asText(), + "the user member must carry the receiver's pairwise sub"); + Assertions.assertEquals(sessionId, subId.path("session").path("id").asText(), + "the session member must pass through unchanged"); + Assertions.assertFalse(set.toString().contains(testUserId), + "the internal user ID must not appear anywhere in the SET"); + } + + // --- triggers ---------------------------------------------------------- + + protected void setUserEnabled(boolean enabled) { + UserResource userResource = realm.admin().users().get(testUserId); + UserRepresentation rep = userResource.toRepresentation(); + rep.setEnabled(enabled); + userResource.update(rep); + } + + protected String emitEndpointUrl(String receiver) { + return keycloakUrls.getAdmin() + "/realms/" + realm.getName() + + "/ssf/clients/" + receiver + "/events/emit"; + } + + // --- setup --------------------------------------------------------------- + + protected HttpHandler collectingHandler(BlockingQueue queue) { + return new HttpHandler() { + @Override + public void handle(HttpExchange exchange) throws IOException { + try (InputStream is = exchange.getRequestBody()) { + queue.add(new String(is.readAllBytes(), StandardCharsets.UTF_8)); + } + HttpServerUtil.sendResponse(exchange, 202, Map.of()); + } + }; + } + + protected void createPushStream(String receiver, String secret, String pushContextPath) throws IOException { + StreamDeliveryConfig delivery = new StreamDeliveryConfig(); + delivery.setMethod(Ssf.DELIVERY_METHOD_PUSH_URI); + delivery.setEndpointUrl(MOCK_PUSH_BASE_URL + pushContextPath); + delivery.setAuthorizationHeader(PUSH_AUTH_HEADER); + + StreamConfig streamConfig = new StreamConfig(); + streamConfig.setDelivery(delivery); + streamConfig.setEventsRequested(Set.of(RiscAccountDisabled.TYPE, RiscAccountEnabled.TYPE, CaepSessionRevoked.TYPE)); + streamConfig.setDescription("Pairwise subject integration test"); + + String token = obtainReceiverManageToken(receiver, secret); + try (SimpleHttpResponse response = http.doPost(SsfTransmitterUrls.getStreamsEndpointUrl(realm.getBaseUrl())) + .json(streamConfig) + .auth(token) + .acceptJson() + .asResponse()) { + Assertions.assertEquals(201, response.getStatus(), + () -> "stream creation should succeed in test setup; body=" + safeBody(response)); + } + } + + protected String obtainReceiverManageToken(String receiver, String secret) throws IOException { + String tokenUrl = realm.getBaseUrl() + "/protocol/openid-connect/token"; + try (SimpleHttpResponse response = http.doPost(tokenUrl) + .authBasic(receiver, secret) + .param("grant_type", "client_credentials") + .param("scope", SsfScopes.SCOPE_SSF_MANAGE + " " + SsfScopes.SCOPE_SSF_READ) + .asResponse()) { + Assertions.assertEquals(200, response.getStatus(), + "client_credentials grant should succeed for the receiver"); + return response.asJson().get("access_token").asText(); + } + } + + /** + * Logs the test user in to the given client and returns the + * {@code sub} of the issued access token — the user identifier the + * client actually knows. + */ + protected String obtainTokenSubject(String clientId, String secret) throws IOException { + String tokenUrl = realm.getBaseUrl() + "/protocol/openid-connect/token"; + try (SimpleHttpResponse response = http.doPost(tokenUrl) + .authBasic(clientId, secret) + .param("grant_type", "password") + .param("username", TEST_USER) + .param("password", TEST_PASSWORD) + .asResponse()) { + Assertions.assertEquals(200, response.getStatus(), + () -> "password grant should succeed for " + clientId + "; body=" + safeBody(response)); + String accessToken = response.asJson().get("access_token").asText(); + try { + return decodeSet(accessToken).path("sub").asText(); + } catch (Exception e) { + throw new IOException("Could not decode access token", e); + } + } + } + + protected void subscribeTestUser(String receiver) throws IOException { + String url = keycloakUrls.getAdmin() + "/realms/" + realm.getName() + + "/ssf/clients/" + receiver + "/subjects/add"; + try (SimpleHttpResponse response = http.doPost(url) + .auth(adminClient.tokenManager().getAccessTokenString()) + .json(Map.of("type", "user-email", "value", TEST_EMAIL)) + .asResponse()) { + Assertions.assertTrue(response.getStatus() >= 200 && response.getStatus() < 300, + () -> "subscribing the test user should succeed; body=" + safeBody(response)); + } + } + + // --- helpers --------------------------------------------------------- + + protected JsonNode decodeSet(String encoded) throws Exception { + JWSInput jws = new JWSInput(encoded); + return JsonSerialization.readValue(jws.getContent(), JsonNode.class); + } + + protected void assignOptionalClientScopes(String clientId, String... scopeNames) { + ClientRepresentation client = findClientByClientId(clientId); + Assertions.assertNotNull(client, () -> "expected client '" + clientId + "' to exist"); + ClientResource clientResource = realm.admin().clients().get(client.getId()); + + Set alreadyAssigned = clientResource.getOptionalClientScopes().stream() + .map(ClientScopeRepresentation::getName) + .collect(Collectors.toSet()); + + List allScopes = realm.admin().clientScopes().findAll(); + for (String scopeName : scopeNames) { + if (alreadyAssigned.contains(scopeName)) { + continue; + } + ClientScopeRepresentation scope = allScopes.stream() + .filter(s -> scopeName.equals(s.getName())) + .findFirst() + .orElse(null); + Assertions.assertNotNull(scope, + () -> "expected realm scope '" + scopeName + "' to exist"); + clientResource.addOptionalClientScope(scope.getId()); + } + } + + protected ClientRepresentation findClientByClientId(String clientId) { + List clients = realm.admin().clients().findByClientId(clientId); + if (clients.isEmpty()) { + return null; + } + return clients.get(0); + } + + protected void bestEffortDeleteStream(String receiver) { + String adminStreamUrl = keycloakUrls.getAdmin() + "/realms/" + realm.getName() + + "/ssf/clients/" + receiver + "/stream"; + try (SimpleHttpResponse ignored = http.doDelete(adminStreamUrl) + .auth(adminClient.tokenManager().getAccessTokenString()) + .asResponse()) { + // 204 / 404 both fine + } catch (IOException e) { + // best-effort + } + } + + private String safeBody(SimpleHttpResponse response) { + try { + return response.asString(); + } catch (Exception e) { + return ""; + } + } + + // --- config ---------------------------------------------------------- + + public static class PairwiseServerConfig extends DefaultKeycloakServerConfig { + @Override + public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) { + KeycloakServerConfigBuilder configured = super.configure(config); + config.features(Profile.Feature.SSF); + config.log().categoryLevel("org.keycloak.ssf", "DEBUG"); + config.spiOption("ssf-transmitter", "default", + DefaultSsfTransmitterProviderFactory.CONFIG_OUTBOX_DRAINER_INTERVAL, "500ms"); + config.spiOption("ssf-transmitter", "default", + SsfTransmitterConfig.CONFIG_MIN_VERIFICATION_INTERVAL_SECONDS, "0"); + config.spiOption("ssf-transmitter", "default", + SsfTransmitterConfig.CONFIG_ALLOW_INSECURE_PUSH_TARGETS, "true"); + return configured; + } + } + + public static class PairwiseRealm implements RealmConfig { + + @Override + public RealmBuilder configure(RealmBuilder realm) { + realm.name("ssf-transmitter-pairwise"); + realm.attribute(Ssf.SSF_TRANSMITTER_ENABLED_KEY, "true"); + + realm.eventsEnabled(true); + realm.adminEventsEnabled(true); + realm.eventsListeners("jboss-logging", "ssf-events"); + + realm.users( + UserBuilder.create(TEST_USER) + .email(TEST_EMAIL) + .firstName("Ada") + .lastName("PairwiseTester") + .enabled(true) + .password(TEST_PASSWORD) + .build() + ); + + realm.clients( + receiver(PAIRWISE_RECEIVER, PAIRWISE_RECEIVER_SECRET, "NONE") + // No sector identifier URI: the sector is derived + // from the host of the client's redirect URIs. + .redirectUris("https://pairwise-receiver.local.test/*") + .protocolMappers(pairwiseSubMapper()) + .build(), + receiver(PLAIN_RECEIVER, PLAIN_RECEIVER_SECRET, "ALL") + .build() + ); + + return realm; + } + + private static ClientBuilder receiver(String clientId, String secret, String defaultSubjects) { + return ClientBuilder.create(clientId) + .secret(secret) + .serviceAccountsEnabled(true) + // Used by the tests to learn the sub the client sees in its tokens. + .directAccessGrantsEnabled(true) + .publicClient(false) + .attribute(ClientStreamStore.SSF_ENABLED_KEY, "true") + .attribute(ClientStreamStore.SSF_VALID_PUSH_URLS_KEY, MOCK_PUSH_BASE_URL + "/*") + .attribute(ClientStreamStore.SSF_DEFAULT_SUBJECTS_KEY, defaultSubjects); + } + + private static ProtocolMapperRepresentation pairwiseSubMapper() { + ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation(); + mapper.setName("pairwise subject identifier"); + mapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); + mapper.setProtocolMapper("oidc-sha256-pairwise-sub-mapper"); + mapper.setConfig(Map.of(PairwiseSubMapperHelper.PAIRWISE_SUB_ALGORITHM_SALT, "pairwise-test-salt")); + return mapper; + } + } +} diff --git a/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/delivery/SecurityEventTokenDispatcher.java b/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/delivery/SecurityEventTokenDispatcher.java index 6c4638f3ed1a..53a1125028ce 100644 --- a/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/delivery/SecurityEventTokenDispatcher.java +++ b/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/delivery/SecurityEventTokenDispatcher.java @@ -14,6 +14,7 @@ import org.keycloak.ssf.event.token.SsfSecurityEventToken; import org.keycloak.ssf.stream.DeliveryMethod; import org.keycloak.ssf.stream.StreamStatusValue; +import org.keycloak.ssf.subject.SubjectId; import org.keycloak.ssf.transmitter.SsfTransmitterConfig; import org.keycloak.ssf.transmitter.delivery.push.PushDeliveryService; import org.keycloak.ssf.transmitter.event.SecurityEventTokenEncoder; @@ -21,6 +22,7 @@ import org.keycloak.ssf.transmitter.metrics.SsfMetricsBinder; import org.keycloak.ssf.transmitter.outbox.SsfOutboxKinds; import org.keycloak.ssf.transmitter.stream.StreamConfig; +import org.keycloak.ssf.transmitter.subject.PairwiseSubjectRewriter; import org.keycloak.ssf.transmitter.subject.SsfSubjectInclusionResolver; import org.keycloak.ssf.transmitter.subject.SubjectSubscriptionFilter; @@ -51,6 +53,8 @@ public class SecurityEventTokenDispatcher { protected final SubjectSubscriptionFilter subjectSubscriptionFilter; + protected final PairwiseSubjectRewriter pairwiseSubjectRewriter; + protected final SsfMetricsBinder metricsBinder; protected final SsfSubjectInclusionResolver subjectInclusionResolver; @@ -88,9 +92,14 @@ public SecurityEventTokenDispatcher(KeycloakSession session, this.outboxStoreFactory = outboxStoreFactory; this.subjectInclusionResolver = subjectInclusionResolver; this.subjectSubscriptionFilter = createSubjectSubscriptionFilter(); + this.pairwiseSubjectRewriter = createPairwiseSubjectRewriter(); this.metricsBinder = metricsBinder == null ? SsfMetricsBinder.NOOP : metricsBinder; } + protected PairwiseSubjectRewriter createPairwiseSubjectRewriter() { + return new PairwiseSubjectRewriter(session); + } + protected SubjectSubscriptionFilter createSubjectSubscriptionFilter() { if (transmitterConfig == null) { return DEFAULT_SUBJECT_SUBSCRIPTION_FILTER; @@ -493,6 +502,11 @@ protected void enqueueForPoll(StreamConfig stream, } protected SecurityEventToken getNarrowedEventToken(SsfSecurityEventToken eventToken, StreamConfig stream) { + // Shape the subject for this receiver first, so that both profile + // branches below — including the SSE CAEP conversion, which copies + // the subject into the event payload — see the receiver's view. + eventToken = applyReceiverSubject(eventToken, stream); + // StreamConfig.getProfile() is an SsfProfile enum — comparing it against // the String constants in Ssf (Ssf.PROFILE_SSF_1_0 etc.) always returned // false, so neither branch ever fired and the SSE CAEP converter was @@ -511,6 +525,35 @@ protected SecurityEventToken getNarrowedEventToken(SsfSecurityEventToken eventTo }; } + /** + * Replaces the internal user ID in the SET subject with the receiver + * client's pairwise subject identifier, when the receiver has a + * pairwise subject identifier mapper configured — see + * {@link PairwiseSubjectRewriter}. + * + *

Runs as part of the per-stream narrowing step, i.e. after the + * subject gates and right before signing, so everything upstream + * (and the outbox bookkeeping, which records the original token) + * keeps working on the internal user ID. Returns the given token + * when nothing changes and a copy otherwise; the given token is + * never modified. + * + *

Throws {@link org.keycloak.ssf.SsfException} if the pairwise + * subject cannot be computed. The callers treat that as a failed + * delivery, so the internal user ID is never sent as a fallback. + */ + protected SsfSecurityEventToken applyReceiverSubject(SsfSecurityEventToken eventToken, StreamConfig stream) { + SubjectId subjectId = eventToken.getSubjectId(); + SubjectId receiverSubjectId = pairwiseSubjectRewriter.rewrite(subjectId, stream, eventToken.getIss()); + if (receiverSubjectId == subjectId) { + return eventToken; + } + + SsfSecurityEventToken receiverToken = eventToken.copy(); + receiverToken.setSubjectId(receiverSubjectId); + return receiverToken; + } + /** * Narrows a {@link SsfSecurityEventToken} into a more general {@link SecurityEventToken}. * diff --git a/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriter.java b/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriter.java new file mode 100644 index 000000000000..662e0a42e527 --- /dev/null +++ b/ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriter.java @@ -0,0 +1,226 @@ +package org.keycloak.ssf.transmitter.subject; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.ProtocolMapperModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; +import org.keycloak.protocol.ProtocolMapper; +import org.keycloak.protocol.oidc.mappers.AbstractPairwiseSubMapper; +import org.keycloak.provider.ProviderFactory; +import org.keycloak.ssf.SsfException; +import org.keycloak.ssf.subject.ComplexSubjectId; +import org.keycloak.ssf.subject.IssuerSubjectId; +import org.keycloak.ssf.subject.OpaqueSubjectId; +import org.keycloak.ssf.subject.SubjectId; +import org.keycloak.ssf.subject.SubjectUserLookup; +import org.keycloak.ssf.transmitter.stream.StreamConfig; + +/** + * Replaces the internal Keycloak user ID in the subject of an outgoing + * Security Event Token with the pairwise subject identifier of the + * receiver client, when that client has a pairwise subject identifier + * mapper configured. + * + *

A client with a pairwise mapper only ever sees the pairwise + * {@code sub} in its ID tokens, access tokens and logout tokens, so it + * cannot correlate a SET that carries the internal user ID — and + * sending that ID would hand the receiver the very global identifier + * the pairwise mapper is meant to hide. + * + *

The rewrite runs at delivery time, right before the SET is signed + * for one specific stream. Everything upstream — the subject gates, + * the purge snapshot lookups and the trusted-emitter subject + * resolution — keeps working on the internal user ID. + * + *

Only subjects that identify a local user by its ID are rewritten: + * an {@code iss_sub} subject whose issuer is this realm, and an + * {@code opaque} subject whose ID resolves to a user. For a complex + * subject only the {@code user} member is considered. All other + * formats ({@code email}, federated {@code iss_sub}, ...) pass through + * unchanged. + * + *

Only mappers defined directly on the receiver client are + * considered, in line with + * {@link org.keycloak.protocol.oidc.utils.PairwiseSubMapperUtils#isPairwiseSubjectMatching}. + */ +public class PairwiseSubjectRewriter { + + protected final KeycloakSession session; + + public PairwiseSubjectRewriter(KeycloakSession session) { + this.session = session; + } + + /** + * Returns the subject to put on the wire for the given stream. + * Returns the very same {@code subjectId} instance when nothing + * needs to change; otherwise a copy — the given subject is never + * modified. + * + * @param subjectId the subject of the outgoing SET, may be {@code null} + * @param stream the stream the SET is delivered to + * @param tokenIssuer the {@code iss} of the outgoing SET + * @throws SsfException if the receiver has a pairwise mapper but + * the pairwise subject cannot be computed. The + * internal user ID is never used as a fallback. + */ + public SubjectId rewrite(SubjectId subjectId, StreamConfig stream, String tokenIssuer) { + + if (subjectId == null || stream == null || stream.getClientId() == null) { + return subjectId; + } + + SubjectId userSubject = subjectId instanceof ComplexSubjectId complex ? complex.getUser() : subjectId; + String userId = extractLocalUserId(userSubject, tokenIssuer); + if (userId == null) { + return subjectId; + } + + RealmModel realm = session.getContext().getRealm(); + ClientModel receiverClient = realm.getClientById(stream.getClientId()); + if (receiverClient == null) { + return subjectId; + } + + PairwiseMapper pairwiseMapper = findPairwiseMapper(receiverClient); + if (pairwiseMapper == null) { + return subjectId; + } + + UserModel user = PurgedUserSnapshot.resolveUserOrSnapshot(session, realm, userId); + if (user == null) { + if (userSubject instanceof OpaqueSubjectId) { + // An opaque ID is not necessarily a user ID (e.g. the stream + // ID of a verification event), so there is nothing to hide. + return subjectId; + } + throw new SsfException("Receiver client has a pairwise subject identifier mapper but the user of the " + + "event subject could not be resolved. clientId=" + receiverClient.getClientId() + + " streamId=" + stream.getStreamId()); + } + + String pairwiseSubject = generatePairwiseSubject(pairwiseMapper, receiverClient, user, stream); + SubjectId rewrittenUserSubject = withUserIdentifier(userSubject, pairwiseSubject); + + if (subjectId instanceof ComplexSubjectId complex) { + return withUser(complex, rewrittenUserSubject); + } + return rewrittenUserSubject; + } + + /** + * Returns the internal user ID the given subject refers to, or + * {@code null} if the subject does not identify a local user by its + * ID and therefore is not a candidate for the rewrite. + */ + protected String extractLocalUserId(SubjectId userSubject, String tokenIssuer) { + if (userSubject instanceof IssuerSubjectId issuerSubject) { + String sub = issuerSubject.getSub(); + if (sub == null || sub.isBlank() || !isLocalIssuer(issuerSubject.getIss(), tokenIssuer)) { + return null; + } + return sub; + } + if (userSubject instanceof OpaqueSubjectId opaqueSubject) { + String id = opaqueSubject.getId(); + return id == null || id.isBlank() ? null : id; + } + return null; + } + + /** + * Returns {@code true} if the issuer of an {@code iss_sub} subject + * is this transmitter, which means {@code sub} is an internal user + * ID. Natively emitted events reuse the issuer of the SET; subjects + * supplied by a trusted emitter use the realm issuer. + */ + protected boolean isLocalIssuer(String subjectIssuer, String tokenIssuer) { + if (subjectIssuer == null) { + return false; + } + return subjectIssuer.equals(tokenIssuer) || SubjectUserLookup.isRealmIssuer(session, subjectIssuer); + } + + /** + * Finds the first pairwise subject identifier mapper defined + * directly on the receiver client, or {@code null} if there is none. + */ + protected PairwiseMapper findPairwiseMapper(ClientModel receiverClient) { + KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory(); + return receiverClient.getProtocolMappersStream() + .map(mapperModel -> { + ProviderFactory factory = + sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper()); + return factory instanceof AbstractPairwiseSubMapper mapper + ? new PairwiseMapper(mapperModel, mapper) + : null; + }) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); + } + + protected String generatePairwiseSubject(PairwiseMapper pairwiseMapper, ClientModel receiverClient, + UserModel user, StreamConfig stream) { + String pairwiseSubject; + try { + pairwiseSubject = pairwiseMapper.mapper().generateSub(pairwiseMapper.model(), receiverClient, user); + } catch (RuntimeException e) { + throw new SsfException("Could not compute the pairwise subject identifier for the receiver client. " + + "clientId=" + receiverClient.getClientId() + " streamId=" + stream.getStreamId(), e); + } + if (pairwiseSubject == null || pairwiseSubject.isBlank()) { + throw new SsfException("Pairwise subject identifier mapper returned no subject for the receiver client. " + + "clientId=" + receiverClient.getClientId() + " streamId=" + stream.getStreamId()); + } + return pairwiseSubject; + } + + /** + * Returns a copy of the given user subject that carries + * {@code identifier} instead of the internal user ID. + */ + protected SubjectId withUserIdentifier(SubjectId userSubject, String identifier) { + if (userSubject instanceof IssuerSubjectId issuerSubject) { + IssuerSubjectId copy = new IssuerSubjectId(); + copy.setIss(issuerSubject.getIss()); + copy.setSub(identifier); + copyAttributes(issuerSubject, copy); + return copy; + } + OpaqueSubjectId copy = new OpaqueSubjectId(); + copy.setId(identifier); + copyAttributes(userSubject, copy); + return copy; + } + + /** + * Returns a copy of the given complex subject with the {@code user} + * member replaced. + */ + protected ComplexSubjectId withUser(ComplexSubjectId complex, SubjectId userSubject) { + ComplexSubjectId copy = complex.copy(); + copy.setUser(userSubject); + return copy; + } + + protected void copyAttributes(SubjectId source, SubjectId target) { + Map attributes = source.getAttributes(); + if (attributes != null) { + target.setAttributes(new HashMap<>(attributes)); + } + } + + /** + * A pairwise subject identifier mapper together with its + * configuration on the receiver client. + */ + protected record PairwiseMapper(ProtocolMapperModel model, AbstractPairwiseSubMapper mapper) { + } +} diff --git a/ssf/transmitter/src/test/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriterTest.java b/ssf/transmitter/src/test/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriterTest.java new file mode 100644 index 000000000000..7c2f8087aa4e --- /dev/null +++ b/ssf/transmitter/src/test/java/org/keycloak/ssf/transmitter/subject/PairwiseSubjectRewriterTest.java @@ -0,0 +1,268 @@ +package org.keycloak.ssf.transmitter.subject; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.KeycloakContext; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.KeycloakUriInfo; +import org.keycloak.models.ProtocolMapperModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.UserProvider; +import org.keycloak.protocol.ProtocolMapper; +import org.keycloak.protocol.oidc.mappers.PairwiseSubMapperHelper; +import org.keycloak.protocol.oidc.mappers.SHA256PairwiseSubMapper; +import org.keycloak.protocol.oidc.mappers.UserAttributeMapper; +import org.keycloak.ssf.SsfException; +import org.keycloak.ssf.subject.ComplexSubjectId; +import org.keycloak.ssf.subject.EmailSubjectId; +import org.keycloak.ssf.subject.IssuerSubjectId; +import org.keycloak.ssf.subject.OpaqueSubjectId; +import org.keycloak.ssf.subject.SubjectId; +import org.keycloak.ssf.transmitter.stream.StreamConfig; +import org.keycloak.urls.UrlType; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Unit tests for {@link PairwiseSubjectRewriter}: which subjects are + * rewritten to the receiver client's pairwise subject identifier, which + * pass through, and that the internal user ID is never used as a + * fallback. + */ +class PairwiseSubjectRewriterTest { + + static final String REALM_NAME = "test"; + static final String BASE_URI = "https://kc.example.test/"; + static final String ISSUER = "https://kc.example.test/realms/" + REALM_NAME; + static final String FOREIGN_ISSUER = "https://idp.example.test"; + + static final String CLIENT_UUID = "receiver-client-uuid"; + static final String USER_ID = "8f6b1a52-6f0b-4c0e-9d0c-2f1f8d1f7a11"; + + static final String SECTOR_IDENTIFIER_URI = "https://receiver.example.test/sector.json"; + static final String SALT = "test-salt"; + + static final String PAIRWISE_MAPPER_ID = "oidc-sha256-pairwise-sub-mapper"; + static final String OTHER_MAPPER_ID = UserAttributeMapper.PROVIDER_ID; + + KeycloakSession session; + RealmModel realm; + ClientModel receiverClient; + UserProvider userProvider; + UserModel user; + StreamConfig stream; + + SHA256PairwiseSubMapper pairwiseMapper = new SHA256PairwiseSubMapper(); + PairwiseSubjectRewriter rewriter; + + @BeforeEach + void setUp() { + session = mock(KeycloakSession.class); + realm = mock(RealmModel.class); + receiverClient = mock(ClientModel.class); + userProvider = mock(UserProvider.class); + user = mock(UserModel.class); + + KeycloakContext context = mock(KeycloakContext.class); + KeycloakUriInfo uriInfo = mock(KeycloakUriInfo.class); + KeycloakSessionFactory sessionFactory = mock(KeycloakSessionFactory.class); + + lenient().when(session.getContext()).thenReturn(context); + lenient().when(context.getRealm()).thenReturn(realm); + lenient().when(context.getUri(UrlType.FRONTEND)).thenReturn(uriInfo); + lenient().when(uriInfo.getBaseUri()).thenReturn(URI.create(BASE_URI)); + lenient().when(realm.getName()).thenReturn(REALM_NAME); + lenient().when(realm.getClientById(CLIENT_UUID)).thenReturn(receiverClient); + lenient().when(receiverClient.getClientId()).thenReturn("receiver"); + + lenient().when(session.users()).thenReturn(userProvider); + lenient().when(userProvider.getUserById(realm, USER_ID)).thenReturn(user); + lenient().when(user.getId()).thenReturn(USER_ID); + + lenient().when(session.getKeycloakSessionFactory()).thenReturn(sessionFactory); + lenient().when(sessionFactory.getProviderFactory(ProtocolMapper.class, PAIRWISE_MAPPER_ID)) + .thenReturn(pairwiseMapper); + lenient().when(sessionFactory.getProviderFactory(ProtocolMapper.class, OTHER_MAPPER_ID)) + .thenReturn(new UserAttributeMapper()); + + stream = new StreamConfig(); + stream.setStreamId("stream-1"); + stream.setClientId(CLIENT_UUID); + + rewriter = new PairwiseSubjectRewriter(session); + } + + @Test + void issSubWithLocalIssuer_isRewrittenToPairwiseSubject() { + receiverHasMappers(otherMapper(), pairwiseMapper()); + IssuerSubjectId subject = issSub(ISSUER, USER_ID); + + SubjectId result = rewriter.rewrite(subject, stream, ISSUER); + + IssuerSubjectId rewritten = assertInstanceOf(IssuerSubjectId.class, result); + assertNotSame(subject, rewritten, "the original subject must not be reused"); + assertEquals(ISSUER, rewritten.getIss()); + assertEquals(expectedPairwiseSubject(), rewritten.getSub()); + assertNotEquals(USER_ID, rewritten.getSub()); + assertEquals(USER_ID, subject.getSub(), "the original subject must not be modified"); + } + + @Test + void issSubWithRealmIssuerDifferentFromTokenIssuer_isRewritten() { + // A trusted emitter names the user with the realm issuer; the SET + // itself may be issued under a different (SSF-specific) issuer URL. + receiverHasMappers(pairwiseMapper()); + + SubjectId result = rewriter.rewrite(issSub(ISSUER, USER_ID), stream, "https://ssf.example.test/issuer"); + + assertEquals(expectedPairwiseSubject(), assertInstanceOf(IssuerSubjectId.class, result).getSub()); + } + + @Test + void complexSubject_onlyUserMemberIsRewritten() { + receiverHasMappers(pairwiseMapper()); + ComplexSubjectId complex = new ComplexSubjectId(); + complex.setUser(issSub(ISSUER, USER_ID)); + OpaqueSubjectId sessionSubject = opaque("session-1"); + complex.setSession(sessionSubject); + OpaqueSubjectId tenantSubject = opaque("tenant-1"); + complex.setTenant(tenantSubject); + + SubjectId result = rewriter.rewrite(complex, stream, ISSUER); + + ComplexSubjectId rewritten = assertInstanceOf(ComplexSubjectId.class, result); + assertNotSame(complex, rewritten); + assertEquals(expectedPairwiseSubject(), assertInstanceOf(IssuerSubjectId.class, rewritten.getUser()).getSub()); + assertSame(sessionSubject, rewritten.getSession()); + assertSame(tenantSubject, rewritten.getTenant()); + assertEquals(USER_ID, ((IssuerSubjectId) complex.getUser()).getSub(), + "the original subject must not be modified"); + } + + @Test + void opaqueSubjectResolvingToUser_isRewritten() { + receiverHasMappers(pairwiseMapper()); + + SubjectId result = rewriter.rewrite(opaque(USER_ID), stream, ISSUER); + + assertEquals(expectedPairwiseSubject(), assertInstanceOf(OpaqueSubjectId.class, result).getId()); + } + + @Test + void opaqueSubjectNotResolvingToUser_passesThrough() { + // e.g. the stream ID subject of a verification event + receiverHasMappers(pairwiseMapper()); + OpaqueSubjectId subject = opaque("stream-1"); + + assertSame(subject, rewriter.rewrite(subject, stream, ISSUER)); + } + + @Test + void receiverWithoutPairwiseMapper_passesThrough() { + receiverHasMappers(otherMapper()); + IssuerSubjectId subject = issSub(ISSUER, USER_ID); + + assertSame(subject, rewriter.rewrite(subject, stream, ISSUER)); + } + + @Test + void issSubWithForeignIssuer_passesThrough() { + receiverHasMappers(pairwiseMapper()); + IssuerSubjectId subject = issSub(FOREIGN_ISSUER, "external-subject"); + + assertSame(subject, rewriter.rewrite(subject, stream, ISSUER)); + } + + @Test + void emailSubject_passesThrough() { + receiverHasMappers(pairwiseMapper()); + EmailSubjectId subject = new EmailSubjectId(); + subject.setEmail("user@example.test"); + + assertSame(subject, rewriter.rewrite(subject, stream, ISSUER)); + } + + @Test + void nullSubject_passesThrough() { + assertSame(null, rewriter.rewrite(null, stream, ISSUER)); + } + + @Test + void issSubWithUnresolvableUser_failsInsteadOfLeakingTheUserId() { + receiverHasMappers(pairwiseMapper()); + + assertThrows(SsfException.class, + () -> rewriter.rewrite(issSub(ISSUER, "unknown-user-id"), stream, ISSUER)); + } + + @Test + void pairwiseSubjectNotComputable_failsInsteadOfLeakingTheUserId() { + // No salt: the mapper cannot compute a subject. + ProtocolMapperModel broken = pairwiseMapper(); + broken.getConfig().remove(PairwiseSubMapperHelper.PAIRWISE_SUB_ALGORITHM_SALT); + receiverHasMappers(broken); + + assertThrows(SsfException.class, + () -> rewriter.rewrite(issSub(ISSUER, USER_ID), stream, ISSUER)); + } + + // --- helpers ----------------------------------------------------------- + + /** The value the same client would see as {@code sub} in its tokens. */ + String expectedPairwiseSubject() { + return pairwiseMapper.generateSub(pairwiseMapper(), receiverClient, user); + } + + void receiverHasMappers(ProtocolMapperModel... mappers) { + when(receiverClient.getProtocolMappersStream()).thenAnswer(invocation -> Stream.of(mappers)); + } + + static ProtocolMapperModel pairwiseMapper() { + ProtocolMapperModel model = new ProtocolMapperModel(); + model.setName("pairwise"); + model.setProtocolMapper(PAIRWISE_MAPPER_ID); + Map config = new HashMap<>(); + config.put(PairwiseSubMapperHelper.SECTOR_IDENTIFIER_URI, SECTOR_IDENTIFIER_URI); + config.put(PairwiseSubMapperHelper.PAIRWISE_SUB_ALGORITHM_SALT, SALT); + model.setConfig(config); + return model; + } + + static ProtocolMapperModel otherMapper() { + ProtocolMapperModel model = new ProtocolMapperModel(); + model.setName("other"); + model.setProtocolMapper(OTHER_MAPPER_ID); + model.setConfig(new HashMap<>()); + return model; + } + + static IssuerSubjectId issSub(String iss, String sub) { + IssuerSubjectId subject = new IssuerSubjectId(); + subject.setIss(iss); + subject.setSub(sub); + return subject; + } + + static OpaqueSubjectId opaque(String id) { + OpaqueSubjectId subject = new OpaqueSubjectId(); + subject.setId(id); + return subject; + } +}