utils.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package alts
  19. import (
  20. "context"
  21. "errors"
  22. "strings"
  23. "google.golang.org/grpc/codes"
  24. "google.golang.org/grpc/peer"
  25. "google.golang.org/grpc/status"
  26. )
  27. // AuthInfoFromContext extracts the alts.AuthInfo object from the given context,
  28. // if it exists. This API should be used by gRPC server RPC handlers to get
  29. // information about the communicating peer. For client-side, use grpc.Peer()
  30. // CallOption.
  31. func AuthInfoFromContext(ctx context.Context) (AuthInfo, error) {
  32. p, ok := peer.FromContext(ctx)
  33. if !ok {
  34. return nil, errors.New("no Peer found in Context")
  35. }
  36. return AuthInfoFromPeer(p)
  37. }
  38. // AuthInfoFromPeer extracts the alts.AuthInfo object from the given peer, if it
  39. // exists. This API should be used by gRPC clients after obtaining a peer object
  40. // using the grpc.Peer() CallOption.
  41. func AuthInfoFromPeer(p *peer.Peer) (AuthInfo, error) {
  42. altsAuthInfo, ok := p.AuthInfo.(AuthInfo)
  43. if !ok {
  44. return nil, errors.New("no alts.AuthInfo found in Peer")
  45. }
  46. return altsAuthInfo, nil
  47. }
  48. // ClientAuthorizationCheck checks whether the client is authorized to access
  49. // the requested resources based on the given expected client service accounts.
  50. // This API should be used by gRPC server RPC handlers. This API should not be
  51. // used by clients.
  52. func ClientAuthorizationCheck(ctx context.Context, expectedServiceAccounts []string) error {
  53. authInfo, err := AuthInfoFromContext(ctx)
  54. if err != nil {
  55. return status.Errorf(codes.PermissionDenied, "The context is not an ALTS-compatible context: %v", err)
  56. }
  57. peer := authInfo.PeerServiceAccount()
  58. for _, sa := range expectedServiceAccounts {
  59. if strings.EqualFold(peer, sa) {
  60. return nil
  61. }
  62. }
  63. return status.Errorf(codes.PermissionDenied, "Client %v is not authorized", peer)
  64. }