smolnar82 commented on code in PR #1257:
URL: https://github.com/apache/knox/pull/1257#discussion_r3393847014


##########
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTToken.java:
##########
@@ -100,14 +101,14 @@ public JWTToken(JWTokenAttributes jwtAttributes) {
     if (jwtAttributes.getClientId() != null) {
       builder.claim(CLIENT_ID_CLAIM, jwtAttributes.getClientId());
     }
-    if (jwtAttributes.getActor() != null) {
-      // RFC 8693 Token Exchange: The "act" (actor) claim provides a means 
within a JWT to express
-      // that delegation has occurred and identify the acting party to whom 
authority has been delegated.
-      // The act claim value is a JSON object containing a "sub" claim with 
the identity of the actor.
-      JWTClaimsSet actClaims = new JWTClaimsSet.Builder()
-          .subject(jwtAttributes.getActor())
-          .build();
-      builder.claim(ACT_CLAIM, actClaims.toJSONObject());
+    // RFC 8693 Token Exchange: The "act" (actor) claim provides a means 
within a JWT to express
+    // that delegation has occurred and identify the acting party to whom 
authority has been delegated.
+    // The actor chain is converted to the nested structure required by RFC 
8693.
+    if (jwtAttributes.getActorChain() != null && 
!jwtAttributes.getActorChain().isEmpty()) {

Review Comment:
   This if is redundant -> TokenUtils.buildNestedActClaim checks for the same 
and returns null.



##########
gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenResource.java:
##########
@@ -1106,14 +1107,30 @@ 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)) {
-        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);
-          log.addingActorClaimToToken(primaryPrincipalName, 
impersonatedPrincipalName);
+      // RFC 8693 Token Exchange: Build the actor chain if delegated auth is 
enabled
+      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)) {
+            // 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");

Review Comment:
   This logic deserves its own private method (e.g. `handleDelegatedAuth`), 
including the `if` statement -> here it would only be one method call (e.g. 
`handleDelegatedAuth(...)`.



##########
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTToken.java:
##########
@@ -100,14 +101,14 @@ public JWTToken(JWTokenAttributes jwtAttributes) {
     if (jwtAttributes.getClientId() != null) {
       builder.claim(CLIENT_ID_CLAIM, jwtAttributes.getClientId());
     }
-    if (jwtAttributes.getActor() != null) {
-      // RFC 8693 Token Exchange: The "act" (actor) claim provides a means 
within a JWT to express
-      // that delegation has occurred and identify the acting party to whom 
authority has been delegated.
-      // The act claim value is a JSON object containing a "sub" claim with 
the identity of the actor.
-      JWTClaimsSet actClaims = new JWTClaimsSet.Builder()
-          .subject(jwtAttributes.getActor())
-          .build();
-      builder.claim(ACT_CLAIM, actClaims.toJSONObject());
+    // RFC 8693 Token Exchange: The "act" (actor) claim provides a means 
within a JWT to express
+    // that delegation has occurred and identify the acting party to whom 
authority has been delegated.
+    // The actor chain is converted to the nested structure required by RFC 
8693.
+    if (jwtAttributes.getActorChain() != null && 
!jwtAttributes.getActorChain().isEmpty()) {
+      Map<String, Object> nestedAct = 
org.apache.knox.gateway.services.security.token.TokenUtils.buildNestedActClaim(jwtAttributes.getActorChain());

Review Comment:
   nit: TokenUtils can be imported -> no need for the fully qualified class 
name to be added here.



##########
gateway-spi/src/main/java/org/apache/knox/gateway/security/ActorChainPrincipal.java:
##########
@@ -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

Review Comment:
   Maybe return `Optional<String>` instead of `null`?



##########
gateway-spi/src/main/java/org/apache/knox/gateway/security/ActorChainPrincipalImpl.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Implementation of ActorChainPrincipal that holds the RFC 8693 actor 
delegation chain.
+ */
+public class ActorChainPrincipalImpl implements ActorChainPrincipal {
+  private final List<Map<String, Object>> actorChain;
+
+  /**
+   * Creates a new ActorChainPrincipal with the specified actor chain.
+   *
+   * @param actorChain the list of actor claim maps, ordered from most recent 
to oldest
+   */
+  public ActorChainPrincipalImpl(List<Map<String, Object>> actorChain) {
+    this.actorChain = actorChain == null
+        ? Collections.emptyList()
+        : Collections.unmodifiableList(new ArrayList<>(actorChain));
+  }
+
+  @Override
+  public List<Map<String, Object>> getActorChain() {
+    return actorChain;
+  }
+
+  @Override
+  public String getCurrentActor() {
+    if (actorChain.isEmpty()) {
+      return null;
+    }
+    Object sub = actorChain.get(0).get("sub");
+    return sub != null ? sub.toString() : null;
+  }
+
+  @Override
+  public String getOriginalDelegator() {
+    if (actorChain.isEmpty()) {
+      return null;
+    }
+    Object sub = actorChain.get(actorChain.size() - 1).get("sub");
+    return sub != null ? sub.toString() : null;
+  }
+
+  @Override
+  public String getName() {
+    // Return the current actor's identity as the principal name
+    String currentActor = getCurrentActor();
+    return currentActor != null ? currentActor : "";
+  }

Review Comment:
   I did not find any use of this method, I think it can be simply removed.



##########
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/TokenUtils.java:
##########
@@ -114,4 +118,143 @@ private static boolean useHMAC(char[] hmacSecret, String 
signingKeystoreName) {
     return hmacSecret != null && StringUtils.isBlank(signingKeystoreName);
   }
 
+  /**
+   * Extract the actor chain from an RFC 8693 'act' claim in a JWT token.
+   *
+   * <p>The 'act' claim in RFC 8693 represents a delegation chain where each 
actor
+   * delegated authority to the next. The claim is structured as a nested JSON 
object,
+   * where each level contains identity claims (such as 'sub' and 'iss') and 
potentially
+   * another nested 'act' claim.</p>
+   *
+   * <p>According to RFC 8693 Section 4.1, the 'act' claim contains identity 
claims that
+   * identify the actor. Common identity claims include:</p>
+   * <ul>
+   *   <li>'sub' - the subject/identity of the actor</li>
+   *   <li>'iss' - the issuer of the actor's identity</li>
+   * </ul>
+   *
+   * <p>Non-identity claims (e.g., 'exp', 'nbf', 'aud') are not relevant to 
the validity
+   * of the containing JWT and should not be used within 'act' claims.</p>
+   *
+   * <p>Example JWT 'act' claim structure:</p>
+   * <pre>
+   * {
+   *   "sub": "service-a",
+   *   "iss": "https://issuer.example.com";,
+   *   "act": {
+   *     "sub": "service-b",
+   *     "act": {
+   *       "sub": "service-c"
+   *     }
+   *   }
+   * }
+   * </pre>
+   *
+   * <p>This method flattens this nested structure into a list ordered from 
most recent
+   * actor (service-a) to oldest (service-c).</p>
+   *
+   * @param token The JWT token to extract the actor chain from
+   * @return A list of actor claim maps, ordered from most recent to oldest; 
empty list if no 'act' claim exists
+   */
+  @SuppressWarnings("unchecked")
+  public static List<Map<String, Object>> extractActorChain(JWT token) {
+    if (token == null) {
+      return Collections.emptyList();
+    }
+
+    Object actClaim = token.getClaimAsObject(JWTToken.ACT_CLAIM);
+    if (actClaim == null) {
+      return Collections.emptyList();
+    }

Review Comment:
   These 2 `if`s could be merged:
   ```
   if (token == null || token.getClaimAsObject(JWTToken.ACT_CLAIM) == null) {
      return Collections.emptyList();
   }
   ```
   Maybe something like this?
   ```
   public static List<Map<String, Object>> extractActorChain(JWT token) {
       final Object currentAct = token == null ? null : 
token.getClaimAsObject(JWTToken.ACT_CLAIM);
       final List<Map<String, Object>> actorChain = new ArrayList<>();
   
       while (currentAct instanceof Map<?, ?> actorMap) {
           actorChain.add(new LinkedHashMap<>((Map<String, Object>) actorMap));
           currentAct = actorMap.get(JWTToken.ACT_CLAIM);
       }
   
       return Collections.unmodifiableList(actorChain);
   }
   ```



##########
gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java:
##########
@@ -147,6 +148,11 @@ 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 = 
currentSubject.getPrincipals(ActorChainPrincipal.class);

Review Comment:
   We have named methods in `SubjectUtils` to get different principals from 
current subject (`getCurrentGroupPrincipals`, `getTokenIdPrincipals`, ...), I 
think we should add `getActorChainPrincipals` there too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to