Example usage for org.apache.hadoop.security UserGroupInformation createUserForTesting

List of usage examples for org.apache.hadoop.security UserGroupInformation createUserForTesting

Introduction

In this page you can find the example usage for org.apache.hadoop.security UserGroupInformation createUserForTesting.

Prototype

@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation createUserForTesting(String user, String[] userGroups) 

Source Link

Document

Create a UGI for testing HDFS and MapReduce

Usage

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testDeleteRowAsGroupIT() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    Connection conn = ConnectionFactory.createConnection(conf);
    Table table = conn.getTable(TableName.valueOf("temp"));

    // Add a new row (as process owner)
    Put put = new Put(Bytes.toBytes("row5"));
    put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"), Bytes.toBytes("val2"));
    table.put(put);//from ww  w.  j a va  2 s  .c o m

    String user = "IT";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp"));

            try {
                // Delete the new row
                Delete delete = new Delete(Bytes.toBytes("row5"));
                table.delete(delete);
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            conn.close();
            return null;
        }
    });

    // Delete the new row (as process owner)
    Delete delete = new Delete(Bytes.toBytes("row5"));
    table.delete(delete);

    conn.close();
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testCloneSnapshotAsGroupQA() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();//w ww  .jav a  2 s  . co m

    List<HBaseProtos.SnapshotDescription> snapshots = admin.listSnapshots("test_snapshot");
    if (CollectionUtils.isNotEmpty(snapshots)) {
        admin.deleteSnapshot("test_snapshot");
    }
    String user = "QA";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "QA" });

    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();
            Table table = conn.getTable(TableName.valueOf("test_namespace", "temp"));
            TableName tableName = table.getName();

            admin.disableTable(tableName);

            // Create a snapshot
            admin.snapshot("test_snapshot", tableName);

            // Clone snapshot
            HTableDescriptor tableDescriptor = new HTableDescriptor(
                    TableName.valueOf("test_namespace", "temp_cloned"));
            TableName newTableName = tableDescriptor.getTableName();
            admin.cloneSnapshot("test_snapshot", newTableName);
            admin.disableTable(newTableName);
            admin.deleteTable(newTableName);

            admin.enableTable(tableName);

            conn.close();
            return null;
        }
    });

    snapshots = admin.listSnapshots("test_snapshot");
    if (CollectionUtils.isNotEmpty(snapshots)) {
        admin.deleteSnapshot("test_snapshot");
    }
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testCloneSnapshotAsNonQAGroup() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();/*from w ww  .j a v  a  2 s . c om*/
    TableName tableName = conn.getTable(TableName.valueOf("test_namespace", "temp")).getName();

    admin.disableTable(tableName);

    // Create a snapshot
    List<HBaseProtos.SnapshotDescription> snapshots = admin.listSnapshots("test_snapshot");
    if (CollectionUtils.isEmpty(snapshots)) {
        admin.snapshot("test_snapshot", tableName);
    }

    admin.enableTable(tableName);

    String user = "public";

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "public" });

    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();

            try {
                TableName clone = TableName.valueOf("test_namespace", "temp_cloned_public");
                if (admin.tableExists(clone)) {
                    // Delete it
                    admin.deleteTable(clone);
                }
                // Clone snapshot
                admin.cloneSnapshot("test_snapshot", clone);
                Assert.fail("Failure expected on an unauthorized group public");
            } catch (Exception e) {
                // Expected
            }
            conn.close();
            return null;
        }
    });
    TableName clone = TableName.valueOf("test_namespace", "temp_cloned_public");

    if (admin.tableExists(clone)) {
        admin.deleteTable(clone);
    }
    admin.deleteSnapshot("test_snapshot");
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testTagBasedTablePolicy() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("temp3"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("colfam1"));
    tableDescriptor.addFamily(new HColumnDescriptor("colfam2"));

    // Try to create a "temp3" table as the "IT" group - this should fail
    String user = "IT";

    // Try to create the table as the "IT" group - this should fail
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();

            try {
                admin.createTable(tableDescriptor);
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }/*from  w  w  w. j  av  a  2  s .com*/

            conn.close();
            return null;
        }
    });

    // Now try to create the table as the "dev" group - this should work
    ugi = UserGroupInformation.createUserForTesting("dev", new String[] { "dev" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Admin admin = conn.getAdmin();

            admin.createTable(tableDescriptor);

            conn.close();
            return null;
        }
    });

    // Drop the table
    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();

    admin.disableTable(TableName.valueOf("temp3"));
    admin.deleteTable(TableName.valueOf("temp3"));

    conn.close();
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testTagBasedColumnFamilyPolicy() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    // Create a new table as process owner
    final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("temp3"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("colfam1"));
    tableDescriptor.addFamily(new HColumnDescriptor("colfam2"));

    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();/*from   www.j av a2 s .c o m*/

    admin.createTable(tableDescriptor);

    // Add a new row
    Put put = new Put(Bytes.toBytes("row1"));
    put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"), Bytes.toBytes("val1"));
    Table table = conn.getTable(TableName.valueOf("temp3"));
    table.put(put);

    put = new Put(Bytes.toBytes("row1"));
    put.addColumn(Bytes.toBytes("colfam2"), Bytes.toBytes("col1"), Bytes.toBytes("val2"));
    table.put(put);

    conn.close();

    String user = "dev";
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "dev" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp3"));

            // Try to read the "colfam1" of the "temp3" table as the "dev" group - this should work
            Get get = new Get(Bytes.toBytes("row1"));
            Result result = table.get(get);
            byte[] valResult = result.getValue(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"));
            Assert.assertTrue(Arrays.equals(valResult, Bytes.toBytes("val1")));

            // Now try to read the "colfam2" column family of the temp3 table - this should fail
            get = new Get(Bytes.toBytes("row1"));
            result = table.get(get);
            valResult = result.getValue(Bytes.toBytes("colfam2"), Bytes.toBytes("col1"));
            Assert.assertNull(valResult);

            conn.close();
            return null;
        }
    });

    // Now try to read colfam1 as the "IT" group - this should fail
    ugi = UserGroupInformation.createUserForTesting("IT", new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp3"));

            Get get = new Get(Bytes.toBytes("row1"));
            try {
                table.get(get);
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            return null;
        }
    });

    // Drop the table
    conn = ConnectionFactory.createConnection(conf);
    admin = conn.getAdmin();

    admin.disableTable(TableName.valueOf("temp3"));
    admin.deleteTable(TableName.valueOf("temp3"));

    conn.close();
}

From source file:org.apache.ranger.authorization.hbase.HBaseRangerAuthorizationTest.java

License:Apache License

@Test
public void testTagBasedColumnPolicy() throws Exception {
    final Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "localhost");
    conf.set("hbase.zookeeper.property.clientPort", "" + port);
    conf.set("zookeeper.znode.parent", "/hbase-unsecure");

    // Create a new table as process owner
    final HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf("temp3"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("colfam1"));
    tableDescriptor.addFamily(new HColumnDescriptor("colfam2"));

    Connection conn = ConnectionFactory.createConnection(conf);
    Admin admin = conn.getAdmin();//from  w  w w . j ava2 s.c  o  m

    admin.createTable(tableDescriptor);

    // Add a new row
    Put put = new Put(Bytes.toBytes("row1"));
    put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"), Bytes.toBytes("val1"));
    Table table = conn.getTable(TableName.valueOf("temp3"));
    table.put(put);

    put = new Put(Bytes.toBytes("row1"));
    put.addColumn(Bytes.toBytes("colfam2"), Bytes.toBytes("col1"), Bytes.toBytes("val2"));
    table.put(put);

    conn.close();

    String user = "dev";
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting(user, new String[] { "dev" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp3"));

            // Try to write something to the "col1" column of the "colfam1" of the "temp3" table as the "dev" group
            // - this should work
            Put put = new Put(Bytes.toBytes("row3"));
            put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"), Bytes.toBytes("val2"));
            table.put(put);

            // Try to write something to the "col2" column of the "colfam1" of the "temp3" table as the "dev" group
            // - this should fail
            put = new Put(Bytes.toBytes("row3"));
            put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col2"), Bytes.toBytes("val2"));
            try {
                table.put(put);
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            conn.close();
            return null;
        }
    });

    ugi = UserGroupInformation.createUserForTesting("IT", new String[] { "IT" });
    ugi.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            Connection conn = ConnectionFactory.createConnection(conf);
            Table table = conn.getTable(TableName.valueOf("temp3"));

            // Try to write something to the "col1" column of the "colfam1" of the "temp3" table as the "IT" group
            // - this should fail
            Put put = new Put(Bytes.toBytes("row3"));
            put.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("col1"), Bytes.toBytes("val2"));
            try {
                table.put(put);
                Assert.fail("Failure expected on an unauthorized user");
            } catch (IOException ex) {
                // expected
            }

            conn.close();
            return null;
        }
    });

    // Drop the table
    conn = ConnectionFactory.createConnection(conf);
    admin = conn.getAdmin();

    admin.disableTable(TableName.valueOf("temp3"));
    admin.deleteTable(TableName.valueOf("temp3"));

    conn.close();
}

From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerGSSTest.java

License:Apache License

@org.junit.BeforeClass
public static void setup() throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//  w w  w.j a  v  a 2s .c o  m

    configureKerby(basedir);

    // JAAS Config file - We need to point to the correct keytab files
    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/kafka_kerberos.jaas");
    String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    content = content.replaceAll("<basedir>", basedir);
    //content = content.replaceAll("zookeeper/localhost", "zookeeper/" + address);

    Path path2 = FileSystems.getDefault().getPath(basedir, "/target/test-classes/kafka_kerberos.jaas");
    Files.write(path2, content.getBytes(StandardCharsets.UTF_8));

    System.setProperty("java.security.auth.login.config", path2.toString());

    // Set up Zookeeper to require SASL
    Map<String, Object> zookeeperProperties = new HashMap<>();
    zookeeperProperties.put("authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
    zookeeperProperties.put("requireClientAuthScheme", "sasl");
    zookeeperProperties.put("jaasLoginRenew", "3600000");

    InstanceSpec instanceSpec = new InstanceSpec(null, -1, -1, -1, true, 1, -1, -1, zookeeperProperties,
            "localhost");

    zkServer = new TestingServer(instanceSpec, true);

    // Get a random port
    ServerSocket serverSocket = new ServerSocket(0);
    port = serverSocket.getLocalPort();
    serverSocket.close();

    tempDir = Files.createTempDirectory("kafka");

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", tempDir.toString());
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SASL_PLAINTEXT
    props.put("listeners", "SASL_PLAINTEXT://localhost:" + port);
    props.put("security.inter.broker.protocol", "SASL_PLAINTEXT");
    props.put("sasl.enabled.mechanisms", "GSSAPI");
    props.put("sasl.mechanism.inter.broker.protocol", "GSSAPI");
    props.put("sasl.kerberos.service.name", "kafka");

    // Plug in Apache Ranger authorizer
    props.put("authorizer.class.name",
            "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer");

    // Create users for testing
    UserGroupInformation.createUserForTesting("client@kafka.apache.org", new String[] { "public" });
    UserGroupInformation.createUserForTesting("kafka/localhost@kafka.apache.org", new String[] { "IT" });

    KafkaConfig config = new KafkaConfig(props);
    kafkaServer = new KafkaServerStartable(config);
    kafkaServer.startup();

    // Create some topics
    ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$);

    final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false);
    AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
    AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
}

From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerSASLSSLTest.java

License:Apache License

@org.junit.BeforeClass
public static void setup() throws Exception {
    // JAAS Config file
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }//from   w  w w .  j a va 2  s  .  c om

    File f = new File(basedir + "/src/test/resources/kafka_plain.jaas");
    System.setProperty("java.security.auth.login.config", f.getPath());

    // Create keys
    String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE";
    String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE";

    // Create a truststore
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, "security".toCharArray());

    serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30),
            "sspass", "myservicekey", "skpass", keystore);
    clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass",
            "myclientkey", "ckpass", keystore);

    File truststoreFile = File.createTempFile("kafkatruststore", ".jks");
    try (OutputStream output = new FileOutputStream(truststoreFile)) {
        keystore.store(output, "security".toCharArray());
    }
    truststorePath = truststoreFile.getPath();

    zkServer = new TestingServer();

    // Get a random port
    ServerSocket serverSocket = new ServerSocket(0);
    port = serverSocket.getLocalPort();
    serverSocket.close();

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", "/tmp/kafka");
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SASL_SSL
    props.put("listeners", "SASL_SSL://localhost:" + port);
    props.put("security.inter.broker.protocol", "SASL_SSL");
    props.put("sasl.enabled.mechanisms", "PLAIN");
    props.put("sasl.mechanism.inter.broker.protocol", "PLAIN");

    props.put("ssl.keystore.location", serviceKeystorePath);
    props.put("ssl.keystore.password", "sspass");
    props.put("ssl.key.password", "skpass");
    props.put("ssl.truststore.location", truststorePath);
    props.put("ssl.truststore.password", "security");

    // Plug in Apache Ranger authorizer
    props.put("authorizer.class.name",
            "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer");

    // Create users for testing
    UserGroupInformation.createUserForTesting("alice", new String[] { "IT" });

    KafkaConfig config = new KafkaConfig(props);
    kafkaServer = new KafkaServerStartable(config);
    kafkaServer.startup();

    // Create some topics
    ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$);

    final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false);
    AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
    AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
}

From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerTest.java

License:Apache License

@org.junit.BeforeClass
public static void setup() throws Exception {
    // Create keys
    String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE";
    String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE";

    // Create a truststore
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, "security".toCharArray());

    serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30),
            "sspass", "myservicekey", "skpass", keystore);
    clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass",
            "myclientkey", "ckpass", keystore);

    File truststoreFile = File.createTempFile("kafkatruststore", ".jks");
    try (OutputStream output = new FileOutputStream(truststoreFile)) {
        keystore.store(output, "security".toCharArray());
    }//from  www . j  a va  2  s  .  c o  m
    truststorePath = truststoreFile.getPath();

    zkServer = new TestingServer();

    // Get a random port
    ServerSocket serverSocket = new ServerSocket(0);
    port = serverSocket.getLocalPort();
    serverSocket.close();

    tempDir = Files.createTempDirectory("kafka");

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", tempDir.toString());
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SSL
    props.put("listeners", "SSL://localhost:" + port);
    props.put("ssl.keystore.location", serviceKeystorePath);
    props.put("ssl.keystore.password", "sspass");
    props.put("ssl.key.password", "skpass");
    props.put("ssl.truststore.location", truststorePath);
    props.put("ssl.truststore.password", "security");
    props.put("security.inter.broker.protocol", "SSL");
    props.put("ssl.client.auth", "required");

    // Plug in Apache Ranger authorizer
    props.put("authorizer.class.name",
            "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer");

    // Create users for testing
    UserGroupInformation.createUserForTesting(clientDN, new String[] { "public" });
    UserGroupInformation.createUserForTesting(serviceDN, new String[] { "IT" });

    KafkaConfig config = new KafkaConfig(props);
    kafkaServer = new KafkaServerStartable(config);
    kafkaServer.startup();

    // Create some topics
    ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$);

    final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false);
    AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
    AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
}

From source file:org.apache.ranger.authorization.kms.authorizer.RangerKmsAuthorizerTest.java

License:Apache License

@Test
public void testCreateKeys() throws Throwable {
    if (!UNRESTRICTED_POLICIES_INSTALLED) {
        return;/*www. java2s  .c  o m*/
    }

    // bob should have permission to create
    final UserGroupInformation ugi = UserGroupInformation.createRemoteUser("bob");
    ugi.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            KMSWebApp.getACLs().assertAccess(Type.CREATE, ugi, KMSOp.CREATE_KEY, "newkey1", "127.0.0.1");
            return null;
        }
    });

    // "eve" should not have permission to create
    final UserGroupInformation ugi2 = UserGroupInformation.createRemoteUser("eve");
    ugi2.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            try {
                KMSWebApp.getACLs().assertAccess(Type.CREATE, ugi2, KMSOp.CREATE_KEY, "newkey2", "127.0.0.1");
                Assert.fail("Failure expected");
            } catch (AuthorizationException ex) {
                // expected
            }
            return null;
        }
    });

    // the IT group should not have permission to create
    final UserGroupInformation ugi3 = UserGroupInformation.createUserForTesting("alice", new String[] { "IT" });
    ugi3.doAs(new PrivilegedExceptionAction<Void>() {

        public Void run() throws Exception {
            try {
                KMSWebApp.getACLs().assertAccess(Type.CREATE, ugi3, KMSOp.CREATE_KEY, "newkey1", "127.0.0.1");
                Assert.fail("Failure expected");
            } catch (AuthorizationException ex) {
                // expected
            }
            return null;
        }
    });
}