forked from mtusi2026/mtusi2026lab3
На 5
This commit is contained in:
@@ -2,6 +2,7 @@ package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -17,6 +18,8 @@ import (
|
||||
"gitea.privcloud.tech/mtusi2026/internal/service/chat"
|
||||
)
|
||||
|
||||
var messageKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type ChatHandler struct {
|
||||
router router.Router
|
||||
provider jwtprovider.Provider
|
||||
@@ -176,6 +179,12 @@ func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
keyValues := r.Header.Values("Idempotency-Key")
|
||||
if len(keyValues) != 1 || !messageKeyPattern.MatchString(keyValues[0]) {
|
||||
framework.JSONError(ctx, w, apperr.New(apperr.CodeBadRequest, "invalid idempotency key"))
|
||||
return
|
||||
}
|
||||
|
||||
var req contracts.CreateMessage
|
||||
if !framework.Decode(w, r, &req) || !framework.Validate(w, r, h.validator, &req) {
|
||||
return
|
||||
@@ -187,9 +196,10 @@ func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
message, err := h.chat.CreateMessage(ctx, dto.CreateMessage{
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
IdempotencyKey: keyValues[0],
|
||||
ChatID: chatID,
|
||||
SenderID: userData.UserID,
|
||||
Text: req.Text,
|
||||
})
|
||||
if err != nil {
|
||||
framework.JSONError(ctx, w, err)
|
||||
|
||||
@@ -76,6 +76,7 @@ func (s *server) Stop(ctx context.Context) error {
|
||||
s.ready.Store(false)
|
||||
if err := s.server.Shutdown(ctx); err != nil {
|
||||
slog.Error("rest server shutdown failed", "error", err)
|
||||
_ = s.server.Close()
|
||||
return err
|
||||
}
|
||||
slog.Info("rest server shutdown successfully")
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/config"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/migrator"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/postgres"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// The explicit runner supplies a newly created database; never alter the API database.
|
||||
func TestIdempotencyTransactionAndExpiry(t *testing.T) {
|
||||
database := os.Getenv("TEST_DATABASE_NAME")
|
||||
if database == "" {
|
||||
t.Skip("run make test-storage for an isolated PostgreSQL database")
|
||||
}
|
||||
if database == os.Getenv("POSTGRES_DATABASE") {
|
||||
t.Fatal("test database must differ from application database")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Postgres.Database = database
|
||||
cfg.Postgres.RunMigrations = true
|
||||
if err = migrator.New(cfg).Start(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := postgres.New(cfg.Postgres)
|
||||
defer pool.Close()
|
||||
repo := NewMessagesRepo(pool)
|
||||
user, chat := uuid.New(), uuid.New()
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO users(id,name,username,password_hash) VALUES($1,'Synthetic','atomic_test','unused')`, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO chats(id,title) VALUES($1,'Atomic test')`, chat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, chat, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := dto.CreateMessage{ChatID: chat, SenderID: user, Text: "atomic", IdempotencyKey: "atomic-key"}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Rollback(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var messages, keys int
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 0 || keys != 0 {
|
||||
t.Fatalf("rollback left %d messages, %d keys", messages, keys)
|
||||
}
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := repo.CreateIdempotentTx(ctx, tx, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Expire the test record only: no shortened production TTL and no wall-clock wait.
|
||||
if _, err = pool.Exec(ctx, `UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE user_id=$1`, user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Text = "new after expiry"
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := repo.CreateIdempotentTx(ctx, tx, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.ID == second.ID {
|
||||
t.Fatal("expired key replayed old message")
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 2 || keys != 1 {
|
||||
t.Fatalf("expiry left %d messages, %d keys; want 2,1", messages, keys)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `CREATE FUNCTION reject_test_key() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.key='failure-key' THEN RAISE EXCEPTION 'synthetic failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test_key BEFORE INSERT ON message_idempotency FOR EACH ROW EXECUTE FUNCTION reject_test_key()`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.IdempotencyKey = "failure-key"
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err == nil {
|
||||
t.Fatal("expected injected failure")
|
||||
}
|
||||
if err = tx.Rollback(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM messages),(SELECT count(*) FROM message_idempotency)`).Scan(&messages, &keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if messages != 2 || keys != 1 {
|
||||
t.Fatal("failed result persisted a side effect")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `DROP TRIGGER reject_test_key ON message_idempotency; DROP FUNCTION reject_test_key()`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tx, err = pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = repo.CreateIdempotentTx(ctx, tx, req); err != nil {
|
||||
t.Fatal("transient failure was cached", err)
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Log("rollback removed both side effect and key; expired key created one new message")
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgerrcode"
|
||||
@@ -22,16 +25,43 @@ func NewMessagesRepo(pool *pgxpool.Pool) *MessagesRepo {
|
||||
return &MessagesRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) Create(ctx context.Context, req dto.Message) error {
|
||||
const query = `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`
|
||||
if _, err := r.pool.Exec(ctx, query, req.ID, req.ChatID, req.SenderID, req.Text, req.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok &&
|
||||
pgErr.Code == pgerrcode.ForeignKeyViolation && pgErr.ConstraintName == "messages_sender_member_fk" {
|
||||
return apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return apperr.WrapPostgres(err, "failed to create message")
|
||||
// CreateIdempotentTx serializes only requests sharing an idempotency scope.
|
||||
// The transaction commits both the message and its replay record, or neither.
|
||||
func (r *MessagesRepo) CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error) {
|
||||
scope := req.SenderID.String() + ":POST:" + req.ChatID.String() + ":" + req.IdempotencyKey
|
||||
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, scope); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to lock message key")
|
||||
}
|
||||
return nil
|
||||
hash := sha256.Sum256([]byte(req.Text)) // text is the complete lab3 request model
|
||||
var storedHash []byte
|
||||
var messageID uuid.UUID
|
||||
err := tx.QueryRow(ctx, `SELECT request_hash, message_id FROM message_idempotency
|
||||
WHERE user_id=$1 AND method='POST' AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()`,
|
||||
req.SenderID, req.ChatID, req.IdempotencyKey).Scan(&storedHash, &messageID)
|
||||
if err == nil {
|
||||
if !bytes.Equal(hash[:], storedHash) {
|
||||
return nil, apperr.New(apperr.CodeConflict, "idempotency key used with different content")
|
||||
}
|
||||
return scanMessage(tx.QueryRow(ctx, `SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE id=$1`, messageID))
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, apperr.WrapPostgres(err, "failed to read message key")
|
||||
}
|
||||
message := dto.Message{ID: uuid.New(), ChatID: req.ChatID, SenderID: req.SenderID, Text: req.Text, CreatedAt: time.Now().UTC().Truncate(time.Microsecond)}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)`,
|
||||
message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt); err != nil {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok && pgErr.Code == pgerrcode.ForeignKeyViolation {
|
||||
return nil, apperr.Wrap(err, apperr.CodeNotFound, "chat not found")
|
||||
}
|
||||
return nil, apperr.WrapPostgres(err, "failed to create message")
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,chat_id,key,request_hash,message_id,expires_at)
|
||||
VALUES($1,'POST',$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
|
||||
ON CONFLICT(user_id,method,chat_id,key) DO UPDATE SET request_hash=EXCLUDED.request_hash,
|
||||
message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at`, req.SenderID, req.ChatID, req.IdempotencyKey, hash[:], message.ID); err != nil {
|
||||
return nil, apperr.WrapPostgres(err, "failed to save message key")
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (r *MessagesRepo) GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error) {
|
||||
|
||||
@@ -15,9 +15,10 @@ type Message struct {
|
||||
}
|
||||
|
||||
type CreateMessage struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
IdempotencyKey string
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
type MessageFilters struct {
|
||||
|
||||
@@ -3,7 +3,9 @@ package encrypting
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -30,13 +32,13 @@ func (e *encryptor) EncryptSecret(_ context.Context, secret string) (string, err
|
||||
return string(res), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) EncryptSecretUsingSum256(_ context.Context, secret string) (string, error) {
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
res, err := e.generateFromPasswordFunc([]byte(hex.EncodeToString(sum[:])), e.cost)
|
||||
if err != nil {
|
||||
return "", ErrFailedToEncryptPassword
|
||||
// EncryptSecretUsingSum256 hashes a high-entropy session token, not a password.
|
||||
func (e *encryptor) EncryptSecretUsingSum256(ctx context.Context, secret string) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(res), nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
return "sha256:" + hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password string) error {
|
||||
@@ -47,11 +49,24 @@ func (e *encryptor) CompareHashAndSecret(_ context.Context, hash, password strin
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(_ context.Context, hash, password string) error {
|
||||
sum := sha256.Sum256([]byte(password))
|
||||
err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:])))
|
||||
if err != nil {
|
||||
return ErrFailedToComparePasswords
|
||||
func (e *encryptor) CompareHashAndSecretUsingSum256(ctx context.Context, hash, secret string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
sum := sha256.Sum256([]byte(secret))
|
||||
if payload, ok := strings.CutPrefix(hash, "sha256:"); ok {
|
||||
stored, err := hex.DecodeString(payload)
|
||||
if err != nil || len(stored) != sha256.Size || subtle.ConstantTimeCompare(stored, sum[:]) != 1 {
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// Preserve existing lab2/lab3 sessions across a rolling deployment.
|
||||
// Passwords continue to use Argon2id; only old random-token fingerprints use this fallback.
|
||||
if strings.HasPrefix(hash, "$2") {
|
||||
if err := e.compareHashAndPasswordFunc([]byte(hash), []byte(hex.EncodeToString(sum[:]))); err == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFailedToComparePasswords
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package encrypting
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSessionFingerprints(t *testing.T) {
|
||||
e := New()
|
||||
ctx := context.Background()
|
||||
token := "synthetic-high-entropy-session-value"
|
||||
hash, err := e.EncryptSecretUsingSum256(ctx, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, hash, token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{"sha256:00", "sha256:invalid", "unknown"} {
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, bad, token) == nil {
|
||||
t.Fatal("accepted malformed fingerprint")
|
||||
}
|
||||
}
|
||||
if e.CompareHashAndSecretUsingSum256(ctx, hash, token+"x") == nil {
|
||||
t.Fatal("accepted wrong token")
|
||||
}
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
legacy, err := bcrypt.GenerateFromPassword([]byte(hex.EncodeToString(sum[:])), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = e.CompareHashAndSecretUsingSum256(ctx, string(legacy), token); err != nil {
|
||||
t.Fatal("legacy session rejected", err)
|
||||
}
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if e.CompareHashAndSecretUsingSum256(canceled, hash, token) == nil {
|
||||
t.Fatal("ignored cancellation")
|
||||
}
|
||||
}
|
||||
@@ -197,7 +197,16 @@ func Token(r *http.Request) (string, bool) {
|
||||
return token, true
|
||||
}
|
||||
|
||||
type sessionContextKey struct{}
|
||||
|
||||
func WithVerifiedSession(r *http.Request, data *dto.UserDataInToken) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, *data))
|
||||
}
|
||||
|
||||
func ParseToken(r *http.Request, provider jwtprovider.Provider) (*dto.UserDataInToken, error) {
|
||||
if data, ok := r.Context().Value(sessionContextKey{}).(dto.UserDataInToken); ok {
|
||||
return &data, nil
|
||||
}
|
||||
foundHeader := r.Header.Get(headers.HeaderAuthorization)
|
||||
if foundHeader == "" {
|
||||
return nil, apperr.New(apperr.CodeUnauthorized, "missing authorization header")
|
||||
|
||||
@@ -39,12 +39,13 @@ func (a *authMiddleware) WithAdminAccess(next http.Handler) http.Handler {
|
||||
|
||||
func (a *authMiddleware) privateAccessCheckCallback(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := a.verifySession(r); err != nil {
|
||||
data, err := a.verifySession(r)
|
||||
if err != nil {
|
||||
framework.JSONError(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +62,7 @@ func (a *authMiddleware) operatorAccessCheckCallback(expectedRole role.Role, nex
|
||||
return
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, framework.WithVerifiedSession(r, u))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/mtusi2026/internal/dto"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
|
||||
"gitea.privcloud.tech/mtusi2026/internal/pkg/rest/framework"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type sessionVerifier struct {
|
||||
calls int
|
||||
data dto.UserDataInToken
|
||||
err error
|
||||
}
|
||||
|
||||
func (v *sessionVerifier) VerifySession(context.Context, dto.Token) (*dto.UserDataInToken, error) {
|
||||
v.calls++
|
||||
return &v.data, v.err
|
||||
}
|
||||
|
||||
func TestVerifiedSessionIsRequestScoped(t *testing.T) {
|
||||
verifier := &sessionVerifier{data: dto.UserDataInToken{UserID: uuid.New()}}
|
||||
middleware := NewAuthMiddleware(verifier)
|
||||
handled := 0
|
||||
handler := middleware.WithPrivateAccess(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// A nil provider is intentional: the handler must use the verified request identity.
|
||||
data, err := framework.ParseToken(r, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data.UserID != verifier.data.UserID {
|
||||
t.Fatal("verified identity changed")
|
||||
}
|
||||
handled++
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
for range 2 {
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 204 {
|
||||
t.Fatal(recorder.Code)
|
||||
}
|
||||
}
|
||||
if verifier.calls != 2 || handled != 2 {
|
||||
t.Fatal("session verification must run for every request")
|
||||
}
|
||||
verifier.err = apperr.New(apperr.CodeUnauthorized, "revoked session")
|
||||
request := httptest.NewRequest("GET", "/private", nil)
|
||||
request.Header.Set("Authorization", "Bearer synthetic-token")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
if recorder.Code != 401 || handled != 2 {
|
||||
t.Fatal("revocation was bypassed by cached request identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingTokenDoesNotCallSessionStore(t *testing.T) {
|
||||
verifier := &sessionVerifier{err: errors.New("must not be called")}
|
||||
handler := NewAuthMiddleware(verifier).WithPrivateAccess(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("handler called without a token") }))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/private", nil))
|
||||
if recorder.Code != 401 || verifier.calls != 0 {
|
||||
t.Fatal("missing token was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
func Instance(id string) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ type chatsRepo interface {
|
||||
}
|
||||
|
||||
type messagesRepo interface {
|
||||
Create(ctx context.Context, req dto.Message) error
|
||||
CreateIdempotentTx(ctx context.Context, tx pgx.Tx, req dto.CreateMessage) (*dto.Message, error)
|
||||
GetByIDForChat(ctx context.Context, chatID, messageID uuid.UUID) (*dto.Message, error)
|
||||
ListForChat(ctx context.Context, chatID uuid.UUID, page dto.PageQuery) ([]dto.Message, error)
|
||||
}
|
||||
|
||||
@@ -169,18 +169,13 @@ func (c *Chat) CreateMessage(ctx context.Context, req dto.CreateMessage) (*dto.M
|
||||
return nil, err
|
||||
}
|
||||
|
||||
message := dto.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: req.ChatID,
|
||||
SenderID: req.SenderID,
|
||||
Text: req.Text,
|
||||
CreatedAt: time.Now().Truncate(time.Microsecond),
|
||||
}
|
||||
if err := c.messagesRepo.Create(ctx, message); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &message, nil
|
||||
var message *dto.Message
|
||||
err := c.tm.RunInTransaction(ctx, nil, func(tx pgx.Tx) error {
|
||||
var err error
|
||||
message, err = c.messagesRepo.CreateIdempotentTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
return message, err
|
||||
}
|
||||
|
||||
func (c *Chat) ListForChat(ctx context.Context, req dto.MessageFilters) (*dto.Page[dto.Message], error) {
|
||||
|
||||
Reference in New Issue
Block a user