org.apache.zookeeper.data.Id Java Examples

The following examples show how to use org.apache.zookeeper.data.Id. 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: TestSecureRMRegistryOperations.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserHomedirsPermissionsRestricted() throws Throwable {
  // test that the /users/$user permissions are restricted
  RMRegistryOperationsService rmRegistryOperations =
      startRMRegistryOperations();
  // create Alice's dir, so it should have an ACL for Alice
  final String home = rmRegistryOperations.initUserRegistry(ALICE);
  List<ACL> acls = rmRegistryOperations.zkGetACLS(home);
  ACL aliceACL = null;
  for (ACL acl : acls) {
    LOG.info(RegistrySecurity.aclToString(acl));
    Id id = acl.getId();
    if (id.getScheme().equals(ZookeeperConfigOptions.SCHEME_SASL)
        && id.getId().startsWith(ALICE)) {

      aliceACL = acl;
      break;
    }
  }
  assertNotNull(aliceACL);
  assertEquals(RegistryAdminService.USER_HOMEDIR_ACL_PERMISSIONS,
      aliceACL.getPerms());
}
 
Example #2
Source File: ZKManager.java    From tbschedule with Apache License 2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString.toString()),
        Integer.parseInt(this.properties.getProperty(keys.zkSessionTimeout.toString())),
        new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                sessionEvent(connectionLatch, event);
            }
        });
    String authString = this.properties.getProperty(keys.userName.toString()) + ":" + this.properties
        .getProperty(keys.password.toString());
    this.isCheckParentPath = Boolean
        .parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(), "true"));
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #3
Source File: RuleBasedZooKeeperAclProvider.java    From helios with Apache License 2.0 6 votes vote down vote up
@Override
public List<ACL> getAclForPath(final String path) {
  // id -> permissions
  final Map<Id, Integer> matching = Maps.newHashMap();

  for (final Rule rule : rules) {
    if (rule.matches(path)) {
      final int existingPerms = matching.containsKey(rule.id) ? matching.get(rule.id) : 0;
      matching.put(rule.id, rule.perms | existingPerms);
    }
  }

  if (matching.isEmpty()) {
    return null;
  }

  final List<ACL> acls = Lists.newArrayList();
  for (final Map.Entry<Id, Integer> e : matching.entrySet()) {
    acls.add(new ACL(e.getValue(), e.getKey()));
  }

  return acls;
}
 
Example #4
Source File: LogSearchConfigZKHelper.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Get ACLs from a property (get the value then parse and transform it as ACL objects)
 * @param properties key/value pairs that needs to be parsed as ACLs
 * @return list of ACLs
 */
public static List<ACL> getAcls(Map<String, String> properties) {
  String aclStr = properties.get(ZK_ACLS_PROPERTY);
  if (StringUtils.isBlank(aclStr)) {
    return ZooDefs.Ids.OPEN_ACL_UNSAFE;
  }

  List<ACL> acls = new ArrayList<>();
  List<String> aclStrList = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(aclStr);
  for (String unparcedAcl : aclStrList) {
    String[] parts = unparcedAcl.split(":");
    if (parts.length == 3) {
      acls.add(new ACL(parsePermission(parts[2]), new Id(parts[0], parts[1])));
    }
  }
  return acls;
}
 
Example #5
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateSetupInProgressNode() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    CreateBuilder createBuilder = setupSetupInProgressPathMocks(aclList).getLeft();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(createBuilder).withACL(aclList);
    verify(createBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE,
            "id2".getBytes(Charsets.UTF_8));
}
 
Example #6
Source File: ZKManager.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
	zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
			.toString()), Integer.parseInt(this.properties
			.getProperty(keys.zkSessionTimeout.toString())),
			new Watcher() {
				public void process(WatchedEvent event) {
					sessionEvent(connectionLatch, event);
				}
			});
	String authString = this.properties.getProperty(keys.userName.toString())
			+ ":"+ this.properties.getProperty(keys.password.toString());
	this.isCheckParentPath = Boolean.parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(),"true"));
	zk.addAuthInfo("digest", authString.getBytes());
	acl.clear();
	acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
			DigestAuthenticationProvider.generateDigest(authString))));
	acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #7
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteSetupInProgressNodeAfterCompletion() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    DeleteBuilder deleteBuilder = setupSetupInProgressPathMocks(aclList).getRight();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(deleteBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE);
}
 
Example #8
Source File: TestModeledFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcl() throws NoSuchAlgorithmException
{
    List<ACL> aclList = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test"))));
    ModelSpec<TestModel> aclModelSpec = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()).withAclList(aclList).build();
    ModeledFramework<TestModel> client = ModeledFramework.wrap(async, aclModelSpec);
    complete(client.set(new TestModel("John", "Galt", "Galt's Gulch", 21, BigInteger.valueOf(1010101))));
    complete(client.update(new TestModel("John", "Galt", "Galt's Gulch", 54, BigInteger.valueOf(88))), (__, e) -> Assert.assertNotNull(e, "Should've gotten an auth failure"));

    try (CuratorFramework authCurator = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).authorization("digest", "test:test".getBytes()).build())
    {
        authCurator.start();
        ModeledFramework<TestModel> authClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(authCurator), aclModelSpec);
        complete(authClient.update(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))), (__, e) -> Assert.assertNull(e, "Should've succeeded"));
    }
}
 
Example #9
Source File: RemoteConfigurationMonitorTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private void validateKnoxConfigNodeACLs(List<ACL> expectedACLS, List<ACL> actualACLs) {
    assertEquals(expectedACLS.size(), actualACLs.size());
    int matchedCount = 0;
    for (ACL expected : expectedACLS) {
        for (ACL actual : actualACLs) {
            Id expectedId = expected.getId();
            Id actualId = actual.getId();
            if (actualId.getScheme().equals(expectedId.getScheme()) && actualId.getId().equals(expectedId.getId())) {
                matchedCount++;
                assertEquals(expected.getPerms(), actual.getPerms());
                break;
            }
        }
    }
    assertEquals("ACL mismatch despite being same quantity.", expectedACLS.size(), matchedCount);
}
 
Example #10
Source File: ZKRMStateStore.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
@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;
}
 
Example #11
Source File: CuratorClientService.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void setACL(String path, List<EntryACL> entryACLs) {
    // Translate the abstract ACLs into ZooKeeper ACLs
    List<ACL> delegateACLs = new ArrayList<>();
    for (EntryACL entryACL : entryACLs) {
        String scheme = entryACL.getType();
        String id = entryACL.getId();
        int permissions = 0;
        if (entryACL.canWrite()) {
            permissions = ZooDefs.Perms.ALL;
        } else if (entryACL.canRead()){
            permissions = ZooDefs.Perms.READ;
        }
        delegateACLs.add(new ACL(permissions, new Id(scheme, id)));
    }

    try {
        // Set the ACLs for the path
        delegate.setACL().withACL(delegateACLs).forPath(path);
    } catch (Exception e) {
        log.errorSettingEntryACL(path, e);
    }
}
 
Example #12
Source File: TestSecureRMRegistryOperations.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserHomedirsPermissionsRestricted() throws Throwable {
  // test that the /users/$user permissions are restricted
  RMRegistryOperationsService rmRegistryOperations =
      startRMRegistryOperations();
  // create Alice's dir, so it should have an ACL for Alice
  final String home = rmRegistryOperations.initUserRegistry(ALICE);
  List<ACL> acls = rmRegistryOperations.zkGetACLS(home);
  ACL aliceACL = null;
  for (ACL acl : acls) {
    LOG.info(RegistrySecurity.aclToString(acl));
    Id id = acl.getId();
    if (id.getScheme().equals(ZookeeperConfigOptions.SCHEME_SASL)
        && id.getId().startsWith(ALICE)) {

      aliceACL = acl;
      break;
    }
  }
  assertNotNull(aliceACL);
  assertEquals(RegistryAdminService.USER_HOMEDIR_ACL_PERMISSIONS,
      aliceACL.getPerms());
}
 
Example #13
Source File: Utils.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static List<ACL> getWorkerACL(Map conf) {
    // This is a work around to an issue with ZK where a sasl super user is not super unless there is an open SASL ACL
    // so we are trying to give the correct perms
    if (!isZkAuthenticationConfiguredTopology(conf)) {
        return null;
    }
    String stormZKUser = (String) conf.get(Config.STORM_ZOOKEEPER_SUPERACL);
    if (stormZKUser == null) {
        throw new IllegalArgumentException("Authentication is enabled but " + Config.STORM_ZOOKEEPER_SUPERACL + " is not set");
    }
    String[] split = stormZKUser.split(":", 2);
    if (split.length != 2) {
        throw new IllegalArgumentException(Config.STORM_ZOOKEEPER_SUPERACL +
                " does not appear to be in the form scheme:acl, i.e. sasl:storm-user");
    }
    ArrayList<ACL> ret = new ArrayList<>(ZooDefs.Ids.CREATOR_ALL_ACL);
    ret.add(new ACL(ZooDefs.Perms.ALL, new Id(split[0], split[1])));
    return ret;
}
 
Example #14
Source File: RegistrySecurity.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a string down to an ID, adding a realm if needed
 * @param idPair id:data tuple
 * @param realm realm to add
 * @return the ID.
 * @throws IllegalArgumentException if the idPair is invalid
 */
public Id parse(String idPair, String realm) {
  int firstColon = idPair.indexOf(':');
  int lastColon = idPair.lastIndexOf(':');
  if (firstColon == -1 || lastColon == -1 || firstColon != lastColon) {
    throw new IllegalArgumentException(
        "ACL '" + idPair + "' not of expected form scheme:id");
  }
  String scheme = idPair.substring(0, firstColon);
  String id = idPair.substring(firstColon + 1);
  if (id.endsWith("@")) {
    Preconditions.checkArgument(
        StringUtils.isNotEmpty(realm),
        "@ suffixed account but no realm %s", id);
    id = id + realm;
  }
  return new Id(scheme, id);
}
 
Example #15
Source File: SetupStepsTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateSetupInProgressNode() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    CreateBuilder createBuilder = setupSetupInProgressPathMocks(aclList).getLeft();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(createBuilder).withACL(aclList);
    verify(createBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE,
            "id2".getBytes(Charsets.UTF_8));
}
 
Example #16
Source File: SetupStepsTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteSetupInProgressNodeAfterCompletion() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    DeleteBuilder deleteBuilder = setupSetupInProgressPathMocks(aclList).getRight();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(deleteBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE);
}
 
Example #17
Source File: ZKRMStateStore.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
@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;
}
 
Example #18
Source File: ZKManager.java    From uncode-schedule with Apache License 2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
  zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
      .toString()), Integer.parseInt(this.properties
      .getProperty(keys.zkSessionTimeout.toString())),
      new Watcher() {
        public void process(WatchedEvent event) {
          sessionEvent(connectionLatch, event);
        }
      });
  String authString = this.properties.getProperty(keys.userName.toString())
      + ":" + this.properties.getProperty(keys.password.toString());
  zk.addAuthInfo("digest", authString.getBytes());
  acl.clear();
  acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
      DigestAuthenticationProvider.generateDigest(authString))));
  acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #19
Source File: ZookeeperUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @return
 */
public List<ACL> getCreateNodeAcls() {
    List<ACL> listAcls = new ArrayList<ACL>(3);
    try {
        Id id = new Id(PropertiesDynLoading.authScheme,
                DigestAuthenticationProvider.generateDigest(PropertiesDynLoading.accessKey));
        ACL acl = new ACL(Perms.CREATE, id);
        listAcls.add(acl);

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
        return Ids.OPEN_ACL_UNSAFE;
    }
    return listAcls;
}
 
Example #20
Source File: ZKUtil.java    From codes-scratch-zookeeper-netty with Apache License 2.0 6 votes vote down vote up
public static CuratorFramework create() {
    RetryNTimes retryPolicy = new RetryNTimes(5, 5000);
    String authString = Constants.ZK_USER_NAME + ":" + Constants.ZK_PASSWORD;
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(Constants.ZK_CONNECT_STRING)
                                                     .retryPolicy(retryPolicy)
                                                     .connectionTimeoutMs(Constants.ZOO_KEEPER_TIMEOUT)
                                                     .sessionTimeoutMs(Constants.ZOO_KEEPER_TIMEOUT * 3)
                                                     .authorization("digest", authString.getBytes()).build();
    try {
        acl.clear();
        acl.add(new ACL(ZooDefs.Perms.ALL,
                        new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
        acl.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        LOGGER.error("ZKUtil-->>create() error,", e);
    }
    return client;
}
 
Example #21
Source File: ZKManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
            .toString()), Integer.parseInt(this.properties
            .getProperty(keys.zkSessionTimeout.toString())),
            new Watcher() {
                public void process(WatchedEvent event) {
                    sessionEvent(connectionLatch, event);
                }
            });
    String authString = this.properties.getProperty(keys.userName.toString())
            + ":"+ this.properties.getProperty(keys.password.toString());
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
            DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example #22
Source File: RegistrySecurity.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a string down to an ID, adding a realm if needed
 * @param idPair id:data tuple
 * @param realm realm to add
 * @return the ID.
 * @throws IllegalArgumentException if the idPair is invalid
 */
public Id parse(String idPair, String realm) {
  int firstColon = idPair.indexOf(':');
  int lastColon = idPair.lastIndexOf(':');
  if (firstColon == -1 || lastColon == -1 || firstColon != lastColon) {
    throw new IllegalArgumentException(
        "ACL '" + idPair + "' not of expected form scheme:id");
  }
  String scheme = idPair.substring(0, firstColon);
  String id = idPair.substring(firstColon + 1);
  if (id.endsWith("@")) {
    Preconditions.checkArgument(
        StringUtils.isNotEmpty(realm),
        "@ suffixed account but no realm %s", id);
    id = id + realm;
  }
  return new Id(scheme, id);
}
 
Example #23
Source File: VMParamsAllAndReadonlyDigestZkACLProvider.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Note: only used for tests
 */
protected List<ACL> createACLsToAdd(boolean includeReadOnly,
                                    String digestAllUsername, String digestAllPassword,
                                    String digestReadonlyUsername, String digestReadonlyPassword) {

    try {
    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)
    if (!StringUtils.isEmpty(digestAllUsername) && !StringUtils.isEmpty(digestAllPassword)) {
      result.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(digestAllUsername + ":" + digestAllPassword))));
    }

    if (includeReadOnly) {
      // Besides that support for adding additional "READONLY"-acls for another user
      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 = ZooDefs.Ids.OPEN_ACL_UNSAFE;
    }
    
    return result;
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
}
 
Example #24
Source File: ZKUtil.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Parse comma separated list of ACL entries to secure generated nodes, e.g.
 * <code>sasl:hdfs/[email protected]:cdrwa,sasl:hdfs/[email protected]:cdrwa</code>
 *
 * @return ACL list
 * @throws {@link BadAclFormatException} if an ACL is invalid
 */
public static List<ACL> parseACLs(String aclString) throws
    BadAclFormatException {
  List<ACL> acl = Lists.newArrayList();
  if (aclString == null) {
    return acl;
  }
  
  List<String> aclComps = Lists.newArrayList(
      Splitter.on(',').omitEmptyStrings().trimResults()
      .split(aclString));
  for (String a : aclComps) {
    // from ZooKeeperMain private method
    int firstColon = a.indexOf(':');
    int lastColon = a.lastIndexOf(':');
    if (firstColon == -1 || lastColon == -1 || firstColon == lastColon) {
      throw new BadAclFormatException(
          "ACL '" + a + "' not of expected form scheme:id:perm");
    }

    ACL newAcl = new ACL();
    newAcl.setId(new Id(a.substring(0, firstColon), a.substring(
        firstColon + 1, lastColon)));
    newAcl.setPerms(getPermFromString(a.substring(lastColon + 1)));
    acl.add(newAcl);
  }
  
  return acl;
}
 
Example #25
Source File: SaslZkACLProvider.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected List<ACL> createNonSecurityACLsToAdd() {
  List<ACL> ret = new ArrayList<ACL>();
  ret.add(new ACL(ZooDefs.Perms.ALL, new Id("sasl", superUser)));
  ret.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE));
  return ret;
}
 
Example #26
Source File: ZookeeperManager.java    From chronus with Apache License 2.0 5 votes vote down vote up
private void connect() throws Exception {
    RetryPolicy retryPolicy = new RetryUntilElapsed(Integer.MAX_VALUE, 10);
    String userName = properties.getProperty(keys.userName.toString());
    String zkConnectString = properties.getProperty(keys.zkConnectString.toString());
    int zkSessionTimeout = Integer.parseInt(properties.getProperty(keys.zkSessionTimeout.toString()));
    int zkConnectionTimeout = Integer.parseInt(properties.getProperty(keys.zkConnectionTimeout.toString()));
    boolean isCheckParentPath = Boolean.parseBoolean(properties.getProperty(keys.isCheckParentPath.toString(), "true"));
    String authString = userName + ":" + properties.getProperty(keys.password.toString());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
    log.info("----------------------------开始创建ZK连接----------------------------");
    log.info("zkConnectString:{}", zkConnectString);
    log.info("zkSessionTimeout:{}", zkSessionTimeout);
    log.info("zkConnectionTimeout:{}", zkConnectionTimeout);
    log.info("isCheckParentPath:{}", isCheckParentPath);
    log.info("userName:{}", userName);

    curator = CuratorFrameworkFactory.builder().connectString(zkConnectString)
            .sessionTimeoutMs(zkSessionTimeout)
            .connectionTimeoutMs(zkConnectionTimeout)
            .retryPolicy(retryPolicy).authorization("digest", authString.getBytes())
            .aclProvider(new ACLProvider() {
                @Override
                public List<ACL> getDefaultAcl() {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }

                @Override
                public List<ACL> getAclForPath(String path) {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
            }).build();
    curator.start();
    log.info("----------------------------创建ZK连接成功----------------------------");
    this.isCheckParentPath = isCheckParentPath;
}
 
Example #27
Source File: CuratorACLProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SaslACLProvider(ZooKeeperClientConfig config) {

            if(!StringUtils.isEmpty(config.getAuthPrincipal())) {

                final String realm = config.getAuthPrincipal().substring(config.getAuthPrincipal().indexOf('@') + 1, config.getAuthPrincipal().length());
                final String[] user = config.getAuthPrincipal().substring(0, config.getAuthPrincipal().indexOf('@')).split("/");
                final String host = user.length == 2 ? user[1] : null;
                final String instance = user[0];
                final StringBuilder principal = new StringBuilder(instance);

                if (!config.getRemoveHostFromPrincipal().equalsIgnoreCase("true")) {
                    principal.append("/");
                    principal.append(host);
                }

                if (!config.getRemoveRealmFromPrincipal().equalsIgnoreCase("true")) {
                    principal.append("@");
                    principal.append(realm);
                }

                this.acls = Lists.newArrayList(new ACL(ZooDefs.Perms.ALL, new Id(SASL_AUTH_SCHEME, principal.toString())));
                this.acls.addAll(ZooDefs.Ids.READ_ACL_UNSAFE);

            }else{
                throw new IllegalArgumentException("No Kerberos Principal configured for use with SASL Authentication Scheme");
            }
        }
 
Example #28
Source File: RuleBasedZooKeeperAclProviderTest.java    From helios with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoMatchingRules() {
  final Id id = new Id("some_scheme", "id");
  final RuleBasedZooKeeperAclProvider aclProvider = RuleBasedZooKeeperAclProvider.builder()
      .rule("/foo/bar/baz", WRITE, id)
      .build();

  assertNull(aclProvider.getAclForPath("/foo/bar"));
}
 
Example #29
Source File: ActiveInstanceStateTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedPathIsCreatedWithRightACLIfNotExists() throws Exception {

    when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]");
    when(configuration.getString(
            HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);


    when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(curatorFramework.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(getPath())).thenReturn(null);

    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(curatorFramework.create()).thenReturn(createBuilder);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
    ACL expectedAcl = new ACL(ZooDefs.Perms.ALL, new Id("sasl", "[email protected]"));
    when(createBuilder.
            withACL(Arrays.asList(new ACL[]{expectedAcl}))).thenReturn(createBuilder);

    SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
    when(curatorFramework.setData()).thenReturn(setDataBuilder);

    ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
    activeInstanceState.update("id1");

    verify(createBuilder).forPath(getPath());
}
 
Example #30
Source File: CuratorClientService.java    From knox with Apache License 2.0 5 votes vote down vote up
SASLOwnerACLProvider(boolean isKerberos) {
    if(isKerberos) {
        saslACL.add(new ACL(ZooDefs.Perms.ALL, new Id("sasl", "knox")));
    } else {
        this.saslACL.addAll(ZooDefs.Ids.CREATOR_ALL_ACL); // All permissions for any authenticated user
    }
}