Skip to content

Restrict administrative token issuance and use by source network - #4174

Draft
vlast3k wants to merge 1 commit into
cloudfoundry:developfrom
vlast3k:admin-token-network-policy
Draft

vlast3k wants to merge 1 commit into
cloudfoundry:developfrom
vlast3k:admin-token-network-policy

Conversation

@vlast3k

@vlast3k vlast3k commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add an operator-controlled, deployment-wide source-network policy for administrative token issuance,
refresh, and use, preserving ordinary tokens and default behavior when disabled.

  • Protect uaa.admin, cloud_controller.admin, cloud_controller.admin_read_only,
    cloud_controller.global_auditor, and zones.<id>.admin; optional exact additions extend this set.
  • Inspect resolved scopes, client-only authorities, retained refresh capabilities, and final claims.
  • Check validated bearer authentication before success/context publication on every resource chain.
  • Check validated JWT assertions and exchange subjects even when output scopes are ordinary;
    ordinary clients can still introspect administrative subject tokens.
  • Fail startup on invalid CIDRs; enabled with an empty allowlist denies protected tokens.
  • Use the current container-normalized remote address, never caller-provided forwarding headers.
  • Document configuration, denial behavior, proxy trust, and coordinated rollout; add REST Docs examples.

Configuration prefix: uaa.admin_token_network_policy with enabled, allowed_cidrs, and
additional_protected_scopes. Identity-zone/client configuration cannot weaken the deployment policy.

Validation

  • 136 focused server tests passed (policy, bearer filter, chain wiring, assertion/exchange authentication).
  • 76 token-service tests passed, including narrowed client scopes, retained administrative refresh
    scopes, and final enhancer overrides.
  • Full generateDocs succeeded: 126 docs tests and rendered Slate HTML.
  • Changed Markdown passes lint; git diff --check is clean.

Draft pending security/CI review, database/grant/zone integration coverage, and real-ingress forged-header
tests. No live deployment was changed. Operators must configure actual trusted proxies and NAT/VPN
egress; documentation addresses are not defaults. External transforming proxies/custom authentication
managers must preserve equivalent checks on original credentials.

Coordinated changes

UAA alone cannot enforce use at offline JWT resource servers. Companion draft PRs:

This is a network allowlist, not cryptographic binding to the original issuance IP or a complete
delegation/escalation boundary. Other resource servers need independent enforcement.

@fhanik

fhanik commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

First suggestion is that the property lives inside an existing namespace, for example

jwt:
  token:
    admin:
      network:

the pattern is zones\..+\.admin (AdminTokenNetworkPolicy.java:70). Its .+ also matches dots, so the existing zones.<id>.clients.admin scope is protected too. The docs list only zones..admin.

High level AI review below.

@fhanik fhanik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. I went through it with the policy disabled and enabled.

Disabled (the default): no behavior change found. The full suite passes on 20400fa, the documented uaa.yml keys bind, and the defaults are disabled with empty lists. The two new AccessDeniedException catches in the filters wrap only the authentication step, where the existing code does not throw that exception.

Enabled: all 21 bearer-token filters in the security chains receive the policy, as do the token services and the external IdP manager.

In addition to the namespace and the zone pattern from my earlier comment, the inline comments cover:

  1. The check in ExternalOAuthAuthenticationManager.validateToken also blocks the browser sign-in through an external IdP.
  2. Denials throw AccessDeniedException, so the implicit and hybrid flows do not get the OAuth error redirect, and /oauth/token logs each denial at ERROR with a stack trace.
  3. With the policy disabled, every token issuance with a refresh token still decodes the refresh token, and every external token validation parses the claims.
  4. The denial log line has no request context.

Points 1 and 2 come with tests that fail on this commit, a guard test that passes, and a suggested fix that turns them green.

Smaller points:

  • UaaConfig and SpringServletXmlSecurityConfiguration use the fully qualified org.cloudfoundry.identity.uaa.oauth.AdminTokenNetworkPolicy; an import is enough.
  • Imports are out of order in AdminTokenNetworkPolicy, OAuth2AuthenticationProcessingFilter, BackwardsCompatibleTokenEndpointAuthenticationFilter and ExternalOAuthAuthenticationManager.
  • Both filters write the same 403 body by hand; one shared helper keeps the text in one place.
  • Zone tests (subdomain and zone path) are still open, as the description notes.

jwtToken.checkExpiry();
// Assertions and exchange subject tokens are credentials, even when output scopes are ordinary.
// This validation path is not used for introspection subjects.
adminTokenNetworkPolicy.checkClaims(JsonUtils.readValueAsMap(jwtToken.getJwt().getClaims()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check also runs for the browser sign-in through an external IdP, not only for assertions and exchange subjects. validateToken is reached from three places:

  • the jwt-bearer assertion at /oauth/token (getExternalAuthenticationDetails without an origin),
  • verifySubjectToken for token exchange,
  • the interactive callback /login/callback/{origin} (getExternalAuthenticationDetails with the origin).

For an oauth2.0 IdP, the token validated here is the upstream access token. If it lists a protected scope (for example an upstream UAA that grants cloud_controller.admin to the user), a user who signs in from outside the allowlist gets an AccessDeniedException and lands on /oauth_error, even when the application asks only for openid. The same happens for an OIDC id_token with a scope, authorities or granted_scopes claim that names a protected scope. The sign-in issues no UAA token, and an administrative token requested afterwards is still checked by UaaTokenServices.

enforceRelyingPartyAudience already separates the two cases (it is true only for the interactive callback), so the check can be limited to the machine-to-machine callers:

Suggested change
adminTokenNetworkPolicy.checkClaims(JsonUtils.readValueAsMap(jwtToken.getJwt().getClaims()));
if (!enforceRelyingPartyAudience) {
adminTokenNetworkPolicy.checkClaims(JsonUtils.readValueAsMap(jwtToken.getJwt().getClaims()));
}

With this change the test below passes, and the cases of administrativeAssertionsAndExchangeSubjectsRequireAllowedCurrentSource are still denied. If blocking the sign-in is intended instead, please describe it in the docs and in the comment above.

This line also parses the claims of every validated external token while the policy is disabled; see the comment on UaaTokenServices.

Tests for ExternalOAuthAuthenticationManagerTest: the first fails on this commit with AccessDeniedException, the guard passes
    @Test
    void interactiveLoginThroughAnExternalProviderIsNotBlockedByTheUpstreamTokenScopes() {
        ExternalOAuthAuthenticationManager manager = managerForAnOAuth20ProviderReturning(upstreamAccessTokenWithAnAdministrativeScope());
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(requestFrom("198.51.100.1")));
        try {
            // origin set: the browser callback /login/callback/upstream-uaa
            ExternalOAuthCodeToken interactiveLogin = new ExternalOAuthCodeToken("code", "upstream-uaa", "http://localhost/callback", null, null, null);

            assertThatNoException().isThrownBy(() -> manager.getExternalAuthenticationDetails(interactiveLogin));
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    }

    // Guard: the same upstream token presented as a JWT bearer assertion (no origin) is denied, as documented.
    @Test
    void jwtBearerAssertionWithTheSameUpstreamTokenIsDenied() {
        ExternalOAuthAuthenticationManager manager = managerForAnOAuth20ProviderReturning(upstreamAccessTokenWithAnAdministrativeScope());
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(requestFrom("198.51.100.1")));
        try {
            // origin null: the assertion of a jwt-bearer grant at /oauth/token
            ExternalOAuthCodeToken assertion = new ExternalOAuthCodeToken(null, null, null, null, null, null);

            assertThatThrownBy(() -> manager.getExternalAuthenticationDetails(assertion))
                    .isInstanceOf(AccessDeniedException.class)
                    .hasMessage("Administrative token source address is not allowed");
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }
    }

    private String upstreamAccessTokenWithAnAdministrativeScope() {
        Map<String, Object> header = map(
                entry(HeaderParameterNames.ALGORITHM, JWSAlgorithm.RS256.getName()),
                entry(HeaderParameterNames.KEY_ID, OIDC_PROVIDER_KEY)
        );
        JWSSigner signer = new KeyInfo(OIDC_PROVIDER_KEY, OIDC_PROVIDER_TOKEN_SIGNING_KEY, DEFAULT_UAA_URL).getSigner();
        Map<String, Object> claims = map(
                entry(ISS, "http://issuer.com"),
                entry(AUD, "uaa-relying-party"),
                entry(EXPIRY_IN_SECONDS, ((int) (System.currentTimeMillis() / 1000L)) + 60),
                entry(SUB, "abc-def-asdf"),
                entry(EMAIL, "someuser@example.com"),
                entry("scope", List.of("openid", "cloud_controller.admin"))
        );
        return UaaTokenUtils.constructToken(header, claims, signer);
    }

    private ExternalOAuthAuthenticationManager managerForAnOAuth20ProviderReturning(String upstreamAccessToken) {
        RawExternalOAuthIdentityProviderDefinition config = new RawExternalOAuthIdentityProviderDefinition();
        config.setResponseType("code");
        config.setIssuer("http://issuer.com");
        config.setTokenKey(OIDC_PROVIDER_TOKEN_SIGNING_KEY);
        config.setRelyingPartyId("uaa-relying-party");
        IdentityProvider<RawExternalOAuthIdentityProviderDefinition> upstream = new IdentityProvider<>();
        upstream.setType(OAUTH20);
        upstream.setOriginKey("upstream-uaa");
        upstream.setConfig(config);
        when(identityProviderProvisioning.retrieveByOrigin("upstream-uaa", ZONE_ID)).thenReturn((IdentityProvider) upstream);

        ExternalOAuthAuthenticationManager manager = new ExternalOAuthAuthenticationManager(
                identityProviderProvisioning, new IdentityZoneManagerImpl(), new RestTemplate(), new RestTemplate(),
                tokenEndpointBuilder, new KeyInfoService(UAA_ISSUER_BASE_URL), oidcMetadataFetcher, false) {
            @Override
            public IdentityProvider resolveOriginProvider(String token) {
                return upstream;
            }

            // the authorization code exchange with the upstream provider returns its access token
            @Override
            protected <T extends AbstractExternalOAuthIdentityProviderDefinition<T>> String getTokenFromCode(
                    ExternalOAuthCodeToken codeToken, IdentityProvider<T> provider) {
                return upstreamAccessToken;
            }
        };
        manager.setAdminTokenNetworkPolicy(new AdminTokenNetworkPolicy(
                new UaaProperties.AdminTokenNetworkPolicy(true, List.of("192.0.2.0/24"), List.of())));
        return manager;
    }

    private static MockHttpServletRequest requestFrom(String remoteAddress) {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRemoteAddr(remoteAddress);
        return request;
    }

byte[] address = literal(request == null ? null : request.getRemoteAddr());
if (address == null || networks.stream().noneMatch(network -> network.contains(address))) {
LOGGER.warn("Administrative token network policy denied request");
throw new AccessDeniedException("Administrative token source address is not allowed");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AccessDeniedException is not an OAuth2Exception, so the authorization endpoint does not produce the OAuth error redirect the docs describe ("Authorization endpoint flows use the existing OAuth authorization error handling"). UaaAuthorizationEndpoint.getImplicitGrantOrHybridResponse catches only OAuth2Exception, and authorize rethrows anything else. When a signed-in user outside the allowlist requests uaa.admin with response_type=token:

  • without prompt: 302 to /login, and the client receives nothing at its redirect_uri,
  • with prompt=none: 302 to the redirect_uri with error=internal_server_error.

At /oauth/token the response is the expected 403, but it goes through TokenEndpoint's generic Exception handler, which logs every denial at ERROR with a stack trace.

Throwing an OAuth2Exception subclass with access_denied and 403 (like the private ForbiddenException in DefaultWebResponseExceptionTranslator) fixes these cases. With that change, both tests below pass, and TokenEndpoint handles the denial in its OAuth2Exception handler, which logs at WARN without the stack trace. The catches in the two filters and the rethrow in ExternalOAuthAuthenticationManager.verifySubjectToken then need to name the new type. Otherwise verifySubjectToken wraps the denial in invalid_token.

MockMvc test (uaa module, mock/token): the first two fail on this commit, the guard passes
package org.cloudfoundry.identity.uaa.mock.token;

import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication;
import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails;
import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal;
import org.cloudfoundry.identity.uaa.constants.OriginKeys;
import org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils;
import org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils;
import org.cloudfoundry.identity.uaa.scim.ScimUser;
import org.cloudfoundry.identity.uaa.user.UaaAuthority;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

/**
 * The allowlist contains the MockMvc default address 127.0.0.1, so the admin token obtained in
 * AbstractTokenMockMvcTests#setUpContext is still issued. The denied requests come from 198.51.100.1.
 */
@TestPropertySource(properties = {
        "uaa.admin-token-network-policy.enabled=true",
        "uaa.admin-token-network-policy.allowed-cidrs[0]=127.0.0.1/32"
})
class AdminTokenNetworkPolicyMockMvcTests extends AbstractTokenMockMvcTests {

    private static final String OUTSIDE_THE_ALLOWLIST = "198.51.100.1";
    private static final String INSIDE_THE_ALLOWLIST = "127.0.0.1";

    // Fails on this commit: 302 to /login
    @Test
    void deniedImplicitGrantRedirectsToTheClientWithAccessDenied() throws Exception {
        MvcResult result = mockMvc.perform(implicitGrantForAnAdministrativeScope(OUTSIDE_THE_ALLOWLIST)).andReturn();

        assertThat(result.getResponse().getStatus()).isEqualTo(302);
        assertThat(result.getResponse().getRedirectedUrl())
                .startsWith(TEST_REDIRECT_URI + "#")
                .contains("error=access_denied")
                .doesNotContain("access_token=");
    }

    // Fails on this commit: error=internal_server_error
    @Test
    void deniedImplicitGrantWithPromptNoneRedirectsToTheClientWithAccessDenied() throws Exception {
        MvcResult result = mockMvc.perform(implicitGrantForAnAdministrativeScope(OUTSIDE_THE_ALLOWLIST)
                .param("prompt", "none")).andReturn();

        assertThat(result.getResponse().getStatus()).isEqualTo(302);
        assertThat(result.getResponse().getRedirectedUrl())
                .startsWith(TEST_REDIRECT_URI + "#")
                .contains("error=access_denied");
    }

    // Guard: the same request from an allowed address issues the token
    @Test
    void implicitGrantFromAnAllowedAddressIssuesTheToken() throws Exception {
        MvcResult result = mockMvc.perform(implicitGrantForAnAdministrativeScope(INSIDE_THE_ALLOWLIST)).andReturn();

        assertThat(result.getResponse().getStatus()).isEqualTo(302);
        assertThat(result.getResponse().getRedirectedUrl())
                .startsWith(TEST_REDIRECT_URI + "#")
                .contains("access_token=");
    }

    private MockHttpServletRequestBuilder implicitGrantForAnAdministrativeScope(String remoteAddress) {
        // uaa.admin is a built-in protected scope. The client may request it and the user is a member of the group.
        String clientId = "implicit-" + generator.generate();
        setUpClients(clientId, "uaa.none", "openid,uaa.admin", "implicit", true, TEST_REDIRECT_URI);
        ScimUser user = setUpUser(jdbcScimUserProvisioning, jdbcScimGroupMembershipManager, jdbcScimGroupProvisioning,
                "admin-user-" + generator.generate(), "openid,uaa.admin", OriginKeys.UAA, IdentityZoneHolder.get().getId());

        return get("/oauth/authorize")
                .session(sessionOf(user))
                .param(OAuth2Utils.RESPONSE_TYPE, "token")
                .param(OAuth2Utils.SCOPE, "uaa.admin")
                .param(OAuth2Utils.STATE, generator.generate())
                .param(OAuth2Utils.CLIENT_ID, clientId)
                .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)
                .with(request -> {
                    request.setRemoteAddr(remoteAddress);
                    return request;
                });
    }

    private static MockHttpSession sessionOf(ScimUser user) {
        UaaPrincipal principal = new UaaPrincipal(user.getId(), user.getUserName(), user.getPrimaryEmail(),
                OriginKeys.UAA, "", IdentityZoneHolder.get().getId());
        UaaAuthentication authentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES,
                new UaaAuthenticationDetails(false, "clientId", OriginKeys.ORIGIN, "sessionId"));
        authentication.setAuthenticationMethods(Set.of("pwd"));
        MockHttpSession session = new MockHttpSession();
        MockMvcUtils.getZoneSession(session).setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                new MockMvcUtils.MockSecurityContext(authentication));
        return session;
    }
}

}
adminTokenNetworkPolicy.checkClaims(jwtAccessToken);
if (refreshToken != null) {
adminTokenNetworkPolicy.checkClaims(JsonUtils.readValueAsMap(JwtHelper.decode(refreshToken).getClaims()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the policy disabled (the default), this decodes the refresh token and parses its claims on every issuance that returns a refresh token, and then check returns on !enabled. ExternalOAuthAuthenticationManager.validateToken does the same for every validated external token. An isEnabled() guard at these two call sites keeps the default path as it was. Another option is a checkClaims overload that takes the encoded token and decodes it only when the policy is enabled.

// The servlet container establishes proxy trust. Never read forwarded headers or authentication details here.
byte[] address = literal(request == null ? null : request.getRemoteAddr());
if (address == null || networks.stream().noneMatch(network -> network.contains(address))) {
LOGGER.warn("Administrative token network policy denied request");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This message does not say which request was denied. The docs ask operators to verify allowed and denied issuance and use before enabling the policy, and to inventory admin egress addresses and automation clients. A fixed message makes both hard to do from the logs. Adding the remote address, plus the client id and zone where the callers have them, keeps the message free of credentials and token contents. An audit event for the denial would also make it visible in the audit log.

private boolean protectedPrivileges(Collection<String> privileges) {
return privileges != null && privileges.stream().anyMatch(privilege -> privilege != null && (
ADMIN_SCOPES.contains(privilege) || additionalProtectedScopes.contains(privilege)
|| privilege.matches("zones\\..+\\.admin")));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up to the pattern point in my earlier comment: ZoneManagementScopes.ZONE_MANAGING_SCOPE_REGEX matches the zone id with [^\\.]+, without dots. A precompiled pattern also avoids compiling the regex on every check:

Suggested change
|| privilege.matches("zones\\..+\\.admin")));
|| ZONE_ADMIN_SCOPE.matcher(privilege).matches()));

with private static final Pattern ZONE_ADMIN_SCOPE = Pattern.compile("zones\\.[^.]+\\.admin");. If the wider match is intended, the docs should list zones.<id>.clients.admin.

Test for AdminTokenNetworkPolicyTests, fails on this commit:

    @Test
    void zoneClientAdministratorScopeIsNotABuiltInProtectedScope() {
        request("198.51.100.1");

        assertThatCode(() -> policy.checkIssuance(List.of("zones.tenant.clients.admin"), List.of()))
                .doesNotThrowAnyException();
    }

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Development

Successfully merging this pull request may close these issues.

2 participants