From 2d8c5f6c2b4bf5ca713bb2b1a4cc826138712455 Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Wed, 14 Oct 2020 12:53:56 +0100 Subject: [PATCH] add ErrInvalidScheme when HTTP is used HTTP can result in silent failure, as Cloud Run will redirect to HTTPS, which in turn is a 200 for the HTML content --- client.go | 17 +++++++++++++++++ client_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/client.go b/client.go index 37bb06e..84258af 100644 --- a/client.go +++ b/client.go @@ -5,12 +5,18 @@ package logs import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" + "net/url" "time" ) +// ErrInvalidScheme is returned when HTTP is used, which results in a silent failure +// due to Cloud Run's redirection of HTTP -> HTTPs. +var ErrInvalidScheme = errors.New("Client.URL must be HTTPS, not HTTP") + // Alert represents configuration for performing alerting. type Alert struct { // CreatedAt is a timestamp indicating when the alert was created. This field is read-only. @@ -930,6 +936,17 @@ func (e Error) Error() string { func call(client *http.Client, authToken, endpoint, method string, in, out interface{}) error { var body io.Reader + // parse the URL + u, err := url.Parse(endpoint) + if err != nil { + return fmt.Errorf("parsing url: %w", err) + } + + // ensure HTTPS + if u.Scheme == "http" { + return ErrInvalidScheme + } + // default client if client == nil { client = http.DefaultClient diff --git a/client_test.go b/client_test.go index 3f41fbb..76a96ee 100644 --- a/client_test.go +++ b/client_test.go @@ -2,6 +2,7 @@ package logs_test import ( "os" + "strings" "testing" "github.com/apex/logs" @@ -24,3 +25,14 @@ func TestService_GetProjects(t *testing.T) { assert.NotEmpty(t, p.Description) assert.NotEmpty(t, p.Name) } + +// Test erroring on HTTP. +func TestHTTP(t *testing.T) { + c := logs.Client{ + URL: strings.Replace(os.Getenv("URL"), "https://", "http://", 1), + AuthToken: os.Getenv("AUTH_TOKEN"), + } + + _, err := c.GetProjects() + assert.EqualError(t, err, "Client.URL must be HTTPS, not HTTP") +}