Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cleanup(httpapi): remove optional logging-related complexity #1008

Merged
merged 1 commit into from
Dec 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 6 additions & 16 deletions internal/httpapi/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"github.com/ooni/probe-cli/v3/internal/netxlite"
)

// joinURLPath appends |resourcePath| to |urlPath|.
// joinURLPath appends resourcePath to urlPath.
func joinURLPath(urlPath, resourcePath string) string {
if resourcePath == "" {
if urlPath == "" {
Expand All @@ -34,7 +34,7 @@ func joinURLPath(urlPath, resourcePath string) string {
return urlPath + resourcePath
}

// newRequest creates a new http.Request from the given |ctx|, |endpoint|, and |desc|.
// newRequest creates a new http.Request from the given ctx, endpoint, and desc.
func newRequest(ctx context.Context, endpoint *Endpoint, desc *Descriptor) (*http.Request, error) {
URL, err := url.Parse(endpoint.BaseURL)
if err != nil {
Expand Down Expand Up @@ -111,7 +111,7 @@ func (err *errMaybeCensorship) Unwrap() error {
// ErrTruncated indicates we truncated the response body.
var ErrTruncated = errors.New("httpapi: truncated response body")

// docall calls the API represented by the given request |req| on the given |endpoint|
// docall calls the API represented by the given request req on the given endpoint
// and returns the response and its body or an error.
func docall(endpoint *Endpoint, desc *Descriptor, request *http.Request) (*http.Response, []byte, error) {
// Implementation note: remember to mark errors for which you want
Expand Down Expand Up @@ -178,7 +178,7 @@ func call(ctx context.Context, desc *Descriptor, endpoint *Endpoint) (*http.Resp
return docall(endpoint, desc, request)
}

// Call invokes the API described by |desc| on the given HTTP |endpoint| and
// Call invokes the API described by desc on the given HTTP endpoint and
// returns the response body (as a slice of bytes) or an error.
//
// Note: this function returns ErrHTTPRequestFailed if the HTTP status code is
Expand All @@ -189,26 +189,16 @@ func Call(ctx context.Context, desc *Descriptor, endpoint *Endpoint) ([]byte, er
return rawResponseBody, err
}

// goodContentTypeForJSON tracks known-good content-types for JSON. If the content-type
// is not in this map, |CallWithJSONResponse| emits a warning message.
var goodContentTypeForJSON = map[string]bool{
applicationJSON: true,
}

// CallWithJSONResponse is like Call but also assumes that the response is a
// JSON body and attempts to parse it into the |response| field.
// JSON body and attempts to parse it into the response field.
//
// Note: this function returns ErrHTTPRequestFailed if the HTTP status code is
// greater or equal than 400. You could use errors.As to obtain a copy of the
// error that was returned and see for yourself the actual status code.
func CallWithJSONResponse(ctx context.Context, desc *Descriptor, endpoint *Endpoint, response any) error {
httpResp, rawRespBody, err := call(ctx, desc, endpoint)
_, rawRespBody, err := call(ctx, desc, endpoint)
if err != nil {
return err
}
if ctype := httpResp.Header.Get("Content-Type"); !goodContentTypeForJSON[ctype] {
endpoint.Logger.Warnf("httpapi: unexpected content-type: %s", ctype)
// fallthrough
}
return json.Unmarshal(rawRespBody, response)
}
296 changes: 1 addition & 295 deletions internal/httpapi/call_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import (
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
Expand All @@ -19,7 +17,6 @@ import (
"github.com/ooni/probe-cli/v3/internal/model"
"github.com/ooni/probe-cli/v3/internal/model/mocks"
"github.com/ooni/probe-cli/v3/internal/netxlite"
"github.com/ooni/probe-cli/v3/internal/runtimex"
)

func Test_joinURLPath(t *testing.T) {
Expand Down Expand Up @@ -191,7 +188,7 @@ func Test_newRequest(t *testing.T) {
Accept: "",
Authorization: "",
ContentType: "",
LogBody: false,
LogBody: true, // just to exercise the code path
MaxBodySize: 0,
Method: http.MethodPost,
RequestBody: []byte("deadbeef"),
Expand Down Expand Up @@ -1227,297 +1224,6 @@ func TestCallWithJSONResponseHonoursContext(t *testing.T) {
}
}

func TestLogging(t *testing.T) {

// This test was originally written for the httpx package and we have adapted it
// by keeping the ~same implementation with a custom callx function that converts
// the previous semantics of httpx to the new semantics of httpapi.
callx := func(baseURL string, logBody bool, logger model.Logger, request, response any) error {
desc := MustNewPOSTJSONWithJSONResponseDescriptor("/", request).WithBodyLogging(logBody)
runtimex.Assert(desc.LogBody == logBody, "desc.LogBody should be equal to logBody here")
endpoint := &Endpoint{
BaseURL: baseURL,
HTTPClient: http.DefaultClient,
Logger: logger,
}
return CallWithJSONResponse(context.Background(), desc, endpoint, response)
}

// we also needed to create a constructor for the logger
newlogger := func(logs chan string) model.Logger {
return &mocks.Logger{
MockDebugf: func(format string, v ...interface{}) {
logs <- fmt.Sprintf(format, v...)
},
MockWarnf: func(format string, v ...interface{}) {
logs <- fmt.Sprintf(format, v...)
},
}
}

t.Run("body logging enabled, 200 Ok, and without content-type", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("[]"))
},
))
logs := make(chan string, 1024)
defer server.Close()
var (
input []string
output []string
)
logger := newlogger(logs)
err := callx(server.URL, true, logger, input, &output)
var found int
close(logs)
for entry := range logs {
if strings.HasPrefix(entry, "httpapi: request body: ") {
// we expect this because body logging is enabled
found |= 1 << 0
continue
}
if strings.HasPrefix(entry, "httpapi: response body: ") {
// we expect this because body logging is enabled
found |= 1 << 1
continue
}
if strings.HasPrefix(entry, "httpapi: unexpected content-type: ") {
// we would expect this because the server does not send us any content-type
found |= 1 << 2
continue
}
if strings.HasPrefix(entry, "httpapi: request body length: ") {
// we should see this because we sent a body
found |= 1 << 3
continue
}
if strings.HasPrefix(entry, "httpapi: response body length: ") {
// we should see this because we receive a body
found |= 1 << 4
continue
}
}
if found != (1<<0 | 1<<1 | 1<<2 | 1<<3 | 1<<4) {
t.Fatal("did not find the expected logs")
}
if err != nil {
t.Fatal(err)
}
})

t.Run("body logging enabled, 200 Ok, and with content-type", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("content-type", "application/json")
w.Write([]byte("[]"))
},
))
logs := make(chan string, 1024)
defer server.Close()
var (
input []string
output []string
)
logger := newlogger(logs)
err := callx(server.URL, true, logger, input, &output)
var found int
close(logs)
for entry := range logs {
if strings.HasPrefix(entry, "httpapi: request body: ") {
// we expect this because body logging is enabled
found |= 1 << 0
continue
}
if strings.HasPrefix(entry, "httpapi: response body: ") {
// we expect this because body logging is enabled
found |= 1 << 1
continue
}
if strings.HasPrefix(entry, "httpapi: unexpected content-type: ") {
// we do not expect this because the server sends us a content-type
found |= 1 << 2
continue
}
if strings.HasPrefix(entry, "httpapi: request body length: ") {
// we should see this because we sent a body
found |= 1 << 3
continue
}
if strings.HasPrefix(entry, "httpapi: response body length: ") {
// we should see this because we receive a body
found |= 1 << 4
continue
}
}
if found != (1<<0 | 1<<1 | 1<<3 | 1<<4) {
t.Fatal("did not find the expected logs")
}
if err != nil {
t.Fatal(err)
}
})

t.Run("body logging enabled and 401 Unauthorized", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(401)
w.Write([]byte("[]"))
},
))
logs := make(chan string, 1024)
defer server.Close()
var (
input []string
output []string
)
logger := newlogger(logs)
err := callx(server.URL, true, logger, input, &output)
var found int
close(logs)
for entry := range logs {
if strings.HasPrefix(entry, "httpapi: request body: ") {
// should occur because body logging is enabled
found |= 1 << 0
continue
}
if strings.HasPrefix(entry, "httpapi: response body: ") {
// should occur because body logging is enabled
found |= 1 << 1
continue
}
if strings.HasPrefix(entry, "httpapi: unexpected content-type: ") {
// note: this one should not occur because the code is 401 so we're not
// actually going to parse the JSON document
found |= 1 << 2
continue
}
if strings.HasPrefix(entry, "httpapi: request body length: ") {
// we should see this because we send a body
found |= 1 << 3
continue
}
if strings.HasPrefix(entry, "httpapi: response body length: ") {
// we should see this because we receive a body
found |= 1 << 4
continue
}
}
if found != (1<<0 | 1<<1 | 1<<3 | 1<<4) {
t.Fatal("did not find the expected logs")
}
var failure *ErrHTTPRequestFailed
if !errors.As(err, &failure) || failure.StatusCode != 401 {
t.Fatal("unexpected err", err)
}
})

t.Run("body logging NOT enabled and 200 Ok", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("[]"))
},
))
logs := make(chan string, 1024)
defer server.Close()
var (
input []string
output []string
)
logger := newlogger(logs)
err := callx(server.URL, false, logger, input, &output) // no logging
var found int
close(logs)
for entry := range logs {
if strings.HasPrefix(entry, "httpapi: request body: ") {
// should not see it: body logging is disabled
found |= 1 << 0
continue
}
if strings.HasPrefix(entry, "httpapi: response body: ") {
// should not see it: body logging is disabled
found |= 1 << 1
continue
}
if strings.HasPrefix(entry, "httpapi: unexpected content-type: ") {
// this one should be logged ANYWAY because it's orthogonal to the
// body logging so we should see it also in this case.
found |= 1 << 2
continue
}
if strings.HasPrefix(entry, "httpapi: request body length: ") {
// should see this because we send a body
found |= 1 << 3
continue
}
if strings.HasPrefix(entry, "httpapi: response body length: ") {
// should see this because we're receiving a body
found |= 1 << 4
continue
}
}
if found != (1<<2 | 1<<3 | 1<<4) {
t.Fatal("did not find the expected logs")
}
if err != nil {
t.Fatal(err)
}
})

t.Run("body logging NOT enabled and 401 Unauthorized", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(401)
w.Write([]byte("[]"))
},
))
logs := make(chan string, 1024)
defer server.Close()
var (
input []string
output []string
)
logger := newlogger(logs)
err := callx(server.URL, false, logger, input, &output) // no logging
var found int
close(logs)
for entry := range logs {
if strings.HasPrefix(entry, "httpapi: request body: ") {
// should not see it: body logging is disabled
found |= 1 << 0
continue
}
if strings.HasPrefix(entry, "httpapi: response body: ") {
// should not see it: body logging is disabled
found |= 1 << 1
continue
}
if strings.HasPrefix(entry, "httpapi: unexpected content-type: ") {
// should not see it because we don't parse the body on 401 errors
found |= 1 << 2
continue
}
if strings.HasPrefix(entry, "httpapi: request body length: ") {
// we send a body so we should see it
found |= 1 << 3
continue
}
if strings.HasPrefix(entry, "httpapi: response body length: ") {
// we receive a body so we should see it
found |= 1 << 4
continue
}
}
if found != (1<<3 | 1<<4) {
t.Fatal("did not find the expected logs")
}
var failure *ErrHTTPRequestFailed
if !errors.As(err, &failure) || failure.StatusCode != 401 {
t.Fatal("unexpected err", err)
}
})
}

func Test_errMaybeCensorship_Unwrap(t *testing.T) {
t.Run("for errors.Is", func(t *testing.T) {
var err error = &errMaybeCensorship{io.EOF}
Expand Down
Loading