iam.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. pb "cloud.google.com/go/iam/apiv1/iampb"
  27. gax "github.com/googleapis/gax-go/v2"
  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. GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error)
  38. }
  39. // grpcClient implements client for the standard gRPC-based IAMPolicy service.
  40. type grpcClient struct {
  41. c pb.IAMPolicyClient
  42. }
  43. var withRetry = gax.WithRetry(func() gax.Retryer {
  44. return gax.OnCodes([]codes.Code{
  45. codes.DeadlineExceeded,
  46. codes.Unavailable,
  47. }, gax.Backoff{
  48. Initial: 100 * time.Millisecond,
  49. Max: 60 * time.Second,
  50. Multiplier: 1.3,
  51. })
  52. })
  53. func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) {
  54. return g.GetWithVersion(ctx, resource, 1)
  55. }
  56. func (g *grpcClient) GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error) {
  57. var proto *pb.Policy
  58. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
  59. ctx = insertMetadata(ctx, md)
  60. err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  61. var err error
  62. proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{
  63. Resource: resource,
  64. Options: &pb.GetPolicyOptions{
  65. RequestedPolicyVersion: requestedPolicyVersion,
  66. },
  67. })
  68. return err
  69. }, withRetry)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return proto, nil
  74. }
  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)
  78. return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  79. _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{
  80. Resource: resource,
  81. Policy: p,
  82. })
  83. return err
  84. }, withRetry)
  85. }
  86. func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) {
  87. var res *pb.TestIamPermissionsResponse
  88. md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource))
  89. ctx = insertMetadata(ctx, md)
  90. err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
  91. var err error
  92. res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{
  93. Resource: resource,
  94. Permissions: perms,
  95. })
  96. return err
  97. }, withRetry)
  98. if err != nil {
  99. return nil, err
  100. }
  101. return res.Permissions, nil
  102. }
  103. // A Handle provides IAM operations for a resource.
  104. type Handle struct {
  105. c client
  106. resource string
  107. }
  108. // A Handle3 provides IAM operations for a resource. It is similar to a Handle, but provides access to newer IAM features (e.g., conditions).
  109. type Handle3 struct {
  110. c client
  111. resource string
  112. version int32
  113. }
  114. // InternalNewHandle is for use by the Google Cloud Libraries only.
  115. //
  116. // InternalNewHandle returns a Handle for resource.
  117. // The conn parameter refers to a server that must support the IAMPolicy service.
  118. func InternalNewHandle(conn grpc.ClientConnInterface, resource string) *Handle {
  119. return InternalNewHandleGRPCClient(pb.NewIAMPolicyClient(conn), resource)
  120. }
  121. // InternalNewHandleGRPCClient is for use by the Google Cloud Libraries only.
  122. //
  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)
  127. }
  128. // InternalNewHandleClient is for use by the Google Cloud Libraries only.
  129. //
  130. // InternalNewHandleClient returns a Handle for resource using the given
  131. // client implementation.
  132. func InternalNewHandleClient(c client, resource string) *Handle {
  133. return &Handle{
  134. c: c,
  135. resource: resource,
  136. }
  137. }
  138. // V3 returns a Handle3, which is like Handle except it sets
  139. // requestedPolicyVersion to 3 when retrieving a policy and policy.version to 3
  140. // when storing a policy.
  141. func (h *Handle) V3() *Handle3 {
  142. return &Handle3{
  143. c: h.c,
  144. resource: h.resource,
  145. version: 3,
  146. }
  147. }
  148. // Policy retrieves the IAM policy for the resource.
  149. func (h *Handle) Policy(ctx context.Context) (*Policy, error) {
  150. proto, err := h.c.Get(ctx, h.resource)
  151. if err != nil {
  152. return nil, err
  153. }
  154. return &Policy{InternalProto: proto}, nil
  155. }
  156. // SetPolicy replaces the resource's current policy with the supplied Policy.
  157. //
  158. // If policy was created from a prior call to Get, then the modification will
  159. // only succeed if the policy has not changed since the Get.
  160. func (h *Handle) SetPolicy(ctx context.Context, policy *Policy) error {
  161. return h.c.Set(ctx, h.resource, policy.InternalProto)
  162. }
  163. // TestPermissions returns the subset of permissions that the caller has on the resource.
  164. func (h *Handle) TestPermissions(ctx context.Context, permissions []string) ([]string, error) {
  165. return h.c.Test(ctx, h.resource, permissions)
  166. }
  167. // A RoleName is a name representing a collection of permissions.
  168. type RoleName string
  169. // Common role names.
  170. const (
  171. Owner RoleName = "roles/owner"
  172. Editor RoleName = "roles/editor"
  173. Viewer RoleName = "roles/viewer"
  174. )
  175. const (
  176. // AllUsers is a special member that denotes all users, even unauthenticated ones.
  177. AllUsers = "allUsers"
  178. // AllAuthenticatedUsers is a special member that denotes all authenticated users.
  179. AllAuthenticatedUsers = "allAuthenticatedUsers"
  180. )
  181. // A Policy is a list of Bindings representing roles
  182. // granted to members.
  183. //
  184. // The zero Policy is a valid policy with no bindings.
  185. type Policy struct {
  186. // TODO(jba): when type aliases are available, put Policy into an internal package
  187. // 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
  191. }
  192. // Members returns the list of members with the supplied role.
  193. // The return value should not be modified. Use Add and Remove
  194. // to modify the members of a role.
  195. func (p *Policy) Members(r RoleName) []string {
  196. b := p.binding(r)
  197. if b == nil {
  198. return nil
  199. }
  200. return b.Members
  201. }
  202. // HasRole reports whether member has role r.
  203. func (p *Policy) HasRole(member string, r RoleName) bool {
  204. return memberIndex(member, p.binding(r)) >= 0
  205. }
  206. // Add adds member member to role r if it is not already present.
  207. // A new binding is created if there is no binding for the role.
  208. func (p *Policy) Add(member string, r RoleName) {
  209. b := p.binding(r)
  210. if b == nil {
  211. if p.InternalProto == nil {
  212. p.InternalProto = &pb.Policy{}
  213. }
  214. p.InternalProto.Bindings = append(p.InternalProto.Bindings, &pb.Binding{
  215. Role: string(r),
  216. Members: []string{member},
  217. })
  218. return
  219. }
  220. if memberIndex(member, b) < 0 {
  221. b.Members = append(b.Members, member)
  222. return
  223. }
  224. }
  225. // Remove removes member from role r if it is present.
  226. func (p *Policy) Remove(member string, r RoleName) {
  227. bi := p.bindingIndex(r)
  228. if bi < 0 {
  229. return
  230. }
  231. bindings := p.InternalProto.Bindings
  232. b := bindings[bi]
  233. mi := memberIndex(member, b)
  234. if mi < 0 {
  235. return
  236. }
  237. // Order doesn't matter for bindings or members, so to remove, move the last item
  238. // into the removed spot and shrink the slice.
  239. if len(b.Members) == 1 {
  240. // Remove binding.
  241. last := len(bindings) - 1
  242. bindings[bi] = bindings[last]
  243. bindings[last] = nil
  244. p.InternalProto.Bindings = bindings[:last]
  245. return
  246. }
  247. // Remove member.
  248. // TODO(jba): worry about multiple copies of m?
  249. last := len(b.Members) - 1
  250. b.Members[mi] = b.Members[last]
  251. b.Members[last] = ""
  252. b.Members = b.Members[:last]
  253. }
  254. // Roles returns the names of all the roles that appear in the Policy.
  255. func (p *Policy) Roles() []RoleName {
  256. if p.InternalProto == nil {
  257. return nil
  258. }
  259. var rns []RoleName
  260. for _, b := range p.InternalProto.Bindings {
  261. rns = append(rns, RoleName(b.Role))
  262. }
  263. return rns
  264. }
  265. // binding returns the Binding for the suppied role, or nil if there isn't one.
  266. func (p *Policy) binding(r RoleName) *pb.Binding {
  267. i := p.bindingIndex(r)
  268. if i < 0 {
  269. return nil
  270. }
  271. return p.InternalProto.Bindings[i]
  272. }
  273. func (p *Policy) bindingIndex(r RoleName) int {
  274. if p.InternalProto == nil {
  275. return -1
  276. }
  277. for i, b := range p.InternalProto.Bindings {
  278. if b.Role == string(r) {
  279. return i
  280. }
  281. }
  282. return -1
  283. }
  284. // memberIndex returns the index of m in b's Members, or -1 if not found.
  285. func memberIndex(m string, b *pb.Binding) int {
  286. if b == nil {
  287. return -1
  288. }
  289. for i, mm := range b.Members {
  290. if mm == m {
  291. return i
  292. }
  293. }
  294. return -1
  295. }
  296. // insertMetadata inserts metadata into the given context
  297. func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context {
  298. out, _ := metadata.FromOutgoingContext(ctx)
  299. out = out.Copy()
  300. for _, md := range mds {
  301. for k, v := range md {
  302. out[k] = append(out[k], v...)
  303. }
  304. }
  305. return metadata.NewOutgoingContext(ctx, out)
  306. }
  307. // A Policy3 is a list of Bindings representing roles granted to members.
  308. //
  309. // The zero Policy3 is a valid policy with no bindings.
  310. //
  311. // It is similar to a Policy, except a Policy3 provides direct access to the
  312. // list of Bindings.
  313. //
  314. // The policy version is always set to 3.
  315. type Policy3 struct {
  316. etag []byte
  317. Bindings []*pb.Binding
  318. }
  319. // Policy retrieves the IAM policy for the resource.
  320. //
  321. // requestedPolicyVersion is always set to 3.
  322. func (h *Handle3) Policy(ctx context.Context) (*Policy3, error) {
  323. proto, err := h.c.GetWithVersion(ctx, h.resource, h.version)
  324. if err != nil {
  325. return nil, err
  326. }
  327. return &Policy3{
  328. Bindings: proto.Bindings,
  329. etag: proto.Etag,
  330. }, nil
  331. }
  332. // SetPolicy replaces the resource's current policy with the supplied Policy.
  333. //
  334. // If policy was created from a prior call to Get, then the modification will
  335. // only succeed if the policy has not changed since the Get.
  336. func (h *Handle3) SetPolicy(ctx context.Context, policy *Policy3) error {
  337. return h.c.Set(ctx, h.resource, &pb.Policy{
  338. Bindings: policy.Bindings,
  339. Etag: policy.etag,
  340. Version: h.version,
  341. })
  342. }
  343. // TestPermissions returns the subset of permissions that the caller has on the resource.
  344. func (h *Handle3) TestPermissions(ctx context.Context, permissions []string) ([]string, error) {
  345. return h.c.Test(ctx, h.resource, permissions)
  346. }