1 // Copyright 2025 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 15 package headers
16 17 import (
18 "net/http"
19 20 "cloud.google.com/go/auth"
21 "cloud.google.com/go/auth/internal"
22 )
23 24 // SetAuthHeader uses the provided token to set the Authorization and trust
25 // boundary headers on a request. If the token.Type is empty, the type is
26 // assumed to be Bearer.
27 func SetAuthHeader(token *auth.Token, req *http.Request) {
28 typ := token.Type
29 if typ == "" {
30 typ = internal.TokenTypeBearer
31 }
32 req.Header.Set("Authorization", typ+" "+token.Value)
33 34 if headerVal, setHeader := getTrustBoundaryHeader(token); setHeader {
35 req.Header.Set("x-allowed-locations", headerVal)
36 }
37 }
38 39 // SetAuthMetadata uses the provided token to set the Authorization and trust
40 // boundary metadata. If the token.Type is empty, the type is assumed to be
41 // Bearer.
42 func SetAuthMetadata(token *auth.Token, m map[string]string) {
43 typ := token.Type
44 if typ == "" {
45 typ = internal.TokenTypeBearer
46 }
47 m["authorization"] = typ + " " + token.Value
48 49 if headerVal, setHeader := getTrustBoundaryHeader(token); setHeader {
50 m["x-allowed-locations"] = headerVal
51 }
52 }
53 54 func getTrustBoundaryHeader(token *auth.Token) (val string, present bool) {
55 if data, ok := token.Metadata[internal.TrustBoundaryDataKey]; ok {
56 if tbd, ok := data.(internal.TrustBoundaryData); ok {
57 return tbd.TrustBoundaryHeader()
58 }
59 }
60 return "", false
61 }
62