go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/resultdb/internal/http_client.go (about) 1 // Copyright 2020 The LUCI Authors. 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 internal 16 17 import ( 18 "context" 19 "net/http" 20 21 "go.chromium.org/luci/server/auth" 22 ) 23 24 var httpClientCtxKey = "context key for a *http.Client" 25 26 // MustGetContextHTTPClient retrieves the current http.client from the context. 27 func MustGetContextHTTPClient(ctx context.Context) *http.Client { 28 client, ok := ctx.Value(&httpClientCtxKey).(*http.Client) 29 if !ok { 30 panic("no HTTP client in context") 31 } 32 return client 33 } 34 35 // WithSelfTransport sets an http client in the context using the service's own authroity. 36 // WARNING: Use this only when using auth.AsProject is not possible, as using this to 37 // authorize RPCs that touch project data leads to "confused deputy" problems. 38 func WithSelfTransport(ctx context.Context) (context.Context, error) { 39 // If a client is already present in the context, do not replace it, it may be a test. 40 if _, ok := ctx.Value(&httpClientCtxKey).(*http.Client); ok { 41 return ctx, nil 42 } 43 44 tr, err := auth.GetRPCTransport(ctx, auth.AsSelf) 45 if err != nil { 46 return nil, err 47 } 48 return context.WithValue(ctx, &httpClientCtxKey, &http.Client{Transport: tr}), nil 49 } 50 51 // WithTestHTTPClient sets the supplied http client in the context for testing. 52 func WithTestHTTPClient(ctx context.Context, client *http.Client) context.Context { 53 return context.WithValue(ctx, &httpClientCtxKey, client) 54 }