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
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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.
-->
<!--
KnoxIDF /client endpoints opted out of knoxidf.client.registration.delegated.callers.denied, so a
delegated token may register clients and list, revoke, enable or disable the user's tokens (the
behavior before KNOX-3600 and KNOX-3603). knoxidf-token-delegation-policy.xml keeps the default
and refuses it. test_delegation.py presents the tokens that topology mints here.
-->
<topology>
<gateway>
<provider>
<role>federation</role>
<name>JWTProvider</name>
<enabled>true</enabled>
<param>
<name>knox.token.exp.server-managed</name>
<value>true</value>
</param>
</provider>
<provider>
<role>identity-assertion</role>
<name>Default</name>
<enabled>true</enabled>
</provider>
</gateway>

<service>
<role>KNOXIDF</role>
<param>
<name>knoxidf.knox.token.limit.per.user</name>
<value>-1</value>
</param>
<param>
<name>knoxidf.client.registration.delegated.callers.denied</name>
<value>false</value>
</param>
</service>
</topology>
125 changes: 123 additions & 2 deletions .github/workflows/tests/test_delegation.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@
'passthrough' audience validator (so the requested
resource is minted as aud). The service TTL is 86400s
so a shorter per-policy TTL is provably what caps the
minted token's lifetime.
minted token's lifetime. Its KNOXIDF /client
endpoints refuse delegated callers (the default).
- knoxidf-client-delegated-allowed -- the same /client endpoints, opted out of
knoxidf.client.registration.delegated.callers.denied.
- knoxidf-admin -- KNOXIDF_ADMIN delegation-policy REST API; writes to the
gateway-wide embedded H2 policy store the exchange reads.
- knoxauthtoken -- KNOX-AUTH-SERVICE with the k8s destination audience
Expand Down Expand Up @@ -67,13 +70,27 @@
AC9 -- headless delegation succeeds when the policy allows it, fails (invalid_request) when not.

KNOX-3568 -- audit of delegated token use: accepted, rejected and two-hop delegated tokens.

KNOX-3600, KNOX-3603 -- a delegated token cannot register a client at the KnoxIDF /client
endpoints, nor list, revoke, enable or disable the tokens of the user it acts for, unless the
topology opts out.
"""

import json
import unittest
import uuid

from requests.auth import HTTPBasicAuth

from common_utils import gateway_base_url, get_token_claim, get_token_id_display_text, knox_get
from common_utils import (
gateway_base_url,
get_token_claim,
get_token_id_display_text,
knox_delete,
knox_get,
knox_post,
knox_put,
)
from delegated_audit_helpers import (
DESTINATION_PATH,
assert_token_not_in_audit_log,
Expand Down Expand Up @@ -125,6 +142,14 @@
SERVICE_TTL_SEC = 86400
POLICY_TTL_SEC = 120

# KnoxIDF /client endpoints (KNOX-3600, KNOX-3603): refused to delegated callers on the policy
# topology (the default), reachable on the topology that opts out.
CLIENT_PATH = "/gateway/{topology}/knoxidf/api/v1/client/"
DELEGATED_CALLERS_DENIED_TOPOLOGY = "knoxidf-token-delegation-policy"
DELEGATED_CALLERS_ALLOWED_TOPOLOGY = "knoxidf-client-delegated-allowed"
CLIENT_REDIRECT_URI = "https://app.example.com/cb"
CLIENT_METHODS = {"GET": knox_get, "PUT": knox_put, "DELETE": knox_delete}


class TestDelegation(unittest.TestCase): # pylint: disable=too-many-instance-attributes
"""Full RFC 8693 delegation path (policy lookup, act/aud minting, TTL, headless) through Knox.
Expand Down Expand Up @@ -445,6 +470,102 @@ def test_nested_act_chain_is_audited_most_recent_actor_first(self):

self._assert_accepted_at_destination(second_hop, f"{SAM_USER}<-{ACTOR_USER}")

def _delegate_tom(self):
"""A token delegated to recursiveUser acting for tom (sub=tom, act.sub=recursiveUser)."""
self._actor_policy.register(
can_act_for_users=[TOM_USER], resource_policy={RESOURCE_A: []})
response = token_exchange(self.delegation_url, self._mint(self.tom_auth),
resources=[RESOURCE_A], actor_token=self._mint(self.actor_auth))
return self._assert_delegated_token(response, TOM_USER, ACTOR_USER, RESOURCE_A)

@staticmethod
def _register_client(topology, token):
"""Register a client at ``topology`` as ``token``; returns the raw response."""
url = gateway_base_url() + CLIENT_PATH.format(topology=topology).lstrip("/") + "register"
return knox_post(url, headers={"Authorization": f"Bearer {token}"},
data={"redirect_uris": CLIENT_REDIRECT_URI})

def _register_client_ok(self, topology, token):
"""Register a client at ``topology`` as ``token``; assert 200 and return its client_id."""
response = self._register_client(topology, token)
self.assertEqual(response.status_code, 200, response.text)
return response.json()["client_id"]

@staticmethod
def _client_token_calls(client_id, other_client_id):
"""(verb, audit event, method, path, body) of each /client token endpoint, in safe order."""
batch = json.dumps([other_client_id])
return [
("list", "client_token_listing", "GET", f"getUserTokens?userName={TOM_USER}", None),
("disable", "client_disablement", "PUT", "disable", client_id),
("enable", "client_enablement", "PUT", "enable", client_id),
("disable", "client_disablement", "PUT", "disableTokens", batch),
("enable", "client_enablement", "PUT", "enableTokens", batch),
("revoke", "client_revocation", "DELETE", "revoke", client_id),
("revoke", "client_revocation", "DELETE", "revokeTokens", batch),
]

@staticmethod
def _call_client(topology, token, method, path, body):
"""Call a /client token endpoint as ``token``; returns the response and request URI."""
separator = "&" if "?" in path else "?"
uri = (f"{CLIENT_PATH.format(topology=topology)}{path}"
f"{separator}audit_marker={uuid.uuid4()}")
headers = {"Authorization": f"Bearer {token}"}
if body is not None:
headers["Content-Type"] = "application/json"
response = CLIENT_METHODS[method](
gateway_base_url() + uri.lstrip("/"), headers=headers, data=body)
return response, uri

def _assert_refusal_audited(self, uri, event):
"""Assert the request to ``uri`` left one authorization failure for the refusal."""
records = [record for record in audit_records_for(self, uri)
if record.fields.get("event") == event]
self.assertEqual(len(records), 1, f"expected one {event} record: {records}")
record = records[0]
self.assertEqual(record.action, "authorization", record.line)
self.assertEqual(record.outcome, "failure", record.line)
self.assertEqual(record.user, TOM_USER, record.line)
self.assertEqual(record.fields.get("reason"), "delegated_caller_denied", record.line)

def test_delegated_token_refused_at_client_endpoints(self):
"""KNOX-3600, KNOX-3603: a delegated token cannot register, nor touch the user's tokens."""
topology = DELEGATED_CALLERS_DENIED_TOPOLOGY
token = self._delegate_tom()
# tom's own token registers the clients the delegated token then tries to act on.
tom_token = self._mint(self.tom_auth)
client_id = self._register_client_ok(topology, tom_token)
other_client_id = self._register_client_ok(topology, tom_token)

assert_oauth_error(self, self._register_client(topology, token), 403, "access_denied",
"A delegated token cannot register a client.")
calls = self._client_token_calls(client_id, other_client_id)
for verb, event, method, path, body in calls:
with self.subTest(path=path):
response, uri = self._call_client(topology, token, method, path, body)
assert_oauth_error(self, response, 403, "access_denied",
f"A delegated token cannot {verb} tokens.")
self._assert_refusal_audited(uri, event)

# tom's own token reaches every endpoint, so the 403s above came from the delegated check.
for _, _, method, path, body in calls:
with self.subTest(path=path, caller=TOM_USER):
response, _ = self._call_client(topology, tom_token, method, path, body)
self.assertEqual(response.status_code, 200, response.text)

def test_delegated_token_reaches_client_endpoints_when_allowed(self):
"""KNOX-3600, KNOX-3603: a topology that opts out lets a delegated token use /client."""
topology = DELEGATED_CALLERS_ALLOWED_TOPOLOGY
token = self._delegate_tom()
client_id = self._register_client_ok(topology, token)
other_client_id = self._register_client_ok(topology, token)

for _, _, method, path, body in self._client_token_calls(client_id, other_client_id):
with self.subTest(path=path):
response, _ = self._call_client(topology, token, method, path, body)
self.assertEqual(response.status_code, 200, response.text)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,17 @@
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
Expand All @@ -51,6 +55,8 @@
import java.util.Set;
import java.util.stream.Collectors;

import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static jakarta.ws.rs.core.MediaType.APPLICATION_XML;
import static org.apache.knox.gateway.util.knoxidf.KnoxIDFConstants.BASE_RESOURCE_PATH;
import static org.apache.knox.gateway.util.knoxidf.KnoxIDFConstants.CLIENT_REGISTRATION_ALLOWED_SCOPES;
import static org.apache.knox.gateway.util.knoxidf.KnoxIDFConstants.CLIENT_REGISTRATION_ANONYMOUS_ALLOWED;
Expand Down Expand Up @@ -220,6 +226,83 @@ public Response registerClient(@FormParam("redirect_uris") String redirectUris,
}
}

// The inherited token endpoints authorize the user a delegated token acts for; refuse delegated callers.

@Override
@GET
@Path(GET_USER_TOKENS)
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public Response getUserTokens(@Context UriInfo uriInfo) {
final Response denied = delegatedTokenAccessDenied("client_token_listing", "list");
return denied != null ? denied : super.getUserTokens(uriInfo);
}

@Override
@DELETE
@Path(REVOKE_PATH)
@Produces({ APPLICATION_JSON })
public Response revoke(String token) {
final Response denied = delegatedTokenAccessDenied("client_revocation", "revoke");
return denied != null ? denied : super.revoke(token);
}

@Override
@DELETE
@Path(BATCH_REVOKE_PATH)
@Produces({ APPLICATION_JSON })
public Response revokeTokens(String tokenIds) {
final Response denied = delegatedTokenAccessDenied("client_revocation", "revoke");
return denied != null ? denied : super.revokeTokens(tokenIds);
}

@Override
@PUT
@Path(ENABLE_PATH)
@Produces({ APPLICATION_JSON })
public Response enable(String tokenId) {
final Response denied = delegatedTokenAccessDenied("client_enablement", "enable");
return denied != null ? denied : super.enable(tokenId);
}

@Override
@PUT
@Path(BATCH_ENABLE_PATH)
@Consumes({ APPLICATION_JSON })
@Produces({ APPLICATION_JSON })
public Response enableTokens(String tokenIds) {
final Response denied = delegatedTokenAccessDenied("client_enablement", "enable");
return denied != null ? denied : super.enableTokens(tokenIds);
}

@Override
@PUT
@Path(DISABLE_PATH)
@Produces({ APPLICATION_JSON })
public Response disable(String tokenId) {
final Response denied = delegatedTokenAccessDenied("client_disablement", "disable");
return denied != null ? denied : super.disable(tokenId);
}

@Override
@PUT
@Path(BATCH_DISABLE_PATH)
@Consumes({ APPLICATION_JSON })
@Produces({ APPLICATION_JSON })
public Response disableTokens(String tokenIds) {
final Response denied = delegatedTokenAccessDenied("client_disablement", "disable");
return denied != null ? denied : super.disableTokens(tokenIds);
}

// Returns the access_denied response, audited, when a delegated caller must be refused; null otherwise.
private Response delegatedTokenAccessDenied(final String event, final String verb) {
if (!delegatedCallerDenied()) {
return null;
}
KnoxIDFAudit.audit(Action.AUTHORIZATION, KnoxIDFAudit.subjectLabel(SubjectUtils.getCurrentEffectivePrincipalName()),
ResourceType.PRINCIPAL, ActionOutcome.FAILURE, "event=" + event + " reason=delegated_caller_denied");
return error("access_denied", "A delegated token cannot " + verb + " tokens.");
}

/**
* @return {@code true} when the request must be rejected because an anonymous caller is
* attempting to register a client while open registration has not been explicitly enabled.
Expand All @@ -242,9 +325,10 @@ boolean clientCallerDenied() {
}

/**
* @return {@code true} when the request must be rejected because the caller's token carries an RFC 8693
* actor chain while delegated callers have not been explicitly allowed. Only a token with an act claim
* has one: a delegated token minted without delegated auth, or presented as a passcode, does not.
* @return {@code true} when the request (client registration, or listing, revoking, enabling or disabling tokens)
* must be rejected because the caller's token carries an RFC 8693 actor chain while delegated callers have
* not been explicitly allowed. Only a token with an act claim has one: a delegated token minted without
* delegated auth, or presented as a passcode, does not.
*/
boolean delegatedCallerDenied() {
return delegatedCallersDenied && SubjectUtils.getActorChainPrincipal(SubjectUtils.getCurrentSubject()) != null;
Expand Down
Loading
Loading