lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,361 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *MessageRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
var created domain.Message
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
message, err := createIdempotent(ctx, queries, draft, r.store.idempotencyTTL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
created = message
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// mapError нужен и здесь: отказ BEGIN/COMMIT (недоступная БД, исчерпанный
|
||||
// пул, истёкший контекст) обязан давать 503, а не 500.
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// Replay returns the stored message for a live Idempotency-Key without
|
||||
// touching attachment state. The caller uses it before attachment validation so
|
||||
// a replay stays 201 even if a linked attachment later failed.
|
||||
func (r *MessageRepository) Replay(
|
||||
ctx context.Context,
|
||||
draft domain.MessageDraft,
|
||||
) (domain.Message, bool, error) {
|
||||
var (
|
||||
replayed domain.Message
|
||||
found bool
|
||||
)
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
stored, err := queries.LookupMessageIdempotency(ctx, sqlcgen.LookupMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
replayed = mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, false, fmt.Errorf("replay idempotent message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return replayed, found, nil
|
||||
}
|
||||
|
||||
// createIdempotent stores the message and its Idempotency-Key in one
|
||||
// transaction: either both are committed or neither, so a replay never observes
|
||||
// a claimed key whose message is missing. Claiming is a single statement, so
|
||||
// concurrent duplicates with the same key wait for the winner and then replay
|
||||
// the message it stored.
|
||||
func createIdempotent(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
draft domain.MessageDraft,
|
||||
ttl time.Duration,
|
||||
) (domain.Message, error) {
|
||||
_, err := queries.ClaimMessageIdempotency(ctx, sqlcgen.ClaimMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
RequestHash: draft.Idempotency.RequestHash[:],
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
})
|
||||
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows): // the key is still live: replay it
|
||||
return replayIdempotent(ctx, queries, draft)
|
||||
case err != nil:
|
||||
return domain.Message{}, mapError(err)
|
||||
default:
|
||||
return createClaimed(ctx, queries, draft)
|
||||
}
|
||||
}
|
||||
|
||||
func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
row, err := queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
for position, attachmentID := range draft.AttachmentIDs {
|
||||
if err := queries.AttachToMessage(ctx, sqlcgen.AttachToMessageParams{
|
||||
MessageID: row.ID,
|
||||
AttachmentID: attachmentID,
|
||||
Position: int16(position),
|
||||
}); err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
err = queries.CompleteMessageIdempotency(ctx, sqlcgen.CompleteMessageIdempotencyParams{
|
||||
MessageID: pgtype.UUID{Bytes: row.ID, Valid: true},
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
created := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
created.AttachmentIDs = make([]uuid.UUID, 0, len(draft.AttachmentIDs))
|
||||
created.AttachmentIDs = append(created.AttachmentIDs, draft.AttachmentIDs...)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
stored, err := queries.GetMessageIdempotency(ctx, sqlcgen.GetMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.Message{}, domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return domain.Message{}, errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
replayed := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return replayed, nil
|
||||
}
|
||||
|
||||
// listAttachmentIDs returns attachment IDs in the order the sender supplied
|
||||
// them. An empty result is normalised to an empty slice, never nil: the
|
||||
// contract marks attachment_ids as required.
|
||||
func listAttachmentIDs(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messageID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := queries.ListMessageAttachments(ctx, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.AttachmentID)
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
limit = clampLimit(limit)
|
||||
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
||||
|
||||
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
|
||||
if len(messages) == 0 {
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: callerID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf(
|
||||
"%w: chat %s for user %s",
|
||||
domain.ErrNotFound, chatID, callerID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
|
||||
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) fetch(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
fetch int32,
|
||||
) ([]domain.Message, error) {
|
||||
var messages []domain.Message
|
||||
|
||||
if after == nil {
|
||||
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
} else {
|
||||
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
AfterCreatedAt: after.CreatedAt,
|
||||
AfterID: after.ID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
}
|
||||
|
||||
if err := attachMessageLinks(ctx, r.store.queries, messages); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// attachMessageLinks fetches all links for a page in one query and normalises
|
||||
// absent lists to empty slices.
|
||||
func attachMessageLinks(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messages []domain.Message,
|
||||
) error {
|
||||
if len(messages) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(messages))
|
||||
for index := range messages {
|
||||
ids = append(ids, messages[index].ID)
|
||||
messages[index].AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
rows, err := queries.ListMessageAttachments(ctx, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
byMessage := make(map[uuid.UUID][]uuid.UUID, len(messages))
|
||||
for _, row := range rows {
|
||||
byMessage[row.MessageID] = append(byMessage[row.MessageID], row.AttachmentID)
|
||||
}
|
||||
|
||||
for index := range messages {
|
||||
if linked, ok := byMessage[messages[index].ID]; ok {
|
||||
messages[index].AttachmentIDs = linked
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapMessageRow(row sqlcgen.Message) domain.Message {
|
||||
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
}
|
||||
|
||||
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
|
||||
return domain.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: toUTCTime(createdAt),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user