chore(migrate) moved codebase from lab4

This commit is contained in:
Mikhail Verkovykh
2026-11-14 23:17:36 +03:00
parent 276dbdad8a
commit 28d68dc30b
123 changed files with 11677 additions and 0 deletions
+120
View File
@@ -0,0 +1,120 @@
// Package internal wires HTTP routes, middleware and storage into one Fiber
// application and owns the process-wide error handler.
package internal
import (
"errors"
"log/slog"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/attachments"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/chats"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/health"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/messages"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/objectstore"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/users"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/recover"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/jackc/pgx/v5/pgxpool"
)
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) (*fiber.App, error) {
st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL)
objects, err := objectstore.New(objectstore.Config{
Endpoint: cfg.S3Endpoint,
Region: cfg.S3Region,
Bucket: cfg.S3Bucket,
AccessKey: cfg.S3AccessKey,
SecretKey: cfg.S3SecretKey,
})
if err != nil {
return nil, err
}
app := fiber.New(fiber.Config{
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
// BodyLimit is the coarse HTTP envelope. The attachment handler and
// BindJSON enforce their own smaller budgets.
BodyLimit: cfg.HTTPBodyLimit,
// Without StreamRequestBody fasthttp buffers the entire body
// before the handler runs. Streaming lets the upload path copy in
// 32 KiB chunks and stops a 10 MiB body from becoming a per-request
// allocation even when the request is later rejected.
StreamRequestBody: true,
ErrorHandler: handleError,
})
app.Use(recover.New())
app.Use(requestid.New())
app.Use(func(c fiber.Ctx) error {
c.Set("X-Instance-Id", cfg.InstanceID)
return c.Next()
})
healthHandler := health.NewHandler(st, sessions, objects)
healthRoutes := app.Group("/health")
healthRoutes.Get("/live", healthHandler.Live)
healthRoutes.Get("/ready", healthHandler.Ready)
authHandler := auth.NewHandler(st, sessions)
usersHandler := users.NewHandler(st, config.MaxJSONBodyBytes)
chatsHandler := chats.NewHandler(st, config.MaxJSONBodyBytes)
messagesHandler := messages.NewHandler(st, config.MaxJSONBodyBytes)
attachmentsHandler := attachments.NewHandler(
st,
objects,
attachments.NewValidator(cfg.MaxImagePixels, cfg.ImageDecodeBytes),
cfg.MaxUploadBytes,
cfg.UploadDrainLimit,
cfg.UploadTimeout,
cfg.DownloadTimeout,
cfg.UploadTempDir,
)
api := app.Group("/api/v1")
api.Post("/users", usersHandler.CreateUser)
api.Post("/auth/sessions", authHandler.CreateSession)
protected := api.Group("", auth.BearerAuth(sessions))
protected.Get("/users/me", usersHandler.GetCurrentUser)
protected.Delete("/auth/sessions/current", authHandler.RevokeSession)
protected.Get("/chats", chatsHandler.ListChats)
protected.Post("/chats", chatsHandler.CreateChat)
protected.Get("/chats/:chat_id", chatsHandler.GetChat)
protected.Get("/chats/:chat_id/messages", messagesHandler.ListMessages)
protected.Post("/chats/:chat_id/messages", messagesHandler.CreateMessage)
protected.Post("/chats/:chat_id/attachments", attachmentsHandler.Upload)
protected.Get("/attachments/:attachment_id", attachmentsHandler.Get)
protected.Get("/attachments/:attachment_id/content", attachmentsHandler.Download)
return app, nil
}
// handleError is the only writer of error responses: handlers and the store
// return *common.AppError and this function decides status, headers and body.
func handleError(c fiber.Ctx, err error) error {
if appErr, ok := errors.AsType[*common.AppError](err); ok {
if appErr.Challenge != "" {
c.Set(fiber.HeaderWWWAuthenticate, appErr.Challenge)
}
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
if fiberErr, ok := errors.AsType[*fiber.Error](err); ok {
return common.SendError(c, fiberErr.Code,
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
}
slog.Error("unhandled request error",
"request_id", requestid.FromContext(c), "err", err)
return common.SendError(c, fiber.StatusInternalServerError,
common.ErrorCodeInternal, "Internal server error")
}
+329
View File
@@ -0,0 +1,329 @@
package attachments
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"os"
"strconv"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/objectstore"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
const copyBufferSize = 32 * 1024
type Handler struct {
store *store.Store
objects *objectstore.Client
validator *Validator
maxUploadBytes int64
drainLimit int64
uploadTimeout time.Duration
downloadTimeout time.Duration
tempDir string
}
func NewHandler(st *store.Store, client *objectstore.Client, validator *Validator, maxUploadBytes, drainLimit int64, uploadTimeout, downloadTimeout time.Duration, tempDir string) *Handler {
return &Handler{
store: st,
objects: client,
validator: validator,
maxUploadBytes: maxUploadBytes,
drainLimit: drainLimit,
uploadTimeout: uploadTimeout,
downloadTimeout: downloadTimeout,
tempDir: tempDir,
}
}
// Upload stores raw PNG/JPEG bytes. The order is deliberate:
// 1. authorize before reading the body;
// 2. stream the body to a bounded temporary file while hashing;
// 3. validate pixels and decode;
// 4. commit a pending metadata row;
// 5. PUT the object;
// 6. mark the row ready.
//
// A 201 is therefore returned only after both the object and its metadata are
// durable. Every failure between 4 and 6 has a compensation path, and the
// reconciler covers crashes that prevent compensation from running.
func (h *Handler) Upload(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
// Authorization precedes any body I/O: an outsider cannot make the server
// read a large upload before learning that the chat is not theirs.
isMember, err := h.store.IsMember(c.Context(), userID, chatID)
if err != nil {
return err
}
if !isMember {
return common.NotFound("chat not found")
}
filename := c.Query("filename")
if err := common.ValidateFilename(filename); err != nil {
return err
}
contentType, _, err := mime.ParseMediaType(c.Get(fiber.HeaderContentType))
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
return common.UnsupportedMedia("Content-Type must be image/png or image/jpeg")
}
// Reject an obviously oversized request before allocating a temp file or
// decoding anything. Chunked requests are caught by the streaming counter
// below.
//
// AGENT: the declared body is drained first, but only within the bounded
// HTTP envelope (upload limit plus the JSON body slack). If the server
// closed immediately, the client would often see a connection reset instead
// of the required 413 while it was still sending. Draining is bounded and
// uses a 32 KiB buffer, so it does not weaken the memory guarantee.
if rawLength := c.Get(fiber.HeaderContentLength); rawLength != "" {
declared, parseErr := strconv.ParseInt(rawLength, 10, 64)
if parseErr != nil || declared < 0 {
return common.BadRequest("invalid Content-Length")
}
if declared > h.maxUploadBytes {
if declared <= h.drainLimit {
_, _ = io.CopyBuffer(io.Discard, io.LimitReader(requestBody(c), declared), make([]byte, copyBufferSize))
}
return common.PayloadTooLarge("upload exceeds the byte limit")
}
}
if err = os.MkdirAll(h.tempDir, 0o700); err != nil {
slog.Error("create upload temp dir", "err", err)
return common.Internal()
}
file, err := os.CreateTemp(h.tempDir, "upload-*.part")
if err != nil {
slog.Error("create upload temp file", "err", err)
return common.Internal()
}
filePath := file.Name()
defer func() {
_ = file.Close()
_ = os.Remove(filePath)
}()
// AGENT: the 32 KiB copy buffer is the only request-sized allocation here.
// The body is never read with io.ReadAll, so ten simultaneous 10 MiB
// uploads do not require ten 10 MiB Go slices.
var reader io.Reader = requestBody(c)
hasher := sha256.New()
copyBuffer := make([]byte, copyBufferSize)
written, err := io.CopyBuffer(io.MultiWriter(file, hasher), io.LimitReader(reader, h.maxUploadBytes+1), copyBuffer)
if err != nil {
return common.BadRequest("incomplete upload body")
}
if written == 0 {
return common.UnsupportedMedia("upload body is empty")
}
if written > h.maxUploadBytes {
return common.PayloadTooLarge("upload exceeds the byte limit")
}
ctx, cancel := context.WithTimeout(c.Context(), h.uploadTimeout)
defer cancel()
info, err := h.validator.Validate(ctx, file, contentType)
if err != nil {
return err
}
attachmentID := uuid.New()
attachment := model.Attachment{
ID: attachmentID,
ChatID: chatID,
OwnerID: userID,
Filename: filename,
ContentType: info.ContentType,
SizeBytes: written,
SHA256: hex.EncodeToString(hasher.Sum(nil)),
Status: "pending",
Variants: []model.Variant{},
ErrorCode: nil,
CreatedAt: common.NowUTC(),
UpdatedAt: common.NowUTC(),
// AGENT: the key is server-generated from UUIDs and never contains the
// client filename. That keeps traversal and collisions out of the
// object store even before application authorization is considered.
ObjectKey: objectKey(chatID, attachmentID),
}
if err = h.store.CreatePendingAttachment(ctx, attachment); err != nil {
return err
}
if _, err = file.Seek(0, 0); err != nil {
h.compensate(attachment.ID, attachment.ObjectKey)
return common.BadRequest("cannot read upload body")
}
if err = h.objects.Put(ctx, attachment.ObjectKey, file, written, attachment.ContentType); err != nil {
slog.Error("store attachment object", "err", err, "attachment_id", attachment.ID)
h.compensate(attachment.ID, attachment.ObjectKey)
return common.Unavailable("object storage unavailable")
}
updatedAt, err := h.store.MarkAttachmentReady(ctx, attachment.ID)
if err != nil {
slog.Error("mark attachment ready", "err", err, "attachment_id", attachment.ID)
h.compensate(attachment.ID, attachment.ObjectKey)
return common.Unavailable("attachment metadata unavailable")
}
attachment.Status = "ready"
attachment.UpdatedAt = common.RFCFormTime(updatedAt)
return c.Status(fiber.StatusCreated).JSON(attachment)
}
// compensate is best effort by design. If either delete fails, the pending row
// or the object remains visible to the reconciler, which retries after the
// configured grace period.
func (h *Handler) compensate(attachmentID uuid.UUID, key string) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.objects.Delete(ctx, key); err != nil && !errors.Is(err, objectstore.ErrNotFound) {
slog.Error("compensate: delete object", "err", err, "attachment_id", attachmentID)
}
if err := h.store.DeletePendingAttachment(ctx, attachmentID); err != nil {
slog.Error("compensate: delete pending row", "err", err, "attachment_id", attachmentID)
}
}
func (h *Handler) Get(c fiber.Ctx) error {
userID := common.MustUserID(c)
attachmentID, err := common.PathUUID(c, "attachment_id")
if err != nil {
return err
}
attachment, err := h.store.GetAttachmentForUser(c.Context(), userID, attachmentID)
if err != nil {
return err
}
if attachment.Status != "ready" {
return common.Conflict("attachment is not ready")
}
return c.JSON(attachment)
}
func (h *Handler) Download(c fiber.Ctx) error {
userID := common.MustUserID(c)
attachmentID, err := common.PathUUID(c, "attachment_id")
if err != nil {
return err
}
variant := c.Query("variant", "original")
if variant == "" {
variant = "original"
}
if variant != "original" {
return common.BadRequest("unsupported variant")
}
attachment, err := h.store.GetAttachmentForUser(c.Context(), userID, attachmentID)
if err != nil {
return err
}
if attachment.Status != "ready" {
return common.Conflict("attachment is not ready")
}
ctx, cancel := context.WithTimeout(c.Context(), h.downloadTimeout)
body, size, err := h.objects.Get(ctx, attachment.ObjectKey)
if err != nil {
cancel()
if errors.Is(err, objectstore.ErrNotFound) {
slog.Error("attachment object missing", "attachment_id", attachment.ID)
return common.NotFound("attachment content not found")
}
slog.Error("read attachment object", "err", err, "attachment_id", attachment.ID)
return common.Unavailable("object storage unavailable")
}
if size != attachment.SizeBytes {
_ = body.Close()
cancel()
slog.Error("attachment object size mismatch",
"attachment_id", attachment.ID, "metadata_size", attachment.SizeBytes, "object_size", size)
return common.Unavailable("attachment content is inconsistent")
}
c.Set(fiber.HeaderContentType, attachment.ContentType)
c.Set(fiber.HeaderContentLength, strconv.FormatInt(attachment.SizeBytes, 10))
c.Set(fiber.HeaderContentDisposition, mime.FormatMediaType("inline", map[string]string{"filename": attachment.Filename}))
c.Set(fiber.HeaderCacheControl, "private, no-store")
c.Set("X-Content-Type-Options", "nosniff")
// AGENT: SendStreamWriter copies the S3 body straight to the response. The
// API never materializes the whole object in RAM and never redirects the
// client to a bucket URL, so authorization is enforced on every byte.
//
// The context and body are released inside the callback, not by a defer in
// this handler: the handler returns before fasthttp copies the stream, and
// canceling the S3 request context earlier truncates the response.
return c.SendStreamWriter(func(writer *bufio.Writer) {
defer cancel()
defer func() { _ = body.Close() }()
if _, copyErr := io.Copy(writer, body); copyErr != nil {
slog.Error("stream attachment to client", "err", copyErr, "attachment_id", attachment.ID)
}
})
}
func requestBody(c fiber.Ctx) io.Reader {
if reader := c.Request().BodyStream(); reader != nil {
return reader
}
return bytes.NewReader(c.Body())
}
func objectKey(chatID, attachmentID uuid.UUID) string {
return fmt.Sprintf("attachments/%s/%s", chatID, attachmentID)
}
// CleanupStaleUploads removes temp files abandoned by a previous crash. A
// running request removes its own file in a defer; this only handles the
// process-died-mid-upload case.
func CleanupStaleUploads(dir string, olderThan time.Duration) {
entries, err := os.ReadDir(dir)
if err != nil {
return
}
cutoff := time.Now().Add(-olderThan)
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, infoErr := entry.Info()
if infoErr != nil || info.ModTime().After(cutoff) {
continue
}
_ = os.Remove(dir + string(os.PathSeparator) + entry.Name())
}
}
+129
View File
@@ -0,0 +1,129 @@
// Package attachments implements the synchronous upload, metadata lookup and
// authorized download path for chat attachments.
package attachments
import (
"context"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"os"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"golang.org/x/sync/semaphore"
)
type Validator struct {
maxPixels int64
decodeBudget *semaphore.Weighted
budgetBytes int64
}
type ImageInfo struct {
ContentType string
Width int
Height int
}
func NewValidator(maxPixels, decodeBudgetBytes int64) *Validator {
return &Validator{
maxPixels: maxPixels,
decodeBudget: semaphore.NewWeighted(decodeBudgetBytes),
budgetBytes: decodeBudgetBytes,
}
}
// Validate checks the declared media type against the real bytes and then
// decodes the image under a shared memory budget. The decode is what turns a
// structurally broken or truncated file into 415 instead of a saved object.
//
// AGENT: image.DecodeConfig first reads only the header. This is the important
// ordering: a decompression bomb is rejected from width×height before the
// decoder is allowed to allocate pixel memory.
func (v *Validator) Validate(ctx context.Context, file *os.File, declared string) (ImageInfo, error) {
mediaType, _, err := mime.ParseMediaType(declared)
if err != nil {
return ImageInfo{}, common.UnsupportedMedia("Content-Type must be image/png or image/jpeg")
}
if mediaType != "image/png" && mediaType != "image/jpeg" {
return ImageInfo{}, common.UnsupportedMedia("Content-Type must be image/png or image/jpeg")
}
if _, err = file.Seek(0, 0); err != nil {
return ImageInfo{}, common.BadRequest("cannot read upload body")
}
head := make([]byte, 512)
n, readErr := file.Read(head)
if readErr != nil && !errors.Is(readErr, io.EOF) {
return ImageInfo{}, common.BadRequest("cannot read upload body")
}
detected := http.DetectContentType(head[:n])
if detected != mediaType {
return ImageInfo{}, common.UnsupportedMedia("file content does not match Content-Type")
}
if _, err = file.Seek(0, 0); err != nil {
return ImageInfo{}, common.BadRequest("cannot read upload body")
}
config, format, err := image.DecodeConfig(file)
if err != nil {
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
}
if format != "png" && format != "jpeg" {
return ImageInfo{}, common.UnsupportedMedia("only PNG and JPEG images are accepted")
}
if (format == "png" && mediaType != "image/png") || (format == "jpeg" && mediaType != "image/jpeg") {
return ImageInfo{}, common.UnsupportedMedia("file content does not match Content-Type")
}
if config.Width <= 0 || config.Height <= 0 {
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
}
pixels := int64(config.Width) * int64(config.Height)
if pixels <= 0 || pixels > v.maxPixels {
return ImageInfo{}, common.PayloadTooLarge("image has too many pixels")
}
// Approximate decoded RGBA size. The semaphore caps the sum across
// concurrent requests; a single 40 Mp image needs ~160 MiB, so a lower
// configured budget is a deliberate operator choice and becomes a 413.
weight := pixels * 4
if weight > v.budgetBytes {
return ImageInfo{}, common.PayloadTooLarge("image is too large to validate")
}
if err = v.decodeBudget.Acquire(ctx, weight); err != nil {
return ImageInfo{}, common.Unavailable("image validation is busy")
}
defer v.decodeBudget.Release(weight)
if _, err = file.Seek(0, 0); err != nil {
return ImageInfo{}, common.BadRequest("cannot read upload body")
}
info, decodeErr := safeDecode(file)
if decodeErr != nil {
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
}
bounds := info.Bounds()
if bounds.Dx() != config.Width || bounds.Dy() != config.Height {
return ImageInfo{}, common.UnsupportedMedia("invalid or corrupted image")
}
return ImageInfo{ContentType: mediaType, Width: config.Width, Height: config.Height}, nil
}
// safeDecode converts a decoder panic into an ordinary error. A malformed
// client file must never crash the process or become a 500.
func safeDecode(file *os.File) (img image.Image, err error) {
defer func() {
if recovered := recover(); recovered != nil {
img = nil
err = errors.New("image decoder panic")
}
}()
img, _, err = image.Decode(file)
return img, err
}
+134
View File
@@ -0,0 +1,134 @@
package attachments
import (
"bytes"
"context"
"image"
"image/color"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"testing"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
)
// writeTemp stores raw bytes in a temporary file and returns its path. The
// validator works on *os.File so it can seek, sniff and decode the same body
// without loading it into memory twice.
func writeTemp(t *testing.T, name string, data []byte) *os.File {
t.Helper()
path := filepath.Join(t.TempDir(), name)
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
file, err := os.Open(path)
if err != nil {
t.Fatalf("open %s: %v", path, err)
}
t.Cleanup(func() { _ = file.Close() })
return file
}
func encodePNG(t *testing.T, width, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
for x := 0; x < width; x++ {
for y := 0; y < height; y++ {
img.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 0x40, A: 0xff})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
func TestValidateAcceptsPNGAndJPEG(t *testing.T) {
validator := NewValidator(40_000_000, 256<<20)
ctx := context.Background()
pngFile := writeTemp(t, "image.png", encodePNG(t, 8, 6))
info, err := validator.Validate(ctx, pngFile, "image/png")
if err != nil {
t.Fatalf("valid png rejected: %v", err)
}
if info.ContentType != "image/png" || info.Width != 8 || info.Height != 6 {
t.Fatalf("unexpected png info: %+v", info)
}
img := image.NewRGBA(image.Rect(0, 0, 4, 3))
var buf bytes.Buffer
if err = jpeg.Encode(&buf, img, nil); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
jpegFile := writeTemp(t, "image.jpg", buf.Bytes())
info, err = validator.Validate(ctx, jpegFile, "image/jpeg; charset=binary")
if err != nil {
t.Fatalf("valid jpeg rejected: %v", err)
}
if info.ContentType != "image/jpeg" || info.Width != 4 || info.Height != 3 {
t.Fatalf("unexpected jpeg info: %+v", info)
}
}
func TestValidateRejectsMismatchedOrBrokenContent(t *testing.T) {
validator := NewValidator(40_000_000, 256<<20)
ctx := context.Background()
pngBytes := encodePNG(t, 8, 6)
cases := []struct {
name string
data []byte
declared string
code string
}{
{"png declared as jpeg", pngBytes, "image/jpeg", common.ErrorCodeUnsupportedMedia},
{"text declared as png", []byte("this is not an image at all"), "image/png", common.ErrorCodeUnsupportedMedia},
{"unsupported declared type", pngBytes, "image/gif", common.ErrorCodeUnsupportedMedia},
{"garbage declared type", pngBytes, "not a media type", common.ErrorCodeUnsupportedMedia},
{"truncated png", pngBytes[:len(pngBytes)/2], "image/png", common.ErrorCodeUnsupportedMedia},
{"empty body", nil, "image/png", common.ErrorCodeUnsupportedMedia},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
file := writeTemp(t, "upload", tc.data)
if _, err := validator.Validate(ctx, file, tc.declared); !common.IsCode(err, tc.code) {
t.Fatalf("Validate(%q) = %v, want code %s", tc.name, err, tc.code)
}
})
}
}
func TestValidateRejectsTooManyPixelsBeforeDecoding(t *testing.T) {
validator := NewValidator(100, 256<<20)
file := writeTemp(t, "big.png", encodePNG(t, 20, 20))
_, err := validator.Validate(context.Background(), file, "image/png")
if !common.IsCode(err, common.ErrorCodePayloadTooLarge) {
t.Fatalf("Validate = %v, want %s", err, common.ErrorCodePayloadTooLarge)
}
}
func TestValidateRejectsImageAboveDecodeBudget(t *testing.T) {
// A 100-pixel image needs ~400 bytes of RGBA memory, more than this budget.
validator := NewValidator(40_000_000, 100)
file := writeTemp(t, "budget.png", encodePNG(t, 10, 10))
_, err := validator.Validate(context.Background(), file, "image/png")
if !common.IsCode(err, common.ErrorCodePayloadTooLarge) {
t.Fatalf("Validate = %v, want %s", err, common.ErrorCodePayloadTooLarge)
}
}
func TestSafeDecodeConvertsPanicToError(t *testing.T) {
// image.Decode does not panic on arbitrary bytes, so this only guards the
// contract that safeDecode always returns an error instead of crashing.
file := writeTemp(t, "junk", []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff})
if _, err := safeDecode(file); err == nil {
t.Fatal("safeDecode accepted junk bytes")
}
}
+127
View File
@@ -0,0 +1,127 @@
// Package auth implements password hashing, Basic login, Bearer session
// middleware and the authentication routes.
package auth
import (
"encoding/base64"
"errors"
"log/slog"
"strings"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
type Handler struct {
store *store.Store
sessions *session.Store
}
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
return &Handler{store: st, sessions: sessions}
}
func (h *Handler) CreateSession(c fiber.Ctx) error {
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
if !ok {
return common.NewChallenge(basicChallenge, "invalid credentials")
}
user, err := h.store.GetUserByUsername(c.Context(), username)
if err != nil {
if common.IsCode(err, common.ErrorCodeNotFound) {
// An unknown username returns before Argon2 runs, while a known
// username with a wrong password runs VerifyPassword. The branches
// therefore take different time, so username enumeration through
// response timing is theoretically possible. The contract only
// requires the same 401 body and challenge.
return common.NewChallenge(basicChallenge, "invalid credentials")
}
return err
}
valid, err := VerifyPassword(user.PasswordHash, password)
if err != nil || !valid {
return common.NewChallenge(basicChallenge, "invalid credentials")
}
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
if err != nil {
slog.Error("create session", "err", err)
return common.Unavailable("session store unavailable")
}
return c.Status(fiber.StatusCreated).JSON(model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: common.RFCFormTime(expiresAt),
User: user,
})
}
func (h *Handler) RevokeSession(c fiber.Ctx) error {
token, ok := common.SessionToken(c)
if !ok {
return common.NewChallenge(bearerChallenge, "authentication required")
}
if err := h.sessions.Revoke(c.Context(), token); err != nil {
slog.Error("revoke session", "err", err)
return common.Unavailable("session store unavailable")
}
return c.SendStatus(fiber.StatusNoContent)
}
func BearerAuth(sessions *session.Store) fiber.Handler {
return func(c fiber.Ctx) error {
header := strings.TrimSpace(c.Get(fiber.HeaderAuthorization))
scheme, token, found := strings.Cut(header, " ")
token = strings.TrimSpace(token)
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") {
return common.NewChallenge(bearerChallenge, "authentication required")
}
userID, err := sessions.Lookup(c.Context(), token)
if err != nil {
if errors.Is(err, session.ErrNotFound) {
return common.NewChallenge(bearerChallenge, "session expired or revoked")
}
slog.Error("session lookup", "err", err)
return common.Unavailable("session store unavailable")
}
c.Locals(common.KeyUserID, userID)
c.Locals(common.KeySessionToken, token)
return c.Next()
}
}
func parseBasic(header string) (string, string, bool) {
scheme, encoded, found := strings.Cut(strings.TrimSpace(header), " ")
if !found || !strings.EqualFold(scheme, "Basic") || encoded == "" {
return "", "", false
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
if decoded, err = base64.RawStdEncoding.DecodeString(encoded); err != nil {
return "", "", false
}
}
// RFC 7617: split at the first colon; a colon is legal inside the password.
username, password, found := strings.Cut(string(decoded), ":")
if !found || username == "" || password == "" {
return "", "", false
}
return username, password, true
}
+73
View File
@@ -0,0 +1,73 @@
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonMemory = 64 * 1024
argonIterations = 2
argonParallelism = 4
argonKeyLength = 32
argonSaltLength = 16
)
var ErrInvalidHash = errors.New("invalid password hash")
func HashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key)), nil
}
func VerifyPassword(encoded, password string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, ErrInvalidHash
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
return false, ErrInvalidHash
}
var memory uint32
var iterations uint32
var parallelism uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil {
return false, ErrInvalidHash
}
// argon2.IDKey panics when the cost parameters are outside its supported
// range. A corrupted row or an attacker-supplied encoding must be rejected
// with ErrInvalidHash instead of taking the process down.
if iterations < 1 || parallelism < 1 || memory < 8*uint32(parallelism) {
return false, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) == 0 {
return false, ErrInvalidHash
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(expected) == 0 {
return false, ErrInvalidHash
}
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expected)))
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
}
+64
View File
@@ -0,0 +1,64 @@
package auth
import (
"strings"
"testing"
)
func TestPasswordRoundTripPreservesFullRange(t *testing.T) {
passwords := []string{
"simple-password-123",
"colon:inside:password",
"пароль-с-кириллицей-12",
strings.Repeat("😀", 128),
}
for _, password := range passwords {
hash, err := HashPassword(password)
if err != nil {
t.Fatalf("HashPassword: %v", err)
}
ok, err := VerifyPassword(hash, password)
if err != nil || !ok {
t.Fatalf("VerifyPassword rejected the correct password (ok=%v err=%v)", ok, err)
}
ok, err = VerifyPassword(hash, password+"x")
if err != nil || ok {
t.Fatalf("VerifyPassword accepted a different password (ok=%v err=%v)", ok, err)
}
}
}
func TestPasswordHashIsSalted(t *testing.T) {
first, err := HashPassword("same-password-123")
if err != nil {
t.Fatal(err)
}
second, err := HashPassword("same-password-123")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
if _, err := VerifyPassword("not-a-hash", "same-password-123"); err == nil {
t.Fatal("invalid encoded hash was accepted")
}
}
func TestVerifyPasswordRejectsMalformedCostAndEmptyDigest(t *testing.T) {
malformed := []string{
// Empty digest would make argon2 derive a zero-length key.
"$argon2id$v=19$m=65536,t=2,p=4$c2FsdA$",
// Zero cost parameters are outside argon2's supported range and would
// otherwise panic inside the KDF.
"$argon2id$v=19$m=65536,t=0,p=4$c2FsdA$YWJjZA",
"$argon2id$v=19$m=65536,t=2,p=0$c2FsdA$YWJjZA",
"$argon2id$v=19$m=1,t=2,p=4$c2FsdA$YWJjZA",
}
for _, encoded := range malformed {
ok, err := VerifyPassword(encoded, "same-password-123")
if err == nil || ok {
t.Fatalf("VerifyPassword(%q) = (%v, %v), want ErrInvalidHash", encoded, ok, err)
}
}
}
+86
View File
@@ -0,0 +1,86 @@
// Package chats implements chat creation, lookup and cursor-paginated listing.
package chats
import (
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type Handler struct {
store *store.Store
jsonBodyLimit int64
}
func NewHandler(st *store.Store, jsonBodyLimit int64) *Handler {
return &Handler{store: st, jsonBodyLimit: jsonBodyLimit}
}
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
}
func (h *Handler) CreateChat(c fiber.Ctx) error {
userID := common.MustUserID(c)
var req CreateChatRequest
if err := common.BindJSON(c, &req, h.jsonBodyLimit); err != nil {
return err
}
if err := common.ValidateChatTitle(req.Title); err != nil {
return err
}
if err := common.ValidateMemberIDs(req.MemberIDs, userID); err != nil {
return err
}
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).JSON(chat)
}
func (h *Handler) ListChats(c fiber.Ctx) error {
userID := common.MustUserID(c)
limit, err := common.ParseLimit(c, 50)
if err != nil {
return err
}
cursor, err := common.ParseCursor(c)
if err != nil {
return err
}
if cursor != nil && cursor.ContextID != userID {
return common.BadRequest("bad cursor value")
}
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
if err != nil {
return err
}
return c.JSON(page)
}
func (h *Handler) GetChat(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
if err != nil {
return err
}
return c.JSON(chat)
}
@@ -0,0 +1,64 @@
package common
import (
"strings"
"testing"
"github.com/google/uuid"
)
func TestValidateFilename(t *testing.T) {
valid := []string{"photo.png", "фото 1.jpeg", "a", strings.Repeat("a", 255)}
for _, name := range valid {
if err := ValidateFilename(name); err != nil {
t.Errorf("ValidateFilename(%q) = %v, want nil", name, err)
}
}
invalid := []string{
"", " ", ".", "..", "dir/photo.png", `dir\photo.png`,
"nul\x00byte", "line\nbreak", strings.Repeat("a", 256),
}
for _, name := range invalid {
if err := ValidateFilename(name); err == nil {
t.Errorf("ValidateFilename(%q) = nil, want error", name)
}
}
}
func TestValidateAttachmentIDs(t *testing.T) {
ids := make([]uuid.UUID, 10)
for index := range ids {
ids[index] = uuid.New()
}
if err := ValidateAttachmentIDs(ids); err != nil {
t.Fatalf("ten unique ids rejected: %v", err)
}
if err := ValidateAttachmentIDs(append(ids, uuid.New())); err == nil {
t.Fatal("eleven ids accepted")
}
if err := ValidateAttachmentIDs([]uuid.UUID{ids[0], ids[0]}); err == nil {
t.Fatal("duplicate ids accepted")
}
if err := ValidateAttachmentIDs(nil); err != nil {
t.Fatalf("empty list rejected: %v", err)
}
}
func TestValidateMessageText(t *testing.T) {
if err := ValidateMessageText("", 1); err != nil {
t.Fatalf("empty text with attachment rejected: %v", err)
}
if err := ValidateMessageText(" ", 1); err != nil {
t.Fatalf("blank text with attachment rejected: %v", err)
}
if err := ValidateMessageText("", 0); err == nil {
t.Fatal("empty text without attachment accepted")
}
if err := ValidateMessageText(strings.Repeat("ж", 4000), 0); err != nil {
t.Fatalf("4000 code points rejected: %v", err)
}
if err := ValidateMessageText(strings.Repeat("ж", 4001), 1); err == nil {
t.Fatal("4001 code points accepted")
}
}
+63
View File
@@ -0,0 +1,63 @@
package common
import (
"bytes"
"encoding/json"
"io"
"strings"
"github.com/gofiber/fiber/v3"
)
// ReadBodyLimited reads at most limit bytes from the request body. The caller
// must use it instead of c.Body() when the endpoint has a smaller budget than
// the process-wide Fiber.BodyLimit. The limit itself belongs to the caller
// (config.MaxJSONBodyBytes for JSON endpoints).
//
// with StreamRequestBody enabled fasthttp exposes the network body as a
// stream, so io.ReadAll over a LimitReader allocates only the bytes the
// endpoint actually accepts instead of the whole upload limit.
func ReadBodyLimited(c fiber.Ctx, limit int64) ([]byte, error) {
var reader io.Reader = c.Request().BodyStream()
if reader == nil {
reader = bytes.NewReader(c.Body())
}
data, err := io.ReadAll(io.LimitReader(reader, limit+1))
if err != nil {
return nil, BadRequest("incomplete request body")
}
if int64(len(data)) > limit {
return nil, PayloadTooLarge("request body is too large")
}
return data, nil
}
func BindJSON(c fiber.Ctx, dst any, limit int64) error {
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body, err := ReadBodyLimited(c, limit)
if err != nil {
return err
}
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
return nil
}
+142
View File
@@ -0,0 +1,142 @@
// Package common contains cross-cutting HTTP helpers: contract errors, JSON
// binding, validation, cursor pagination and timestamp formatting.
package common
import (
"errors"
"net/http"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/requestid"
)
const (
ErrorCodeInvalidRequest = "invalid_request"
ErrorCodeUnauthorized = "unauthorized"
ErrorCodeNotFound = "not_found"
ErrorCodeConflict = "conflict"
ErrorCodePayloadTooLarge = "payload_too_large"
ErrorCodeUnsupportedMedia = "unsupported_media_type"
ErrorCodeRateLimited = "rate_limited"
ErrorCodeUnavailable = "unavailable"
ErrorCodeInternal = "internal_error"
)
type APIErrorResponse struct {
Error APIError `json:"error"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
func NewError(code, message, requestID string) APIErrorResponse {
return APIErrorResponse{
Error: APIError{
Code: code,
Message: message,
RequestID: requestID,
},
}
}
// AppError is the single contract error type. Handlers and the store return it;
// the Fiber error handler is the only place that turns it into a response.
type AppError struct {
Status int
Code string
Message string
Challenge string // WWW-Authenticate value, set for 401 responses
}
func (e *AppError) Error() string {
return e.Message
}
func NewAppError(status int, code, message string) *AppError {
return &AppError{
Status: status,
Code: code,
Message: message,
}
}
func BadRequest(message string) *AppError {
return NewAppError(http.StatusBadRequest, ErrorCodeInvalidRequest, message)
}
func NotFound(message string) *AppError {
return NewAppError(http.StatusNotFound, ErrorCodeNotFound, message)
}
func Conflict(message string) *AppError {
return NewAppError(http.StatusConflict, ErrorCodeConflict, message)
}
func UnsupportedMedia(message string) *AppError {
return NewAppError(http.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
}
func PayloadTooLarge(message string) *AppError {
return NewAppError(http.StatusRequestEntityTooLarge, ErrorCodePayloadTooLarge, message)
}
func Internal() *AppError {
return NewAppError(http.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
}
func Unavailable(message string) *AppError {
return NewAppError(http.StatusServiceUnavailable, ErrorCodeUnavailable, message)
}
// NewChallenge builds the 401 that carries a WWW-Authenticate header.
func NewChallenge(challenge, message string) *AppError {
return &AppError{
Status: http.StatusUnauthorized,
Code: ErrorCodeUnauthorized,
Message: message,
Challenge: challenge,
}
}
// IsCode reports whether err is an AppError with the given contract code.
func IsCode(err error, code string) bool {
appErr, ok := errors.AsType[*AppError](err)
return ok && appErr.Code == code
}
func ErrorCodeFromStatus(status int) string {
switch status {
case http.StatusBadRequest:
return ErrorCodeInvalidRequest
case http.StatusUnauthorized:
return ErrorCodeUnauthorized
case http.StatusNotFound:
return ErrorCodeNotFound
case http.StatusConflict:
return ErrorCodeConflict
case http.StatusRequestEntityTooLarge:
return ErrorCodePayloadTooLarge
case http.StatusUnsupportedMediaType:
return ErrorCodeUnsupportedMedia
case http.StatusTooManyRequests:
return ErrorCodeRateLimited
case http.StatusServiceUnavailable:
return ErrorCodeUnavailable
default:
return ErrorCodeInternal
}
}
func getRequestID(c fiber.Ctx) string {
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
return id
}
return requestid.FromContext(c)
}
func SendError(c fiber.Ctx, status int, code, message string) error {
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
}
@@ -0,0 +1,30 @@
package common
import (
"strings"
"testing"
)
func TestValidateIdempotencyKey(t *testing.T) {
tests := []struct {
name string
key string
ok bool
}{
{name: "hex", key: "4f8c2d1e", ok: true},
{name: "allowed punctuation", key: "load-1_a.b:c", ok: true},
{name: "empty", key: "", ok: false},
{name: "space", key: "two words", ok: false},
{name: "slash", key: "a/b", ok: false},
{name: "too long", key: strings.Repeat("a", 129), ok: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := ValidateIdempotencyKey(test.key) == nil
if got != test.ok {
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
}
})
}
}
+39
View File
@@ -0,0 +1,39 @@
package common
import (
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
const (
KeyUserID = "userID"
KeySessionToken = "sessionToken"
)
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
return userID, ok
}
func MustUserID(c fiber.Ctx) uuid.UUID {
userID, ok := UserID(c)
if !ok {
panic("common: authenticated user ID is missing from the request context")
}
return userID
}
func SessionToken(c fiber.Ctx) (string, bool) {
token, ok := c.Locals(KeySessionToken).(string)
return token, ok && token != ""
}
// PathUUID parses a UUID path parameter. A malformed value is a contract
// invalid_request, not a lookup failure.
func PathUUID(c fiber.Ctx, name string) (uuid.UUID, error) {
id, err := uuid.Parse(c.Params(name))
if err != nil {
return uuid.Nil, BadRequest("invalid " + name + " format")
}
return id, nil
}
+102
View File
@@ -0,0 +1,102 @@
package common
import (
"encoding/base64"
"strconv"
"strings"
"time"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type CursorKeyCtx struct {
Time time.Time
ID uuid.UUID
ContextID uuid.UUID
}
type Page[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
limitStr, exists := c.Queries()["limit"]
if !exists {
return defaultLimit, nil
}
if strings.TrimSpace(limitStr) == "" {
return 0, BadRequest("limit param declared but empty")
}
limit, err := strconv.Atoi(limitStr)
if err != nil || limit < 1 || limit > 100 {
return 0, BadRequest("limit must be an integer between 1 and 100")
}
return limit, nil
}
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
cursorStr, exists := c.Queries()["cursor"]
if !exists {
return nil, nil
}
if strings.TrimSpace(cursorStr) == "" {
return nil, BadRequest("cursor param declared but empty")
}
cursor, ok := DecodeCursor(cursorStr)
if !ok {
return nil, BadRequest("invalid cursor format")
}
return cursor, nil
}
func EncodeCursor(key CursorKeyCtx) string {
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil, false
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return nil, false
}
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
if err != nil {
return nil, false
}
parsedID, err := uuid.Parse(parts[1])
if err != nil {
return nil, false
}
parsedContext, err := uuid.Parse(parts[2])
if err != nil {
return nil, false
}
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
}
func NextCursor[T interface {
GetID() uuid.UUID
GetCreatedAt() time.Time
}](items []T, hasMore bool, contextID uuid.UUID) *string {
if !hasMore || len(items) == 0 {
return nil
}
last := items[len(items)-1]
encoded := EncodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
return &encoded
}
+31
View File
@@ -0,0 +1,31 @@
package common
import (
"testing"
"time"
"github.com/google/uuid"
)
func TestCursorRoundTrip(t *testing.T) {
want := CursorKeyCtx{
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
}
encoded := EncodeCursor(want)
got, ok := DecodeCursor(encoded)
if !ok {
t.Fatal("cursor did not decode")
}
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
t.Fatalf("cursor round trip changed the key: %+v", got)
}
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
if _, ok := DecodeCursor(invalid); ok {
t.Fatalf("invalid cursor %q was accepted", invalid)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
package common
import "testing"
func TestValidatePasswordRange(t *testing.T) {
cases := []struct {
password string
valid bool
}{
{"short", false},
{"12345678901", false},
{"123456789012", true},
{"пароль-из-двенадцати", true},
{"😀", false},
}
for _, tc := range cases {
if got := ValidatePassword(tc.password) == nil; got != tc.valid {
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
}
}
}
+27
View File
@@ -0,0 +1,27 @@
package common
import (
"encoding/json"
"time"
)
// PostgreSQL stores microseconds, so keeping the same boundary in Go
// prevents a create response from showing more precision
// than a later read can reproduce.
const storageTimePrecision = time.Microsecond
type RFCFormTime time.Time
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
// RFC 3339 permits an optional fractional second.
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
layout := "2006-01-02T15:04:05Z"
if utc.Nanosecond() != 0 {
layout = "2006-01-02T15:04:05.000000Z"
}
return json.Marshal(utc.Format(layout))
}
func NowUTC() RFCFormTime {
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
}
+48
View File
@@ -0,0 +1,48 @@
package common
import (
"encoding/json"
"testing"
"time"
)
func TestNowUTCHasMicrosecondPrecision(t *testing.T) {
now := time.Time(NowUTC())
if now.Nanosecond()%1000 != 0 {
t.Fatalf("NowUTC() kept precision below a microsecond: %v", now)
}
if now.Location() != time.UTC {
t.Fatalf("NowUTC() location = %v, want UTC", now.Location())
}
}
func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) {
cases := []struct {
name string
value time.Time
want string
}{
{
name: "microseconds",
value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC),
want: `"2026-10-26T12:34:56.123456Z"`,
},
{
name: "exact second",
value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC),
want: `"2026-10-26T12:34:56Z"`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
encoded, err := json.Marshal(RFCFormTime(tc.value))
if err != nil {
t.Fatalf("marshal RFC form time: %v", err)
}
if string(encoded) != tc.want {
t.Fatalf("RFC form time = %s, want %s", encoded, tc.want)
}
})
}
}
+149
View File
@@ -0,0 +1,149 @@
package common
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
var (
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
)
func blank(s string) bool {
return strings.TrimSpace(s) == ""
}
func strLenBetween(s string, min, max int) bool {
n := utf8.RuneCountInString(s)
return n >= min && n <= max
}
func ValidateCreateUser(username, displayName string) error {
if !usernameRegex.MatchString(username) {
return BadRequest("username must match ^[a-z0-9_]{3,32}$")
}
if blank(displayName) {
return BadRequest("display_name must not be empty or only whitespace")
}
if !strLenBetween(displayName, 1, 100) {
return BadRequest("display_name must be between 1 and 100 Unicode code points")
}
return nil
}
func ValidatePassword(password string) error {
if blank(password) {
return BadRequest("password must not be empty or only whitespace")
}
if !strLenBetween(password, 12, 128) {
return BadRequest("password must be between 12 and 128 Unicode code points")
}
return nil
}
func ValidateChatTitle(title string) error {
if blank(title) {
return BadRequest("title must not be empty or only whitespace")
}
if !strLenBetween(title, 1, 100) {
return BadRequest("title must be between 1 and 100 Unicode code points")
}
return nil
}
func ValidateMessageText(text string, attachmentCount int) error {
if attachmentCount == 0 && blank(text) {
return BadRequest("text must not be empty or only whitespace")
}
if !strLenBetween(text, 0, 4000) {
return BadRequest("text must be between 0 and 4000 Unicode code points")
}
return nil
}
func ValidateAttachmentIDs(ids []uuid.UUID) error {
if len(ids) > 10 {
return BadRequest("attachment_ids must contain at most 10 items")
}
seen := make(map[uuid.UUID]bool, len(ids))
for _, id := range ids {
if seen[id] {
return BadRequest("attachment_ids must not contain duplicates")
}
seen[id] = true
}
return nil
}
func ValidateFilename(filename string) error {
if !strLenBetween(filename, 1, 255) {
return BadRequest("filename must be between 1 and 255 Unicode code points")
}
if blank(filename) {
return BadRequest("filename must not be empty or only whitespace")
}
if filename == "." || filename == ".." {
return BadRequest("filename is not allowed")
}
for _, r := range filename {
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
return BadRequest("filename contains a forbidden character")
}
}
return nil
}
func ValidateIdempotencyKey(key string) error {
if key == "" {
return BadRequest("Idempotency-Key header is required")
}
if !idempotencyKeyRegex.MatchString(key) {
return BadRequest("Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
}
return nil
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) error {
if len(ids) < 1 || len(ids) > 100 {
return BadRequest("member_ids must contain between 1 and 100 members")
}
seen := make(map[uuid.UUID]bool, len(ids))
callerFound := false
for _, id := range ids {
if seen[id] {
return BadRequest("member_ids must not contain duplicates")
}
seen[id] = true
if id == callerID {
callerFound = true
}
}
if !callerFound {
return BadRequest("caller must be included in member_ids")
}
return nil
}
+283
View File
@@ -0,0 +1,283 @@
// Package config loads and validates process configuration from environment
// variables and optional *_FILE secrets.
package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
// Configuration may make a limit stricter, never looser.
MaxUploadBytesHardCap = 10 * 1024 * 1024
MaxImagePixelsHardCap = 40_000_000
// MaxJSONBodyBytes is the body budget of every JSON endpoint. It is also
// the slack between the global HTTP body limit and the upload limit, so a
// smaller MAX_UPLOAD_BYTES cannot strangle JSON requests.
MaxJSONBodyBytes = 1 * 1024 * 1024
)
type Config struct {
Host string
Port string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
DatabaseURL string
CacheURL string
DBMaxConns int32
DBTimeout time.Duration
RedisTimeout time.Duration
StartupWait time.Duration
RunMigrations bool
MigrateOnly bool
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
UploadTimeout time.Duration
DownloadTimeout time.Duration
MaxUploadBytes int64
MaxImagePixels int64
ImageDecodeBytes int64
UploadTempDir string
// HTTP timeouts and body limits are derived once in Load so that app.go
// and the handlers never invent values of their own.
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
UploadDrainLimit int64
HTTPBodyLimit int
ReconcileGrace time.Duration
ReconcileInterval time.Duration
}
func Load() (Config, error) {
instance, err := instanceID()
if err != nil {
return Config{}, err
}
sessionTTL, err := envInt("SESSION_TTL_SECONDS", 3600, 1, 0)
if err != nil {
return Config{}, err
}
idempotencyTTL, err := envInt("IDEMPOTENCY_TTL_SECONDS", 86400, 1, 0)
if err != nil {
return Config{}, err
}
maxConns, err := envInt("DB_POOL_MAX_CONNS", 10, 1, 100)
if err != nil {
return Config{}, err
}
maxUpload, err := envInt[int64]("MAX_UPLOAD_BYTES", MaxUploadBytesHardCap, 1, MaxUploadBytesHardCap)
if err != nil {
return Config{}, err
}
maxPixels, err := envInt[int64]("MAX_IMAGE_PIXELS", MaxImagePixelsHardCap, 1, MaxImagePixelsHardCap)
if err != nil {
return Config{}, err
}
decodeMB, err := envInt("IMAGE_DECODE_MEMORY_MB", 256, 32, 4096)
if err != nil {
return Config{}, err
}
cfg := Config{
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
InstanceID: instance,
SessionTTL: time.Duration(sessionTTL) * time.Second,
IdempotencyTTL: time.Duration(idempotencyTTL) * time.Second,
DBMaxConns: int32(maxConns),
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
S3Region: envOr("S3_REGION", "us-east-1"),
S3Bucket: envOr("S3_BUCKET", "messenger-attachments"),
ReadTimeout: 30 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 60 * time.Second,
UploadTimeout: 30 * time.Second,
DownloadTimeout: 60 * time.Second,
MaxUploadBytes: maxUpload,
MaxImagePixels: maxPixels,
ImageDecodeBytes: int64(decodeMB) * 1024 * 1024,
UploadTempDir: envOr("UPLOAD_TEMP_DIR", filepath.Join(os.TempDir(), "messenger-uploads")),
}
cfg.deriveHTTPLimits()
if cfg.RunMigrations, err = envBool("RUN_MIGRATIONS", true); err != nil {
return Config{}, err
}
if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil {
return Config{}, err
}
reconcileOnly, err := envBool("RECONCILE_ONLY", false)
if err != nil {
return Config{}, err
}
reconcileGrace, err := envInt("RECONCILE_GRACE_SECONDS", 900, 60, 0)
if err != nil {
return Config{}, err
}
cfg.ReconcileGrace = time.Duration(reconcileGrace) * time.Second
reconcileInterval, err := envInt("RECONCILE_INTERVAL_SECONDS", 300, 10, 0)
if err != nil {
return Config{}, err
}
cfg.ReconcileInterval = time.Duration(reconcileInterval) * time.Second
if cfg.DatabaseURL, err = secret("DATABASE_URL"); err != nil {
return Config{}, err
}
if cfg.DatabaseURL == "" {
return Config{}, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
}
if cfg.MigrateOnly {
return cfg, nil
}
if cfg.S3Endpoint, err = secret("S3_ENDPOINT"); err != nil {
return Config{}, err
}
if cfg.S3Endpoint == "" {
return Config{}, fmt.Errorf("S3_ENDPOINT or S3_ENDPOINT_FILE is required")
}
if cfg.S3AccessKey, err = secret("S3_ACCESS_KEY_ID"); err != nil {
return Config{}, err
}
if cfg.S3AccessKey == "" {
return Config{}, fmt.Errorf("S3_ACCESS_KEY_ID or S3_ACCESS_KEY_ID_FILE is required")
}
if cfg.S3SecretKey, err = secret("S3_SECRET_ACCESS_KEY"); err != nil {
return Config{}, err
}
if cfg.S3SecretKey == "" {
return Config{}, fmt.Errorf("S3_SECRET_ACCESS_KEY or S3_SECRET_ACCESS_KEY_FILE is required")
}
if reconcileOnly {
return cfg, nil
}
if cfg.CacheURL, err = secret("CACHE_URL"); err != nil {
return Config{}, err
}
if cfg.CacheURL == "" {
if cfg.CacheURL, err = secret("REDIS_URL"); err != nil {
return Config{}, err
}
}
if cfg.CacheURL == "" {
return Config{}, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required")
}
if value := strings.ToLower(envOr("SESSION_STORE", "redis")); value != "redis" {
return Config{}, fmt.Errorf("SESSION_STORE must be redis (got %q)", value)
}
return cfg, nil
}
// deriveHTTPLimits is the single place that relates the three HTTP budgets:
// the transport gate must admit both a full upload and a full JSON body, and it
// must leave room for the handler to drain an oversized declared body so the
// client receives a 413 instead of a connection reset.
func (c *Config) deriveHTTPLimits() {
c.UploadDrainLimit = c.MaxUploadBytes + MaxJSONBodyBytes
c.HTTPBodyLimit = int(c.UploadDrainLimit)
}
func instanceID() (string, error) {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value, nil
}
name, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("determine INSTANCE_ID: %w", err)
}
if name = strings.TrimSpace(name); name == "" {
return "", fmt.Errorf("determine INSTANCE_ID: hostname is empty and INSTANCE_ID is not set")
}
return name, nil
}
func envBool(name string, fallback bool) (bool, error) {
value := os.Getenv(name)
if value == "" {
return fallback, nil
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return false, fmt.Errorf("%s must be true or false", name)
}
return parsed, nil
}
// envInt parses an integer setting into int or int64; max <= 0 means "no upper
// bound". Both widths are needed by Config, and one helper keeps validation
// identical for every numeric variable.
func envInt[T ~int | ~int64](name string, fallback, min, max T) (T, error) {
value := os.Getenv(name)
if value == "" {
return fallback, nil
}
parsed, err := strconv.ParseInt(value, 10, 64)
if err != nil || parsed < int64(min) || (max > 0 && parsed > int64(max)) {
if max > 0 {
return 0, fmt.Errorf("%s must be an integer between %d and %d", name, min, max)
}
return 0, fmt.Errorf("%s must be an integer >= %d", name, min)
}
result := T(parsed)
if int64(result) != parsed {
return 0, fmt.Errorf("%s is out of range", name)
}
return result, nil
}
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
func secret(name string) (string, error) {
if value := os.Getenv(name); value != "" {
return value, nil
}
path := os.Getenv(name + "_FILE")
if path == "" {
return "", nil
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s_FILE: %w", name, err)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE is empty", name)
}
return value, nil
}
+64
View File
@@ -0,0 +1,64 @@
package config
import "testing"
func TestInstanceIDUsesConfiguredValue(t *testing.T) {
t.Setenv("INSTANCE_ID", " api-1 ")
got, err := instanceID()
if err != nil {
t.Fatalf("instanceID: %v", err)
}
if got != "api-1" {
t.Fatalf("instanceID = %q, want api-1", got)
}
}
func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Setenv("INSTANCE_ID", " ")
got, err := instanceID()
if err != nil {
t.Fatalf("instanceID: %v", err)
}
if got == "" {
t.Fatal("instanceID returned an empty value")
}
}
func TestDerivedHTTPLimits(t *testing.T) {
cfg := Config{MaxUploadBytes: 2 * 1024 * 1024}
cfg.deriveHTTPLimits()
if cfg.UploadDrainLimit != cfg.MaxUploadBytes+MaxJSONBodyBytes {
t.Fatalf("drain limit = %d, want upload + JSON body", cfg.UploadDrainLimit)
}
if cfg.HTTPBodyLimit != int(cfg.UploadDrainLimit) {
t.Fatalf("body limit = %d, want %d", cfg.HTTPBodyLimit, cfg.UploadDrainLimit)
}
if cfg.HTTPBodyLimit-int(cfg.MaxUploadBytes) != MaxJSONBodyBytes {
t.Fatal("transport gate would strangle a full JSON body")
}
}
func TestEnvIntHandlesBothWidths(t *testing.T) {
t.Setenv("TEST_ENV_INT", "42")
small, err := envInt("TEST_ENV_INT", 1, 1, 100)
if err != nil || small != 42 {
t.Fatalf("envInt = %d, %v; want 42, nil", small, err)
}
large, err := envInt[int64]("TEST_ENV_INT", 1, 1, 100)
if err != nil || large != 42 {
t.Fatalf("envInt[int64] = %d, %v; want 42, nil", large, err)
}
}
func TestEnvIntRejectsOutOfRange(t *testing.T) {
for _, value := range []string{"0", "101", "not-a-number"} {
t.Setenv("TEST_ENV_INT", value)
if _, err := envInt("TEST_ENV_INT", 1, 1, 100); err == nil {
t.Fatalf("envInt accepted %q", value)
}
}
}
+44
View File
@@ -0,0 +1,44 @@
// Package database owns the PostgreSQL connection pool and schema migrations.
package database
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
}
cfg.MaxConns = maxConns
cfg.MinConns = 1
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
deadline := time.Now().Add(wait)
for {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err = pool.Ping(pingCtx)
cancel()
if err == nil {
return pool, nil
}
if time.Now().After(deadline) || ctx.Err() != nil {
pool.Close()
return nil, fmt.Errorf("postgres is not reachable: %w", err)
}
time.Sleep(500 * time.Millisecond)
}
}
+71
View File
@@ -0,0 +1,71 @@
package database
import (
"embed"
"errors"
"fmt"
"time"
"github.com/golang-migrate/migrate/v4"
pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
const migrationsTable = "schema_migrations"
// Migrate applies every pending embedded migration. golang-migrate takes its
// own advisory lock, so concurrent processes serialise instead of racing the
// schema.
func Migrate(databaseURL string) error {
source, err := iofs.New(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("load embedded migrations: %w", err)
}
connConfig, err := pgx.ParseConfig(databaseURL)
if err != nil {
_ = source.Close()
return fmt.Errorf("parse DATABASE_URL for migrations: %w", err)
}
if connConfig.RuntimeParams == nil {
connConfig.RuntimeParams = make(map[string]string)
}
connConfig.RuntimeParams["lock_timeout"] = "30000"
connConfig.ConnectTimeout = 3 * time.Second
db := stdlib.OpenDB(*connConfig)
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
driver, err := pgxmigrate.WithInstance(db, &pgxmigrate.Config{
MigrationsTable: migrationsTable,
StatementTimeout: 30 * time.Second,
})
if err != nil {
_ = source.Close()
_ = db.Close()
return fmt.Errorf("create migration driver: %w", err)
}
migrator, err := migrate.NewWithInstance("iofs", source, "pgx5", driver)
if err != nil {
_ = source.Close()
_ = driver.Close()
return fmt.Errorf("create migrator: %w", err)
}
defer func() {
// Close closes both the embedded source and the database connection.
_, _ = migrator.Close()
}()
if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
return fmt.Errorf("apply migrations: %w", err)
}
return nil
}
@@ -0,0 +1,4 @@
DROP TABLE IF EXISTS messages;
DROP TABLE IF EXISTS chat_members;
DROP TABLE IF EXISTS chats;
DROP TABLE IF EXISTS users;
@@ -0,0 +1,38 @@
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_user_idx
ON chat_members (user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
@@ -0,0 +1 @@
DROP TABLE IF EXISTS message_idempotency;
@@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS message_idempotency (
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
idempotency_key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (sender_id, chat_id, idempotency_key),
CONSTRAINT message_idempotency_key_len CHECK (char_length(idempotency_key) BETWEEN 1 AND 128)
);
CREATE INDEX IF NOT EXISTS message_idempotency_expires_at_idx
ON message_idempotency (expires_at);
@@ -0,0 +1,6 @@
DROP TABLE IF EXISTS message_attachments;
DROP TABLE IF EXISTS attachments;
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_len;
ALTER TABLE messages
ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000);
@@ -0,0 +1,46 @@
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_len;
ALTER TABLE messages
ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
CREATE TABLE IF NOT EXISTS attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 bytea NOT NULL,
object_key text NOT NULL,
status text NOT NULL,
error_code text,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_len CHECK (octet_length(sha256) = 32),
CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready', 'failed')),
CONSTRAINT attachments_error_state CHECK (
(status = 'pending' AND error_code IS NULL) OR
(status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL)
),
CONSTRAINT attachments_object_key_key UNIQUE (object_key)
);
CREATE INDEX IF NOT EXISTS attachments_chat_created_idx
ON attachments (chat_id, created_at, id);
CREATE INDEX IF NOT EXISTS attachments_status_created_idx
ON attachments (status, created_at);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE RESTRICT,
position integer NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position CHECK (position >= 0),
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position)
);
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx
ON message_attachments (attachment_id);
+88
View File
@@ -0,0 +1,88 @@
package database
import (
"errors"
"io/fs"
"regexp"
"strconv"
"testing"
"github.com/golang-migrate/migrate/v4/source/iofs"
)
// latestMigrationVersion is the only value to bump when a migration is added.
// The rest of the test derives filenames and ordering from the directory.
const latestMigrationVersion = 3
var migrationFilePattern = regexp.MustCompile(`^(\d{4})_[a-z0-9_]+\.(up|down)\.sql$`)
func TestEmbeddedMigrationsAreCompleteAndContiguous(t *testing.T) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
t.Fatalf("read embedded migrations: %v", err)
}
up := make(map[int]string, latestMigrationVersion)
down := make(map[int]string, latestMigrationVersion)
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
match := migrationFilePattern.FindStringSubmatch(name)
if match == nil {
t.Fatalf("migration %q does not match NNNN_name.{up,down}.sql", name)
}
version, parseErr := strconv.Atoi(match[1])
if parseErr != nil || version < 1 || version > latestMigrationVersion {
t.Fatalf("migration %q has version outside 1..%d", name, latestMigrationVersion)
}
files := up
if match[2] == "down" {
files = down
}
if previous, ok := files[version]; ok {
t.Fatalf("version %d has two %s files: %q and %q", version, match[2], previous, name)
}
files[version] = name
}
for version := 1; version <= latestMigrationVersion; version++ {
if up[version] == "" {
t.Fatalf("version %d is missing an up migration", version)
}
if down[version] == "" {
t.Fatalf("version %d is missing a down migration", version)
}
}
source, err := iofs.New(migrationFiles, "migrations")
if err != nil {
t.Fatalf("parse migrations with golang-migrate: %v", err)
}
defer func() { _ = source.Close() }()
version, err := source.First()
if err != nil {
t.Fatalf("read first migration: %v", err)
}
for expected := 1; expected <= latestMigrationVersion; expected++ {
if version != uint(expected) {
t.Fatalf("migration order = %d, want %d", version, expected)
}
next, nextErr := source.Next(version)
if expected == latestMigrationVersion {
if !errors.Is(nextErr, fs.ErrNotExist) {
t.Fatalf("expected %d to be the last migration, got %v", version, nextErr)
}
break
}
if nextErr != nil {
t.Fatalf("read migration after %d: %v", version, nextErr)
}
version = next
}
}
+61
View File
@@ -0,0 +1,61 @@
// Package health exposes liveness and readiness endpoints plus the process
// shutdown flag used by readiness.
package health
import (
"sync/atomic"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/objectstore"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
type Handler struct {
store *store.Store
sessions *session.Store
objects *objectstore.Client
}
func NewHandler(st *store.Store, sessions *session.Store, objects *objectstore.Client) *Handler {
return &Handler{store: st, sessions: sessions, objects: objects}
}
var shuttingDown atomic.Bool
func SignalShutdown() {
shuttingDown.Store(true)
}
type Status struct {
Status string `json:"status"`
}
func (h *Handler) Live(c fiber.Ctx) error {
return c.JSON(Status{Status: "ok"})
}
func (h *Handler) Ready(c fiber.Ctx) error {
if shuttingDown.Load() {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "service is shutting down")
}
if err := h.store.Ping(c.Context()); err != nil {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "database unavailable")
}
if err := h.sessions.Ping(c.Context()); err != nil {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
if err := h.objects.Ping(c.Context()); err != nil {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "object storage unavailable")
}
return c.JSON(Status{Status: "ok"})
}
+82
View File
@@ -0,0 +1,82 @@
// Package messages implements message creation with idempotency and message
// history pagination.
package messages
import (
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
type Handler struct {
store *store.Store
jsonBodyLimit int64
}
func NewHandler(st *store.Store, jsonBodyLimit int64) *Handler {
return &Handler{store: st, jsonBodyLimit: jsonBodyLimit}
}
type CreateMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
}
func (h *Handler) CreateMessage(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
idempotencyKey := c.Get("Idempotency-Key")
if err := common.ValidateIdempotencyKey(idempotencyKey); err != nil {
return err
}
var req CreateMessageRequest
if err := common.BindJSON(c, &req, h.jsonBodyLimit); err != nil {
return err
}
if err := common.ValidateAttachmentIDs(req.AttachmentIDs); err != nil {
return err
}
if err := common.ValidateMessageText(req.Text, len(req.AttachmentIDs)); err != nil {
return err
}
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey, req.AttachmentIDs)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).JSON(message)
}
func (h *Handler) ListMessages(c fiber.Ctx) error {
userID := common.MustUserID(c)
chatID, err := common.PathUUID(c, "chat_id")
if err != nil {
return err
}
limit, err := common.ParseLimit(c, 50)
if err != nil {
return err
}
cursor, err := common.ParseCursor(c)
if err != nil {
return err
}
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
if err != nil {
return err
}
return c.JSON(page)
}
+80
View File
@@ -0,0 +1,80 @@
// Package model defines the JSON-facing domain types shared by handlers,
// storage and the public contract.
package model
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
PasswordHash string `json:"-"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
func (u User) GetID() uuid.UUID { return u.ID }
func (u User) GetCreatedAt() time.Time { return time.Time(u.CreatedAt) }
type Chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
func (c Chat) GetID() uuid.UUID { return c.ID }
func (c Chat) GetCreatedAt() time.Time { return time.Time(c.CreatedAt) }
type Message struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
SenderID uuid.UUID `json:"sender_id"`
Text string `json:"text"`
CreatedAt common.RFCFormTime `json:"created_at"`
AttachmentIDs []uuid.UUID `json:"attachment_ids"`
}
func (m Message) GetID() uuid.UUID { return m.ID }
func (m Message) GetCreatedAt() time.Time { return time.Time(m.CreatedAt) }
type Attachment struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
OwnerID uuid.UUID `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []Variant `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt common.RFCFormTime `json:"created_at"`
UpdatedAt common.RFCFormTime `json:"updated_at"`
// ObjectKey is internal and never serialized.
ObjectKey string `json:"-"`
}
func (a Attachment) GetID() uuid.UUID { return a.ID }
func (a Attachment) GetCreatedAt() time.Time { return time.Time(a.CreatedAt) }
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt common.RFCFormTime `json:"expires_at"`
User User `json:"user"`
}
+176
View File
@@ -0,0 +1,176 @@
// Package objectstore is the only place that knows how to talk to the private S3
// bucket. PostgreSQL remains the source of truth for metadata; this package
// stores and returns opaque bytes only.
package objectstore
import (
"context"
"errors"
"io"
"net/http"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/smithy-go"
)
var ErrNotFound = errors.New("object not found")
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
}
type Client struct {
s3 *s3.Client
bucket string
}
// Object describes one key returned by List. It intentionally exposes only the
// fields the reconciler needs.
type Object struct {
Key string
Size int64
LastModified time.Time
}
func New(cfg Config) (*Client, error) {
awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),
awsconfig.WithRegion(cfg.Region),
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
cfg.AccessKey, cfg.SecretKey, "")),
)
if err != nil {
return nil, err
}
// AGENT: a bounded retry count keeps a broken S3 dependency from turning an
// HTTP upload into an unbounded wait. Context deadlines in the handlers set
// the overall request budget.
awsCfg.RetryMaxAttempts = 2
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConnsPerHost = 20
transport.MaxIdleConns = 40
client := s3.NewFromConfig(awsCfg, func(options *s3.Options) {
// RustFS is addressed by its Compose service name, so virtual-host
// addressing cannot work without extra DNS entries. Path-style is the
// portable choice for every S3-compatible server used in this stand.
options.UsePathStyle = true
options.BaseEndpoint = aws.String(strings.TrimRight(cfg.Endpoint, "/"))
options.HTTPClient = &http.Client{Transport: transport}
})
return &Client{s3: client, bucket: cfg.Bucket}, nil
}
func (c *Client) Bucket() string { return c.bucket }
// Ping is used by /health/ready. HeadBucket is the cheapest authenticated call
// that proves both the endpoint and the scoped credentials work.
func (c *Client) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
_, err := c.s3.HeadBucket(pingCtx, &s3.HeadBucketInput{Bucket: aws.String(c.bucket)})
return mapError(err)
}
func (c *Client) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
_, err := c.s3.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
Body: body,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
return mapError(err)
}
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) {
output, err := c.s3.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
})
if err != nil {
return nil, 0, mapError(err)
}
size := int64(0)
if output.ContentLength != nil {
size = *output.ContentLength
}
return output.Body, size, nil
}
func (c *Client) Delete(ctx context.Context, key string) error {
_, err := c.s3.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(c.bucket),
Key: aws.String(key),
})
return mapError(err)
}
func (c *Client) List(ctx context.Context, prefix string) ([]Object, error) {
var objects []Object
var continuation *string
for {
output, err := c.s3.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(c.bucket),
Prefix: aws.String(prefix),
ContinuationToken: continuation,
})
if err != nil {
return nil, mapError(err)
}
for _, item := range output.Contents {
if item.Key == nil {
continue
}
object := Object{Key: *item.Key}
if item.Size != nil {
object.Size = *item.Size
}
if item.LastModified != nil {
object.LastModified = *item.LastModified
}
objects = append(objects, object)
}
if output.IsTruncated == nil || !*output.IsTruncated {
return objects, nil
}
continuation = output.NextContinuationToken
if continuation == nil {
return objects, nil
}
}
}
// mapError turns a missing object into a sentinel the HTTP layer can map to
// 404, while every other failure stays a dependency error (503).
func mapError(err error) error {
if err == nil {
return nil
}
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NoSuchKey", "NoSuchBucket", "NotFound", "XMinioInvalidObjectName":
return ErrNotFound
}
}
return err
}
+115
View File
@@ -0,0 +1,115 @@
// Package reconcile repairs the two failure windows between PostgreSQL
// metadata and S3 bytes:
//
// - a pending metadata row whose upload never finished or whose 201 was
// never returned;
// - an S3 object whose metadata transaction never committed.
//
// Both repairs use a grace period so an upload that is still in flight is
// never touched.
package reconcile
import (
"context"
"errors"
"log/slog"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/objectstore"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
)
const objectPrefix = "attachments/"
type Reconciler struct {
store *store.Store
objects *objectstore.Client
grace time.Duration
logger *slog.Logger
}
type Stats struct {
StalePending int `json:"stale_pending"`
OrphanObjects int `json:"orphan_objects"`
DeletedRows int `json:"deleted_rows"`
DeletedObjects int `json:"deleted_objects"`
Skipped int `json:"skipped"`
}
func New(st *store.Store, objects *objectstore.Client, grace time.Duration, logger *slog.Logger) *Reconciler {
if logger == nil {
logger = slog.Default()
}
return &Reconciler{store: st, objects: objects, grace: grace, logger: logger}
}
func (r *Reconciler) RunOnce(ctx context.Context, dryRun bool) (Stats, error) {
var stats Stats
cutoff := time.Now().UTC().Add(-r.grace)
// Phase 1: rows that were committed as pending but never reached ready.
stale, err := r.store.ListStalePendingAttachments(ctx, cutoff, 500)
if err != nil {
return stats, err
}
for _, attachment := range stale {
stats.StalePending++
if dryRun {
r.logger.Info("reconcile: would remove stale pending attachment",
"attachment_id", attachment.ID, "object_key", attachment.ObjectKey,
"created_at", attachment.CreatedAt)
continue
}
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil && !errors.Is(err, objectstore.ErrNotFound) {
// Keep the row for the next pass. Deleting it now would lose the
// only pointer to an object that might still exist.
r.logger.Error("reconcile: delete stale object",
"err", err, "attachment_id", attachment.ID)
stats.Skipped++
continue
}
if err = r.store.DeletePendingAttachment(ctx, attachment.ID); err != nil {
r.logger.Error("reconcile: delete stale row", "err", err, "attachment_id", attachment.ID)
stats.Skipped++
continue
}
stats.DeletedRows++
stats.DeletedObjects++
}
// Phase 2: objects with no metadata row at all. The pending row is written
// before the PUT in the normal path, so this only happens after a crash in
// a narrow window (or manual bucket tampering).
listed, err := r.objects.List(ctx, objectPrefix)
if err != nil {
return stats, err
}
known, err := r.store.ListAttachmentObjectKeys(ctx)
if err != nil {
return stats, err
}
for _, object := range listed {
if _, ok := known[object.Key]; ok {
continue
}
// A missing LastModified must not be treated as ancient: skipping is
// safer than deleting an object that may have just been created.
if object.LastModified.IsZero() || object.LastModified.After(cutoff) {
continue
}
stats.OrphanObjects++
if dryRun {
r.logger.Info("reconcile: would delete orphan object", "object_key", object.Key)
continue
}
if err = r.objects.Delete(ctx, object.Key); err != nil && !errors.Is(err, objectstore.ErrNotFound) {
r.logger.Error("reconcile: delete orphan object", "err", err, "object_key", object.Key)
stats.Skipped++
continue
}
stats.DeletedObjects++
}
return stats, nil
}
+103
View File
@@ -0,0 +1,103 @@
// Package session stores bearer sessions in Redis. Tokens are hashed before
// they become keys, and the configured TTL is absolute.
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
var ErrNotFound = errors.New("session not found")
const keyPrefix = "messenger:session:"
type Store struct {
client *redis.Client
ttl time.Duration
timeout time.Duration
}
func New(rawURL string, ttl, timeout time.Duration) (*Store, error) {
options, err := redis.ParseURL(rawURL)
if err != nil {
return nil, fmt.Errorf("parse CACHE_URL: %w", err)
}
options.PoolSize = 10
options.DialTimeout = timeout
options.ReadTimeout = timeout
options.WriteTimeout = timeout
options.MaxRetries = 0
return &Store{
client: redis.NewClient(options),
ttl: ttl,
timeout: timeout,
}, nil
}
func (s *Store) Close() error {
return s.client.Close()
}
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Ping(pingCtx).Err()
}
func (s *Store) Create(ctx context.Context, userID uuid.UUID) (string, time.Time, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", time.Time{}, fmt.Errorf("generate token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
expiresAt := time.Now().UTC().Add(s.ttl)
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
if err := s.client.Set(opCtx, keyFor(token), userID.String(), s.ttl).Err(); err != nil {
return "", time.Time{}, err
}
return token, expiresAt, nil
}
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
value, err := s.client.Get(opCtx, keyFor(token)).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, ErrNotFound
}
if err != nil {
return uuid.Nil, err
}
userID, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, ErrNotFound
}
return userID, nil
}
func (s *Store) Revoke(ctx context.Context, token string) error {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Del(opCtx, keyFor(token)).Err()
}
func keyFor(token string) string {
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
return keyPrefix + hex.EncodeToString(sum[:])
}
+170
View File
@@ -0,0 +1,170 @@
package store
import (
"context"
"encoding/hex"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// CreatePendingAttachment records the intent to store an object before the S3
// PUT happens. Committing this row first is what makes the reconciler able to
// distinguish "never uploaded" from "uploaded but process died".
func (s *Store) CreatePendingAttachment(ctx context.Context, att model.Attachment) error {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
hash, err := hex.DecodeString(att.SHA256)
if err != nil {
return common.BadRequest("invalid sha256")
}
_, err = s.pool.Exec(ctx, `
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
object_key, status, error_code, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL, $9, $9)`,
att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes,
hash, att.ObjectKey, time.Time(att.CreatedAt))
return dbError(err)
}
// MarkAttachmentReady publishes metadata only after the object bytes are known
// to be in S3. A 201 is therefore a promise about both stores.
func (s *Store) MarkAttachmentReady(ctx context.Context, id uuid.UUID) (time.Time, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
updatedAt := time.Now().UTC()
tag, err := s.pool.Exec(ctx, `
UPDATE attachments
SET status = 'ready', updated_at = $2
WHERE id = $1 AND status = 'pending'`, id, updatedAt)
if err != nil {
return time.Time{}, dbError(err)
}
if tag.RowsAffected() == 0 {
return time.Time{}, common.Conflict("attachment is not pending")
}
return updatedAt, nil
}
// DeletePendingAttachment removes a row only while it is still pending. The
// status guard is the safety property: if an upload completed concurrently, the
// compensation or reconciler pass must not delete a ready attachment.
func (s *Store) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(ctx,
`DELETE FROM attachments WHERE id = $1 AND status = 'pending'`, id)
return dbError(err)
}
func (s *Store) GetAttachmentForUser(ctx context.Context, userID, attachmentID uuid.UUID) (model.Attachment, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
att, err := scanAttachment(s.pool.QueryRow(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code,
a.created_at, a.updated_at, a.object_key
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
WHERE a.id = $1`, attachmentID, userID))
if err != nil {
return model.Attachment{}, err
}
return att, nil
}
// ListStalePendingAttachments is the entry point for crash recovery. cutoff is
// an instant, not a duration: rows created before it are eligible. The caller
// computes it as now - grace so the boundary can be tuned and tested.
func (s *Store) ListStalePendingAttachments(ctx context.Context, cutoff time.Time, limit int) ([]model.Attachment, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(ctx, `
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.status, a.error_code,
a.created_at, a.updated_at, a.object_key
FROM attachments a
WHERE a.status = 'pending' AND a.created_at < $1
ORDER BY a.created_at
LIMIT $2`, cutoff, limit)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
var result []model.Attachment
for rows.Next() {
att, scanErr := scanAttachment(rows)
if scanErr != nil {
return nil, dbError(scanErr)
}
result = append(result, att)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
return result, nil
}
func (s *Store) ListAttachmentObjectKeys(ctx context.Context) (map[string]struct{}, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(ctx, `SELECT object_key FROM attachments`)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
keys := make(map[string]struct{})
for rows.Next() {
var key string
if err = rows.Scan(&key); err != nil {
return nil, dbError(err)
}
keys[key] = struct{}{}
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
return keys, nil
}
func scanAttachment(row rowScanner) (model.Attachment, error) {
var (
att model.Attachment
hash []byte
errCode *string
createdAt time.Time
updatedAt time.Time
)
if err := row.Scan(
&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType,
&att.SizeBytes, &hash, &att.Status, &errCode,
&createdAt, &updatedAt, &att.ObjectKey,
); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Attachment{}, common.NotFound("attachment not found")
}
return model.Attachment{}, dbError(err)
}
att.SHA256 = hex.EncodeToString(hash)
att.ErrorCode = errCode
att.Variants = []model.Variant{}
att.CreatedAt = common.RFCFormTime(createdAt.UTC())
att.UpdatedAt = common.RFCFormTime(updatedAt.UTC())
return att, nil
}
+142
View File
@@ -0,0 +1,142 @@
package store
import (
"context"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, dbError(err)
}
defer rollback(tx)
var existing int
if err = tx.QueryRow(ctx,
`SELECT count(*) FROM users WHERE id = ANY($1::uuid[])`,
memberIDs).Scan(&existing); err != nil {
return model.Chat{}, dbError(err)
}
if existing != len(memberIDs) {
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
}
chat := model.Chat{
ID: uuid.New(),
Title: title,
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
CreatedAt: common.NowUTC(),
}
if _, err = tx.Exec(ctx,
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil {
return model.Chat{}, dbError(err)
}
for _, memberID := range memberIDs {
if _, err = tx.Exec(ctx,
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
chat.ID, memberID); err != nil {
return model.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return model.Chat{}, dbError(err)
}
return chat, nil
}
func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return scanChat(s.pool.QueryRow(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
WHERE c.id = $1`, chatID, userID))
}
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
cursorTime, cursorID := cursorValues(cursor)
rows, err := s.pool.Query(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
WHERE (c.created_at, c.id) > ($2, $3)
ORDER BY c.created_at, c.id
LIMIT $4`, userID, cursorTime, cursorID, limit+1)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]model.Chat, 0, limit)
for rows.Next() {
chat, scanErr := scanChat(rows)
if scanErr != nil {
return nil, scanErr
}
chats = append(chats, chat)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
hasMore := len(chats) > limit
if hasMore {
chats = chats[:limit]
}
return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil
}
func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
var exists int
err := s.pool.QueryRow(ctx,
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
chatID, userID).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, dbError(err)
}
return true, nil
}
// scanChat owns the "row is missing" meaning for single-row lookups; list
// queries never see ErrNoRows.
func scanChat(row rowScanner) (model.Chat, error) {
var chat model.Chat
var createdAt time.Time
if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.NotFound("chat not found")
}
return model.Chat{}, dbError(err)
}
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
return chat, nil
}
+44
View File
@@ -0,0 +1,44 @@
package store
import (
"context"
"errors"
"log/slog"
"net"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func isUniqueViolation(err error) bool {
pgErr, ok := errors.AsType[*pgconn.PgError](err)
return ok && pgErr.Code == "23505"
}
// dbError maps driver failures to contract errors. Unexpected failures are
// logged with their cause so a 500 is never silent.
func dbError(err error) error {
if err == nil {
return nil
}
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
switch pgErr.Code {
case "23505":
return common.Conflict("resource already exists")
case "23503", "23514", "22P02":
return common.BadRequest("request conflicts with stored data")
}
}
if _, ok := errors.AsType[net.Error](err); ok || errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, context.Canceled) ||
pgconn.SafeToRetry(err) ||
errors.Is(err, pgx.ErrTxClosed) {
return common.Unavailable("database unavailable")
}
slog.Error("unhandled database error", "err", err)
return common.Internal()
}
+285
View File
@@ -0,0 +1,285 @@
package store
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"sort"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string, attachmentIDs []uuid.UUID) (model.Message, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
// Sorting makes the idempotency fingerprint independent of the order
// in which the client listed the same set of attachment IDs. The response
// uses the same deterministic order.
attachmentIDs = canonicalAttachmentIDs(attachmentIDs)
fingerprint := messageFingerprint(text, attachmentIDs)
if message, found, err := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint); err != nil {
return model.Message{}, err
} else if found {
return message, nil
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: common.NowUTC(),
AttachmentIDs: attachmentIDs,
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, dbError(err)
}
defer rollback(tx)
// Check membership and attachment ownership in the same transaction as the
// insert. A foreign chat or a foreign attachment is intentionally the same
// 404 as a missing object, so the API does not leak existence.
var member int
err = tx.QueryRow(ctx,
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
chatID, senderID).Scan(&member)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, common.NotFound("chat not found")
}
if err != nil {
return model.Message{}, dbError(err)
}
if len(attachmentIDs) > 0 {
rows, queryErr := tx.Query(ctx, `
SELECT id, status FROM attachments
WHERE chat_id = $1 AND id = ANY($2::uuid[])`, chatID, attachmentIDs)
if queryErr != nil {
return model.Message{}, dbError(queryErr)
}
found := 0
for rows.Next() {
var (
id uuid.UUID
status string
)
if scanErr := rows.Scan(&id, &status); scanErr != nil {
rows.Close()
return model.Message{}, dbError(scanErr)
}
found++
if status != "ready" {
rows.Close()
return model.Message{}, common.Conflict("attachment is not ready")
}
}
if err = rows.Err(); err != nil {
rows.Close()
return model.Message{}, dbError(err)
}
rows.Close()
if found != len(attachmentIDs) {
return model.Message{}, common.NotFound("attachment not found")
}
}
_, 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, time.Time(message.CreatedAt))
if err != nil {
return model.Message{}, dbError(err)
}
for position, attachmentID := range attachmentIDs {
if _, err = tx.Exec(ctx, `
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES ($1, $2, $3)`, message.ID, attachmentID, position); err != nil {
return model.Message{}, dbError(err)
}
}
expiresAt := time.Time(message.CreatedAt).Add(s.idempotencyTTL)
tag, err := tx.Exec(ctx, `
INSERT INTO message_idempotency
(sender_id, chat_id, idempotency_key, request_hash, message_id, created_at, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
SET request_hash = EXCLUDED.request_hash,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at,
expires_at = EXCLUDED.expires_at
WHERE message_idempotency.expires_at <= now()`,
senderID, chatID, idempotencyKey, fingerprint, message.ID,
time.Time(message.CreatedAt), expiresAt)
if err != nil {
return model.Message{}, dbError(err)
}
if tag.RowsAffected() == 0 {
rollback(tx)
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint)
if lookupErr != nil {
return model.Message{}, lookupErr
}
if !found {
return model.Message{}, common.Internal()
}
return stored, nil
}
if err = tx.Commit(ctx); err != nil {
return model.Message{}, dbError(err)
}
return message, nil
}
func canonicalAttachmentIDs(ids []uuid.UUID) []uuid.UUID {
result := append([]uuid.UUID(nil), ids...)
sort.Slice(result, func(i, j int) bool {
return bytes.Compare(result[i][:], result[j][:]) < 0
})
if result == nil {
return []uuid.UUID{}
}
return result
}
// messageFingerprint keeps the lab3 hash for messages without attachments, so
// an idempotency key stored before this migration still replays correctly. For
// messages with attachments the sorted IDs are part of the canonical body.
func messageFingerprint(text string, attachmentIDs []uuid.UUID) []byte {
if len(attachmentIDs) == 0 {
sum := sha256.Sum256([]byte(text))
return sum[:]
}
hash := sha256.New()
hash.Write([]byte(text))
hash.Write([]byte{0})
for _, id := range attachmentIDs {
hash.Write(id[:])
}
return hash.Sum(nil)
}
func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid.UUID, idempotencyKey string, expectedHash []byte) (model.Message, bool, error) {
var message model.Message
var createdAt time.Time
var storedHash []byte
err := s.pool.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT ma.attachment_id
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position),
i.request_hash
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
JOIN chat_members cm ON cm.chat_id = i.chat_id AND cm.user_id = i.sender_id
WHERE i.sender_id = $1
AND i.chat_id = $2
AND i.idempotency_key = $3
AND i.expires_at > now()`,
senderID, chatID, idempotencyKey).Scan(
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt,
&message.AttachmentIDs, &storedHash)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, false, nil
}
if err != nil {
return model.Message{}, false, dbError(err)
}
if !bytes.Equal(storedHash, expectedHash) {
return model.Message{}, false, common.Conflict("idempotency key reused with a different message")
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []uuid.UUID{}
}
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
return message, true, nil
}
func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
isMember, err := s.IsMember(ctx, userID, chatID)
if err != nil {
return nil, err
}
if !isMember {
return nil, common.NotFound("chat not found")
}
// AGENT: Cursor context is checked only after membership, so a foreign
// caller gets 404 and cannot probe cursor validity against someone else's chat.
if cursor != nil && cursor.ContextID != chatID {
return nil, common.BadRequest("bad cursor value")
}
cursorTime, cursorID := cursorValues(cursor)
rows, err := s.pool.Query(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
ARRAY(SELECT ma.attachment_id
FROM message_attachments ma
WHERE ma.message_id = m.id
ORDER BY ma.position)
FROM messages m
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
ORDER BY m.created_at, m.id
LIMIT $4`, chatID, cursorTime, cursorID, limit+1)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
messages := make([]model.Message, 0, limit)
for rows.Next() {
message, scanErr := scanMessage(rows)
if scanErr != nil {
return nil, dbError(scanErr)
}
messages = append(messages, message)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
hasMore := len(messages) > limit
if hasMore {
messages = messages[:limit]
}
return &common.Page[model.Message]{
Items: messages,
NextCursor: common.NextCursor(messages, hasMore, chatID),
}, nil
}
func scanMessage(row rowScanner) (model.Message, error) {
var message model.Message
var createdAt time.Time
if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text,
&createdAt, &message.AttachmentIDs); err != nil {
return model.Message{}, err
}
if message.AttachmentIDs == nil {
message.AttachmentIDs = []uuid.UUID{}
}
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
return message, nil
}
+80
View File
@@ -0,0 +1,80 @@
package store
import (
"bytes"
"crypto/sha256"
"testing"
"github.com/google/uuid"
)
func TestCanonicalAttachmentIDsSortsAndCopies(t *testing.T) {
first, second, third := uuid.MustParse("00000000-0000-0000-0000-000000000003"),
uuid.MustParse("00000000-0000-0000-0000-000000000001"),
uuid.MustParse("00000000-0000-0000-0000-000000000002")
input := []uuid.UUID{first, second, third}
got := canonicalAttachmentIDs(input)
want := []uuid.UUID{second, third, first}
if !equalIDs(got, want) {
t.Fatalf("canonicalAttachmentIDs = %v, want %v", got, want)
}
if !equalIDs(input, []uuid.UUID{first, second, third}) {
t.Fatalf("canonicalAttachmentIDs mutated its input: %v", input)
}
}
func TestCanonicalAttachmentIDsReturnsEmptySliceForNil(t *testing.T) {
got := canonicalAttachmentIDs(nil)
if got == nil {
t.Fatal("canonicalAttachmentIDs(nil) = nil, want empty slice")
}
if len(got) != 0 {
t.Fatalf("canonicalAttachmentIDs(nil) = %v, want empty", got)
}
}
// TestMessageFingerprintWithoutAttachmentsPreservesLab3Hash is the
// compatibility guard: idempotency rows written before attachments existed
// must still match on replay.
func TestMessageFingerprintWithoutAttachmentsPreservesLab3Hash(t *testing.T) {
expected := sha256.Sum256([]byte("hello"))
if got := messageFingerprint("hello", nil); !bytes.Equal(got, expected[:]) {
t.Fatalf("fingerprint = %x, want %x", got, expected)
}
if got := messageFingerprint("hello", []uuid.UUID{}); !bytes.Equal(got, expected[:]) {
t.Fatalf("empty slice fingerprint = %x, want %x", got, expected)
}
}
func TestMessageFingerprintDependsOnSortedAttachments(t *testing.T) {
first := uuid.MustParse("00000000-0000-0000-0000-000000000001")
second := uuid.MustParse("00000000-0000-0000-0000-000000000002")
// CreateMessage canonicalizes before hashing; the pair must therefore be
// order independent even though messageFingerprint itself takes the list
// as given.
one := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{first, second}))
reordered := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{second, first}))
if !bytes.Equal(one, reordered) {
t.Fatal("fingerprint depends on attachment order")
}
other := messageFingerprint("hello", canonicalAttachmentIDs([]uuid.UUID{first}))
if bytes.Equal(one, other) {
t.Fatal("fingerprint ignores attachment identity")
}
}
func equalIDs(a, b []uuid.UUID) bool {
if len(a) != len(b) {
return false
}
for index := range a {
if a[index] != b[index] {
return false
}
}
return true
}
+17
View File
@@ -0,0 +1,17 @@
package store
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/google/uuid"
)
// cursorValues converts an optional page cursor to the two keyset columns used
// by every paginated query. A nil cursor means "start from the beginning".
func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) {
if cursor == nil {
return time.Time{}, uuid.Nil
}
return cursor.Time, cursor.ID
}
+36
View File
@@ -0,0 +1,36 @@
// Package store contains the PostgreSQL persistence layer. It uses plain
// parameterized SQL, one bounded pool and explicit transaction boundaries.
// Contract errors are returned as common.AppError so HTTP status mapping stays
// in one place.
package store
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type Store struct {
pool *pgxpool.Pool
timeout time.Duration
idempotencyTTL time.Duration
}
func New(pool *pgxpool.Pool, timeout, idempotencyTTL time.Duration) *Store {
return &Store{pool: pool, timeout: timeout, idempotencyTTL: idempotencyTTL}
}
func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.timeout)
}
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
return s.pool.Ping(pingCtx)
}
type rowScanner interface {
Scan(dest ...any) error
}
+16
View File
@@ -0,0 +1,16 @@
package store
import (
"context"
"time"
"github.com/jackc/pgx/v5"
)
const rollbackTimeout = 5 * time.Second
func rollback(tx pgx.Tx) {
ctx, cancel := context.WithTimeout(context.Background(), rollbackTimeout)
defer cancel()
_ = tx.Rollback(ctx)
}
+69
View File
@@ -0,0 +1,69 @@
package store
import (
"context"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
user := model.User{
ID: uuid.New(),
Username: username,
DisplayName: displayName,
PasswordHash: passwordHash,
CreatedAt: common.NowUTC(),
}
_, err := s.pool.Exec(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)`,
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
if err != nil {
if isUniqueViolation(err) {
return model.User{}, common.Conflict("username already taken")
}
return model.User{}, dbError(err)
}
return user, nil
}
func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return s.scanUser(s.pool.QueryRow(ctx, `
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE id = $1`, id))
}
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return s.scanUser(s.pool.QueryRow(ctx, `
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username))
}
func (s *Store) scanUser(row rowScanner) (model.User, error) {
var user model.User
var createdAt time.Time
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, common.NotFound("user not found")
}
return model.User{}, dbError(err)
}
user.CreatedAt = common.RFCFormTime(createdAt.UTC())
return user, nil
}
+62
View File
@@ -0,0 +1,62 @@
// Package users implements registration and the current-user endpoint.
package users
import (
"log/slog"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
type Handler struct {
store *store.Store
jsonBodyLimit int64
}
func NewHandler(st *store.Store, jsonBodyLimit int64) *Handler {
return &Handler{store: st, jsonBodyLimit: jsonBodyLimit}
}
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
func (h *Handler) CreateUser(c fiber.Ctx) error {
var req CreateUserRequest
if err := common.BindJSON(c, &req, h.jsonBodyLimit); err != nil {
return err
}
if err := common.ValidateCreateUser(req.Username, req.DisplayName); err != nil {
return err
}
if err := common.ValidatePassword(req.Password); err != nil {
return err
}
hash, err := auth.HashPassword(req.Password)
if err != nil {
slog.Error("hash password", "err", err)
return common.Internal()
}
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
if err != nil {
return err
}
return c.Status(fiber.StatusCreated).JSON(user)
}
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
user, err := h.store.GetUserByID(c.Context(), common.MustUserID(c))
if err != nil {
return err
}
return c.JSON(user)
}