diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java b/gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java new file mode 100644 index 000000000000..748eaba2ab4c --- /dev/null +++ b/gcloud-java-core/src/main/java/com/google/gcloud/IamPolicy.java @@ -0,0 +1,256 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Base class for Identity and Access Management (IAM) policies. IAM policies are used to specify + * access settings for Cloud Platform resources. A policy is a map of bindings. A binding assigns + * a set of identities to a role, where the identities can be user accounts, Google groups, Google + * domains, and service accounts. A role is a named list of permissions defined by IAM. + * + * @param the data type of roles (should be serializable) + * @see Policy + */ +public abstract class IamPolicy implements Serializable { + + private static final long serialVersionUID = 1114489978726897720L; + + private final Map> bindings; + private final String etag; + private final Integer version; + + /** + * Builder for an IAM Policy. + * + * @param the data type of roles + * @param the subclass extending this abstract builder + */ + public abstract static class Builder> { + + private final Map> bindings = new HashMap<>(); + private String etag; + private Integer version; + + /** + * Constructor for IAM Policy builder. + */ + protected Builder() {} + + /** + * Replaces the builder's map of bindings with the given map of bindings. + * + * @throws IllegalArgumentException if the provided map is null or contain any null values + */ + public final B bindings(Map> bindings) { + checkArgument(bindings != null, "The provided map of bindings cannot be null."); + for (Map.Entry> binding : bindings.entrySet()) { + verifyBinding(binding.getKey(), binding.getValue()); + } + this.bindings.clear(); + for (Map.Entry> binding : bindings.entrySet()) { + this.bindings.put(binding.getKey(), new HashSet(binding.getValue())); + } + return self(); + } + + /** + * Adds a binding to the policy. + * + * @throws IllegalArgumentException if the policy already contains a binding with the same role + * or if the role or any identities are null + */ + public final B addBinding(R role, Set identities) { + verifyBinding(role, identities); + checkArgument(!bindings.containsKey(role), + "The policy already contains a binding with the role " + role.toString() + "."); + bindings.put(role, new HashSet(identities)); + return self(); + } + + /** + * Adds a binding to the policy. + * + * @throws IllegalArgumentException if the policy already contains a binding with the same role + * or if the role or any identities are null + */ + public final B addBinding(R role, Identity first, Identity... others) { + HashSet identities = new HashSet<>(); + identities.add(first); + identities.addAll(Arrays.asList(others)); + return addBinding(role, identities); + } + + private void verifyBinding(R role, Collection identities) { + checkArgument(role != null, "The role cannot be null."); + verifyIdentities(identities); + } + + private void verifyIdentities(Collection identities) { + checkArgument(identities != null, "A role cannot be assigned to a null set of identities."); + checkArgument(!identities.contains(null), "Null identities are not permitted."); + } + + /** + * Removes the binding associated with the specified role. + */ + public final B removeBinding(R role) { + bindings.remove(role); + return self(); + } + + /** + * Adds one or more identities to an existing binding. + * + * @throws IllegalArgumentException if the policy doesn't contain a binding with the specified + * role or any identities are null + */ + public final B addIdentity(R role, Identity first, Identity... others) { + checkArgument(bindings.containsKey(role), + "The policy doesn't contain the role " + role.toString() + "."); + List toAdd = new LinkedList<>(); + toAdd.add(first); + toAdd.addAll(Arrays.asList(others)); + verifyIdentities(toAdd); + bindings.get(role).addAll(toAdd); + return self(); + } + + /** + * Removes one or more identities from an existing binding. + * + * @throws IllegalArgumentException if the policy doesn't contain a binding with the specified + * role + */ + public final B removeIdentity(R role, Identity first, Identity... others) { + checkArgument(bindings.containsKey(role), + "The policy doesn't contain the role " + role.toString() + "."); + bindings.get(role).remove(first); + bindings.get(role).removeAll(Arrays.asList(others)); + return self(); + } + + /** + * Sets the policy's etag. + * + *

Etags are used for optimistic concurrency control as a way to help prevent simultaneous + * updates of a policy from overwriting each other. It is strongly suggested that systems make + * use of the etag in the read-modify-write cycle to perform policy updates in order to avoid + * race conditions. An etag is returned in the response to getIamPolicy, and systems are + * expected to put that etag in the request to setIamPolicy to ensure that their change will be + * applied to the same version of the policy. If no etag is provided in the call to + * setIamPolicy, then the existing policy is overwritten blindly. + */ + protected final B etag(String etag) { + this.etag = etag; + return self(); + } + + /** + * Sets the version of the policy. The default version is 0, meaning only the "owner", "editor", + * and "viewer" roles are permitted. If the version is 1, you may also use other roles. + */ + protected final B version(Integer version) { + this.version = version; + return self(); + } + + @SuppressWarnings("unchecked") + private B self() { + return (B) this; + } + + public abstract IamPolicy build(); + } + + protected IamPolicy(Builder> builder) { + ImmutableMap.Builder> bindingsBuilder = ImmutableMap.builder(); + for (Map.Entry> binding : builder.bindings.entrySet()) { + bindingsBuilder.put(binding.getKey(), ImmutableSet.copyOf(binding.getValue())); + } + this.bindings = bindingsBuilder.build(); + this.etag = builder.etag; + this.version = builder.version; + } + + /** + * Returns a builder containing the properties of this IAM Policy. + */ + public abstract Builder> toBuilder(); + + /** + * The map of bindings that comprises the policy. + */ + public Map> bindings() { + return bindings; + } + + /** + * The policy's etag. + * + *

Etags are used for optimistic concurrency control as a way to help prevent simultaneous + * updates of a policy from overwriting each other. It is strongly suggested that systems make + * use of the etag in the read-modify-write cycle to perform policy updates in order to avoid + * race conditions. An etag is returned in the response to getIamPolicy, and systems are + * expected to put that etag in the request to setIamPolicy to ensure that their change will be + * applied to the same version of the policy. If no etag is provided in the call to + * setIamPolicy, then the existing policy is overwritten blindly. + */ + public String etag() { + return etag; + } + + /** + * Sets the version of the policy. The default version is 0, meaning only the "owner", "editor", + * and "viewer" roles are permitted. If the version is 1, you may also use other roles. + */ + public Integer version() { + return version; + } + + @Override + public final int hashCode() { + return Objects.hash(getClass(), bindings, etag, version); + } + + @Override + public final boolean equals(Object obj) { + if (obj == null || !getClass().equals(obj.getClass())) { + return false; + } + @SuppressWarnings("rawtypes") + IamPolicy other = (IamPolicy) obj; + return Objects.equals(bindings, other.bindings()) + && Objects.equals(etag, other.etag()) + && Objects.equals(version, other.version()); + } +} diff --git a/gcloud-java-core/src/main/java/com/google/gcloud/Identity.java b/gcloud-java-core/src/main/java/com/google/gcloud/Identity.java new file mode 100644 index 000000000000..d1644198f759 --- /dev/null +++ b/gcloud-java-core/src/main/java/com/google/gcloud/Identity.java @@ -0,0 +1,225 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.CaseFormat; + +import java.io.Serializable; +import java.util.Objects; + +/** + * An identity in an {@link IamPolicy}. The following types of identities are permitted in IAM + * policies: + *

    + *
  • Google account + *
  • Service account + *
  • Google group + *
  • Google Apps domain + *
+ * + *

There are also two special identities that represent all users and all Google-authenticated + * accounts. + * + * @see Concepts + * related to identity + */ +public final class Identity implements Serializable { + + private static final long serialVersionUID = -8181841964597657446L; + + private final Type type; + private final String id; + + /** + * The types of IAM identities. + */ + public enum Type { + + /** + * Represents anyone who is on the internet; with or without a Google account. + */ + ALL_USERS, + + /** + * Represents anyone who is authenticated with a Google account or a service account. + */ + ALL_AUTHENTICATED_USERS, + + /** + * Represents a specific Google account. + */ + USER, + + /** + * Represents a service account. + */ + SERVICE_ACCOUNT, + + /** + * Represents a Google group. + */ + GROUP, + + /** + * Represents all the users of a Google Apps domain name. + */ + DOMAIN + } + + private Identity(Type type, String id) { + this.type = type; + this.id = id; + } + + public Type type() { + return type; + } + + /** + * Returns the string identifier for this identity. The id corresponds to: + *

    + *
  • email address (for identities of type {@code USER}, {@code SERVICE_ACCOUNT}, and + * {@code GROUP}) + *
  • domain (for identities of type {@code DOMAIN}) + *
  • {@code null} (for identities of type {@code ALL_USERS} and + * {@code ALL_AUTHENTICATED_USERS}) + *
+ */ + public String id() { + return id; + } + + /** + * Returns a new identity representing anyone who is on the internet; with or without a Google + * account. + */ + public static Identity allUsers() { + return new Identity(Type.ALL_USERS, null); + } + + /** + * Returns a new identity representing anyone who is authenticated with a Google account or a + * service account. + */ + public static Identity allAuthenticatedUsers() { + return new Identity(Type.ALL_AUTHENTICATED_USERS, null); + } + + /** + * Returns a new user identity. + * + * @param email An email address that represents a specific Google account. For example, + * alice@gmail.com or joe@example.com. + */ + public static Identity user(String email) { + return new Identity(Type.USER, checkNotNull(email)); + } + + /** + * Returns a new service account identity. + * + * @param email An email address that represents a service account. For example, + * my-other-app@appspot.gserviceaccount.com. + */ + public static Identity serviceAccount(String email) { + return new Identity(Type.SERVICE_ACCOUNT, checkNotNull(email)); + } + + /** + * Returns a new group identity. + * + * @param email An email address that represents a Google group. For example, + * admins@example.com. + */ + public static Identity group(String email) { + return new Identity(Type.GROUP, checkNotNull(email)); + } + + /** + * Returns a new domain identity. + * + * @param domain A Google Apps domain name that represents all the users of that domain. For + * example, google.com or example.com. + */ + public static Identity domain(String domain) { + return new Identity(Type.DOMAIN, checkNotNull(domain)); + } + + @Override + public int hashCode() { + return Objects.hash(id, type); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Identity)) { + return false; + } + Identity other = (Identity) obj; + return Objects.equals(id, other.id()) && Objects.equals(type, other.type()); + } + + /** + * Returns the string value associated with the identity. Used primarily for converting from + * {@code Identity} objects to strings for protobuf-generated policies. + */ + public String strValue() { + switch (type) { + case ALL_USERS: + return "allUsers"; + case ALL_AUTHENTICATED_USERS: + return "allAuthenticatedUsers"; + case USER: + return "user:" + id; + case SERVICE_ACCOUNT: + return "serviceAccount:" + id; + case GROUP: + return "group:" + id; + case DOMAIN: + return "domain:" + id; + default: + throw new IllegalStateException("Unexpected identity type: " + type); + } + } + + /** + * Converts a string to an {@code Identity}. Used primarily for converting protobuf-generated + * policy identities to {@code Identity} objects. + */ + public static Identity valueOf(String identityStr) { + String[] info = identityStr.split(":"); + Type type = Type.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, info[0])); + switch (type) { + case ALL_USERS: + return Identity.allUsers(); + case ALL_AUTHENTICATED_USERS: + return Identity.allAuthenticatedUsers(); + case USER: + return Identity.user(info[1]); + case SERVICE_ACCOUNT: + return Identity.serviceAccount(info[1]); + case GROUP: + return Identity.group(info[1]); + case DOMAIN: + return Identity.domain(info[1]); + default: + throw new IllegalStateException("Unexpected identity type " + type); + } + } +} diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java b/gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java new file mode 100644 index 000000000000..db0935c4766d --- /dev/null +++ b/gcloud-java-core/src/test/java/com/google/gcloud/IamPolicyTest.java @@ -0,0 +1,180 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +import org.junit.Test; + +import java.util.Map; +import java.util.Set; + +public class IamPolicyTest { + + private static final Identity ALL_USERS = Identity.allUsers(); + private static final Identity ALL_AUTH_USERS = Identity.allAuthenticatedUsers(); + private static final Identity USER = Identity.user("abc@gmail.com"); + private static final Identity SERVICE_ACCOUNT = + Identity.serviceAccount("service-account@gmail.com"); + private static final Identity GROUP = Identity.group("group@gmail.com"); + private static final Identity DOMAIN = Identity.domain("google.com"); + private static final Map> BINDINGS = ImmutableMap.of( + "viewer", + ImmutableSet.of(USER, SERVICE_ACCOUNT, ALL_USERS), + "editor", + ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN)); + private static final PolicyImpl SIMPLE_POLICY = PolicyImpl.builder() + .addBinding("viewer", ImmutableSet.of(USER, SERVICE_ACCOUNT, ALL_USERS)) + .addBinding("editor", ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN)) + .build(); + private static final PolicyImpl FULL_POLICY = + new PolicyImpl.Builder(SIMPLE_POLICY.bindings(), "etag", 1).build(); + + static class PolicyImpl extends IamPolicy { + + static class Builder extends IamPolicy.Builder { + + private Builder() {} + + private Builder(Map> bindings, String etag, Integer version) { + bindings(bindings).etag(etag).version(version); + } + + @Override + public PolicyImpl build() { + return new PolicyImpl(this); + } + } + + PolicyImpl(Builder builder) { + super(builder); + } + + @Override + public Builder toBuilder() { + return new Builder(bindings(), etag(), version()); + } + + static Builder builder() { + return new Builder(); + } + } + + @Test + public void testBuilder() { + assertEquals(BINDINGS, FULL_POLICY.bindings()); + assertEquals("etag", FULL_POLICY.etag()); + assertEquals(1, FULL_POLICY.version().intValue()); + Map> editorBinding = + ImmutableMap.>builder().put("editor", BINDINGS.get("editor")).build(); + PolicyImpl policy = FULL_POLICY.toBuilder().bindings(editorBinding).build(); + assertEquals(editorBinding, policy.bindings()); + assertEquals("etag", policy.etag()); + assertEquals(1, policy.version().intValue()); + policy = SIMPLE_POLICY.toBuilder().removeBinding("editor").build(); + assertEquals(ImmutableMap.of("viewer", BINDINGS.get("viewer")), policy.bindings()); + assertNull(policy.etag()); + assertNull(policy.version()); + policy = policy.toBuilder() + .removeIdentity("viewer", USER, ALL_USERS) + .addIdentity("viewer", DOMAIN, GROUP) + .build(); + assertEquals(ImmutableMap.of("viewer", ImmutableSet.of(SERVICE_ACCOUNT, DOMAIN, GROUP)), + policy.bindings()); + assertNull(policy.etag()); + assertNull(policy.version()); + policy = PolicyImpl.builder().addBinding("owner", USER, SERVICE_ACCOUNT).build(); + assertEquals( + ImmutableMap.of("owner", ImmutableSet.of(USER, SERVICE_ACCOUNT)), policy.bindings()); + assertNull(policy.etag()); + assertNull(policy.version()); + try { + SIMPLE_POLICY.toBuilder().addBinding("viewer", USER); + fail("Should have failed due to duplicate role."); + } catch (IllegalArgumentException e) { + assertEquals("The policy already contains a binding with the role viewer.", e.getMessage()); + } + try { + SIMPLE_POLICY.toBuilder().addBinding("editor", ImmutableSet.of(USER)); + fail("Should have failed due to duplicate role."); + } catch (IllegalArgumentException e) { + assertEquals("The policy already contains a binding with the role editor.", e.getMessage()); + } + } + + @Test + public void testEqualsHashCode() { + assertNotNull(FULL_POLICY); + PolicyImpl emptyPolicy = PolicyImpl.builder().build(); + AnotherPolicyImpl anotherPolicy = new AnotherPolicyImpl.Builder().build(); + assertNotEquals(emptyPolicy, anotherPolicy); + assertNotEquals(emptyPolicy.hashCode(), anotherPolicy.hashCode()); + assertNotEquals(FULL_POLICY, SIMPLE_POLICY); + assertNotEquals(FULL_POLICY.hashCode(), SIMPLE_POLICY.hashCode()); + PolicyImpl copy = SIMPLE_POLICY.toBuilder().build(); + assertEquals(SIMPLE_POLICY, copy); + assertEquals(SIMPLE_POLICY.hashCode(), copy.hashCode()); + } + + @Test + public void testBindings() { + assertTrue(PolicyImpl.builder().build().bindings().isEmpty()); + assertEquals(BINDINGS, SIMPLE_POLICY.bindings()); + } + + @Test + public void testEtag() { + assertNull(SIMPLE_POLICY.etag()); + assertEquals("etag", FULL_POLICY.etag()); + } + + @Test + public void testVersion() { + assertNull(SIMPLE_POLICY.version()); + assertEquals(1, FULL_POLICY.version().intValue()); + } + + static class AnotherPolicyImpl extends IamPolicy { + + static class Builder extends IamPolicy.Builder { + + private Builder() {} + + @Override + public AnotherPolicyImpl build() { + return new AnotherPolicyImpl(this); + } + } + + AnotherPolicyImpl(Builder builder) { + super(builder); + } + + @Override + public Builder toBuilder() { + return new Builder(); + } + } +} diff --git a/gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java b/gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java new file mode 100644 index 000000000000..828f1c839431 --- /dev/null +++ b/gcloud-java-core/src/test/java/com/google/gcloud/IdentityTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +public class IdentityTest { + + private static final Identity ALL_USERS = Identity.allUsers(); + private static final Identity ALL_AUTH_USERS = Identity.allAuthenticatedUsers(); + private static final Identity USER = Identity.user("abc@gmail.com"); + private static final Identity SERVICE_ACCOUNT = + Identity.serviceAccount("service-account@gmail.com"); + private static final Identity GROUP = Identity.group("group@gmail.com"); + private static final Identity DOMAIN = Identity.domain("google.com"); + + @Test + public void testAllUsers() { + assertEquals(Identity.Type.ALL_USERS, ALL_USERS.type()); + assertNull(ALL_USERS.id()); + } + + @Test + public void testAllAuthenticatedUsers() { + assertEquals(Identity.Type.ALL_AUTHENTICATED_USERS, ALL_AUTH_USERS.type()); + assertNull(ALL_AUTH_USERS.id()); + } + + @Test + public void testUser() { + assertEquals(Identity.Type.USER, USER.type()); + assertEquals("abc@gmail.com", USER.id()); + } + + @Test(expected = NullPointerException.class) + public void testUserNullEmail() { + Identity.user(null); + } + + @Test + public void testServiceAccount() { + assertEquals(Identity.Type.SERVICE_ACCOUNT, SERVICE_ACCOUNT.type()); + assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.id()); + } + + @Test(expected = NullPointerException.class) + public void testServiceAccountNullEmail() { + Identity.serviceAccount(null); + } + + @Test + public void testGroup() { + assertEquals(Identity.Type.GROUP, GROUP.type()); + assertEquals("group@gmail.com", GROUP.id()); + } + + @Test(expected = NullPointerException.class) + public void testGroupNullEmail() { + Identity.group(null); + } + + @Test + public void testDomain() { + assertEquals(Identity.Type.DOMAIN, DOMAIN.type()); + assertEquals("google.com", DOMAIN.id()); + } + + @Test(expected = NullPointerException.class) + public void testDomainNullId() { + Identity.domain(null); + } + + @Test + public void testIdentityToAndFromPb() { + compareIdentities(ALL_USERS, Identity.valueOf(ALL_USERS.strValue())); + compareIdentities(ALL_AUTH_USERS, Identity.valueOf(ALL_AUTH_USERS.strValue())); + compareIdentities(USER, Identity.valueOf(USER.strValue())); + compareIdentities(SERVICE_ACCOUNT, Identity.valueOf(SERVICE_ACCOUNT.strValue())); + compareIdentities(GROUP, Identity.valueOf(GROUP.strValue())); + compareIdentities(DOMAIN, Identity.valueOf(DOMAIN.strValue())); + } + + private void compareIdentities(Identity expected, Identity actual) { + assertEquals(expected, actual); + assertEquals(expected.type(), actual.type()); + assertEquals(expected.id(), actual.id()); + } +} diff --git a/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Policy.java b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Policy.java new file mode 100644 index 000000000000..0d7118dcbbd7 --- /dev/null +++ b/gcloud-java-resourcemanager/src/main/java/com/google/gcloud/resourcemanager/Policy.java @@ -0,0 +1,164 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.resourcemanager; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.CaseFormat; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.gcloud.IamPolicy; +import com.google.gcloud.Identity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * An Identity and Access Management (IAM) policy for a project. IAM policies are used to specify + * access settings for Cloud Platform resources. A policy is a map of bindings. A binding assigns + * a set of identities to a role, where the identities can be user accounts, Google groups, Google + * domains, and service accounts. A role is a named list of permissions defined by IAM. Policies set + * at the project level control access both to the project and to resources associated with the + * project. + * + * @see Policy + */ +public class Policy extends IamPolicy { + + private static final long serialVersionUID = -5573557282693961850L; + + /** + * Represents legacy roles in an IAM Policy. + */ + public enum Role { + + /** + * Permissions for read-only actions that preserve state. + */ + VIEWER("roles/viewer"), + + /** + * All viewer permissions and permissions for actions that modify state. + */ + EDITOR("roles/editor"), + + /** + * All editor permissions and permissions for the following actions: + *
    + *
  • Manage access control for a resource. + *
  • Set up billing (for a project). + *
+ */ + OWNER("roles/owner"); + + private String strValue; + + private Role(String strValue) { + this.strValue = strValue; + } + + String strValue() { + return strValue; + } + + static Role fromStr(String roleStr) { + return Role.valueOf(CaseFormat.LOWER_CAMEL.to( + CaseFormat.UPPER_UNDERSCORE, roleStr.substring("roles/".length()))); + } + } + + /** + * Builder for an IAM Policy. + */ + public static class Builder extends IamPolicy.Builder { + + private Builder() {} + + @VisibleForTesting + Builder(Map> bindings, String etag, Integer version) { + bindings(bindings).etag(etag).version(version); + } + + @Override + public Policy build() { + return new Policy(this); + } + } + + private Policy(Builder builder) { + super(builder); + } + + public static Builder builder() { + return new Builder(); + } + + @Override + public Builder toBuilder() { + return new Builder(bindings(), etag(), version()); + } + + com.google.api.services.cloudresourcemanager.model.Policy toPb() { + com.google.api.services.cloudresourcemanager.model.Policy policyPb = + new com.google.api.services.cloudresourcemanager.model.Policy(); + List bindingPbList = + new LinkedList<>(); + for (Map.Entry> binding : bindings().entrySet()) { + com.google.api.services.cloudresourcemanager.model.Binding bindingPb = + new com.google.api.services.cloudresourcemanager.model.Binding(); + bindingPb.setRole(binding.getKey().strValue()); + bindingPb.setMembers( + Lists.transform( + new ArrayList<>(binding.getValue()), + new Function() { + @Override + public String apply(Identity identity) { + return identity.strValue(); + } + })); + bindingPbList.add(bindingPb); + } + policyPb.setBindings(bindingPbList); + policyPb.setEtag(etag()); + policyPb.setVersion(version()); + return policyPb; + } + + static Policy fromPb( + com.google.api.services.cloudresourcemanager.model.Policy policyPb) { + Map> bindings = new HashMap<>(); + for (com.google.api.services.cloudresourcemanager.model.Binding bindingPb : + policyPb.getBindings()) { + bindings.put( + Role.fromStr(bindingPb.getRole()), + ImmutableSet.copyOf( + Lists.transform( + bindingPb.getMembers(), + new Function() { + @Override + public Identity apply(String identityPb) { + return Identity.valueOf(identityPb); + } + }))); + } + return new Policy.Builder(bindings, policyPb.getEtag(), policyPb.getVersion()).build(); + } +} diff --git a/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/PolicyTest.java b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/PolicyTest.java new file mode 100644 index 000000000000..05d1b85bdbed --- /dev/null +++ b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/PolicyTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gcloud.resourcemanager; + +import static org.junit.Assert.assertEquals; + +import com.google.common.collect.ImmutableSet; +import com.google.gcloud.Identity; + +import org.junit.Test; + +public class PolicyTest { + + private static final Identity ALL_USERS = Identity.allUsers(); + private static final Identity ALL_AUTH_USERS = Identity.allAuthenticatedUsers(); + private static final Identity USER = Identity.user("abc@gmail.com"); + private static final Identity SERVICE_ACCOUNT = + Identity.serviceAccount("service-account@gmail.com"); + private static final Identity GROUP = Identity.group("group@gmail.com"); + private static final Identity DOMAIN = Identity.domain("google.com"); + private static final Policy SIMPLE_POLICY = Policy.builder() + .addBinding(Policy.Role.VIEWER, ImmutableSet.of(USER, SERVICE_ACCOUNT, ALL_USERS)) + .addBinding(Policy.Role.EDITOR, ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN)) + .build(); + private static final Policy FULL_POLICY = + new Policy.Builder(SIMPLE_POLICY.bindings(), "etag", 1).build(); + + @Test + public void testIamPolicyToBuilder() { + assertEquals(FULL_POLICY, FULL_POLICY.toBuilder().build()); + assertEquals(SIMPLE_POLICY, SIMPLE_POLICY.toBuilder().build()); + } + + @Test + public void testPolicyToAndFromPb() { + assertEquals(FULL_POLICY, Policy.fromPb(FULL_POLICY.toPb())); + assertEquals(SIMPLE_POLICY, Policy.fromPb(SIMPLE_POLICY.toPb())); + } +} diff --git a/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/SerializationTest.java b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/SerializationTest.java index 497de880254a..35b72ae1713f 100644 --- a/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/SerializationTest.java +++ b/gcloud-java-resourcemanager/src/test/java/com/google/gcloud/resourcemanager/SerializationTest.java @@ -20,6 +20,8 @@ import static org.junit.Assert.assertNotSame; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.gcloud.Identity; import com.google.gcloud.PageImpl; import com.google.gcloud.RetryParams; @@ -53,6 +55,9 @@ public class SerializationTest { ResourceManager.ProjectGetOption.fields(ResourceManager.ProjectField.NAME); private static final ResourceManager.ProjectListOption PROJECT_LIST_OPTION = ResourceManager.ProjectListOption.filter("name:*"); + private static final Policy POLICY = Policy.builder() + .addBinding(Policy.Role.VIEWER, ImmutableSet.of(Identity.user("abc@gmail.com"))) + .build(); @Test public void testServiceOptions() throws Exception { @@ -70,7 +75,7 @@ public void testServiceOptions() throws Exception { @Test public void testModelAndRequests() throws Exception { Serializable[] objects = {PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, PROJECT, PAGE_RESULT, - PROJECT_GET_OPTION, PROJECT_LIST_OPTION}; + PROJECT_GET_OPTION, PROJECT_LIST_OPTION, POLICY}; for (Serializable obj : objects) { Object copy = serializeAndDeserialize(obj); assertEquals(obj, obj);