forward.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package ca
  2. import (
  3. "golang.org/x/net/context"
  4. "google.golang.org/grpc/metadata"
  5. "google.golang.org/grpc/peer"
  6. )
  7. const (
  8. certForwardedKey = "forwarded_cert"
  9. certCNKey = "forwarded_cert_cn"
  10. certOUKey = "forwarded_cert_ou"
  11. certOrgKey = "forwarded_cert_org"
  12. remoteAddrKey = "remote_addr"
  13. )
  14. // forwardedTLSInfoFromContext obtains forwarded TLS CN/OU from the grpc.MD
  15. // object in ctx.
  16. func forwardedTLSInfoFromContext(ctx context.Context) (remoteAddr string, cn string, org string, ous []string) {
  17. md, _ := metadata.FromContext(ctx)
  18. if len(md[remoteAddrKey]) != 0 {
  19. remoteAddr = md[remoteAddrKey][0]
  20. }
  21. if len(md[certCNKey]) != 0 {
  22. cn = md[certCNKey][0]
  23. }
  24. if len(md[certOrgKey]) != 0 {
  25. org = md[certOrgKey][0]
  26. }
  27. ous = md[certOUKey]
  28. return
  29. }
  30. func isForwardedRequest(ctx context.Context) bool {
  31. md, _ := metadata.FromContext(ctx)
  32. if len(md[certForwardedKey]) != 1 {
  33. return false
  34. }
  35. return md[certForwardedKey][0] == "true"
  36. }
  37. // WithMetadataForwardTLSInfo reads certificate from context and returns context where
  38. // ForwardCert is set based on original certificate.
  39. func WithMetadataForwardTLSInfo(ctx context.Context) (context.Context, error) {
  40. md, ok := metadata.FromContext(ctx)
  41. if !ok {
  42. md = metadata.MD{}
  43. }
  44. ous := []string{}
  45. org := ""
  46. cn := ""
  47. certSubj, err := certSubjectFromContext(ctx)
  48. if err == nil {
  49. cn = certSubj.CommonName
  50. ous = certSubj.OrganizationalUnit
  51. if len(certSubj.Organization) > 0 {
  52. org = certSubj.Organization[0]
  53. }
  54. }
  55. // If there's no TLS cert, forward with blank TLS metadata.
  56. // Note that the presence of this blank metadata is extremely
  57. // important. Without it, it would look like manager is making
  58. // the request directly.
  59. md[certForwardedKey] = []string{"true"}
  60. md[certCNKey] = []string{cn}
  61. md[certOrgKey] = []string{org}
  62. md[certOUKey] = ous
  63. peer, ok := peer.FromContext(ctx)
  64. if ok {
  65. md[remoteAddrKey] = []string{peer.Addr.String()}
  66. }
  67. return metadata.NewContext(ctx, md), nil
  68. }