-
Notifications
You must be signed in to change notification settings - Fork 17
/
target.go
40 lines (34 loc) · 1.08 KB
/
target.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
Copyright 2023 Chainguard, Inc.
SPDX-License-Identifier: Apache-2.0
*/
package cloudevents
import (
"context"
"log"
"net/http"
"strings"
metrics "github.com/chainguard-dev/terraform-infra-common/pkg/httpmetrics"
cehttp "github.com/cloudevents/sdk-go/v2/protocol/http"
"google.golang.org/api/idtoken"
)
// WithTarget wraps cloudevents.WithTarget to authenticate requests with an
// identity token when the target is an HTTPS URL.
func WithTarget(ctx context.Context, url string) []cehttp.Option {
opts := make([]cehttp.Option, 0, 2)
if strings.HasPrefix(url, "https://") {
idc, err := idtoken.NewClient(ctx, url)
if err != nil {
log.Panicf("failed to create idtoken client: %v", err)
}
// If we don't specify a client, NewClientHTTP will use http.DefaultClient
// and may clobber its Transport. To avoid so, we pass a client with the
// the metrics transport instead.
metricsClient := http.Client{
Transport: metrics.WrapTransport(idc.Transport),
}
opts = append(opts, cehttp.WithClient(metricsClient))
}
opts = append(opts, cehttp.WithTarget(url))
return opts
}