You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by xy...@apache.org on 2022/07/28 08:39:30 UTC
[pulsar] branch branch-2.8 updated (a3515aba8d0 -> a7d22cabab2)
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a change to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
from a3515aba8d0 [fix][broker][branch-2.8] Fix potential to add duplicated consumer (#16826)
new a5692a6a685 fix: NamespacesTest execution order (#14552)
new bdd65f510ed [fix][branch-2.9] Fix wrong unit of NIC speed on linux (#15770)
new 969871d6727 [Authorization] Optimize the logic of allowing namespace operation (#13090)
new c0999e51125 [Authorization] Role with namespace produce authz can also get topics (#13773)
new 556e4e03a2f Fix wrong prompt exception when get non-persistent topic list without GET_BUDNLE permission (#14638)
new 428f453fc28 [pulsar-admin] Add corresponding get command for namespace (#12322)
new 42704c6c588 [fix][broker] Fix NPE when set `AutoTopicCreationOverride` (#15653)
new e3ac4fb8d3d Fix grant all permissions but can't list topic. (#15501)
new a7d22cabab2 [fix][tests] TieredStorageConfigurationTests - clear system properties (#15957)
The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../authorization/PulsarAuthorizationProvider.java | 159 ++++++++++++-------
.../pulsar/broker/admin/impl/NamespacesBase.java | 33 +++-
.../apache/pulsar/broker/admin/v1/Namespaces.java | 65 ++++++++
.../broker/admin/v1/NonPersistentTopics.java | 25 ++-
.../apache/pulsar/broker/admin/v2/Namespaces.java | 59 +++++++
.../broker/admin/v2/NonPersistentTopics.java | 31 ++--
.../loadbalance/impl/LinuxBrokerHostUsageImpl.java | 8 +-
.../apache/pulsar/broker/admin/AdminApi2Test.java | 44 ++++++
.../apache/pulsar/broker/admin/NamespacesTest.java | 2 +-
.../pulsar/broker/auth/AuthorizationTest.java | 33 +++-
.../loadbalance/LoadReportNetworkLimitTest.java | 4 +-
.../BrokerServiceAutoSubscriptionCreationTest.java | 19 ++-
.../BrokerServiceAutoTopicCreationTest.java | 37 +++--
.../api/AuthorizationProducerConsumerTest.java | 13 ++
.../org/apache/pulsar/client/admin/Namespaces.java | 81 ++++++++++
.../client/admin/internal/NamespacesImpl.java | 170 +++++++++++++++++++++
.../pulsar/admin/cli/PulsarAdminToolTest.java | 6 +
.../org/apache/pulsar/admin/cli/CmdNamespaces.java | 65 ++++++++
.../provider/TieredStorageConfigurationTests.java | 42 ++---
19 files changed, 758 insertions(+), 138 deletions(-)
[pulsar] 08/09: Fix grant all permissions but can't list topic. (#15501)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit e3ac4fb8d3d251643295cdea09109e6e7be97abe
Author: Jiwei Guo <te...@apache.org>
AuthorDate: Mon May 9 22:05:07 2022 +0800
Fix grant all permissions but can't list topic. (#15501)
(cherry picked from commit 5155b1df876bd98d173e87753cca642b82b6595a)
---
.../authorization/PulsarAuthorizationProvider.java | 2 +-
.../apache/pulsar/broker/auth/AuthorizationTest.java | 18 +++---------------
2 files changed, 4 insertions(+), 16 deletions(-)
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
index d7e8ac98efd..527201ae0cf 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
@@ -584,6 +584,7 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
namespaceName, role, authData, AuthAction.packages);
case GET_TOPIC:
case GET_TOPICS:
+ case GET_BUNDLE:
return allowConsumeOrProduceOpsAsync(namespaceName, role, authData);
case UNSUBSCRIBE:
case CLEAR_BACKLOG:
@@ -592,7 +593,6 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
case CREATE_TOPIC:
case DELETE_TOPIC:
case ADD_BUNDLE:
- case GET_BUNDLE:
case DELETE_BUNDLE:
case GRANT_PERMISSION:
case GET_PERMISSION:
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
index 4b18791fce0..2596d243a9f 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
@@ -19,7 +19,6 @@
package org.apache.pulsar.broker.auth;
import static org.mockito.Mockito.when;
-import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@@ -27,7 +26,6 @@ import java.util.EnumSet;
import org.apache.pulsar.broker.authorization.AuthorizationService;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminBuilder;
-import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AuthAction;
@@ -233,7 +231,7 @@ public class AuthorizationTest extends MockedPulsarServiceBaseTest {
}
@Test
- public void testGetListWithoutGetBundleOp() throws Exception {
+ public void testGetListWithGetBundleOp() throws Exception {
String tenant = "p1";
String namespaceV1 = "p1/global/ns1";
String namespaceV2 = "p1/ns2";
@@ -249,18 +247,8 @@ public class AuthorizationTest extends MockedPulsarServiceBaseTest {
.authentication(new MockAuthentication("pass.pass2"))
.build();
when(pulsar.getAdminClient()).thenReturn(admin2);
- try {
- admin2.topics().getList(namespaceV1, TopicDomain.non_persistent);
- } catch (Exception ex) {
- assertTrue(ex instanceof PulsarAdminException.NotAuthorizedException);
- assertEquals(ex.getMessage(), "Unauthorized to validateNamespaceOperation for operation [GET_BUNDLE] on namespace [p1/global/ns1]");
- }
- try {
- admin2.topics().getList(namespaceV2, TopicDomain.non_persistent);
- } catch (Exception ex) {
- assertTrue(ex instanceof PulsarAdminException.NotAuthorizedException);
- assertEquals(ex.getMessage(), "Unauthorized to validateNamespaceOperation for operation [GET_BUNDLE] on namespace [p1/ns2]");
- }
+ Assert.assertEquals(admin2.topics().getList(namespaceV1, TopicDomain.non_persistent).size(), 0);
+ Assert.assertEquals(admin2.topics().getList(namespaceV2, TopicDomain.non_persistent).size(), 0);
}
private static void waitForChange() {
[pulsar] 04/09: [Authorization] Role with namespace produce authz can also get topics (#13773)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit c0999e51125e260d3d24d44ad75373b781b67f4a
Author: Ruguo Yu <ji...@163.com>
AuthorDate: Wed Mar 2 16:57:11 2022 +0800
[Authorization] Role with namespace produce authz can also get topics (#13773)
(cherry picked from commit 89d60af1981f732b68fe783666bcc470c18afd32)
---
.../authorization/PulsarAuthorizationProvider.java | 35 ++++++++++++++++++++++
.../api/AuthorizationProducerConsumerTest.java | 6 ++++
2 files changed, 41 insertions(+)
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
index aab4b2b5ac1..d7e8ac98efd 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
@@ -230,6 +230,40 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
return allowTheSpecifiedActionOpsAsync(namespaceName, role, authenticationData, AuthAction.sinks);
}
+ private CompletableFuture<Boolean> allowConsumeOrProduceOpsAsync(NamespaceName namespaceName,
+ String role,
+ AuthenticationDataSource authenticationData) {
+ CompletableFuture<Boolean> finalResult = new CompletableFuture<>();
+ allowTheSpecifiedActionOpsAsync(namespaceName, role, authenticationData, AuthAction.consume)
+ .whenComplete((consumeAuthorized, e) -> {
+ if (e == null) {
+ if (consumeAuthorized) {
+ finalResult.complete(consumeAuthorized);
+ return;
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Namespace [{}] Role [{}] exception occurred while trying to check Consume "
+ + "permission. {}", namespaceName, role, e.getCause());
+ }
+ }
+ allowTheSpecifiedActionOpsAsync(namespaceName, role, authenticationData, AuthAction.produce)
+ .whenComplete((produceAuthorized, ex) -> {
+ if (ex == null) {
+ finalResult.complete(produceAuthorized);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Namespace [{}] Role [{}] exception occurred while trying to check "
+ + "Produce permission. {}", namespaceName, role, ex.getCause());
+ }
+ finalResult.completeExceptionally(ex.getCause());
+ }
+ });
+ });
+
+ return finalResult;
+ }
+
private CompletableFuture<Boolean> allowTheSpecifiedActionOpsAsync(NamespaceName namespaceName, String role,
AuthenticationDataSource authenticationData,
AuthAction authAction) {
@@ -550,6 +584,7 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
namespaceName, role, authData, AuthAction.packages);
case GET_TOPIC:
case GET_TOPICS:
+ return allowConsumeOrProduceOpsAsync(namespaceName, role, authData);
case UNSUBSCRIBE:
case CLEAR_BACKLOG:
return allowTheSpecifiedActionOpsAsync(
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
index 475dc8d1ab8..31b2451575d 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
@@ -415,6 +415,12 @@ public class AuthorizationProducerConsumerTest extends ProducerConsumerBase {
assertEquals(sub1Admin.topics().getStats(topicName + "-partition-0").getSubscriptions()
.get(subscriptionName).getMsgBacklog(), 0);
+ superAdmin.namespaces().revokePermissionsOnNamespace(namespace, subscriptionRole);
+ superAdmin.namespaces().grantPermissionOnNamespace(namespace, subscriptionRole,
+ Sets.newHashSet(AuthAction.produce));
+ assertEquals(sub1Admin.topics().getPartitionedTopicList(namespace),
+ Lists.newArrayList(topicName));
+
log.info("-- Exiting {} test --", methodName);
}
[pulsar] 06/09: [pulsar-admin] Add corresponding get command for namespace (#12322)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 428f453fc285a2da3178bd82ba7456832ffb1678
Author: Ruguo Yu <ji...@163.com>
AuthorDate: Mon Nov 8 19:13:02 2021 +0800
[pulsar-admin] Add corresponding get command for namespace (#12322)
### Motivation
CLI `./bin/pulsar-admin` provides many `set` commands for namespace and also provides corresponding `get` commands, but I found that the following `set` commands lack corresponding `get` commands.
- [grant-subscription-permission](https://pulsar.apache.org/tools/pulsar-admin/2.9.0-SNAPSHOT/#-em-grant-subscription-permission-em-)
- [set-auto-topic-creation](https://pulsar.apache.org/tools/pulsar-admin/2.9.0-SNAPSHOT/#-em-set-auto-topic-creation-em-)
- [set-auto-subscription-creation](https://pulsar.apache.org/tools/pulsar-admin/2.9.0-SNAPSHOT/#-em-set-auto-subscription-creation-em-)
- [set-encryption-required](https://pulsar.apache.org/tools/pulsar-admin/2.9.0-SNAPSHOT/#-em-set-encryption-required-em-)
- [set-subscription-auth-mode](https://pulsar.apache.org/tools/pulsar-admin/2.9.0-SNAPSHOT/#-em-set-subscription-auth-mode-em-)
The purpose of this PR is to supplement these `get` commands, as follow:
- subscription-permission
- get-auto-topic-creation
- get-auto-subscription-creation
- get-encryption-required
- get-subscription-auth-mode
(cherry picked from commit d055ebd1186ffae2d2af1382e05b21c60e9f9574)
---
.../pulsar/broker/admin/impl/NamespacesBase.java | 24 +++
.../apache/pulsar/broker/admin/v1/Namespaces.java | 65 ++++++++
.../apache/pulsar/broker/admin/v2/Namespaces.java | 59 +++++++
.../pulsar/broker/auth/AuthorizationTest.java | 6 +
.../BrokerServiceAutoSubscriptionCreationTest.java | 19 ++-
.../BrokerServiceAutoTopicCreationTest.java | 37 +++--
.../api/AuthorizationProducerConsumerTest.java | 7 +
.../org/apache/pulsar/client/admin/Namespaces.java | 81 ++++++++++
.../client/admin/internal/NamespacesImpl.java | 170 +++++++++++++++++++++
.../pulsar/admin/cli/PulsarAdminToolTest.java | 6 +
.../org/apache/pulsar/admin/cli/CmdNamespaces.java | 65 ++++++++
11 files changed, 518 insertions(+), 21 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
index e04b5bc0069..7c581b2cf83 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
@@ -814,6 +814,12 @@ public abstract class NamespacesBase extends AdminResource {
});
}
+ protected AutoTopicCreationOverride internalGetAutoTopicCreation() {
+ validateNamespacePolicyOperation(namespaceName, PolicyName.AUTO_TOPIC_CREATION, PolicyOperation.READ);
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.autoTopicCreationOverride;
+ }
+
protected void internalSetAutoTopicCreation(AsyncResponse asyncResponse,
AutoTopicCreationOverride autoTopicCreationOverride) {
final int maxPartitions = pulsar().getConfig().getMaxNumPartitionsPerPartitionedTopic();
@@ -888,6 +894,12 @@ public abstract class NamespacesBase extends AdminResource {
});
}
+ protected AutoSubscriptionCreationOverride internalGetAutoSubscriptionCreation() {
+ validateNamespacePolicyOperation(namespaceName, PolicyName.AUTO_SUBSCRIPTION_CREATION, PolicyOperation.READ);
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.autoSubscriptionCreationOverride;
+ }
+
protected void internalRemoveAutoSubscriptionCreation(AsyncResponse asyncResponse) {
internalSetAutoSubscriptionCreation(asyncResponse, null);
}
@@ -1715,6 +1727,12 @@ public abstract class NamespacesBase extends AdminResource {
}
}
+ protected SubscriptionAuthMode internalGetSubscriptionAuthMode() {
+ validateNamespacePolicyOperation(namespaceName, PolicyName.SUBSCRIPTION_AUTH_MODE, PolicyOperation.READ);
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.subscription_auth_mode;
+ }
+
protected void internalModifyEncryptionRequired(boolean encryptionRequired) {
validateNamespacePolicyOperation(namespaceName, PolicyName.ENCRYPTION, PolicyOperation.WRITE);
validatePoliciesReadOnlyAccess();
@@ -1733,6 +1751,12 @@ public abstract class NamespacesBase extends AdminResource {
}
}
+ protected Boolean internalGetEncryptionRequired() {
+ validateNamespacePolicyOperation(namespaceName, PolicyName.ENCRYPTION, PolicyOperation.READ);
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.encryption_required;
+ }
+
protected DelayedDeliveryPolicies internalGetDelayedDelivery() {
validateNamespacePolicyOperation(namespaceName, PolicyName.DELAYED_DELIVERY, PolicyOperation.READ);
return getNamespacePolicies(namespaceName).delayed_delivery_policies;
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/Namespaces.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/Namespaces.java
index 9fec59cd4b6..9130245a23f 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/Namespaces.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/Namespaces.java
@@ -245,6 +245,22 @@ public class Namespaces extends NamespacesBase {
return policies.auth_policies.getNamespaceAuthentication();
}
+ @GET
+ @Path("/{property}/{cluster}/{namespace}/permissions/subscription")
+ @ApiOperation(value = "Retrieve the permissions for a subscription.")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Property or cluster or namespace doesn't exist"),
+ @ApiResponse(code = 409, message = "Namespace is not empty")})
+ public Map<String, Set<String>> getPermissionOnSubscription(@PathParam("property") String property,
+ @PathParam("cluster") String cluster,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(property, cluster, namespace);
+ validateNamespaceOperation(NamespaceName.get(property, namespace), NamespaceOperation.GET_PERMISSION);
+
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.auth_policies.getSubscriptionAuthentication();
+ }
+
@POST
@Path("/{property}/{cluster}/{namespace}/permissions/{role}")
@ApiOperation(hidden = true, value = "Grant a new permission to a role on a namespace.")
@@ -449,6 +465,18 @@ public class Namespaces extends NamespacesBase {
internalModifyDeduplication(enableDeduplication);
}
+ @GET
+ @Path("/{property}/{cluster}/{namespace}/autoTopicCreation")
+ @ApiOperation(value = "Get autoTopicCreation info in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or cluster or namespace doesn't exist")})
+ public AutoTopicCreationOverride getAutoTopicCreation(@PathParam("property") String property,
+ @PathParam("cluster") String cluster,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(property, cluster, namespace);
+ return internalGetAutoTopicCreation();
+ }
+
@POST
@Path("/{property}/{cluster}/{namespace}/autoTopicCreation")
@ApiOperation(value = "Override broker's allowAutoTopicCreation setting for a namespace")
@@ -510,6 +538,18 @@ public class Namespaces extends NamespacesBase {
}
}
+ @GET
+ @Path("/{property}/{cluster}/{namespace}/autoSubscriptionCreation")
+ @ApiOperation(value = "Get autoSubscriptionCreation info in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Property or cluster or namespace doesn't exist")})
+ public AutoSubscriptionCreationOverride getAutoSubscriptionCreation(@PathParam("property") String property,
+ @PathParam("cluster") String cluster,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(property, cluster, namespace);
+ return internalGetAutoSubscriptionCreation();
+ }
+
@DELETE
@Path("/{property}/{cluster}/{namespace}/autoSubscriptionCreation")
@ApiOperation(value = "Remove override of broker's allowAutoSubscriptionCreation in a namespace")
@@ -958,6 +998,18 @@ public class Namespaces extends NamespacesBase {
internalSetSubscriptionAuthMode(subscriptionAuthMode);
}
+ @GET
+ @Path("/{property}/{cluster}/{namespace}/subscriptionAuthMode")
+ @ApiOperation(value = "Get subscription auth mode in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Property or cluster or namespace doesn't exist")})
+ public SubscriptionAuthMode getSubscriptionAuthMode(@PathParam("property") String property,
+ @PathParam("cluster") String cluster,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(property, cluster, namespace);
+ return internalGetSubscriptionAuthMode();
+ }
+
@POST
@Path("/{property}/{cluster}/{namespace}/encryptionRequired")
@ApiOperation(hidden = true, value = "Message encryption is required or not for all topics in a namespace")
@@ -970,6 +1022,19 @@ public class Namespaces extends NamespacesBase {
internalModifyEncryptionRequired(encryptionRequired);
}
+ @GET
+ @Path("/{property}/{cluster}/{namespace}/encryptionRequired")
+ @ApiOperation(value = "Get message encryption required status in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Property or cluster or namespace doesn't exist")})
+ public Boolean getEncryptionRequired(@PathParam("property") String property,
+ @PathParam("cluster") String cluster,
+ @PathParam("namespace") String namespace) {
+ validateAdminAccessForTenant(property);
+ validateNamespaceName(property, cluster, namespace);
+ return internalGetEncryptionRequired();
+ }
+
@GET
@Path("/{property}/{cluster}/{namespace}/maxProducersPerTopic")
@ApiOperation(value = "Get maxProducersPerTopic config on a namespace.")
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Namespaces.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Namespaces.java
index 76e543001f2..ef16d1ca640 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Namespaces.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Namespaces.java
@@ -192,6 +192,21 @@ public class Namespaces extends NamespacesBase {
return policies.auth_policies.getNamespaceAuthentication();
}
+ @GET
+ @Path("/{tenant}/{namespace}/permissions/subscription")
+ @ApiOperation(value = "Retrieve the permissions for a subscription.")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or cluster or namespace doesn't exist"),
+ @ApiResponse(code = 409, message = "Namespace is not empty")})
+ public Map<String, Set<String>> getPermissionOnSubscription(@PathParam("tenant") String tenant,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(tenant, namespace);
+ validateNamespaceOperation(NamespaceName.get(tenant, namespace), NamespaceOperation.GET_PERMISSION);
+
+ Policies policies = getNamespacePolicies(namespaceName);
+ return policies.auth_policies.getSubscriptionAuthentication();
+ }
+
@POST
@Path("/{tenant}/{namespace}/permissions/{role}")
@ApiOperation(value = "Grant a new permission to a role on a namespace.")
@@ -382,6 +397,17 @@ public class Namespaces extends NamespacesBase {
internalModifyDeduplication(null);
}
+ @GET
+ @Path("/{tenant}/{namespace}/autoTopicCreation")
+ @ApiOperation(value = "Get autoTopicCreation info in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or namespace doesn't exist")})
+ public AutoTopicCreationOverride getAutoTopicCreation(@PathParam("tenant") String tenant,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(tenant, namespace);
+ return internalGetAutoTopicCreation();
+ }
+
@POST
@Path("/{tenant}/{namespace}/autoTopicCreation")
@ApiOperation(value = "Override broker's allowAutoTopicCreation setting for a namespace")
@@ -443,6 +469,17 @@ public class Namespaces extends NamespacesBase {
}
}
+ @GET
+ @Path("/{tenant}/{namespace}/autoSubscriptionCreation")
+ @ApiOperation(value = "Get autoSubscriptionCreation info in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or namespace doesn't exist")})
+ public AutoSubscriptionCreationOverride getAutoSubscriptionCreation(@PathParam("tenant") String tenant,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(tenant, namespace);
+ return internalGetAutoSubscriptionCreation();
+ }
+
@DELETE
@Path("/{tenant}/{namespace}/autoSubscriptionCreation")
@ApiOperation(value = "Remove override of broker's allowAutoSubscriptionCreation in a namespace")
@@ -977,6 +1014,17 @@ public class Namespaces extends NamespacesBase {
internalSetSubscriptionAuthMode(subscriptionAuthMode);
}
+ @GET
+ @Path("/{tenant}/{namespace}/subscriptionAuthMode")
+ @ApiOperation(value = "Get subscription auth mode in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or namespace doesn't exist")})
+ public SubscriptionAuthMode getSubscriptionAuthMode(@PathParam("tenant") String tenant,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(tenant, namespace);
+ return internalGetSubscriptionAuthMode();
+ }
+
@POST
@Path("/{tenant}/{namespace}/encryptionRequired")
@ApiOperation(value = "Message encryption is required or not for all topics in a namespace")
@@ -992,6 +1040,17 @@ public class Namespaces extends NamespacesBase {
internalModifyEncryptionRequired(encryptionRequired);
}
+ @GET
+ @Path("/{tenant}/{namespace}/encryptionRequired")
+ @ApiOperation(value = "Get message encryption required status in a namespace")
+ @ApiResponses(value = {@ApiResponse(code = 403, message = "Don't have admin permission"),
+ @ApiResponse(code = 404, message = "Tenant or namespace doesn't exist")})
+ public Boolean getEncryptionRequired(@PathParam("tenant") String tenant,
+ @PathParam("namespace") String namespace) {
+ validateNamespaceName(tenant, namespace);
+ return internalGetEncryptionRequired();
+ }
+
@GET
@Path("/{tenant}/{namespace}/delayedDelivery")
@ApiOperation(value = "Get delayed delivery messages config on a namespace.")
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
index 7bbbc9072f3..4b18791fce0 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
@@ -35,6 +35,7 @@ import org.apache.pulsar.common.policies.data.ClusterData;
import org.apache.pulsar.common.policies.data.ClusterDataImpl;
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
import org.apache.pulsar.common.policies.data.SubscriptionAuthMode;
+import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -203,7 +204,12 @@ public class AuthorizationTest extends MockedPulsarServiceBaseTest {
// tests for subscription auth mode
admin.namespaces().grantPermissionOnNamespace("p1/c1/ns1", "*", EnumSet.of(AuthAction.consume));
+ admin.namespaces().setSubscriptionAuthMode("p1/c1/ns1", SubscriptionAuthMode.None);
+ Assert.assertEquals(admin.namespaces().getSubscriptionAuthMode("p1/c1/ns1"),
+ SubscriptionAuthMode.None);
admin.namespaces().setSubscriptionAuthMode("p1/c1/ns1", SubscriptionAuthMode.Prefix);
+ Assert.assertEquals(admin.namespaces().getSubscriptionAuthMode("p1/c1/ns1"),
+ SubscriptionAuthMode.Prefix);
waitForChange();
assertTrue(auth.canLookup(TopicName.get("persistent://p1/c1/ns1/ds1"), "role1", null));
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoSubscriptionCreationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoSubscriptionCreationTest.java
index 81f9521bbff..dc4b3d9d51d 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoSubscriptionCreationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoSubscriptionCreationTest.java
@@ -26,6 +26,7 @@ import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AutoSubscriptionCreationOverride;
+import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
@@ -98,10 +99,13 @@ public class BrokerServiceAutoSubscriptionCreationTest extends BrokerTestBase {
admin.topics().createNonPartitionedTopic(topicName.toString());
pulsar.getConfiguration().setAllowAutoSubscriptionCreation(false);
+ AutoSubscriptionCreationOverride autoSubscriptionCreationOverride = AutoSubscriptionCreationOverride.builder()
+ .allowAutoSubscriptionCreation(true)
+ .build();
pulsar.getAdminClient().namespaces().setAutoSubscriptionCreation(topicName.getNamespace(),
- AutoSubscriptionCreationOverride.builder()
- .allowAutoSubscriptionCreation(true)
- .build());
+ autoSubscriptionCreationOverride);
+ Assert.assertEquals(pulsar.getAdminClient().namespaces().getAutoSubscriptionCreation(topicName.getNamespace()),
+ autoSubscriptionCreationOverride);
// Subscribe operation should be successful
pulsarClient.newConsumer().topic(topicName.toString()).subscriptionName(subscriptionName).subscribe();
@@ -117,10 +121,13 @@ public class BrokerServiceAutoSubscriptionCreationTest extends BrokerTestBase {
admin.topics().createNonPartitionedTopic(topicName.toString());
pulsar.getConfiguration().setAllowAutoSubscriptionCreation(true);
+ AutoSubscriptionCreationOverride autoSubscriptionCreationOverride = AutoSubscriptionCreationOverride.builder()
+ .allowAutoSubscriptionCreation(false)
+ .build();
pulsar.getAdminClient().namespaces().setAutoSubscriptionCreation(topicName.getNamespace(),
- AutoSubscriptionCreationOverride.builder()
- .allowAutoSubscriptionCreation(false)
- .build());
+ autoSubscriptionCreationOverride);
+ Assert.assertEquals(pulsar.getAdminClient().namespaces().getAutoSubscriptionCreation(topicName.getNamespace()),
+ autoSubscriptionCreationOverride);
try {
pulsarClient.newConsumer().topic(topicName.toString()).subscriptionName(subscriptionName).subscribe();
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
index 33ed35636db..1b3ca1616fa 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BrokerServiceAutoTopicCreationTest.java
@@ -29,6 +29,7 @@ import org.apache.pulsar.common.events.EventsTopicNames;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AutoTopicCreationOverride;
import org.apache.pulsar.common.policies.data.TopicType;
+import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
@@ -168,11 +169,13 @@ public class BrokerServiceAutoTopicCreationTest extends BrokerTestBase{
final String subscriptionName = "test-topic-sub-4";
final TopicName topicName = TopicName.get(topicString);
pulsar.getConfiguration().setAllowAutoTopicCreation(false);
- pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(),
- AutoTopicCreationOverride.builder()
- .allowAutoTopicCreation(true)
- .topicType(TopicType.NON_PARTITIONED.toString())
- .build());
+ AutoTopicCreationOverride autoTopicCreationOverride = AutoTopicCreationOverride.builder()
+ .allowAutoTopicCreation(true)
+ .topicType(TopicType.NON_PARTITIONED.toString())
+ .build();
+ pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), autoTopicCreationOverride);
+ Assert.assertEquals(pulsar.getAdminClient().namespaces().getAutoTopicCreation(topicName.getNamespace()),
+ autoTopicCreationOverride);
pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe();
assertTrue(admin.namespaces().getTopics("prop/ns-abc").contains(topicString));
@@ -185,10 +188,12 @@ public class BrokerServiceAutoTopicCreationTest extends BrokerTestBase{
final String subscriptionName = "test-topic-sub-5";
final TopicName topicName = TopicName.get(topicString);
pulsar.getConfiguration().setAllowAutoTopicCreation(true);
- pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(),
- AutoTopicCreationOverride.builder()
- .allowAutoTopicCreation(false)
- .build());
+ AutoTopicCreationOverride autoTopicCreationOverride = AutoTopicCreationOverride.builder()
+ .allowAutoTopicCreation(false)
+ .build();
+ pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), autoTopicCreationOverride);
+ Assert.assertEquals(pulsar.getAdminClient().namespaces().getAutoTopicCreation(topicName.getNamespace()),
+ autoTopicCreationOverride);
try {
pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe();
@@ -205,12 +210,14 @@ public class BrokerServiceAutoTopicCreationTest extends BrokerTestBase{
final TopicName topicName = TopicName.get(topicString);
pulsar.getConfiguration().setAllowAutoTopicCreation(false);
- pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(),
- AutoTopicCreationOverride.builder()
- .allowAutoTopicCreation(true)
- .topicType(TopicType.PARTITIONED.toString())
- .defaultNumPartitions(4)
- .build());
+ AutoTopicCreationOverride autoTopicCreationOverride = AutoTopicCreationOverride.builder()
+ .allowAutoTopicCreation(true)
+ .topicType(TopicType.PARTITIONED.toString())
+ .defaultNumPartitions(4)
+ .build();
+ pulsar.getAdminClient().namespaces().setAutoTopicCreation(topicName.getNamespace(), autoTopicCreationOverride);
+ Assert.assertEquals(pulsar.getAdminClient().namespaces().getAutoTopicCreation(topicName.getNamespace()),
+ autoTopicCreationOverride);
final String subscriptionName = "test-topic-sub-6";
pulsarClient.newConsumer().topic(topicString).subscriptionName(subscriptionName).subscribe();
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
index 31b2451575d..a899b314357 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/AuthorizationProducerConsumerTest.java
@@ -34,6 +34,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -281,6 +282,9 @@ public class AuthorizationProducerConsumerTest extends ProducerConsumerBase {
String otherPrincipal = "Principal-1-to-access-sub";
tenantAdmin.namespaces().grantPermissionOnSubscription(namespace, subscriptionName,
Collections.singleton(otherPrincipal));
+ TreeMap<String, Set<String>> permissionOnSubscription = new TreeMap<>();
+ permissionOnSubscription.put(subscriptionName, Collections.singleton(otherPrincipal));
+ Assert.assertEquals(tenantAdmin.namespaces().getPermissionOnSubscription(namespace), permissionOnSubscription);
// now, subscriptionRole doesn't have subscription level access so, it will fail to access subscription
try {
@@ -301,6 +305,9 @@ public class AuthorizationProducerConsumerTest extends ProducerConsumerBase {
// now, grant subscription-access to subscriptionRole as well
superAdmin.namespaces().grantPermissionOnSubscription(namespace, subscriptionName,
Sets.newHashSet(otherPrincipal, subscriptionRole));
+ TreeMap<String, Set<String>> permissionOnSubscription1 = new TreeMap<>();
+ permissionOnSubscription1.put(subscriptionName, Sets.newHashSet(otherPrincipal, subscriptionRole));
+ Assert.assertEquals(tenantAdmin.namespaces().getPermissionOnSubscription(namespace), permissionOnSubscription1);
sub1Admin.topics().skipAllMessages(topicName, subscriptionName);
sub1Admin.topics().skipMessages(topicName, subscriptionName, 1);
diff --git a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/Namespaces.java b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/Namespaces.java
index 6ea4bab025c..fb1b67e7f1d 100644
--- a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/Namespaces.java
+++ b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/Namespaces.java
@@ -687,6 +687,19 @@ public interface Namespaces {
*/
CompletableFuture<Void> revokePermissionsOnNamespaceAsync(String namespace, String role);
+ /**
+ * Get permission to role to access subscription's admin-api.
+ * @param namespace
+ * @throws PulsarAdminException
+ */
+ Map<String, Set<String>> getPermissionOnSubscription(String namespace) throws PulsarAdminException;
+
+ /**
+ * Get permission to role to access subscription's admin-api asynchronously.
+ * @param namespace
+ */
+ CompletableFuture<Map<String, Set<String>>> getPermissionOnSubscriptionAsync(String namespace);
+
/**
* Grant permission to role to access subscription's admin-api.
* @param namespace
@@ -1237,6 +1250,23 @@ public interface Namespaces {
CompletableFuture<Void> setAutoTopicCreationAsync(
String namespace, AutoTopicCreationOverride autoTopicCreationOverride);
+ /**
+ * Get the autoTopicCreation info within a namespace.
+ *
+ * @param namespace
+ * @return
+ * @throws PulsarAdminException
+ */
+ AutoTopicCreationOverride getAutoTopicCreation(String namespace) throws PulsarAdminException;
+
+ /**
+ * Get the autoTopicCreation info within a namespace asynchronously.
+ *
+ * @param namespace
+ * @return
+ */
+ CompletableFuture<AutoTopicCreationOverride> getAutoTopicCreationAsync(String namespace);
+
/**
* Removes the autoTopicCreation policy for a given namespace.
* <p/>
@@ -1322,6 +1352,23 @@ public interface Namespaces {
CompletableFuture<Void> setAutoSubscriptionCreationAsync(
String namespace, AutoSubscriptionCreationOverride autoSubscriptionCreationOverride);
+ /**
+ * Get the autoSubscriptionCreation info within a namespace.
+ *
+ * @param namespace
+ * @return
+ * @throws PulsarAdminException
+ */
+ AutoSubscriptionCreationOverride getAutoSubscriptionCreation(String namespace) throws PulsarAdminException;
+
+ /**
+ * Get the autoSubscriptionCreation info within a namespace asynchronously.
+ *
+ * @param namespace
+ * @return
+ */
+ CompletableFuture<AutoSubscriptionCreationOverride> getAutoSubscriptionCreationAsync(String namespace);
+
/**
* Sets the subscriptionTypesEnabled policy for a given namespace, overriding broker settings.
*
@@ -2438,6 +2485,23 @@ public interface Namespaces {
*/
void setEncryptionRequiredStatus(String namespace, boolean encryptionRequired) throws PulsarAdminException;
+ /**
+ * Get the encryption required status within a namespace.
+ *
+ * @param namespace
+ * @return
+ * @throws PulsarAdminException
+ */
+ Boolean getEncryptionRequiredStatus(String namespace) throws PulsarAdminException;
+
+ /**
+ * Get the encryption required status within a namespace asynchronously.
+ *
+ * @param namespace
+ * @return
+ */
+ CompletableFuture<Boolean> getEncryptionRequiredStatusAsync(String namespace);
+
/**
* Set the encryption required status for all topics within a namespace asynchronously.
* <p/>
@@ -2646,6 +2710,23 @@ public interface Namespaces {
*/
CompletableFuture<Void> setSubscriptionAuthModeAsync(String namespace, SubscriptionAuthMode subscriptionAuthMode);
+ /**
+ * Get the subscriptionAuthMode within a namespace.
+ *
+ * @param namespace
+ * @return
+ * @throws PulsarAdminException
+ */
+ SubscriptionAuthMode getSubscriptionAuthMode(String namespace) throws PulsarAdminException;
+
+ /**
+ * Get the subscriptionAuthMode within a namespace asynchronously.
+ *
+ * @param namespace
+ * @return
+ */
+ CompletableFuture<SubscriptionAuthMode> getSubscriptionAuthModeAsync(String namespace);
+
/**
* Get the deduplicationSnapshotInterval for a namespace.
*
diff --git a/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/NamespacesImpl.java b/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/NamespacesImpl.java
index 6a489f9bcd3..1d59d4c9c20 100644
--- a/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/NamespacesImpl.java
+++ b/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/NamespacesImpl.java
@@ -513,6 +513,39 @@ public class NamespacesImpl extends BaseResource implements Namespaces {
return asyncDeleteRequest(path);
}
+ @Override
+ public Map<String, Set<String>> getPermissionOnSubscription(String namespace) throws PulsarAdminException {
+ try {
+ return getPermissionOnSubscriptionAsync(namespace).get(this.readTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ throw (PulsarAdminException) e.getCause();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new PulsarAdminException(e);
+ } catch (TimeoutException e) {
+ throw new PulsarAdminException.TimeoutException(e);
+ }
+ }
+
+ @Override
+ public CompletableFuture<Map<String, Set<String>>> getPermissionOnSubscriptionAsync(String namespace) {
+ NamespaceName ns = NamespaceName.get(namespace);
+ WebTarget path = namespacePath(ns, "permissions", "subscription");
+ final CompletableFuture<Map<String, Set<String>>> future = new CompletableFuture<>();
+ asyncGetRequest(path,
+ new InvocationCallback<Map<String, Set<String>>>() {
+ @Override
+ public void completed(Map<String, Set<String>> permissions) {
+ future.complete(permissions);
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ future.completeExceptionally(getApiException(throwable.getCause()));
+ }
+ });
+ return future;
+ }
@Override
public void grantPermissionOnSubscription(String namespace, String subscription, Set<String> roles)
@@ -995,6 +1028,40 @@ public class NamespacesImpl extends BaseResource implements Namespaces {
return asyncPostRequest(path, Entity.entity(autoTopicCreationOverride, MediaType.APPLICATION_JSON));
}
+ @Override
+ public AutoTopicCreationOverride getAutoTopicCreation(String namespace) throws PulsarAdminException {
+ try {
+ return getAutoTopicCreationAsync(namespace).get(this.readTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ throw (PulsarAdminException) e.getCause();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new PulsarAdminException(e);
+ } catch (TimeoutException e) {
+ throw new PulsarAdminException.TimeoutException(e);
+ }
+ }
+
+ @Override
+ public CompletableFuture<AutoTopicCreationOverride> getAutoTopicCreationAsync(String namespace) {
+ NamespaceName ns = NamespaceName.get(namespace);
+ WebTarget path = namespacePath(ns, "autoTopicCreation");
+ final CompletableFuture<AutoTopicCreationOverride> future = new CompletableFuture<>();
+ asyncGetRequest(path,
+ new InvocationCallback<AutoTopicCreationOverride>() {
+ @Override
+ public void completed(AutoTopicCreationOverride autoTopicCreationOverride) {
+ future.complete(autoTopicCreationOverride);
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ future.completeExceptionally(getApiException(throwable.getCause()));
+ }
+ });
+ return future;
+ }
+
@Override
public void removeAutoTopicCreation(String namespace) throws PulsarAdminException {
try {
@@ -1040,6 +1107,41 @@ public class NamespacesImpl extends BaseResource implements Namespaces {
return asyncPostRequest(path, Entity.entity(autoSubscriptionCreationOverride, MediaType.APPLICATION_JSON));
}
+ @Override
+ public AutoSubscriptionCreationOverride getAutoSubscriptionCreation(String namespace) throws PulsarAdminException {
+ try {
+ return getAutoSubscriptionCreationAsync(namespace).get(this.readTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ throw (PulsarAdminException) e.getCause();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new PulsarAdminException(e);
+ } catch (TimeoutException e) {
+ throw new PulsarAdminException.TimeoutException(e);
+ }
+ }
+
+ @Override
+ public CompletableFuture<AutoSubscriptionCreationOverride> getAutoSubscriptionCreationAsync(String namespace) {
+ NamespaceName ns = NamespaceName.get(namespace);
+ WebTarget path = namespacePath(ns, "autoSubscriptionCreation");
+ final CompletableFuture<AutoSubscriptionCreationOverride> future = new CompletableFuture<>();
+ asyncGetRequest(path,
+ new InvocationCallback<AutoSubscriptionCreationOverride>() {
+ @Override
+ public void completed(AutoSubscriptionCreationOverride autoSubscriptionCreation) {
+ future.complete(autoSubscriptionCreation);
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ future.completeExceptionally(getApiException(throwable.getCause()));
+ }
+ });
+ return future;
+ }
+
+
@Override
public void setSubscriptionTypesEnabled(
String namespace, Set<SubscriptionType> subscriptionTypesEnabled) throws PulsarAdminException {
@@ -2105,6 +2207,40 @@ public class NamespacesImpl extends BaseResource implements Namespaces {
return asyncPostRequest(path, Entity.entity(subscriptionAuthMode, MediaType.APPLICATION_JSON));
}
+ @Override
+ public SubscriptionAuthMode getSubscriptionAuthMode(String namespace) throws PulsarAdminException {
+ try {
+ return getSubscriptionAuthModeAsync(namespace).get(this.readTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ throw (PulsarAdminException) e.getCause();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new PulsarAdminException(e);
+ } catch (TimeoutException e) {
+ throw new PulsarAdminException.TimeoutException(e);
+ }
+ }
+
+ @Override
+ public CompletableFuture<SubscriptionAuthMode> getSubscriptionAuthModeAsync(String namespace) {
+ NamespaceName ns = NamespaceName.get(namespace);
+ WebTarget path = namespacePath(ns, "subscriptionAuthMode");
+ final CompletableFuture<SubscriptionAuthMode> future = new CompletableFuture<>();
+ asyncGetRequest(path,
+ new InvocationCallback<SubscriptionAuthMode>() {
+ @Override
+ public void completed(SubscriptionAuthMode subscriptionAuthMode) {
+ future.complete(subscriptionAuthMode);
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ future.completeExceptionally(getApiException(throwable.getCause()));
+ }
+ });
+ return future;
+ }
+
@Override
public void setEncryptionRequiredStatus(String namespace, boolean encryptionRequired) throws PulsarAdminException {
try {
@@ -2127,6 +2263,40 @@ public class NamespacesImpl extends BaseResource implements Namespaces {
return asyncPostRequest(path, Entity.entity(encryptionRequired, MediaType.APPLICATION_JSON));
}
+ @Override
+ public Boolean getEncryptionRequiredStatus(String namespace) throws PulsarAdminException {
+ try {
+ return getEncryptionRequiredStatusAsync(namespace).get(this.readTimeoutMs, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ throw (PulsarAdminException) e.getCause();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new PulsarAdminException(e);
+ } catch (TimeoutException e) {
+ throw new PulsarAdminException.TimeoutException(e);
+ }
+ }
+
+ @Override
+ public CompletableFuture<Boolean> getEncryptionRequiredStatusAsync(String namespace) {
+ NamespaceName ns = NamespaceName.get(namespace);
+ WebTarget path = namespacePath(ns, "encryptionRequired");
+ final CompletableFuture<Boolean> future = new CompletableFuture<>();
+ asyncGetRequest(path,
+ new InvocationCallback<Boolean>() {
+ @Override
+ public void completed(Boolean enabled) {
+ future.complete(enabled);
+ }
+
+ @Override
+ public void failed(Throwable throwable) {
+ future.completeExceptionally(getApiException(throwable.getCause()));
+ }
+ });
+ return future;
+ }
+
@Override
public DelayedDeliveryPolicies getDelayedDelivery(String namespace) throws PulsarAdminException {
try {
diff --git a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
index 362e2308a60..792a85bb3d0 100644
--- a/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
+++ b/pulsar-client-tools-test/src/test/java/org/apache/pulsar/admin/cli/PulsarAdminToolTest.java
@@ -509,6 +509,9 @@ public class PulsarAdminToolTest {
.topicType(TopicType.NON_PARTITIONED.toString())
.build());
+ namespaces.run(split("get-auto-topic-creation myprop/clust/ns1"));
+ verify(mockNamespaces).getAutoTopicCreation("myprop/clust/ns1");
+
namespaces.run(split("remove-auto-topic-creation myprop/clust/ns1"));
verify(mockNamespaces).removeAutoTopicCreation("myprop/clust/ns1");
@@ -516,6 +519,9 @@ public class PulsarAdminToolTest {
verify(mockNamespaces).setAutoSubscriptionCreation("myprop/clust/ns1",
AutoSubscriptionCreationOverride.builder().allowAutoSubscriptionCreation(true).build());
+ namespaces.run(split("get-auto-subscription-creation myprop/clust/ns1"));
+ verify(mockNamespaces).getAutoSubscriptionCreation("myprop/clust/ns1");
+
namespaces.run(split("remove-auto-subscription-creation myprop/clust/ns1"));
verify(mockNamespaces).removeAutoSubscriptionCreation("myprop/clust/ns1");
diff --git a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
index 4c08bce9c04..25087cfb25e 100644
--- a/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
+++ b/pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdNamespaces.java
@@ -235,6 +235,18 @@ public class CmdNamespaces extends CmdBase {
}
}
+ @Parameters(commandDescription = "Get permissions to access subscription admin-api")
+ private class SubscriptionPermissions extends CliCommand {
+ @Parameter(description = "tenant/namespace", required = true)
+ private java.util.List<String> params;
+
+ @Override
+ void run() throws PulsarAdminException {
+ String namespace = validateNamespace(params);
+ print(getAdmin().namespaces().getPermissionOnSubscription(namespace));
+ }
+ }
+
@Parameters(commandDescription = "Grant permissions to access subscription admin-api")
private class GrantSubscriptionPermissions extends CliCommand {
@Parameter(description = "tenant/namespace", required = true)
@@ -586,6 +598,18 @@ public class CmdNamespaces extends CmdBase {
}
}
+ @Parameters(commandDescription = "Get autoTopicCreation info for a namespace")
+ private class GetAutoTopicCreation extends CliCommand {
+ @Parameter(description = "tenant/namespace", required = true)
+ private java.util.List<String> params;
+
+ @Override
+ void run() throws PulsarAdminException {
+ String namespace = validateNamespace(params);
+ print(getAdmin().namespaces().getAutoTopicCreation(namespace));
+ }
+ }
+
@Parameters(commandDescription = "Remove override of autoTopicCreation for a namespace")
private class RemoveAutoTopicCreation extends CliCommand {
@Parameter(description = "tenant/namespace", required = true)
@@ -617,6 +641,18 @@ public class CmdNamespaces extends CmdBase {
}
}
+ @Parameters(commandDescription = "Get the autoSubscriptionCreation for a namespace")
+ private class GetAutoSubscriptionCreation extends CliCommand {
+ @Parameter(description = "tenant/namespace", required = true)
+ private java.util.List<String> params;
+
+ @Override
+ void run() throws PulsarAdminException {
+ String namespace = validateNamespace(params);
+ print(getAdmin().namespaces().getAutoSubscriptionCreation(namespace));
+ }
+ }
+
@Parameters(commandDescription = "Remove override of autoSubscriptionCreation for a namespace")
private class RemoveAutoSubscriptionCreation extends CliCommand {
@Parameter(description = "tenant/namespace", required = true)
@@ -1271,6 +1307,18 @@ public class CmdNamespaces extends CmdBase {
}
}
+ @Parameters(commandDescription = "Get encryption required for a namespace")
+ private class GetEncryptionRequired extends CliCommand {
+ @Parameter(description = "tenant/namespace", required = true)
+ private java.util.List<String> params;
+
+ @Override
+ void run() throws PulsarAdminException {
+ String namespace = validateNamespace(params);
+ print(getAdmin().namespaces().getEncryptionRequiredStatus(namespace));
+ }
+ }
+
@Parameters(commandDescription = "Get the delayed delivery policy for a namespace")
private class GetDelayedDelivery extends CliCommand {
@Parameter(description = "tenant/namespace", required = true)
@@ -1403,6 +1451,18 @@ public class CmdNamespaces extends CmdBase {
}
}
+ @Parameters(commandDescription = "Get subscriptionAuthMod for a namespace")
+ private class GetSubscriptionAuthMode extends CliCommand {
+ @Parameter(description = "tenant/namespace", required = true)
+ private java.util.List<String> params;
+
+ @Override
+ void run() throws PulsarAdminException {
+ String namespace = validateNamespace(params);
+ print(getAdmin().namespaces().getSubscriptionAuthMode(namespace));
+ }
+ }
+
@Parameters(commandDescription = "Get deduplicationSnapshotInterval for a namespace")
private class GetDeduplicationSnapshotInterval extends CliCommand {
@Parameter(description = "tenant/namespace", required = true)
@@ -2328,6 +2388,7 @@ public class CmdNamespaces extends CmdBase {
jcommander.addCommand("grant-permission", new GrantPermissions());
jcommander.addCommand("revoke-permission", new RevokePermissions());
+ jcommander.addCommand("subscription-permission", new SubscriptionPermissions());
jcommander.addCommand("grant-subscription-permission", new GrantSubscriptionPermissions());
jcommander.addCommand("revoke-subscription-permission", new RevokeSubscriptionPermissions());
@@ -2367,9 +2428,11 @@ public class CmdNamespaces extends CmdBase {
jcommander.addCommand("remove-deduplication", new RemoveDeduplication());
jcommander.addCommand("set-auto-topic-creation", new SetAutoTopicCreation());
+ jcommander.addCommand("get-auto-topic-creation", new GetAutoTopicCreation());
jcommander.addCommand("remove-auto-topic-creation", new RemoveAutoTopicCreation());
jcommander.addCommand("set-auto-subscription-creation", new SetAutoSubscriptionCreation());
+ jcommander.addCommand("get-auto-subscription-creation", new GetAutoSubscriptionCreation());
jcommander.addCommand("remove-auto-subscription-creation", new RemoveAutoSubscriptionCreation());
jcommander.addCommand("get-retention", new GetRetention());
@@ -2409,7 +2472,9 @@ public class CmdNamespaces extends CmdBase {
jcommander.addCommand("unsubscribe", new Unsubscribe());
jcommander.addCommand("set-encryption-required", new SetEncryptionRequired());
+ jcommander.addCommand("get-encryption-required", new GetEncryptionRequired());
jcommander.addCommand("set-subscription-auth-mode", new SetSubscriptionAuthMode());
+ jcommander.addCommand("get-subscription-auth-mode", new GetSubscriptionAuthMode());
jcommander.addCommand("set-delayed-delivery", new SetDelayedDelivery());
jcommander.addCommand("get-delayed-delivery", new GetDelayedDelivery());
[pulsar] 01/09: fix: NamespacesTest execution order (#14552)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit a5692a6a685275d406285d7453e213460880c8d0
Author: Baozi <wu...@gmail.com>
AuthorDate: Tue Mar 8 00:07:00 2022 +0800
fix: NamespacesTest execution order (#14552)
(cherry picked from commit f80e2ccf20e5af41c36983f2a93be95b57be841c)
---
.../src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java
index 3b27ff787b1..2dd26954397 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/NamespacesTest.java
@@ -850,11 +850,11 @@ public class NamespacesTest extends MockedPulsarServiceBaseTest {
assertEquals(re.getResponse().getStatus(), Status.PRECONDITION_FAILED.getStatusCode());
}
response = mock(AsyncResponse.class);
- namespaces.deleteNamespace(response, testTenant, testLocalCluster, bundledNsLocal, false, false);
doReturn(Optional.of(localWebServiceUrl)).when(nsSvc).getWebServiceUrl(any(NamespaceBundle.class), any(LookupOptions.class));
for (NamespaceBundle bundle : nsBundles.getBundles()) {
doReturn(true).when(nsSvc).isServiceUnitOwned(bundle);
}
+ namespaces.deleteNamespace(response, testTenant, testLocalCluster, bundledNsLocal, false, false);
ArgumentCaptor<Response> captor2 = ArgumentCaptor.forClass(Response.class);
verify(response, timeout(5000).times(1)).resume(captor2.capture());
assertEquals(captor2.getValue().getStatus(), Status.NO_CONTENT.getStatusCode());
[pulsar] 05/09: Fix wrong prompt exception when get non-persistent topic list without GET_BUDNLE permission (#14638)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 556e4e03a2f24ab51a4d4de55a1465ec49216bb5
Author: Jiwei Guo <te...@apache.org>
AuthorDate: Sat Mar 12 11:20:57 2022 +0800
Fix wrong prompt exception when get non-persistent topic list without GET_BUDNLE permission (#14638)
Fixes #14191
### Motivation
We have some big issues with the permission part. We only have the permission with [doc](https://pulsar.apache.org/docs/en/admin-api-permissions/) mentioned. But if user do it according to the doc, they will face the same issue that #14191 described. We don't have GET_BUNDLE in the grant interface but given the prompt message to the user. And currently, only the admin role could have the permission.
This pr is not solving the permission issue but fixing the prompt message first, not giving 500 error to the user. Then I open an issue https://github.com/apache/pulsar/issues/14639 to discuss refactoring the permission part.
### Modification
- Return 403 to the user when permission is denied.
(cherry picked from commit ca6e82422ecbc5272d3dda2c90873c5a493764e1)
---
.../broker/admin/v1/NonPersistentTopics.java | 25 +++++++-------
.../broker/admin/v2/NonPersistentTopics.java | 31 ++++++++---------
.../pulsar/broker/auth/AuthorizationTest.java | 39 ++++++++++++++++++++--
3 files changed, 62 insertions(+), 33 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/NonPersistentTopics.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/NonPersistentTopics.java
index c5d5870642b..e2ed1ee8cd2 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/NonPersistentTopics.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v1/NonPersistentTopics.java
@@ -196,6 +196,7 @@ public class NonPersistentTopics extends PersistentTopics {
Policies policies = null;
NamespaceName nsName = null;
try {
+ validateNamespaceName(property, cluster, namespace);
validateNamespaceOperation(namespaceName, NamespaceOperation.GET_TOPICS);
policies = getNamespacePolicies(property, cluster, namespace);
nsName = NamespaceName.get(property, cluster, namespace);
@@ -230,22 +231,19 @@ public class NonPersistentTopics extends PersistentTopics {
}
}
- final List<String> topics = Lists.newArrayList();
- FutureUtil.waitForAll(futures).handle((result, exception) -> {
- for (int i = 0; i < futures.size(); i++) {
- try {
- if (futures.get(i).isDone() && futures.get(i).get() != null) {
- topics.addAll(futures.get(i).get());
+ FutureUtil.waitForAll(futures).whenComplete((result, ex) -> {
+ if (ex != null) {
+ resumeAsyncResponseExceptionally(asyncResponse, ex);
+ } else {
+ final List<String> topics = Lists.newArrayList();
+ for (int i = 0; i < futures.size(); i++) {
+ List<String> topicList = futures.get(i).join();
+ if (topicList != null) {
+ topics.addAll(topicList);
}
- } catch (InterruptedException | ExecutionException e) {
- log.error("[{}] Failed to get list of topics under namespace {}/{}/{}", clientAppId(), property,
- cluster, namespace, e);
- asyncResponse.resume(new RestException(e instanceof ExecutionException ? e.getCause() : e));
- return null;
}
+ asyncResponse.resume(topics);
}
- asyncResponse.resume(topics);
- return null;
});
}
@@ -262,6 +260,7 @@ public class NonPersistentTopics extends PersistentTopics {
@PathParam("bundle") String bundleRange) {
log.info("[{}] list of topics on namespace bundle {}/{}/{}/{}", clientAppId(), property, cluster, namespace,
bundleRange);
+ validateNamespaceName(property, cluster, namespace);
validateNamespaceOperation(namespaceName, NamespaceOperation.GET_BUNDLE);
Policies policies = getNamespacePolicies(property, cluster, namespace);
if (!cluster.equals(Constants.GLOBAL_CLUSTER)) {
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
index d390049b405..8a0f123d2ce 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/NonPersistentTopics.java
@@ -403,26 +403,23 @@ public class NonPersistentTopics extends PersistentTopics {
}
}
- final List<String> topics = Lists.newArrayList();
- FutureUtil.waitForAll(futures).handle((result, exception) -> {
- for (int i = 0; i < futures.size(); i++) {
- try {
- if (futures.get(i).isDone() && futures.get(i).get() != null) {
- topics.addAll(futures.get(i).get());
+ FutureUtil.waitForAll(futures).whenComplete((result, ex) -> {
+ if (ex != null) {
+ resumeAsyncResponseExceptionally(asyncResponse, ex);
+ } else {
+ final List<String> topics = Lists.newArrayList();
+ for (int i = 0; i < futures.size(); i++) {
+ List<String> topicList = futures.get(i).join();
+ if (topicList != null) {
+ topics.addAll(topicList);
}
- } catch (InterruptedException | ExecutionException e) {
- log.error("[{}] Failed to get list of topics under namespace {}", clientAppId(), namespaceName, e);
- asyncResponse.resume(new RestException(e instanceof ExecutionException ? e.getCause() : e));
- return null;
}
+ final List<String> nonPersistentTopics =
+ topics.stream()
+ .filter(name -> !TopicName.get(name).isPersistent())
+ .collect(Collectors.toList());
+ asyncResponse.resume(nonPersistentTopics);
}
-
- final List<String> nonPersistentTopics =
- topics.stream()
- .filter(name -> !TopicName.get(name).isPersistent())
- .collect(Collectors.toList());
- asyncResponse.resume(nonPersistentTopics);
- return null;
});
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
index dcdc602985b..7bbbc9072f3 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/auth/AuthorizationTest.java
@@ -18,14 +18,17 @@
*/
package org.apache.pulsar.broker.auth;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
-
import java.util.EnumSet;
-
import org.apache.pulsar.broker.authorization.AuthorizationService;
+import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminBuilder;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AuthAction;
import org.apache.pulsar.common.policies.data.ClusterData;
@@ -35,7 +38,6 @@ import org.apache.pulsar.common.policies.data.SubscriptionAuthMode;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
-
import com.google.common.collect.Sets;
@Test(groups = "flaky")
@@ -224,6 +226,37 @@ public class AuthorizationTest extends MockedPulsarServiceBaseTest {
admin.clusters().deleteCluster("c1");
}
+ @Test
+ public void testGetListWithoutGetBundleOp() throws Exception {
+ String tenant = "p1";
+ String namespaceV1 = "p1/global/ns1";
+ String namespaceV2 = "p1/ns2";
+ admin.clusters().createCluster("c1", ClusterData.builder().build());
+ admin.tenants().createTenant(tenant, new TenantInfoImpl(Sets.newHashSet("role1"), Sets.newHashSet("c1")));
+ admin.namespaces().createNamespace(namespaceV1, Sets.newHashSet("c1"));
+ admin.namespaces().grantPermissionOnNamespace(namespaceV1, "pass.pass2", EnumSet.of(AuthAction.produce));
+ admin.namespaces().createNamespace(namespaceV2, Sets.newHashSet("c1"));
+ admin.namespaces().grantPermissionOnNamespace(namespaceV2, "pass.pass2", EnumSet.of(AuthAction.produce));
+ PulsarAdmin admin2 = PulsarAdmin.builder().serviceHttpUrl(brokerUrl != null
+ ? brokerUrl.toString()
+ : brokerUrlTls.toString())
+ .authentication(new MockAuthentication("pass.pass2"))
+ .build();
+ when(pulsar.getAdminClient()).thenReturn(admin2);
+ try {
+ admin2.topics().getList(namespaceV1, TopicDomain.non_persistent);
+ } catch (Exception ex) {
+ assertTrue(ex instanceof PulsarAdminException.NotAuthorizedException);
+ assertEquals(ex.getMessage(), "Unauthorized to validateNamespaceOperation for operation [GET_BUNDLE] on namespace [p1/global/ns1]");
+ }
+ try {
+ admin2.topics().getList(namespaceV2, TopicDomain.non_persistent);
+ } catch (Exception ex) {
+ assertTrue(ex instanceof PulsarAdminException.NotAuthorizedException);
+ assertEquals(ex.getMessage(), "Unauthorized to validateNamespaceOperation for operation [GET_BUNDLE] on namespace [p1/ns2]");
+ }
+ }
+
private static void waitForChange() {
try {
Thread.sleep(100);
[pulsar] 07/09: [fix][broker] Fix NPE when set `AutoTopicCreationOverride` (#15653)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 42704c6c58833b4dd86820421f62f84e71aa92c3
Author: Qiang Zhao <ma...@gmail.com>
AuthorDate: Fri May 20 15:21:47 2022 +0800
[fix][broker] Fix NPE when set `AutoTopicCreationOverride` (#15653)
(cherry picked from commit e2afcf0a7ee90908fa647656624aacb9fd93249c)
---
.../pulsar/broker/admin/impl/NamespacesBase.java | 9 +++--
.../apache/pulsar/broker/admin/AdminApi2Test.java | 44 ++++++++++++++++++++++
2 files changed, 50 insertions(+), 3 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
index 7c581b2cf83..0b0d02b7a6b 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
@@ -99,6 +99,7 @@ import org.apache.pulsar.common.policies.data.SchemaCompatibilityStrategy;
import org.apache.pulsar.common.policies.data.SubscribeRate;
import org.apache.pulsar.common.policies.data.SubscriptionAuthMode;
import org.apache.pulsar.common.policies.data.TenantOperation;
+import org.apache.pulsar.common.policies.data.TopicType;
import org.apache.pulsar.common.policies.data.ValidateResult;
import org.apache.pulsar.common.policies.data.impl.AutoTopicCreationOverrideImpl;
import org.apache.pulsar.common.policies.data.impl.DispatchRateImpl;
@@ -832,9 +833,11 @@ public abstract class NamespacesBase extends AdminResource {
"Invalid configuration for autoTopicCreationOverride. the detail is "
+ validateResult.getErrorInfo());
}
- if (maxPartitions > 0 && autoTopicCreationOverride.getDefaultNumPartitions() > maxPartitions) {
- throw new RestException(Status.NOT_ACCEPTABLE,
- "Number of partitions should be less than or equal to " + maxPartitions);
+ if (Objects.equals(autoTopicCreationOverride.getTopicType(), TopicType.PARTITIONED.toString())) {
+ if (maxPartitions > 0 && autoTopicCreationOverride.getDefaultNumPartitions() > maxPartitions) {
+ throw new RestException(Status.NOT_ACCEPTABLE,
+ "Number of partitions should be less than or equal to " + maxPartitions);
+ }
}
}
// Force to read the data s.t. the watch to the cache content is setup.
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java
index 445dec0b633..ede133ef92f 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/AdminApi2Test.java
@@ -46,6 +46,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.core.Response.Status;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
@@ -81,6 +82,7 @@ import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.AutoFailoverPolicyData;
import org.apache.pulsar.common.policies.data.AutoFailoverPolicyType;
+import org.apache.pulsar.common.policies.data.AutoTopicCreationOverride;
import org.apache.pulsar.common.policies.data.BacklogQuota;
import org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationData;
import org.apache.pulsar.common.policies.data.BrokerNamespaceIsolationDataImpl;
@@ -1614,6 +1616,48 @@ public class AdminApi2Test extends MockedPulsarServiceBaseTest {
}
}
+ @Test
+ public void testAutoTopicCreationOverrideWithMaxNumPartitionsLimit() throws Exception{
+ super.internalCleanup();
+ conf.setMaxNumPartitionsPerPartitionedTopic(10);
+ super.internalSetup();
+ admin.clusters().createCluster("test", ClusterData.builder().serviceUrl(brokerUrl.toString()).build());
+ TenantInfoImpl tenantInfo = new TenantInfoImpl(
+ Sets.newHashSet("role1", "role2"), Sets.newHashSet("test"));
+ admin.tenants().createTenant("testTenant", tenantInfo);
+ // test non-partitioned
+ admin.namespaces().createNamespace("testTenant/ns1", Sets.newHashSet("test"));
+ AutoTopicCreationOverride overridePolicy = AutoTopicCreationOverride
+ .builder().allowAutoTopicCreation(true)
+ .topicType("non-partitioned")
+ .build();
+ admin.namespaces().setAutoTopicCreation("testTenant/ns1", overridePolicy);
+ AutoTopicCreationOverride newOverridePolicy =
+ admin.namespaces().getAutoTopicCreation("testTenant/ns1");
+ assertEquals(overridePolicy, newOverridePolicy);
+ // test partitioned
+ AutoTopicCreationOverride partitionedOverridePolicy = AutoTopicCreationOverride
+ .builder().allowAutoTopicCreation(true)
+ .topicType("partitioned")
+ .defaultNumPartitions(10)
+ .build();
+ admin.namespaces().setAutoTopicCreation("testTenant/ns1", partitionedOverridePolicy);
+ AutoTopicCreationOverride partitionedNewOverridePolicy =
+ admin.namespaces().getAutoTopicCreation("testTenant/ns1");
+ assertEquals(partitionedOverridePolicy, partitionedNewOverridePolicy);
+ // test partitioned with error
+ AutoTopicCreationOverride partitionedWrongOverridePolicy = AutoTopicCreationOverride
+ .builder().allowAutoTopicCreation(true)
+ .topicType("partitioned")
+ .defaultNumPartitions(123)
+ .build();
+ try {
+ admin.namespaces().setAutoTopicCreation("testTenant/ns1", partitionedWrongOverridePolicy);
+ fail();
+ } catch (Exception ex) {
+ assertTrue(ex.getCause() instanceof NotAcceptableException);
+ }
+ }
@Test
public void testMaxTopicsPerNamespace() throws Exception {
super.internalCleanup();
[pulsar] 03/09: [Authorization] Optimize the logic of allowing namespace operation (#13090)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 969871d6727b941fb99014156436adad1459f976
Author: Ruguo Yu <ji...@163.com>
AuthorDate: Thu Dec 9 16:10:13 2021 +0800
[Authorization] Optimize the logic of allowing namespace operation (#13090)
(cherry picked from commit f04139ffcc3358833b021da8e500e7e0b631e389)
---
.../authorization/PulsarAuthorizationProvider.java | 124 +++++++++++----------
1 file changed, 68 insertions(+), 56 deletions(-)
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
index b5ebf962ba1..aab4b2b5ac1 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authorization/PulsarAuthorizationProvider.java
@@ -531,27 +531,44 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
String role,
NamespaceOperation operation,
AuthenticationDataSource authData) {
- CompletableFuture<Boolean> isAuthorizedFuture;
- switch (operation) {
- case PACKAGES:
- isAuthorizedFuture = allowTheSpecifiedActionOpsAsync(namespaceName, role, authData, AuthAction.packages);
- break;
- case GET_TOPICS:
- case UNSUBSCRIBE:
- case CLEAR_BACKLOG:
- isAuthorizedFuture = allowTheSpecifiedActionOpsAsync(namespaceName, role, authData, AuthAction.consume);
- break;
- default:
- isAuthorizedFuture = CompletableFuture.completedFuture(false);
+ if (log.isDebugEnabled()) {
+ log.debug("Check allowNamespaceOperationAsync [{}] on [{}].", operation.name(), namespaceName);
}
- CompletableFuture<Boolean> isTenantAdminFuture = validateTenantAdminAccess(namespaceName.getTenant(), role, authData);
- return isTenantAdminFuture.thenCombine(isAuthorizedFuture, (isTenantAdmin, isAuthorized) -> {
- if (log.isDebugEnabled()) {
- log.debug("Verify if role {} is allowed to {} to topic {}: isTenantAdmin={}, isAuthorized={}",
- role, operation, namespaceName, isTenantAdmin, isAuthorized);
- }
- return isTenantAdmin || isAuthorized;
- });
+
+ return validateTenantAdminAccess(namespaceName.getTenant(), role, authData)
+ .thenCompose(isSuperUserOrAdmin -> {
+ if (log.isDebugEnabled()) {
+ log.debug("Verify if role {} is allowed to {} to namespace {}: isSuperUserOrAdmin={}",
+ role, operation, namespaceName, isSuperUserOrAdmin);
+ }
+ if (isSuperUserOrAdmin) {
+ return CompletableFuture.completedFuture(true);
+ } else {
+ switch (operation) {
+ case PACKAGES:
+ return allowTheSpecifiedActionOpsAsync(
+ namespaceName, role, authData, AuthAction.packages);
+ case GET_TOPIC:
+ case GET_TOPICS:
+ case UNSUBSCRIBE:
+ case CLEAR_BACKLOG:
+ return allowTheSpecifiedActionOpsAsync(
+ namespaceName, role, authData, AuthAction.consume);
+ case CREATE_TOPIC:
+ case DELETE_TOPIC:
+ case ADD_BUNDLE:
+ case GET_BUNDLE:
+ case DELETE_BUNDLE:
+ case GRANT_PERMISSION:
+ case GET_PERMISSION:
+ case REVOKE_PERMISSION:
+ return CompletableFuture.completedFuture(false);
+ default:
+ return FutureUtil.failedFuture(new IllegalStateException(
+ "NamespaceOperation [" + operation.name() + "] is not supported."));
+ }
+ }
+ });
}
@Override
@@ -568,41 +585,8 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
String role,
TopicOperation operation,
AuthenticationDataSource authData) {
- log.debug("Check allowTopicOperationAsync [" + operation.name() + "] on [" + topicName.toString() + "].");
-
- CompletableFuture<Boolean> isAuthorizedFuture;
-
- switch (operation) {
- case LOOKUP:
- case GET_STATS:
- case GET_METADATA:
- isAuthorizedFuture = canLookupAsync(topicName, role, authData);
- break;
- case PRODUCE:
- isAuthorizedFuture = canProduceAsync(topicName, role, authData);
- break;
- case GET_SUBSCRIPTIONS:
- case CONSUME:
- case SUBSCRIBE:
- case UNSUBSCRIBE:
- case SKIP:
- case EXPIRE_MESSAGES:
- case PEEK_MESSAGES:
- case RESET_CURSOR:
- case SET_REPLICATED_SUBSCRIPTION_STATUS:
- isAuthorizedFuture = canConsumeAsync(topicName, role, authData, authData.getSubscription());
- break;
- case TERMINATE:
- case COMPACT:
- case OFFLOAD:
- case UNLOAD:
- case ADD_BUNDLE_RANGE:
- case GET_BUNDLE_RANGE:
- case DELETE_BUNDLE_RANGE:
- return validateTenantAdminAccess(topicName.getTenant(), role, authData);
- default:
- return FutureUtil.failedFuture(
- new IllegalStateException("TopicOperation [" + operation.name() + "] is not supported."));
+ if (log.isDebugEnabled()) {
+ log.debug("Check allowTopicOperationAsync [{}] on [{}].", operation.name(), topicName);
}
return validateTenantAdminAccess(topicName.getTenant(), role, authData)
@@ -614,7 +598,35 @@ public class PulsarAuthorizationProvider implements AuthorizationProvider {
if (isSuperUserOrAdmin) {
return CompletableFuture.completedFuture(true);
} else {
- return isAuthorizedFuture;
+ switch (operation) {
+ case LOOKUP:
+ case GET_STATS:
+ case GET_METADATA:
+ return canLookupAsync(topicName, role, authData);
+ case PRODUCE:
+ return canProduceAsync(topicName, role, authData);
+ case GET_SUBSCRIPTIONS:
+ case CONSUME:
+ case SUBSCRIBE:
+ case UNSUBSCRIBE:
+ case SKIP:
+ case EXPIRE_MESSAGES:
+ case PEEK_MESSAGES:
+ case RESET_CURSOR:
+ case SET_REPLICATED_SUBSCRIPTION_STATUS:
+ return canConsumeAsync(topicName, role, authData, authData.getSubscription());
+ case TERMINATE:
+ case COMPACT:
+ case OFFLOAD:
+ case UNLOAD:
+ case ADD_BUNDLE_RANGE:
+ case GET_BUNDLE_RANGE:
+ case DELETE_BUNDLE_RANGE:
+ return CompletableFuture.completedFuture(false);
+ default:
+ return FutureUtil.failedFuture(new IllegalStateException(
+ "TopicOperation [" + operation.name() + "] is not supported."));
+ }
}
});
}
[pulsar] 09/09: [fix][tests] TieredStorageConfigurationTests - clear system properties (#15957)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit a7d22cabab2838220638fc85e1bce59866590134
Author: Enrico Olivelli <eo...@apache.org>
AuthorDate: Fri Jun 24 15:45:26 2022 +0200
[fix][tests] TieredStorageConfigurationTests - clear system properties (#15957)
(cherry picked from commit bacc9d69c66777879a6418e3d61c546150a5e753)
---
.../provider/TieredStorageConfigurationTests.java | 42 ++++++++++++----------
1 file changed, 24 insertions(+), 18 deletions(-)
diff --git a/tiered-storage/jcloud/src/test/java/org/apache/bookkeeper/mledger/offload/jcloud/provider/TieredStorageConfigurationTests.java b/tiered-storage/jcloud/src/test/java/org/apache/bookkeeper/mledger/offload/jcloud/provider/TieredStorageConfigurationTests.java
index bf5e046bf70..8370fb95804 100644
--- a/tiered-storage/jcloud/src/test/java/org/apache/bookkeeper/mledger/offload/jcloud/provider/TieredStorageConfigurationTests.java
+++ b/tiered-storage/jcloud/src/test/java/org/apache/bookkeeper/mledger/offload/jcloud/provider/TieredStorageConfigurationTests.java
@@ -129,19 +129,21 @@ public class TieredStorageConfigurationTests {
// set the aws properties with fake creds so the defaultProviderChain works
System.setProperty("aws.accessKeyId", "fakeid1");
System.setProperty("aws.secretKey", "fakekey1");
- Credentials creds1 = config.getProviderCredentials().get();
- assertEquals(creds1.identity, "fakeid1");
- assertEquals(creds1.credential, "fakekey1");
+ try {
+ Credentials creds1 = config.getProviderCredentials().get();
+ assertEquals(creds1.identity, "fakeid1");
+ assertEquals(creds1.credential, "fakekey1");
- // reset the properties and ensure we get different values by re-evaluating the chain
- System.setProperty("aws.accessKeyId", "fakeid2");
- System.setProperty("aws.secretKey", "fakekey2");
- Credentials creds2 = config.getProviderCredentials().get();
- assertEquals(creds2.identity, "fakeid2");
- assertEquals(creds2.credential, "fakekey2");
-
- System.clearProperty("aws.accessKeyId");
- System.clearProperty("aws.secretKey");
+ // reset the properties and ensure we get different values by re-evaluating the chain
+ System.setProperty("aws.accessKeyId", "fakeid2");
+ System.setProperty("aws.secretKey", "fakekey2");
+ Credentials creds2 = config.getProviderCredentials().get();
+ assertEquals(creds2.identity, "fakeid2");
+ assertEquals(creds2.credential, "fakekey2");
+ } finally {
+ System.clearProperty("aws.accessKeyId");
+ System.clearProperty("aws.secretKey");
+ }
}
/**
@@ -215,11 +217,15 @@ public class TieredStorageConfigurationTests {
map.put("s3ManagedLedgerOffloadRegion", "my-region");
System.setProperty("jclouds.SystemPropertyA", "A");
System.setProperty("jclouds.region", "jclouds-region");
- TieredStorageConfiguration config = new TieredStorageConfiguration(map);
- Properties properties = config.getOverrides();
- System.out.println(properties.toString());
- assertEquals(properties.get("jclouds.region"), "jclouds-region");
- assertEquals(config.getServiceEndpoint(), "http://localhost");
- assertEquals(properties.get("jclouds.SystemPropertyA"), "A");
+ try {
+ TieredStorageConfiguration config = new TieredStorageConfiguration(map);
+ Properties properties = config.getOverrides();
+ assertEquals(properties.get("jclouds.region"), "jclouds-region");
+ assertEquals(config.getServiceEndpoint(), "http://localhost");
+ assertEquals(properties.get("jclouds.SystemPropertyA"), "A");
+ } finally {
+ System.clearProperty("jclouds.SystemPropertyA");
+ System.clearProperty("jclouds.region");
+ }
}
}
[pulsar] 02/09: [fix][branch-2.9] Fix wrong unit of NIC speed on linux (#15770)
Posted by xy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
xyz pushed a commit to branch branch-2.8
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit bdd65f510edb2e017edef1e3f0dc706bbde349cc
Author: gaozhangmin <ga...@qq.com>
AuthorDate: Fri May 27 17:32:11 2022 +0800
[fix][branch-2.9] Fix wrong unit of NIC speed on linux (#15770)
(cherry picked from commit 48d60865d252d32b7aad70d4662f04d765f45f0c)
---
.../pulsar/broker/loadbalance/impl/LinuxBrokerHostUsageImpl.java | 8 ++++----
.../pulsar/broker/loadbalance/LoadReportNetworkLimitTest.java | 4 ++--
2 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/LinuxBrokerHostUsageImpl.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/LinuxBrokerHostUsageImpl.java
index 53d8d3e379d..39297a41ab3 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/LinuxBrokerHostUsageImpl.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/loadbalance/impl/LinuxBrokerHostUsageImpl.java
@@ -248,7 +248,7 @@ public class LinuxBrokerHostUsageImpl implements BrokerHostUsage {
private double getTotalNicLimitKbps(List<String> nics) {
// Use the override value as configured. Return the total max speed across all available NICs, converted
// from Gbps into Kbps
- return overrideBrokerNicSpeedGbps.map(aDouble -> aDouble * nics.size() * 1024 * 1024)
+ return overrideBrokerNicSpeedGbps.map(aDouble -> aDouble * nics.size() * 1000 * 1000)
.orElseGet(() -> nics.stream().mapToDouble(nicPath -> {
// Nic speed is in Mbits/s, return kbits/s
try {
@@ -258,7 +258,7 @@ public class LinuxBrokerHostUsageImpl implements BrokerHostUsage {
+ " config [loadBalancerOverrideBrokerNicSpeedGbps] to override it.", nicPath), e);
return 0d;
}
- }).sum() * 1024);
+ }).sum() * 1000);
}
private Path getNicTxPath(String nic) {
@@ -277,7 +277,7 @@ public class LinuxBrokerHostUsageImpl implements BrokerHostUsage {
log.error("Failed to read rx_bytes for NIC " + s, e);
return 0d;
}
- }).sum() * 8 / 1024;
+ }).sum() * 8d / 1000;
}
private double getTotalNicUsageTxKb(List<String> nics) {
@@ -288,7 +288,7 @@ public class LinuxBrokerHostUsageImpl implements BrokerHostUsage {
log.error("Failed to read tx_bytes for NIC " + s, e);
return 0d;
}
- }).sum() * 8 / 1024;
+ }).sum() * 8d / 1000;
}
private static long readLongFromFile(String path) throws IOException {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadReportNetworkLimitTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadReportNetworkLimitTest.java
index 460210d33d6..2d9dc1abb0e 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadReportNetworkLimitTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/loadbalance/LoadReportNetworkLimitTest.java
@@ -56,8 +56,8 @@ public class LoadReportNetworkLimitTest extends MockedPulsarServiceBaseTest {
LoadManagerReport report = admin.brokerStats().getLoadReport();
if (SystemUtils.IS_OS_LINUX) {
- assertEquals(report.getBandwidthIn().limit, nicCount * 5.4 * 1024 * 1024);
- assertEquals(report.getBandwidthOut().limit, nicCount * 5.4 * 1024 * 1024);
+ assertEquals(report.getBandwidthIn().limit, nicCount * 5.4 * 1000 * 1000);
+ assertEquals(report.getBandwidthOut().limit, nicCount * 5.4 * 1000 * 1000);
} else {
// On non-Linux system we don't report the network usage
assertEquals(report.getBandwidthIn().limit, -1.0);