Skip to content

Commit 3ea527b

Browse files
mattisonchaolhotari
authored andcommitted
[fix][broker] support missing tenant level fine-granted permissions (#23660)
(cherry picked from commit 280997e)
1 parent d136476 commit 3ea527b

File tree

3 files changed

+209
-5
lines changed

3 files changed

+209
-5
lines changed

pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
import org.apache.pulsar.common.naming.NamedEntity;
4949
import org.apache.pulsar.common.policies.data.TenantInfo;
5050
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
51+
import org.apache.pulsar.common.policies.data.TenantOperation;
5152
import org.apache.pulsar.common.util.FutureUtil;
5253
import org.slf4j.Logger;
5354
import org.slf4j.LoggerFactory;
@@ -62,7 +63,7 @@ public class TenantsBase extends PulsarWebResource {
6263
@ApiResponse(code = 404, message = "Tenant doesn't exist")})
6364
public void getTenants(@Suspended final AsyncResponse asyncResponse) {
6465
final String clientAppId = clientAppId();
65-
validateSuperUserAccessAsync()
66+
validateBothSuperUserAndTenantOperation(null, TenantOperation.LIST_TENANTS)
6667
.thenCompose(__ -> tenantResources().listTenantsAsync())
6768
.thenAccept(tenants -> {
6869
// deep copy the tenants to avoid concurrent sort exception
@@ -84,7 +85,7 @@ public void getTenants(@Suspended final AsyncResponse asyncResponse) {
8485
public void getTenantAdmin(@Suspended final AsyncResponse asyncResponse,
8586
@ApiParam(value = "The tenant name") @PathParam("tenant") String tenant) {
8687
final String clientAppId = clientAppId();
87-
validateSuperUserAccessAsync()
88+
validateBothSuperUserAndTenantOperation(tenant, TenantOperation.GET_TENANT)
8889
.thenCompose(__ -> tenantResources().getTenantAsync(tenant))
8990
.thenApply(tenantInfo -> {
9091
if (!tenantInfo.isPresent()) {
@@ -121,7 +122,7 @@ public void createTenant(@Suspended final AsyncResponse asyncResponse,
121122
asyncResponse.resume(new RestException(Status.PRECONDITION_FAILED, "Tenant name is not valid"));
122123
return;
123124
}
124-
validateSuperUserAccessAsync()
125+
validateBothSuperUserAndTenantOperation(tenant, TenantOperation.CREATE_TENANT)
125126
.thenCompose(__ -> validatePoliciesReadOnlyAccessAsync())
126127
.thenCompose(__ -> validateClustersAsync(tenantInfo))
127128
.thenCompose(__ -> validateAdminRoleAsync(tenantInfo))
@@ -169,7 +170,7 @@ public void updateTenant(@Suspended final AsyncResponse asyncResponse,
169170
@ApiParam(value = "The tenant name") @PathParam("tenant") String tenant,
170171
@ApiParam(value = "TenantInfo") TenantInfoImpl newTenantAdmin) {
171172
final String clientAppId = clientAppId();
172-
validateSuperUserAccessAsync()
173+
validateBothSuperUserAndTenantOperation(tenant, TenantOperation.UPDATE_TENANT)
173174
.thenCompose(__ -> validatePoliciesReadOnlyAccessAsync())
174175
.thenCompose(__ -> validateClustersAsync(newTenantAdmin))
175176
.thenCompose(__ -> validateAdminRoleAsync(newTenantAdmin))
@@ -206,7 +207,7 @@ public void deleteTenant(@Suspended final AsyncResponse asyncResponse,
206207
@PathParam("tenant") @ApiParam(value = "The tenant name") String tenant,
207208
@QueryParam("force") @DefaultValue("false") boolean force) {
208209
final String clientAppId = clientAppId();
209-
validateSuperUserAccessAsync()
210+
validateBothSuperUserAndTenantOperation(tenant, TenantOperation.DELETE_TENANT)
210211
.thenCompose(__ -> validatePoliciesReadOnlyAccessAsync())
211212
.thenCompose(__ -> internalDeleteTenant(tenant, force))
212213
.thenAccept(__ -> {
@@ -304,4 +305,41 @@ private CompletableFuture<Void> validateAdminRoleAsync(TenantInfoImpl info) {
304305
}
305306
return CompletableFuture.completedFuture(null);
306307
}
308+
309+
private CompletableFuture<Boolean> validateBothSuperUserAndTenantOperation(String tenant,
310+
TenantOperation operation) {
311+
final var superUserValidationFuture = validateSuperUserAccessAsync();
312+
final var tenantOperationValidationFuture = validateTenantOperationAsync(tenant, operation);
313+
return CompletableFuture.allOf(superUserValidationFuture, tenantOperationValidationFuture)
314+
.handle((__, err) -> {
315+
if (!superUserValidationFuture.isCompletedExceptionally()
316+
|| !tenantOperationValidationFuture.isCompletedExceptionally()) {
317+
return true;
318+
}
319+
if (log.isDebugEnabled()) {
320+
Throwable superUserValidationException = null;
321+
try {
322+
superUserValidationFuture.join();
323+
} catch (Throwable ex) {
324+
superUserValidationException = FutureUtil.unwrapCompletionException(ex);
325+
}
326+
Throwable brokerOperationValidationException = null;
327+
try {
328+
tenantOperationValidationFuture.join();
329+
} catch (Throwable ex) {
330+
brokerOperationValidationException = FutureUtil.unwrapCompletionException(ex);
331+
}
332+
log.debug("validateBothTenantOperationAndSuperUser failed."
333+
+ " originalPrincipal={} clientAppId={} operation={} "
334+
+ "superuserValidationError={} tenantOperationValidationError={}",
335+
originalPrincipal(), clientAppId(), operation.toString(),
336+
superUserValidationException, brokerOperationValidationException);
337+
}
338+
throw new RestException(Status.UNAUTHORIZED,
339+
String.format("Unauthorized to validateBothTenantOperationAndSuperUser for"
340+
+ " originalPrincipal [%s] and clientAppId [%s] "
341+
+ "about operation [%s] ",
342+
originalPrincipal(), clientAppId(), operation.toString()));
343+
});
344+
}
307345
}
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.pulsar.broker.admin;
20+
21+
import static org.mockito.ArgumentMatchers.any;
22+
import static org.mockito.ArgumentMatchers.eq;
23+
import static org.mockito.ArgumentMatchers.isNull;
24+
import static org.mockito.Mockito.spy;
25+
import static org.mockito.Mockito.verify;
26+
import lombok.SneakyThrows;
27+
import org.apache.commons.lang3.reflect.FieldUtils;
28+
import org.apache.pulsar.broker.authorization.AuthorizationService;
29+
import org.apache.pulsar.client.admin.PulsarAdmin;
30+
import org.apache.pulsar.client.admin.PulsarAdminException;
31+
import org.apache.pulsar.client.impl.auth.AuthenticationToken;
32+
import org.apache.pulsar.common.policies.data.TenantInfo;
33+
import org.apache.pulsar.common.policies.data.TenantOperation;
34+
import org.apache.pulsar.security.MockedPulsarStandalone;
35+
import org.mockito.Mockito;
36+
import org.testng.Assert;
37+
import org.testng.annotations.AfterClass;
38+
import org.testng.annotations.AfterMethod;
39+
import org.testng.annotations.BeforeClass;
40+
import org.testng.annotations.BeforeMethod;
41+
import org.testng.annotations.Test;
42+
import java.util.Set;
43+
import java.util.UUID;
44+
45+
@Test(groups = "broker-admin")
46+
public class TenantEndpointsAuthorizationTest extends MockedPulsarStandalone {
47+
48+
private AuthorizationService orignalAuthorizationService;
49+
private AuthorizationService spyAuthorizationService;
50+
51+
private PulsarAdmin superUserAdmin;
52+
private PulsarAdmin nobodyAdmin;
53+
54+
@SneakyThrows
55+
@BeforeClass(alwaysRun = true)
56+
public void setup() {
57+
configureTokenAuthentication();
58+
configureDefaultAuthorization();
59+
start();
60+
this.superUserAdmin = PulsarAdmin.builder()
61+
.serviceHttpUrl(getPulsarService().getWebServiceAddress())
62+
.authentication(new AuthenticationToken(SUPER_USER_TOKEN))
63+
.build();
64+
this.nobodyAdmin = PulsarAdmin.builder()
65+
.serviceHttpUrl(getPulsarService().getWebServiceAddress())
66+
.authentication(new AuthenticationToken(NOBODY_TOKEN))
67+
.build();
68+
}
69+
70+
@BeforeMethod(alwaysRun = true)
71+
public void before() throws IllegalAccessException {
72+
orignalAuthorizationService = getPulsarService().getBrokerService().getAuthorizationService();
73+
spyAuthorizationService = spy(orignalAuthorizationService);
74+
FieldUtils.writeField(getPulsarService().getBrokerService(), "authorizationService",
75+
spyAuthorizationService, true);
76+
}
77+
78+
@AfterMethod(alwaysRun = true)
79+
public void after() throws IllegalAccessException {
80+
if (orignalAuthorizationService != null) {
81+
FieldUtils.writeField(getPulsarService().getBrokerService(), "authorizationService", orignalAuthorizationService, true);
82+
}
83+
}
84+
85+
@SneakyThrows
86+
@AfterClass(alwaysRun = true)
87+
public void cleanup() {
88+
if (superUserAdmin != null) {
89+
superUserAdmin.close();
90+
superUserAdmin = null;
91+
}
92+
spyAuthorizationService = null;
93+
orignalAuthorizationService = null;
94+
super.close();
95+
}
96+
97+
@Test
98+
public void testListTenants() throws PulsarAdminException {
99+
superUserAdmin.tenants().getTenants();
100+
// test allow broker operation
101+
verify(spyAuthorizationService)
102+
.allowTenantOperationAsync(isNull(), Mockito.eq(TenantOperation.LIST_TENANTS), any(), any());
103+
// fallback to superuser
104+
verify(spyAuthorizationService).isSuperUser(any(), any());
105+
106+
// ---- test nobody
107+
Assert.assertThrows(PulsarAdminException.NotAuthorizedException.class, () -> nobodyAdmin.tenants().getTenants());
108+
}
109+
110+
111+
@Test
112+
public void testGetTenant() throws PulsarAdminException {
113+
String tenantName = "public";
114+
superUserAdmin.tenants().getTenantInfo(tenantName);
115+
// test allow broker operation
116+
verify(spyAuthorizationService)
117+
.allowTenantOperationAsync(eq(tenantName), Mockito.eq(TenantOperation.GET_TENANT), any(), any());
118+
// fallback to superuser
119+
verify(spyAuthorizationService).isSuperUser(any(), any());
120+
121+
// ---- test nobody
122+
Assert.assertThrows(PulsarAdminException.NotAuthorizedException.class, () -> nobodyAdmin.tenants().getTenantInfo(tenantName));
123+
}
124+
125+
@Test
126+
public void testUpdateTenant() throws PulsarAdminException {
127+
String tenantName = "public";
128+
superUserAdmin.tenants().updateTenant(tenantName, TenantInfo.builder()
129+
.allowedClusters(Set.of(getPulsarService().getConfiguration().getClusterName()))
130+
.adminRoles(Set.of("example")).build());
131+
// test allow broker operation
132+
verify(spyAuthorizationService)
133+
.allowTenantOperationAsync(eq(tenantName), Mockito.eq(TenantOperation.UPDATE_TENANT), any(), any());
134+
// fallback to superuser
135+
verify(spyAuthorizationService).isSuperUser(any(), any());
136+
137+
// ---- test nobody
138+
Assert.assertThrows(PulsarAdminException.NotAuthorizedException.class, () -> nobodyAdmin.tenants()
139+
.updateTenant(tenantName, TenantInfo.builder().adminRoles(Set.of("example")).build()));
140+
}
141+
142+
@Test
143+
public void testDeleteTenant() throws PulsarAdminException {
144+
String tenantName = UUID.randomUUID().toString();
145+
superUserAdmin.tenants().createTenant(tenantName, TenantInfo.builder()
146+
.allowedClusters(Set.of(getPulsarService().getConfiguration().getClusterName()))
147+
.adminRoles(Set.of("example")).build());
148+
149+
Mockito.clearInvocations(spyAuthorizationService);
150+
superUserAdmin.tenants().deleteTenant(tenantName);
151+
// test allow broker operation
152+
verify(spyAuthorizationService)
153+
.allowTenantOperationAsync(eq(tenantName), Mockito.eq(TenantOperation.DELETE_TENANT), any(), any());
154+
// fallback to superuser
155+
verify(spyAuthorizationService).isSuperUser(any(), any());
156+
157+
// ---- test nobody
158+
Assert.assertThrows(PulsarAdminException.NotAuthorizedException.class, () -> nobodyAdmin.tenants().deleteTenant(tenantName));
159+
}
160+
}

pulsar-common/src/main/java/org/apache/pulsar/common/policies/data/TenantOperation.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,10 @@ public enum TenantOperation {
2525
CREATE_NAMESPACE,
2626
DELETE_NAMESPACE,
2727
LIST_NAMESPACES,
28+
29+
LIST_TENANTS,
30+
GET_TENANT,
31+
CREATE_TENANT,
32+
UPDATE_TENANT,
33+
DELETE_TENANT,
2834
}

0 commit comments

Comments
 (0)