From b9bd515fec6c818c47806d69cdb480b9d8b50cf7 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Mon, 16 Nov 2026 08:01:40 +0100 Subject: [PATCH] keystone: drop 2024.1 patch merged upstream 0005-trusts-oauth1-app-creds-reject-delegated-tokens-acro.patch reverses completely against the current unmaintained/2024.1 sdist, keystone-25.0.1.dev39. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Roger Luethi --- ...p-creds-reject-delegated-tokens-acro.patch | 1221 ----------------- 1 file changed, 1221 deletions(-) delete mode 100644 patches/2024.1/keystone/0005-trusts-oauth1-app-creds-reject-delegated-tokens-acro.patch diff --git a/patches/2024.1/keystone/0005-trusts-oauth1-app-creds-reject-delegated-tokens-acro.patch b/patches/2024.1/keystone/0005-trusts-oauth1-app-creds-reject-delegated-tokens-acro.patch deleted file mode 100644 index d62147b1..00000000 --- a/patches/2024.1/keystone/0005-trusts-oauth1-app-creds-reject-delegated-tokens-acro.patch +++ /dev/null @@ -1,1221 +0,0 @@ -From 1adf1f098ff52abf5cf5bce12e6afc1322cbaa68 Mon Sep 17 00:00:00 2001 -From: Grzegorz Grasza -Date: Thu, 23 Jul 2026 09:32:00 +0200 -Subject: [PATCH 5/7] trusts, oauth1, app-creds: reject delegated tokens across - all endpoints - -_check_application_credential() in trusts.py only recognized -'application_credential' in token.methods, so OAuth1 access-token-scoped -and ec2credential-derived tokens were never blocked from creating, -listing, reading, or deleting trusts -- unlike application_credential, -which has had this restriction since LP#2148477. - -Two more endpoints that mint a new persistent grant had the same gap: - -- users.py's _block_delegated_token_app_creds (guarding application - credential and access-rule CRUD) only checked trust_id/access_token_id, - so ec2credential-scoped tokens could create, list, read, and delete - application credentials. -- os_oauth1.py's AuthorizeResource.put (PUT /v3/OS-OAUTH1/authorize) only - checked is_delegated_auth (trust/oauth1) and application_credential, so - an ec2credential-scoped token could authorize OAuth1 request tokens. - -All three are extended to the same primary-auth-method allowlist used in -credentials.py, users.py, and token.py: any token whose methods aren't -entirely primary auth methods is rejected outright. Trust-scoped tokens -are deliberately not blocked from trust operations on trust_id alone -- -that's the trust redelegation feature working as designed (a trustee -creating a further, narrower trust from one they were delegated) and -trustee self-service reads of their own trusts. A trust-scoped token -whose underlying method is itself delegated (an EC2 credential's blob -can embed a trust_id, see keystone.api.credentials._assign_unique_id) is -still caught by the method check regardless of trust scoping. -application_credential keeps its existing, documented opt-in escape -hatch for trust management -(allow_insecure_application_credential_trust_escalation) and its -unrestricted/restricted distinction for creating further application -credentials (_check_unrestricted_application_credential); OAuth1 and EC2 -credentials have no such use case and are blocked unconditionally -everywhere. - -This also closes off the underlying role-escalation path in trust -creation: trust role validation checks the trustor's full role -assignments, not the requesting token's own scoped roles, so a -narrowly-scoped oauth1/ec2 token could previously delegate roles it was -never itself authorized for. Blocking those token types from trust -creation removes the path to that gap without needing to touch the -validation itself. - -Neither the app-cred nor the OAuth1-authorize gap is reachable on -current master, where a separate middleware change globally rejects any -caller token with 'ec2credential' in its methods before Flask routing -- -but that change is not backported to stable branches, so both gaps are -live there. Fixed at the source regardless, so the guard doesn't depend -on an unrelated middleware check remaining in place. - -An empty token.methods list (e.g. an ec2credential-derived token that -lost its methods on a fernet cache-miss round-trip -- ec2credential has -no bit in the method bitmask) is also treated as delegated at all three -call sites: _PRIMARY_AUTH_METHODS.issuperset([]) is True, so without this -an empty list would otherwise be accepted as 'all primary'. - -Consolidated the three independent _PRIMARY_AUTH_METHODS copies (this -patch, LP#2158538, LP#2159643) into keystone.api._shared.delegation, -per gtema's review comment #16 -- now that all three land together the -NameError-avoidance reason for keeping them separate no longer applies. -Also replaced the hardcoded method list with an operator-extensible one -([auth] additional_primary_auth_methods): a hardcoded allowlist blocks -any third-party auth plugin (e.g. a site-specific SSO integration) from -reauthenticating/managing its own trusts, app-creds, and OAuth1 tokens, -since it can never appear in a list only keystone maintainers can edit. - -Closes-Bug: #2153453 -Change-Id: Ic8775eb0fdaa2330206023818ce18f76430fa45e -Assisted-by: Claude Sonnet 5 -Signed-off-by: Grzegorz Grasza -Signed-off-by: Artem Goncharov -(cherry picked from commit c8872fabde992542b304895f90d5ac1651e87e24) ---- - keystone/api/_shared/delegation.py | 73 +++ - keystone/api/os_oauth1.py | 32 +- - keystone/api/trusts.py | 71 ++- - keystone/api/users.py | 32 +- - keystone/conf/auth.py | 21 + - .../unit/test_v3_application_credential.py | 104 ++++ - keystone/tests/unit/test_v3_oauth1.py | 57 ++ - keystone/tests/unit/test_v3_trust.py | 486 ++++++++++++++++++ - .../notes/bug-2153453-6f2a1d9e0c7b4a83.yaml | 40 ++ - 9 files changed, 863 insertions(+), 53 deletions(-) - create mode 100644 keystone/api/_shared/delegation.py - create mode 100644 releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml - -diff --git a/keystone/api/_shared/delegation.py b/keystone/api/_shared/delegation.py -new file mode 100644 -index 000000000..5812ec61c ---- /dev/null -+++ b/keystone/api/_shared/delegation.py -@@ -0,0 +1,73 @@ -+# Licensed under the Apache License, Version 2.0 (the "License"); you may -+# not use this file except in compliance with the License. You may obtain -+# a copy of the License at -+# -+# http://www.apache.org/licenses/LICENSE-2.0 -+# -+# Unless required by applicable law or agreed to in writing, software -+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -+# License for the specific language governing permissions and limitations -+# under the License. -+ -+# Shared primary-vs-delegated auth method classification, used by -+# keystone.api.trusts, keystone.api.os_oauth1, keystone.api.users, -+# keystone.api.credentials, and keystone.auth.plugins.token to guard -+# sensitive actions (managing trusts, OAuth1 access tokens, application -+# credentials, or another user's credentials; exchanging a token for -+# another token) against delegated-token abuse. See LP#2153453, -+# LP#2158538, LP#2159643. -+ -+import keystone.conf -+ -+CONF = keystone.conf.CONF -+ -+# Auth methods that authenticate a user directly. Anything else -- -+# a delegated credential (application_credential, oauth1, ec2credential, -+# oauth2_credential) or a future, not-yet-reviewed delegated method -- is -+# treated as delegated by default and rejected from the sensitive actions -+# this module's callers guard. This is a deny-by-default allowlist, not a -+# denylist of specific known-bad methods: a new delegated method nobody -+# has reviewed yet must be blocked automatically, not silently allowed -+# through until someone remembers to add it to a denylist. -+_BUILTIN_PRIMARY_AUTH_METHODS = frozenset( -+ { -+ 'external', -+ 'kerberos', -+ 'mapped', -+ 'openid', -+ 'password', -+ 'saml2', -+ 'token', -+ 'totp', -+ 'x509', -+ } -+) -+ -+ -+def primary_auth_methods(): -+ """The effective set of primary (non-delegated) auth methods. -+ -+ Operators running a custom, third-party auth plugin (e.g. a -+ site-specific SSO integration) can list its method name in -+ [auth] additional_primary_auth_methods so tokens issued through it -+ are not mistaken for a delegated credential by the guards in this -+ module's callers. -+ """ -+ return _BUILTIN_PRIMARY_AUTH_METHODS | frozenset( -+ CONF.auth.additional_primary_auth_methods -+ ) -+ -+ -+def is_delegated_method(token): -+ """Return True if token.methods indicates a delegated credential. -+ -+ An empty methods list is treated as delegated, not allowed: a token -+ whose methods were lost on a fernet round-trip (e.g. -+ ec2credential/oauth2_credential decoding to []) must not be treated -+ as if it had no delegated methods at all -- issuperset([]) is True. -+ """ -+ return bool(token) and ( -+ not token.methods -+ or not primary_auth_methods().issuperset(token.methods) -+ ) -diff --git a/keystone/api/os_oauth1.py b/keystone/api/os_oauth1.py -index 4e61652a4..8131cc517 100644 ---- a/keystone/api/os_oauth1.py -+++ b/keystone/api/os_oauth1.py -@@ -20,6 +20,7 @@ from oslo_utils import timeutils - from urllib import parse as urlparse - from werkzeug import exceptions - -+from keystone.api._shared import delegation - from keystone.api._shared import json_home_relations - from keystone.common import authorization - from keystone.common import context -@@ -42,6 +43,25 @@ ENFORCER = rbac_enforcer.RBACEnforcer - CONF = keystone.conf.CONF - - -+def _check_can_authorize_request_token(ctx, token): -+ """Reject delegated tokens from authorizing OAuth1 request tokens. -+ -+ Authorizing a request token mints a new, independent OAuth1 access -+ token delegation. Allowing a delegated token (application credential, -+ EC2 credential, another OAuth1 access token, or trust-scoped token) to -+ do this would let a narrower-scope grant bootstrap a broader, -+ independently-lived one. -+ """ -+ trust_id = getattr(ctx, 'trust_id', None) -+ if trust_id or delegation.is_delegated_method(token): -+ raise exception.Forbidden( -+ _( -+ 'Cannot authorize a request token with a token issued via ' -+ 'delegation.' -+ ) -+ ) -+ -+ - _build_resource_relation = json_home_relations.os_oauth1_resource_rel_func - _build_parameter_relation = json_home_relations.os_oauth1_parameter_rel_func - -@@ -288,21 +308,11 @@ class AuthorizeResource(_OAuth1ResourceBase): - 'roles', []) - validation.lazy_validate(schema.request_token_authorize, roles) - ctx = flask.request.environ[context.REQUEST_CONTEXT_ENV] -- if ctx.is_delegated_auth: -- raise exception.Forbidden( -- _('Cannot authorize a request token with a token issued via ' -- 'delegation.')) - auth_context = flask.request.environ.get( - authorization.AUTH_CONTEXT_ENV, {} - ) - token = auth_context.get('token') -- if token and 'application_credential' in token.methods: -- raise exception.Forbidden( -- _( -- 'Cannot authorize a request token with a token issued via ' -- 'delegation.' -- ) -- ) -+ _check_can_authorize_request_token(ctx, token) - - req_token = PROVIDERS.oauth_api.get_request_token(request_token_id) - -diff --git a/keystone/api/trusts.py b/keystone/api/trusts.py -index ab2aa9a7a..82a3259a6 100644 ---- a/keystone/api/trusts.py -+++ b/keystone/api/trusts.py -@@ -21,6 +21,7 @@ import http.client - from oslo_log import log - from oslo_policy import _checks as op_checks - -+from keystone.api._shared import delegation - from keystone.api._shared import json_home_relations - from keystone.common import authorization - from keystone.common import context -@@ -49,28 +50,50 @@ TRUST_ID_PARAMETER_RELATION = _build_parameter_relation( - parameter_name='trust_id') - - --def _check_application_credential(): -- """Block application credential tokens from all trust operations. -- -- Application credentials are single-project delegation tokens. Allowing -- them to read or manage trusts would permit a compromised application -- credential to enumerate or manipulate the trust delegation chain, -- expanding its effective scope beyond the single project it was issued for. -- This applies regardless of the 'unrestricted' flag. -+def _check_delegated_token(): -+ """Block delegated tokens from all trust operations. -+ -+ Delegated tokens (application credentials, OAuth1 access tokens, EC2 -+ credentials) are narrower-scope grants than a normal user session. -+ Allowing them to read or manage trusts would permit a compromised -+ delegation to enumerate or manipulate the trust delegation chain -- or, -+ for creation, mint a new trust delegating roles the trustor holds but -+ the delegation itself was never scoped to, since trust role validation -+ checks the trustor's full role assignments, not the requesting token's -+ own scoped roles -- expanding its effective scope well beyond what it -+ was issued for. -+ -+ Trust-scoped tokens are deliberately NOT blocked here: managing trusts -+ with a trust-scoped token is the redelegation feature working as -+ designed (a trustee creating a further, narrower trust from one they -+ were delegated), and trustee self-service reads of their own trusts. -+ A trust-scoped token whose underlying auth method is itself delegated -+ (e.g. an EC2 credential's blob embeds a trust_id -- see -+ keystone.api.credentials._assign_unique_id) is still caught below, -+ since token.methods reflects that underlying method regardless of the -+ trust scoping. -+ -+ application_credential tokens have a documented, opt-in escape hatch -+ (allow_insecure_application_credential_trust_escalation, LP#2150089) -+ for workflows such as Heat that need it. OAuth1 and EC2 credentials -+ have no such use case and are blocked unconditionally, regardless of -+ that option. - """ -- if CONF.security_compliance.allow_insecure_application_credential_trust_escalation: # noqa -+ token = flask.request.environ.get(authorization.AUTH_CONTEXT_ENV, {}).get( -+ 'token' -+ ) -+ if not token: -+ return -+ if not delegation.is_delegated_method(token): -+ return -+ if ( -+ 'application_credential' in token.methods -+ and CONF.security_compliance.allow_insecure_application_credential_trust_escalation -+ ): - return -- auth_context = flask.request.environ.get( -- authorization.AUTH_CONTEXT_ENV, {} -+ raise exception.ForbiddenAction( -+ action=_('Delegated tokens cannot manage trusts.') - ) -- token = auth_context.get('token') -- if token and 'application_credential' in token.methods: -- raise exception.ForbiddenAction( -- action=_( -- "Using method 'application_credential' is not " -- "allowed for managing trusts." -- ) -- ) - - - def _build_trust_target_enforcement(): -@@ -128,7 +151,7 @@ class TrustResource(ks_flask.ResourceBase): - json_home_parameter_rel_func = _build_parameter_relation - - def _check_unrestricted(self): -- _check_application_credential() -+ _check_delegated_token() - - def _find_redelegated_trust(self): - # Check if delegated via trust -@@ -186,7 +209,7 @@ class TrustResource(ks_flask.ResourceBase): - def _get_trust(self, trust_id): - ENFORCER.enforce_call(action='identity:get_trust', - build_target=_build_trust_target_enforcement) -- _check_application_credential() -+ _check_delegated_token() - - # NOTE(cmurphy) look up trust before doing is_admin authorization - to - # maintain the API contract, we expect a missing trust to raise a 404 -@@ -235,7 +258,7 @@ class TrustResource(ks_flask.ResourceBase): - target_attr=target) - else: - ENFORCER.enforce_call(action='identity:list_trusts') -- _check_application_credential() -+ _check_delegated_token() - - trusts = [] - -@@ -385,7 +408,7 @@ class RolesForTrustListResource(flask_restful.Resource): - # block access here - raise exception.ForbiddenAction( - action=_('Requested user has no relation to this trust')) -- _check_application_credential() -+ _check_delegated_token() - - trust = PROVIDERS.trust_api.get_trust(trust_id) - -@@ -435,7 +458,7 @@ class RoleForTrustResource(flask_restful.Resource): - # block access here - raise exception.ForbiddenAction( - action=_('Requested user has no relation to this trust')) -- _check_application_credential() -+ _check_delegated_token() - - trust = PROVIDERS.trust_api.get_trust(trust_id) - -diff --git a/keystone/api/users.py b/keystone/api/users.py -index 7d529531e..583f326b1 100644 ---- a/keystone/api/users.py -+++ b/keystone/api/users.py -@@ -21,6 +21,7 @@ import http.client - from oslo_serialization import jsonutils - from werkzeug import exceptions - -+from keystone.api._shared import delegation - from keystone.api._shared import json_home_relations - from keystone.application_credential import schema as app_cred_schema - from keystone.common import json_home -@@ -119,14 +120,8 @@ def _check_delegation_for_ec2(oslo_context, token, project_id): - - def _block_delegated_token(oslo_context, token): - """Raise Forbidden if the token is any form of delegation.""" -- if oslo_context.is_delegated_auth: -- raise ks_exception.Forbidden( -- _( -- 'Cannot manage OAuth access tokens with a token ' -- 'issued via delegation.' -- ) -- ) -- if 'application_credential' in token.methods: -+ trust_id = getattr(oslo_context, 'trust_id', None) -+ if trust_id or delegation.is_delegated_method(token): - raise ks_exception.Forbidden( - _( - 'Cannot manage OAuth access tokens with a token ' -@@ -136,24 +131,25 @@ def _block_delegated_token(oslo_context, token): - - - def _block_delegated_token_app_creds(oslo_context, token): -- """Raise Forbidden if the token is a trust or OAuth1 delegation. -+ """Raise Forbidden if the token is a trust, OAuth1, or EC2 delegation. - -- Trust-scoped and OAuth1 access token-scoped tokens must not be used to -- create, list, read, or delete application credentials or access rules. -- Creating an application credential via such a token produces a persistent -- credential that outlives the delegation's expiry or scope, providing a -- backdoor that breaks the accountability model: the trust-scoped token -- carries the full delegation chain enabling audit, but a derived application -- credential does not. -+ Trust-scoped, OAuth1 access token-scoped, and EC2-derived tokens must -+ not be used to create, list, read, or delete application credentials or -+ access rules. Creating an application credential via such a token -+ produces a persistent credential that outlives the delegation's expiry -+ or scope, providing a backdoor that breaks the accountability model: the -+ trust-scoped token carries the full delegation chain enabling audit, but -+ a derived application credential does not. - - Application credential tokens are intentionally excluded from this check. - The unrestricted/restricted distinction for application credentials is a - documented feature handled separately by - _check_unrestricted_application_credential. - """ -+ if 'application_credential' in token.methods: -+ return - trust_id = getattr(oslo_context, 'trust_id', None) -- access_token_id = getattr(token, 'access_token_id', None) -- if trust_id or access_token_id: -+ if trust_id or delegation.is_delegated_method(token): - raise ks_exception.Forbidden( - _( - 'Cannot manage application credentials with a token ' -diff --git a/keystone/conf/auth.py b/keystone/conf/auth.py -index d53fc15e3..312f31c5a 100644 ---- a/keystone/conf/auth.py -+++ b/keystone/conf/auth.py -@@ -85,6 +85,26 @@ unless you are overriding keystone's own `application_credential` - authentication plugin. - """)) - -+additional_primary_auth_methods = cfg.ListOpt( -+ 'additional_primary_auth_methods', -+ default=[], -+ help=utils.fmt( -+ """ -+Auth method names, beyond keystone's own built-in primary methods -+(password, totp, mapped, saml2, openid, external, kerberos, x509, token), -+that authenticate a user directly rather than via a delegated credential. -+Set this if you run a custom, third-party auth plugin (for example a -+site-specific SSO integration) so that tokens issued through it are not -+mistaken for a delegated credential (application credential, OAuth1 -+access token, EC2 credential) by the guards that block delegated tokens -+from managing trusts, application credentials, OAuth1 access tokens, -+credentials, or exchanging a token for another token. Without this, a -+token issued via an unlisted custom method is treated as delegated and -+rejected from those actions by default. -+""" -+ ), -+) -+ - - GROUP_NAME = __name__.split('.')[-1] - ALL_OPTS = [ -@@ -95,6 +115,7 @@ ALL_OPTS = [ - oauth1, - mapped, - application_credential, -+ additional_primary_auth_methods, - ] - - -diff --git a/keystone/tests/unit/test_v3_application_credential.py b/keystone/tests/unit/test_v3_application_credential.py -index 03c03e1bc..05e7dfe1a 100644 ---- a/keystone/tests/unit/test_v3_application_credential.py -+++ b/keystone/tests/unit/test_v3_application_credential.py -@@ -16,9 +16,13 @@ import uuid - - import http.client - -+from keystoneclient.contrib.ec2 import utils as ec2_utils -+ - from keystone.common import provider_api - import keystone.conf -+from keystone.credential.providers import fernet as credential_fernet - from keystone.tests import unit -+from keystone.tests.unit import ksfixtures - from keystone.tests.unit import test_v3 - - -@@ -791,3 +795,103 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): - headers={'X-Auth-Token': trust_token}, - expected_status_code=http.client.FORBIDDEN, - ) -+ -+ -+class AppCredEc2GuardTests(ApplicationCredentialTestCase): -+ """EC2-derived tokens must not manage application credentials. -+ -+ An ec2credential-scoped token has no delegation markers -+ (trust_id/access_token_id) that the pre-existing -+ _block_delegated_token_app_creds check looked for, so it slipped -+ through unblocked. See LP#2153453. -+ """ -+ -+ def setUp(self): -+ super().setUp() -+ self.useFixture( -+ ksfixtures.KeyRepository( -+ self.config_fixture, -+ 'credential', -+ credential_fernet.MAX_ACTIVE_KEYS, -+ ) -+ ) -+ -+ def _get_ec2_token_id(self): -+ blob, ref = unit.new_ec2_credential( -+ user_id=self.user_id, project_id=self.project_id -+ ) -+ self.post('/credentials', body={'credential': ref}) -+ signer = ec2_utils.Ec2Signer(blob['secret']) -+ params = { -+ 'SignatureMethod': 'HmacSHA256', -+ 'SignatureVersion': '2', -+ 'AWSAccessKeyId': blob['access'], -+ } -+ request = { -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ sig_ref = { -+ 'access': blob['access'], -+ 'signature': signer.generate(request), -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ r = self.post( -+ '/ec2tokens', -+ body={'ec2Credentials': sig_ref}, -+ expected_status=http.client.OK, -+ ) -+ return r.headers.get('X-Subject-Token') -+ -+ def test_ec2_token_cannot_create_application_credential(self): -+ ec2_token = self._get_ec2_token_id() -+ app_cred_body = self._app_cred_body(roles=[{'id': self.role_id}]) -+ self.post( -+ f'/users/{self.user_id}/application_credentials', -+ body=app_cred_body, -+ token=ec2_token, -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_ec2_token_cannot_list_application_credentials(self): -+ ec2_token = self._get_ec2_token_id() -+ self.get( -+ f'/users/{self.user_id}/application_credentials', -+ token=ec2_token, -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_ec2_token_cannot_get_application_credential(self): -+ ec2_token = self._get_ec2_token_id() -+ app_cred_body = self._app_cred_body(roles=[{'id': self.role_id}]) -+ r = self.post( -+ f'/users/{self.user_id}/application_credentials', -+ body=app_cred_body, -+ ) -+ app_cred_id = r.result['application_credential']['id'] -+ self.get( -+ MEMBER_PATH_FMT -+ % {'user_id': self.user_id, 'app_cred_id': app_cred_id}, -+ token=ec2_token, -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_ec2_token_cannot_delete_application_credential(self): -+ ec2_token = self._get_ec2_token_id() -+ app_cred_body = self._app_cred_body(roles=[{'id': self.role_id}]) -+ r = self.post( -+ f'/users/{self.user_id}/application_credentials', -+ body=app_cred_body, -+ ) -+ app_cred_id = r.result['application_credential']['id'] -+ self.delete( -+ MEMBER_PATH_FMT -+ % {'user_id': self.user_id, 'app_cred_id': app_cred_id}, -+ token=ec2_token, -+ expected_status=http.client.FORBIDDEN, -+ ) -diff --git a/keystone/tests/unit/test_v3_oauth1.py b/keystone/tests/unit/test_v3_oauth1.py -index 113e92bcf..bbddd0efc 100644 ---- a/keystone/tests/unit/test_v3_oauth1.py -+++ b/keystone/tests/unit/test_v3_oauth1.py -@@ -20,6 +20,7 @@ import uuid - - import freezegun - import http.client -+from keystoneclient.contrib.ec2 import utils as ec2_utils - from oslo_serialization import jsonutils - from pycadf import cadftaxonomy - import urllib -@@ -27,6 +28,7 @@ from urllib import parse as urlparse - - from keystone.common import provider_api - import keystone.conf -+from keystone.credential.providers import fernet as credential_fernet - from keystone import exception - from keystone import oauth1 - from keystone.oauth1.backends import base -@@ -787,6 +789,61 @@ class AuthTokenTests(object): - expected_status=http.client.FORBIDDEN, - ) - -+ def _get_ec2_token_id(self): -+ self.useFixture( -+ ksfixtures.KeyRepository( -+ self.config_fixture, -+ 'credential', -+ credential_fernet.MAX_ACTIVE_KEYS, -+ ) -+ ) -+ blob, ref = unit.new_ec2_credential( -+ user_id=self.user_id, project_id=self.project_id -+ ) -+ self.post('/credentials', body={'credential': ref}) -+ signer = ec2_utils.Ec2Signer(blob['secret']) -+ params = { -+ 'SignatureMethod': 'HmacSHA256', -+ 'SignatureVersion': '2', -+ 'AWSAccessKeyId': blob['access'], -+ } -+ request = { -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ sig_ref = { -+ 'access': blob['access'], -+ 'signature': signer.generate(request), -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ r = self.post( -+ '/ec2tokens', -+ body={'ec2Credentials': sig_ref}, -+ expected_status=http.client.OK, -+ ) -+ return r.headers.get('X-Subject-Token') -+ -+ def test_ec2_token_cannot_authorize_request_token(self): -+ ec2_token = self._get_ec2_token_id() -+ url = self._approve_request_token_url() -+ body = {'roles': [{'id': self.role_id}]} -+ self.put( -+ url, -+ body=body, -+ token=ec2_token, -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_ec2_token_cannot_list_access_tokens(self): -+ ec2_token = self._get_ec2_token_id() -+ url = f'/users/{self.user_id}/OS-OAUTH1/access_tokens' -+ self.get(url, token=ec2_token, expected_status=http.client.FORBIDDEN) -+ - - class FernetAuthTokenTests(AuthTokenTests, OAuthFlowTests): - -diff --git a/keystone/tests/unit/test_v3_trust.py b/keystone/tests/unit/test_v3_trust.py -index 82685bb69..e6222b972 100644 ---- a/keystone/tests/unit/test_v3_trust.py -+++ b/keystone/tests/unit/test_v3_trust.py -@@ -14,11 +14,24 @@ import datetime - import uuid - - import http.client -+from unittest import mock -+import urllib - -+import flask -+ -+from keystoneclient.contrib.ec2 import utils as ec2_utils -+ -+from keystone.api._shared import delegation -+from keystone.api import trusts as trusts_api -+from keystone.common import authorization -+from keystone.common import context - from keystone.common import provider_api - import keystone.conf -+from keystone.credential.providers import fernet as credential_fernet - from keystone import exception -+from keystone import oauth1 - from keystone.tests import unit -+from keystone.tests.unit import ksfixtures - from keystone.tests.unit import test_v3 - - CONF = keystone.conf.CONF -@@ -692,3 +705,476 @@ class TrustsWithApplicationCredentials(test_v3.RestfulTestCase): - 'trust_id': trust['id']}, - token=token_data.headers['x-subject-token'], - expected_status=http.client.FORBIDDEN) -+ -+ -+class TrustsWithOtherDelegatedTokens(test_v3.RestfulTestCase): -+ """OAuth1 access-token and ec2credential tokens must not manage trusts. -+ -+ Mirrors TrustsWithApplicationCredentials, closing the gap identified -+ in LP#2153453 comments #9-10 ("EC2 tokens can still create trusts and -+ authorize OAuth1") that was never actually fixed for either token -+ type in this file. -+ """ -+ -+ def setUp(self): -+ super().setUp() -+ self.trustee_user = unit.create_user( -+ PROVIDERS.identity_api, domain_id=self.domain_id -+ ) -+ self.trustee_user_id = self.trustee_user['id'] -+ self.base_url = 'http://localhost/v3' -+ self.useFixture( -+ ksfixtures.KeyRepository( -+ self.config_fixture, -+ 'credential', -+ credential_fernet.MAX_ACTIVE_KEYS, -+ ) -+ ) -+ -+ def _make_trust_ref(self): -+ return unit.new_trust_ref( -+ trustor_user_id=self.user_id, -+ trustee_user_id=self.trustee_user_id, -+ project_id=self.project_id, -+ role_ids=[self.role_id], -+ ) -+ -+ def _get_ec2_token(self): -+ blob, ref = unit.new_ec2_credential( -+ user_id=self.user_id, project_id=self.project_id -+ ) -+ self.post('/credentials', body={'credential': ref}) -+ signer = ec2_utils.Ec2Signer(blob['secret']) -+ params = { -+ 'SignatureMethod': 'HmacSHA256', -+ 'SignatureVersion': '2', -+ 'AWSAccessKeyId': blob['access'], -+ } -+ request = { -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ sig_ref = { -+ 'access': blob['access'], -+ 'signature': signer.generate(request), -+ 'host': 'foo', -+ 'verb': 'GET', -+ 'path': '/bar', -+ 'params': params, -+ } -+ r = self.post( -+ '/ec2tokens', -+ body={'ec2Credentials': sig_ref}, -+ expected_status=http.client.OK, -+ ) -+ return r.headers.get('X-Subject-Token') -+ -+ def _urllib_parse_qs_text_keys(self, content): -+ results = urllib.parse.parse_qs(content) -+ return {key.decode('utf-8'): value for key, value in results.items()} -+ -+ def _create_single_consumer(self): -+ ref = {'description': uuid.uuid4().hex} -+ resp = self.post('/OS-OAUTH1/consumers', body={'consumer': ref}) -+ return resp.result['consumer'] -+ -+ def _create_request_token(self, consumer, project_id): -+ endpoint = '/OS-OAUTH1/request_token' -+ client = oauth1.Client( -+ consumer['key'], -+ client_secret=consumer['secret'], -+ signature_method=oauth1.SIG_HMAC, -+ callback_uri='oob', -+ ) -+ headers = {'requested_project_id': project_id} -+ url, headers, body = client.sign( -+ self.base_url + endpoint, http_method='POST', headers=headers -+ ) -+ return endpoint, headers -+ -+ def _create_access_token(self, consumer, token): -+ endpoint = '/OS-OAUTH1/access_token' -+ client = oauth1.Client( -+ consumer['key'], -+ client_secret=consumer['secret'], -+ resource_owner_key=token.key, -+ resource_owner_secret=token.secret, -+ signature_method=oauth1.SIG_HMAC, -+ verifier=token.verifier, -+ ) -+ url, headers, body = client.sign( -+ self.base_url + endpoint, http_method='POST' -+ ) -+ headers.update({'Content-Type': 'application/json'}) -+ return endpoint, headers -+ -+ def _get_oauth_token_request(self, consumer, token): -+ client = oauth1.Client( -+ consumer['key'], -+ client_secret=consumer['secret'], -+ resource_owner_key=token.key, -+ resource_owner_secret=token.secret, -+ signature_method=oauth1.SIG_HMAC, -+ ) -+ endpoint = '/auth/tokens' -+ url, headers, body = client.sign( -+ self.base_url + endpoint, http_method='POST' -+ ) -+ headers.update({'Content-Type': 'application/json'}) -+ ref = {'auth': {'identity': {'oauth1': {}, 'methods': ['oauth1']}}} -+ return endpoint, headers, ref -+ -+ def _authorize_request_token(self, request_id): -+ if isinstance(request_id, bytes): -+ request_id = request_id.decode() -+ return f'/OS-OAUTH1/authorize/{request_id}' -+ -+ def _get_oauth1_token(self): -+ consumer = self._create_single_consumer() -+ consumer = {'key': consumer['id'], 'secret': consumer['secret']} -+ -+ url, headers = self._create_request_token(consumer, self.project_id) -+ content = self.post( -+ url, -+ headers=headers, -+ response_content_type='application/x-www-form-urlencoded', -+ ) -+ credentials = self._urllib_parse_qs_text_keys(content.result) -+ request_key = credentials['oauth_token'][0] -+ request_secret = credentials['oauth_token_secret'][0] -+ request_token = oauth1.Token(request_key, request_secret) -+ -+ url = self._authorize_request_token(request_key) -+ body = {'roles': [{'id': self.role_id}]} -+ resp = self.put(url, body=body, expected_status=http.client.OK) -+ verifier = resp.result['token']['oauth_verifier'] -+ -+ request_token.set_verifier(verifier) -+ url, headers = self._create_access_token(consumer, request_token) -+ content = self.post( -+ url, -+ headers=headers, -+ response_content_type='application/x-www-form-urlencoded', -+ ) -+ credentials = self._urllib_parse_qs_text_keys(content.result) -+ access_key = credentials['oauth_token'][0] -+ access_secret = credentials['oauth_token_secret'][0] -+ access_token = oauth1.Token(access_key, access_secret) -+ -+ url, headers, body = self._get_oauth_token_request( -+ consumer, access_token -+ ) -+ content = self.post(url, headers=headers, body=body) -+ return content.headers['X-Subject-Token'] -+ -+ def test_create_trust_with_ec2_token(self): -+ """An ec2credential token must not be able to create a trust.""" -+ self.post( -+ '/OS-TRUST/trusts', -+ body={'trust': self._make_trust_ref()}, -+ token=self._get_ec2_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_list_trusts_with_ec2_token(self): -+ """An ec2credential token must not be able to list trusts.""" -+ self.get( -+ '/OS-TRUST/trusts', -+ token=self._get_ec2_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_get_trust_with_ec2_token(self): -+ """An ec2credential token must not be able to read a trust.""" -+ r = self.post( -+ '/OS-TRUST/trusts', body={'trust': self._make_trust_ref()} -+ ) -+ trust_id = r.result['trust']['id'] -+ self.get( -+ f'/OS-TRUST/trusts/{trust_id}', -+ token=self._get_ec2_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_delete_trust_with_ec2_token(self): -+ """An ec2credential token must not be able to delete a trust.""" -+ r = self.post( -+ '/OS-TRUST/trusts', body={'trust': self._make_trust_ref()} -+ ) -+ trust_id = r.result['trust']['id'] -+ self.delete( -+ f'/OS-TRUST/trusts/{trust_id}', -+ token=self._get_ec2_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ self.get( -+ f'/OS-TRUST/trusts/{trust_id}', expected_status=http.client.OK -+ ) -+ -+ def test_create_trust_with_oauth1_token(self): -+ """An OAuth1 access-token-scoped token must not create a trust. -+ -+ Without the delegation-boundary check, this still ends up 403 -+ today -- but only by accident, via _find_redelegated_trust()'s -+ unrelated "delegated by trust only" check (OAuth-scoped tokens are -+ also flagged is_delegated_auth). Assert the specific message so -+ this test actually exercises the delegation-boundary check. -+ """ -+ r = self.post( -+ '/OS-TRUST/trusts', -+ body={'trust': self._make_trust_ref()}, -+ token=self._get_oauth1_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ self.assertIn( -+ 'Delegated tokens cannot manage trusts', -+ r.result['error']['message'], -+ ) -+ -+ def test_list_trusts_with_oauth1_token(self): -+ """An OAuth1 access-token-scoped token must not list trusts.""" -+ self.get( -+ '/OS-TRUST/trusts', -+ token=self._get_oauth1_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_get_trust_with_oauth1_token(self): -+ """An OAuth1 access-token-scoped token must not read a trust.""" -+ r = self.post( -+ '/OS-TRUST/trusts', body={'trust': self._make_trust_ref()} -+ ) -+ trust_id = r.result['trust']['id'] -+ self.get( -+ f'/OS-TRUST/trusts/{trust_id}', -+ token=self._get_oauth1_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ def test_delete_trust_with_oauth1_token(self): -+ """An OAuth1 access-token-scoped token must not delete a trust.""" -+ r = self.post( -+ '/OS-TRUST/trusts', body={'trust': self._make_trust_ref()} -+ ) -+ trust_id = r.result['trust']['id'] -+ self.delete( -+ f'/OS-TRUST/trusts/{trust_id}', -+ token=self._get_oauth1_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ self.get( -+ f'/OS-TRUST/trusts/{trust_id}', expected_status=http.client.OK -+ ) -+ -+ def test_escape_hatch_does_not_extend_to_oauth1_or_ec2(self): -+ """allow_insecure_application_credential_trust_escalation is app-cred-only. -+ -+ Enabling it must not exempt oauth1 or ec2credential tokens from -+ the trust-management block -- only application_credential has a -+ documented use case for this escape hatch. -+ """ -+ self.config_fixture.config( -+ group='security_compliance', -+ allow_insecure_application_credential_trust_escalation=True, -+ ) -+ self.post( -+ '/OS-TRUST/trusts', -+ body={'trust': self._make_trust_ref()}, -+ token=self._get_ec2_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ self.post( -+ '/OS-TRUST/trusts', -+ body={'trust': self._make_trust_ref()}, -+ token=self._get_oauth1_token(), -+ expected_status=http.client.FORBIDDEN, -+ ) -+ -+ -+class TestTrustGuardUnit(unit.BaseTestCase): -+ """Unit-level tests for _check_delegated_token (LP#2153453). -+ -+ Calls the guard directly with a stub Flask request context, -+ independent of HTTP request handling or the auth middleware. Matters -+ for ec2credential specifically: an unrelated, already-landed fix bans -+ ec2credential-method tokens at the auth middleware layer before this -+ guard ever runs, so an HTTP-level test would pass regardless of -+ whether the guard itself recognizes ec2credential as delegated. It -+ also matters for oauth1, since _find_redelegated_trust()'s unrelated -+ "delegated by trust only" check happens to also reject oauth1-scoped -+ trust creation, masking whether this guard's own check fires. -+ """ -+ -+ def _check(self, methods, trust_id=None, escape_hatch=False): -+ CONF.set_override( -+ 'allow_insecure_application_credential_trust_escalation', -+ escape_hatch, -+ group='security_compliance', -+ ) -+ self.addCleanup( -+ CONF.clear_override, -+ 'allow_insecure_application_credential_trust_escalation', -+ group='security_compliance', -+ ) -+ app = flask.Flask('test-trusts-guard') -+ with app.test_request_context('/'): -+ token = mock.Mock() -+ token.methods = methods -+ oslo_context = mock.Mock() -+ oslo_context.trust_id = trust_id -+ flask.request.environ[authorization.AUTH_CONTEXT_ENV] = { -+ 'token': token -+ } -+ flask.request.environ[context.REQUEST_CONTEXT_ENV] = oslo_context -+ trusts_api._check_delegated_token() -+ -+ def test_rejects_ec2credential_token(self): -+ self.assertRaises( -+ exception.ForbiddenAction, self._check, ['ec2credential'] -+ ) -+ -+ def test_rejects_oauth1_token(self): -+ self.assertRaises(exception.ForbiddenAction, self._check, ['oauth1']) -+ -+ def test_allows_trust_scoped_token_with_primary_method(self): -+ """A trust-scoped token from a primary auth method is legitimate. -+ -+ This is the trust redelegation feature working as designed: a -+ trustee authenticates (e.g. with a password) to get a trust-scoped -+ token, then uses it to create a further, narrower trust, or to -+ read/list their own trust. Blocking on trust_id alone would break -+ that feature; only the underlying auth method matters here. -+ """ -+ self._check(['password'], trust_id=uuid.uuid4().hex) -+ -+ def test_rejects_ec2_derived_trust_scoped_token(self): -+ """An EC2 credential's blob can embed a trust_id. -+ -+ See keystone.api.credentials._assign_unique_id -- this produces a -+ token that is both trust-scoped and ec2credential-derived. The -+ method check alone must still catch this; trust_id doesn't need -+ its own check. -+ """ -+ self.assertRaises( -+ exception.ForbiddenAction, -+ self._check, -+ ['ec2credential'], -+ trust_id=uuid.uuid4().hex, -+ ) -+ -+ def test_rejects_empty_methods(self): -+ """An empty method list must be treated as delegated, not allowed. -+ -+ This is the fernet round-trip case: methods is serialised as a -+ bitmask over CONF.auth.methods, and a name absent from that list -+ encodes to 0 and decodes back to []. Since issuperset([]) is True, -+ an EC2- or OAuth2-derived token read back from its payload used to -+ pass straight through. -+ """ -+ self.assertRaises(exception.ForbiddenAction, self._check, []) -+ -+ def test_rejects_empty_methods_with_trust_scope(self): -+ """Same, for a token that is additionally trust-scoped.""" -+ self.assertRaises( -+ exception.ForbiddenAction, -+ self._check, -+ [], -+ trust_id=uuid.uuid4().hex, -+ ) -+ -+ def test_allows_password_token(self): -+ self._check(['password']) -+ -+ def test_escape_hatch_allows_application_credential(self): -+ self._check(['application_credential'], escape_hatch=True) -+ -+ def test_escape_hatch_does_not_allow_ec2credential(self): -+ self.assertRaises( -+ exception.ForbiddenAction, -+ self._check, -+ ['ec2credential'], -+ escape_hatch=True, -+ ) -+ -+ def test_escape_hatch_does_not_allow_oauth1(self): -+ self.assertRaises( -+ exception.ForbiddenAction, -+ self._check, -+ ['oauth1'], -+ escape_hatch=True, -+ ) -+ -+ -+class TestSharedDelegationGuardUnit(unit.BaseTestCase): -+ """Unit tests for keystone.api._shared.delegation. -+ -+ LP#2153453, LP#2158538, LP#2159643. Used by trusts.py, os_oauth1.py, -+ users.py, credentials.py, and -+ auth/plugins/token.py to classify a token's methods as primary -+ (allowed) or delegated (blocked from the sensitive actions each of -+ those callers guards). -+ """ -+ -+ def _token(self, methods): -+ token = mock.Mock() -+ token.methods = methods -+ return token -+ -+ def test_rejects_empty_methods(self): -+ """Cover the fernet round-trip gap. -+ -+ ec2credential/oauth2_credential have no bit in the method -+ bitmask, so a token carrying only one of those decodes back to -+ an empty list on any cache miss. -+ """ -+ self.assertTrue(delegation.is_delegated_method(self._token([]))) -+ -+ def test_allows_builtin_primary_method(self): -+ self.assertFalse( -+ delegation.is_delegated_method(self._token(['password'])) -+ ) -+ -+ def test_rejects_known_delegated_method(self): -+ self.assertTrue( -+ delegation.is_delegated_method(self._token(['ec2credential'])) -+ ) -+ -+ def test_rejects_unknown_future_method_by_default(self): -+ """Deny-by-default. -+ -+ A brand new, unreviewed method name must be treated as -+ delegated until an operator or a future patch explicitly -+ allowlists it -- this is the property an allow-by-default -+ denylist design would not have. -+ """ -+ self.assertTrue( -+ delegation.is_delegated_method( -+ self._token(['some_future_delegated_method']) -+ ) -+ ) -+ -+ def test_additional_primary_auth_methods_allows_custom_plugin(self): -+ """A custom auth plugin is not mistaken for a delegated credential. -+ -+ E.g. a site-specific SSO integration, once listed in -+ [auth] additional_primary_auth_methods. -+ """ -+ CONF.set_override( -+ 'additional_primary_auth_methods', ['sso'], group='auth' -+ ) -+ self.addCleanup( -+ CONF.clear_override, -+ 'additional_primary_auth_methods', -+ group='auth', -+ ) -+ self.assertFalse(delegation.is_delegated_method(self._token(['sso']))) -+ -+ def test_unlisted_custom_plugin_still_denied_by_default(self): -+ """An unlisted custom method is still denied without opt-in. -+ -+ Adding the extension point does not weaken the default posture -+ for anyone who hasn't opted in. -+ """ -+ self.assertTrue(delegation.is_delegated_method(self._token(['sso']))) -diff --git a/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml b/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml -new file mode 100644 -index 000000000..6caaa15dd ---- /dev/null -+++ b/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml -@@ -0,0 +1,40 @@ -+--- -+security: -+ - | -+ [`bug 2153453 `_] -+ EC2-derived tokens (``methods: ['ec2credential']``) could still create, -+ list, read, or delete trusts (``/v3/OS-TRUST/trusts``), create, list, -+ read, or delete application credentials -+ (``/v3/users/{user_id}/application_credentials``), and authorize OAuth1 -+ request tokens (``PUT -+ /v3/OS-OAUTH1/authorize/{request_token_id}``), because none of the -+ delegation guards on those endpoints recognized ``ec2credential`` as a -+ delegated method. OAuth1 access-token-scoped tokens had the same gap -+ for trust management. A stolen EC2 access/secret key pair or OAuth1 -+ access token could therefore bootstrap a trust, application credential, -+ or OAuth1 access token delegation that outlives revocation of the -+ original credential. -+ -+ These endpoints now use the same primary-auth-method allowlist already -+ used by ``/v3/credentials`` and the ``OS-EC2`` compat endpoints: any -+ token whose methods aren't entirely primary (interactive) auth methods, -+ or that carries a ``trust_id``, is rejected. Application credential -+ tokens keep their existing, documented behavior on each endpoint -+ (the opt-in trust-escalation escape hatch, and the -+ unrestricted/restricted distinction for creating further application -+ credentials); OAuth1 and EC2 credentials have no such use case and are -+ blocked unconditionally. -+ -+upgrade: -+ - | -+ `bug 2153453 `_: A token issued via -+ a custom, third-party auth plugin (for example a site-specific SSO -+ integration) is now treated as a delegated credential by default and -+ rejected from managing trusts, application credentials, and OAuth1 -+ access tokens, unless its method name is listed in the new -+ ``[auth] additional_primary_auth_methods`` option. Deployments that -+ run a custom auth plugin beyond keystone's own built-in methods -+ (``password``, ``totp``, ``mapped``, ``saml2``, ``openid``, -+ ``external``, ``kerberos``, ``x509``, ``token``) must add its method -+ name to this option to avoid regressing self-service workflows for -+ users authenticated through it, such as switching active project. --- -2.47.3 -