Subject: 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. . Author: Grzegorz Grasza Date: Thu, 23 Jul 2026 09:32:00 +0200 Bug: https://bugs.launchpad.net/keystone/+bug/2153453 Bug-Debian: https://bugs.debian.org/XXXXXXX Change-Id: Ic8775eb0fdaa2330206023818ce18f76430fa45e Assisted-by: Claude Sonnet 5 Signed-off-by: Grzegorz Grasza Signed-off-by: Artem Goncharov Origin: pre-OSSA mailing list Last-Update: 2026-08-11 diff --git a/keystone/api/os_oauth1.py b/keystone/api/os_oauth1.py index 4870d9a06..e0338a6f9 100644 --- a/keystone/api/os_oauth1.py +++ b/keystone/api/os_oauth1.py @@ -42,6 +42,61 @@ ENFORCER = rbac_enforcer.RBACEnforcer CONF = keystone.conf.CONF +# Methods that authenticate a user directly, as opposed to via a delegated +# credential (application_credential, oauth1, ec2credential). Anything not +# in this set is treated as delegated by _check_can_authorize_request_token, +# so a new delegated auth method is restricted by default instead of +# silently falling through unchecked. +# +# Deliberately a local, independent copy rather than an import from a +# shared module: this set is also defined in keystone.api.credentials, +# keystone.api.trusts, keystone.api.users, and +# keystone.auth.plugins.token, each fixing a separately reported, +# separately embargoed security bug (LP#2158538, LP#2159643, LP#2153453). +# Each of those bugs may be disclosed and its patch applied on its own, +# in any order, so none of these copies may depend on another one of +# these patches having landed first. Once all of the related bugs are +# public, consolidating these into one keystone.api._shared module is a +# reasonable follow-up cleanup -- do not do it while any of them are +# still embargoed, or re-applying one patch without the others will +# NameError. +_PRIMARY_AUTH_METHODS = frozenset( + { + 'external', + 'kerberos', + 'mapped', + 'openid', + 'password', + 'saml2', + 'token', + 'totp', + 'x509', + } +) + + +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) + is_delegated_method = bool(token) and not _PRIMARY_AUTH_METHODS.issuperset( + token.methods + ) + if trust_id or is_delegated_method: + 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 @@ -311,24 +366,11 @@ class AuthorizeResource(_OAuth1ResourceBase): ) 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 252bd3b44..ef16ea477 100644 --- a/keystone/api/trusts.py +++ b/keystone/api/trusts.py @@ -50,28 +50,83 @@ TRUST_ID_PARAMETER_RELATION = _build_parameter_relation( ) -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. +# Methods that authenticate a user directly, as opposed to via a delegated +# credential (application_credential, oauth1, ec2credential). Anything not +# in this set is treated as delegated by _check_delegated_token, so +# a new delegated auth method is restricted by default instead of silently +# falling through unchecked. +# +# Deliberately a local, independent copy rather than an import from a +# shared module: this set is also defined in keystone.api.credentials, +# keystone.api.os_oauth1, keystone.api.users, and +# keystone.auth.plugins.token, each fixing a separately reported, +# separately embargoed security bug (LP#2158538, LP#2159643, LP#2153453). +# Each of those bugs may be disclosed and its patch applied on its own, +# in any order, so none of these copies may depend on another one of +# these patches having landed first. Once all of the related bugs are +# public, consolidating these into one keystone.api._shared module is a +# reasonable follow-up cleanup -- do not do it while any of them are +# still embargoed, or re-applying one patch without the others will +# NameError. +_PRIMARY_AUTH_METHODS = frozenset( + { + 'external', + 'kerberos', + 'mapped', + 'openid', + 'password', + 'saml2', + 'token', + 'totp', + 'x509', + } +) + + +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: + token = flask.request.environ.get(authorization.AUTH_CONTEXT_ENV, {}).get( + 'token' + ) + if not token: return - auth_context = flask.request.environ.get( - authorization.AUTH_CONTEXT_ENV, {} + if _PRIMARY_AUTH_METHODS.issuperset(token.methods): + return + if ( + 'application_credential' in token.methods + and CONF.security_compliance.allow_insecure_application_credential_trust_escalation + ): + return + 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(): @@ -129,7 +184,7 @@ def _normalize_trust_roles(trust): class TrustResourceBase(ks_flask.ResourceBase): def _check_unrestricted(self): - _check_application_credential() + _check_delegated_token() class TrustsResource(TrustResourceBase): @@ -218,7 +273,7 @@ class TrustsResource(TrustResourceBase): ) else: ENFORCER.enforce_call(action='identity:list_trusts') - _check_application_credential() + _check_delegated_token() trusts = [] @@ -334,7 +389,7 @@ class TrustResource(TrustResourceBase): 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 @@ -438,7 +493,7 @@ class RolesForTrustListResource(flask_restful.Resource): 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) @@ -490,7 +545,7 @@ class RoleForTrustResource(flask_restful.Resource): 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 b24abd060..1e67d5d30 100644 --- a/keystone/api/users.py +++ b/keystone/api/users.py @@ -119,16 +119,46 @@ def _check_delegation_for_ec2(oslo_context, token, project_id): ) +# Methods that authenticate a user directly, as opposed to via a delegated +# credential (application_credential, oauth1, ec2credential). Anything not +# in this set is treated as delegated by _block_delegated_token and +# _block_delegated_token_app_creds, so a new delegated auth method is +# restricted by default instead of silently falling through unchecked. +# +# Deliberately a local, independent copy rather than an import from a +# shared module: this set is also defined in keystone.api.credentials, +# keystone.api.os_oauth1, keystone.api.trusts, and +# keystone.auth.plugins.token, each fixing a separately reported, +# separately embargoed security bug (LP#2158538, LP#2159643, LP#2153453). +# Each of those bugs may be disclosed and its patch applied on its own, +# in any order, so none of these copies may depend on another one of +# these patches having landed first. Once all of the related bugs are +# public, consolidating these into one keystone.api._shared module is a +# reasonable follow-up cleanup -- do not do it while any of them are +# still embargoed, or re-applying one patch without the others will +# NameError. +_PRIMARY_AUTH_METHODS = frozenset( + { + 'external', + 'kerberos', + 'mapped', + 'openid', + 'password', + 'saml2', + 'token', + 'totp', + 'x509', + } +) + + 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) + is_delegated_method = bool(token) and not _PRIMARY_AUTH_METHODS.issuperset( + token.methods + ) + if trust_id or is_delegated_method: raise ks_exception.Forbidden( _( 'Cannot manage OAuth access tokens with a token ' @@ -138,24 +168,28 @@ 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: + is_delegated_method = bool(token) and not _PRIMARY_AUTH_METHODS.issuperset( + token.methods + ) + if trust_id or is_delegated_method: raise ks_exception.Forbidden( _( 'Cannot manage application credentials with a token ' diff --git a/keystone/tests/unit/test_v3_application_credential.py b/keystone/tests/unit/test_v3_application_credential.py index 75c663515..ecf6bc5bc 100644 --- a/keystone/tests/unit/test_v3_application_credential.py +++ b/keystone/tests/unit/test_v3_application_credential.py @@ -15,12 +15,15 @@ import http.client import unittest import uuid +from keystoneclient.contrib.ec2 import utils as ec2_utils from oslo_utils import timeutils from testtools import matchers 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 CONF = keystone.conf.CONF @@ -1015,3 +1018,103 @@ class ApplicationCredentialTestCase(test_v3.RestfulTestCase): expected_status_code=http.client.NO_CONTENT, headers={"X-Auth-Token": token}, ) + + +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 6e3df9a76..c883553f6 100644 --- a/keystone/tests/unit/test_v3_oauth1.py +++ b/keystone/tests/unit/test_v3_oauth1.py @@ -22,12 +22,14 @@ from urllib import parse as urlparse import uuid import freezegun +from keystoneclient.contrib.ec2 import utils as ec2_utils from oslo_serialization import jsonutils from oslo_utils import timeutils from pycadf import cadftaxonomy 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 @@ -835,6 +837,61 @@ class AuthTokenTests: 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): def config_overrides(self): diff --git a/keystone/tests/unit/test_v3_trust.py b/keystone/tests/unit/test_v3_trust.py index 57bb24624..79e114a25 100644 --- a/keystone/tests/unit/test_v3_trust.py +++ b/keystone/tests/unit/test_v3_trust.py @@ -11,14 +11,25 @@ # under the License. import http.client +from unittest import mock +import urllib import uuid +import flask + +from keystoneclient.contrib.ec2 import utils as ec2_utils from oslo_utils import timeutils +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 @@ -775,3 +786,383 @@ class TrustsWithApplicationCredentials(test_v3.RestfulTestCase): 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_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, + ) diff --git a/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml b/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml new file mode 100644 index 000000000..a67768790 --- /dev/null +++ b/releasenotes/notes/bug-2153453-6f2a1d9e0c7b4a83.yaml @@ -0,0 +1,26 @@ +--- +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. -- 2.53.0