auth.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package f5cloudexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/f5cloudexporter"
  4. import (
  5. "fmt"
  6. "net/http"
  7. "golang.org/x/oauth2"
  8. )
  9. const (
  10. sourceHeader = "X-F5-Source"
  11. )
  12. type f5CloudAuthRoundTripper struct {
  13. transport http.RoundTripper
  14. tokenSource oauth2.TokenSource
  15. source string
  16. }
  17. func (rt *f5CloudAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  18. // Clone request to ensure thread safety
  19. req2 := req.Clone(req.Context())
  20. // Add authorization header
  21. tkn, err := rt.tokenSource.Token()
  22. if err != nil {
  23. return nil, err
  24. }
  25. tkn.SetAuthHeader(req2)
  26. // Add F5 specific headers
  27. req2.Header.Add(sourceHeader, rt.source)
  28. resp, err := rt.transport.RoundTrip(req2)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return resp, nil
  33. }
  34. func newF5CloudAuthRoundTripper(ts oauth2.TokenSource, source string, next http.RoundTripper) (http.RoundTripper, error) {
  35. if ts == nil {
  36. return nil, fmt.Errorf("no TokenSource exists")
  37. }
  38. if len(source) == 0 {
  39. return nil, fmt.Errorf("no source provided")
  40. }
  41. rt := f5CloudAuthRoundTripper{
  42. transport: next,
  43. tokenSource: ts,
  44. source: source,
  45. }
  46. return &rt, nil
  47. }