package student_tests import ( "bytes" "encoding/base64" "encoding/json" "io" "net/http" "testing" ) type contractErrorResponse struct { Error struct { Code string `json:"code"` Message string `json:"message"` RequestID string `json:"request_id"` } `json:"error"` } func requireContractError( t *testing.T, response *http.Response, wantStatus int, wantCode string, ) { t.Helper() defer response.Body.Close() if response.StatusCode != wantStatus { body, _ := io.ReadAll(response.Body) t.Fatalf( "expected status %d, got %d: %s", wantStatus, response.StatusCode, body, ) } requestID := response.Header.Get("X-Request-Id") if requestID == "" { t.Fatal("error response has no X-Request-Id") } if contentType := response.Header.Get("Content-Type"); contentType != "application/json; charset=utf-8" { t.Fatalf("unexpected error Content-Type: %q", contentType) } var payload contractErrorResponse if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { t.Fatalf("decode error response: %v", err) } if payload.Error.Code != wantCode { t.Fatalf( "expected error code %q, got %q", wantCode, payload.Error.Code, ) } if payload.Error.Message == "" { t.Fatal("error response has an empty message") } if payload.Error.RequestID != requestID { t.Fatal("body request_id differs from X-Request-Id") } } func sendRegistration( t *testing.T, baseURL string, contentType string, body []byte, ) *http.Response { t.Helper() request, err := http.NewRequest( http.MethodPost, baseURL+"/api/v1/users", bytes.NewReader(body), ) if err != nil { t.Fatalf("create registration request: %v", err) } if contentType != "" { request.Header.Set("Content-Type", contentType) } response, err := http.DefaultClient.Do(request) if err != nil { t.Fatalf("send registration request: %v", err) } return response } func TestJSONRequestRequiresApplicationJSON(t *testing.T) { testServer, _ := setupTestServer() defer testServer.Close() body := []byte( `{"username":"mime_probe","display_name":"Test",` + `"password":"123456789012"}`, ) for _, contentType := range []string{ "", "text/plain", "application/xml", "application/json; charset=iso-8859-1", } { contentType := contentType t.Run(contentType, func(t *testing.T) { response := sendRegistration( t, testServer.URL, contentType, body, ) requireContractError( t, response, http.StatusUnsupportedMediaType, "unsupported_media_type", ) }) } response := sendRegistration( t, testServer.URL, "application/json; charset=UTF-8", body, ) defer response.Body.Close() if response.StatusCode != http.StatusCreated { responseBody, _ := io.ReadAll(response.Body) t.Fatalf( "expected application/json with UTF-8 charset to be accepted, "+ "got %d: %s", response.StatusCode, responseBody, ) } } func TestJSONRequestRejectsInvalidUTF8WithoutMutation(t *testing.T) { testServer, _ := setupTestServer() defer testServer.Close() body := append( []byte( `{"username":"utf8_probe","display_name":"Test",`+ `"password":"12345678901`, ), 0xff, ) body = append(body, []byte(`"}`)...) response := sendRegistration( t, testServer.URL, "application/json", body, ) requireContractError( t, response, http.StatusBadRequest, "invalid_request", ) validBody := []byte( `{"username":"utf8_probe","display_name":"Test",` + `"password":"12345678901�"}`, ) validResponse := sendRegistration( t, testServer.URL, "application/json", validBody, ) defer validResponse.Body.Close() if validResponse.StatusCode != http.StatusCreated { responseBody, _ := io.ReadAll(validResponse.Body) t.Fatalf( "invalid UTF-8 request mutated storage; expected subsequent "+ "valid registration 201, got %d: %s", validResponse.StatusCode, responseBody, ) } } func TestJSONRequestRejectsOversizedBody(t *testing.T) { testServer, _ := setupTestServer() defer testServer.Close() response := sendRegistration( t, testServer.URL, "application/json", bytes.Repeat([]byte(" "), (1<<20)+1), ) requireContractError( t, response, http.StatusRequestEntityTooLarge, "payload_too_large", ) } func TestBasicAuthRejectsInvalidUTF8(t *testing.T) { testServer, _ := setupSessionTestServer(t, 0) defer testServer.Close() credentials := append([]byte("unknown:"), 0xff) request, err := http.NewRequest( http.MethodPost, testServer.URL+"/api/v1/auth/sessions", nil, ) if err != nil { t.Fatalf("create session request: %v", err) } request.Header.Set( "Authorization", "Basic "+base64.StdEncoding.EncodeToString(credentials), ) response, err := http.DefaultClient.Do(request) if err != nil { t.Fatalf("send session request: %v", err) } defer response.Body.Close() if response.StatusCode != http.StatusUnauthorized { body, _ := io.ReadAll(response.Body) t.Fatalf( "expected invalid UTF-8 Basic credentials to return 401, "+ "got %d: %s", response.StatusCode, body, ) } if got := response.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { t.Fatalf("unexpected Basic challenge: %q", got) } }