1 // Copyright 2016 Google LLC
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // Package iam supports the resource-specific operations of Google Cloud
16 // IAM (Identity and Access Management) for the Google Cloud Libraries.
17 // See https://cloud.google.com/iam for more about IAM.
19 // Users of the Google Cloud Libraries will typically not use this package
20 // directly. Instead they will begin with some resource that supports IAM, like
21 // a pubsub topic, and call its IAM method to get a Handle for that resource.
29 gax "github.com/googleapis/gax-go/v2"
30 pb "google.golang.org/genproto/googleapis/iam/v1"
31 "google.golang.org/grpc"
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/metadata"
36 // client abstracts the IAMPolicy API to allow multiple implementations.
37 type client interface {
38 Get(ctx context.Context, resource string) (*pb.Policy, error)
39 Set(ctx context.Context, resource string, p *pb.Policy) error
40 Test(ctx context.Context, resource string, perms []string) ([]string, error)
43 // grpcClient implements client for the standard gRPC-based IAMPolicy service.
44 type grpcClient struct {
48 var withRetry = gax.WithRetry(func() gax.Retryer {
49 return gax.OnCodes([]codes.Code{
50 codes.DeadlineExceeded,
53 Initial: 100 * time.Millisecond,
54 Max: 60 * time.Second,
59 func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) {
61 md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
62 ctx = insertMetadata(ctx, md)
64 err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
66 proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{Resource: resource})
75 func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) error {
76 md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
77 ctx = insertMetadata(ctx, md)
79 return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
80 _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{
88 func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) {
89 var res *pb.TestIamPermissionsResponse
90 md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
91 ctx = insertMetadata(ctx, md)
93 err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
95 res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{
104 return res.Permissions, nil
107 // A Handle provides IAM operations for a resource.
113 // InternalNewHandle is for use by the Google Cloud Libraries only.
115 // InternalNewHandle returns a Handle for resource.
116 // The conn parameter refers to a server that must support the IAMPolicy service.
117 func InternalNewHandle(conn *grpc.ClientConn, resource string) *Handle {
118 return InternalNewHandleGRPCClient(pb.NewIAMPolicyClient(conn), resource)
121 // InternalNewHandleGRPCClient is for use by the Google Cloud Libraries only.
123 // InternalNewHandleClient returns a Handle for resource using the given
124 // grpc service that implements IAM as a mixin
125 func InternalNewHandleGRPCClient(c pb.IAMPolicyClient, resource string) *Handle {
126 return InternalNewHandleClient(&grpcClient{c: c}, resource)
129 // InternalNewHandleClient is for use by the Google Cloud Libraries only.
131 // InternalNewHandleClient returns a Handle for resource using the given
132 // client implementation.
133 func InternalNewHandleClient(c client, resource string) *Handle {
140 // Policy retrieves the IAM policy for the resource.
141 func (h *Handle) Policy(ctx context.Context) (*Policy, error) {
142 proto, err := h.c.Get(ctx, h.resource)
146 return &Policy{InternalProto: proto}, nil
149 // SetPolicy replaces the resource's current policy with the supplied Policy.
151 // If policy was created from a prior call to Get, then the modification will
152 // only succeed if the policy has not changed since the Get.
153 func (h *Handle) SetPolicy(ctx context.Context, policy *Policy) error {
154 return h.c.Set(ctx, h.resource, policy.InternalProto)
157 // TestPermissions returns the subset of permissions that the caller has on the resource.
158 func (h *Handle) TestPermissions(ctx context.Context, permissions []string) ([]string, error) {
159 return h.c.Test(ctx, h.resource, permissions)
162 // A RoleName is a name representing a collection of permissions.
165 // Common role names.
167 Owner RoleName = "roles/owner"
168 Editor RoleName = "roles/editor"
169 Viewer RoleName = "roles/viewer"
173 // AllUsers is a special member that denotes all users, even unauthenticated ones.
174 AllUsers = "allUsers"
176 // AllAuthenticatedUsers is a special member that denotes all authenticated users.
177 AllAuthenticatedUsers = "allAuthenticatedUsers"
180 // A Policy is a list of Bindings representing roles
181 // granted to members.
183 // The zero Policy is a valid policy with no bindings.
185 // TODO(jba): when type aliases are available, put Policy into an internal package
186 // and provide an exported alias here.
188 // This field is exported for use by the Google Cloud Libraries only.
189 // It may become unexported in a future release.
190 InternalProto *pb.Policy
193 // Members returns the list of members with the supplied role.
194 // The return value should not be modified. Use Add and Remove
195 // to modify the members of a role.
196 func (p *Policy) Members(r RoleName) []string {
204 // HasRole reports whether member has role r.
205 func (p *Policy) HasRole(member string, r RoleName) bool {
206 return memberIndex(member, p.binding(r)) >= 0
209 // Add adds member member to role r if it is not already present.
210 // A new binding is created if there is no binding for the role.
211 func (p *Policy) Add(member string, r RoleName) {
214 if p.InternalProto == nil {
215 p.InternalProto = &pb.Policy{}
217 p.InternalProto.Bindings = append(p.InternalProto.Bindings, &pb.Binding{
219 Members: []string{member},
223 if memberIndex(member, b) < 0 {
224 b.Members = append(b.Members, member)
229 // Remove removes member from role r if it is present.
230 func (p *Policy) Remove(member string, r RoleName) {
231 bi := p.bindingIndex(r)
235 bindings := p.InternalProto.Bindings
237 mi := memberIndex(member, b)
241 // Order doesn't matter for bindings or members, so to remove, move the last item
242 // into the removed spot and shrink the slice.
243 if len(b.Members) == 1 {
245 last := len(bindings) - 1
246 bindings[bi] = bindings[last]
248 p.InternalProto.Bindings = bindings[:last]
252 // TODO(jba): worry about multiple copies of m?
253 last := len(b.Members) - 1
254 b.Members[mi] = b.Members[last]
256 b.Members = b.Members[:last]
259 // Roles returns the names of all the roles that appear in the Policy.
260 func (p *Policy) Roles() []RoleName {
261 if p.InternalProto == nil {
265 for _, b := range p.InternalProto.Bindings {
266 rns = append(rns, RoleName(b.Role))
271 // binding returns the Binding for the suppied role, or nil if there isn't one.
272 func (p *Policy) binding(r RoleName) *pb.Binding {
273 i := p.bindingIndex(r)
277 return p.InternalProto.Bindings[i]
280 func (p *Policy) bindingIndex(r RoleName) int {
281 if p.InternalProto == nil {
284 for i, b := range p.InternalProto.Bindings {
285 if b.Role == string(r) {
292 // memberIndex returns the index of m in b's Members, or -1 if not found.
293 func memberIndex(m string, b *pb.Binding) int {
297 for i, mm := range b.Members {
305 // insertMetadata inserts metadata into the given context
306 func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
307 out, _ := metadata.FromOutgoingContext(ctx)
309 for _, md := range mds {
310 for k, v := range md {
311 out[k] = append(out[k], v...)
314 return metadata.NewOutgoingContext(ctx, out)