//go:build e2e package main import ( "bytes" "context" "encoding/base64" "encoding/hex" "errors" "net/http" "net/http/httptest" "strings" "testing" "github.com/google/uuid" "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/port/outbound" ) func TestFixtureHandlerRevokesOnlyWithConfiguredBearer(t *testing.T) { organizationID := uuid.New() userID := uuid.New() successorUserID := uuid.New() called := false handler := &fixtureHandler{ token: strings.Repeat("ab", 32), revoke: func(_ context.Context, gotOrganizationID, gotUserID, gotSuccessorUserID uuid.UUID) error { called = true if gotOrganizationID != organizationID || gotUserID != userID || gotSuccessorUserID != successorUserID { t.Fatalf("revoke IDs = %s/%s/%s, want %s/%s/%s", gotOrganizationID, gotUserID, gotSuccessorUserID, organizationID, userID, successorUserID) } return nil }, } body := `{"organization_id":"` + organizationID.String() + `","user_id":"` + userID.String() + `","successor_user_id":"` + successorUserID.String() + `"}` unauthorized := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json") if unauthorized.Code != http.StatusUnauthorized || called { t.Fatalf("unauthorized response = %d, revoke called = %t", unauthorized.Code, called) } if len(unauthorized.Body.Bytes()) != 0 { t.Fatalf("unauthorized response exposed a body: %q", unauthorized.Body.String()) } response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json; charset=utf-8") if response.Code != http.StatusNoContent || !called { t.Fatalf("authorized response = %d, revoke called = %t", response.Code, called) } if len(response.Body.Bytes()) != 0 { t.Fatalf("success response exposed a body: %q", response.Body.String()) } } func TestFixtureHandlerRejectsInvalidRequestsWithoutCallingRevoker(t *testing.T) { called := false handler := &fixtureHandler{ token: strings.Repeat("ab", 32), revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error { called = true return nil }, } validBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}` userID := uuid.NewString() sameUserBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + userID + `","successor_user_id":"` + userID + `"}` largeBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `","padding":"` + strings.Repeat("x", maxRequestBody) + `"}` tests := []struct { name string method string path string body string authority string contentType string wantStatus int }{ {name: "unknown path", method: http.MethodPost, path: "/other", wantStatus: http.StatusNotFound}, {name: "wrong method", method: http.MethodGet, path: fixtureEndpoint, wantStatus: http.StatusMethodNotAllowed}, {name: "wrong content type", method: http.MethodPost, path: fixtureEndpoint, body: validBody, authority: "Bearer " + handler.token, contentType: "text/plain", wantStatus: http.StatusUnsupportedMediaType}, {name: "unknown field", method: http.MethodPost, path: fixtureEndpoint, body: strings.TrimSuffix(validBody, "}") + `,"extra":"value"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, {name: "malformed UUID", method: http.MethodPost, path: fixtureEndpoint, body: `{"organization_id":"bad","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, {name: "same owner and successor", method: http.MethodPost, path: fixtureEndpoint, body: sameUserBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, {name: "trailing JSON", method: http.MethodPost, path: fixtureEndpoint, body: validBody + `{}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, {name: "oversized body", method: http.MethodPost, path: fixtureEndpoint, body: largeBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusRequestEntityTooLarge}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { response := fixtureRequest(handler, test.method, test.path, test.body, test.authority, test.contentType) if response.Code != test.wantStatus { t.Fatalf("response status = %d, want %d", response.Code, test.wantStatus) } if len(response.Body.Bytes()) != 0 { t.Fatalf("response exposed a body: %q", response.Body.String()) } }) } if called { t.Fatal("revoker was called for an invalid request") } } func TestFixtureHandlerBoundsControlRequests(t *testing.T) { handler := &fixtureHandler{token: strings.Repeat("ab", 32)} for range maxFixtureRequests { response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json") if response.Code != http.StatusUnauthorized { t.Fatalf("request before limit status = %d, want %d", response.Code, http.StatusUnauthorized) } } response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json") if response.Code != http.StatusTooManyRequests { t.Fatalf("request after limit status = %d, want %d", response.Code, http.StatusTooManyRequests) } } func TestFixtureHandlerMapsStorageErrorsToEmptyResponses(t *testing.T) { handler := &fixtureHandler{ token: strings.Repeat("ab", 32), revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error { return errors.Join(errors.New("private database detail"), outbound.ErrTransactionConflict) }, } body := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}` response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json") if response.Code != http.StatusConflict { t.Fatalf("response status = %d, want %d", response.Code, http.StatusConflict) } if len(response.Body.Bytes()) != 0 { t.Fatalf("response exposed internal error: %q", response.Body.String()) } if got := statusForFixtureError(postgres.ErrCompanyFixtureScope); got != http.StatusNotFound { t.Fatalf("fixture scope status = %d, want %d", got, http.StatusNotFound) } } func TestFixtureHealthIsMinimal(t *testing.T) { handler := &fixtureHandler{} response := fixtureRequest(handler, http.MethodGet, fixtureHealthPath, "", "", "") if response.Code != http.StatusNoContent || len(response.Body.Bytes()) != 0 { t.Fatalf("health response = %d %q, want empty %d", response.Code, response.Body.String(), http.StatusNoContent) } wrongMethod := fixtureRequest(handler, http.MethodPost, fixtureHealthPath, "", "", "") if wrongMethod.Code != http.StatusMethodNotAllowed || wrongMethod.Header().Get("Allow") != http.MethodGet { t.Fatalf("health wrong-method response = %d, Allow = %q", wrongMethod.Code, wrongMethod.Header().Get("Allow")) } } func TestFixtureTokenStrengthAcceptsOnlyAtLeast32Bytes(t *testing.T) { bytes32 := bytes.Repeat([]byte{0x4a}, 32) for name, token := range map[string]string{ "hex": hex.EncodeToString(bytes32), "base64": base64.RawURLEncoding.EncodeToString(bytes32), "too short": hex.EncodeToString(bytes32[:31]), "invalid": "not-a-token", } { t.Run(name, func(t *testing.T) { want := name == "hex" || name == "base64" if got := hasFixtureTokenStrength(token); got != want { t.Fatalf("hasFixtureTokenStrength() = %t, want %t", got, want) } }) } } func fixtureRequest(handler http.Handler, method, path, body, authorization, contentType string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, path, strings.NewReader(body)) if authorization != "" { request.Header.Set("Authorization", authorization) } if contentType != "" { request.Header.Set("Content-Type", contentType) } response := httptest.NewRecorder() handler.ServeHTTP(response, request) return response }