forked from mtusi2026/mtusi2026lab4
274 lines
10 KiB
Go
274 lines
10 KiB
Go
package auth_tests
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"highload/internal/database/sqlc"
|
|
repository "highload/internal/repository/postgres"
|
|
"highload/internal/service"
|
|
"highload/internal/transport/http/handler"
|
|
"highload/internal/transport/http/httputils"
|
|
"highload/internal/transport/http/middleware"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
)
|
|
|
|
func TestErrorDiagnosticsRecordedOnceAndPublicResponseIsSafe(t *testing.T) {
|
|
var output bytes.Buffer
|
|
original := slog.Default()
|
|
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil)))
|
|
defer slog.SetDefault(original)
|
|
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: errors.New("synthetic-storage-diagnostic")})))
|
|
_, cause := users.GetUser(context.Background(), uuid.NewString())
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
|
request.Header.Set("Authorization", "Bearer synthetic-secret-not-for-logs")
|
|
recorder := httptest.NewRecorder()
|
|
mid := middleware.NewMiddleware(nil, "auth-test")
|
|
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_ = httputils.WriteServiceError(w, cause, middleware.RequestIDFromContext(r.Context()))
|
|
})).ServeHTTP(recorder, request)
|
|
assertContractError(t, recorder, 500, "internal_error")
|
|
if strings.Contains(recorder.Body.String(), "synthetic-storage-diagnostic") {
|
|
t.Error("public response exposed internal cause")
|
|
}
|
|
if strings.Contains(output.String(), "synthetic-secret-not-for-logs") {
|
|
t.Error("server log exposed a Bearer credential")
|
|
}
|
|
var records []map[string]any
|
|
for _, line := range strings.Split(strings.TrimSpace(output.String()), "\n") {
|
|
if line == "" {
|
|
continue
|
|
}
|
|
var record map[string]any
|
|
if json.Unmarshal([]byte(line), &record) != nil {
|
|
t.Error("diagnostic log is not structured JSON")
|
|
continue
|
|
}
|
|
// Access records are not detailed duplicate error records.
|
|
if record["msg"] != "http request" {
|
|
records = append(records, record)
|
|
}
|
|
}
|
|
if len(records) != 1 {
|
|
t.Errorf("want exactly one detailed error at response boundary, got %d", len(records))
|
|
return
|
|
}
|
|
record := records[0]
|
|
if _, malformed := record["!BADKEY"]; malformed {
|
|
t.Error("structured error log contains !BADKEY: slog arguments are not valid key/value pairs")
|
|
}
|
|
if record["request_id"] != recorder.Header().Get("X-Request-Id") || record["status"] != float64(500) ||
|
|
(record["code"] != "internal_error" && record["error_code"] != "internal_error") {
|
|
t.Error("diagnostic is missing matching request_id/status/error code")
|
|
}
|
|
encoded, _ := json.Marshal(record)
|
|
if !bytes.Contains(encoded, []byte("synthetic-storage-diagnostic")) {
|
|
t.Error("diagnostic lost storage cause")
|
|
}
|
|
}
|
|
|
|
// Faults enter through sqlc's database interface, then pass through the real
|
|
// repository, service and HTTP error mapper. Driver causes are deliberately
|
|
// not required to survive: the public category and response are the contract.
|
|
type errorCase struct {
|
|
name string
|
|
cause error
|
|
want error
|
|
status int
|
|
code string
|
|
}
|
|
|
|
func databaseErrorCases() []errorCase {
|
|
cases := []errorCase{
|
|
{"no_rows", pgx.ErrNoRows, service.ErrNotFound, 404, "not_found"},
|
|
{"duplicate", &pgconn.PgError{Code: "23505"}, service.ErrAlreadyExists, 409, "conflict"},
|
|
{"eof", io.EOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
|
{"deadline", context.DeadlineExceeded, service.ErrServiceUnavailable, 503, "unavailable"},
|
|
{"unexpected_eof", io.ErrUnexpectedEOF, service.ErrServiceUnavailable, 503, "unavailable"},
|
|
{"closed_connection", pgconn.ErrConnClosed, service.ErrServiceUnavailable, 503, "unavailable"},
|
|
{"connection_refused", unavailableRow{}.Scan(), service.ErrServiceUnavailable, 503, "unavailable"},
|
|
// Docker removes the stopped service from DNS. The real outage probe
|
|
// returned a ConnectError containing this error, without a net.OpError.
|
|
{"database_dns_missing", &net.DNSError{Err: "no such host", Name: "postgres", IsNotFound: true}, service.ErrServiceUnavailable, 503, "unavailable"},
|
|
{"sql_syntax", &pgconn.PgError{Code: "42601", Message: "private SQL diagnostic"}, service.ErrServerError, 500, "internal_error"},
|
|
{"unexpected", errors.New("private database diagnostic"), service.ErrServerError, 500, "internal_error"},
|
|
}
|
|
for _, code := range []string{"53300", "57P03", "08006", "08001", "57P01", "57P02"} {
|
|
cases = append(cases, errorCase{"sqlstate_" + code, &pgconn.PgError{Code: code}, service.ErrServiceUnavailable, 503, "unavailable"})
|
|
}
|
|
// Wrapping must not change how an existing error category is recognized.
|
|
originals := append([]errorCase(nil), cases...)
|
|
for _, tc := range originals {
|
|
tc.name = "wrapped_" + tc.name
|
|
tc.cause = fmt.Errorf("database operation: %w", tc.cause)
|
|
cases = append(cases, tc)
|
|
}
|
|
return cases
|
|
}
|
|
|
|
type faultRow struct{ cause error }
|
|
|
|
func (r faultRow) Scan(...any) error { return r.cause }
|
|
|
|
type faultDB struct {
|
|
unavailableDB
|
|
cause error
|
|
}
|
|
|
|
func (d faultDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
|
return faultRow{d.cause}
|
|
}
|
|
|
|
func assertContractError(t *testing.T, recorder *httptest.ResponseRecorder, status int, code string) {
|
|
t.Helper()
|
|
if recorder.Code != status {
|
|
t.Fatalf("want HTTP %d, got %d", status, recorder.Code)
|
|
}
|
|
if recorder.Header().Get("Content-Type") != "application/json" {
|
|
t.Fatal("error response must have application/json content type")
|
|
}
|
|
var payload struct {
|
|
Error struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id"`
|
|
} `json:"error"`
|
|
}
|
|
decoder := json.NewDecoder(recorder.Body)
|
|
if err := decoder.Decode(&payload); err != nil {
|
|
t.Fatal("error response is not valid JSON")
|
|
}
|
|
if decoder.Decode(new(any)) != io.EOF {
|
|
t.Fatal("error response contains more than one JSON value")
|
|
}
|
|
if payload.Error.Code != code || payload.Error.RequestID == "" ||
|
|
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
|
t.Fatal("error category or request ID violates the API contract")
|
|
}
|
|
if payload.Error.Message == "" || strings.Contains(payload.Error.Message, "private") {
|
|
t.Fatal("error message is empty or discloses internal diagnostics")
|
|
}
|
|
}
|
|
|
|
func TestErrorDatabaseCategoryReachesHTTP(t *testing.T) {
|
|
for _, tc := range databaseErrorCases() {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: tc.cause})))
|
|
_, err := users.GetUser(context.Background(), uuid.NewString())
|
|
if !errors.Is(err, tc.want) {
|
|
t.Fatalf("want category %v, got %v", tc.want, err)
|
|
}
|
|
if errors.Is(tc.cause, context.DeadlineExceeded) && !strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
|
|
t.Error("deadline diagnostic context lost between repository and service")
|
|
}
|
|
recorder := httptest.NewRecorder()
|
|
mid := middleware.NewMiddleware(nil, "auth-test")
|
|
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_ = httputils.WriteServiceError(w, err, middleware.RequestIDFromContext(r.Context()))
|
|
})).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
|
assertContractError(t, recorder, tc.status, tc.code)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestErrorUnavailableSQLLoginKeepsCategory(t *testing.T) {
|
|
for _, tc := range databaseErrorCases() {
|
|
if tc.status != 503 {
|
|
continue
|
|
}
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
queries := sqlc.New(faultDB{cause: tc.cause})
|
|
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
|
|
mid := middleware.NewMiddleware(auth, "auth-test")
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
|
request.SetBasicAuth("synthetic_user", "Synthetic:password")
|
|
recorder := httptest.NewRecorder()
|
|
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
|
|
assertContractError(t, recorder, 503, "unavailable")
|
|
})
|
|
}
|
|
}
|
|
|
|
// The caller exists; the other member lookup fails. This isolates the service
|
|
// branch that used to replace the received err with ErrServerError.
|
|
type memberFaultDB struct {
|
|
unavailableDB
|
|
caller uuid.UUID
|
|
cause error
|
|
}
|
|
|
|
func (d memberFaultDB) QueryRow(_ context.Context, _ string, args ...any) pgx.Row {
|
|
id := uuid.UUID(args[0].(pgtype.UUID).Bytes)
|
|
if id == d.caller {
|
|
return memberUserRow{id}
|
|
}
|
|
return faultRow{d.cause}
|
|
}
|
|
|
|
type memberUserRow struct{ id uuid.UUID }
|
|
|
|
func (r memberUserRow) Scan(dst ...any) error {
|
|
*dst[0].(*pgtype.UUID) = pgtype.UUID{Bytes: [16]byte(r.id), Valid: true}
|
|
*dst[1].(*string) = "error_test_caller"
|
|
*dst[2].(*string) = "Error test caller"
|
|
*dst[3].(*string) = "unused password hash"
|
|
*dst[4].(*pgtype.Timestamptz) = pgtype.Timestamptz{Time: time.Unix(1, 0), Valid: true}
|
|
return nil
|
|
}
|
|
|
|
func TestErrorChatMemberLookupKeepsOperationMeaning(t *testing.T) {
|
|
for _, tc := range databaseErrorCases() {
|
|
if tc.status != 503 && tc.status != 404 && tc.status != 500 {
|
|
continue
|
|
}
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
caller := uuid.New()
|
|
queries := sqlc.New(memberFaultDB{caller: caller, cause: tc.cause})
|
|
users := repository.NewUserRepository(queries)
|
|
// No writable repository: an invalid member list must never reach
|
|
// chat insertion. Accidentally continuing is a test failure.
|
|
chats := service.NewChatService(nil, users, service.NewUserService(users))
|
|
_, err := chats.Create(context.Background(), "Error regression", []string{caller.String(), uuid.NewString()}, caller.String())
|
|
want, status, code := tc.want, tc.status, tc.code
|
|
if tc.status == 404 {
|
|
// contracts/README.md:17: unknown members make POST /chats invalid.
|
|
want, status, code = service.ErrInvalidInput, 400, "invalid_request"
|
|
}
|
|
if !errors.Is(err, want) {
|
|
t.Fatalf("want category %v, got %v", want, err)
|
|
}
|
|
gotStatus, gotCode := httputils.ErrorFromService(err)
|
|
if gotStatus != status || gotCode != code {
|
|
t.Fatalf("want %d/%s, got %d/%s", status, code, gotStatus, gotCode)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestErrorMissingBasicPrecedesForbiddenBody(t *testing.T) {
|
|
mid := middleware.NewMiddleware(nil, "auth-test")
|
|
auth := handler.NewAuthHandler(nil)
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
|
recorder := httptest.NewRecorder()
|
|
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
|
assertContractError(t, recorder, 401, "unauthorized")
|
|
if recorder.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
|
t.Fatal("missing Basic challenge")
|
|
}
|
|
}
|