Example usage for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest

List of usage examples for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest

Introduction

In this page you can find the example usage for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest.

Prototype

public static String generateDigest(String idPassword) throws NoSuchAlgorithmException 

Source Link

Usage

From source file:org.apache.hadoop.registry.client.impl.zk.RegistrySecurity.java

License:Apache License

/**
 * Generate a base-64 encoded digest of the idPasswordPair pair
 * @param idPasswordPair id:password//from ww  w . j a v a  2  s.co m
 * @return a string that can be used for authentication
 */
public String digest(String idPasswordPair) throws IOException {
    if (StringUtils.isEmpty(idPasswordPair) || !isValid(idPasswordPair)) {
        throw new IOException("Invalid id:password");
    }
    try {
        return DigestAuthenticationProvider.generateDigest(idPasswordPair);
    } catch (NoSuchAlgorithmException e) {
        // unlikely since it is standard to the JVM, but maybe JCE restrictions
        // could trigger it
        throw new IOException(e.toString(), e);
    }
}

From source file:org.apache.hadoop.security.token.delegation.TestZKDelegationTokenSecretManager.java

License:Apache License

@Test
public void testACLs() throws Exception {
    DelegationTokenManager tm1;/*from   w w w.  jav a 2 s.c o m*/
    String connectString = zkServer.getConnectString();
    Configuration conf = getSecretConf(connectString);
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    String userPass = "myuser:mypass";
    final ACL digestACL = new ACL(ZooDefs.Perms.ALL,
            new Id("digest", DigestAuthenticationProvider.generateDigest(userPass)));
    ACLProvider digestAclProvider = new ACLProvider() {
        @Override
        public List<ACL> getAclForPath(String path) {
            return getDefaultAcl();
        }

        @Override
        public List<ACL> getDefaultAcl() {
            List<ACL> ret = new ArrayList<ACL>();
            ret.add(digestACL);
            return ret;
        }
    };

    CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(connectString)
            .retryPolicy(retryPolicy).aclProvider(digestAclProvider)
            .authorization("digest", userPass.getBytes("UTF-8")).build();
    curatorFramework.start();
    ZKDelegationTokenSecretManager.setCurator(curatorFramework);
    tm1 = new DelegationTokenManager(conf, new Text("bla"));
    tm1.init();

    // check ACL
    String workingPath = conf.get(ZKDelegationTokenSecretManager.ZK_DTSM_ZNODE_WORKING_PATH);
    verifyACL(curatorFramework, "/" + workingPath, digestACL);

    tm1.destroy();
    ZKDelegationTokenSecretManager.setCurator(null);
    curatorFramework.close();
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java

License:Apache License

/**
 * Given the {@link Configuration} and {@link ACL}s used (zkAcl) for
 * ZooKeeper access, construct the {@link ACL}s for the store's root node.
 * In the constructed {@link ACL}, all the users allowed by zkAcl are given
 * rwa access, while the current RM has exclude create-delete access.
 *
 * To be called only when HA is enabled and the configuration doesn't set ACL
 * for the root node.//  w w w  .  j  ava2 s.c o  m
 */
@VisibleForTesting
@Private
@Unstable
protected List<ACL> constructZkRootNodeACL(Configuration conf, List<ACL> sourceACLs)
        throws NoSuchAlgorithmException {
    List<ACL> zkRootNodeAcl = new ArrayList<ACL>();
    for (ACL acl : sourceACLs) {
        zkRootNodeAcl
                .add(new ACL(ZKUtil.removeSpecificPerms(acl.getPerms(), CREATE_DELETE_PERMS), acl.getId()));
    }

    zkRootNodeUsername = HAUtil.getConfValueForRMInstance(YarnConfiguration.RM_ADDRESS,
            YarnConfiguration.DEFAULT_RM_ADDRESS, conf);
    Id rmId = new Id(zkRootNodeAuthScheme,
            DigestAuthenticationProvider.generateDigest(zkRootNodeUsername + ":" + zkRootNodePassword));
    zkRootNodeAcl.add(new ACL(CREATE_DELETE_PERMS, rmId));
    return zkRootNodeAcl;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore.java

License:Apache License

/**
 * Given the {@link Configuration} and {@link ACL}s used (zkAcl) for
 * ZooKeeper access, construct the {@link ACL}s for the store's root node.
 * In the constructed {@link ACL}, all the users allowed by zkAcl are given
 * rwa access, while the current RM has exclude create-delete access.
 *
 * To be called only when HA is enabled and the configuration doesn't set ACL
 * for the root node.//from   ww  w . jav  a  2  s. co  m
 */
@VisibleForTesting
@Private
@Unstable
protected List<ACL> constructZkRootNodeACL(Configuration conf, List<ACL> sourceACLs)
        throws NoSuchAlgorithmException {
    List<ACL> zkRootNodeAcl = new ArrayList<>();
    for (ACL acl : sourceACLs) {
        zkRootNodeAcl
                .add(new ACL(ZKUtil.removeSpecificPerms(acl.getPerms(), CREATE_DELETE_PERMS), acl.getId()));
    }

    zkRootNodeUsername = HAUtil.getConfValueForRMInstance(YarnConfiguration.RM_ADDRESS,
            YarnConfiguration.DEFAULT_RM_ADDRESS, conf);
    Id rmId = new Id(zkRootNodeAuthScheme,
            DigestAuthenticationProvider.generateDigest(zkRootNodeUsername + ":" + zkRootNodePassword));
    zkRootNodeAcl.add(new ACL(CREATE_DELETE_PERMS, rmId));
    return zkRootNodeAcl;
}

From source file:org.apache.solr.common.cloud.SolrZkClientTest.java

License:Apache License

@Override
public void setUp() throws Exception {
    super.setUp();

    final String SCHEME = "digest";
    final String AUTH = "user:pass";

    String zkDir = createTempDir().toString();
    log.info("ZooKeeper dataDir:" + zkDir);
    zkServer = new ZkTestServer(zkDir);
    zkServer.run();/*from  w ww.  ja  va 2s  . c om*/

    try (SolrZkClient client = new SolrZkClient(zkServer.getZkHost(), AbstractZkTestCase.TIMEOUT)) {
        // Set up chroot
        client.makePath("/solr", false, true);
    }

    defaultClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT);
    defaultClient.makePath(PATH, true);

    aclClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT) {
        @Override
        protected ZkACLProvider createZkACLProvider() {
            return new DefaultZkACLProvider() {
                @Override
                protected List<ACL> createGlobalACLsToAdd() {
                    try {
                        Id id = new Id(SCHEME, DigestAuthenticationProvider.generateDigest(AUTH));
                        return Collections.singletonList(new ACL(ZooDefs.Perms.ALL, id));
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
        }
    };

    credentialsClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT) {
        @Override
        protected ZkCredentialsProvider createZkCredentialsToAddAutomatically() {
            return new DefaultZkCredentialsProvider() {
                @Override
                protected Collection<ZkCredentials> createCredentials() {
                    return Collections
                            .singleton(new ZkCredentials(SCHEME, AUTH.getBytes(StandardCharsets.UTF_8)));
                }
            };
        }
    };
}

From source file:org.apache.solr.common.cloud.TestZkConfigManager.java

License:Apache License

@Test
public void testUploadWithACL() throws IOException {

    zkServer.ensurePathExists("/acl");

    final String readOnlyUsername = "readonly";
    final String readOnlyPassword = "readonly";
    final String writeableUsername = "writeable";
    final String writeablePassword = "writeable";

    ZkACLProvider aclProvider = new DefaultZkACLProvider() {
        @Override//from ww  w  .  j ava 2  s  .  c o m
        protected List<ACL> createGlobalACLsToAdd() {
            try {
                List<ACL> result = new ArrayList<>();
                result.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider
                        .generateDigest(writeableUsername + ":" + writeablePassword))));
                result.add(new ACL(ZooDefs.Perms.READ, new Id("digest", DigestAuthenticationProvider
                        .generateDigest(readOnlyUsername + ":" + readOnlyPassword))));
                return result;
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
    };

    ZkCredentialsProvider readonly = new DefaultZkCredentialsProvider() {
        @Override
        protected Collection<ZkCredentials> createCredentials() {
            List<ZkCredentials> credentials = new ArrayList<>();
            credentials.add(new ZkCredentials("digest",
                    (readOnlyUsername + ":" + readOnlyPassword).getBytes(Charsets.UTF_8)));
            return credentials;
        }
    };

    ZkCredentialsProvider writeable = new DefaultZkCredentialsProvider() {
        @Override
        protected Collection<ZkCredentials> createCredentials() {
            List<ZkCredentials> credentials = new ArrayList<>();
            credentials.add(new ZkCredentials("digest",
                    (writeableUsername + ":" + writeablePassword).getBytes(Charsets.UTF_8)));
            return credentials;
        }
    };

    Path configPath = createTempDir("acl-config");
    Files.createFile(configPath.resolve("file1"));

    // Start with all-access client
    try (SolrZkClient client = buildZkClient(zkServer.getZkAddress("/acl"), aclProvider, writeable)) {
        ZkConfigManager configManager = new ZkConfigManager(client);
        configManager.uploadConfigDir(configPath, "acltest");
        assertEquals(1, configManager.listConfigs().size());
    }

    // Readonly access client can get the list of configs, but can't upload
    try (SolrZkClient client = buildZkClient(zkServer.getZkAddress("/acl"), aclProvider, readonly)) {
        ZkConfigManager configManager = new ZkConfigManager(client);
        assertEquals(1, configManager.listConfigs().size());
        configManager.uploadConfigDir(configPath, "acltest2");
        fail("Should have thrown an ACL exception");
    } catch (IOException e) {
        assertEquals(KeeperException.NoAuthException.class, Throwables.getRootCause(e).getClass());
    }

    // Client with no auth whatsoever can't even get the list of configs
    try (SolrZkClient client = new SolrZkClient(zkServer.getZkAddress("/acl"), 10000)) {
        ZkConfigManager configManager = new ZkConfigManager(client);
        configManager.listConfigs();
        fail("Should have thrown an ACL exception");
    } catch (IOException e) {
        assertEquals(KeeperException.NoAuthException.class, Throwables.getRootCause(e).getClass());
    }

}

From source file:org.apache.solr.common.cloud.VMParamsAllAndReadonlyDigestZkACLProvider.java

License:Apache License

@Override
protected List<ACL> createGlobalACLsToAdd() {
    try {//from w ww  .j av  a 2s  . c  om
        List<ACL> result = new ArrayList<ACL>();

        // Not to have to provide too much credentials and ACL information to the process it is assumed that you want "ALL"-acls
        // added to the user you are using to connect to ZK (if you are using VMParamsSingleSetCredentialsDigestZkCredentialsProvider)
        String digestAllUsername = System.getProperty(zkDigestAllUsernameVMParamName);
        String digestAllPassword = System.getProperty(zkDigestAllPasswordVMParamName);
        if (!StringUtils.isEmpty(digestAllUsername) && !StringUtils.isEmpty(digestAllPassword)) {
            result.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
                    DigestAuthenticationProvider.generateDigest(digestAllUsername + ":" + digestAllPassword))));
        }

        // Besides that support for adding additional "READONLY"-acls for another user
        String digestReadonlyUsername = System.getProperty(zkDigestReadonlyUsernameVMParamName);
        String digestReadonlyPassword = System.getProperty(zkDigestReadonlyPasswordVMParamName);
        if (!StringUtils.isEmpty(digestReadonlyUsername) && !StringUtils.isEmpty(digestReadonlyPassword)) {
            result.add(new ACL(ZooDefs.Perms.READ, new Id("digest", DigestAuthenticationProvider
                    .generateDigest(digestReadonlyUsername + ":" + digestReadonlyPassword))));
        }

        if (result.isEmpty()) {
            result = super.createGlobalACLsToAdd();
        }

        return result;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.solr.security.hadoop.TestZkAclsWithHadoopAuth.java

License:Apache License

private static String digest(String userName, String passwd) {
    try {/* www  .j  ava 2  s. co  m*/
        return DigestAuthenticationProvider.generateDigest(userName + ":" + passwd);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.apache.storm.cluster.ClusterUtils.java

License:Apache License

public static List<ACL> mkTopoOnlyAcls(Map topoConf) throws NoSuchAlgorithmException {
    List<ACL> aclList = null;
    String payload = (String) topoConf.get(Config.STORM_ZOOKEEPER_TOPOLOGY_AUTH_PAYLOAD);
    if (Utils.isZkAuthenticationConfiguredTopology(topoConf)) {
        aclList = new ArrayList<>();
        ACL acl1 = ZooDefs.Ids.CREATOR_ALL_ACL.get(0);
        aclList.add(acl1);/*from   w ww.j a va2 s . c  om*/
        ACL acl2 = new ACL(ZooDefs.Perms.READ,
                new Id("digest", DigestAuthenticationProvider.generateDigest(payload)));
        aclList.add(acl2);
    }
    return aclList;
}

From source file:org.apache.twill.zookeeper.ZKClientTest.java

License:Apache License

@Test
public void testACL() throws IOException, ExecutionException, InterruptedException, NoSuchAlgorithmException {
    InMemoryZKServer zkServer = InMemoryZKServer.builder().setDataDir(tmpFolder.newFolder()).setTickTime(1000)
            .build();//w w  w  .j ava 2s  .  c  om
    zkServer.startAndWait();

    try {
        String userPass = "user:pass";
        String digest = DigestAuthenticationProvider.generateDigest(userPass);

        // Creates two zkclients
        ZKClientService zkClient = ZKClientService.Builder.of(zkServer.getConnectionStr())
                .addAuthInfo("digest", userPass.getBytes()).build();
        zkClient.startAndWait();

        ZKClientService noAuthClient = ZKClientService.Builder.of(zkServer.getConnectionStr()).build();
        noAuthClient.startAndWait();

        // Create a node that is readable by all client, but admin for the creator
        String path = "/testacl";
        zkClient.create(path, "test".getBytes(), CreateMode.PERSISTENT,
                ImmutableList.of(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE),
                        new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS)))
                .get();

        // Verify the ACL
        ACLData aclData = zkClient.getACL(path).get();
        Assert.assertEquals(2, aclData.getACL().size());
        ACL acl = aclData.getACL().get(1);
        Assert.assertEquals(ZooDefs.Perms.ALL, acl.getPerms());
        Assert.assertEquals("digest", acl.getId().getScheme());
        Assert.assertEquals(digest, acl.getId().getId());

        Assert.assertArrayEquals("test".getBytes(), noAuthClient.getData(path).get().getData());

        // When tries to write using the no-auth zk client, it should fail.
        try {
            noAuthClient.setData(path, "test2".getBytes()).get();
            Assert.fail();
        } catch (ExecutionException e) {
            Assert.assertTrue(e.getCause() instanceof KeeperException.NoAuthException);
        }

        // Change ACL to make it open for all
        zkClient.setACL(path, ImmutableList.of(new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE)))
                .get();

        // Write again with the non-auth client, now should succeed.
        noAuthClient.setData(path, "test2".getBytes()).get();

        noAuthClient.stopAndWait();
        zkClient.stopAndWait();

    } finally {
        zkServer.stopAndWait();
    }
}