org.apache.kafka.common.security.auth.KafkaPrincipal Java Examples

The following examples show how to use org.apache.kafka.common.security.auth.KafkaPrincipal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 6 votes vote down vote up
@Test
public void getAcls() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "my_user");
    Resource topic1 = Resource.fromString(Topic.name() + Resource.Separator() + "topic1");
    Resource topic2 = Resource.fromString(Topic.name() + Resource.Separator() + "topic2");

    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    client.addAcls(readAcl, topic1);
    client.addAcls(readAcl, topic2);

    Map<Resource, Set<Acl>> allAcls = new HashMap<>();
    allAcls.put(topic1, readAcl);
    allAcls.put(topic2, readAcl);

    assertThat(client.getAcls(), is(allAcls));
}
 
Example #2
Source File: RangerKafkaAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public scala.collection.immutable.Map<Resource, Set<Acl>> getAcls(KafkaPrincipal principal) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerKafkaAuthorizer.getAcls(KafkaPrincipal)");
	}

	scala.collection.immutable.Map<Resource, Set<Acl>> ret = null;

	try {
		activatePluginClassLoader();

		ret = rangerKakfaAuthorizerImpl.getAcls(principal);
	} finally {
		deactivatePluginClassLoader();
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerKafkaAuthorizer.getAcls(KafkaPrincipal)");
	}

	return ret;
}
 
Example #3
Source File: TestAclsCrud.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAclsForNonExistentRole() {
  sentryKafkaAuthorizer = new SentryKafkaAuthorizer();
  java.util.Map<String, String> configs = new HashMap<>();
  configs.put(KafkaAuthConf.SENTRY_KAFKA_SITE_URL, "file://" + sentrySitePath.getAbsolutePath());
  sentryKafkaAuthorizer.configure(configs);

  final String role1 = "role1";
  Set<Acl> acls = new HashSet<>();
  final Acl acl = new Acl(new KafkaPrincipal("role", role1),
      Allow$.MODULE$,
      "127.0.0.1",
      Operation$.MODULE$.fromString("READ"));
  acls.add(acl);
  scala.collection.immutable.Set<Acl> aclsScala = scala.collection.JavaConversions.asScalaSet(acls).toSet();
  Resource resource = new Resource(ResourceType$.MODULE$.fromString("TOPIC"), "test-topic");
  try {
    sentryKafkaAuthorizer.addAcls(aclsScala, resource);
  } catch (Exception ex) {
    assertCausedMessage(ex, "Can not add Acl for non-existent Role: role1");
  }
}
 
Example #4
Source File: JwtKafkaPrincipalBuilder.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaPrincipal build(AuthenticationContext context) {
    if (context instanceof SaslAuthenticationContext) {
        OAuthBearerSaslServer server = (OAuthBearerSaslServer) ((SaslAuthenticationContext) context).server();
        if (OAuthBearerLoginModule.OAUTHBEARER_MECHANISM.equals(server.getMechanismName())) {
            return new JwtKafkaPrincipal(KafkaPrincipal.USER_TYPE,
                    server.getAuthorizationID(),
                    (BearerTokenWithPayload) server.getNegotiatedProperty("OAUTHBEARER.token"));
        }
    }

    return super.build(context);
}
 
Example #5
Source File: SimpleAclOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private Collection<AclBinding> getAclBindings(String username, Set<SimpleAclRule> aclRules) {
    KafkaPrincipal principal = new KafkaPrincipal("User", username);
    Collection<AclBinding> aclBindings = new ArrayList<>();
    for (SimpleAclRule rule: aclRules) {
        aclBindings.add(rule.toKafkaAclBinding(principal));
    }
    return aclBindings;
}
 
Example #6
Source File: SimpleAclOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns Set of ACLs applying to single user.
 *
 * @param username  Name of the user.
 * @return The Set of ACLs applying to single user.
 */
public Set<SimpleAclRule> getAcls(String username)   {
    log.debug("Searching for ACL rules of user {}", username);
    Set<SimpleAclRule> result = new HashSet<>();
    KafkaPrincipal principal = new KafkaPrincipal("User", username);

    AclBindingFilter aclBindingFilter = new AclBindingFilter(ResourcePatternFilter.ANY,
        new AccessControlEntryFilter(principal.toString(), null, AclOperation.ANY, AclPermissionType.ANY));

    Collection<AclBinding> aclBindings = null;
    try {
        aclBindings = adminClient.describeAcls(aclBindingFilter).values().get();
    } catch (InterruptedException | ExecutionException e) {
        // Admin Client API needs authorizer enabled on the Kafka brokers
        if (e.getCause() instanceof SecurityDisabledException) {
            throw new InvalidResourceException("Authorization needs to be enabled in the Kafka custom resource", e.getCause());
        } else if (e.getCause() instanceof UnknownServerException && e.getMessage().contains("Simple ACL delegation not enabled")) {
            throw new InvalidResourceException("Simple ACL delegation needs to be enabled in the Kafka custom resource", e.getCause());
        }
    }

    if (aclBindings != null) {
        log.debug("ACL rules for user {}", username);
        for (AclBinding aclBinding : aclBindings) {
            log.debug("{}", aclBinding);
            result.add(SimpleAclRule.fromAclBinding(aclBinding));
        }
    }

    return result;
}
 
Example #7
Source File: SimpleAclOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns set with all usernames which have some ACLs.
 *
 * @return The set with all usernames which have some ACLs.
 */
public Set<String> getUsersWithAcls()   {
    Set<String> result = new HashSet<>();
    Set<String> ignored = new HashSet<>(IGNORED_USERS.size());

    log.debug("Searching for Users with any ACL rules");

    Collection<AclBinding> aclBindings;
    try {
        aclBindings = adminClient.describeAcls(AclBindingFilter.ANY).values().get();
    } catch (InterruptedException | ExecutionException e) {
        return result;
    }

    for (AclBinding aclBinding : aclBindings) {
        KafkaPrincipal principal = SecurityUtils.parseKafkaPrincipal(aclBinding.entry().principal());

        if (KafkaPrincipal.USER_TYPE.equals(principal.getPrincipalType()))  {
            // Username in ACL might keep different format (for example based on user's subject) and need to be decoded
            String username = KafkaUserModel.decodeUsername(principal.getName());

            if (IGNORED_USERS.contains(username))   {
                if (!ignored.contains(username)) {
                    // This info message is loged only once per reocnciliation even if there are multiple rules
                    log.info("Existing ACLs for user '{}' will be ignored.", username);
                    ignored.add(username);
                }
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Adding user {} to Set of users with ACLs", username);
                }

                result.add(username);
            }
        }
    }

    return result;
}
 
Example #8
Source File: SimpleAclRule.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Create Kafka's AclBinding instance from current SimpleAclRule instance for the provided principal
 *
 * @param principal KafkaPrincipal instance for the current SimpleAclRule
 * @return Kafka AclBinding instance
 */
public AclBinding toKafkaAclBinding(KafkaPrincipal principal) {
    ResourcePattern resourcePattern = resource.toKafkaResourcePattern();
    AclPermissionType kafkaType = toKafkaAclPermissionType(type);
    org.apache.kafka.common.acl.AclOperation kafkaOperation = toKafkaAclOperation(operation);
    return new AclBinding(resourcePattern, new AccessControlEntry(principal.toString(), getHost(), kafkaOperation, kafkaType));
}
 
Example #9
Source File: SimpleAclOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUsersFromAcls(VertxTestContext context)  {
    Admin mockAdminClient = mock(AdminClient.class);
    SimpleAclOperator aclOp = new SimpleAclOperator(vertx, mockAdminClient);

    ResourcePattern res1 = new ResourcePattern(ResourceType.TOPIC, "my-topic", PatternType.LITERAL);
    ResourcePattern res2 = new ResourcePattern(ResourceType.GROUP, "my-group", PatternType.LITERAL);

    KafkaPrincipal foo = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "CN=foo");
    AclBinding fooAclBinding = new AclBinding(res1, new AccessControlEntry(foo.toString(), "*",
            org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));
    KafkaPrincipal bar = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "CN=bar");
    AclBinding barAclBinding = new AclBinding(res1, new AccessControlEntry(bar.toString(), "*",
            org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));
    KafkaPrincipal baz = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "baz");
    AclBinding bazAclBinding = new AclBinding(res2, new AccessControlEntry(baz.toString(), "*",
            org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));
    KafkaPrincipal all = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "*");
    AclBinding allAclBinding = new AclBinding(res1, new AccessControlEntry(all.toString(), "*",
            org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));
    KafkaPrincipal anonymous = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "ANONYMOUS");
    AclBinding anonymousAclBinding = new AclBinding(res2, new AccessControlEntry(anonymous.toString(), "*",
            org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));

    Collection<AclBinding> aclBindings =
            asList(fooAclBinding, barAclBinding, bazAclBinding, allAclBinding, anonymousAclBinding);

    assertDoesNotThrow(() -> mockDescribeAcls(mockAdminClient, AclBindingFilter.ANY, aclBindings));
    assertThat(aclOp.getUsersWithAcls(), is(new HashSet<>(asList("foo", "bar", "baz"))));
    context.completeNow();
}
 
Example #10
Source File: SimpleAclOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconcileInternalDelete(VertxTestContext context) {
    Admin mockAdminClient = mock(AdminClient.class);
    SimpleAclOperator aclOp = new SimpleAclOperator(vertx, mockAdminClient);

    ResourcePattern resource = new ResourcePattern(ResourceType.TOPIC, "my-topic", PatternType.LITERAL);

    KafkaPrincipal foo = new KafkaPrincipal("User", "CN=foo");
    AclBinding readAclBinding = new AclBinding(resource, new AccessControlEntry(foo.toString(), "*", org.apache.kafka.common.acl.AclOperation.READ, AclPermissionType.ALLOW));

    ArgumentCaptor<Collection<AclBindingFilter>> aclBindingFiltersCaptor = ArgumentCaptor.forClass(Collection.class);
    assertDoesNotThrow(() -> {
        mockDescribeAcls(mockAdminClient, null, Collections.singleton(readAclBinding));
        mockDeleteAcls(mockAdminClient, Collections.singleton(readAclBinding), aclBindingFiltersCaptor);
    });

    Checkpoint async = context.checkpoint();
    aclOp.reconcile("CN=foo", null)
            .onComplete(context.succeeding(rr -> context.verify(() -> {

                Collection<AclBindingFilter> capturedAclBindingFilters = aclBindingFiltersCaptor.getValue();
                assertThat(capturedAclBindingFilters, hasSize(1));
                assertThat(capturedAclBindingFilters, hasItem(readAclBinding.toFilter()));

                Set<ResourcePatternFilter> capturedResourcePatternFilters =
                        capturedAclBindingFilters.stream().map(AclBindingFilter::patternFilter).collect(Collectors.toSet());
                assertThat(capturedResourcePatternFilters, hasSize(1));
                assertThat(capturedResourcePatternFilters, hasItem(resource.toFilter()));

                async.flag();
            })));
}
 
Example #11
Source File: RangerKafkaAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public scala.collection.immutable.Map<Resource, Set<Acl>> getAcls(
		KafkaPrincipal principal) {
	scala.collection.immutable.Map<Resource, Set<Acl>> aclList = new scala.collection.immutable.HashMap<Resource, Set<Acl>>();
	logger.error("getAcls(KafkaPrincipal) is not supported by Ranger for Kafka");
	return aclList;
}
 
Example #12
Source File: SentryKafkaAuthorizer.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Override
  public boolean authorize(RequestChannel.Session session, Operation operation,
                           Resource resource) {
    LOG.debug("Authorizing Session: " + session + " for Operation: " + operation + " on Resource: " + resource);
    final KafkaPrincipal user = session.principal();
    if (isSuperUser(user)) {
      LOG.debug("Allowing SuperUser: " + user + " in " + session + " for Operation: " + operation + " on Resource: " + resource);
      return true;
    }
    LOG.debug("User: " + user + " is not a SuperUser");
    return binding.authorize(session, operation, resource);
}
 
Example #13
Source File: SentryKafkaAuthorizer.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private void getSuperUsers(String kafkaSuperUsers) {
  super_users = new ArrayList<>();
  String[] superUsers = kafkaSuperUsers.split(";");
  for (String superUser : superUsers) {
    if (!superUser.isEmpty()) {
      final String trimmedUser = superUser.trim();
      super_users.add(KafkaPrincipal.fromString(trimmedUser));
      LOG.debug("Adding " + trimmedUser + " to list of Kafka SuperUsers.");
    }
  }
}
 
Example #14
Source File: SentryKafkaAuthorizer.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private boolean isSuperUser(KafkaPrincipal user) {
  if (super_users != null) {
    for (KafkaPrincipal superUser : super_users) {
      if (superUser.equals(user)) {
        return true;
      }
    }
  }
  return false;
}
 
Example #15
Source File: KafkaAuthBinding.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
public Map<Resource, scala.collection.immutable.Set<Acl>> getAcls(KafkaPrincipal principal) {
    if (principal.getPrincipalType().toLowerCase().equals("group")) {
        List<String> roles = getRolesforGroup(principal.getName());
        return getAclsForRoles(roles);
    } else {
        LOG.info("Did not recognize Principal type: " + principal.getPrincipalType() + ". Returning Acls for all principals.");
        return getAcls();
    }
}
 
Example #16
Source File: KafkaAuthBinding.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
private java.util.Map<Resource, scala.collection.immutable.Set<Acl>> rolePrivilegesToResourceAcls(java.util.Map<String, scala.collection.immutable.Set<TSentryPrivilege>> rolePrivilegesMap) {
    final java.util.Map<Resource, scala.collection.immutable.Set<Acl>> resourceAclsMap = new HashMap<>();
    for (String role : rolePrivilegesMap.keySet()) {
        scala.collection.immutable.Set<TSentryPrivilege> privileges = rolePrivilegesMap.get(role);
        final Iterator<TSentryPrivilege> iterator = privileges.iterator();
        while (iterator.hasNext()) {
            TSentryPrivilege privilege = iterator.next();
            final List<TAuthorizable> authorizables = privilege.getAuthorizables();
            String host = null;
            String operation = privilege.getAction();
            for (TAuthorizable tAuthorizable : authorizables) {
                if (tAuthorizable.getType().equals(KafkaAuthorizable.AuthorizableType.HOST.name())) {
                    host = tAuthorizable.getName();
                } else {
                    Resource resource = new Resource(ResourceType$.MODULE$.fromString(tAuthorizable.getType()), tAuthorizable.getName());
                    if (operation.equals("*")) {
                        operation = "All";
                    }
                    Acl acl = new Acl(new KafkaPrincipal("role", role), Allow$.MODULE$, host, Operation$.MODULE$.fromString(operation));
                    Set<Acl> newAclsJava = new HashSet<Acl>();
                    newAclsJava.add(acl);
                    addExistingAclsForResource(resourceAclsMap, resource, newAclsJava);
                    final scala.collection.mutable.Set<Acl> aclScala = JavaConversions.asScalaSet(newAclsJava);
                    resourceAclsMap.put(resource, aclScala.<Acl>toSet());
                }
            }
        }
    }

    return resourceAclsMap;
}
 
Example #17
Source File: SentryKafkaAuthorizerTest.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdmin() {

  KafkaPrincipal admin = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "admin");
  RequestChannel.Session host1Session = new RequestChannel.Session(admin, testHostName1);
  RequestChannel.Session host2Session = new RequestChannel.Session(admin, testHostName2);

  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Create"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Describe"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("ClusterAction"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Read"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Write"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Create"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Delete"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Alter"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Describe"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("ClusterAction"),topic1Resource));

  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Create"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Describe"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("ClusterAction"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Read"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Write"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Create"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Delete"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Alter"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Describe"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("ClusterAction"), topic1Resource));
}
 
Example #18
Source File: SentryKafkaAuthorizerTest.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubAdmin() {
  KafkaPrincipal admin = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "subadmin");
  RequestChannel.Session host1Session = new RequestChannel.Session(admin, testHostName1);
  RequestChannel.Session host2Session = new RequestChannel.Session(admin, testHostName2);

  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Create"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Describe"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("ClusterAction"), clusterResource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Read"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Write"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Create"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Delete"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Alter"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("Describe"), topic1Resource));
  Assert.assertTrue("Test failed.", authorizer.authorize(host1Session, Operation$.MODULE$.fromString("ClusterAction"),topic1Resource));

  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Create"), clusterResource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Describe"), clusterResource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("ClusterAction"), clusterResource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Read"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Write"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Create"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Delete"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Alter"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("Describe"), topic1Resource));
  Assert.assertFalse("Test failed.", authorizer.authorize(host2Session, Operation$.MODULE$.fromString("ClusterAction"), topic1Resource));

}
 
Example #19
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void getAcls_withResource() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "my_user");
    Resource topic1 = Resource.fromString(Topic.name() + Resource.Separator() + "topic1");
    Resource topic2 = Resource.fromString(Topic.name() + Resource.Separator() + "topic2");

    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    client.addAcls(readAcl, topic1);
    client.addAcls(readAcl, topic2);

    assertThat(client.getAcls(topic1), is(readAcl));
}
 
Example #20
Source File: KeycloakRBACAuthorizer.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
@Override
public scala.collection.immutable.Map<Resource, Set<Acl>> getAcls(KafkaPrincipal principal) {
    if (!delegateToKafkaACL) {
        throw new RuntimeException("Simple ACL delegation not enabled");
    }
    return super.getAcls(principal);
}
 
Example #21
Source File: EmbeddedSingleNodeKafkaCluster.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the supplied ACL information to ZK, where it will be picked up by the brokes authorizer.
 *
 * @param username    the who.
 * @param permission  the allow|deny.
 * @param resource    the thing
 * @param ops         the what.
 */
public void addUserAcl(final String username,
                       final AclPermissionType permission,
                       final Resource resource,
                       final Set<AclOperation> ops) {

  final KafkaPrincipal principal = new KafkaPrincipal("User", username);
  final PermissionType scalaPermission = PermissionType$.MODULE$.fromJava(permission);

  final Set<Acl> javaAcls = ops.stream()
      .map(Operation$.MODULE$::fromJava)
      .map(op -> new Acl(principal, scalaPermission, "*", op))
      .collect(Collectors.toSet());

  final scala.collection.immutable.Set<Acl> scalaAcls =
      JavaConversions.asScalaSet(javaAcls).toSet();

  kafka.security.auth.ResourceType scalaResType =
      ResourceType$.MODULE$.fromJava(resource.resourceType());

  final kafka.security.auth.Resource scalaResource =
      new kafka.security.auth.Resource(scalaResType, resource.name());

  authorizer.addAcls(scalaAcls, scalaResource);

  addedAcls.add(scalaResource);
}
 
Example #22
Source File: KafkaAdminClient.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all {@link Acl}s associated to the given {@link KafkaPrincipal}
 *
 * @param principal
 *      the {@link KafkaPrincipal} to look up {@link Acl}s for
 * @return unmodifiable map of all {@link Acl}s associated to the given {@link KafkaPrincipal}
 * @throws IllegalArgumentException
 *      if principal is {@code null}
 * @throws AdminOperationException
 *      if there is an issue reading the {@link Acl}s
 */
public Map<Resource, Set<Acl>> getAcls(KafkaPrincipal principal) {
    if (principal == null)
        throw new IllegalArgumentException("principal cannot be null");

    LOG.debug("Fetching all ACLs for principal [{}]", principal);

    try {
        return convertKafkaAclMap(getAuthorizer().getAcls(principal));
    } catch (ZkException | ZooKeeperClientException e) {
        throw new AdminOperationException("Unable to retrieve ACLs for principal: " + principal, e);
    }
}
 
Example #23
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void getAcls_immutable() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "my_user");
    Resource topic = Resource.fromString(Topic.name() + Resource.Separator() + "topic");

    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));
    client.addAcls(readAcl, topic);
    client.getAcls().clear();
}
 
Example #24
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void getAcls_withKafkaPrincipal() {
    KafkaPrincipal user1 = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user1");
    KafkaPrincipal user2 = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user2");
    Resource topic1 = Resource.fromString(Topic.name() + Resource.Separator() + "topic1");

    Set<Acl> user1Acl = Collections.singleton(new Acl(user1, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));
    Set<Acl> user2Acl = Collections.singleton(new Acl(user2, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    client.addAcls(user1Acl, topic1);
    client.addAcls(user2Acl, topic1);

    assertThat(client.getAcls(user1), is(Collections.singletonMap(topic1, user1Acl)));
}
 
Example #25
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void getAcls_withKafkaPrincipal_immutable() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user");
    Resource topic = Resource.fromString(Topic.name() + Resource.Separator() + "topic");

    Set<Acl> userAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));
    client.addAcls(userAcl, topic);
    client.getAcls(user).clear();
}
 
Example #26
Source File: SimpleAclOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private Collection<AclBindingFilter> getAclBindingFilters(String username, Set<SimpleAclRule> aclRules) {
    KafkaPrincipal principal = new KafkaPrincipal("User", username);
    Collection<AclBindingFilter> aclBindingFilters = new ArrayList<>();
    for (SimpleAclRule rule: aclRules) {
        aclBindingFilters.add(rule.toKafkaAclBinding(principal).toFilter());
    }
    return aclBindingFilters;
}
 
Example #27
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void getAcls_withResource_immutable() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user");
    Resource topic = Resource.fromString(Topic.name() + Resource.Separator() + "topic");

    Set<Acl> userAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));
    client.addAcls(userAcl, topic);
    client.getAcls(topic).clear();
}
 
Example #28
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void addAcls() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "my_user");
    Resource topic1 = Resource.fromString(Topic.name() + Resource.Separator() + "topic1");
    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    client.addAcls(readAcl, topic1);

    assertThat(client.getAcls(topic1), is(readAcl));
}
 
Example #29
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = AdminOperationException.class)
public void addAcls_zkException() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user");
    Resource resource = Resource.fromString(Topic.name() + Resource.Separator() + "topic");
    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    failureClient.addAcls(readAcl, resource);
}
 
Example #30
Source File: KafkaAdminClientTest.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
@Test
public void removeAcls() {
    KafkaPrincipal user = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "my_user");
    Resource topic1 = Resource.fromString(Topic.name() + Resource.Separator() + "topic1");
    Set<Acl> readAcl = Collections.singleton(new Acl(user, Allow$.MODULE$, Acl.WildCardHost(), Read$.MODULE$));

    client.addAcls(readAcl, topic1);

    assertThat(client.getAcls(topic1), is(readAcl));

    client.removeAcls(readAcl, topic1);

    assertThat(client.getAcls(topic1), is(empty()));
}