github.com/google/trillian-examples@v0.0.0-20240520080811-0d40d35cef0e/binary_transparency/firmware/internal/client/wclient.go (about) 1 // Copyright 2021 Google LLC. All Rights Reserved. 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 client 16 17 import ( 18 "fmt" 19 "io" 20 "net/http" 21 "net/url" 22 23 "github.com/golang/glog" 24 "github.com/google/trillian-examples/binary_transparency/firmware/api" 25 "golang.org/x/mod/sumdb/note" 26 "google.golang.org/grpc/status" 27 ) 28 29 // WitnessClient is an HTTP client for the FT witness. 30 type WitnessClient struct { 31 // URL is the base URL for the FT witness. 32 URL *url.URL 33 LogSigVerifier note.Verifier 34 } 35 36 // GetWitnessCheckpoint returns a checkpoint from witness server 37 func (c WitnessClient) GetWitnessCheckpoint() (*api.LogCheckpoint, error) { 38 u, err := c.URL.Parse(api.WitnessGetCheckpoint) 39 if err != nil { 40 return nil, err 41 } 42 r, err := http.Get(u.String()) 43 if err != nil { 44 return nil, err 45 } 46 defer func() { 47 if err := r.Body.Close(); err != nil { 48 glog.Errorf("r.Body.Close(): %v", err) 49 } 50 }() 51 if r.StatusCode != 200 { 52 return nil, errFromRsp("failed to fetch checkpoint", r) 53 } 54 55 b, err := io.ReadAll(r.Body) 56 if err != nil { 57 return nil, fmt.Errorf("failed to read body: %w", err) 58 } 59 return api.ParseCheckpoint(b, c.LogSigVerifier) 60 } 61 62 func errFromRsp(m string, r *http.Response) error { 63 if r.StatusCode == 200 { 64 return nil 65 } 66 67 b, _ := io.ReadAll(r.Body) // Ignore any error, we want to ensure we return the right status code which we already know. 68 69 msg := fmt.Sprintf("%s: %s", m, string(b)) 70 return status.New(codeFromHTTPResponse(r.StatusCode), msg).Err() 71 }