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 @@ -46,6 +46,7 @@
import org.apache.knox.gateway.i18n.GatewaySpiResources;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
import org.apache.knox.gateway.security.ActorChainPrincipal;
import org.apache.knox.gateway.security.GroupPrincipal;
import org.apache.knox.gateway.security.ImpersonatedPrincipal;
import org.apache.knox.gateway.security.PrimaryPrincipal;
Expand Down Expand Up @@ -147,14 +148,19 @@ protected void continueChainAsPrincipal(HttpServletRequestWrapper request, Servl
final Set<TokenIdPrincipal> tokenIdPrincipals = SubjectUtils.getTokenIdPrincipals(currentSubject);
subject.getPrincipals().addAll(tokenIdPrincipals);

// RFC 8693 Token Exchange: Preserve ActorChainPrincipal from the current subject
// This ensures the delegation chain is maintained through identity assertion
final Set<ActorChainPrincipal> actorChainPrincipals = SubjectUtils.getActorChainPrincipal(currentSubject, subject);
subject.getPrincipals().addAll(actorChainPrincipals);

doAs(request, response, chain, subject);
}
else {
doFilterInternal(request, response, chain);
}
}

private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
throws IOException, ServletException {
try {
Subject.doAs(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -67,6 +68,7 @@
import org.apache.knox.gateway.filter.AbstractGatewayFilter;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
import org.apache.knox.gateway.security.ActorChainPrincipalImpl;
import org.apache.knox.gateway.security.PrimaryPrincipal;
import org.apache.knox.gateway.security.SubjectUtils;
import org.apache.knox.gateway.security.TokenIdPrincipal;
Expand Down Expand Up @@ -386,14 +388,16 @@ protected Subject createSubjectFromToken(final JWT token) throws UnknownTokenExc
if (expectedPrincipalClaim != null) {
claimvalue = token.getClaim(expectedPrincipalClaim);
}
// Extract actor chain from the JWT token if present (RFC 8693)
List<Map<String, Object>> actorChain = TokenUtils.extractActorChain(token);
// The newly constructed Sets check whether this Subject has been set read-only
// before permitting subsequent modifications. The newly created Sets also prevent
// illegal modifications by ensuring that callers have sufficient permissions.
//
// To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals").
// To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials").
// To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
return createSubjectFromTokenData(principal, claimvalue);
return createSubjectFromTokenData(principal, claimvalue, null, actorChain);
}

public Subject createSubjectFromTokenIdentifier(final String tokenId) throws UnknownTokenException {
Expand All @@ -419,11 +423,19 @@ public Subject createSubjectFromTokenIdentifier(final String tokenId) throws Unk

@SuppressWarnings("rawtypes")
protected Subject createSubjectFromTokenData(final String principal, final String expectedPrincipalClaimValue) {
return createSubjectFromTokenData(principal, expectedPrincipalClaimValue, null);
return createSubjectFromTokenData(principal, expectedPrincipalClaimValue, null, null);
}

@SuppressWarnings("rawtypes")
protected Subject createSubjectFromTokenData(final String principal, final String expectedPrincipalClaimValue, final String tokenId) {
return createSubjectFromTokenData(principal, expectedPrincipalClaimValue, tokenId, null);
}

@SuppressWarnings("rawtypes")
protected Subject createSubjectFromTokenData(final String principal,
final String expectedPrincipalClaimValue,
final String tokenId,
final List<Map<String, Object>> actorChain) {
String claimValue =
(expectedPrincipalClaimValue != null) ? expectedPrincipalClaimValue.toLowerCase(Locale.ROOT) : null;

Expand All @@ -435,6 +447,11 @@ protected Subject createSubjectFromTokenData(final String principal, final Strin
principals.add(new TokenIdPrincipal(tokenId));
}

// Add ActorChainPrincipal if an actor chain is present (RFC 8693 token exchange)
if (actorChain != null && !actorChain.isEmpty()) {
principals.add(new ActorChainPrincipalImpl(actorChain));
}

// The newly constructed Sets check whether this Subject has been set read-only
// before permitting subsequent modifications. The newly created Sets also prevent
// illegal modifications by ensuring that callers have sufficient permissions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
import org.apache.knox.gateway.config.GatewayConfig;
import org.apache.knox.gateway.context.ContextAttributes;
import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.security.ActorChainPrincipal;
import org.apache.knox.gateway.security.GroupPrincipal;
import org.apache.knox.gateway.security.SubjectUtils;
import org.apache.knox.gateway.security.TokenIdPrincipal;
Expand Down Expand Up @@ -1106,21 +1107,41 @@ protected JWT getJWT(String userName, long expires, String jku) throws TokenServ
jwtAttributesBuilder.setClientId(tokenIdPrincipals.iterator().next().getName());
}

// RFC 8693 Token Exchange: Add the "act" claim if delegated auth is enabled and impersonation occurred
if (enableDelegatedAuth && SubjectUtils.isImpersonating(subject)) {
// RFC 8693 Token Exchange: Build the actor chain if delegated auth is enabled
handleDelegatedAuthentication(subject, jwtAttributesBuilder);
}

jwtAttributes = jwtAttributesBuilder.build();
token = ts.issueToken(jwtAttributes);
return token;
}

private void handleDelegatedAuthentication(Subject subject, JWTokenAttributesBuilder jwtAttributesBuilder) {
if (enableDelegatedAuth) {
// First check if there's an existing actor chain from a previous token exchange
Set<ActorChainPrincipal> actorChainPrincipals = subject.getPrincipals(ActorChainPrincipal.class);
List<Map<String, Object>> existingChain = null;
if (!actorChainPrincipals.isEmpty()) {
existingChain = actorChainPrincipals.iterator().next().getActorChain();
log.generalInfoMessage("Found existing actor chain with " + existingChain.size() + " actors");
}

// Check if impersonation is occurring to add a new actor to the chain
if (SubjectUtils.isImpersonating(subject)) {
String primaryPrincipalName = SubjectUtils.getPrimaryPrincipalName(subject);
String impersonatedPrincipalName = SubjectUtils.getImpersonatedPrincipalName(subject);
if (primaryPrincipalName != null && impersonatedPrincipalName != null && !primaryPrincipalName.equals(impersonatedPrincipalName)) {
// The primary principal (the one doing the impersonation) becomes the actor
jwtAttributesBuilder.setActor(primaryPrincipalName);
// Build the new actor chain by adding the current actor (primary principal) to the existing chain
List<Map<String, Object>> newActorChain = TokenUtils.addActorToChain(existingChain, primaryPrincipalName);
jwtAttributesBuilder.setActorChain(newActorChain);
log.addingActorClaimToToken(primaryPrincipalName, impersonatedPrincipalName);
}
} else if (existingChain != null && !existingChain.isEmpty()) {
// No new impersonation, but preserve existing actor chain
jwtAttributesBuilder.setActorChain(existingChain);
log.generalInfoMessage("Preserving existing actor chain without adding new actor");
}
}

jwtAttributes = jwtAttributesBuilder.build();
token = ts.issueToken(jwtAttributes);
return token;
}

private boolean shouldIncludeGroups() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.knox.gateway.service.knoxtoken;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.knox.gateway.security.ActorChainPrincipal;
import org.apache.knox.gateway.security.ActorChainPrincipalImpl;
import org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder;
import org.apache.knox.gateway.services.security.token.TokenUtils;
import org.apache.knox.gateway.services.security.token.impl.JWT;
import org.apache.knox.gateway.services.security.token.impl.JWTToken;
import org.junit.Test;

/**
* Test class to verify RFC 8693 actor chain functionality end-to-end.
*/
public class ActorChainTest {

@Test
public void testActorChainPreservation() throws Exception {
// Step 1: Create initial token with actor chain (simulating token from previous exchange)
List<Map<String, Object>> initialChain = new ArrayList<>();

Map<String, Object> actor1 = new LinkedHashMap<>();
actor1.put("sub", "service-a");
actor1.put("iss", "https://issuer.example.com");
initialChain.add(actor1);

Map<String, Object> actor2 = new LinkedHashMap<>();
actor2.put("sub", "service-b");
initialChain.add(actor2);

JWTokenAttributesBuilder builder1 = new JWTokenAttributesBuilder();
builder1.setUserName("end-user")
.setAlgorithm("RS256")
.setExpires(System.currentTimeMillis() + 30000)
.setActorChain(initialChain);

JWTToken token1 = new JWTToken(builder1.build());

// Step 2: Extract actor chain from token (simulating JWT validation)
List<Map<String, Object>> extractedChain = TokenUtils.extractActorChain(token1);
assertNotNull("Extracted chain should not be null", extractedChain);
assertEquals("Should have 2 actors", 2, extractedChain.size());
assertEquals("First actor should be service-a", "service-a", extractedChain.get(0).get("sub"));
assertEquals("Second actor should be service-b", "service-b", extractedChain.get(1).get("sub"));

// Step 3: Create ActorChainPrincipal (simulating what AbstractJWTFilter does)
ActorChainPrincipal actorChainPrincipal = new ActorChainPrincipalImpl(extractedChain);
assertEquals("Current actor should be service-a", "service-a", actorChainPrincipal.getCurrentActor());
assertEquals("Original delegator should be service-b", "service-b", actorChainPrincipal.getOriginalDelegator());

// Step 4: Add new actor to chain (simulating what TokenResource does)
String newActor = "service-c";
List<Map<String, Object>> newChain = TokenUtils.addActorToChain(extractedChain, newActor);
assertEquals("Should have 3 actors", 3, newChain.size());
assertEquals("New actor should be first", newActor, newChain.get(0).get("sub"));
assertEquals("Previous first actor should be second", "service-a", newChain.get(1).get("sub"));
assertEquals("Previous second actor should be third", "service-b", newChain.get(2).get("sub"));

// Step 5: Create new token with extended chain
JWTokenAttributesBuilder builder2 = new JWTokenAttributesBuilder();
builder2.setUserName("end-user")
.setAlgorithm("RS256")
.setExpires(System.currentTimeMillis() + 30000)
.setActorChain(newChain);

JWTToken token2 = new JWTToken(builder2.build());

// Step 6: Verify the new token has the complete chain
List<Map<String, Object>> finalChain = TokenUtils.extractActorChain(token2);
assertNotNull("Final chain should not be null", finalChain);
assertEquals("Should have 3 actors in final token", 3, finalChain.size());
assertEquals("First actor should be service-c", "service-c", finalChain.get(0).get("sub"));
assertEquals("Second actor should be service-a", "service-a", finalChain.get(1).get("sub"));
assertEquals("Third actor should be service-b", "service-b", finalChain.get(2).get("sub"));

// Verify issuer is preserved for actor1
assertEquals("Issuer should be preserved", "https://issuer.example.com", finalChain.get(1).get("iss"));
}

@Test
public void testActorChainInNestedStructure() throws ParseException {
// Create a token with nested actor structure
List<Map<String, Object>> chain = new ArrayList<>();

Map<String, Object> actor1 = new LinkedHashMap<>();
actor1.put("sub", "actor1");
chain.add(actor1);

Map<String, Object> actor2 = new LinkedHashMap<>();
actor2.put("sub", "actor2");
chain.add(actor2);

Map<String, Object> actor3 = new LinkedHashMap<>();
actor3.put("sub", "actor3");
chain.add(actor3);

JWTokenAttributesBuilder builder = new JWTokenAttributesBuilder();
builder.setUserName("testuser")
.setAlgorithm("RS256")
.setExpires(System.currentTimeMillis() + 30000)
.setActorChain(chain);

JWT token = new JWTToken(builder.build());

// Verify the act claim is present
Object actClaim = token.getClaimAsObject(JWTToken.ACT_CLAIM);
assertNotNull("Act claim should be present", actClaim);
assertTrue("Act claim should be a Map", actClaim instanceof Map);

// Verify nested structure
Map<?, ?> level1 = (Map<?, ?>) actClaim;
assertEquals("Level 1 sub should be actor1", "actor1", level1.get("sub"));

Object level2Act = level1.get(JWTToken.ACT_CLAIM);
assertNotNull("Level 2 act should be present", level2Act);
assertTrue("Level 2 act should be a Map", level2Act instanceof Map);

Map<?, ?> level2 = (Map<?, ?>) level2Act;
assertEquals("Level 2 sub should be actor2", "actor2", level2.get("sub"));

Object level3Act = level2.get(JWTToken.ACT_CLAIM);
assertNotNull("Level 3 act should be present", level3Act);
assertTrue("Level 3 act should be a Map", level3Act instanceof Map);

Map<?, ?> level3 = (Map<?, ?>) level3Act;
assertEquals("Level 3 sub should be actor3", "actor3", level3.get("sub"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.knox.gateway.security;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
* A Principal that represents the chain of actors (delegation chain) from RFC 8693 token exchange.
*
* <p>This principal is used to represent the 'act' claim chain from a JWT, which provides
* a means to express that delegation has occurred and identify the acting parties to whom
* authority has been delegated.</p>
*
* <p>The actor chain is ordered from most recent (current actor) to oldest (original delegator).
* Each actor in the chain is represented as a Map containing identity claims. According to
* RFC 8693 Section 4.1:</p>
* <ul>
* <li>Identity claims such as 'sub' (subject) and 'iss' (issuer) should be used to identify actors</li>
* <li>The combination of 'iss' and 'sub' may be necessary to uniquely identify an actor</li>
* <li>Non-identity claims (e.g., 'exp', 'nbf', 'aud') are NOT meaningful within 'act' claims
* and should not be used</li>
* </ul>
*
* <p>Example chain structure:</p>
* <pre>
* [
* {"sub": "service-c", "iss": "https://issuer.example.com"}, // Most recent actor
* {"sub": "service-b", "iss": "https://issuer.example.com"}, // Previous actor
* {"sub": "service-a"} // Original delegator
* ]
* </pre>
*
* @see <a href="https://datatracker.ietf.org/doc/html/rfc8693#section-4.1">RFC 8693 Section 4.1 - Actor Claim</a>
*/
public interface ActorChainPrincipal extends Principal {

/**
* Returns the chain of actors in order from most recent to oldest.
*
* <p>Each Map in the list represents an actor's claims, with at minimum a 'sub' claim.
* The first element in the list is the most recent actor (the one who directly
* performed the current delegation), and the last element is the original delegator.</p>
*
* @return an immutable list of actor claim maps, never null but may be empty
*/
List<Map<String, Object>> getActorChain();

/**
* Returns the subject (identity) of the most recent actor in the chain.
*
* <p>This is equivalent to calling {@code getActorChain().get(0).get("sub")}
* if the chain is not empty.</p>
*
* @return the subject of the most recent actor, or null if the chain is empty
Comment thread
smolnar82 marked this conversation as resolved.
*/
String getCurrentActor();

/**
* Returns the subject (identity) of the original delegator (the first actor in the chain).
*
* <p>This is the actor who initiated the delegation chain. It is equivalent to calling
* {@code getActorChain().get(getActorChain().size() - 1).get("sub")}
* if the chain is not empty.</p>
*
* @return the subject of the original delegator, or null if the chain is empty
*/
String getOriginalDelegator();
}
Loading
Loading