You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

316 lines
9.1 KiB

  1. // Copyright 2016 Google LLC
  2. //
  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
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  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.
  14. // Package iam supports the resource-specific operations of Google Cloud
  15. // IAM (Identity and Access Management) for the Google Cloud Libraries.
  16. // See https://cloud.google.com/iam for more about IAM.
  17. //
  18. // Users of the Google Cloud Libraries will typically not use this package
  19. // directly. Instead they will begin with some resource that supports IAM, like
  20. // a pubsub topic, and call its IAM method to get a Handle for that resource.
  21. package iam
  22. import (
  23. "context"
  24. "fmt"
  25. "time"
  26. gax "github.com/googleapis/gax-go/v2"
  27. pb "google.golang.org/genproto/googleapis/iam/v1"
  28. "google.golang.org/grpc"
  29. "google.golang.org/grpc/codes"
  30. "google.golang.org/grpc/metadata"
  31. )
  32. // client abstracts the IAMPolicy API to allow multiple implementations.
  33. type client interface {
  34. Get(ctx context.Context, resource string) (*pb.Policy, error)
  35. Set(ctx context.Context, resource string, p *pb.Policy) error
  36. Test(ctx context.Context, resource string, perms []string) ([]string, error)
  37. }
  38. // grpcClient implements client for the standard gRPC-based IAMPolicy service.
  39. type grpcClient struct {
  40. c pb.IAMPolicyClient
  41. }
  42. var withRetry = gax.WithRetry(func() gax.Retryer {
  43. return gax.OnCodes([]codes.Code{
  44. codes.DeadlineExceeded,
  45. codes.Unavailable,
  46. }, gax.Backoff{
  47. Initial: 100 * time.Millisecond,
  48. Max: 60 * time.Second,
  49. Multiplier: 1.3,
  50. })
  51. })
  52. func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) {
  53. var proto *pb.Policy
  54. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
  55. ctx = insertMetadata(ctx, md)
  56. err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  57. var err error
  58. proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{Resource: resource})
  59. return err
  60. }, withRetry)
  61. if err != nil {
  62. return nil, err
  63. }
  64. return proto, nil
  65. }
  66. func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) error {
  67. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
  68. ctx = insertMetadata(ctx, md)
  69. return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  70. _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{
  71. Resource: resource,
  72. Policy: p,
  73. })
  74. return err
  75. }, withRetry)
  76. }
  77. func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) {
  78. var res *pb.TestIamPermissionsResponse
  79. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
  80. ctx = insertMetadata(ctx, md)
  81. err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  82. var err error
  83. res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{
  84. Resource: resource,
  85. Permissions: perms,
  86. })
  87. return err
  88. }, withRetry)
  89. if err != nil {
  90. return nil, err
  91. }
  92. return res.Permissions, nil
  93. }
  94. // A Handle provides IAM operations for a resource.
  95. type Handle struct {
  96. c client
  97. resource string
  98. }
  99. // InternalNewHandle is for use by the Google Cloud Libraries only.
  100. //
  101. // InternalNewHandle returns a Handle for resource.
  102. // The conn parameter refers to a server that must support the IAMPolicy service.
  103. func InternalNewHandle(conn *grpc.ClientConn, resource string) *Handle {
  104. return InternalNewHandleGRPCClient(pb.NewIAMPolicyClient(conn), resource)
  105. }
  106. // InternalNewHandleGRPCClient is for use by the Google Cloud Libraries only.
  107. //
  108. // InternalNewHandleClient returns a Handle for resource using the given
  109. // grpc service that implements IAM as a mixin
  110. func InternalNewHandleGRPCClient(c pb.IAMPolicyClient, resource string) *Handle {
  111. return InternalNewHandleClient(&grpcClient{c: c}, resource)
  112. }
  113. // InternalNewHandleClient is for use by the Google Cloud Libraries only.
  114. //
  115. // InternalNewHandleClient returns a Handle for resource using the given
  116. // client implementation.
  117. func InternalNewHandleClient(c client, resource string) *Handle {
  118. return &Handle{
  119. c: c,
  120. resource: resource,
  121. }
  122. }
  123. // Policy retrieves the IAM policy for the resource.
  124. func (h *Handle) Policy(ctx context.Context) (*Policy, error) {
  125. proto, err := h.c.Get(ctx, h.resource)
  126. if err != nil {
  127. return nil, err
  128. }
  129. return &Policy{InternalProto: proto}, nil
  130. }
  131. // SetPolicy replaces the resource's current policy with the supplied Policy.
  132. //
  133. // If policy was created from a prior call to Get, then the modification will
  134. // only succeed if the policy has not changed since the Get.
  135. func (h *Handle) SetPolicy(ctx context.Context, policy *Policy) error {
  136. return h.c.Set(ctx, h.resource, policy.InternalProto)
  137. }
  138. // TestPermissions returns the subset of permissions that the caller has on the resource.
  139. func (h *Handle) TestPermissions(ctx context.Context, permissions []string) ([]string, error) {
  140. return h.c.Test(ctx, h.resource, permissions)
  141. }
  142. // A RoleName is a name representing a collection of permissions.
  143. type RoleName string
  144. // Common role names.
  145. const (
  146. Owner RoleName = "roles/owner"
  147. Editor RoleName = "roles/editor"
  148. Viewer RoleName = "roles/viewer"
  149. )
  150. const (
  151. // AllUsers is a special member that denotes all users, even unauthenticated ones.
  152. AllUsers = "allUsers"
  153. // AllAuthenticatedUsers is a special member that denotes all authenticated users.
  154. AllAuthenticatedUsers = "allAuthenticatedUsers"
  155. )
  156. // A Policy is a list of Bindings representing roles
  157. // granted to members.
  158. //
  159. // The zero Policy is a valid policy with no bindings.
  160. type Policy struct {
  161. // TODO(jba): when type aliases are available, put Policy into an internal package
  162. // and provide an exported alias here.
  163. // This field is exported for use by the Google Cloud Libraries only.
  164. // It may become unexported in a future release.
  165. InternalProto *pb.Policy
  166. }
  167. // Members returns the list of members with the supplied role.
  168. // The return value should not be modified. Use Add and Remove
  169. // to modify the members of a role.
  170. func (p *Policy) Members(r RoleName) []string {
  171. b := p.binding(r)
  172. if b == nil {
  173. return nil
  174. }
  175. return b.Members
  176. }
  177. // HasRole reports whether member has role r.
  178. func (p *Policy) HasRole(member string, r RoleName) bool {
  179. return memberIndex(member, p.binding(r)) >= 0
  180. }
  181. // Add adds member member to role r if it is not already present.
  182. // A new binding is created if there is no binding for the role.
  183. func (p *Policy) Add(member string, r RoleName) {
  184. b := p.binding(r)
  185. if b == nil {
  186. if p.InternalProto == nil {
  187. p.InternalProto = &pb.Policy{}
  188. }
  189. p.InternalProto.Bindings = append(p.InternalProto.Bindings, &pb.Binding{
  190. Role: string(r),
  191. Members: []string{member},
  192. })
  193. return
  194. }
  195. if memberIndex(member, b) < 0 {
  196. b.Members = append(b.Members, member)
  197. return
  198. }
  199. }
  200. // Remove removes member from role r if it is present.
  201. func (p *Policy) Remove(member string, r RoleName) {
  202. bi := p.bindingIndex(r)
  203. if bi < 0 {
  204. return
  205. }
  206. bindings := p.InternalProto.Bindings
  207. b := bindings[bi]
  208. mi := memberIndex(member, b)
  209. if mi < 0 {
  210. return
  211. }
  212. // Order doesn't matter for bindings or members, so to remove, move the last item
  213. // into the removed spot and shrink the slice.
  214. if len(b.Members) == 1 {
  215. // Remove binding.
  216. last := len(bindings) - 1
  217. bindings[bi] = bindings[last]
  218. bindings[last] = nil
  219. p.InternalProto.Bindings = bindings[:last]
  220. return
  221. }
  222. // Remove member.
  223. // TODO(jba): worry about multiple copies of m?
  224. last := len(b.Members) - 1
  225. b.Members[mi] = b.Members[last]
  226. b.Members[last] = ""
  227. b.Members = b.Members[:last]
  228. }
  229. // Roles returns the names of all the roles that appear in the Policy.
  230. func (p *Policy) Roles() []RoleName {
  231. if p.InternalProto == nil {
  232. return nil
  233. }
  234. var rns []RoleName
  235. for _, b := range p.InternalProto.Bindings {
  236. rns = append(rns, RoleName(b.Role))
  237. }
  238. return rns
  239. }
  240. // binding returns the Binding for the suppied role, or nil if there isn't one.
  241. func (p *Policy) binding(r RoleName) *pb.Binding {
  242. i := p.bindingIndex(r)
  243. if i < 0 {
  244. return nil
  245. }
  246. return p.InternalProto.Bindings[i]
  247. }
  248. func (p *Policy) bindingIndex(r RoleName) int {
  249. if p.InternalProto == nil {
  250. return -1
  251. }
  252. for i, b := range p.InternalProto.Bindings {
  253. if b.Role == string(r) {
  254. return i
  255. }
  256. }
  257. return -1
  258. }
  259. // memberIndex returns the index of m in b's Members, or -1 if not found.
  260. func memberIndex(m string, b *pb.Binding) int {
  261. if b == nil {
  262. return -1
  263. }
  264. for i, mm := range b.Members {
  265. if mm == m {
  266. return i
  267. }
  268. }
  269. return -1
  270. }
  271. // insertMetadata inserts metadata into the given context
  272. func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
  273. out, _ := metadata.FromOutgoingContext(ctx)
  274. out = out.Copy()
  275. for _, md := range mds {
  276. for k, v := range md {
  277. out[k] = append(out[k], v...)
  278. }
  279. }
  280. return metadata.NewOutgoingContext(ctx, out)
  281. }