ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/auth"
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
"mtusi.ru/messenger-lab4/internal/session"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// identity is the authenticated principal derived only from the Bearer
|
||||
// session. X-User-Id is not consulted anywhere in this package.
|
||||
type identity struct {
|
||||
user model.User
|
||||
token string
|
||||
}
|
||||
|
||||
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
|
||||
// and messages; Valkey is the source of truth for sessions. App adds request
|
||||
// validation, authentication and contract mapping.
|
||||
type App struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
objects *objectstore.Store
|
||||
log *slog.Logger
|
||||
ready atomic.Bool
|
||||
maxBody int64
|
||||
instanceID string
|
||||
version string
|
||||
startedAt time.Time
|
||||
dummyHash string
|
||||
|
||||
maxUpload int64
|
||||
maxPixels int64
|
||||
tempDir string
|
||||
decodeSem chan struct{}
|
||||
putSem chan struct{}
|
||||
|
||||
createdMessages atomic.Uint64
|
||||
replayedMessages atomic.Uint64
|
||||
conflictMessages atomic.Uint64
|
||||
}
|
||||
|
||||
// Options carries the upload limits and concurrency bound. Values are
|
||||
// validated by config.Load before the application starts.
|
||||
type Options struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
DecodeConcurrency int
|
||||
PutConcurrency int
|
||||
TempDir string
|
||||
}
|
||||
|
||||
// New creates the HTTP application. The dummy Argon2id hash is generated once
|
||||
// so login can spend the same work for an unknown username as for a known one.
|
||||
func New(repository *store.Store, sessions *session.Store, objects *objectstore.Store, logger *slog.Logger, instanceID, version string, options Options) (*App, error) {
|
||||
dummy, err := auth.Hash("dummy-password-never-used-for-login")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if options.MaxUploadBytes <= 0 {
|
||||
options.MaxUploadBytes = 10 * 1024 * 1024
|
||||
}
|
||||
if options.MaxImagePixels <= 0 {
|
||||
options.MaxImagePixels = 40_000_000
|
||||
}
|
||||
if options.DecodeConcurrency <= 0 {
|
||||
options.DecodeConcurrency = 1
|
||||
}
|
||||
if options.PutConcurrency <= 0 {
|
||||
options.PutConcurrency = 1
|
||||
}
|
||||
app := &App{
|
||||
store: repository,
|
||||
sessions: sessions,
|
||||
objects: objects,
|
||||
log: logger,
|
||||
maxBody: maxBodyBytes,
|
||||
instanceID: instanceID,
|
||||
version: version,
|
||||
startedAt: time.Now(),
|
||||
dummyHash: dummy,
|
||||
maxUpload: options.MaxUploadBytes,
|
||||
maxPixels: options.MaxImagePixels,
|
||||
tempDir: options.TempDir,
|
||||
decodeSem: make(chan struct{}, options.DecodeConcurrency),
|
||||
putSem: make(chan struct{}, options.PutConcurrency),
|
||||
}
|
||||
app.ready.Store(true)
|
||||
return app, nil
|
||||
}
|
||||
|
||||
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
|
||||
// received and before http.Server.Shutdown stops accepting connections.
|
||||
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
|
||||
|
||||
// Handler returns the fully instrumented handler.
|
||||
func (a *App) Handler() http.Handler {
|
||||
return a.withObservability(a)
|
||||
}
|
||||
|
||||
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
|
||||
// error shape because the public error enum has no method_not_allowed code.
|
||||
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/health/live":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
case "/health/ready":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.readiness(w, r)
|
||||
case "/api/v1/users":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createUser(w, r)
|
||||
case "/api/v1/auth/sessions":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createSession(w, r)
|
||||
case "/api/v1/auth/sessions/current":
|
||||
if r.Method != http.MethodDelete {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.logout).ServeHTTP(w, r)
|
||||
case "/api/v1/users/me":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.currentUser).ServeHTTP(w, r)
|
||||
case "/api/v1/chats":
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.withAuth(a.listChats).ServeHTTP(w, r)
|
||||
case http.MethodPost:
|
||||
a.withAuth(a.createChat).ServeHTTP(w, r)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
default:
|
||||
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/attachments/"); ok {
|
||||
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.attachmentRoutes(w, r, rest, actor)
|
||||
}).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
|
||||
// Authentication runs before resource resolution: an anonymous
|
||||
// request must not learn whether a chat id exists.
|
||||
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.chatRoutes(w, r, rest, actor)
|
||||
}).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
||||
parts := splitPath(rest)
|
||||
if len(parts) == 1 {
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.getChat(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "attachments" {
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createAttachment(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "messages" {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.listMessages(w, r, parts[0], actor)
|
||||
case http.MethodPost:
|
||||
a.createMessage(w, r, parts[0], actor)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
|
||||
// withAuth resolves the Bearer session before the wrapped handler runs.
|
||||
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, problem := a.authenticate(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
next(w, r, actor)
|
||||
}
|
||||
}
|
||||
|
||||
// readiness reports whether the mandatory synchronous path can be served.
|
||||
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
|
||||
// answer, and without Valkey it cannot authenticate a single protected call.
|
||||
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.ready.Load() {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
dbErr := a.store.Ping(dbCtx)
|
||||
dbCancel()
|
||||
if dbErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
cacheErr := a.sessions.Ping(cacheCtx)
|
||||
cacheCancel()
|
||||
if cacheErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// writeJSON encodes a success response. X-Request-Id is set by middleware
|
||||
// before the handler runs, so even a marshal-time 500 keeps the header.
|
||||
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if _, err := w.Write(data); err != nil {
|
||||
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func trimPathPrefix(value, prefix string) (string, bool) {
|
||||
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
|
||||
return "", false
|
||||
}
|
||||
return value[len(prefix):], true
|
||||
}
|
||||
|
||||
func splitPath(value string) []string {
|
||||
parts := strings.Split(value, "/")
|
||||
for _, part := range parts {
|
||||
if part == "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg" // register the JPEG decoder used by image.DecodeConfig/Decode
|
||||
_ "image/png" // register the PNG decoder used by image.DecodeConfig/Decode
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/objectstore"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
objectPrefix = "attachments/"
|
||||
decodeWaitTimeout = 30 * time.Second
|
||||
putWaitTimeout = 10 * time.Second
|
||||
maxFilenameCodePoints = 255
|
||||
imagePNG = "image/png"
|
||||
imageJPEG = "image/jpeg"
|
||||
attachmentStateReady = "ready"
|
||||
attachmentStatePending = "pending"
|
||||
maxImageDimensionProduct = int64(40_000_000)
|
||||
)
|
||||
|
||||
// attachmentRoutes handles /api/v1/attachments/{id} and .../content. The
|
||||
// caller has already been authenticated by withAuth.
|
||||
func (a *App) attachmentRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
||||
parts := splitPath(rest)
|
||||
if len(parts) == 1 {
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.getAttachment(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "content" {
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.downloadAttachment(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
|
||||
// createAttachment performs a synchronous binary upload. The body is streamed
|
||||
// to a bounded temporary file while its SHA-256 is computed; the image is
|
||||
// validated before any S3 or database write. Only a validated image can create
|
||||
// a pending row, so an invalid request never leaves an accounted object behind.
|
||||
func (a *App) createAttachment(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
filename, problem := uploadFilename(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
declared, problem := uploadMediaType(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
a.log.Error("attachment membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > a.maxUpload {
|
||||
a.writeError(w, r, statusPayloadTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
temp, err := os.CreateTemp(a.tempDir, "lab4-upload-*")
|
||||
if err != nil {
|
||||
a.log.Error("could not create upload temp file", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
tempName := temp.Name()
|
||||
defer func() {
|
||||
_ = temp.Close()
|
||||
_ = os.Remove(tempName)
|
||||
}()
|
||||
|
||||
hasher := sha256.New()
|
||||
body := http.MaxBytesReader(w, r.Body, a.maxUpload)
|
||||
written, err := io.Copy(io.MultiWriter(temp, hasher), body)
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
switch {
|
||||
case errors.As(err, &tooLarge):
|
||||
a.writeError(w, r, statusPayloadTooLarge)
|
||||
case errors.Is(err, syscall.ENOSPC):
|
||||
a.log.Error("upload temp file is full", "request_id", requestIDFromContext(r.Context()))
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
default:
|
||||
a.writeError(w, r, invalidRequest("could not read the upload body"))
|
||||
}
|
||||
return
|
||||
}
|
||||
if written > a.maxUpload {
|
||||
a.writeError(w, r, statusPayloadTooLarge)
|
||||
return
|
||||
}
|
||||
if written == 0 {
|
||||
a.writeError(w, r, unsupportedMediaType("the upload body is empty"))
|
||||
return
|
||||
}
|
||||
|
||||
detected, width, height, problem := a.validateImage(r.Context(), temp, declared)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
sum := hex.EncodeToString(hasher.Sum(nil))
|
||||
attachmentID := uuid.New()
|
||||
objectKey := objectPrefix + attachmentID
|
||||
createdAt := time.Now().UTC()
|
||||
record := store.AttachmentRecord{
|
||||
Attachment: model.Attachment{
|
||||
ID: attachmentID,
|
||||
ChatID: chatID,
|
||||
OwnerID: actor.user.ID,
|
||||
Filename: filename,
|
||||
ContentType: detected,
|
||||
SizeBytes: written,
|
||||
SHA256: sum,
|
||||
Status: attachmentStatePending,
|
||||
Variants: []model.Variant{},
|
||||
ErrorCode: nil,
|
||||
CreatedAt: model.Time{Time: createdAt},
|
||||
UpdatedAt: model.Time{Time: createdAt},
|
||||
},
|
||||
ObjectKey: objectKey,
|
||||
}
|
||||
|
||||
if err := a.store.CreatePendingAttachment(r.Context(), record, createdAt); err != nil {
|
||||
a.log.Error("could not record attachment intent", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
||||
_ = a.store.DeleteAttachmentRow(context.Background(), attachmentID)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
// Bound the number of simultaneous object writes per API replica. A queued
|
||||
// upload has already been streamed to a bounded temporary file and is not
|
||||
// holding a decoded image, so waiting here does not add unbounded RAM.
|
||||
select {
|
||||
case a.putSem <- struct{}{}:
|
||||
err = a.objects.Put(r.Context(), objectKey, temp, written, detected)
|
||||
<-a.putSem
|
||||
case <-time.After(putWaitTimeout):
|
||||
a.compensatePending(attachmentID)
|
||||
a.log.Warn("S3 upload queue timed out", "request_id", requestIDFromContext(r.Context()),
|
||||
"attachment_id", attachmentID)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case <-r.Context().Done():
|
||||
a.compensatePending(attachmentID)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Compensation for a failed PUT: the pending row is removed. If this
|
||||
// best-effort delete also fails, the reconciler removes the stale row
|
||||
// and any object after the grace period.
|
||||
a.compensatePending(attachmentID)
|
||||
a.log.Error("S3 upload failed", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
||||
if errors.Is(err, objectstore.ErrUnavailable) || errors.Is(err, objectstore.ErrNotFound) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
updatedAt, err := a.store.MarkAttachmentReady(r.Context(), attachmentID, time.Now().UTC())
|
||||
if err != nil {
|
||||
// The object and the pending row are both durable. Never delete the
|
||||
// object here: an ambiguous COMMIT could have promoted the row already,
|
||||
// and deleting a ready original is worse than a reconciler pass.
|
||||
a.log.Error("could not promote attachment after S3 upload", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
record.Status = attachmentStateReady
|
||||
record.UpdatedAt = model.Time{Time: updatedAt}
|
||||
a.log.Info("attachment ready",
|
||||
"request_id", requestIDFromContext(r.Context()),
|
||||
"attachment_id", attachmentID,
|
||||
"chat_id", chatID,
|
||||
"size_bytes", written,
|
||||
"content_type", detected,
|
||||
"image_width", width,
|
||||
"image_height", height,
|
||||
)
|
||||
a.writeJSON(w, r, http.StatusCreated, record.Attachment)
|
||||
}
|
||||
|
||||
// compensatePending removes the upload intent after a failed or abandoned S3
|
||||
// write. A failed best-effort delete is intentionally left to the reconciler:
|
||||
// deleting a possibly committed row here would be worse than a stale pending row.
|
||||
func (a *App) compensatePending(attachmentID string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
_ = a.store.DeleteAttachmentRow(cleanupCtx, attachmentID)
|
||||
cancel()
|
||||
}
|
||||
|
||||
// validateImage applies every content rule before S3 or PostgreSQL is touched.
|
||||
// The declared media type must match the bytes; the decoded pixel count is
|
||||
// checked from the header before a potentially large full decode.
|
||||
func (a *App) validateImage(ctx context.Context, temp *os.File, declared string) (detected string, width, height int, problem *apiError) {
|
||||
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
||||
return "", 0, 0, statusInternal
|
||||
}
|
||||
header := make([]byte, 512)
|
||||
n, err := io.ReadFull(temp, header)
|
||||
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return "", 0, 0, unsupportedMediaType("the upload body is not a valid image")
|
||||
}
|
||||
detected = http.DetectContentType(header[:n])
|
||||
if detected != imagePNG && detected != imageJPEG {
|
||||
return "", 0, 0, unsupportedMediaType("only PNG and JPEG images are accepted")
|
||||
}
|
||||
if declared != detected {
|
||||
return "", 0, 0, unsupportedMediaType("Content-Type does not match the image bytes")
|
||||
}
|
||||
|
||||
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
||||
return "", 0, 0, statusInternal
|
||||
}
|
||||
config, format, err := image.DecodeConfig(temp)
|
||||
if err != nil || (format != "png" && format != "jpeg") {
|
||||
return "", 0, 0, unsupportedMediaType("the image header is corrupt or unsupported")
|
||||
}
|
||||
if config.Width < 1 || config.Height < 1 {
|
||||
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
|
||||
}
|
||||
pixels := int64(config.Width) * int64(config.Height)
|
||||
if pixels > a.maxPixels || pixels > maxImageDimensionProduct {
|
||||
return "", 0, 0, statusPayloadTooLarge
|
||||
}
|
||||
|
||||
select {
|
||||
case a.decodeSem <- struct{}{}:
|
||||
defer func() { <-a.decodeSem }()
|
||||
case <-time.After(decodeWaitTimeout):
|
||||
return "", 0, 0, statusUnavailable
|
||||
case <-ctx.Done():
|
||||
return "", 0, 0, statusUnavailable
|
||||
}
|
||||
|
||||
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
||||
return "", 0, 0, statusInternal
|
||||
}
|
||||
decoded, _, err := image.Decode(temp)
|
||||
if err != nil {
|
||||
return "", 0, 0, unsupportedMediaType("the image is corrupt or truncated")
|
||||
}
|
||||
bounds := decoded.Bounds()
|
||||
if bounds.Dx() < 1 || bounds.Dy() < 1 {
|
||||
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
|
||||
}
|
||||
return detected, bounds.Dx(), bounds.Dy(), nil
|
||||
}
|
||||
|
||||
// uploadMediaType parses the declared Content-Type strictly. Parameters are
|
||||
// accepted; any other media type is rejected before the body is read.
|
||||
func uploadMediaType(r *http.Request) (string, *apiError) {
|
||||
raw := strings.TrimSpace(r.Header.Get("Content-Type"))
|
||||
if raw == "" {
|
||||
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
|
||||
}
|
||||
mediaType, _, err := mime.ParseMediaType(raw)
|
||||
if err != nil || (mediaType != imagePNG && mediaType != imageJPEG) {
|
||||
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
|
||||
}
|
||||
return mediaType, nil
|
||||
}
|
||||
|
||||
// uploadFilename validates the display-only filename query parameter. The
|
||||
// value is never used as a path or an object key.
|
||||
func uploadFilename(r *http.Request) (string, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return "", invalidRequest("query string is not valid")
|
||||
}
|
||||
values, present := query["filename"]
|
||||
if !present || len(values) != 1 || values[0] == "" {
|
||||
return "", invalidRequest("filename query parameter is required exactly once")
|
||||
}
|
||||
name := values[0]
|
||||
if !utf8.ValidString(name) {
|
||||
return "", invalidRequest("filename must be valid UTF-8")
|
||||
}
|
||||
if count := utf8.RuneCountInString(name); count < 1 || count > maxFilenameCodePoints {
|
||||
return "", invalidRequest("filename must contain 1 to 255 Unicode code points")
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return "", invalidRequest("filename must not be a path component")
|
||||
}
|
||||
for _, char := range name {
|
||||
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
|
||||
return "", invalidRequest("filename must not contain path separators, NUL or control characters")
|
||||
}
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (a *App) getAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
|
||||
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
default:
|
||||
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The object is the source of truth for existence. A row whose bytes are
|
||||
// gone must not be presented as a ready attachment.
|
||||
if _, err := a.objects.Stat(r.Context(), record.ObjectKey); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, objectstore.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
case errors.Is(err, objectstore.ErrUnavailable):
|
||||
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
default:
|
||||
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
}
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, record.Attachment)
|
||||
}
|
||||
|
||||
func (a *App) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
|
||||
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := requireOriginalVariant(r); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
default:
|
||||
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
}
|
||||
return
|
||||
}
|
||||
body, info, err := a.objects.Get(r.Context(), record.ObjectKey)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, objectstore.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
case errors.Is(err, objectstore.ErrUnavailable):
|
||||
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
default:
|
||||
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
}
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", record.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(info.Size, 10))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, body); err != nil {
|
||||
a.log.Warn("attachment stream interrupted", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// requireOriginalVariant accepts the optional variant parameter but lab4 has
|
||||
// only the original. An unknown variant of a ready object is 404.
|
||||
func requireOriginalVariant(r *http.Request) *apiError {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return invalidRequest("query string is not valid")
|
||||
}
|
||||
values, present := query["variant"]
|
||||
if !present {
|
||||
return nil
|
||||
}
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return invalidRequest("variant must be a non-empty string")
|
||||
}
|
||||
if values[0] == "original" {
|
||||
return nil
|
||||
}
|
||||
return statusNotFound
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/cursor"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title *string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
var request createChatRequest
|
||||
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Title == nil {
|
||||
a.writeError(w, r, invalidRequest("title is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateTitle(*request.Title); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
|
||||
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
|
||||
return
|
||||
}
|
||||
|
||||
members := make([]string, 0, len(request.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(request.MemberIDs))
|
||||
callerIncluded := false
|
||||
for _, rawID := range request.MemberIDs {
|
||||
id, ok := uuid.Normalize(rawID)
|
||||
if !ok {
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
|
||||
return
|
||||
}
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
members = append(members, id)
|
||||
if id == actor.user.ID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnknownMember):
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
// normalizePathUUID validates a path identifier before any database access.
|
||||
func normalizePathUUID(raw, field string) (string, *apiError) {
|
||||
id, ok := uuid.Normalize(raw)
|
||||
if !ok {
|
||||
return "", invalidRequest(field + " must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
|
||||
// safe human-readable message and an optional authentication challenge. The
|
||||
// request id is filled from the request context at write time.
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
challenge string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.code + ": " + e.message }
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
var (
|
||||
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
|
||||
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
|
||||
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
|
||||
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
|
||||
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
|
||||
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
|
||||
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
|
||||
)
|
||||
|
||||
func invalidRequest(message string) *apiError {
|
||||
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
|
||||
}
|
||||
|
||||
func conflict(message string) *apiError {
|
||||
return &apiError{status: http.StatusConflict, code: "conflict", message: message}
|
||||
}
|
||||
|
||||
func unsupportedMediaType(message string) *apiError {
|
||||
return &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: message}
|
||||
}
|
||||
|
||||
func unauthorizedBasic() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
|
||||
}
|
||||
|
||||
func unauthorizedBearer() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
|
||||
}
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// writeError writes a JSON error whose request_id matches X-Request-Id. The
|
||||
// message never contains SQL, stack traces, credentials or object existence
|
||||
// details for foreign resources.
|
||||
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
|
||||
requestID := requestIDFromContext(r.Context())
|
||||
if requestID == "" {
|
||||
requestID = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
if problem.challenge != "" {
|
||||
w.Header().Set("WWW-Authenticate", problem.challenge)
|
||||
}
|
||||
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
|
||||
Code: problem.code,
|
||||
Message: problem.message,
|
||||
RequestID: requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
}
|
||||
|
||||
type requestIDContextKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
value, _ := ctx.Value(requestIDContextKey{}).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// statusWriter records the status code and byte count for logs and for the
|
||||
// panic path, so a partially written response is not written twice.
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
if w.wrote {
|
||||
return
|
||||
}
|
||||
w.wrote = true
|
||||
w.status = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(data []byte) (int, error) {
|
||||
if !w.wrote {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
written, err := w.ResponseWriter.Write(data)
|
||||
w.bytes += written
|
||||
return written, err
|
||||
}
|
||||
|
||||
func (a *App) withObservability(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
requestID := uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
// Stable for the life of the process and unique per container. lab3
|
||||
// uses the container hostname: it is the actual process identity, so
|
||||
// stop-one can map a response to exactly one container. lab7 will
|
||||
// replace it with an opaque alias.
|
||||
w.Header().Set("X-Instance-Id", a.instanceID)
|
||||
// Extra, non-contract header used only to observe an image replacement
|
||||
// during the rolling-update experiment. The mandatory contract does
|
||||
// not define or require it.
|
||||
w.Header().Set("X-App-Version", a.version)
|
||||
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
a.log.Error("panic while handling request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"panic", recovered,
|
||||
)
|
||||
if !writer.wrote {
|
||||
a.writeError(writer, r, statusInternal)
|
||||
}
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
a.log.Log(r.Context(), level, "http request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
|
||||
"bytes", writer.bytes,
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
|
||||
// atomicBool keeps the readiness flag readable from the signal goroutine
|
||||
// without importing sync/atomic into every handler file.
|
||||
type atomicBool struct{ value atomic.Bool }
|
||||
|
||||
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
|
||||
func (b *atomicBool) Load() bool { return b.value.Load() }
|
||||
@@ -0,0 +1,213 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/cursor"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
const maxMessageAttachments = 10
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs json.RawMessage `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
// messageHash is the canonical semantic body used for idempotency. A missing
|
||||
// attachment_ids is normalised to [], exactly as the contract requires, and
|
||||
// JSON object key order never affects the hash. Array order is preserved: the
|
||||
// response also preserves it.
|
||||
type messageHashBody struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// The key is validated before the body, but after authentication and path
|
||||
// validation: a malformed/missing key is always 400, while an outsider
|
||||
// still cannot learn anything by replaying someone else's key.
|
||||
idempotencyKey, problem := idempotencyKey(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// Resource access is checked before the body is decoded so a foreign chat
|
||||
// always looks like a missing chat, independent of the submitted payload.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var request createMessageRequest
|
||||
if problem := a.decodeJSON(r, &request, "text", "attachment_ids"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Text == nil {
|
||||
a.writeError(w, r, invalidRequest("text is required"))
|
||||
return
|
||||
}
|
||||
attachmentIDs, problem := parseAttachmentIDs(request.AttachmentIDs)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(*request.Text) > 4000 {
|
||||
a.writeError(w, r, invalidRequest("text must contain at most 4000 Unicode code points"))
|
||||
return
|
||||
}
|
||||
if isBlank(*request.Text) && len(attachmentIDs) == 0 {
|
||||
a.writeError(w, r, invalidRequest("text must not be blank without attachments"))
|
||||
return
|
||||
}
|
||||
|
||||
canonical, err := json.Marshal(messageHashBody{Text: *request.Text, AttachmentIDs: attachmentIDs})
|
||||
if err != nil {
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
hash := sha256.Sum256(canonical)
|
||||
message, replayed, err := a.store.CreateMessageIdempotent(
|
||||
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID),
|
||||
idempotencyKey, hash[:], *request.Text, attachmentIDs,
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
a.conflictMessages.Add(1)
|
||||
a.writeError(w, r, statusConflict)
|
||||
return
|
||||
case errors.Is(err, store.ErrAttachmentNotReady):
|
||||
a.writeError(w, r, conflict("attachment is not ready"))
|
||||
return
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if replayed {
|
||||
a.replayedMessages.Add(1)
|
||||
} else {
|
||||
a.createdMessages.Add(1)
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
// parseAttachmentIDs accepts an absent field as [], rejects null and every
|
||||
// wrong JSON type, and enforces the UUID / uniqueness / count rules before any
|
||||
// database access.
|
||||
func parseAttachmentIDs(raw json.RawMessage) ([]string, *apiError) {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return nil, invalidRequest("attachment_ids must be an array, not null")
|
||||
}
|
||||
var values []string
|
||||
if err := json.Unmarshal(raw, &values); err != nil {
|
||||
return nil, invalidRequest("attachment_ids must be an array of UUID strings")
|
||||
}
|
||||
if len(values) > maxMessageAttachments {
|
||||
return nil, invalidRequest("attachment_ids must contain at most 10 items")
|
||||
}
|
||||
result := make([]string, 0, len(values))
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
id, ok := uuid.Normalize(value)
|
||||
if !ok {
|
||||
return nil, invalidRequest("every attachment_ids entry must be a UUID")
|
||||
}
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
return nil, invalidRequest("attachment_ids must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
result = append(result, id)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func messagePath(chatID string) string {
|
||||
return "/api/v1/chats/" + chatID + "/messages"
|
||||
}
|
||||
|
||||
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// A foreign/nonexistent chat is always 404, even if the query itself is
|
||||
// malformed; this avoids making object existence observable.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Messages(r.Context(), chatID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// InternalStats is the operator-only JSON document served on the loopback
|
||||
// metrics listener inside each API container. It is deliberately not part of
|
||||
// the public contract and is never routed through the load balancer; the
|
||||
// experiment scripts read it with `docker exec` to attribute saturation to
|
||||
// the connection pool versus PostgreSQL/CPU.
|
||||
type InternalStats struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Version string `json:"version"`
|
||||
UptimeSeconds float64 `json:"uptime_seconds"`
|
||||
Pool poolStats `json:"pool"`
|
||||
Messages messageCounters `json:"messages"`
|
||||
Runtime runtimeStats `json:"runtime"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
}
|
||||
|
||||
type poolStats struct {
|
||||
MaxConns int32 `json:"max_conns"`
|
||||
TotalConns int32 `json:"total_conns"`
|
||||
AcquiredConns int32 `json:"acquired_conns"`
|
||||
IdleConns int32 `json:"idle_conns"`
|
||||
EmptyAcquireCount int64 `json:"empty_acquire_count"`
|
||||
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
|
||||
AcquireCount int64 `json:"acquire_count"`
|
||||
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
|
||||
NewConnsCount int64 `json:"new_conns_count"`
|
||||
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
|
||||
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
|
||||
}
|
||||
|
||||
type messageCounters struct {
|
||||
Created uint64 `json:"created"`
|
||||
Replayed uint64 `json:"replayed"`
|
||||
Conflicts uint64 `json:"conflicts"`
|
||||
}
|
||||
|
||||
type runtimeStats struct {
|
||||
Goroutines int `json:"goroutines"`
|
||||
HeapAlloc uint64 `json:"heap_alloc_bytes"`
|
||||
HeapSys uint64 `json:"heap_sys_bytes"`
|
||||
TotalAlloc uint64 `json:"total_alloc_bytes"`
|
||||
}
|
||||
|
||||
// InternalStatsHandler serves one snapshot. It is mounted only on the
|
||||
// 127.0.0.1 listener started by cmd/messenger.
|
||||
func (a *App) InternalStatsHandler(w http.ResponseWriter, _ *http.Request) {
|
||||
pool := a.store.PoolStats()
|
||||
var memory runtime.MemStats
|
||||
runtime.ReadMemStats(&memory)
|
||||
stats := InternalStats{
|
||||
InstanceID: a.instanceID,
|
||||
Version: a.version,
|
||||
UptimeSeconds: time.Since(a.startedAt).Seconds(),
|
||||
Pool: poolStats{
|
||||
MaxConns: pool.MaxConns,
|
||||
TotalConns: pool.TotalConns,
|
||||
AcquiredConns: pool.AcquiredConns,
|
||||
IdleConns: pool.IdleConns,
|
||||
EmptyAcquireCount: pool.EmptyAcquireCount,
|
||||
CanceledAcquireCount: pool.CanceledAcquireCount,
|
||||
AcquireCount: pool.AcquireCount,
|
||||
AcquireDurationMillis: pool.AcquireDurationMillis,
|
||||
NewConnsCount: pool.NewConnsCount,
|
||||
MaxLifetimeDestroyCount: pool.MaxLifetimeDestroyCount,
|
||||
MaxIdleDestroyCount: pool.MaxIdleDestroyCount,
|
||||
},
|
||||
Messages: messageCounters{
|
||||
Created: a.createdMessages.Load(),
|
||||
Replayed: a.replayedMessages.Load(),
|
||||
Conflicts: a.conflictMessages.Load(),
|
||||
},
|
||||
Runtime: runtimeStats{
|
||||
Goroutines: runtime.NumGoroutine(),
|
||||
HeapAlloc: memory.HeapAlloc,
|
||||
HeapSys: memory.HeapSys,
|
||||
TotalAlloc: memory.TotalAlloc,
|
||||
},
|
||||
CollectedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(stats)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/auth"
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/session"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
// createSession is the only endpoint that accepts Basic credentials. It never
|
||||
// accepts a JSON body and never reveals whether the username exists.
|
||||
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
// Reject values that could never have been registered before touching the
|
||||
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
|
||||
if !usernameAllowed(username) || !validLoginPassword(password) {
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// Spend the same KDF work for an unknown username so response timing
|
||||
// does not disclose account existence.
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
match, err := auth.Verify(password, passwordHash)
|
||||
if err != nil {
|
||||
// A corrupt stored hash is an internal data problem, not a wrong
|
||||
// password; do not silently lock the account out with a 401 log line.
|
||||
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !match {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: model.Time{Time: expiresAt},
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
|
||||
// header on a business endpoint, a missing header and an X-User-Id header all
|
||||
// produce the same 401 challenge.
|
||||
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok || !auth.ValidTokenShape(token) {
|
||||
return identity{}, unauthorizedBearer()
|
||||
}
|
||||
|
||||
userID, err := a.sessions.Get(r.Context(), token)
|
||||
switch {
|
||||
case errors.Is(err, session.ErrInvalid):
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, session.ErrUnavailable):
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
|
||||
user, err := a.store.UserByID(r.Context(), userID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// A session pointing at a missing user is not usable. Deleting it is
|
||||
// best effort; the response is the normal 401 either way.
|
||||
_ = a.sessions.Delete(r.Context(), token)
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
return identity{user: user, token: token}, nil
|
||||
}
|
||||
|
||||
// logout revokes the current server-side session. The response has no body.
|
||||
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
|
||||
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func bearerToken(header string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(header)
|
||||
space := strings.IndexByte(trimmed, ' ')
|
||||
if space <= 0 {
|
||||
return "", false
|
||||
}
|
||||
if !strings.EqualFold(trimmed[:space], "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
token := trimmed[space+1:]
|
||||
if token == "" || strings.ContainsAny(token, " \t") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
// validLoginPassword mirrors the registration policy. A login with an
|
||||
// out-of-range password cannot match any stored hash and must still look like
|
||||
// an ordinary 401.
|
||||
func validLoginPassword(password string) bool {
|
||||
if !utf8.ValidString(password) || isBlank(password) {
|
||||
return false
|
||||
}
|
||||
count := utf8.RuneCountInString(password)
|
||||
return count >= 12 && count <= 128
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/auth"
|
||||
"mtusi.ru/messenger-lab4/internal/store"
|
||||
)
|
||||
|
||||
type createUserRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var request createUserRequest
|
||||
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Username == nil {
|
||||
a.writeError(w, r, invalidRequest("username is required"))
|
||||
return
|
||||
}
|
||||
if request.DisplayName == nil {
|
||||
a.writeError(w, r, invalidRequest("display_name is required"))
|
||||
return
|
||||
}
|
||||
if request.Password == nil {
|
||||
a.writeError(w, r, invalidRequest("password is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateUsername(*request.Username); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validateDisplayName(*request.DisplayName); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validatePassword(*request.Password); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := auth.Hash(*request.Password)
|
||||
if err != nil {
|
||||
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
a.writeError(w, r, statusConflict)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.writeJSON(w, r, http.StatusOK, actor.user)
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// decodeJSON enforces the contract's JSON rules: application/json, strict
|
||||
// UTF-8, exactly one object with exactly the documented top-level keys, no
|
||||
// unknown/duplicate fields and a bounded body size.
|
||||
//
|
||||
// encoding/json matches struct fields case-insensitively even with
|
||||
// DisallowUnknownFields, so the exact key set is checked separately on the
|
||||
// token stream. That also rejects Unicode case-folding aliases and duplicates.
|
||||
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
|
||||
if raw := r.Header.Get("Content-Type"); raw != "" {
|
||||
mediaType, _, err := mime.ParseMediaType(raw)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return statusUnsupportedMediaType
|
||||
}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
|
||||
if err != nil {
|
||||
return invalidRequest("could not read request body")
|
||||
}
|
||||
if int64(len(body)) > a.maxBody {
|
||||
return statusPayloadTooLarge
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return invalidRequest("request body must not be empty")
|
||||
}
|
||||
if !utf8.Valid(body) {
|
||||
return invalidRequest("request body must be valid UTF-8")
|
||||
}
|
||||
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
|
||||
return problem
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return invalidRequest("request body does not match the documented schema")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
|
||||
allowed := make(map[string]struct{}, len(allowedKeys))
|
||||
for _, key := range allowedKeys {
|
||||
allowed[key] = struct{}{}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
opening, ok := token.(json.Delim)
|
||||
if !ok || opening != '{' {
|
||||
return invalidRequest("request body must be a JSON object")
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(allowedKeys))
|
||||
for decoder.More() {
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
key, ok := token.(string)
|
||||
if !ok {
|
||||
return invalidRequest("request body must contain string field names")
|
||||
}
|
||||
if _, duplicate := seen[key]; duplicate {
|
||||
return invalidRequest("request body must not contain duplicate fields")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return invalidRequest("request body contains an unknown field")
|
||||
}
|
||||
var value json.RawMessage
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
}
|
||||
if _, err := decoder.Token(); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageParams parses limit/cursor. Cursor decoding happens after membership is
|
||||
// verified so a foreign chat cannot be probed with a malformed cursor.
|
||||
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return 0, "", invalidRequest("query string is not valid")
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, present := query["limit"]; present {
|
||||
if len(values) != 1 {
|
||||
return 0, "", invalidRequest("limit must be specified once")
|
||||
}
|
||||
parsed, err := strconv.Atoi(values[0])
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if values, present := query["cursor"]; present {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return 0, "", invalidRequest("cursor must be a non-empty string")
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
|
||||
func validateUsername(value string) *apiError {
|
||||
if !usernameAllowed(value) {
|
||||
return invalidRequest("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDisplayName(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("display_name must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTitle(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("title must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("title must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMessageText(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("text must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
|
||||
return invalidRequest("text must contain 1 to 4000 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePassword implements the registration rule: 12 to 128 Unicode code
|
||||
// points, not only whitespace. The exact bytes are handed to Argon2id, so
|
||||
// Unicode passwords are neither truncated nor normalized by the server.
|
||||
func validatePassword(value string) *apiError {
|
||||
if !utf8.ValidString(value) {
|
||||
return invalidRequest("password must be valid UTF-8")
|
||||
}
|
||||
if isBlank(value) {
|
||||
return invalidRequest("password must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
|
||||
return invalidRequest("password must contain 12 to 128 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isBlank(value string) bool {
|
||||
return strings.TrimSpace(value) == ""
|
||||
}
|
||||
|
||||
// usernameAllowed is a byte-wise equivalent of the contract pattern
|
||||
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
|
||||
func usernameAllowed(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// idempotencyKey enforces the contract's header rule exactly:
|
||||
// ASCII [A-Za-z0-9._:-]{1,128}, present exactly once. No trimming: whitespace
|
||||
// is outside the permitted alphabet, so a value with surrounding spaces is
|
||||
// rejected rather than silently normalised into a different scope.
|
||||
func idempotencyKey(r *http.Request) (string, *apiError) {
|
||||
values := r.Header.Values("Idempotency-Key")
|
||||
if len(values) != 1 {
|
||||
return "", invalidRequest("Idempotency-Key header is required exactly once")
|
||||
}
|
||||
key := values[0]
|
||||
if len(key) < 1 || len(key) > 128 {
|
||||
return "", invalidRequest("Idempotency-Key must contain 1 to 128 ASCII characters")
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
c := key[i]
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z':
|
||||
case c >= 'a' && c <= 'z':
|
||||
case c >= '0' && c <= '9':
|
||||
case c == '.' || c == '_' || c == ':' || c == '-':
|
||||
default:
|
||||
return "", invalidRequest("Idempotency-Key may contain only A-Z a-z 0-9 . _ : -")
|
||||
}
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type sampleRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
|
||||
|
||||
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
|
||||
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
|
||||
}
|
||||
if destination.Username == nil || *destination.Username != "alice" {
|
||||
t.Fatalf("decoded value = %+v", destination)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
contentType string
|
||||
status int
|
||||
}{
|
||||
{"empty", "", "application/json", http.StatusBadRequest},
|
||||
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
|
||||
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
|
||||
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
|
||||
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
|
||||
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
|
||||
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
|
||||
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
|
||||
request.Header.Set("Content-Type", tc.contentType)
|
||||
var destination sampleRequest
|
||||
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
|
||||
if problem == nil {
|
||||
t.Fatal("decodeJSON accepted an invalid body")
|
||||
}
|
||||
if problem.status != tc.status {
|
||||
t.Fatalf("status = %d, want %d", problem.status, tc.status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := append([]byte(`{"username":"`), 0xff, 0xfe)
|
||||
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
app.maxBody = 16
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("oversized body = %v, want 413", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsernameValidation(t *testing.T) {
|
||||
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
|
||||
for _, value := range valid {
|
||||
if problem := validateUsername(value); problem != nil {
|
||||
t.Fatalf("validateUsername(%q) = %v", value, problem)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
|
||||
for _, value := range invalid {
|
||||
if problem := validateUsername(value); problem == nil {
|
||||
t.Fatalf("validateUsername accepted %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLengthValidationCountsCodePoints(t *testing.T) {
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
|
||||
t.Fatalf("100 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
|
||||
t.Fatal("101 code points accepted")
|
||||
}
|
||||
if problem := validateDisplayName(" "); problem == nil {
|
||||
t.Fatal("blank display_name accepted")
|
||||
}
|
||||
|
||||
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
|
||||
t.Fatalf("4000 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
|
||||
t.Fatal("4001 code points accepted")
|
||||
}
|
||||
if problem := validateMessageText(" \t\n"); problem == nil {
|
||||
t.Fatal("blank message accepted")
|
||||
}
|
||||
|
||||
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
|
||||
t.Fatalf("12-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
|
||||
t.Fatal("11-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
|
||||
t.Fatalf("128-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
|
||||
t.Fatal("129-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
|
||||
t.Fatal("whitespace password accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageParams(t *testing.T) {
|
||||
valid := map[string][2]any{
|
||||
"": {50, ""},
|
||||
"?limit=1": {1, ""},
|
||||
"?limit=100": {100, ""},
|
||||
"?limit=7&cursor=x": {7, "x"},
|
||||
}
|
||||
for query, want := range valid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
limit, cursor, problem := decodeTestApp().pageParams(request)
|
||||
if problem != nil {
|
||||
t.Fatalf("pageParams(%q) = %v", query, problem)
|
||||
}
|
||||
if limit != want[0].(int) || cursor != want[1].(string) {
|
||||
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
|
||||
}
|
||||
}
|
||||
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
|
||||
for _, query := range invalid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
|
||||
t.Fatalf("pageParams accepted %q", query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokenParsing(t *testing.T) {
|
||||
token := strings.Repeat("a", 43)
|
||||
cases := map[string]string{
|
||||
"Bearer " + token: token,
|
||||
"bearer " + token: token,
|
||||
"BEARER " + token: token,
|
||||
}
|
||||
for header, want := range cases {
|
||||
got, ok := bearerToken(header)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
|
||||
}
|
||||
}
|
||||
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
|
||||
if _, ok := bearerToken(header); ok {
|
||||
t.Fatalf("bearerToken accepted %q", header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorEnvelopeShape(t *testing.T) {
|
||||
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
|
||||
data, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
|
||||
t.Fatalf("unexpected error JSON: %s", data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashAndVerify(t *testing.T) {
|
||||
password := "correct horse battery staple"
|
||||
encoded, err := Hash(password)
|
||||
if err != nil {
|
||||
t.Fatalf("Hash: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$") {
|
||||
t.Fatalf("unexpected PHC prefix: %q", encoded)
|
||||
}
|
||||
match, err := Verify(password, encoded)
|
||||
if err != nil || !match {
|
||||
t.Fatalf("Verify(correct) = %v, %v", match, err)
|
||||
}
|
||||
match, err = Verify(password+"x", encoded)
|
||||
if err != nil || match {
|
||||
t.Fatalf("Verify(wrong) = %v, %v", match, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashUnicodeAndMaximumLength(t *testing.T) {
|
||||
for _, password := range []string{
|
||||
"pässwörd:12✓",
|
||||
strings.Repeat("界", 128),
|
||||
" leading and trailing spaces ",
|
||||
} {
|
||||
encoded, err := Hash(password)
|
||||
if err != nil {
|
||||
t.Fatalf("Hash(%q): %v", password, err)
|
||||
}
|
||||
if match, err := Verify(password, encoded); err != nil || !match {
|
||||
t.Fatalf("Verify(%q) = %v, %v", password, match, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashUsesRandomSalt(t *testing.T) {
|
||||
first, err := Hash("same-password-twice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := Hash("same-password-twice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("two hashes of the same password are identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHashes(t *testing.T) {
|
||||
for _, encoded := range []string{
|
||||
"",
|
||||
"plaintext",
|
||||
"$2a$10$abcdefghijklmnopqrstuv",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$not-base64$hash",
|
||||
"$argon2id$v=19$m=1,t=3,p=2$c2FsdHNhbHQ$aGFzaGhhc2hoYXNoaGFzaA",
|
||||
"$argon2id$v=19$m=19456,t=2,p=1$c2FsdA$aGFzaA",
|
||||
} {
|
||||
if _, err := Verify("password", encoded); err == nil {
|
||||
t.Fatalf("Verify accepted malformed hash %q", encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseBasic(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
username string
|
||||
password string
|
||||
ok bool
|
||||
}{
|
||||
{
|
||||
name: "ordinary",
|
||||
raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:secret")),
|
||||
username: "alice",
|
||||
password: "secret",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "password contains colon and UTF-8",
|
||||
raw: "bAsIc " + base64.StdEncoding.EncodeToString([]byte("alice:pässwörd:with:colons")),
|
||||
username: "alice",
|
||||
password: "pässwörd:with:colons",
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
name: "unpadded base64",
|
||||
raw: "Basic " + base64.RawStdEncoding.EncodeToString([]byte("alice:secret")),
|
||||
username: "alice",
|
||||
password: "secret",
|
||||
ok: true,
|
||||
},
|
||||
{name: "no scheme", raw: "alice:secret"},
|
||||
{name: "wrong scheme", raw: "Bearer abc"},
|
||||
{name: "no space", raw: "Basic" + base64.StdEncoding.EncodeToString([]byte("alice:secret"))},
|
||||
{name: "bad base64", raw: "Basic !!!"},
|
||||
{name: "no separator", raw: "Basic " + base64.StdEncoding.EncodeToString([]byte("alice"))},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
username, password, err := ParseBasic(tc.raw)
|
||||
if !tc.ok {
|
||||
if err == nil {
|
||||
t.Fatalf("ParseBasic accepted %q", tc.raw)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("ParseBasic: %v", err)
|
||||
}
|
||||
if username != tc.username || password != tc.password {
|
||||
t.Fatalf("got %q/%q, want %q/%q", username, password, tc.username, tc.password)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenProperties(t *testing.T) {
|
||||
first, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("tokens are not unique")
|
||||
}
|
||||
if len(first) != 43 {
|
||||
t.Fatalf("token length = %d, want 43 (256 bits)", len(first))
|
||||
}
|
||||
if !ValidTokenShape(first) {
|
||||
t.Fatal("issued token fails its own shape check")
|
||||
}
|
||||
if TokenHash(first) == TokenHash(second) {
|
||||
t.Fatal("token hashes collide")
|
||||
}
|
||||
if len(TokenHash(first)) != 64 {
|
||||
t.Fatalf("token hash length = %d", len(TokenHash(first)))
|
||||
}
|
||||
for _, bad := range []string{"", "short", "has space in it", strings.Repeat("a", 129), "abc+/="} {
|
||||
if ValidTokenShape(bad) {
|
||||
t.Fatalf("ValidTokenShape accepted %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Package auth implements the lab3 credential primitives: a library password
|
||||
// KDF (Argon2id), opaque session tokens and RFC 7617 Basic parsing. None of
|
||||
// these helpers log or serialise the secret material they receive.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Argon2id parameters. 19 MiB / 2 passes / 1 lane is the OWASP password
|
||||
// storage minimum for Argon2id, chosen so eight concurrent registrations fit
|
||||
// inside the 256 MiB API container limit. The parameters are stored in every
|
||||
// PHC string, so a future change remains backward compatible.
|
||||
const (
|
||||
argonMemory uint32 = 19 * 1024 // KiB
|
||||
argonIterations uint32 = 2
|
||||
argonParallelism uint8 = 1
|
||||
argonSaltLength = 16
|
||||
argonKeyLength uint32 = 32
|
||||
)
|
||||
|
||||
// ErrInvalidHash means a stored PHC string is malformed or uses unsupported
|
||||
// parameters. It is an internal error, never shown to a client.
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
// Hash derives an Argon2id PHC string for password. Callers must validate the
|
||||
// password policy before calling; the KDF itself accepts arbitrary UTF-8.
|
||||
func Hash(password string) (string, error) {
|
||||
salt := make([]byte, argonSaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password 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
|
||||
}
|
||||
|
||||
// Verify checks password against a PHC string in constant time and reports
|
||||
// whether the encoded hash was structurally valid. A malformed hash is not a
|
||||
// password mismatch and should be treated as an internal error by the caller.
|
||||
func Verify(password, encoded string) (match bool, err error) {
|
||||
params, salt, key, err := parse(encoded)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
candidate := argon2.IDKey([]byte(password), salt, params.iterations, params.memory, params.parallelism, uint32(len(key)))
|
||||
return subtle.ConstantTimeCompare(candidate, key) == 1, nil
|
||||
}
|
||||
|
||||
type params struct {
|
||||
memory uint32
|
||||
iterations uint32
|
||||
parallelism uint8
|
||||
}
|
||||
|
||||
func parse(encoded string) (params, []byte, []byte, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
var p params
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism); err != nil {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
if p.memory < 8*1024 || p.memory > 256*1024 || p.iterations < 1 || p.iterations > 10 || p.parallelism < 1 || p.parallelism > 16 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) < 8 || len(salt) > 64 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
key, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(key) < 16 || len(key) > 64 {
|
||||
return params{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
return p, salt, key, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// tokenBytes gives 256 bits of entropy, the contract minimum. The token is an
|
||||
// opaque value: it is not a username, a UUID or a JWT.
|
||||
const tokenBytes = 32
|
||||
|
||||
// NewToken returns a URL-safe opaque session token.
|
||||
func NewToken() (string, error) {
|
||||
raw := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||
}
|
||||
|
||||
// TokenHash is the only representation of a token that is persisted. A cache
|
||||
// dump therefore does not contain bearer credentials usable against the API.
|
||||
func TokenHash(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// ValidTokenShape rejects absurd header values before hashing. The check is a
|
||||
// superset of the 43-character tokens this server issues, so token rotation
|
||||
// remains possible without rejecting old values early.
|
||||
func ValidTokenShape(token string) bool {
|
||||
if len(token) < 16 || len(token) > 128 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(token); i++ {
|
||||
c := token[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ErrMalformedBasic is returned for anything that is not a well-formed
|
||||
// RFC 7617 Basic credential. Callers must answer with the same 401 as a
|
||||
// wrong password.
|
||||
var ErrMalformedBasic = errors.New("malformed basic credentials")
|
||||
|
||||
// ParseBasic decodes an Authorization header of the form "Basic base64(user:pass)".
|
||||
// The password may contain colons and arbitrary UTF-8; only the first colon
|
||||
// separates the username.
|
||||
func ParseBasic(header string) (username, password string, err error) {
|
||||
const scheme = "basic"
|
||||
trimmed := header
|
||||
if len(trimmed) < len(scheme)+1 || !equalFoldASCII(trimmed[:len(scheme)], scheme) || trimmed[len(scheme)] != ' ' {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
encoded := trimmed[len(scheme)+1:]
|
||||
if encoded == "" || len(encoded) > 1024 {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
// Some clients omit the RFC 4648 padding. Accept the unpadded form as
|
||||
// well, but never fall back to a different alphabet.
|
||||
decoded, err = base64.RawStdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
}
|
||||
separator := -1
|
||||
for i := 0; i < len(decoded); i++ {
|
||||
if decoded[i] == ':' {
|
||||
separator = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if separator < 0 {
|
||||
return "", "", ErrMalformedBasic
|
||||
}
|
||||
return string(decoded[:separator]), string(decoded[separator+1:]), nil
|
||||
}
|
||||
|
||||
func equalFoldASCII(value, lower string) bool {
|
||||
if len(value) != len(lower) {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if c >= 'A' && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
if c != lower[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
// Package config loads the explicit runtime configuration of the lab3
|
||||
// messenger. The container image stays immutable: the same image is configured
|
||||
// through environment variables (or files referenced by *_FILE variables for
|
||||
// operators that do not want secrets in the environment).
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultSessionTTL is the contract default of contracts/README.md.
|
||||
DefaultSessionTTL = time.Hour
|
||||
// MaxShutdownTimeout leaves headroom below the 10 second termination
|
||||
// window promised by the previous lab and expected by the container
|
||||
// checks, even if an operator overrides the environment variable.
|
||||
MaxShutdownTimeout = 9 * time.Second
|
||||
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
|
||||
MaxStartupTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
// Config is validated at startup. The process refuses to start with an
|
||||
// invalid value instead of silently falling back to a different security or
|
||||
// durability posture.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
ShutdownDrain time.Duration
|
||||
StartupTimeout time.Duration
|
||||
MetricsAddr string
|
||||
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
|
||||
SessionTTL time.Duration
|
||||
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBConnectTimeout time.Duration
|
||||
DBStatementTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
|
||||
CachePoolSize int
|
||||
CacheTimeout time.Duration
|
||||
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3Timeout time.Duration
|
||||
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
DecodeConcurrency int
|
||||
PutConcurrency int
|
||||
TempDir string
|
||||
}
|
||||
|
||||
// Load reads and validates the full API configuration.
|
||||
func Load() (Config, error) { return load(true, true) }
|
||||
|
||||
// LoadMigrate loads only what the one-shot migration command needs.
|
||||
func LoadMigrate() (Config, error) { return load(false, false) }
|
||||
|
||||
// LoadTool loads the database and S3 configuration used by the offline
|
||||
// reconciler and the bucket/test tools; Valkey is not required.
|
||||
func LoadTool() (Config, error) { return load(false, true) }
|
||||
|
||||
// load is the shared parser. requireCache and requireS3 select which optional
|
||||
// dependency blocks are mandatory for the calling command.
|
||||
func load(requireCache, requireS3 bool) (Config, error) {
|
||||
cfg := Config{
|
||||
Host: envString("APP_HOST", "0.0.0.0"),
|
||||
Env: envString("APP_ENV", "lab"),
|
||||
ShutdownTimeout: 6 * time.Second,
|
||||
ShutdownDrain: 3 * time.Second,
|
||||
StartupTimeout: 30 * time.Second,
|
||||
QueryTimeout: 3 * time.Second,
|
||||
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
|
||||
}
|
||||
|
||||
port, err := envInt("APP_PORT", 8080)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("APP_PORT: %w", err)
|
||||
}
|
||||
if port < 1 || port > 65535 {
|
||||
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
|
||||
}
|
||||
cfg.Port = port
|
||||
|
||||
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
|
||||
}
|
||||
cfg.LogLevel = level
|
||||
|
||||
if strings.TrimSpace(cfg.Host) == "" {
|
||||
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
|
||||
}
|
||||
|
||||
databaseURL, err := secret("DATABASE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.DatabaseURL = databaseURL
|
||||
|
||||
if requireCache {
|
||||
cacheURL, err := secret("CACHE_URL")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.CacheURL = cacheURL
|
||||
}
|
||||
|
||||
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
|
||||
}
|
||||
if seconds < 1 || seconds > 30*24*60*60 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(seconds) * time.Second
|
||||
|
||||
maxConns, err := envInt("DB_MAX_CONNS", 8)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
|
||||
}
|
||||
if maxConns < 1 || maxConns > 100 {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
|
||||
}
|
||||
cfg.DBMaxConns = int32(maxConns)
|
||||
|
||||
minConns, err := envInt("DB_MIN_CONNS", 1)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
|
||||
}
|
||||
if minConns < 0 || minConns > maxConns {
|
||||
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
|
||||
}
|
||||
cfg.DBMinConns = int32(minConns)
|
||||
|
||||
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
|
||||
}
|
||||
if cachePool < 1 || cachePool > 100 {
|
||||
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
|
||||
}
|
||||
cfg.CachePoolSize = cachePool
|
||||
|
||||
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if shutdown > MaxShutdownTimeout {
|
||||
shutdown = MaxShutdownTimeout
|
||||
}
|
||||
cfg.ShutdownTimeout = shutdown
|
||||
|
||||
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
// The drain must finish before the hard shutdown window; otherwise a
|
||||
// SIGTERM could spend the whole grace period advertising readiness and
|
||||
// never reach http.Server.Shutdown.
|
||||
if drain >= shutdown {
|
||||
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
|
||||
}
|
||||
cfg.ShutdownDrain = drain
|
||||
|
||||
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cfg.StartupTimeout = startup
|
||||
|
||||
if requireS3 {
|
||||
if err := loadS3(&cfg); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// loadS3 parses the private object store configuration and the image limits
|
||||
// that must be enforced before any unbounded read or decode.
|
||||
func loadS3(cfg *Config) error {
|
||||
endpoint, err := secret("S3_ENDPOINT")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.S3Endpoint = endpoint
|
||||
cfg.S3Region = envString("S3_REGION", "us-east-1")
|
||||
cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments")
|
||||
if !validBucketName(cfg.S3Bucket) {
|
||||
return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
|
||||
}
|
||||
accessKey, err := secret("S3_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secretKey, err := secret("S3_SECRET_KEY")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.S3AccessKey = accessKey
|
||||
cfg.S3SecretKey = secretKey
|
||||
|
||||
timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.S3Timeout = timeout
|
||||
|
||||
maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
|
||||
if err != nil {
|
||||
return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
|
||||
}
|
||||
if maxUpload < 1 || maxUpload > 10*1024*1024 {
|
||||
return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760")
|
||||
}
|
||||
cfg.MaxUploadBytes = maxUpload
|
||||
|
||||
maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000)
|
||||
if err != nil {
|
||||
return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
|
||||
}
|
||||
if maxPixels < 1 || maxPixels > 40_000_000 {
|
||||
return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000")
|
||||
}
|
||||
cfg.MaxImagePixels = maxPixels
|
||||
|
||||
concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err)
|
||||
}
|
||||
if concurrency < 1 || concurrency > 4 {
|
||||
return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4")
|
||||
}
|
||||
cfg.DecodeConcurrency = concurrency
|
||||
|
||||
// The single-node SeaweedFS stand was verified stable at one concurrent
|
||||
// PUT per API replica; two concurrent multi-megabyte writes could restart
|
||||
// it. Uploads queue after their body was already streamed to a bounded
|
||||
// temporary file, so queuing does not add unbounded RAM.
|
||||
putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err)
|
||||
}
|
||||
if putConcurrency != 1 {
|
||||
return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand")
|
||||
}
|
||||
cfg.PutConcurrency = putConcurrency
|
||||
cfg.TempDir = envString("UPLOAD_TEMP_DIR", "")
|
||||
return nil
|
||||
}
|
||||
|
||||
func validBucketName(value string) bool {
|
||||
if len(value) < 3 || len(value) > 63 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-'
|
||||
}
|
||||
|
||||
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
|
||||
// compose-style file secrets win over inherited environment values. Values are
|
||||
// never echoed in error messages.
|
||||
func secret(name string) (string, error) {
|
||||
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
|
||||
}
|
||||
|
||||
func envString(key, fallback string) string {
|
||||
// An environment variable set to an empty string is treated as unset; this
|
||||
// keeps container defaults working when compose passes "" for an optional
|
||||
// setting.
|
||||
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) (int, error) {
|
||||
raw, ok := os.LookupEnv(key)
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("expected an integer, got %q", raw)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func envInt64(key string, fallback int64) (int64, error) {
|
||||
raw, ok := os.LookupEnv(key)
|
||||
if !ok || strings.TrimSpace(raw) == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("expected an integer, got %q", raw)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
|
||||
value, err := envInt(key, fallback)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", key, err)
|
||||
}
|
||||
if value < minimum || value > maximum {
|
||||
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
|
||||
}
|
||||
return time.Duration(value) * time.Second, nil
|
||||
}
|
||||
|
||||
func parseLogLevel(raw string) (slog.Level, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||
case "debug":
|
||||
return slog.LevelDebug, nil
|
||||
case "info":
|
||||
return slog.LevelInfo, nil
|
||||
case "warn", "warning":
|
||||
return slog.LevelWarn, nil
|
||||
case "error":
|
||||
return slog.LevelError, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var allKeys = []string{
|
||||
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
|
||||
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
|
||||
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
|
||||
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
|
||||
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
|
||||
"CACHE_URL", "CACHE_URL_FILE",
|
||||
"S3_ENDPOINT", "S3_ENDPOINT_FILE", "S3_REGION", "S3_BUCKET",
|
||||
"S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE", "S3_SECRET_KEY", "S3_SECRET_KEY_FILE",
|
||||
"S3_TIMEOUT_SECONDS", "MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_DECODE_CONCURRENCY", "S3_PUT_CONCURRENCY", "UPLOAD_TEMP_DIR",
|
||||
}
|
||||
|
||||
func clearEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, key := range allKeys {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
}
|
||||
|
||||
func baseEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
|
||||
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
|
||||
t.Setenv("S3_ENDPOINT", "http://s3:8333")
|
||||
t.Setenv("S3_BUCKET", "messenger-attachments")
|
||||
t.Setenv("S3_ACCESS_KEY", "local-test-access")
|
||||
t.Setenv("S3_SECRET_KEY", "local-test-secret")
|
||||
}
|
||||
|
||||
func TestLoadDefaults(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
|
||||
t.Fatalf("unexpected defaults: %+v", cfg)
|
||||
}
|
||||
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
|
||||
t.Fatalf("unexpected pool defaults: %+v", cfg)
|
||||
}
|
||||
if cfg.MaxUploadBytes != 10*1024*1024 || cfg.MaxImagePixels != 40_000_000 || cfg.DecodeConcurrency != 1 {
|
||||
t.Fatalf("unexpected upload defaults: %+v", cfg)
|
||||
}
|
||||
if cfg.S3Bucket != "messenger-attachments" || cfg.S3Region != "us-east-1" {
|
||||
t.Fatalf("unexpected S3 defaults: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadReadsSecretsFromFiles(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
directory := t.TempDir()
|
||||
databaseFile := filepath.Join(directory, "database_url")
|
||||
cacheFile := filepath.Join(directory, "cache_url")
|
||||
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", databaseFile)
|
||||
t.Setenv("CACHE_URL_FILE", cacheFile)
|
||||
t.Setenv("S3_ENDPOINT", "http://s3:8333")
|
||||
t.Setenv("S3_ACCESS_KEY", "file-test-access")
|
||||
t.Setenv("S3_SECRET_KEY", "file-test-secret")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
|
||||
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
|
||||
}
|
||||
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
|
||||
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidValues(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
key string
|
||||
value string
|
||||
}{
|
||||
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
|
||||
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
|
||||
{"zero port", "APP_PORT", "0"},
|
||||
{"bad log level", "LOG_LEVEL", "verbose"},
|
||||
{"zero max conns", "DB_MAX_CONNS", "0"},
|
||||
{"min above max", "DB_MIN_CONNS", "9"},
|
||||
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
|
||||
{"bad int", "APP_PORT", "eighty"},
|
||||
{"upload above contract", "MAX_UPLOAD_BYTES", "10485761"},
|
||||
{"pixels above contract", "MAX_IMAGE_PIXELS", "40000001"},
|
||||
{"zero decode concurrency", "UPLOAD_DECODE_CONCURRENCY", "0"},
|
||||
{"zero put concurrency", "S3_PUT_CONCURRENCY", "0"},
|
||||
{"unsafe put concurrency", "S3_PUT_CONCURRENCY", "2"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv(tc.key, tc.value)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
|
||||
}
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing CACHE_URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresS3Configuration(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv("S3_ACCESS_KEY", "")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing S3_ACCESS_KEY")
|
||||
}
|
||||
t.Setenv("S3_ACCESS_KEY", "local-test-access")
|
||||
t.Setenv("S3_BUCKET", "Invalid_Bucket")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted an invalid S3 bucket name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateConfigurationDoesNotRequireCacheOrS3(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
|
||||
cfg, err := LoadMigrate()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadMigrate: %v", err)
|
||||
}
|
||||
if cfg.DatabaseURL == "" || cfg.CacheURL != "" || cfg.S3Endpoint != "" {
|
||||
t.Fatalf("unexpected migrate configuration: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownTimeoutIsClamped(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.ShutdownTimeout != MaxShutdownTimeout {
|
||||
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
|
||||
_, err := Load()
|
||||
if err == nil {
|
||||
t.Fatal("Load accepted a missing secret file")
|
||||
}
|
||||
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
|
||||
t.Fatalf("error leaks path: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Package cursor implements the opaque keyset cursor of the contract. A cursor
|
||||
// carries the last item already returned; the next page asks PostgreSQL for
|
||||
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
|
||||
// for message history, to the chat that issued them.
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
ScopeChats = "chats"
|
||||
ScopeMessages = "messages"
|
||||
|
||||
version = 1
|
||||
maxCursorSize = 512
|
||||
)
|
||||
|
||||
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
|
||||
// HTTP layer maps it to 400 invalid_request.
|
||||
var ErrInvalid = errors.New("invalid cursor")
|
||||
|
||||
// Cursor is the decoded keyset position.
|
||||
type Cursor struct {
|
||||
At time.Time
|
||||
ID string
|
||||
ChatID string
|
||||
}
|
||||
|
||||
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
|
||||
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
|
||||
// an identifier on its own.
|
||||
type wire struct {
|
||||
Version int `json:"v"`
|
||||
Scope string `json:"s"`
|
||||
ChatID string `json:"c,omitempty"`
|
||||
Time string `json:"t"`
|
||||
ID string `json:"i"`
|
||||
}
|
||||
|
||||
// ForChat encodes the position of the last returned chat.
|
||||
func ForChat(chat model.Chat) string {
|
||||
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
|
||||
}
|
||||
|
||||
// ForMessage encodes the position of the last returned message.
|
||||
func ForMessage(message model.Message) string {
|
||||
return encode(wire{
|
||||
Scope: ScopeMessages,
|
||||
ChatID: message.ChatID,
|
||||
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: message.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// Decode validates a cursor for the expected scope. chatID is required for the
|
||||
// messages scope and must be empty for the chats scope.
|
||||
func Decode(raw, scope, chatID string) (Cursor, error) {
|
||||
if raw == "" || len(raw) > maxCursorSize {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
var value wire
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
if value.Version != version || value.Scope != scope {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
at, err := time.Parse(time.RFC3339Nano, value.Time)
|
||||
if err != nil || at.IsZero() || at.Location() != time.UTC {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
normalizedID, ok := uuid.Normalize(value.ID)
|
||||
if !ok || normalizedID != value.ID {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
switch scope {
|
||||
case ScopeChats:
|
||||
if value.ChatID != "" {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
return Cursor{At: at, ID: normalizedID}, nil
|
||||
case ScopeMessages:
|
||||
normalizedChat, ok := uuid.Normalize(value.ChatID)
|
||||
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
|
||||
default:
|
||||
return Cursor{}, ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func encode(value wire) string {
|
||||
value.Version = version
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
panic("encode cursor: " + err.Error())
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
)
|
||||
|
||||
func TestChatCursorRoundTrip(t *testing.T) {
|
||||
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
|
||||
chat := model.Chat{
|
||||
ID: "11111111-2222-4333-8444-555555555555",
|
||||
Title: "chat",
|
||||
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
|
||||
CreatedAt: model.Time{Time: at},
|
||||
}
|
||||
raw := ForChat(chat)
|
||||
decoded, err := Decode(raw, ScopeChats, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Decode: %v", err)
|
||||
}
|
||||
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
|
||||
t.Fatalf("decoded = %+v", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageCursorIsBoundToChat(t *testing.T) {
|
||||
at := time.Now().UTC().Truncate(time.Microsecond)
|
||||
chatID := "11111111-2222-4333-8444-555555555555"
|
||||
message := model.Message{
|
||||
ID: "99999999-2222-4333-8444-555555555555",
|
||||
ChatID: chatID,
|
||||
SenderID: "11111111-2222-4333-8444-555555555555",
|
||||
Text: "hello",
|
||||
CreatedAt: model.Time{Time: at},
|
||||
}
|
||||
raw := ForMessage(message)
|
||||
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
|
||||
t.Fatalf("Decode(same chat): %v", err)
|
||||
}
|
||||
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
|
||||
t.Fatal("cursor was accepted for another chat")
|
||||
}
|
||||
if _, err := Decode(raw, ScopeChats, ""); err == nil {
|
||||
t.Fatal("message cursor was accepted by the chats scope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsTamperedCursors(t *testing.T) {
|
||||
at := time.Now().UTC().Truncate(time.Microsecond)
|
||||
valid := wire{
|
||||
Version: version,
|
||||
Scope: ScopeMessages,
|
||||
ChatID: "11111111-2222-4333-8444-555555555555",
|
||||
Time: at.Format(time.RFC3339Nano),
|
||||
ID: "99999999-2222-4333-8444-555555555555",
|
||||
}
|
||||
tampered := []wire{
|
||||
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
|
||||
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
|
||||
}
|
||||
for i, value := range tampered {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := base64.RawURLEncoding.EncodeToString(data)
|
||||
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
|
||||
t.Fatalf("tampered cursor %d was accepted", i)
|
||||
}
|
||||
}
|
||||
|
||||
withExtra, _ := json.Marshal(map[string]any{
|
||||
"v": version, "s": ScopeMessages, "c": valid.ChatID,
|
||||
"t": valid.Time, "i": valid.ID, "x": 1,
|
||||
})
|
||||
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
|
||||
t.Fatal("cursor with an unknown field was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsGarbage(t *testing.T) {
|
||||
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
|
||||
if _, err := Decode(raw, ScopeChats, ""); err == nil {
|
||||
t.Fatalf("Decode accepted %q", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package model holds the public JSON shapes of the lab3 contract. They are
|
||||
// deliberately separate from the database scan helpers so an accidental new
|
||||
// column cannot silently become an API field.
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// Time marshals an RFC 3339 UTC timestamp with exactly six fractional digits.
|
||||
// Go's default time.Time JSON encoder trims trailing zeros, which produces
|
||||
// 3-5 digit fractions that some Python 3.9 datetime parsers (used by the
|
||||
// public test client) reject. A fixed microsecond precision matches
|
||||
// PostgreSQL timestamptz and stays valid RFC 3339.
|
||||
type Time struct{ time.Time }
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
// MarshalJSON implements json.Marshaler.
|
||||
func (t Time) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
|
||||
// User is the public user shape. It never contains a password hash or session
|
||||
// data.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Chat is the public chat shape. MemberIDs preserves the order supplied at
|
||||
// creation; membership is immutable in the mandatory lab3 API.
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Message is the public message shape. SenderID always comes from the server
|
||||
// session, never from the request body. AttachmentIDs is always a JSON array,
|
||||
// never null, and preserves the order supplied by the client.
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Time `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
// Variant is the public derivative shape. Lab4 never creates variants, so
|
||||
// every Attachment carries an empty array; the schema is kept for lab5.
|
||||
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"`
|
||||
}
|
||||
|
||||
// Attachment is the public metadata shape. Object keys, bucket names and
|
||||
// storage credentials are deliberately absent: they are server-side details.
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `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 Time `json:"created_at"`
|
||||
UpdatedAt Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ChatPage is one keyset page of accessible chats.
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// MessagePage is one keyset page of a chat history.
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Session is the login response. Token is only ever written to the response
|
||||
// body, never to logs or PostgreSQL.
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimeMarshalUsesFixedMicroseconds(t *testing.T) {
|
||||
value := Time{Time: time.Date(2026, 11, 30, 12, 0, 0, 120000000, time.UTC)}
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := string(data)
|
||||
// .120000 would be trimmed to .12 by the default encoder; the public
|
||||
// Python 3.9 client requires 3 or 6 fractional digits.
|
||||
if got != `"2026-11-30T12:00:00.120000Z"` {
|
||||
t.Fatalf("marshal = %s", got)
|
||||
}
|
||||
if !strings.HasSuffix(got, "Z\"") {
|
||||
t.Fatal("timestamp does not end in Z")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserJSONHasOnlyPublicFields(t *testing.T) {
|
||||
user := User{
|
||||
ID: "11111111-2222-4333-8444-555555555555",
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: Time{Time: time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)},
|
||||
}
|
||||
data, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var fields map[string]any
|
||||
if err := json.Unmarshal(data, &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fields) != 4 {
|
||||
t.Fatalf("user JSON has unexpected fields: %v", fields)
|
||||
}
|
||||
for _, forbidden := range []string{"password", "password_hash", "token", "token_hash"} {
|
||||
if _, present := fields[forbidden]; present {
|
||||
t.Fatalf("user JSON leaks %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// Package objectstore is the S3 adapter. PostgreSQL stores attachment
|
||||
// metadata; this package stores and streams the original bytes. No handler
|
||||
// talks to the S3 SDK directly, so error classification and timeouts are in one
|
||||
// place.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNotFound means the object (or a prerequisite such as the bucket) does
|
||||
// not exist. The HTTP layer maps it to 404 for an attachment read.
|
||||
ErrNotFound = errors.New("object not found")
|
||||
// ErrUnavailable means S3 could not answer. The HTTP layer maps it to 503
|
||||
// and never to a fabricated success.
|
||||
ErrUnavailable = errors.New("object store unavailable")
|
||||
)
|
||||
|
||||
// Config is the validated S3 connection. Credentials are never logged.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Store is a thin, timeout-aware wrapper around minio-go.
|
||||
type Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// Open parses S3_ENDPOINT as a scheme://host:port URL and builds a client. The
|
||||
// caller must have validated that every field is non-empty.
|
||||
func Open(cfg Config) (*Store, error) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
|
||||
if err != nil || parsed.Host == "" {
|
||||
return nil, errors.New("S3_ENDPOINT must be an http(s) URL with a host")
|
||||
}
|
||||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return nil, errors.New("S3_ENDPOINT scheme must be http or https")
|
||||
}
|
||||
if parsed.Path != "" && parsed.Path != "/" {
|
||||
return nil, errors.New("S3_ENDPOINT must not contain a path")
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 30 * time.Second
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: 3 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
|
||||
MaxIdleConns: 32,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
ExpectContinueTimeout: time.Second,
|
||||
}
|
||||
client, err := minio.New(parsed.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: parsed.Scheme == "https",
|
||||
Region: cfg.Region,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
Transport: transport,
|
||||
// The HTTP request is synchronous user work. One bounded retry is
|
||||
// enough; the default exponential retry series would hold an upload
|
||||
// request open for many seconds when S3 is unreachable.
|
||||
MaxRetries: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.New("could not create S3 client")
|
||||
}
|
||||
return &Store{client: client, bucket: cfg.Bucket, timeout: cfg.Timeout}, nil
|
||||
}
|
||||
|
||||
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
// Put uploads exactly size bytes with the declared content type. The caller
|
||||
// has already validated the image; this function does not buffer the body.
|
||||
func (s *Store) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
PartSize: 16 << 20,
|
||||
NumThreads: 1,
|
||||
DisableMultipart: size <= 16<<20,
|
||||
})
|
||||
if err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get opens the object stream. The caller closes it. A missing object is
|
||||
// ErrNotFound; an unreachable store is ErrUnavailable.
|
||||
//
|
||||
// The operation context must stay alive while the body is read: cancelling it
|
||||
// when Get returns would abort the HTTP response stream. Close releases both
|
||||
// the SDK object and its timeout.
|
||||
//
|
||||
// Existence and size come from a separate StatObject. Calling Stat on the
|
||||
// lazily opened Object would make minio-go attach an If-Match ETag to the
|
||||
// subsequent GET; SeaweedFS 3.98 rejects that conditional read for large
|
||||
// objects with 412 after the store has been restarted. A plain GET avoids the
|
||||
// false precondition while the HEAD still lets the handler return 404 before
|
||||
// it writes response headers.
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, ObjectInfo{}, classify(err)
|
||||
}
|
||||
return &objectStream{ReadCloser: object, cancel: cancel}, ObjectInfo{
|
||||
Key: key,
|
||||
Size: info.Size,
|
||||
ContentType: info.ContentType,
|
||||
LastModified: info.LastModified,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// objectStream ties the S3 read lifetime to Close. The standard S3 response
|
||||
// is not reusable after Close, and the caller always defers Close.
|
||||
type objectStream struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (s *objectStream) Close() error {
|
||||
err := s.ReadCloser.Close()
|
||||
s.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
// Stat checks existence without downloading the bytes. It is used by the
|
||||
// metadata endpoint so a missing object is not reported as a ready attachment.
|
||||
func (s *Store) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{
|
||||
Key: key,
|
||||
Size: info.Size,
|
||||
ContentType: info.ContentType,
|
||||
LastModified: info.LastModified,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Remove deletes one object. S3 delete is idempotent: a missing key is not an
|
||||
// error, which makes a repeated reconciler run safe.
|
||||
func (s *Store) Remove(ctx context.Context, key string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ObjectInfo is the subset of S3 metadata the reconciler needs.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// List returns every object under prefix. The reconciler uses it once per run;
|
||||
// the HTTP path never lists the bucket.
|
||||
func (s *Store) List(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
result := make([]ObjectInfo, 0, 64)
|
||||
for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if object.Err != nil {
|
||||
return nil, classify(object.Err)
|
||||
}
|
||||
result = append(result, ObjectInfo{
|
||||
Key: object.Key,
|
||||
Size: object.Size,
|
||||
ContentType: object.ContentType,
|
||||
LastModified: object.LastModified,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// EnsureBucket creates the bucket if it is absent. It is safe to run
|
||||
// concurrently and repeatedly: an already existing bucket is not an error.
|
||||
// The caller uses administrative credentials; API credentials are not allowed
|
||||
// to create buckets.
|
||||
func (s *Store) EnsureBucket(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return false, classify(err)
|
||||
}
|
||||
if exists {
|
||||
return false, nil
|
||||
}
|
||||
if err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region()}); err != nil {
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "BucketAlreadyOwnedByYou", "BucketAlreadyExists":
|
||||
return false, nil
|
||||
}
|
||||
return false, classify(err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) region() string {
|
||||
// minio-go keeps the region in an unexported field. Passing an empty
|
||||
// region lets it discover us-east-1 for SeaweedFS; the explicit region is
|
||||
// still set in the client options for signed requests.
|
||||
return ""
|
||||
}
|
||||
|
||||
// Probe writes, stats and removes a tiny object. It proves that the configured
|
||||
// credentials can actually use the private bucket without leaving test data.
|
||||
func (s *Store) Probe(ctx context.Context) error {
|
||||
const key = "_bootstrap/probe"
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
body := strings.NewReader("mtusi-lab4-bucket-probe")
|
||||
if _, err := s.client.PutObject(ctx, s.bucket, key, body, int64(body.Len()), minio.PutObjectOptions{
|
||||
ContentType: "text/plain",
|
||||
PartSize: 5 << 20,
|
||||
}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// classify converts an S3/SDK error into the two dependency classes the HTTP
|
||||
// layer understands. An access-denied or malformed-bucket error stays a plain
|
||||
// error and becomes a generic 500: it is a server configuration defect, not a
|
||||
// user error and not a transient outage.
|
||||
func classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
response := minio.ToErrorResponse(err)
|
||||
switch response.Code {
|
||||
case "NoSuchKey", "NoSuchObject", "NotFound":
|
||||
return ErrNotFound
|
||||
case "NoSuchBucket", "SlowDown", "InternalError", "ServiceUnavailable", "XMinioServerNotInitialized":
|
||||
return fmt.Errorf("%w: %s", ErrUnavailable, response.Code)
|
||||
}
|
||||
if response.StatusCode >= 500 {
|
||||
return fmt.Errorf("%w: HTTP %d", ErrUnavailable, response.StatusCode)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// Package session stores opaque server-side sessions in Valkey. The token is
|
||||
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
|
||||
// dump does not contain credentials that can be replayed against the API.
|
||||
//
|
||||
// Valkey is the source of truth for sessions. It is configured with AOF
|
||||
// persistence and a named volume, so valid sessions survive both the API
|
||||
// process and the Valkey process restarting with volumes kept.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/auth"
|
||||
)
|
||||
|
||||
const keyPrefix = "mtusi:lab3:session:"
|
||||
|
||||
var (
|
||||
// ErrInvalid means the token is unknown, expired or malformed.
|
||||
ErrInvalid = errors.New("invalid session")
|
||||
// ErrUnavailable means Valkey is not answering; the API must return a
|
||||
// bounded 503 instead of trusting the bearer token.
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// Options bound every network operation and the connection pool.
|
||||
type Options struct {
|
||||
PoolSize int
|
||||
DialTimeout time.Duration
|
||||
IOTimeout time.Duration
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// Store is a thin, timeout-aware wrapper around go-redis.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
|
||||
// It does not require Valkey to be reachable at startup: /health/ready and
|
||||
// login report the outage as 503.
|
||||
func Open(rawURL string, options Options) (*Store, error) {
|
||||
parsed, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
|
||||
}
|
||||
if options.PoolSize <= 0 {
|
||||
options.PoolSize = 8
|
||||
}
|
||||
if options.DialTimeout <= 0 {
|
||||
options.DialTimeout = 2 * time.Second
|
||||
}
|
||||
if options.IOTimeout <= 0 {
|
||||
options.IOTimeout = 2 * time.Second
|
||||
}
|
||||
if options.TTL <= 0 {
|
||||
options.TTL = time.Hour
|
||||
}
|
||||
parsed.PoolSize = options.PoolSize
|
||||
parsed.DialTimeout = options.DialTimeout
|
||||
parsed.ReadTimeout = options.IOTimeout
|
||||
parsed.WriteTimeout = options.IOTimeout
|
||||
// One retry keeps a transient blip invisible while bounding the worst-case
|
||||
// time a handler spends waiting for the cache.
|
||||
parsed.MaxRetries = 1
|
||||
parsed.MinRetryBackoff = 20 * time.Millisecond
|
||||
parsed.MaxRetryBackoff = 100 * time.Millisecond
|
||||
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
|
||||
}
|
||||
|
||||
// TTL exposes the configured session lifetime (used by tests and startup logs).
|
||||
func (s *Store) TTL() time.Duration { return s.ttl }
|
||||
|
||||
// Create issues a new opaque token and stores the session with a TTL. The
|
||||
// returned expiry is the absolute instant the client must treat as the end of
|
||||
// the session; restarting a process does not extend it.
|
||||
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
|
||||
token, err = auth.NewToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
// A whole number of microseconds keeps the value parseable by the
|
||||
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
|
||||
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
|
||||
}
|
||||
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Get resolves a token to a user id. Unknown, expired and corrupt records are
|
||||
// all ErrInvalid; a transport failure is ErrUnavailable.
|
||||
func (s *Store) Get(ctx context.Context, token string) (string, error) {
|
||||
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var value record
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if !value.ExpiresAt.After(time.Now()) {
|
||||
// TTL should already have removed the key; this also covers a clock
|
||||
// adjustment or an externally imported record.
|
||||
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return value.UserID, nil
|
||||
}
|
||||
|
||||
// Delete revokes the session. Missing keys are not an error here: the caller
|
||||
// has already authenticated the token, and a concurrent logout is harmless.
|
||||
func (s *Store) Delete(ctx context.Context, token string) error {
|
||||
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and the startup log.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close releases the connection pool.
|
||||
func (s *Store) Close() error { return s.client.Close() }
|
||||
|
||||
func key(tokenHash string) string { return keyPrefix + tokenHash }
|
||||
@@ -0,0 +1,184 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
)
|
||||
|
||||
// AttachmentRecord is the database view of an attachment. ObjectKey is an
|
||||
// internal server detail and is never serialised into the public API.
|
||||
type AttachmentRecord struct {
|
||||
model.Attachment
|
||||
ObjectKey string
|
||||
}
|
||||
|
||||
// ReconcileAttachment is the minimal row the offline reconciler needs. It is
|
||||
// intentionally not an API shape.
|
||||
type ReconcileAttachment struct {
|
||||
ID string
|
||||
ObjectKey string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// CreatePendingAttachment records the upload intent before the S3 PUT. If the
|
||||
// process dies after this insert, the row is still accounted for and the
|
||||
// reconciler can remove it after the grace period; it is never returned by the
|
||||
// public API because only ready rows are visible.
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, record AttachmentRecord, createdAt time.Time) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, object_key, created_at, updated_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5, $6, $7,
|
||||
'pending', NULL, $8, $9, $9)`,
|
||||
record.ID, record.ChatID, record.OwnerID, record.Filename,
|
||||
record.ContentType, record.SizeBytes, record.SHA256, record.ObjectKey, createdAt,
|
||||
)
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
// MarkAttachmentReady promotes the pending row after the original bytes are in
|
||||
// S3. If the update fails, the row stays pending and the object remains
|
||||
// accounted; the reconciler owns the cleanup. Nothing is deleted here because
|
||||
// an ambiguous commit must never destroy a successfully stored original.
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, id string, updatedAt time.Time) (time.Time, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = $2
|
||||
WHERE id = $1::uuid AND status = 'pending'
|
||||
RETURNING updated_at`, id, updatedAt).Scan(&stored)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, s.classify(err)
|
||||
}
|
||||
return stored.UTC(), nil
|
||||
}
|
||||
|
||||
// ReadyAttachmentForUser applies the ACL in SQL: the row is returned only when
|
||||
// the caller is a member of the attachment's chat and the attachment is ready.
|
||||
// A foreign and a nonexistent attachment are indistinguishable.
|
||||
func (s *Store) ReadyAttachmentForUser(ctx context.Context, attachmentID, userID string) (AttachmentRecord, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var record AttachmentRecord
|
||||
var createdAt, updatedAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename,
|
||||
a.content_type, a.size_bytes, a.sha256, a.status, a.error_code,
|
||||
a.object_key, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2::uuid
|
||||
WHERE a.id = $1::uuid AND a.status = 'ready'`,
|
||||
attachmentID, userID,
|
||||
).Scan(&record.ID, &record.ChatID, &record.OwnerID, &record.Filename,
|
||||
&record.ContentType, &record.SizeBytes, &record.SHA256, &record.Status, &record.ErrorCode,
|
||||
&record.ObjectKey, &createdAt, &updatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return AttachmentRecord{}, ErrNotFound
|
||||
}
|
||||
return AttachmentRecord{}, s.classify(err)
|
||||
}
|
||||
record.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
record.UpdatedAt = model.Time{Time: updatedAt.UTC()}
|
||||
record.Variants = []model.Variant{}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
// DeleteAttachmentRow removes a pending upload intent. It is used only after a
|
||||
// failed S3 PUT or by the reconciler; ready rows are never deleted here.
|
||||
func (s *Store) DeleteAttachmentRow(ctx context.Context, id string) error {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM attachments WHERE id = $1::uuid`, id)
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
// ListAttachmentsForReconcile returns every row, including internal pending
|
||||
// upload intents. Only the offline reconciler calls it.
|
||||
func (s *Store) ListAttachmentsForReconcile(ctx context.Context) ([]ReconcileAttachment, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id::text, object_key, status, created_at, updated_at
|
||||
FROM attachments
|
||||
ORDER BY created_at, id`)
|
||||
if err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]ReconcileAttachment, 0, 128)
|
||||
for rows.Next() {
|
||||
var item ReconcileAttachment
|
||||
if err := rows.Scan(&item.ID, &item.ObjectKey, &item.Status, &item.CreatedAt, &item.UpdatedAt); err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, s.classify(err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// AttachmentByObjectKey reports whether a row still references the key. The
|
||||
// reconciler re-checks this immediately before deleting an object, so a
|
||||
// concurrent upload that committed between the snapshot and the delete is not
|
||||
// destroyed.
|
||||
func (s *Store) AttachmentByObjectKey(ctx context.Context, key string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&exists); err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// AttachmentState re-reads the status and key before a mutation. A pending row
|
||||
// that became ready while the reconciler was scanning must not be deleted.
|
||||
func (s *Store) AttachmentState(ctx context.Context, id string) (string, string, time.Time, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
var status, objectKey string
|
||||
var updatedAt time.Time
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT status, object_key, updated_at FROM attachments WHERE id = $1::uuid`, id,
|
||||
).Scan(&status, &objectKey, &updatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, s.classify(err)
|
||||
}
|
||||
return status, objectKey, updatedAt.UTC(), nil
|
||||
}
|
||||
|
||||
// DeleteAttachmentIfPending deletes the row only while it is still pending.
|
||||
// The status predicate is the last line of defence against deleting a row that
|
||||
// a concurrent request has already promoted to ready.
|
||||
func (s *Store) DeleteAttachmentIfPending(ctx context.Context, id string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx,
|
||||
`DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`, id)
|
||||
if err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
// advisoryLockKey is a fixed application-wide key. pg_advisory_lock serialises
|
||||
// concurrent API replicas that start at the same time; it is released when the
|
||||
// dedicated connection is returned or the session ends.
|
||||
const advisoryLockKey int64 = 0x6d74756c616233 // "mtulab3"
|
||||
|
||||
type migration struct {
|
||||
version int
|
||||
name string
|
||||
checksum string
|
||||
sql string
|
||||
}
|
||||
|
||||
// Migrate applies every embedded migration exactly once and records its
|
||||
// checksum. Re-running it is a no-op, which is what the restart hook relies on.
|
||||
// A changed migration file is a startup error rather than a silent divergence.
|
||||
func (s *Store) Migrate(ctx context.Context) error {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer conn.Release()
|
||||
|
||||
if _, err := conn.Exec(ctx, `SELECT pg_advisory_lock($1)`, advisoryLockKey); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
defer func() {
|
||||
// Use a background context: the request context may already be
|
||||
// cancelled when a startup timeout fires, but the lock still has to be
|
||||
// released explicitly before the connection is returned to the pool.
|
||||
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, advisoryLockKey)
|
||||
}()
|
||||
|
||||
if _, err := conn.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version integer PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, item := range migrations {
|
||||
var existing string
|
||||
err := conn.QueryRow(ctx, `SELECT checksum FROM schema_migrations WHERE version = $1`, item.version).Scan(&existing)
|
||||
switch {
|
||||
case err == nil:
|
||||
if existing != item.checksum {
|
||||
return fmt.Errorf("migration %04d_%s was modified after it was applied", item.version, item.name)
|
||||
}
|
||||
continue
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return s.classify(err)
|
||||
}
|
||||
|
||||
tx, err := conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, item.sql); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return fmt.Errorf("apply migration %04d_%s: %w", item.version, item.name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO schema_migrations (version, name, checksum) VALUES ($1, $2, $3)`,
|
||||
item.version, item.name, item.checksum,
|
||||
); err != nil {
|
||||
_ = tx.Rollback(context.Background())
|
||||
return s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return s.classify(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]migration, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
name := entry.Name()
|
||||
if len(name) < 9 {
|
||||
return nil, fmt.Errorf("migration %q has no NNNN_ prefix", name)
|
||||
}
|
||||
version, err := strconv.Atoi(name[:4])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migration %q has no numeric prefix", name)
|
||||
}
|
||||
data, err := migrationFiles.ReadFile("migrations/" + name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
items = append(items, migration{
|
||||
version: version,
|
||||
name: strings.TrimSuffix(name[5:], ".sql"),
|
||||
checksum: hex.EncodeToString(sum[:]),
|
||||
sql: string(data),
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].version < items[j].version })
|
||||
for i := 1; i < len(items); i++ {
|
||||
if items[i].version == items[i-1].version {
|
||||
return nil, fmt.Errorf("duplicate migration version %d", items[i].version)
|
||||
}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadMigrations(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations: %v", err)
|
||||
}
|
||||
if len(migrations) != 5 {
|
||||
t.Fatalf("loaded %d migrations, want 5", len(migrations))
|
||||
}
|
||||
for index, item := range migrations {
|
||||
if item.version != index+1 {
|
||||
t.Fatalf("migration order at %d = %d", index, item.version)
|
||||
}
|
||||
}
|
||||
for _, item := range migrations {
|
||||
if len(item.checksum) != 64 {
|
||||
t.Fatalf("checksum for %d has length %d", item.version, len(item.checksum))
|
||||
}
|
||||
lower := strings.ToLower(item.sql)
|
||||
if !strings.Contains(lower, "create ") && !strings.Contains(lower, "alter ") {
|
||||
t.Fatalf("migration %d has no schema statements", item.version)
|
||||
}
|
||||
}
|
||||
// The checksum must be stable across process runs: it is what detects an
|
||||
// edited migration after it has been applied.
|
||||
again, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index := range migrations {
|
||||
if migrations[index].checksum != again[index].checksum {
|
||||
t.Fatal("migration checksums are not deterministic")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationsContainRequiredDomainObjects(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all := ""
|
||||
for _, item := range migrations {
|
||||
all += item.sql
|
||||
}
|
||||
for _, required := range []string{
|
||||
"CREATE TABLE users",
|
||||
"CREATE TABLE chats",
|
||||
"CREATE TABLE chat_members",
|
||||
"CREATE TABLE messages",
|
||||
"CREATE UNIQUE INDEX users_username_key",
|
||||
"messages_sender_membership_fk",
|
||||
"messages_chat_created_id_idx",
|
||||
"CREATE TABLE message_idempotency",
|
||||
"PRIMARY KEY (user_id, method, path, key)",
|
||||
"CREATE TABLE attachments",
|
||||
"CREATE TABLE message_attachments",
|
||||
"attachments_object_key_unique",
|
||||
"message_attachments_attachment_chat_fk",
|
||||
} {
|
||||
if !strings.Contains(all, required) {
|
||||
t.Fatalf("migrations do not contain %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Lab2 schema. PostgreSQL is the source of truth for users, chats, chat
|
||||
-- membership and messages. Sessions intentionally live in Valkey with a TTL.
|
||||
CREATE TABLE 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_format
|
||||
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_length
|
||||
CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_password_hash_present
|
||||
CHECK (length(password_hash) > 0)
|
||||
);
|
||||
|
||||
-- Uniqueness is enforced by the database, not by a read-then-insert check, so
|
||||
-- two concurrent registrations of the same username cannot both succeed.
|
||||
CREATE UNIQUE INDEX users_username_key ON users (username);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_length
|
||||
CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
|
||||
);
|
||||
|
||||
-- "Chats of the current user" walks chat_members by user_id.
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_chat_fk
|
||||
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
|
||||
-- The sender must be a member of the chat at the database level too, not
|
||||
-- only in the HTTP handler.
|
||||
CONSTRAINT messages_sender_membership_fk
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members (chat_id, user_id)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Indexes justified by the two keyset queries of the contract.
|
||||
--
|
||||
-- Message history:
|
||||
-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
-- ORDER BY created_at, id LIMIT $4
|
||||
-- The three-column index lets PostgreSQL start at the cursor position inside
|
||||
-- one chat instead of scanning the whole history for every page.
|
||||
CREATE INDEX messages_chat_created_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Chat list:
|
||||
-- ORDER BY created_at, id LIMIT $1
|
||||
-- after joining chat_members for the current user.
|
||||
CREATE INDEX chats_created_id_idx
|
||||
ON chats (created_at, id);
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Lab3: shared idempotency records for POST /api/v1/chats/{chat_id}/messages.
|
||||
--
|
||||
-- The primary key is exactly the contract scope: acting user + HTTP method +
|
||||
-- chat message path + Idempotency-Key. Different users or chats may reuse the
|
||||
-- same key independently. request_hash lets a replay distinguish the same
|
||||
-- semantic body (201 + original message) from a different body (409).
|
||||
--
|
||||
-- A row is written in the same transaction as the message it references, so a
|
||||
-- committed row always has a committed message and an aborted request leaves
|
||||
-- neither. created_at supports the 24-hour retention prune; contract requires
|
||||
-- at least 24 h, this stand prunes only records older than that bound.
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
method text NOT NULL,
|
||||
path text NOT NULL,
|
||||
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 DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, key),
|
||||
CONSTRAINT message_idempotency_method_post CHECK (method = 'POST'),
|
||||
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128),
|
||||
CONSTRAINT message_idempotency_path_length CHECK (char_length(path) BETWEEN 1 AND 256)
|
||||
);
|
||||
|
||||
-- Retention housekeeping walks old rows; new inserts stay cheap.
|
||||
CREATE INDEX message_idempotency_created_at_idx
|
||||
ON message_idempotency (created_at);
|
||||
@@ -0,0 +1,75 @@
|
||||
-- Lab4: attachment metadata lives in PostgreSQL; the original bytes live in
|
||||
-- the private S3 bucket. The only public state in the mandatory lab4 contract
|
||||
-- is ready. pending exists solely as an internal, server-side upload intent:
|
||||
-- it is written before the S3 PUT and promoted in the same request after the
|
||||
-- PUT. A crash or a database failure between the two steps therefore leaves an
|
||||
-- accounted row, never an anonymous object. The reconciler removes stale
|
||||
-- pending rows and their objects after a documented grace period.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
status text NOT NULL,
|
||||
error_code text,
|
||||
object_key text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL,
|
||||
CONSTRAINT attachments_filename_length
|
||||
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
|
||||
CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT attachments_status
|
||||
CHECK (status IN ('pending', 'ready')),
|
||||
CONSTRAINT attachments_ready_error
|
||||
CHECK ((status = 'ready' AND error_code IS NULL) OR status = 'pending'),
|
||||
CONSTRAINT attachments_object_key
|
||||
CHECK (object_key LIKE 'attachments/%'),
|
||||
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
|
||||
-- Referenced by the composite foreign key of message_attachments so the
|
||||
-- database itself rejects a link to an attachment of another chat.
|
||||
CONSTRAINT attachments_id_chat_unique UNIQUE (id, chat_id)
|
||||
);
|
||||
|
||||
-- The only attachment query on the hot path is "attachment of this chat".
|
||||
CREATE INDEX attachments_chat_created_idx
|
||||
ON attachments (chat_id, created_at, id);
|
||||
|
||||
-- The reconciler scans all rows by state and age. It never runs on the HTTP
|
||||
-- hot path.
|
||||
CREATE INDEX attachments_status_updated_idx
|
||||
ON attachments (status, updated_at);
|
||||
|
||||
-- messages.id is already the primary key; this unique constraint is the
|
||||
-- target required by the composite foreign keys below, not a second identity.
|
||||
-- It must exist before the foreign key that references (id, chat_id).
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
||||
|
||||
-- A message and its attachment links share one transaction. The composite
|
||||
-- foreign keys make "file of another chat" impossible at the database level
|
||||
-- even if a future handler forgets the application check.
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_unique UNIQUE (message_id, position),
|
||||
CONSTRAINT message_attachments_position_nonnegative CHECK (position >= 0),
|
||||
CONSTRAINT message_attachments_message_chat_fk
|
||||
FOREIGN KEY (message_id, chat_id) REFERENCES messages (id, chat_id) ON DELETE CASCADE,
|
||||
CONSTRAINT message_attachments_attachment_chat_fk
|
||||
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments (id, chat_id)
|
||||
);
|
||||
|
||||
-- Reconciler lookup: "is this object key still referenced by any row?".
|
||||
CREATE INDEX message_attachments_attachment_idx
|
||||
ON message_attachments (attachment_id);
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Lab4 contract: a message may carry text = "" when it references at least one
|
||||
-- attachment of the chat (contracts/README.md, "Вложения"). The HTTP handler
|
||||
-- still rejects empty or blank text without attachments; the database
|
||||
-- constraint only widens to permit the documented attachment-only message.
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_length;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_length
|
||||
CHECK (char_length(text) BETWEEN 0 AND 4000);
|
||||
@@ -0,0 +1,702 @@
|
||||
// Package store is the PostgreSQL repository. Every statement uses positional
|
||||
// parameters; identifiers are never interpolated into SQL. The pool is
|
||||
// bounded and every operation carries a context timeout.
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/puddle/v2"
|
||||
|
||||
"mtusi.ru/messenger-lab4/internal/cursor"
|
||||
"mtusi.ru/messenger-lab4/internal/model"
|
||||
"mtusi.ru/messenger-lab4/internal/uuid"
|
||||
)
|
||||
|
||||
// Domain errors. The HTTP layer maps them to the contract's status codes.
|
||||
var (
|
||||
ErrNotFound = errors.New("object not found")
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUnknownMember = errors.New("unknown chat member")
|
||||
ErrUnavailable = errors.New("database unavailable")
|
||||
ErrIdempotencyConflict = errors.New("idempotency key reused with a different request body")
|
||||
ErrAttachmentNotReady = errors.New("attachment is not ready")
|
||||
)
|
||||
|
||||
// Options bounds the pool and every query. Zero values fall back to safe
|
||||
// defaults so the store is still testable from small programs.
|
||||
type Options struct {
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
ConnectTimeout time.Duration
|
||||
StatementTimeout time.Duration
|
||||
QueryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Store owns a bounded pgx pool.
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
}
|
||||
|
||||
// Open parses the DSN and creates the pool. Parse errors deliberately do not
|
||||
// echo the DSN: it contains the database password.
|
||||
func Open(ctx context.Context, dsn string, options Options) (*Store, error) {
|
||||
config, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.New("DATABASE_URL is not a valid PostgreSQL URL")
|
||||
}
|
||||
applyDefaults(&options)
|
||||
config.MaxConns = options.MaxConns
|
||||
config.MinConns = options.MinConns
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = 30 * time.Second
|
||||
config.ConnConfig.ConnectTimeout = options.ConnectTimeout
|
||||
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab4"
|
||||
// A statement timeout in the server session is the last line of defence
|
||||
// against a runaway query; the caller's context is the first.
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(options.StatementTimeout.Milliseconds(), 10)
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||
}
|
||||
return &Store{pool: pool, queryTimeout: options.QueryTimeout}, nil
|
||||
}
|
||||
|
||||
func applyDefaults(options *Options) {
|
||||
if options.MaxConns <= 0 {
|
||||
options.MaxConns = 8
|
||||
}
|
||||
if options.MinConns < 0 {
|
||||
options.MinConns = 0
|
||||
}
|
||||
if options.MinConns > options.MaxConns {
|
||||
options.MinConns = options.MaxConns
|
||||
}
|
||||
if options.ConnectTimeout <= 0 {
|
||||
options.ConnectTimeout = 3 * time.Second
|
||||
}
|
||||
if options.StatementTimeout <= 0 {
|
||||
options.StatementTimeout = 3 * time.Second
|
||||
}
|
||||
if options.QueryTimeout <= 0 {
|
||||
options.QueryTimeout = 3 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and by the startup readiness loop.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
// Close waits for in-flight queries and closes the pool.
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
func (s *Store) opCtx(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.queryTimeout <= 0 {
|
||||
return ctx, func() {}
|
||||
}
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
|
||||
// classify separates a dependency outage (contract 503 unavailable) from a
|
||||
// genuine application bug (500 internal_error). Only the error class is mapped;
|
||||
// the original error is logged server-side and never sent to a client.
|
||||
func (s *Store) classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch {
|
||||
case strings.HasPrefix(pgErr.Code, "08"), // connection exception
|
||||
pgErr.Code == "57P01", // admin shutdown
|
||||
pgErr.Code == "57P02", // crash shutdown
|
||||
pgErr.Code == "57P03", // cannot connect now
|
||||
pgErr.Code == "57014", // query cancelled (statement_timeout)
|
||||
strings.HasPrefix(pgErr.Code, "53"): // insufficient resources
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if errors.Is(err, puddle.ErrClosedPool) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key"
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
func isIdempotencyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505" &&
|
||||
pgErr.ConstraintName == "message_idempotency_pkey"
|
||||
}
|
||||
|
||||
// CreateUser inserts a user and relies on the unique index for both ordinary
|
||||
// duplicates and concurrent registrations of the same username.
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
RETURNING created_at`,
|
||||
id, username, displayName, passwordHash, createdAt,
|
||||
).Scan(&stored)
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
return model.User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UserByUsername returns the public user and the Argon2id hash. The hash is
|
||||
// used only by the login handler and is never serialised.
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var passwordHash string
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, password_hash, created_at
|
||||
FROM users WHERE username = $1`, username,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &passwordHash, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrNotFound
|
||||
}
|
||||
return model.User{}, "", s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
// UserByID resolves the identity stored in a server-side session.
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user model.User
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users WHERE id = $1::uuid`, id,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &createdAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
return model.User{}, s.classify(err)
|
||||
}
|
||||
user.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateChat inserts the chat and its membership in one transaction. A caller
|
||||
// cannot observe a chat without members: either both are committed or neither.
|
||||
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []string, callerID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
var existing int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT count(*) FROM users
|
||||
WHERE id IN (SELECT value::uuid FROM unnest($1::text[]) AS value)`, memberIDs,
|
||||
).Scan(&existing); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if existing != len(memberIDs) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
createdAt := time.Now().UTC()
|
||||
var stored time.Time
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)
|
||||
RETURNING created_at`, id, title, createdAt,
|
||||
).Scan(&stored); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(`INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1::uuid, $2::uuid, $3)`,
|
||||
id, memberID, position)
|
||||
}
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
_ = results.Close()
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Chat{}, ErrUnknownMember
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
|
||||
return model.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: model.Time{Time: stored.UTC()},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// IsChatMember is used before parsing query parameters so a foreign chat is
|
||||
// always 404, independent of the submitted cursor or limit.
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var member bool
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1::uuid AND user_id = $2::uuid
|
||||
)`, chatID, userID).Scan(&member)
|
||||
if err != nil {
|
||||
return false, s.classify(err)
|
||||
}
|
||||
return member, nil
|
||||
}
|
||||
|
||||
// ChatForUser returns a chat only when the user is a member. A missing chat and
|
||||
// a foreign chat are indistinguishable to the caller.
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1::uuid
|
||||
GROUP BY c.id`, chatID, userID,
|
||||
).Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
return model.Chat{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatsPageSelect = `
|
||||
SELECT c.id::text, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1::uuid
|
||||
JOIN chat_members cm ON cm.chat_id = c.id`
|
||||
|
||||
// Chats returns one keyset page of chats visible to the user.
|
||||
func (s *Store) Chats(ctx context.Context, userID string, position *cursor.Cursor, limit int) (model.ChatPage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
query := chatsPageSelect + `
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2`
|
||||
args := []any{userID, limit + 1}
|
||||
if position != nil {
|
||||
query = chatsPageSelect + `
|
||||
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
GROUP BY c.id
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
args = []any{userID, position.At, position.ID, limit + 1}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Chat, 0, limit)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
chat.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, chat)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.ChatPage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.ChatPage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForChat(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// PoolStats is a point-in-time snapshot of the bounded pgx pool. It is used
|
||||
// only by the operator-only metrics listener, never by the public API.
|
||||
type PoolStats struct {
|
||||
MaxConns int32 `json:"max_conns"`
|
||||
TotalConns int32 `json:"total_conns"`
|
||||
AcquiredConns int32 `json:"acquired_conns"`
|
||||
IdleConns int32 `json:"idle_conns"`
|
||||
EmptyAcquireCount int64 `json:"empty_acquire_count"`
|
||||
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
|
||||
AcquireCount int64 `json:"acquire_count"`
|
||||
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
|
||||
NewConnsCount int64 `json:"new_conns_count"`
|
||||
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
|
||||
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
|
||||
}
|
||||
|
||||
// PoolStats reports saturation signals for the connection pool. EmptyAcquire
|
||||
// Count is the number of calls that had to wait for a free connection; a fast
|
||||
// rising value while the API CPU is below its limit points at the database or
|
||||
// the pool size, not at the HTTP layer.
|
||||
func (s *Store) PoolStats() PoolStats {
|
||||
stat := s.pool.Stat()
|
||||
return PoolStats{
|
||||
MaxConns: stat.MaxConns(),
|
||||
TotalConns: stat.TotalConns(),
|
||||
AcquiredConns: stat.AcquiredConns(),
|
||||
IdleConns: stat.IdleConns(),
|
||||
EmptyAcquireCount: stat.EmptyAcquireCount(),
|
||||
CanceledAcquireCount: stat.CanceledAcquireCount(),
|
||||
AcquireCount: stat.AcquireCount(),
|
||||
AcquireDurationMillis: stat.AcquireDuration().Milliseconds(),
|
||||
NewConnsCount: stat.NewConnsCount(),
|
||||
MaxLifetimeDestroyCount: stat.MaxLifetimeDestroyCount(),
|
||||
MaxIdleDestroyCount: stat.MaxIdleDestroyCount(),
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMessageIdempotent appends a message, its attachment links and the
|
||||
// idempotency result in one PostgreSQL transaction. A committed transaction
|
||||
// therefore always contains the message, every link and the key record; a
|
||||
// failed one contains none of them. The idempotency unique index serialises
|
||||
// concurrent replays: the loser blocks, then rolls back and reads the committed
|
||||
// winner, so a concurrent repeat can never create a second message.
|
||||
//
|
||||
// Behavior derived from contracts/README.md:
|
||||
// - a new (user, method, path, key) creates a message and its record, 201;
|
||||
// - the same semantic body replays the stored message and links, 201;
|
||||
// - a different body with the same key is a conflict, 409;
|
||||
// - a transient failure touches neither table, so the client may safely
|
||||
// retry the same key and never observe a duplicate side effect.
|
||||
func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string, attachmentIDs []string) (model.Message, bool, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
message := model.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
// A non-nil empty slice is required: the public Message schema has
|
||||
// attachment_ids: [] as an array, never null.
|
||||
AttachmentIDs: append([]string{}, attachmentIDs...),
|
||||
}
|
||||
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
|
||||
// Validate every attachment against the message chat before writing any
|
||||
// row. The composite foreign key is the second line of defence; this query
|
||||
// lets the handler distinguish "foreign/unknown" (404) from "not ready"
|
||||
// (409) without leaking whether a foreign attachment id exists.
|
||||
if len(attachmentIDs) > 0 {
|
||||
rows, queryErr := tx.Query(ctx, `
|
||||
SELECT id::text, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1::uuid
|
||||
AND id IN (SELECT value::uuid FROM unnest($2::text[]) AS value)`,
|
||||
chatID, attachmentIDs)
|
||||
if queryErr != nil {
|
||||
return model.Message{}, false, s.classify(queryErr)
|
||||
}
|
||||
statuses := make(map[string]string, len(attachmentIDs))
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if scanErr := rows.Scan(&id, &status); scanErr != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, false, s.classify(scanErr)
|
||||
}
|
||||
statuses[id] = status
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, false, s.classify(rows.Err())
|
||||
}
|
||||
rows.Close()
|
||||
if len(statuses) != len(attachmentIDs) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != "ready" {
|
||||
return model.Message{}, false, ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
created := time.Now().UTC()
|
||||
var stored time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
RETURNING created_at`,
|
||||
message.ID, chatID, senderID, text, created,
|
||||
).Scan(&stored)
|
||||
if err != nil {
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
|
||||
if len(attachmentIDs) > 0 {
|
||||
batch := &pgx.Batch{}
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
batch.Queue(`
|
||||
INSERT INTO message_attachments (message_id, attachment_id, chat_id, position)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4)`,
|
||||
message.ID, attachmentID, chatID, position)
|
||||
}
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
for range attachmentIDs {
|
||||
if _, execErr := results.Exec(); execErr != nil {
|
||||
_ = results.Close()
|
||||
if isForeignKeyViolation(execErr) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(execErr)
|
||||
}
|
||||
}
|
||||
if closeErr := results.Close(); closeErr != nil {
|
||||
if isForeignKeyViolation(closeErr) {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
return model.Message{}, false, s.classify(closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO message_idempotency
|
||||
(user_id, method, path, key, request_hash, message_id, created_at)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7)`,
|
||||
senderID, method, path, key, requestHash, message.ID, created)
|
||||
if err != nil {
|
||||
if isIdempotencyViolation(err) {
|
||||
// This transaction never committed. Roll it back explicitly before
|
||||
// reading the winner; PostgreSQL has already released the row lock
|
||||
// when it reported the unique violation.
|
||||
_ = tx.Rollback(ctx)
|
||||
storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key)
|
||||
if replayErr != nil {
|
||||
return model.Message{}, false, replayErr
|
||||
}
|
||||
if !found {
|
||||
return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable)
|
||||
}
|
||||
if !bytes.Equal(storedHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
return storedMessage, true, nil
|
||||
}
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, s.classify(err)
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: stored.UTC()}
|
||||
return message, false, nil
|
||||
}
|
||||
|
||||
func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) {
|
||||
var storedHash []byte
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT i.request_hash,
|
||||
m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
), '{}')
|
||||
FROM message_idempotency i
|
||||
JOIN messages m ON m.id = i.message_id
|
||||
WHERE i.user_id = $1::uuid AND i.method = $2 AND i.path = $3 AND i.key = $4`,
|
||||
userID, method, path, key,
|
||||
).Scan(&storedHash, &message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, model.Message{}, false, nil
|
||||
}
|
||||
return nil, model.Message{}, false, s.classify(err)
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []string{}
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
return storedHash, message, true, nil
|
||||
}
|
||||
|
||||
// PruneIdempotency removes records older than the contract's minimum
|
||||
// retention. It runs opportunistically from every replica; the statement is
|
||||
// safe to execute concurrently and is bounded to keep one delete short.
|
||||
func (s *Store) PruneIdempotency(ctx context.Context, olderThan time.Duration) (int64, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE ctid IN (
|
||||
SELECT ctid FROM message_idempotency
|
||||
WHERE created_at < now() - $1::interval
|
||||
LIMIT 500
|
||||
)`, fmt.Sprintf("%d seconds", int(olderThan.Seconds())))
|
||||
if err != nil {
|
||||
return 0, s.classify(err)
|
||||
}
|
||||
return tag.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const messagesPageSelect = `
|
||||
SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at,
|
||||
COALESCE((
|
||||
SELECT array_agg(ma.attachment_id::text ORDER BY ma.position)
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
), '{}')
|
||||
FROM (`
|
||||
|
||||
// Messages returns one keyset page of a chat history. The caller has already
|
||||
// verified membership; the query itself never loads the whole history.
|
||||
func (s *Store) Messages(ctx context.Context, chatID string, position *cursor.Cursor, limit int) (model.MessagePage, error) {
|
||||
ctx, cancel := s.opCtx(ctx)
|
||||
defer cancel()
|
||||
|
||||
where := `WHERE chat_id = $1::uuid`
|
||||
args := []any{chatID, limit + 1}
|
||||
order := `ORDER BY created_at, id
|
||||
LIMIT $2`
|
||||
if position != nil {
|
||||
where = `WHERE chat_id = $1::uuid
|
||||
AND (created_at, id) > ($2::timestamptz, $3::uuid)`
|
||||
args = []any{chatID, position.At, position.ID, limit + 1}
|
||||
order = `ORDER BY created_at, id
|
||||
LIMIT $4`
|
||||
}
|
||||
query := messagesPageSelect + `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
` + where + `
|
||||
` + order + `
|
||||
) m
|
||||
LEFT JOIN message_attachments ma ON ma.message_id = m.id
|
||||
GROUP BY m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
ORDER BY m.created_at, m.id`
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]model.Message, 0, limit)
|
||||
for rows.Next() {
|
||||
var message model.Message
|
||||
var createdAt time.Time
|
||||
if err := rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &message.AttachmentIDs); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
if message.AttachmentIDs == nil {
|
||||
message.AttachmentIDs = []string{}
|
||||
}
|
||||
message.CreatedAt = model.Time{Time: createdAt.UTC()}
|
||||
items = append(items, message)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.MessagePage{}, s.classify(err)
|
||||
}
|
||||
|
||||
page := model.MessagePage{Items: items}
|
||||
if len(items) > limit {
|
||||
page.Items = items[:limit]
|
||||
next := cursor.ForMessage(page.Items[len(page.Items)-1])
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Package uuid generates and normalizes canonical lowercase UUIDs. The
|
||||
// application, not PostgreSQL, assigns identifiers so every API replica and
|
||||
// the database agree on the exact on-the-wire form.
|
||||
package uuid
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
|
||||
// process cannot safely create identifiers, so panicking is intentional; the
|
||||
// HTTP layer turns it into a generic 500 response.
|
||||
func New() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("crypto/rand failed: " + err.Error())
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
||||
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
|
||||
return format(b)
|
||||
}
|
||||
|
||||
// NewRandom returns a lowercase hex string with n random bytes. It is used for
|
||||
// request ids and stable per-process instance ids, not for resource ids.
|
||||
func NewRandom(n int) string {
|
||||
raw := make([]byte, n)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
panic("crypto/rand failed: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func format(b [16]byte) string {
|
||||
var out [36]byte
|
||||
hex.Encode(out[0:8], b[0:4])
|
||||
out[8] = '-'
|
||||
hex.Encode(out[9:13], b[4:6])
|
||||
out[13] = '-'
|
||||
hex.Encode(out[14:18], b[6:8])
|
||||
out[18] = '-'
|
||||
hex.Encode(out[19:23], b[8:10])
|
||||
out[23] = '-'
|
||||
hex.Encode(out[24:36], b[10:16])
|
||||
return string(out[:])
|
||||
}
|
||||
|
||||
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
|
||||
// case-insensitive) and returns its lowercase representation. Braces, urn:
|
||||
// prefixes, SQL uuid spellings and other aliases are rejected so resource
|
||||
// identifiers have exactly one wire form.
|
||||
func Normalize(value string) (string, bool) {
|
||||
if len(value) != 36 {
|
||||
return "", false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
switch i {
|
||||
case 8, 13, 18, 23:
|
||||
if c != '-' {
|
||||
return "", false
|
||||
}
|
||||
default:
|
||||
if !isHex(c) {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.ToLower(value), true
|
||||
}
|
||||
|
||||
func isHex(c byte) bool {
|
||||
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package uuid
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewIsCanonicalV4(t *testing.T) {
|
||||
id := New()
|
||||
normalized, ok := Normalize(id)
|
||||
if !ok || normalized != id {
|
||||
t.Fatalf("New() returned non-canonical UUID %q", id)
|
||||
}
|
||||
if id[14] != '4' {
|
||||
t.Fatalf("version nibble = %c, want 4", id[14])
|
||||
}
|
||||
if id[19] != '8' && id[19] != '9' && id[19] != 'a' && id[19] != 'b' {
|
||||
t.Fatalf("variant nibble = %c, want 8/9/a/b", id[19])
|
||||
}
|
||||
if New() == New() {
|
||||
t.Fatal("two generated UUIDs are equal")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
valid := "11111111-2222-4333-8444-555555555555"
|
||||
if got, ok := Normalize(valid); !ok || got != valid {
|
||||
t.Fatalf("Normalize(%q) = %q, %v", valid, got, ok)
|
||||
}
|
||||
upper := "AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE"
|
||||
if got, ok := Normalize(upper); !ok || got != "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" {
|
||||
t.Fatalf("uppercase normalization failed: %q, %v", got, ok)
|
||||
}
|
||||
for _, invalid := range []string{
|
||||
"",
|
||||
"{11111111-2222-4333-8444-555555555555}",
|
||||
"urn:uuid:11111111-2222-4333-8444-555555555555",
|
||||
"11111111222243338444555555555555",
|
||||
"11111111-2222-4333-8444-55555555555z",
|
||||
"11111111-2222-4333-8444-5555555555555",
|
||||
" 1111111-2222-4333-8444-555555555555",
|
||||
} {
|
||||
if _, ok := Normalize(invalid); ok {
|
||||
t.Fatalf("Normalize accepted %q", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user