ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,221 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"highload/internal/model"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage"
|
||||
"highload/internal/storage/s3"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
)
|
||||
|
||||
type cleanupRepo struct {
|
||||
repository.AttachmentRepository
|
||||
referenced map[string]bool
|
||||
busy string
|
||||
existsErr error
|
||||
checked []string
|
||||
locked string
|
||||
}
|
||||
|
||||
type cleanupTx struct{ repo *cleanupRepo }
|
||||
|
||||
func (tx cleanupTx) CreateQueued(context.Context, string, string, string, string, string, string, string, int64) (*model.Attachment, error) {
|
||||
return nil, errors.New("cleanup fixture must not create queued attachments")
|
||||
}
|
||||
|
||||
func (tx cleanupTx) CreateAttachment(context.Context, repository.CreateAttachmentParams) (*model.Attachment, error) {
|
||||
return nil, errors.New("unexpected INSERT")
|
||||
}
|
||||
func (tx cleanupTx) GetAttachmentByID(context.Context, string) (*model.Attachment, error) {
|
||||
return nil, errors.New("unexpected attachment lookup")
|
||||
}
|
||||
func (tx cleanupTx) ExistsByObjectKey(ctx context.Context, key string) (bool, error) {
|
||||
r := tx.repo
|
||||
if r.locked != key {
|
||||
return false, errors.New("EXISTS outside locked transaction")
|
||||
}
|
||||
r.checked = append(r.checked, key)
|
||||
return r.referenced[key], r.existsErr
|
||||
}
|
||||
func (r *cleanupRepo) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) {
|
||||
if key == r.busy {
|
||||
return false, nil
|
||||
}
|
||||
r.locked = key
|
||||
defer func() { r.locked = "" }()
|
||||
return true, fn(ctx, cleanupTx{repo: r})
|
||||
}
|
||||
|
||||
type cleanupStore struct {
|
||||
pages map[string][]storage.ObjectInfo
|
||||
next map[string]string
|
||||
listed, deleted []string
|
||||
repo *cleanupRepo
|
||||
listErr, deleteErr error
|
||||
waitList bool
|
||||
}
|
||||
|
||||
func (s *cleanupStore) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) {
|
||||
if prefix != "attachments/" {
|
||||
return nil, nil, errors.New("unexpected prefix")
|
||||
}
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
return nil, nil, errors.New("LIST did not receive deadline")
|
||||
}
|
||||
if s.waitList {
|
||||
<-ctx.Done()
|
||||
return nil, nil, ctx.Err()
|
||||
}
|
||||
key := aws.ToString(token)
|
||||
s.listed = append(s.listed, key)
|
||||
if s.listErr != nil {
|
||||
return nil, nil, s.listErr
|
||||
}
|
||||
if next, ok := s.next[key]; ok {
|
||||
return s.pages[key], &next, nil
|
||||
}
|
||||
return s.pages[key], nil, nil
|
||||
}
|
||||
func (s *cleanupStore) Delete(_ context.Context, key string) error {
|
||||
if s.repo.locked != key {
|
||||
return errors.New("DELETE outside locked transaction")
|
||||
}
|
||||
s.deleted = append(s.deleted, key)
|
||||
return s.deleteErr
|
||||
}
|
||||
|
||||
func TestAttachmentCleanupPagesAndCutoff(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
now := time.Now()
|
||||
old := now.Add(-time.Minute - time.Nanosecond)
|
||||
orphan := "attachments/orphan"
|
||||
opts := &service.AttachmentCleanupOptions{GracePeriod: time.Minute, ListTimeout: time.Second}
|
||||
repo := &cleanupRepo{referenced: map[string]bool{"attachments/referenced": true}, busy: "attachments/busy"}
|
||||
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{
|
||||
"": {{Key: "attachments/equal", LastModified: now.Add(-time.Minute)},
|
||||
{Key: "attachments/fresh", LastModified: now.Add(-time.Second)},
|
||||
{Key: "attachments/future", LastModified: now.Add(time.Hour)},
|
||||
{Key: "attachments/zero"},
|
||||
{Key: "other/orphan", LastModified: old},
|
||||
{Key: "attachments/busy", LastModified: old}},
|
||||
"last": {{Key: "attachments/referenced", LastModified: old}, {Key: orphan, LastModified: old}},
|
||||
}, next: map[string]string{"": "empty", "empty": "last"}}
|
||||
svc := service.NewAttachmentCleanupService(repo, objects, opts)
|
||||
opts.DryRun = true
|
||||
if err := svc.RunOnce(context.Background()); err != nil || len(objects.deleted) != 0 ||
|
||||
!slices.Equal(repo.checked, []string{"attachments/referenced", orphan}) {
|
||||
t.Fatalf("dry-run must check old unlocked keys without deleting: err=%v checked=%v deletes=%v", err, repo.checked, objects.deleted)
|
||||
}
|
||||
opts.DryRun = false
|
||||
objects.listed = nil
|
||||
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.listed, []string{"", "empty", "last"}) ||
|
||||
!slices.Equal(objects.deleted, []string{orphan}) {
|
||||
t.Fatalf("wrong cutoff or page walk: err=%v pages=%v deletes=%v", err, objects.listed, objects.deleted)
|
||||
}
|
||||
})
|
||||
}
|
||||
func TestAttachmentCleanupFaults(t *testing.T) {
|
||||
for _, name := range []string{"list", "exists", "delete", "list_timeout", "pass_timeout", "canceled"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
repo := &cleanupRepo{}
|
||||
objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{"": {{Key: "attachments/old", LastModified: time.Now().Add(-time.Hour)}}}}
|
||||
svc := service.NewAttachmentCleanupService(repo, objects, &service.AttachmentCleanupOptions{GracePeriod: time.Second, ListTimeout: time.Second})
|
||||
sentinel := errors.New("synthetic " + name + " error")
|
||||
var want error = sentinel
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
switch name {
|
||||
case "list":
|
||||
objects.listErr = sentinel
|
||||
case "exists":
|
||||
repo.existsErr = sentinel
|
||||
case "delete":
|
||||
objects.deleteErr = sentinel
|
||||
case "list_timeout":
|
||||
objects.waitList = true
|
||||
want = context.DeadlineExceeded
|
||||
case "pass_timeout":
|
||||
var stop context.CancelFunc
|
||||
ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer stop()
|
||||
objects.waitList = true
|
||||
want = context.DeadlineExceeded
|
||||
case "canceled":
|
||||
cancel()
|
||||
want = context.Canceled
|
||||
}
|
||||
start := time.Now()
|
||||
got := svc.RunOnce(ctx)
|
||||
if !errors.Is(got, want) {
|
||||
t.Fatalf("want %v, got %v", want, got)
|
||||
}
|
||||
if (name == "list_timeout" && time.Since(start) != time.Second) ||
|
||||
(name == "pass_timeout" && time.Since(start) != 100*time.Millisecond) {
|
||||
t.Fatal("wrong cancellation budget")
|
||||
}
|
||||
if name != "delete" && len(objects.deleted) > 0 {
|
||||
t.Fatal("DELETE ran after unsafe precondition")
|
||||
}
|
||||
if name == "delete" && len(objects.deleted) != 1 {
|
||||
t.Fatal("DELETE fault not reached")
|
||||
}
|
||||
repo.existsErr, objects.listErr, objects.deleteErr = nil, nil, nil
|
||||
objects.waitList = false
|
||||
objects.deleted = nil
|
||||
if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.deleted, []string{"attachments/old"}) {
|
||||
t.Fatalf("cleanup did not recover: %v %v", err, objects.deleted)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type cleanupListTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (fn cleanupListTransport) Do(req *http.Request) (*http.Response, error) { return fn(req) }
|
||||
|
||||
func TestAttachmentCleanupS3InvalidNextToken(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
token *string
|
||||
xml string
|
||||
}{
|
||||
{"missing", nil, ""},
|
||||
{"empty", nil, "<NextContinuationToken></NextContinuationToken>"},
|
||||
{"repeat", aws.String("same"), "<NextContinuationToken>same</NextContinuationToken>"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
n := 0
|
||||
obj := &s3.Storage{Bucket: "test", Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://cleanup.invalid"),
|
||||
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{},
|
||||
HTTPClient: cleanupListTransport(func(req *http.Request) (*http.Response, error) {
|
||||
n++
|
||||
if req.URL.Query().Get("continuation-token") != aws.ToString(tc.token) {
|
||||
return nil, errors.New("wrong request token")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(
|
||||
"<ListBucketResult><IsTruncated>true</IsTruncated>" + tc.xml + "</ListBucketResult>"))}, nil
|
||||
}),
|
||||
})}
|
||||
_, _, err := obj.ListPage(context.Background(), tc.token, "attachments/")
|
||||
if !errors.Is(err, storage.ErrStorage) || n != 1 {
|
||||
t.Fatalf("invalid token was not rejected: %v, calls=%d", err, n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
repo "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage"
|
||||
"highload/internal/storage/s3"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func newAttachmentTxFixture(t *testing.T) (*fixture, repo.CreateAttachmentParams) {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 4)
|
||||
owner := uuid.NewString()
|
||||
if _, err := f.pool.Exec(f.ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,'tx_fixture','TX fixture','unused')", owner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := postgres.NewChatRepository(f.queries, f.pool).CreateChat(f.ctx, "Attachment transaction", []string{owner})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f, repo.CreateAttachmentParams{
|
||||
ChatID: chat.ID, OwnerID: owner, ObjectKey: "attachments/" + uuid.NewString(),
|
||||
Filename: "fixture.png", ContentType: "image/png", SizeBytes: 1, Sha256: strings.Repeat("a", 64),
|
||||
}
|
||||
}
|
||||
|
||||
func assertAttachmentCount(t *testing.T, f *fixture, want int) {
|
||||
t.Helper()
|
||||
var attachments, jobs, outbox int
|
||||
err := f.pool.QueryRow(f.ctx, `SELECT (SELECT count(*) FROM attachments),
|
||||
(SELECT count(*) FROM attachment_jobs), (SELECT count(*) FROM outbox)`).Scan(&attachments, &jobs, &outbox)
|
||||
if err != nil || attachments != want || jobs != want || outbox != want {
|
||||
t.Fatalf("expected %d rows each, got attachments=%d jobs=%d outbox=%d (%v)", want, attachments, jobs, outbox, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentTxLockAndRollback(t *testing.T) {
|
||||
f, params := newAttachmentTxFixture(t)
|
||||
// Run the isolation check on the very connection doing the callback INSERT.
|
||||
// A query through the pool would only establish the observer's isolation.
|
||||
if _, err := f.pool.Exec(f.ctx, `
|
||||
CREATE FUNCTION assert_attachment_isolation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF current_setting('transaction_isolation') <> 'read committed' THEN
|
||||
RAISE EXCEPTION 'expected read committed during attachment INSERT';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER assert_attachment_isolation BEFORE INSERT ON attachments
|
||||
FOR EACH ROW EXECUTE FUNCTION assert_attachment_isolation();
|
||||
`, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
||||
id := uuid.NewString()
|
||||
key := "staging/" + id + "/original"
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
type outcome struct {
|
||||
locked bool
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 1)
|
||||
holdCtx, cancelHold := context.WithCancel(f.ctx)
|
||||
defer cancelHold()
|
||||
go func() {
|
||||
locked, err := attachments.WithObjectKeyLock(holdCtx, key, func(ctx context.Context, _ repo.AttachmentTx) error {
|
||||
close(entered)
|
||||
select {
|
||||
case <-release:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
})
|
||||
done <- outcome{locked, err}
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case result := <-done:
|
||||
t.Fatalf("holder never entered callback: %+v", result)
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("holder did not acquire the lock")
|
||||
}
|
||||
unexpected := func(context.Context, repo.AttachmentTx) error {
|
||||
return errors.New("contending callback ran")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, unexpected); locked || err != nil {
|
||||
t.Fatalf("same key must return false, nil without callback: %t, %v", locked, err)
|
||||
}
|
||||
noop := func(context.Context, repo.AttachmentTx) error { return nil }
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key+"-other", noop); !locked || err != nil {
|
||||
t.Fatalf("another key was blocked: %t, %v", locked, err)
|
||||
}
|
||||
close(release)
|
||||
select {
|
||||
case result := <-done:
|
||||
if !result.locked || result.err != nil {
|
||||
t.Fatalf("holder did not complete: %+v", result)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("holder did not close its transaction")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
||||
t.Fatalf("committed lock was not released: %t, %v", locked, err)
|
||||
}
|
||||
|
||||
for _, name := range []string{"callback_error", "context_canceled"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
sentinel := errors.New("synthetic callback failure")
|
||||
ctx, cancel := context.WithCancel(f.ctx)
|
||||
defer cancel()
|
||||
want := error(sentinel)
|
||||
if name == "context_canceled" {
|
||||
want = context.Canceled
|
||||
}
|
||||
locked, err := attachments.WithObjectKeyLock(ctx, key, func(txCtx context.Context, tx repo.AttachmentTx) error {
|
||||
if _, err := tx.CreateQueued(txCtx, id, params.ChatID, params.OwnerID, params.ContentType,
|
||||
params.Sha256, key, params.Filename, params.SizeBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
exists, err := tx.ExistsByObjectKey(txCtx, key)
|
||||
if err != nil || !exists {
|
||||
return fmt.Errorf("transaction did not see its INSERT: %w", err)
|
||||
}
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if name == "context_canceled" {
|
||||
cancel()
|
||||
return txCtx.Err()
|
||||
}
|
||||
return sentinel
|
||||
})
|
||||
if !locked || err != want {
|
||||
t.Fatalf("callback error must pass through unchanged with true: %t, %v", locked, err)
|
||||
}
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if locked, err = attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
||||
t.Fatalf("rollback failed to free lock/pool: %t, %v", locked, err)
|
||||
}
|
||||
t.Log("INSERT ran at read committed, rollback left zero rows and released the lock")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// txS3Transport observes the real SDK requests and retains synthetic bytes for GET.
|
||||
// Before accepting a PUT it challenges the lock from a separate PostgreSQL session.
|
||||
type txS3Transport struct {
|
||||
fixture *fixture
|
||||
key string
|
||||
data []byte
|
||||
put, get, delete int
|
||||
failPut bool
|
||||
}
|
||||
|
||||
func (s *txS3Transport) Do(request *http.Request) (*http.Response, error) {
|
||||
resp := &http.Response{StatusCode: 200, Header: make(http.Header), Body: http.NoBody}
|
||||
key := strings.TrimPrefix(request.URL.Path, "/tx-test/")
|
||||
parts := strings.Split(key, "/")
|
||||
if len(parts) != 3 || parts[0] != "staging" || parts[2] != "original" {
|
||||
return nil, errors.New("unexpected synthetic S3 staging key")
|
||||
}
|
||||
if _, err := uuid.Parse(parts[1]); err != nil {
|
||||
return nil, errors.New("staging key lacks an attachment UUID")
|
||||
}
|
||||
switch request.Method {
|
||||
case http.MethodPut:
|
||||
s.put++
|
||||
s.key = key
|
||||
var acquired bool
|
||||
err := s.fixture.pool.QueryRow(request.Context(),
|
||||
"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", key).Scan(&acquired)
|
||||
if err != nil || acquired {
|
||||
return nil, fmt.Errorf("PUT ran without held object lock: acquired=%t, error=%v", acquired, err)
|
||||
}
|
||||
if s.failPut {
|
||||
resp.StatusCode = 503
|
||||
resp.Header.Set("Content-Type", "application/xml")
|
||||
resp.Body = io.NopCloser(strings.NewReader("<Error><Code>SlowDown</Code><Message>Synthetic outage</Message></Error>"))
|
||||
return resp, nil
|
||||
}
|
||||
defer request.Body.Close()
|
||||
s.data, err = io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case http.MethodGet:
|
||||
s.get++
|
||||
if key != s.key || s.data == nil {
|
||||
return nil, errors.New("object unavailable in fixture")
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(s.data))
|
||||
resp.ContentLength = int64(len(s.data))
|
||||
case http.MethodDelete:
|
||||
s.delete++
|
||||
s.data = nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected S3 method %s", request.Method)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func TestAttachmentTxHTTP(t *testing.T) {
|
||||
_, source, _, _ := runtime.Caller(0)
|
||||
png, err := os.ReadFile(filepath.Join(filepath.Dir(source), "../../tests/fixtures/sample.png"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := fmt.Sprintf("%x", sha256.Sum256(png))
|
||||
for _, scenario := range []struct {
|
||||
name string
|
||||
faultSQL string
|
||||
http int
|
||||
errorCode string
|
||||
}{
|
||||
{name: "s3_unavailable", http: 503, errorCode: "unavailable"},
|
||||
{name: "insert_after_put", faultSQL: "ALTER TABLE attachments ADD CHECK (filename <> 'fixture.png')", http: 500, errorCode: "internal_error"},
|
||||
{name: "commit_after_insert", faultSQL: `
|
||||
CREATE FUNCTION reject_attachment_commit() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'synthetic deferred failure'; END $$;
|
||||
CREATE CONSTRAINT TRIGGER reject_attachment_commit AFTER INSERT ON attachments
|
||||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_attachment_commit();
|
||||
`, http: 500, errorCode: "internal_error"},
|
||||
{name: "committed_upload_is_queued", http: http.StatusAccepted},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
f, params := newAttachmentTxFixture(t)
|
||||
if scenario.faultSQL != "" {
|
||||
if _, err := f.pool.Exec(f.ctx, scenario.faultSQL, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
transport := &txS3Transport{fixture: f, failPut: scenario.http == 503}
|
||||
objects := &s3.Storage{Bucket: "tx-test", Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://tx-s3.invalid"),
|
||||
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{}, HTTPClient: transport,
|
||||
})}
|
||||
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), nil, nil)
|
||||
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
||||
svc := service.NewAttachmentService(attachments, chats, objects)
|
||||
h := handler.NewAttachmentHandler(svc)
|
||||
call := func(method, path, param, value string, data []byte, next http.HandlerFunc) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, bytes.NewReader(data))
|
||||
r = r.WithContext(middleware.WithUserID(f.ctx, params.OwnerID))
|
||||
r.SetPathValue(param, value)
|
||||
r.Header.Set("Content-Type", "image/png")
|
||||
w := httptest.NewRecorder()
|
||||
mid := middleware.NewMiddleware(nil, "attachment-tx")
|
||||
mid.InstanceID(mid.RequestID(next)).ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
w := call(http.MethodPost, "/attachments?filename=fixture.png", "chat_id", params.ChatID, png, h.CreateAttachment)
|
||||
if transport.put != 1 || transport.delete != 0 {
|
||||
t.Fatalf("expected one PUT and zero DELETE, got %d/%d", transport.put, transport.delete)
|
||||
}
|
||||
if scenario.http != http.StatusAccepted {
|
||||
assertContractError(t, w, scenario.http, scenario.errorCode)
|
||||
assertAttachmentCount(t, f, 0)
|
||||
if scenario.http == 503 {
|
||||
if transport.data != nil {
|
||||
t.Fatal("failed S3 PUT stored an object")
|
||||
}
|
||||
_, err := svc.CreateAttachment(f.ctx, params.ChatID, params.OwnerID, "fixture.png", "image/png", bytes.NewReader(png), int64(len(png)))
|
||||
if !errors.Is(err, service.ErrServiceUnavailable) || errors.Is(err, storage.ErrStorage) {
|
||||
t.Fatalf("storage category did not reach service as unavailable: %v", err)
|
||||
}
|
||||
} else if !bytes.Equal(transport.data, png) {
|
||||
t.Fatal("failed database write did not leave the already stored original")
|
||||
}
|
||||
if locked, err := attachments.WithObjectKeyLock(f.ctx, transport.key, func(context.Context, repo.AttachmentTx) error { return nil }); !locked || err != nil {
|
||||
t.Fatalf("failed upload left key locked: %t, %v", locked, err)
|
||||
}
|
||||
t.Logf("direct handler HTTP %d; committed rows=0; DELETE=0", w.Code)
|
||||
return
|
||||
}
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("expected 202 after commit, got %d", w.Code)
|
||||
}
|
||||
assertAttachmentCount(t, f, 1)
|
||||
var response struct {
|
||||
ID string `json:"id"`
|
||||
SHA string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []json.RawMessage `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.SHA != hash ||
|
||||
response.Status != "queued" || response.Variants == nil || len(response.Variants) != 0 || response.ErrorCode != nil {
|
||||
t.Fatal("invalid queued upload response or SHA-256")
|
||||
}
|
||||
row, err := attachments.GetAttachmentForUser(f.ctx, params.OwnerID, response.ID)
|
||||
if err != nil || row.SHA256 != hash || row.ObjectKey != "" || row.StagingKey != transport.key ||
|
||||
transport.key != "staging/"+response.ID+"/original" || row.SizeBytes != int64(len(png)) ||
|
||||
!bytes.Equal(transport.data, png) {
|
||||
t.Fatal("committed metadata/staging does not match uploaded file")
|
||||
}
|
||||
var linked bool
|
||||
err = f.pool.QueryRow(f.ctx, `SELECT EXISTS(SELECT 1 FROM attachment_jobs j
|
||||
JOIN outbox o ON o.job_id=j.id WHERE j.attachment_id=$1
|
||||
AND o.payload->>'attachment_id' = $1::uuid::text AND o.payload->>'job_id'=j.id::text
|
||||
AND o.sent_at IS NULL)`, response.ID).Scan(&linked)
|
||||
if err != nil || !linked {
|
||||
t.Fatal("202 lacks a pending outbox record for the same durable job")
|
||||
}
|
||||
get := call(http.MethodGet, "/attachments/"+response.ID, "attachment_id", response.ID, nil, h.GetAttachment)
|
||||
if get.Code != 200 || !bytes.Equal(bytes.TrimSpace(get.Body.Bytes()), bytes.TrimSpace(w.Body.Bytes())) {
|
||||
t.Fatal("metadata GET changed")
|
||||
}
|
||||
body := call(http.MethodGet, "/attachments/"+response.ID+"/content", "attachment_id", response.ID, nil, h.GetAttachmentContent)
|
||||
assertContractError(t, body, http.StatusConflict, "conflict")
|
||||
if transport.get != 0 {
|
||||
t.Fatal("content GET attempted to read S3 for a queued attachment")
|
||||
}
|
||||
t.Logf("HTTP 202, attachment/job/outbox committed, metadata=200, queued content=409, SHA-256=%s", hash)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func TestStorageAuthHandlerRejectsJSONBody(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
auth := handler.NewAuthHandler(f.auth)
|
||||
mid := middleware.NewMiddleware(f.auth, "auth-test")
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
// Exercise the real handler independently of Router wiring.
|
||||
// This component test does not replace the end-to-end login acceptance test.
|
||||
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Errorf("login with JSON body must return 400; received %d", recorder.Code)
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Error("login with forbidden JSON body attempted to create a session")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"highload/internal/database"
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
)
|
||||
|
||||
func operationBudget(t *testing.T) time.Duration {
|
||||
t.Helper()
|
||||
value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS")
|
||||
if value == "" {
|
||||
t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending")
|
||||
return 3 * time.Second
|
||||
}
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < 500 || n > 10000 {
|
||||
t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000")
|
||||
}
|
||||
return time.Duration(n) * time.Millisecond
|
||||
}
|
||||
|
||||
func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL"))
|
||||
if err != nil {
|
||||
t.Fatal("invalid test URL")
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"])
|
||||
u.RawQuery = q.Encode()
|
||||
// Actual production constructor: never inherit fixture statement_timeout.
|
||||
pool, err := database.NewPostgres(f.ctx, u.String())
|
||||
if err != nil {
|
||||
t.Fatal("application pool unavailable")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
return pool
|
||||
}
|
||||
|
||||
func blockOperation(t *testing.T, f *fixture, mode string) func() {
|
||||
t.Helper()
|
||||
if mode == "blocked_query" {
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("lock transaction failed")
|
||||
}
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("isolated table lock failed")
|
||||
}
|
||||
return func() {
|
||||
ctx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
_ = tx.Rollback(ctx)
|
||||
}
|
||||
}
|
||||
max := f.pool.Config().MaxConns
|
||||
if max <= 0 || max > 128 {
|
||||
t.Fatal("test refuses unbounded/oversized pool")
|
||||
}
|
||||
held := make([]*pgxpool.Conn, 0, max)
|
||||
for range max {
|
||||
conn, err := f.pool.Acquire(f.ctx)
|
||||
if err != nil {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
t.Fatal("pool saturation failed")
|
||||
}
|
||||
held = append(held, conn)
|
||||
}
|
||||
return func() {
|
||||
for _, h := range held {
|
||||
h.Release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresOperationsHaveBoundedWaits(t *testing.T) {
|
||||
budget := operationBudget(t)
|
||||
for _, mode := range []string{"blocked_query", "exhausted_pool"} {
|
||||
for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} {
|
||||
t.Run(mode+"/"+scenario, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
applicationPool(t, f)
|
||||
release := blockOperation(t, f, mode)
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
release()
|
||||
}
|
||||
}()
|
||||
safety := budget + 2*time.Second
|
||||
if scenario == "shorter_caller_deadline" {
|
||||
safety = 150 * time.Millisecond
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), safety)
|
||||
defer cancel()
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
done := make(chan struct{})
|
||||
started := time.Now()
|
||||
go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }()
|
||||
if scenario == "released_before_budget" {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
<-done
|
||||
elapsed := time.Since(started)
|
||||
t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil)
|
||||
switch scenario {
|
||||
case "application_budget":
|
||||
if ctx.Err() != nil || elapsed > budget+250*time.Millisecond {
|
||||
t.Error("application did not independently enforce its operation budget before test safety cancellation")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "shorter_caller_deadline":
|
||||
if elapsed > 750*time.Millisecond {
|
||||
t.Error("short caller deadline was not honored")
|
||||
}
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
case "released_before_budget":
|
||||
if recorder.Code != 200 || elapsed >= budget {
|
||||
t.Error("unblocked operation failed or missed the declared budget")
|
||||
}
|
||||
}
|
||||
if !released {
|
||||
release()
|
||||
released = true
|
||||
}
|
||||
recovery := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("GET", "/api/v1/users/me", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer c()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx))
|
||||
if recovery.Code != 200 {
|
||||
t.Error("service did not recover after releasing lock/pool")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("application pool leaked an acquired connection")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
applicationPool(t, f)
|
||||
tx, err := f.admin.Begin(f.ctx)
|
||||
if err != nil {
|
||||
t.Fatal("cannot start membership blocker")
|
||||
}
|
||||
released := false
|
||||
defer func() {
|
||||
if !released {
|
||||
_ = tx.Rollback(context.Background())
|
||||
}
|
||||
}()
|
||||
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize()
|
||||
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
|
||||
t.Fatal("cannot block membership insertion")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
repo := postgres.NewChatRepository(f.queries, f.pool)
|
||||
_, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID})
|
||||
if !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err)
|
||||
}
|
||||
// The membership INSERT cannot finish while this lock is held, so COMMIT
|
||||
// has not been reached. No ambiguous-commit inference is made here.
|
||||
_ = tx.Rollback(context.Background())
|
||||
released = true
|
||||
for _, name := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 {
|
||||
t.Error("pre-commit cancellation left partial chat data")
|
||||
}
|
||||
}
|
||||
if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil {
|
||||
t.Error("chat repository failed to recover")
|
||||
}
|
||||
if f.pool.Stat().AcquiredConns() != 0 {
|
||||
t.Error("chat cancellation leaked a connection")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
"highload/internal/repository"
|
||||
)
|
||||
|
||||
type logoutObservationKey struct{}
|
||||
type logoutObservation struct {
|
||||
Group int `json:"clients"`
|
||||
Round int `json:"round"`
|
||||
PauseMS int `json:"pause_ms"`
|
||||
ElapsedMS float64 `json:"elapsed_ms"`
|
||||
WaitMS float64 `json:"waitaof_ms"`
|
||||
DelID int64 `json:"del_connection_id"`
|
||||
WaitID int64 `json:"wait_connection_id"`
|
||||
Local *int64 `json:"local_fsynced"`
|
||||
Replicas *int64 `json:"replicas_fsynced"`
|
||||
Kind string `json:"kind"`
|
||||
CommandError string `json:"command_error,omitempty"`
|
||||
RepositoryError string `json:"repository_error,omitempty"`
|
||||
}
|
||||
type logoutAOFObservation struct{}
|
||||
|
||||
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
started := time.Now()
|
||||
err := next(ctx, cmd)
|
||||
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
|
||||
if row == nil {
|
||||
return err
|
||||
}
|
||||
name := cmd.Name()
|
||||
if name != "del" && name != "waitaof" {
|
||||
return err
|
||||
}
|
||||
if name == "waitaof" {
|
||||
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.CommandError = err.Error()
|
||||
row.Kind = "command_error"
|
||||
} else {
|
||||
if value, ok := cmd.(*redisclient.Cmd); ok {
|
||||
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
|
||||
local, lok := reply[0].(int64)
|
||||
replicas, rok := reply[1].(int64)
|
||||
if lok && rok {
|
||||
row.Local = &local
|
||||
row.Replicas = &replicas
|
||||
row.Kind = "acknowledged"
|
||||
if local != 1 {
|
||||
row.Kind = "unacknowledged"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if row.Local == nil {
|
||||
row.Kind = "unexpected_reply"
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
// next is bound to this Conn's processing path. The observation adds a
|
||||
// read-only CLIENT ID on that same path; it never gets a second pool slot.
|
||||
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
|
||||
if e := next(ctx, id); e == nil {
|
||||
if name == "del" {
|
||||
row.DelID = id.Val()
|
||||
} else {
|
||||
row.WaitID = id.Val()
|
||||
}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
f.client.AddHook(logoutAOFObservation{})
|
||||
before := f.client.PoolStats()
|
||||
rows := []logoutObservation{}
|
||||
var mu sync.Mutex
|
||||
stop := make(chan struct{})
|
||||
sampled := make(chan struct{})
|
||||
poolSamples := []map[string]any{}
|
||||
go func() {
|
||||
defer close(sampled)
|
||||
ticker := time.NewTicker(50 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() {
|
||||
close(stop)
|
||||
<-sampled
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
after := f.client.PoolStats()
|
||||
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
|
||||
t.Error("logout left acquired/pending pool connections")
|
||||
}
|
||||
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
|
||||
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
|
||||
_ = os.MkdirAll(directory, 0700)
|
||||
data, _ := json.MarshalIndent(report, "", " ")
|
||||
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
|
||||
t.Error("cannot save Redis diagnostics")
|
||||
}
|
||||
}
|
||||
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
|
||||
}()
|
||||
run := func(clients, round, pause int) {
|
||||
var workers sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
for range clients {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
// Two sessions for one synthetic identity: revoking one must leave the
|
||||
// other valid, even while other workers revoke their own sessions.
|
||||
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
|
||||
user := uuid.NewString()
|
||||
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
|
||||
t.Error("create logout fixture failed")
|
||||
return
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
|
||||
t.Error("create independent fixture failed")
|
||||
return
|
||||
}
|
||||
<-start
|
||||
time.Sleep(time.Duration(pause) * time.Millisecond)
|
||||
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
|
||||
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
|
||||
began := time.Now()
|
||||
_, err := f.repo.RevokeSession(ctx, first[:])
|
||||
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
|
||||
if err != nil {
|
||||
row.RepositoryError = err.Error()
|
||||
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
|
||||
}
|
||||
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
|
||||
t.Error("unacknowledged local fsync must preserve unavailable category")
|
||||
}
|
||||
if row.DelID == 0 || row.DelID != row.WaitID {
|
||||
t.Error("DEL/WAITAOF connection identity not preserved")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
|
||||
t.Error("concurrent logout affected independent session")
|
||||
}
|
||||
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
|
||||
t.Error("revoked session still available")
|
||||
}
|
||||
mu.Lock()
|
||||
rows = append(rows, row)
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
workers.Wait()
|
||||
}
|
||||
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
|
||||
run(1, i+1, pause)
|
||||
}
|
||||
for _, clients := range []int{5, 10} {
|
||||
for round := 1; round <= 3; round++ {
|
||||
run(clients, round, 137*round)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
|
||||
var diagnosticTrackMu sync.Mutex
|
||||
|
||||
func (f *redisFixture) trackSafe(token string) [32]byte {
|
||||
diagnosticTrackMu.Lock()
|
||||
defer diagnosticTrackMu.Unlock()
|
||||
return f.track(token)
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/model"
|
||||
domainrepo "highload/internal/repository"
|
||||
postgresrepo "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Uses the real handler/service/PostgreSQL repository and metadata-only fixtures.
|
||||
// Authentication is already covered by the existing auth tests: only the current
|
||||
// user context is injected here. No S3 server, upload endpoint or Redis is needed.
|
||||
type messageAttachmentFixture struct {
|
||||
*fixture
|
||||
http http.Handler
|
||||
alice, bob string
|
||||
chat, other *model.Chat
|
||||
ids, foreign []string
|
||||
}
|
||||
|
||||
type attachmentMessage struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
// Small dependencies for the real service's one-attachment regression. They
|
||||
// compare UUID identity without prescribing where normalization takes place.
|
||||
// They do not implement persistence/idempotency: PostgreSQL cases prove that.
|
||||
type singleAttachmentChatRepo struct {
|
||||
domainrepo.ChatRepository
|
||||
chat *model.Chat
|
||||
}
|
||||
|
||||
func (r *singleAttachmentChatRepo) GetChatByID(_ context.Context, id string) (*model.Chat, error) {
|
||||
if id != r.chat.ID {
|
||||
return nil, domainrepo.ErrNotFound
|
||||
}
|
||||
return r.chat, nil
|
||||
}
|
||||
|
||||
type singleAttachmentMessageRepo struct {
|
||||
domainrepo.MessageRepository
|
||||
message *model.Message
|
||||
key string
|
||||
calls [][]string
|
||||
}
|
||||
|
||||
func (r *singleAttachmentMessageRepo) CreateMessage(_ context.Context, chatID, userID, text, key string, ids []string) (*model.Message, error) {
|
||||
r.calls = append(r.calls, append([]string{}, ids...))
|
||||
if chatID != r.message.ChatID || userID != r.message.SenderID || text != r.message.Text || key != r.key {
|
||||
return nil, domainrepo.ErrServerError
|
||||
}
|
||||
if len(ids) != len(r.message.AttachmentIDs) {
|
||||
return nil, domainrepo.ErrInvalidInput
|
||||
}
|
||||
for index, raw := range ids {
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil || id.String() != r.message.AttachmentIDs[index] {
|
||||
return nil, domainrepo.ErrInvalidInput
|
||||
}
|
||||
}
|
||||
return r.message, nil
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsSingleIDServiceRegression(t *testing.T) {
|
||||
const attachmentID = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
|
||||
for _, scenario := range []struct {
|
||||
name, inputID string
|
||||
requests int
|
||||
}{
|
||||
{name: "single_attachment_without_panic", inputID: attachmentID, requests: 1},
|
||||
{name: "identical_uppercase_body_replay", inputID: strings.ToUpper(attachmentID), requests: 2},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
t.Errorf("CreateMessage with one valid attachment panicked: %v", recovered)
|
||||
}
|
||||
}()
|
||||
userID, chatID, key := uuid.NewString(), uuid.NewString(), uuid.NewString()
|
||||
original := &model.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: userID,
|
||||
Text: "", AttachmentIDs: []string{attachmentID}, CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
repo := &singleAttachmentMessageRepo{message: original, key: key}
|
||||
chatRepo := &singleAttachmentChatRepo{chat: &model.Chat{ID: chatID, MemberIDs: []string{userID}}}
|
||||
chats := service.NewChatService(chatRepo, nil, nil)
|
||||
messages := service.NewMessageService(repo, chats, nil)
|
||||
for range scenario.requests {
|
||||
// The uppercase case starts uppercase and repeats EXACTLY the same
|
||||
// values. It never assumes different string bodies must be equivalent.
|
||||
input := []string{scenario.inputID}
|
||||
message, err := messages.CreateMessage(context.Background(), "", chatID, userID, key, input)
|
||||
if err != nil || !reflect.DeepEqual(message, original) {
|
||||
t.Fatalf("one attachment / identical uppercase replay: expected original Message without conflict, got %v", err)
|
||||
}
|
||||
}
|
||||
if len(repo.calls) == 0 {
|
||||
t.Fatal("service did not create the message through its repository")
|
||||
}
|
||||
for _, ids := range repo.calls {
|
||||
if len(ids) != 1 {
|
||||
t.Fatal("service lost the single attachment")
|
||||
}
|
||||
id, err := uuid.Parse(ids[0])
|
||||
if err != nil || id.String() != attachmentID {
|
||||
t.Fatal("service changed the attachment UUID identity")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newMessageAttachmentFixture(t *testing.T) *messageAttachmentFixture {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 12)
|
||||
result := &messageAttachmentFixture{fixture: f, alice: uuid.NewString(), bob: uuid.NewString()}
|
||||
for _, id := range []string{result.alice, result.bob} {
|
||||
_, err := f.pool.Exec(f.ctx, `INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES($1,$2,'Synthetic attachment test','fixture-only-not-used-for-login')`,
|
||||
id, "attach_"+strings.ReplaceAll(id, "-", "")[:18])
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare synthetic users")
|
||||
}
|
||||
}
|
||||
chatRepo := postgresrepo.NewChatRepository(f.queries, f.pool)
|
||||
var err error
|
||||
result.chat, err = chatRepo.CreateChat(f.ctx, "Message attachments", []string{result.alice, result.bob})
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare primary chat")
|
||||
}
|
||||
result.other, err = chatRepo.CreateChat(f.ctx, "Other attachment scope", []string{result.alice})
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare other chat")
|
||||
}
|
||||
attachments := postgresrepo.NewAttachmentRepository(f.queries, f.pool)
|
||||
for _, chat := range []*model.Chat{result.chat, result.other} {
|
||||
for i := 0; i < 11; i++ {
|
||||
att, err := attachments.CreateAttachment(f.ctx, domainrepo.CreateAttachmentParams{
|
||||
ChatID: chat.ID, OwnerID: result.alice, Filename: fmt.Sprintf("synthetic-%d.png", i),
|
||||
ObjectKey: "metadata-only/" + uuid.NewString(), ContentType: "image/png",
|
||||
Sha256: strings.Repeat("a", 64), SizeBytes: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal("cannot seed attachment metadata through its PostgreSQL repository")
|
||||
}
|
||||
if chat.ID == result.chat.ID {
|
||||
result.ids = append(result.ids, att.ID)
|
||||
} else {
|
||||
result.foreign = append(result.foreign, att.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deliberately disagree with UUID ordering to catch accidental ORDER BY id.
|
||||
slices.Sort(result.ids)
|
||||
slices.Reverse(result.ids)
|
||||
users := service.NewUserService(postgresrepo.NewUserRepository(f.queries))
|
||||
chats := service.NewChatService(chatRepo, postgresrepo.NewUserRepository(f.queries), users)
|
||||
messages := service.NewMessageService(postgresrepo.NewMessageRepository(f.queries, f.pool), chats, users)
|
||||
h := handler.NewMessageHandler(messages)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage)
|
||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.GetMessagesByChatID)
|
||||
mid := middleware.NewMiddleware(nil, "message-pg-test")
|
||||
result.http = mid.InstanceID(mid.RequestID(mux))
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) call(actor, method, chatID, key string, body any) *httptest.ResponseRecorder {
|
||||
var raw []byte
|
||||
if body != nil {
|
||||
raw, _ = json.Marshal(body)
|
||||
}
|
||||
request := httptest.NewRequest(method, "/api/v1/chats/"+chatID+"/messages?limit=100", bytes.NewReader(raw))
|
||||
request = request.WithContext(middleware.WithUserID(f.ctx, actor))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
f.http.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
func attachmentBody(text string, ids []string) map[string]any {
|
||||
return map[string]any{"text": text, "attachment_ids": ids}
|
||||
}
|
||||
|
||||
func decodeAttachmentMessage(t *testing.T, response *httptest.ResponseRecorder) attachmentMessage {
|
||||
t.Helper()
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("POST message: expected HTTP 201, got %d", response.Code)
|
||||
}
|
||||
var value map[string]json.RawMessage
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil || len(value) != 6 {
|
||||
t.Fatal("Message must contain exactly the six lab4 contract fields, including attachment_ids")
|
||||
}
|
||||
var message attachmentMessage
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil || message.AttachmentIDs == nil {
|
||||
t.Fatal("attachment_ids must be an array, including [] for a text-only message")
|
||||
}
|
||||
for _, id := range []string{message.ID, message.ChatID, message.SenderID} {
|
||||
if _, err := uuid.Parse(id); err != nil {
|
||||
t.Fatal("Message contains an invalid UUID")
|
||||
}
|
||||
}
|
||||
if _, err := time.Parse(time.RFC3339Nano, message.CreatedAt); err != nil || !strings.HasSuffix(message.CreatedAt, "Z") {
|
||||
t.Fatal("Message must preserve a server UTC timestamp")
|
||||
}
|
||||
if response.Header().Get("X-Request-Id") == "" || response.Header().Get("X-Instance-Id") != "message-pg-test" {
|
||||
t.Fatal("message response is missing request/instance identity")
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) history(t *testing.T) []attachmentMessage {
|
||||
t.Helper()
|
||||
r := f.call(f.bob, "GET", f.chat.ID, "", nil)
|
||||
var page struct {
|
||||
Items []attachmentMessage `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
if r.Code != 200 || json.Unmarshal(r.Body.Bytes(), &page) != nil || page.NextCursor != nil {
|
||||
t.Fatal("cannot read the complete synthetic history")
|
||||
}
|
||||
for _, message := range page.Items {
|
||||
if message.AttachmentIDs == nil {
|
||||
t.Fatal("history must include attachment_ids arrays")
|
||||
}
|
||||
}
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) assertLinks(t *testing.T, message attachmentMessage, expected []string) {
|
||||
t.Helper()
|
||||
if !sameOrderedAttachmentUUIDs(message.AttachmentIDs, expected) {
|
||||
t.Fatal("Message attachment order or contents differ from request")
|
||||
}
|
||||
rows, err := f.pool.Query(f.ctx, `SELECT attachment_id::text, position, chat_id::text
|
||||
FROM messages_attachments WHERE message_id=$1 ORDER BY position`, message.ID)
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect attachment links")
|
||||
}
|
||||
defer rows.Close()
|
||||
var actual []string
|
||||
for rows.Next() {
|
||||
var id, chatID string
|
||||
var position int
|
||||
if rows.Scan(&id, &position, &chatID) != nil || position != len(actual) || chatID != f.chat.ID {
|
||||
t.Fatal("attachment link has incorrect position or chat scope")
|
||||
}
|
||||
actual = append(actual, id)
|
||||
}
|
||||
if rows.Err() != nil || !slices.Equal(actual, expected) {
|
||||
t.Fatal("database links do not match exactly the submitted attachment order")
|
||||
}
|
||||
}
|
||||
|
||||
func sameOrderedAttachmentUUIDs(actual, expected []string) bool {
|
||||
if actual == nil || len(actual) != len(expected) {
|
||||
return false
|
||||
}
|
||||
for index, raw := range actual {
|
||||
id, err := uuid.Parse(raw)
|
||||
want, wantErr := uuid.Parse(expected[index])
|
||||
if err != nil || wantErr != nil || id != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sameHistoryMessage(actual, expected attachmentMessage) bool {
|
||||
if !sameOrderedAttachmentUUIDs(actual.AttachmentIDs, expected.AttachmentIDs) {
|
||||
return false
|
||||
}
|
||||
actual.AttachmentIDs = expected.AttachmentIDs
|
||||
return reflect.DeepEqual(actual, expected)
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) snapshot(t *testing.T) map[string][]string {
|
||||
t.Helper()
|
||||
state := make(map[string][]string)
|
||||
for _, table := range []string{"messages", "messages_attachments", "message_idempotency", "attachments"} {
|
||||
// Table names are fixed test constants, never request input.
|
||||
rows, err := f.pool.Query(f.ctx, "SELECT to_jsonb(item)::text FROM "+table+" AS item ORDER BY to_jsonb(item)::text")
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect transaction state")
|
||||
}
|
||||
for rows.Next() {
|
||||
var row string
|
||||
if rows.Scan(&row) != nil {
|
||||
t.Fatal("cannot decode transaction state")
|
||||
}
|
||||
state[table] = append(state[table], row)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
t.Fatal("cannot finish inspecting transaction state")
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func (f *messageAttachmentFixture) assertUnchanged(t *testing.T, before map[string][]string) {
|
||||
t.Helper()
|
||||
if !reflect.DeepEqual(before, f.snapshot(t)) {
|
||||
t.Fatal("failed/conflicting request changed messages, links, idempotency or metadata")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsTextCompatibility(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
key := uuid.NewString()
|
||||
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, map[string]any{"text": "Legacy text 👋"}))
|
||||
second := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody(first.Text, []string{})))
|
||||
if first.ChatID != f.chat.ID || first.SenderID != f.alice || first.Text != "Legacy text 👋" || !reflect.DeepEqual(first, second) {
|
||||
t.Fatal("absent attachment_ids and [] must preserve the same text-only Message")
|
||||
}
|
||||
f.assertLinks(t, first, []string{})
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("text-only replay changed or duplicated history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsOnlyAndOrderZeroToTen(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for count := 0; count <= 10; count++ {
|
||||
t.Run(fmt.Sprintf("count_%d", count), func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids := append([]string{}, f.ids[:count]...)
|
||||
text := ""
|
||||
if count == 0 {
|
||||
text = "Text without attachments"
|
||||
}
|
||||
key := uuid.NewString()
|
||||
body := attachmentBody(text, ids)
|
||||
if count == 1 {
|
||||
body = attachmentBody(text, []string{strings.ToUpper(ids[0])})
|
||||
}
|
||||
first := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body))
|
||||
if count == 1 {
|
||||
before := f.snapshot(t)
|
||||
if replay := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
|
||||
t.Fatal("identical JSON with uppercase attachment UUID must replay the same 201/Message")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
if first.Text != text || first.SenderID != f.bob || first.ChatID != f.chat.ID {
|
||||
t.Fatal("message-only/attachment-only content or sender changed")
|
||||
}
|
||||
f.assertLinks(t, first, ids)
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("history lost the message or attachment order")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsInvalidReferencesAreAtomic(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for _, kind := range []string{"unknown_id", "attachment_from_other_chat", "foreign_chat"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids, actor, chatID := []string{f.ids[0], uuid.NewString()}, f.alice, f.chat.ID
|
||||
if kind == "attachment_from_other_chat" {
|
||||
ids[1] = f.foreign[0]
|
||||
} else if kind == "foreign_chat" {
|
||||
actor, chatID, ids = f.bob, f.other.ID, []string{f.foreign[0]}
|
||||
}
|
||||
before, key := f.snapshot(t), uuid.NewString()
|
||||
response := f.call(actor, "POST", chatID, key, attachmentBody("Must not be written", ids))
|
||||
assertContractError(t, response, 404, "not_found")
|
||||
f.assertUnchanged(t, before)
|
||||
// A rejected attempt must not reserve this user's key as a final result.
|
||||
valid := decodeAttachmentMessage(t, f.call(actor, "POST", f.chat.ID, key, attachmentBody("Valid after 404", f.ids[:1])))
|
||||
f.assertLinks(t, valid, f.ids[:1])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsInvalidListLeavesNoRows(t *testing.T) {
|
||||
if os.Getenv("LAB4_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL")
|
||||
}
|
||||
for _, kind := range []string{"duplicate", "eleven"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids := f.ids
|
||||
if kind == "duplicate" {
|
||||
ids = []string{f.ids[0], f.ids[0]}
|
||||
}
|
||||
before := f.snapshot(t)
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, uuid.NewString(), attachmentBody("invalid list", ids)), 400, "invalid_request")
|
||||
f.assertUnchanged(t, before)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsIdempotencyIncludesListAndOrder(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
key, ids := uuid.NewString(), f.ids[:2]
|
||||
upperIDs := []string{strings.ToUpper(ids[0]), strings.ToUpper(ids[1])}
|
||||
if slices.Equal(upperIDs, ids) {
|
||||
t.Fatal("normalization fixture must contain a UUID with hexadecimal letters")
|
||||
}
|
||||
body := attachmentBody("Same text", upperIDs)
|
||||
first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body))
|
||||
before := f.snapshot(t)
|
||||
for range 3 {
|
||||
if replay := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) {
|
||||
t.Fatal("same key/body did not return the same Message")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
for _, changed := range [][]string{{ids[1], ids[0]}, {ids[0], f.ids[2]}, {ids[0]}, {}} {
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Same text", changed)), 409, "conflict")
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Changed text", ids)), 409, "conflict")
|
||||
f.assertUnchanged(t, before)
|
||||
f.assertLinks(t, first, ids)
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("idempotency conflict changed history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsConcurrentReplayDoesNotMultiplyLinks(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
const workers = 8
|
||||
key, ids := uuid.NewString(), f.ids[:3]
|
||||
gate := make(chan struct{})
|
||||
results := make(chan *httptest.ResponseRecorder, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
<-gate
|
||||
results <- f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Concurrent attachment replay", ids))
|
||||
}()
|
||||
}
|
||||
close(gate)
|
||||
group.Wait()
|
||||
close(results)
|
||||
var first attachmentMessage
|
||||
for response := range results {
|
||||
message := decodeAttachmentMessage(t, response)
|
||||
if first.ID == "" {
|
||||
first = message
|
||||
} else if !reflect.DeepEqual(message, first) {
|
||||
t.Fatal("concurrent replay returned a different Message")
|
||||
}
|
||||
}
|
||||
f.assertLinks(t, first, ids)
|
||||
state := f.snapshot(t)
|
||||
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != len(ids) || len(state["message_idempotency"]) != 1 {
|
||||
t.Fatal("concurrent replay multiplied message, link or idempotency rows")
|
||||
}
|
||||
if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) {
|
||||
t.Fatal("concurrent replay changed history")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentsLinkFailureRollsBackEverything(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
ids, key := f.ids[:2], uuid.NewString()
|
||||
// The sequence survives rollback. It proves that the fault was reached only
|
||||
// after the first link was visible inside the actual application transaction.
|
||||
_, err := f.pool.Exec(f.ctx, `CREATE SEQUENCE test_link_fault_reached;
|
||||
CREATE FUNCTION fail_second_test_link() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF (SELECT count(*) FROM messages_attachments WHERE message_id=NEW.message_id) >= 1 THEN
|
||||
PERFORM nextval('test_link_fault_reached');
|
||||
RAISE EXCEPTION 'synthetic link failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER test_link_fault BEFORE INSERT ON messages_attachments
|
||||
FOR EACH ROW EXECUTE FUNCTION fail_second_test_link();`)
|
||||
if err != nil {
|
||||
t.Fatal("cannot prepare isolated link fault")
|
||||
}
|
||||
before := f.snapshot(t)
|
||||
response := f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids))
|
||||
assertContractError(t, response, 500, "internal_error")
|
||||
var faultReached bool
|
||||
if f.pool.QueryRow(f.ctx, "SELECT is_called FROM test_link_fault_reached").Scan(&faultReached) != nil || !faultReached {
|
||||
t.Fatal("test did not reach an injected link failure after one real link insert")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
if strings.Contains(response.Body.String(), "synthetic link failure") {
|
||||
t.Fatal("response exposed internal SQL fault details")
|
||||
}
|
||||
if _, err := f.pool.Exec(f.ctx, "DROP TRIGGER test_link_fault ON messages_attachments"); err != nil {
|
||||
t.Fatal("cannot clear isolated link fault")
|
||||
}
|
||||
message := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids)))
|
||||
f.assertLinks(t, message, ids)
|
||||
state := f.snapshot(t)
|
||||
if len(state["messages"]) != 1 || len(state["messages_attachments"]) != 2 || len(state["message_idempotency"]) != 1 {
|
||||
t.Fatal("retry after transient link failure did not commit exactly one complete message")
|
||||
}
|
||||
}
|
||||
|
||||
// The public API has immutable membership. Change it only in the isolated
|
||||
// PostgreSQL fixture to exercise the same sender/key after losing access.
|
||||
func TestMessageReplayRechecksCurrentChatMembership(t *testing.T) {
|
||||
f := newMessageAttachmentFixture(t)
|
||||
const key = "membership-recheck"
|
||||
body := attachmentBody("prior authorized write", []string{})
|
||||
original := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body))
|
||||
before := f.snapshot(t)
|
||||
// Membership is immutable in the real contract, including at the FK.
|
||||
// Remove that FK only in this disposable schema to simulate a stale grant
|
||||
// with historical messages left behind.
|
||||
if _, err := f.pool.Exec(f.ctx, "ALTER TABLE messages DROP CONSTRAINT messages_chat_id_sender_id_fkey"); err != nil {
|
||||
t.Fatal("cannot enable membership fault in the isolated fixture")
|
||||
}
|
||||
tag, err := f.pool.Exec(f.ctx, "DELETE FROM chat_members WHERE chat_id=$1 AND user_id=$2",
|
||||
f.chat.ID, f.bob)
|
||||
if err != nil || tag.RowsAffected() != 1 {
|
||||
t.Fatal("cannot remove sender's membership in the isolated fixture")
|
||||
}
|
||||
denied := f.call(f.bob, "POST", f.chat.ID, key, body)
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if denied.Code != http.StatusNotFound || json.Unmarshal(denied.Body.Bytes(), &payload) != nil ||
|
||||
payload.Error.Code != "not_found" || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != denied.Header().Get("X-Request-Id") {
|
||||
t.Fatalf("replay after losing access must return contract 404, got %d", denied.Code)
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
if _, err := f.pool.Exec(f.ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", f.chat.ID, f.bob); err != nil {
|
||||
t.Fatal("cannot restore sender's membership in the isolated fixture")
|
||||
}
|
||||
if got := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(got, original) {
|
||||
t.Fatal("restored access must replay the original Message")
|
||||
}
|
||||
f.assertUnchanged(t, before)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"highload/internal/security"
|
||||
)
|
||||
|
||||
// These are tests of the selected Argon2id implementation, not a requirement
|
||||
// that lab2 use particular parameters or a particular encoded hash format.
|
||||
func TestPasswordRoundTripAndRandomSalt(t *testing.T) {
|
||||
password := "Синтетический:пароль:😀"
|
||||
first, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
second, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
if first == password || second == password || first == second {
|
||||
t.Fatal("hash must differ from plaintext and have a fresh random salt")
|
||||
}
|
||||
if !strings.HasPrefix(first, "$argon2id$") {
|
||||
t.Fatal("selected password implementation did not encode Argon2id")
|
||||
}
|
||||
for _, encoded := range []string{first, second} {
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored hash does not verify the original password")
|
||||
}
|
||||
ok, err = security.VerifyPassword(password+"x", encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("wrong password was accepted or verifier failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordDoesNotTruncateLongUTF8(t *testing.T) {
|
||||
// Both passwords share much more than bcrypt's 72-byte limit; each is
|
||||
// within the lab's 128-code-point maximum.
|
||||
password := strings.Repeat("😀", 127) + "A"
|
||||
different := strings.Repeat("😀", 127) + "B"
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be hashed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("maximum-length UTF-8 password cannot be verified")
|
||||
}
|
||||
ok, err = security.VerifyPassword(different, encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password suffix was truncated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordWhitespaceIsSignificant(t *testing.T) {
|
||||
password := " synthetic-password "
|
||||
encoded, err := security.HashPassword(password)
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
ok, err := security.VerifyPassword(strings.TrimSpace(password), encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatal("password whitespace was discarded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPasswordHashRejectedWithoutPanic(t *testing.T) {
|
||||
valid, err := security.HashPassword("synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal("password hashing failed")
|
||||
}
|
||||
parts := strings.Split(valid, "$")
|
||||
if len(parts) != 6 {
|
||||
t.Fatal("unexpected encoded hash format")
|
||||
}
|
||||
cases := map[string]string{
|
||||
"empty": "",
|
||||
"plaintext": "synthetic-password",
|
||||
"wrong_algorithm": strings.Replace(valid, "argon2id", "argon2i", 1),
|
||||
"wrong_version": strings.Replace(valid, "$v=19$", "$v=999$", 1),
|
||||
"missing_version": strings.Replace(valid, "$v=19$", "$19$", 1),
|
||||
"extra_field": valid + "$extra",
|
||||
}
|
||||
for name, params := range map[string]string{
|
||||
"zero_iterations": "m=65536,t=0,p=2",
|
||||
"zero_threads": "m=65536,t=3,p=0",
|
||||
"tiny_memory": "m=1,t=3,p=2",
|
||||
"huge_memory": "m=4294967295,t=3,p=2",
|
||||
"huge_iterations": "m=65536,t=4294967295,p=2",
|
||||
"huge_threads": "m=65536,t=3,p=255",
|
||||
"negative": "m=-1,t=3,p=2",
|
||||
"non_numeric": "m=no,t=3,p=2",
|
||||
"missing_param": "m=65536,t=3",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[3] = params
|
||||
cases[name] = strings.Join(copyParts, "$")
|
||||
}
|
||||
for name, field := range map[string]int{"salt": 4, "hash": 5} {
|
||||
for label, value := range map[string]string{
|
||||
"empty": "", "bad_base64": "!!!", "wrong_size": "YQ",
|
||||
} {
|
||||
copyParts := append([]string(nil), parts...)
|
||||
copyParts[field] = value
|
||||
cases[name+"_"+label] = strings.Join(copyParts, "$")
|
||||
}
|
||||
}
|
||||
for name, encoded := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("malformed stored hash caused a panic")
|
||||
}
|
||||
}()
|
||||
ok, err := security.VerifyPassword("synthetic-password", encoded)
|
||||
if ok || !errors.Is(err, security.ErrInvalidHash) {
|
||||
t.Error("malformed stored hash was not rejected")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/config"
|
||||
"highload/internal/database"
|
||||
repoerrors "highload/internal/repository"
|
||||
"highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/service"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/google/uuid"
|
||||
redisclient "github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestRedisAddressIsAnAddressNotAFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "postgres_url")
|
||||
if err := os.WriteFile(path, []byte("postgres://fixture:fixture@postgres/messenger"), 0600); err != nil {
|
||||
t.Fatal("cannot create synthetic config fixture")
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", path)
|
||||
t.Setenv("REDIS_ADDR", "redis:6379")
|
||||
t.Setenv("SESSION_TTL_SECONDS", "3600")
|
||||
t.Setenv("SESSION_STORE", "redis")
|
||||
t.Setenv("S3_ENDPOINT", "http://s3-fixture.invalid")
|
||||
t.Setenv("S3_REGION", "us-east-1")
|
||||
t.Setenv("S3_BUCKET", "health-fixture")
|
||||
for variable, value := range map[string]string{
|
||||
"S3_ACCESS_KEY_ID_FILE": "fixture-access-key",
|
||||
"S3_SECRET_ACCESS_KEY_FILE": "fixture-secret-key",
|
||||
} {
|
||||
keyFile := filepath.Join(dir, variable)
|
||||
if err := os.WriteFile(keyFile, []byte(value), 0600); err != nil {
|
||||
t.Fatal("cannot create synthetic S3 key file")
|
||||
}
|
||||
t.Setenv(variable, keyFile)
|
||||
}
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("cannot load synthetic config with REDIS_ADDR=redis:6379: %v", err)
|
||||
}
|
||||
if cfg.Database.RedisAddr != "redis:6379" {
|
||||
t.Fatal("REDIS_ADDR did not reach the Redis configuration")
|
||||
}
|
||||
}
|
||||
|
||||
type redisFixture struct {
|
||||
ctx context.Context
|
||||
client *redisclient.Client
|
||||
repo *redisrepo.SessionRepository
|
||||
keys []string
|
||||
audit *sessionWriteAudit
|
||||
}
|
||||
|
||||
// Only observe writes through this test's client. No global key counting or
|
||||
// FLUSH commands: other clients' sessions must not affect assertions/cleanup.
|
||||
type sessionWriteAudit struct {
|
||||
sync.Mutex
|
||||
keys map[string]bool
|
||||
writes int
|
||||
}
|
||||
|
||||
func (a *sessionWriteAudit) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (a *sessionWriteAudit) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (a *sessionWriteAudit) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "set" && len(cmd.Args()) > 1 {
|
||||
if key, ok := cmd.Args()[1].(string); ok {
|
||||
a.Lock()
|
||||
a.keys[key] = true
|
||||
a.writes++
|
||||
a.Unlock()
|
||||
}
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
func (a *sessionWriteAudit) writeCount() int { a.Lock(); defer a.Unlock(); return a.writes }
|
||||
func (a *sessionWriteAudit) ownedKeys() []string {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
keys := make([]string, 0, len(a.keys))
|
||||
for key := range a.keys {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
type aofReplyHook struct {
|
||||
reply any
|
||||
err error
|
||||
}
|
||||
|
||||
func (h aofReplyHook) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
|
||||
func (h aofReplyHook) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
|
||||
return next
|
||||
}
|
||||
func (h aofReplyHook) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
|
||||
return func(ctx context.Context, cmd redisclient.Cmder) error {
|
||||
if cmd.Name() == "waitaof" {
|
||||
// DEL still runs on the real test Redis. Only its persistence
|
||||
// acknowledgement is fault-injected deterministically.
|
||||
value := cmd.(*redisclient.Cmd)
|
||||
value.SetVal(h.reply)
|
||||
value.SetErr(h.err)
|
||||
return h.err
|
||||
}
|
||||
return next(ctx, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisUnconfirmedAOFNeverReturnsSuccessfulLogout(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reply any
|
||||
err error
|
||||
}{
|
||||
{"local_not_fsynced", []any{int64(0), int64(0)}, nil},
|
||||
{"only_replica_fsynced", []any{int64(0), int64(1)}, nil},
|
||||
{"malformed_reply", []any{int64(1)}, nil},
|
||||
{"command_failure", nil, errors.New("synthetic acknowledgement failure")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
f.redis.client.AddHook(aofReplyHook{tc.reply, tc.err})
|
||||
request := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
recorder := httptest.NewRecorder()
|
||||
redisRouter(f, f.redis.client).ServeHTTP(recorder, request)
|
||||
if recorder.Code != 500 && recorder.Code != 503 {
|
||||
t.Fatalf("unconfirmed persistence must fail logout, got HTTP %d", recorder.Code)
|
||||
}
|
||||
if (tc.name == "local_not_fsynced" || tc.name == "only_replica_fsynced") && recorder.Code != 503 {
|
||||
t.Errorf("valid reply without local acknowledgement must be HTTP 503, got %d", recorder.Code)
|
||||
}
|
||||
code := "internal_error"
|
||||
if recorder.Code == 503 {
|
||||
code = "unavailable"
|
||||
}
|
||||
assertContractError(t, recorder, recorder.Code, code)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
if f.redis.client.Exists(f.ctx, "session:"+hex.EncodeToString(hash[:])).Val() != 0 {
|
||||
t.Fatal("fault fixture did not actually execute DEL before WAITAOF")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newRedisFixture(t *testing.T) *redisFixture {
|
||||
t.Helper()
|
||||
addr := os.Getenv("AUTH_TEST_REDIS_ADDR")
|
||||
if addr == "" {
|
||||
t.Skip("Redis not verified: set AUTH_TEST_REDIS_ADDR to a dedicated test Redis with AOF")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
client, err := database.NewRedis(ctx, addr)
|
||||
if err != nil {
|
||||
t.Fatal("dedicated test Redis is unavailable")
|
||||
}
|
||||
audit := &sessionWriteAudit{keys: make(map[string]bool)}
|
||||
client.AddHook(audit)
|
||||
f := &redisFixture{ctx: ctx, client: client, repo: redisrepo.NewSessionRepository(client), audit: audit}
|
||||
t.Cleanup(func() {
|
||||
cleanup, done := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer done()
|
||||
// No FLUSHDB/FLUSHALL: delete only this test's own random token keys.
|
||||
keys := append(f.audit.ownedKeys(), f.keys...)
|
||||
if len(keys) > 0 {
|
||||
if err := client.Del(cleanup, keys...).Err(); err != nil {
|
||||
t.Error("test-owned Redis key cleanup failed")
|
||||
}
|
||||
}
|
||||
_ = client.Close()
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *redisFixture) track(token string) [32]byte {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
f.keys = append(f.keys, "session:"+hex.EncodeToString(hash[:]))
|
||||
return hash
|
||||
}
|
||||
|
||||
func TestRedisSessionHasTTLAndReadsDoNotExtendIt(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track("synthetic-" + uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 5*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create Redis session")
|
||||
}
|
||||
key := f.keys[0]
|
||||
before := f.client.PTTL(f.ctx, key).Val()
|
||||
if before <= 0 || before > 5*time.Second {
|
||||
t.Fatal("session key has no bounded positive TTL")
|
||||
}
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil {
|
||||
t.Fatal("cannot read Redis session")
|
||||
}
|
||||
if loaded.UserID != created.UserID || !loaded.ExpiresAt.Equal(created.ExpiresAt) ||
|
||||
!loaded.CreatedAt.Equal(created.CreatedAt) {
|
||||
t.Fatal("session identity or original timestamps changed on read")
|
||||
}
|
||||
after := f.client.PTTL(f.ctx, key).Val()
|
||||
if after <= 0 || after >= before {
|
||||
t.Fatal("reading refreshed or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisExpiredAndUnknownSessionsAreNotFound(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("unknown session must be not found")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 200*time.Millisecond); err != nil {
|
||||
t.Fatal("cannot create short-lived test session")
|
||||
}
|
||||
time.Sleep(350 * time.Millisecond)
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("expired Redis session is still available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisLogoutOnlyRemovesSelectedSession(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
first, second := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
userID := uuid.NewString()
|
||||
for _, hash := range [][32]byte{first, second} {
|
||||
if _, err := f.repo.Create(f.ctx, hash[:], userID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create independent sessions")
|
||||
}
|
||||
}
|
||||
count, err := f.repo.RevokeSession(f.ctx, first[:])
|
||||
if err != nil || count != 1 {
|
||||
t.Fatal("logout failed to remove exactly one session or acknowledge persistence")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("revoked session is still readable")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, second[:]); err != nil {
|
||||
t.Fatal("logout removed another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisSessionsSurviveActualRestartWithoutExtendingTTL(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
active, revoked := f.track(uuid.NewString()), f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, active[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
if _, err := f.repo.Create(f.ctx, revoked[:], created.UserID, time.Minute); err != nil {
|
||||
t.Fatal("cannot create revocation fixture")
|
||||
}
|
||||
if _, err := f.repo.RevokeSession(f.ctx, revoked[:]); err != nil {
|
||||
t.Fatal("cannot persist logout before restart")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, active[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) {
|
||||
t.Fatal("restart lost active session or changed its original deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or lost remaining TTL")
|
||||
}
|
||||
if _, err := f.repo.GetSessionByTokenHash(f.ctx, revoked[:]); !errors.Is(err, repoerrors.ErrNotFound) {
|
||||
t.Fatal("restart revived a revoked session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisActiveSessionSurvivesRestartIndependentlyOfLogout(t *testing.T) {
|
||||
hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK")
|
||||
if hook == "" {
|
||||
t.Skip("Redis restart not verified: set an explicit dedicated test restart hook")
|
||||
}
|
||||
f := newRedisFixture(t)
|
||||
hash := f.track(uuid.NewString())
|
||||
created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 30*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create active session")
|
||||
}
|
||||
before := f.client.PTTL(f.ctx, f.keys[0]).Val()
|
||||
if err := exec.CommandContext(f.ctx, hook).Run(); err != nil {
|
||||
t.Fatal("explicit Redis restart hook failed (private output suppressed)")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) || loaded.UserID != created.UserID {
|
||||
t.Fatal("restart lost active session identity or changed its deadline")
|
||||
}
|
||||
if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before {
|
||||
t.Fatal("restart extended or removed the session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func refusedRedis(t *testing.T) *redisclient.Client {
|
||||
t.Helper()
|
||||
client := redisclient.NewClient(&redisclient.Options{
|
||||
Addr: "synthetic-unavailable:6379", MaxRetries: -1,
|
||||
Dialer: func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
},
|
||||
})
|
||||
t.Cleanup(func() { _ = client.Close() })
|
||||
return client
|
||||
}
|
||||
|
||||
func TestRedisUnavailableKeepsUnavailableCategory(t *testing.T) {
|
||||
repo := redisrepo.NewSessionRepository(refusedRedis(t))
|
||||
hash := sha256.Sum256([]byte("synthetic-failed-token"))
|
||||
t.Run("create", func(t *testing.T) {
|
||||
_, err := repo.Create(context.Background(), hash[:], uuid.NewString(), time.Minute)
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("read", func(t *testing.T) {
|
||||
_, err := repo.GetSessionByTokenHash(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
t.Run("logout", func(t *testing.T) {
|
||||
_, err := repo.RevokeSession(context.Background(), hash[:])
|
||||
if !errors.Is(err, repoerrors.ErrServiceUnavailable) {
|
||||
t.Fatalf("want service unavailable, got %v", err)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("Redis network diagnostic context was lost")
|
||||
}
|
||||
})
|
||||
auth := service.NewAuthService(nil, repo, time.Hour)
|
||||
_, err := auth.ValidateSession(context.Background(), "synthetic-error-context")
|
||||
if !errors.Is(err, service.ErrServiceUnavailable) || !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) {
|
||||
t.Error("service lost Redis unavailable category or diagnostic context")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func redisRouter(f *fixture, client *redisclient.Client) http.Handler {
|
||||
users := postgres.NewUserRepository(f.queries)
|
||||
auth := service.NewAuthService(users, redisrepo.NewSessionRepository(client), time.Hour)
|
||||
userService := service.NewUserService(users)
|
||||
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), users, userService)
|
||||
messages := service.NewMessageService(postgres.NewMessageRepository(f.queries, f.pool), chats, userService)
|
||||
objects := readyS3Storage()
|
||||
attachments := service.NewAttachmentService(postgres.NewAttachmentRepository(f.queries, f.pool), chats, objects)
|
||||
return httptransport.NewRouter(middleware.NewMiddleware(auth, "auth-test"), handler.NewAuthHandler(auth),
|
||||
handler.NewHealthHandler(f.pool, client, objects), handler.NewChatHandler(chats), handler.NewUserHandler(userService),
|
||||
handler.NewMessageHandler(messages), handler.NewAttachmentHandler(attachments)).Handler()
|
||||
}
|
||||
|
||||
func TestRedisCriticalOutageHTTPAndReadiness(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
router := redisRouter(f, refusedRedis(t))
|
||||
for _, tc := range []struct {
|
||||
name, path string
|
||||
status int
|
||||
}{
|
||||
{"liveness", "/health/live", 200},
|
||||
{"readiness", "/health/ready", 503},
|
||||
{"protected_request", "/api/v1/users/me", 503},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, tc.path, nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-outage-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Code != tc.status {
|
||||
t.Fatalf("want HTTP %d, got %d", tc.status, recorder.Code)
|
||||
}
|
||||
if tc.status == 503 {
|
||||
assertContractError(t, recorder, 503, "unavailable")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisHTTPAuthContract(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
r := newRedisFixture(t)
|
||||
server := httptest.NewServer(redisRouter(f, r.client))
|
||||
t.Cleanup(server.Close)
|
||||
_, source, _, _ := runtime.Caller(0)
|
||||
root := filepath.Clean(filepath.Join(filepath.Dir(source), "..", ".."))
|
||||
// Test the auth contract in this fixture. The public smoke now needs a
|
||||
// durable broker and worker and runs against the full stand in lab5/acceptance.py.
|
||||
acceptanceCtx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(acceptanceCtx, "python3", "-B", filepath.Join(root, "student-tests/auth_contract.py"),
|
||||
"--base-url", server.URL, "--ttl", "3600")
|
||||
cmd.Dir = root
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if acceptanceCtx.Err() != nil {
|
||||
t.Fatal("HTTP auth acceptance subprocess timed out")
|
||||
}
|
||||
for _, line := range strings.Split(string(output), "\n") {
|
||||
if strings.HasPrefix(line, "FAIL: test_") || strings.HasPrefix(line, "ERROR: test_") {
|
||||
// Print only the method name, never credentials or subtest values.
|
||||
name := strings.Fields(line)[1]
|
||||
t.Log("failed auth case: " + name)
|
||||
}
|
||||
}
|
||||
t.Fatal("HTTP auth acceptance failed with Redis-backed sessions")
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
|
||||
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
|
||||
if base == "" || hook == "" {
|
||||
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
|
||||
}
|
||||
for _, withLogout := range []bool{false, true} {
|
||||
name := "active_only"
|
||||
if withLogout {
|
||||
name = "active_and_revoked"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
f := newRedisFixture(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
call := func(method, path, token string, body any, basic bool, want int, dst any) {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
if body != nil {
|
||||
if json.NewEncoder(&data).Encode(body) != nil {
|
||||
t.Fatal("cannot encode test request")
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
|
||||
if err != nil {
|
||||
t.Fatal("cannot construct test request")
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if basic {
|
||||
req.SetBasicAuth(username, password)
|
||||
} else if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal("restart HTTP request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != want {
|
||||
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
|
||||
}
|
||||
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
|
||||
t.Fatal("invalid restart response JSON")
|
||||
}
|
||||
}
|
||||
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
|
||||
var active struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
|
||||
hash := f.track(active.Token)
|
||||
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("cannot inspect issued session")
|
||||
}
|
||||
if !before.ExpiresAt.Equal(active.ExpiresAt) {
|
||||
t.Fatal("HTTP and Redis expiry differ")
|
||||
}
|
||||
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
|
||||
if remaining < 2*time.Minute {
|
||||
t.Fatal("normal restart suite requires long session TTL")
|
||||
}
|
||||
revoked := ""
|
||||
if withLogout {
|
||||
var other struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
|
||||
revoked = other.Token
|
||||
f.track(revoked)
|
||||
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
}
|
||||
if exec.CommandContext(ctx, hook).Run() != nil {
|
||||
t.Fatal("real API+stores restart hook failed")
|
||||
}
|
||||
call("GET", "/health/live", "", nil, false, 200, nil)
|
||||
call("GET", "/health/ready", "", nil, false, 200, nil)
|
||||
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
|
||||
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
|
||||
if err != nil {
|
||||
t.Fatal("restart lost session")
|
||||
}
|
||||
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
|
||||
t.Fatal("actual API+Redis restart changed session identity/deadline")
|
||||
}
|
||||
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
|
||||
t.Fatal("restart reset/removed original TTL")
|
||||
}
|
||||
if revoked != "" {
|
||||
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
|
||||
revokedHash := sha256.Sum256([]byte(revoked))
|
||||
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
|
||||
t.Fatal("revoked credential reappeared after restart")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
"highload/internal/model"
|
||||
repository "highload/internal/repository/postgres"
|
||||
redisrepo "highload/internal/repository/redis"
|
||||
"highload/internal/security"
|
||||
"highload/internal/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type fixture struct {
|
||||
admin *pgxpool.Pool
|
||||
pool *pgxpool.Pool
|
||||
config *pgxpool.Config
|
||||
queries *sqlc.Queries
|
||||
users *service.UserService
|
||||
auth *service.AuthService
|
||||
redis *redisFixture
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T) *fixture {
|
||||
t.Helper()
|
||||
f := newDatabaseFixture(t, "AUTH_TEST_DATABASE_URL", 4)
|
||||
f.redis = newRedisFixture(t)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
f.users = service.NewUserService(userRepo)
|
||||
f.auth = service.NewAuthService(userRepo, redisrepo.NewSessionRepository(f.redis.client), time.Hour)
|
||||
return f
|
||||
}
|
||||
|
||||
// Shared PostgreSQL fixture: attachment transaction checks do not require Redis/S3.
|
||||
func newDatabaseFixture(t *testing.T, environment string, maxConnections int32) *fixture {
|
||||
t.Helper()
|
||||
url := os.Getenv(environment)
|
||||
if url == "" {
|
||||
t.Skip("PENDING_INFRA: set " + environment + " for a dedicated test PostgreSQL")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
config, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
t.Fatal("cannot parse test PostgreSQL configuration (credentials suppressed)")
|
||||
}
|
||||
config.MaxConns = maxConnections
|
||||
config.MinConns = 0
|
||||
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
admin, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
t.Fatal("cannot open test PostgreSQL pool")
|
||||
}
|
||||
t.Cleanup(admin.Close)
|
||||
if err := admin.Ping(ctx); err != nil {
|
||||
t.Fatal("test PostgreSQL is unavailable")
|
||||
}
|
||||
// Only this uniquely named schema is created and dropped. Existing tables
|
||||
// and volumes are never removed. The role needs CREATE SCHEMA permission.
|
||||
schema := "auth_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
quoted := pgx.Identifier{schema}.Sanitize()
|
||||
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil {
|
||||
t.Fatal("cannot create isolated test schema")
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer done()
|
||||
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
|
||||
t.Error("isolated test schema cleanup failed")
|
||||
}
|
||||
})
|
||||
config = config.Copy()
|
||||
config.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("cannot connect to isolated test schema")
|
||||
}
|
||||
f := &fixture{admin: admin, config: config, ctx: ctx, pool: pool, queries: sqlc.New(pool)}
|
||||
t.Cleanup(func() { f.pool.Close() })
|
||||
_, source, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate migration files")
|
||||
}
|
||||
migrations, err := filepath.Glob(filepath.Join(filepath.Dir(source), "..", "..", "db", "migrations", "*.sql"))
|
||||
if err != nil || len(migrations) == 0 {
|
||||
t.Fatal("migration SQL is missing")
|
||||
}
|
||||
sort.Strings(migrations)
|
||||
for _, path := range migrations {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal("cannot read migration SQL")
|
||||
}
|
||||
// Current migrations are ordinary SQL with Goose Up/Down markers.
|
||||
// This applies schema fixtures; it is NOT a test of Goose version tracking.
|
||||
up, _, _ := strings.Cut(string(data), "-- +goose Down")
|
||||
if !strings.Contains(up, "-- +goose Up") {
|
||||
t.Fatal("test fixture expects SQL migrations with Goose Up/Down markers")
|
||||
}
|
||||
if _, err := f.pool.Exec(ctx, up, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
t.Fatal("migration cannot initialize isolated schema")
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fixture) connect(t *testing.T, ttl time.Duration) {
|
||||
t.Helper()
|
||||
pool, err := pgxpool.NewWithConfig(f.ctx, f.config.Copy())
|
||||
if err != nil {
|
||||
t.Fatal("cannot connect to isolated schema")
|
||||
}
|
||||
f.pool = pool
|
||||
f.queries = sqlc.New(pool)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
sessionRepo := redisrepo.NewSessionRepository(f.redis.client)
|
||||
f.users = service.NewUserService(userRepo)
|
||||
f.auth = service.NewAuthService(userRepo, sessionRepo, ttl)
|
||||
}
|
||||
|
||||
func (f *fixture) user(t *testing.T) (*model.User, string) {
|
||||
t.Helper()
|
||||
password := "Synthetic:" + uuid.NewString()
|
||||
username := "auth_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
|
||||
user, err := f.users.CreateUser(f.ctx, username, "Auth storage", password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic user")
|
||||
}
|
||||
return user, password
|
||||
}
|
||||
|
||||
func (f *fixture) session(t *testing.T, user *model.User, password string) *service.CreatedSession {
|
||||
t.Helper()
|
||||
session, err := f.auth.CreateSession(f.ctx, user.Username, password)
|
||||
if err != nil {
|
||||
t.Fatal("cannot create synthetic session")
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
func TestStoragePasswordIsKDFAndDuplicateCannotOverwrite(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
stored, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || stored.PasswordHash == password || !strings.HasPrefix(stored.PasswordHash, "$argon2id$") {
|
||||
t.Fatal("database did not preserve the selected password KDF")
|
||||
}
|
||||
ok, err := security.VerifyPassword(password, stored.PasswordHash)
|
||||
if err != nil || !ok {
|
||||
t.Fatal("stored password does not verify")
|
||||
}
|
||||
_, err = f.users.CreateUser(f.ctx, user.Username, "Overwrite", password+"x")
|
||||
if !errors.Is(err, service.ErrAlreadyExists) {
|
||||
t.Fatal("duplicate username was not rejected")
|
||||
}
|
||||
after, err := f.queries.GetUserByUsername(f.ctx, user.Username)
|
||||
if err != nil || after.ID != stored.ID || after.PasswordHash != stored.PasswordHash ||
|
||||
after.DisplayName != stored.DisplayName {
|
||||
t.Fatal("failed duplicate registration changed the original user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageSessionHashAndReconnectPreserveDeadline(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
row, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
value, getErr := f.redis.client.Get(f.ctx, key).Result()
|
||||
if err != nil || getErr != nil || strings.Contains(key, session.Token) || strings.Contains(value, session.Token) {
|
||||
t.Fatal("selected session storage did not use SHA-256 of the opaque token")
|
||||
}
|
||||
for _, ownedKey := range f.redis.audit.ownedKeys() {
|
||||
storedValue, err := f.redis.client.Get(f.ctx, ownedKey).Result()
|
||||
if err != nil || strings.Contains(ownedKey, session.Token) || strings.Contains(storedValue, session.Token) {
|
||||
t.Fatal("raw session token was persisted in Redis")
|
||||
}
|
||||
}
|
||||
if f.redis.client.Exists(f.ctx, "session:"+session.Token, session.Token).Val() != 0 {
|
||||
t.Fatal("raw token was stored as a Redis key")
|
||||
}
|
||||
if ttl := f.redis.client.PTTL(f.ctx, key).Val(); ttl <= 0 || ttl > time.Hour {
|
||||
t.Fatal("session must have a positive bounded Redis TTL")
|
||||
}
|
||||
if session.TokenType != "Bearer" || len(session.Token) < 32 || row.RevokedAt != nil ||
|
||||
!row.ExpiresAt.Equal(session.ExpiresAt) || !row.ExpiresAt.After(row.CreatedAt) {
|
||||
t.Fatal("invalid stored session metadata")
|
||||
}
|
||||
beforeDeadline := row.ExpiresAt
|
||||
for range 3 {
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("valid session rejected or mapped to another user")
|
||||
}
|
||||
}
|
||||
f.pool.Close()
|
||||
// A different process configuration must not reset already stored expiry.
|
||||
f.connect(t, 24*time.Hour)
|
||||
id, err := f.auth.ValidateSession(f.ctx, session.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("new pool/services lost the existing session")
|
||||
}
|
||||
after, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
|
||||
if err != nil || !after.ExpiresAt.Equal(beforeDeadline) {
|
||||
t.Fatal("reads or reconnection extended session TTL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageWrongCredentialsNeverCreateSession(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
writes := f.redis.audit.writeCount()
|
||||
for _, credentials := range [][2]string{
|
||||
{user.Username, password + "x"}, {"unknown_auth_user", password},
|
||||
} {
|
||||
_, err := f.auth.CreateSession(f.ctx, credentials[0], credentials[1])
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("wrong credentials did not yield the same unauthorized error")
|
||||
}
|
||||
}
|
||||
if f.redis.audit.writeCount() != writes {
|
||||
t.Fatal("failed login created a session")
|
||||
}
|
||||
for _, token := range []string{"", uuid.NewString()} {
|
||||
if _, err := f.auth.ValidateSession(f.ctx, token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("empty or unknown token accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageRevocationIsPersistentAndSessionSpecific(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
first, second := f.session(t, user, password), f.session(t, user, password)
|
||||
if first.Token == second.Token {
|
||||
t.Fatal("two logins reused the same token")
|
||||
}
|
||||
if err := f.auth.RevokeSession(f.ctx, first.Token); err != nil {
|
||||
t.Fatal("logout failed")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, first.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("revoked session revived after reconnect")
|
||||
}
|
||||
id, err := f.auth.ValidateSession(f.ctx, second.Token)
|
||||
if err != nil || id != user.ID {
|
||||
t.Fatal("logout affected another session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageExpiredSessionCannotRevive(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
hash := sha256.Sum256([]byte(session.Token))
|
||||
key := "session:" + hex.EncodeToString(hash[:])
|
||||
if err := f.redis.client.PExpire(f.ctx, key, time.Millisecond).Err(); err != nil {
|
||||
t.Fatal("cannot set an expired fixture")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("expired session accepted")
|
||||
}
|
||||
f.pool.Close()
|
||||
f.connect(t, 24*time.Hour)
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("new TTL configuration revived an expired session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageShortTTLExpiresAndReLoginWorks(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
f.auth = service.NewAuthService(repository.NewUserRepository(f.queries),
|
||||
redisrepo.NewSessionRepository(f.redis.client), 2*time.Second)
|
||||
user, password := f.user(t)
|
||||
session := f.session(t, user, password)
|
||||
if remaining := time.Until(session.ExpiresAt); remaining <= 0 || remaining > 3*time.Second {
|
||||
t.Fatal("two-second TTL was not used for the stored session")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil || id != user.ID {
|
||||
t.Fatal("fresh short-lived session was rejected")
|
||||
}
|
||||
time.Sleep(max(0, time.Until(session.ExpiresAt)/2))
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil {
|
||||
t.Fatal("session expired before its original deadline")
|
||||
}
|
||||
timer := time.NewTimer(max(0, time.Until(session.ExpiresAt)) + 100*time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-f.ctx.Done():
|
||||
t.Fatal("expiry fixture exceeded its deadline")
|
||||
}
|
||||
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("short-lived session was accepted after its stored deadline")
|
||||
}
|
||||
fresh := f.session(t, user, password)
|
||||
if fresh.Token == session.Token {
|
||||
t.Fatal("re-login reused the expired token")
|
||||
}
|
||||
if id, err := f.auth.ValidateSession(f.ctx, fresh.Token); err != nil || id != user.ID {
|
||||
t.Fatal("re-login did not produce a usable session")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageChatRollbackAfterMemberInsertFailure(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, _ := f.user(t)
|
||||
repo := repository.NewChatRepository(f.queries, f.pool)
|
||||
// A valid first member is inserted before the nonexistent member fails.
|
||||
// Calling the repository bypasses prevalidation and tests real rollback.
|
||||
_, err := repo.CreateChat(f.ctx, "Must roll back", []string{user.ID, uuid.NewString()})
|
||||
if err == nil {
|
||||
t.Fatal("chat with nonexistent member unexpectedly committed")
|
||||
}
|
||||
for _, table := range []string{"chats", "chat_members"} {
|
||||
var count int
|
||||
err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+table).Scan(&count)
|
||||
if err != nil || count != 0 {
|
||||
t.Fatal("failed transaction left partial chat or membership rows")
|
||||
}
|
||||
}
|
||||
created, err := repo.CreateChat(f.ctx, "Valid after rollback", []string{user.ID})
|
||||
if err != nil || created == nil {
|
||||
t.Fatal("rollback poisoned subsequent valid transaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package auth_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"highload/internal/database/sqlc"
|
||||
repository "highload/internal/repository/postgres"
|
||||
"highload/internal/service"
|
||||
"highload/internal/storage/s3"
|
||||
httptransport "highload/internal/transport/http"
|
||||
"highload/internal/transport/http/handler"
|
||||
"highload/internal/transport/http/middleware"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
const healthFixtureBucket = "health-fixture"
|
||||
|
||||
type readyS3Client struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (s *readyS3Client) Do(req *http.Request) (*http.Response, error) {
|
||||
bucketPath := "/" + healthFixtureBucket
|
||||
response := &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody}
|
||||
if req.Method == http.MethodHead && req.URL.Path == bucketPath {
|
||||
return response, nil
|
||||
}
|
||||
if !strings.HasPrefix(req.URL.Path, bucketPath+"/attachments/") {
|
||||
return nil, fmt.Errorf("unexpected path in S3 fixture")
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
switch req.Method {
|
||||
case http.MethodPut:
|
||||
defer req.Body.Close()
|
||||
data, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.objects[req.URL.Path] = data
|
||||
case http.MethodGet:
|
||||
data, ok := s.objects[req.URL.Path]
|
||||
if !ok {
|
||||
response.StatusCode = http.StatusNotFound
|
||||
return response, nil
|
||||
}
|
||||
response.Body = io.NopCloser(bytes.NewReader(data))
|
||||
response.ContentLength = int64(len(data))
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected method in S3 fixture")
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// Supply local S3 responses for readiness and the attachment upload in the HTTP smoke test.
|
||||
func readyS3Storage() *s3.Storage {
|
||||
return &s3.Storage{
|
||||
Bucket: healthFixtureBucket,
|
||||
Client: awss3.New(awss3.Options{
|
||||
Region: "us-east-1",
|
||||
BaseEndpoint: aws.String("http://s3-fixture.invalid"),
|
||||
UsePathStyle: true,
|
||||
Credentials: aws.AnonymousCredentials{},
|
||||
HTTPClient: &readyS3Client{objects: make(map[string][]byte)},
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type unavailableDB struct{}
|
||||
type unavailableRow struct{}
|
||||
|
||||
func (unavailableRow) Scan(...any) error {
|
||||
return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
|
||||
}
|
||||
|
||||
func (unavailableDB) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
|
||||
return pgconn.CommandTag{}, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) Query(context.Context, string, ...any) (pgx.Rows, error) {
|
||||
return nil, unavailableRow{}.Scan()
|
||||
}
|
||||
|
||||
func (unavailableDB) QueryRow(context.Context, string, ...any) pgx.Row {
|
||||
return unavailableRow{}
|
||||
}
|
||||
|
||||
func TestSQLUnavailableLoginStopsBeforeSessionCreation(t *testing.T) {
|
||||
queries := sqlc.New(unavailableDB{})
|
||||
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")
|
||||
}
|
||||
|
||||
func TestMiddlewareMalformedAuthWritesExactlyOneError(t *testing.T) {
|
||||
// Invalid syntax must be rejected before asking an auth service or DB.
|
||||
// A nil service deliberately makes an accidental dependency call visible.
|
||||
mid := middleware.NewMiddleware(nil, "auth-test")
|
||||
for _, header := range []string{"", "Basic invalid", "Bearer", "Bearer ",
|
||||
"Bearer invalid token", "Digest invalid"} {
|
||||
t.Run("malformed", func(t *testing.T) {
|
||||
nextCalled := false
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalled = true })
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", header)
|
||||
recorder := httptest.NewRecorder()
|
||||
mid.RequestID(mid.Auth(next)).ServeHTTP(recorder, request)
|
||||
if nextCalled || recorder.Code != http.StatusUnauthorized {
|
||||
t.Fatal("malformed auth reached business handler or did not yield 401")
|
||||
}
|
||||
if recorder.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("missing contract Bearer challenge")
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
decoder := json.NewDecoder(recorder.Body)
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatal("401 is not one valid JSON object")
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
t.Fatal("middleware wrote more than one response after 401")
|
||||
}
|
||||
if payload.Error.Code != "unauthorized" || payload.Error.RequestID == "" ||
|
||||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
|
||||
t.Fatal("error request ID or code violates contract")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStorageHTTPAuthRoutingAndLogout(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
user, password := f.user(t)
|
||||
userRepo := repository.NewUserRepository(f.queries)
|
||||
chatRepo := repository.NewChatRepository(f.queries, f.pool)
|
||||
chatService := service.NewChatService(chatRepo, userRepo, f.users)
|
||||
messageService := service.NewMessageService(repository.NewMessageRepository(f.queries, f.pool), chatService, f.users)
|
||||
objects := readyS3Storage()
|
||||
attachmentService := service.NewAttachmentService(repository.NewAttachmentRepository(f.queries, f.pool), chatService, objects)
|
||||
router := httptransport.NewRouter(
|
||||
middleware.NewMiddleware(f.auth, "auth-test"), handler.NewAuthHandler(f.auth),
|
||||
handler.NewHealthHandler(f.pool, f.redis.client, objects),
|
||||
handler.NewChatHandler(chatService), handler.NewUserHandler(f.users),
|
||||
handler.NewMessageHandler(messageService),
|
||||
handler.NewAttachmentHandler(attachmentService),
|
||||
).Handler()
|
||||
|
||||
call := func(method, path, token string, login bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, nil)
|
||||
if login {
|
||||
request.SetBasicAuth(user.Username, password)
|
||||
} else if token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, request)
|
||||
if recorder.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("auth response missing X-Request-Id")
|
||||
}
|
||||
return recorder
|
||||
}
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
t.Error("auth router panicked; check constructor/handler wiring")
|
||||
}
|
||||
}()
|
||||
response := call("POST", "/api/v1/auth/sessions", "", true)
|
||||
if response.Code != 201 {
|
||||
t.Fatal("Basic login route did not return 201")
|
||||
}
|
||||
var session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &session); err != nil ||
|
||||
session.Token == "" || session.TokenType != "Bearer" {
|
||||
t.Fatal("login route returned invalid session")
|
||||
}
|
||||
other := f.session(t, user, password)
|
||||
response = call("GET", "/api/v1/users/me", session.Token, false)
|
||||
if response.Code != 200 || strings.Contains(response.Body.String(), "password") {
|
||||
t.Fatal("Bearer user route failed or exposed password fields")
|
||||
}
|
||||
response = call("DELETE", "/api/v1/auth/sessions/current", session.Token, false)
|
||||
if response.Code != 204 || response.Body.Len() != 0 {
|
||||
t.Fatal("contract logout path must return empty 204")
|
||||
}
|
||||
for _, route := range [][2]string{
|
||||
{"GET", "/api/v1/users/me"}, {"DELETE", "/api/v1/auth/sessions/current"},
|
||||
} {
|
||||
response = call(route[0], route[1], session.Token, false)
|
||||
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
|
||||
t.Fatal("revoked token was accepted or challenged with wrong scheme")
|
||||
}
|
||||
}
|
||||
if response := call("GET", "/api/v1/users/me", other.Token, false); response.Code != 200 {
|
||||
t.Fatal("logout invalidated an independent session of the same user")
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user