Implement lab4 private S3 attachments, safe reconciliation and defense guide

This commit is contained in:
2026-10-29 21:36:49 +03:00
parent ec540a1a72
commit 6039524214
61 changed files with 5029 additions and 23 deletions
+103
View File
@@ -0,0 +1,103 @@
package database
import (
"context"
"crypto/sha256"
"embed"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"os"
"sort"
"strconv"
"time"
)
//go:embed migrations/*.sql
var migrations embed.FS
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("invalid database configuration")
}
cfg.MaxConns = 10
if v := os.Getenv("DB_POOL_MAX"); v != "" {
n, e := strconv.Atoi(v)
if e != nil || n < 1 || n > 64 {
return nil, fmt.Errorf("DB_POOL_MAX must be 1..64")
}
cfg.MaxConns = int32(n)
}
cfg.MinConns = 0
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("cannot create database pool")
}
if err = pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("database unavailable")
}
return pool, nil
}
// All migrations and the version ledger commit together. An advisory lock also
// serializes bootstrap across API instances; edited applied migrations fail.
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil {
return err
}
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
return err
}
entries, err := migrations.ReadDir("migrations")
if err != nil {
return err
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, entry := range entries {
body, err := migrations.ReadFile("migrations/" + entry.Name())
if err != nil {
return err
}
checksum := fmt.Sprintf("%x", sha256.Sum256(body))
var stored string
rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name())
if err != nil {
return err
}
found := rows.Next()
if found {
err = rows.Scan(&stored)
}
if err == nil {
err = rows.Err()
}
rows.Close()
if err != nil {
return err
}
if found {
if stored != checksum {
return fmt.Errorf("applied migration changed: %s", entry.Name())
}
continue
}
if _, err = tx.Exec(ctx, string(body)); err != nil {
return err
}
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil {
return err
}
}
return tx.Commit(ctx)
}
@@ -0,0 +1,36 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id),
user_id uuid NOT NULL REFERENCES users(id),
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
sender_id uuid NOT NULL,
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL,
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
);
CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id);
CREATE INDEX chats_order_idx ON chats(created_at, id);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
user_id uuid NOT NULL REFERENCES users(id),
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
@@ -0,0 +1,10 @@
CREATE TABLE message_requests (
user_id uuid NOT NULL REFERENCES users(id),
chat_id uuid NOT NULL REFERENCES chats(id),
key text NOT NULL,
body_hash bytea NOT NULL,
response jsonb NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY(user_id,chat_id,key)
);
CREATE INDEX message_requests_expiry_idx ON message_requests(expires_at);
@@ -0,0 +1,29 @@
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CHECK(char_length(text) BETWEEN 0 AND 4000);
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename text NOT NULL,
object_key text NOT NULL UNIQUE,
content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')),
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages(id),
attachment_id uuid NOT NULL REFERENCES attachments(id),
position integer NOT NULL CHECK(position BETWEEN 0 AND 9),
PRIMARY KEY(message_id,attachment_id),
UNIQUE(message_id,position)
);
-- Durable upload journal is committed BEFORE PUT, so incomplete work remains
-- attributable after process termination. Final metadata + journal deletion
-- share one PG transaction, under the same per-key lock as the reconciler.
CREATE TABLE upload_intents (
object_key text PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
+273
View File
@@ -0,0 +1,273 @@
package messenger
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"os"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
const maxUpload = 10 << 20
const maxPixels = 40000000
type ObjectStore struct {
Client *minio.Client
Bucket string
}
func NewObjectStore(endpoint, bucket, access, secret string) (*ObjectStore, error) {
u, e := url.Parse(endpoint)
if e != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return nil, fmt.Errorf("invalid S3 endpoint")
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxConnsPerHost = 8
transport.ResponseHeaderTimeout = 5 * time.Second
client, e := minio.New(u.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https", Region: "us-east-1", Transport: transport, MaxRetries: 1})
if e != nil {
return nil, fmt.Errorf("invalid S3 configuration")
}
return &ObjectStore{client, bucket}, nil
}
func (o *ObjectStore) Ready(ctx context.Context) bool {
ok, e := o.Client.BucketExists(ctx, o.Bucket)
return e == nil && ok
}
func (s *Server) SetObjectStore(o *ObjectStore) { s.objects = o; s.uploads = make(chan struct{}, 1) }
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"`
Size int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
const attachmentColumns = `a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at,a.object_key`
func scanAttachment(row scanner) (Attachment, string, error) {
a := Attachment{Status: "ready", Variants: []any{}}
var c, u time.Time
var key string
e := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.Size, &a.SHA256, &c, &u, &key)
a.CreatedAt = stamp(c)
a.UpdatedAt = stamp(u)
return a, key, e
}
func validFilename(name string) bool {
if !validText(name, 255) {
return false
}
for _, c := range name {
if c == '/' || c == '\\' || unicode.IsControl(c) {
return false
}
}
return true
}
// A temporary capped spool avoids holding a compressed file in RAM; it is
// removed on every exit. DecodeConfig bounds pixels before full validation.
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request, uid, cid string) {
q, e := url.ParseQuery(r.URL.RawQuery)
if e != nil || len(q["filename"]) != 1 || !validFilename(q.Get("filename")) {
bad(w)
return
}
contentType, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
if e != nil || (contentType != "image/png" && contentType != "image/jpeg") {
fail(w, 415, "unsupported_media_type", "Expected PNG or JPEG")
return
}
if r.ContentLength > maxUpload {
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxUpload+1))
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
return
}
select {
case s.uploads <- struct{}{}:
defer func() { <-s.uploads }()
case <-r.Context().Done():
unavailable(w)
return
}
f, e := os.CreateTemp("", "messenger-upload-*")
if e != nil {
unavailable(w)
return
}
defer os.Remove(f.Name())
defer f.Close()
hash := sha256.New()
n, e := io.Copy(io.MultiWriter(f, hash), http.MaxBytesReader(w, r.Body, maxUpload))
if e != nil {
var over *http.MaxBytesError
if errors.As(e, &over) {
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
} else {
bad(w)
}
return
}
_, _ = f.Seek(0, io.SeekStart)
config, format, e := image.DecodeConfig(f)
if e != nil || "image/"+format != contentType {
fail(w, 415, "unsupported_media_type", "Invalid image or MIME mismatch")
return
}
if config.Width < 1 || config.Height < 1 || int64(config.Width)*int64(config.Height) > maxPixels {
fail(w, 413, "payload_too_large", "Maximum image is 40 million pixels")
return
}
_, _ = f.Seek(0, io.SeekStart)
if !validateImage(f) {
fail(w, 415, "unsupported_media_type", "Invalid image")
return
}
_, _ = f.Seek(0, io.SeekStart)
id := uuid()
key := "originals/" + id
ctx := r.Context()
// Journal survives a crash between PUT and metadata COMMIT.
if _, e = s.db.Exec(ctx, "INSERT INTO upload_intents(object_key) VALUES($1)", key); e != nil {
unavailable(w)
return
}
tx, e := s.db.Begin(ctx)
if e != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil {
unavailable(w)
return
}
// Disable multipart: the bounded spool is <=10MiB, hence one atomic object PUT.
_, e = s.objects.Client.PutObject(ctx, s.objects.Bucket, key, f, n, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
if e != nil {
unavailable(w)
return
}
a, _, e := scanAttachment(tx.QueryRow(ctx, `INSERT INTO attachments AS a(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING `+attachmentColumns, id, cid, uid, q.Get("filename"), key, contentType, n, hex.EncodeToString(hash.Sum(nil))))
if e != nil {
unavailable(w)
return
}
if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil {
unavailable(w)
return
}
if tx.Commit(ctx) != nil {
unavailable(w)
return
}
reply(w, 201, a)
}
func validateImage(r io.Reader) bool { _, _, e := image.Decode(r); return e == nil }
func (s *Server) serveAttachment(w http.ResponseWriter, r *http.Request, uid string, parts []string) {
if r.Method != "GET" || (len(parts) != 4 && len(parts) != 5) || (len(parts) == 5 && parts[4] != "content") {
missing(w)
return
}
id := strings.ToLower(parts[3])
if !uuidRE.MatchString(id) {
bad(w)
return
}
a, key, e := scanAttachment(s.db.QueryRow(r.Context(), `SELECT `+attachmentColumns+` FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, uid))
if errors.Is(e, pgx.ErrNoRows) {
missing(w)
return
}
if e != nil {
unavailable(w)
return
}
if len(parts) == 4 {
reply(w, 200, a)
return
}
q, e := url.ParseQuery(r.URL.RawQuery)
if e != nil || len(q["variant"]) > 1 {
bad(w)
return
}
variant := q.Get("variant")
if variant != "" && variant != "original" {
missing(w)
return
}
object, e := s.objects.Client.GetObject(r.Context(), s.objects.Bucket, key, minio.GetObjectOptions{})
if e != nil {
unavailable(w)
return
}
defer object.Close()
info, e := object.Stat()
if e != nil || info.Size != a.Size {
unavailable(w)
return
}
w.Header().Set("Content-Type", a.ContentType)
w.Header().Set("Content-Length", fmt.Sprint(a.Size))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
w.WriteHeader(200)
_, _ = io.Copy(w, object)
}
// Normalize optional attachments before hashing; JSON key ordering is irrelevant.
func parseMessage(w http.ResponseWriter, r *http.Request) (string, []string, bool) {
var in struct {
Text *string `json:"text"`
Attachments []string `json:"attachment_ids"`
}
// strict decoder accepts an explicitly optional field (suffix '?').
if !decode(w, r, &in, "text", "attachment_ids?") {
return "", nil, false
}
if in.Text == nil || !utf8.ValidString(*in.Text) || utf8.RuneCountInString(*in.Text) > 4000 || len(in.Attachments) > 10 || (strings.TrimSpace(*in.Text) == "" && len(in.Attachments) == 0) {
bad(w)
return "", nil, false
}
seen := map[string]bool{}
for i, id := range in.Attachments {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
bad(w)
return "", nil, false
}
seen[id] = true
in.Attachments[i] = id
}
if in.Attachments == nil {
in.Attachments = []string{}
}
return *in.Text, in.Attachments, true
}
+163
View File
@@ -0,0 +1,163 @@
package messenger
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mtusi/messenger/internal/database"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
)
// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests
// service. Local go test skips this test unless the DB secret path is supplied.
func TestDatabaseConcurrentHTTP(t *testing.T) {
path := os.Getenv("DATABASE_TEST_URL_FILE")
if path == "" {
t.Skip("run make test-race for real PostgreSQL HTTP integration")
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pool, err := database.Open(ctx, strings.TrimSpace(string(raw)))
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err = database.Migrate(ctx, pool); err != nil {
t.Fatal(err)
}
api := New(pool, nil, make([]byte, 32), 3600, nil)
ts := httptest.NewServer(api)
defer ts.Close()
call := func(method, path, body, auth string, status int) map[string]any {
t.Helper()
r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
if err != nil {
t.Error(err)
return nil
}
if body != "" {
r.Header.Set("Content-Type", "application/json")
}
r.Header.Set("Authorization", auth)
if method == "POST" && strings.HasSuffix(path, "/messages") {
r.Header.Set("Idempotency-Key", uuid())
}
response, err := ts.Client().Do(r)
if err != nil {
t.Error(err)
return nil
}
defer response.Body.Close()
b, err := io.ReadAll(response.Body)
if err != nil {
t.Error(err)
return nil
}
if response.StatusCode != status {
t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode)
return nil
}
var v map[string]any
if err = json.Unmarshal(b, &v); err != nil {
t.Error(err)
}
return v
}
username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20]
user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201)
if user == nil {
t.Fatal("create failed")
}
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123"))
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
if session == nil {
t.Fatal("login failed")
}
bearer := "Bearer " + session["token"].(string)
chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201)
if chat == nil {
t.Fatal("chat failed")
}
messages := "/api/v1/chats/" + chat["id"].(string) + "/messages"
var wg sync.WaitGroup
for worker := 0; worker < 10; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
for j := 0; j < 10; j++ {
call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201)
}
}(worker)
}
wg.Wait()
page := call("GET", messages+"?limit=100", "", bearer, 200)
if page == nil {
t.Fatal("history failed")
}
items := page["items"].([]any)
if len(items) != 100 {
t.Fatalf("expected 100 messages, got %d", len(items))
}
seen := map[string]bool{}
for _, v := range items {
m := v.(map[string]any)
id := m["id"].(string)
if seen[id] {
t.Fatal("duplicate ID")
}
seen[id] = true
}
// Race a single key through the real server, then verify only one side effect.
var repeatWG sync.WaitGroup
ids := make(chan string, 12)
for i := 0; i < 12; i++ {
repeatWG.Add(1)
go func() {
defer repeatWG.Done()
req, _ := http.NewRequest("POST", ts.URL+messages, strings.NewReader(`{"text":"one key"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", bearer)
req.Header.Set("Idempotency-Key", "same-concurrent-key")
res, err := ts.Client().Do(req)
if err != nil {
t.Error(err)
return
}
defer res.Body.Close()
var m Message
if res.StatusCode != 201 || json.NewDecoder(res.Body).Decode(&m) != nil {
t.Error("repeat failed")
return
}
ids <- m.ID
}()
}
repeatWG.Wait()
close(ids)
var expected string
for id := range ids {
if expected == "" {
expected = id
}
if id != expected {
t.Error("idempotency duplicate")
}
}
var count int
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id=$1", chat["id"]).Scan(&count); err != nil || count != 101 {
t.Errorf("want 101 persisted messages, got %d: %v", count, err)
}
t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled")
}
+33
View File
@@ -0,0 +1,33 @@
package messenger
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"golang.org/x/crypto/argon2"
"strings"
)
// Fixed, bounded parameters: 64 MiB, 3 passes, 2 lanes, 16-byte salt,
// 32-byte result. The HTTP layer bounds simultaneous KDF work to 2 calls.
func hashPassword(password string) string {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
panic(err)
}
hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
return "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash)
}
func verifyPassword(password, encoded string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || strings.Join(parts[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" {
return false
}
salt, e1 := base64.RawStdEncoding.DecodeString(parts[4])
want, e2 := base64.RawStdEncoding.DecodeString(parts[5])
if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 {
return false
}
got := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
return subtle.ConstantTimeCompare(got, want) == 1
}
+20
View File
@@ -0,0 +1,20 @@
package messenger
import (
"strings"
"testing"
)
func TestPasswordFullUnicodeRange(t *testing.T) {
password := strings.Repeat("🙂", 128) // 512 bytes: exceeds bcrypt's 72-byte limit.
hash := hashPassword(password)
if !verifyPassword(password, hash) || verifyPassword(password+"x", hash) {
t.Fatal("password mismatch")
}
if hash == hashPassword(password) {
t.Fatal("salt reused")
}
if verifyPassword(password, "$argon2id$v=19$m=999999999,t=3,p=2$abc$def") {
t.Fatal("unbounded parameters accepted")
}
}
+158
View File
@@ -0,0 +1,158 @@
package messenger
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
)
type ReconcileResult struct {
DryRun bool `json:"dry_run"`
GraceSeconds int `json:"grace_seconds"`
Scanned int `json:"scanned"`
Orphans int `json:"orphans"`
Missing int `json:"missing"`
StaleIntents int `json:"stale_intents"`
Fresh int `json:"fresh_protected"`
Referenced int `json:"referenced_protected"`
DeletedObjects int `json:"deleted_objects"`
DeletedMetadata int `json:"deleted_metadata"`
ClearedIntents int `json:"cleared_intents"`
DurationMS int64 `json:"duration_ms"`
}
func Reconcile(db *pgxpool.Pool, o *ObjectStore, args []string) error {
flags := flag.NewFlagSet("reconcile", flag.ContinueOnError)
apply := flags.Bool("apply", false, "apply safe deletions; default dry-run")
grace := flags.Int("grace-seconds", 3600, "minimum age (>=60s, greater than upload deadline)")
if e := flags.Parse(args); e != nil {
return e
}
if *grace < 60 {
return fmt.Errorf("grace must be at least 60 seconds")
}
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
result := ReconcileResult{DryRun: !*apply, GraceSeconds: *grace}
// Snapshot is only an inventory. Every candidate is rechecked under the SAME
// per-object transaction lock as upload; current rows and HEAD decide removal.
keys := map[string]bool{}
for object := range o.Client.ListObjects(ctx, o.Bucket, minio.ListObjectsOptions{Prefix: "originals/", Recursive: true}) {
if object.Err != nil {
return fmt.Errorf("S3 list failed")
}
keys[object.Key] = true
}
rows, e := db.Query(ctx, "SELECT object_key FROM attachments UNION SELECT object_key FROM upload_intents")
if e != nil {
return fmt.Errorf("inventory failed")
}
for rows.Next() {
var key string
if e = rows.Scan(&key); e != nil {
rows.Close()
return e
}
keys[key] = true
}
e = rows.Err()
rows.Close()
if e != nil {
return e
}
for key := range keys {
result.Scanned++
tx, e := db.Begin(ctx)
if e != nil {
return fmt.Errorf("reconcile transaction failed")
}
err := func() error {
defer tx.Rollback(context.Background())
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil {
return e
}
var id string
var metadataTime time.Time
// Lock against concurrent message attachment linkage/deletion.
rows, e := tx.Query(ctx, "SELECT id::text,created_at FROM attachments WHERE object_key=$1 FOR UPDATE", key)
if e != nil {
return e
}
hasMetadata := rows.Next()
if hasMetadata {
e = rows.Scan(&id, &metadataTime)
}
rows.Close()
if e != nil {
return e
}
var intentAge bool
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM upload_intents WHERE object_key=$1 AND created_at<=clock_timestamp()-make_interval(secs=>$2))", key, *grace).Scan(&intentAge); e != nil {
return e
}
var freshIntent bool
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM upload_intents WHERE object_key=$1 AND created_at>clock_timestamp()-make_interval(secs=>$2))", key, *grace).Scan(&freshIntent); e != nil {
return e
}
info, headErr := o.Client.StatObject(ctx, o.Bucket, key, minio.StatObjectOptions{})
exists := headErr == nil
if headErr != nil {
code := minio.ToErrorResponse(headErr).Code
if code != "NoSuchKey" && code != "NoSuchObject" && code != "NotFound" {
return fmt.Errorf("HEAD failed; no repair attempted")
}
}
fresh := freshIntent || (exists && time.Since(info.LastModified) < time.Duration(*grace)*time.Second) || (hasMetadata && time.Since(metadataTime) < time.Duration(*grace)*time.Second)
if fresh {
result.Fresh++
return tx.Commit(ctx)
}
if !hasMetadata && exists {
result.Orphans++
if *apply {
if e = o.Client.RemoveObject(ctx, o.Bucket, key, minio.RemoveObjectOptions{}); e != nil {
return e
}
result.DeletedObjects++
}
}
if hasMetadata && !exists {
result.Missing++
var referenced bool
if e = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM message_attachments WHERE attachment_id=$1)", id).Scan(&referenced); e != nil {
return e
}
if referenced {
result.Referenced++
} else if *apply {
if _, e = tx.Exec(ctx, "DELETE FROM attachments WHERE id=$1", id); e != nil {
return e
}
result.DeletedMetadata++
}
}
if intentAge {
result.StaleIntents++
if *apply {
if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil {
return e
}
result.ClearedIntents++
}
}
return tx.Commit(ctx)
}()
if err != nil {
return fmt.Errorf("reconcile failed safely: %w", err)
}
}
result.DurationMS = time.Since(start).Milliseconds()
return json.NewEncoder(os.Stdout).Encode(result)
}
+783
View File
@@ -0,0 +1,783 @@
// Package messenger implements the lab4 contract. PostgreSQL is authoritative.
package messenger
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"io"
"log/slog"
"mime"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type Message struct {
AttachmentIDs []string `json:"attachment_ids"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type Page[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func uuid() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
panic(err)
}
b[6] = (b[6] & 15) | 64
b[8] = (b[8] & 63) | 128
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func validText(v string, max int) bool {
return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max
}
func reply(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, status int, code, msg string) {
reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}})
}
func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") }
func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") }
// Decode exact object keys (encoding/json structs alone accept case variants).
// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well.
func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool {
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || media != "application/json" {
fail(w, 415, "unsupported_media_type", "Expected application/json")
return false
}
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
if _, ok := err.(*http.MaxBytesError); ok {
fail(w, 413, "payload_too_large", "Body exceeds 1 MiB")
} else {
bad(w)
}
return false
}
if !utf8.Valid(b) {
bad(w)
return false
}
d := json.NewDecoder(bytes.NewReader(b))
token, err := d.Token()
if err != nil || token != json.Delim('{') {
bad(w)
return false
}
allowed := map[string]bool{}
for _, f := range fields {
allowed[strings.TrimSuffix(f, "?")] = true
}
seen := map[string]bool{}
for d.More() {
t, e := d.Token()
k, ok := t.(string)
if e != nil || !ok || !allowed[k] || seen[k] {
bad(w)
return false
}
seen[k] = true
var raw json.RawMessage
if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) {
bad(w)
return false
}
}
if _, err = d.Token(); err != nil {
bad(w)
return false
}
if _, err = d.Token(); err != io.EOF {
bad(w)
return false
}
for _, f := range fields {
if !strings.HasSuffix(f, "?") && !seen[f] {
bad(w)
return false
}
}
if json.Unmarshal(b, dst) != nil {
bad(w)
return false
}
return true
}
type cursor struct {
Scope string `json:"scope"`
Time string `json:"time"`
ID string `json:"id"`
}
func (s *Server) encodeCursor(c cursor) *string {
b, _ := json.Marshal(c)
mac := hmac.New(sha256.New, s.secret)
mac.Write(b)
v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
return &v
}
func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) {
var c cursor
limit := 50
// ParseQuery explicitly reports malformed escaping, unlike URL.Query.
values, e := url.ParseQuery(r.URL.RawQuery)
if e != nil {
bad(w)
return 0, c, false
}
if v, ok := values["limit"]; ok {
if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" {
bad(w)
return 0, c, false
}
limit, e = strconv.Atoi(v[0])
if e != nil || limit < 1 || limit > 100 {
bad(w)
return 0, c, false
}
}
if v, ok := values["cursor"]; ok {
if len(v) != 1 || len(v[0]) > 2048 {
bad(w)
return 0, c, false
}
parts := strings.Split(v[0], ".")
if len(parts) != 2 {
bad(w)
return 0, c, false
}
b, e1 := base64.RawURLEncoding.DecodeString(parts[0])
sig, e2 := base64.RawURLEncoding.DecodeString(parts[1])
mac := hmac.New(sha256.New, s.secret)
mac.Write(b)
if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) {
bad(w)
return 0, c, false
}
}
if c.ID != "" {
if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil {
bad(w)
return 0, c, false
}
}
return limit, c, true
}
type Server struct {
db *pgxpool.Pool
cache *redis.Client
secret []byte
ttl int
log *slog.Logger
stopping atomic.Bool
kdf chan struct{}
objects *ObjectStore
uploads chan struct{}
instance string
dummyHash string
}
func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server {
hostname, _ := os.Hostname()
return &Server{instance: hostname, db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")}
}
func (s *Server) Stop() { s.stopping.Store(true) }
func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool {
select {
case s.kdf <- struct{}{}:
return true
case <-ctx.Done():
unavailable(w)
return false
}
}
func unavailable(w http.ResponseWriter) {
fail(w, 503, "unavailable", "Dependency temporarily unavailable")
}
func unauthorized(w http.ResponseWriter, scheme string) {
challenge := scheme + ` realm="messenger"`
if scheme == "Basic" {
challenge += `, charset="UTF-8"`
}
w.Header().Set("WWW-Authenticate", challenge)
fail(w, 401, "unauthorized", "Invalid or missing credentials")
}
func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
const userColumns = "id::text, username, display_name, created_at"
type scanner interface{ Scan(...any) error }
func scanUser(row scanner) (User, error) {
var u User
var t time.Time
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t)
u.CreatedAt = stamp(t)
return u, err
}
func scanMessage(row scanner) (Message, error) {
var m Message
var t time.Time
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t)
m.CreatedAt = stamp(t)
m.AttachmentIDs = []string{}
return m, err
}
func (s *Server) profile(ctx context.Context, uid string) (User, error) {
// Valkey caches ONLY immutable User JSON. Session validity is always read
// from PostgreSQL first; cache loss never permits anonymous access.
key := "profile:v1:" + uid
if s.cache != nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
raw, err := s.cache.Get(c, key).Bytes()
cancel()
var u User
if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid {
return u, nil
}
}
u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid))
if err != nil {
return u, err
}
if s.cache != nil {
raw, _ := json.Marshal(u)
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
_ = s.cache.Set(c, key, raw, 300*time.Second).Err()
cancel()
}
return u, nil
}
func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) {
parts := strings.Fields(r.Header.Get("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
unauthorized(w, "Bearer")
return User{}, nil, false
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil || len(raw) != 32 {
unauthorized(w, "Bearer")
return User{}, nil, false
}
digest := sha256.Sum256([]byte(parts[1]))
var uid string
err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid)
if errors.Is(err, pgx.ErrNoRows) {
unauthorized(w, "Bearer")
return User{}, nil, false
}
if err != nil {
unavailable(w)
return User{}, nil, false
}
u, err := s.profile(r.Context(), uid)
if err != nil {
unavailable(w)
return User{}, nil, false
}
return u, digest[:], true
}
type recorder struct {
http.ResponseWriter
status int
}
func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) }
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
out := &recorder{w, 200}
w = out
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Request-Id", uuid())
w.Header().Set("X-Instance-Id", s.instance)
budget := 3 * time.Second
if strings.Contains(r.URL.Path, "attachments") {
budget = 30 * time.Second
}
ctx, cancel := context.WithTimeout(r.Context(), budget)
defer cancel()
r = r.WithContext(ctx)
route := "unknown"
defer func() {
if recover() != nil {
fail(w, 500, "internal_error", "Internal server error")
}
if s.log != nil {
s.log.Info("request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id"))
}
}()
if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") {
route = r.URL.Path
if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil || (s.objects != nil && !s.objects.Ready(ctx))) {
unavailable(w)
} else {
reply(w, 200, map[string]string{"status": "ok"})
}
return
}
if s.stopping.Load() {
unavailable(w)
return
}
if r.Method == "POST" && r.URL.Path == "/api/v1/users" {
route = "/users"
s.createUser(w, r)
return
}
if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" {
route = "/auth/sessions"
s.login(w, r)
return
}
user, digest, ok := s.authenticate(w, r)
if !ok {
return
}
if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" {
route = "/auth/sessions/current"
tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest)
if err != nil {
unavailable(w)
} else if tag.RowsAffected() == 0 {
unauthorized(w, "Bearer")
} else {
w.WriteHeader(204)
}
return
}
if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" {
route = "/users/me"
reply(w, 200, user)
return
}
if r.URL.Path == "/api/v1/chats" {
route = "/chats"
switch r.Method {
case "POST":
s.createChat(w, r, user.ID)
case "GET":
s.listChats(w, r, user.ID)
default:
missing(w)
}
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && s.objects != nil {
route = "/attachments/{id}"
s.serveAttachment(w, r, user.ID, parts)
return
}
if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" {
missing(w)
return
}
cid := strings.ToLower(parts[3])
route = "/chats/{id}"
if !uuidRE.MatchString(cid) {
bad(w)
return
}
chat, err := s.getChat(ctx, cid, user.ID)
if errors.Is(err, pgx.ErrNoRows) {
missing(w)
return
}
if err != nil {
unavailable(w)
return
}
if len(parts) == 4 && r.Method == "GET" {
reply(w, 200, chat)
return
}
if len(parts) == 5 && parts[4] == "attachments" && r.Method == "POST" && s.objects != nil {
route = "/chats/{id}/attachments"
s.uploadAttachment(w, r, user.ID, cid)
return
}
if len(parts) == 5 && parts[4] == "messages" {
route = "/chats/{id}/messages"
switch r.Method {
case "POST":
s.createMessage(w, r, user.ID, cid)
case "GET":
s.listMessages(w, r, cid)
default:
missing(w)
}
return
}
missing(w)
}
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
var input struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if !decode(w, r, &input, "username", "display_name", "password") {
return
}
if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 {
bad(w)
return
}
if !s.acquireKDF(r.Context(), w) {
return
}
hash := hashPassword(input.Password)
<-s.kdf
u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash))
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
fail(w, 409, "conflict", "Username already exists")
return
}
if err != nil {
unavailable(w)
return
}
reply(w, 201, u)
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1))
if err != nil || len(body) != 0 {
bad(w)
return
}
username, password, ok := r.BasicAuth()
if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 {
unauthorized(w, "Basic")
return
}
var u User
var hash string
var t time.Time
err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash)
absent := errors.Is(err, pgx.ErrNoRows)
if err != nil && !absent {
unavailable(w)
return
}
if absent {
hash = s.dummyHash
}
if !s.acquireKDF(r.Context(), w) {
return
}
valid := verifyPassword(password, hash)
<-s.kdf
if !valid || absent {
unauthorized(w, "Basic")
return
}
raw := make([]byte, 32)
if _, err = rand.Read(raw); err != nil {
panic(err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
digest := sha256.Sum256([]byte(token))
var expires time.Time
err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires)
if err != nil {
unavailable(w)
return
}
u.CreatedAt = stamp(t)
reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u})
}
func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) {
var input struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if !decode(w, r, &input, "title", "member_ids") {
return
}
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
bad(w)
return
}
seen := map[string]bool{}
for i, id := range input.MemberIDs {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
bad(w)
return
}
seen[id] = true
input.MemberIDs[i] = id
}
if !seen[uid] {
bad(w)
return
}
tx, err := s.db.Begin(r.Context())
if err != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs}
var t time.Time
err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t)
if err != nil {
unavailable(w)
return
}
for _, id := range input.MemberIDs {
_, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id)
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == "23503" {
bad(w)
return
}
if err != nil {
unavailable(w)
return
}
}
if tx.Commit(r.Context()) != nil {
unavailable(w)
return
}
chat.CreatedAt = stamp(t)
reply(w, 201, chat)
}
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
func scanChat(row scanner) (Chat, error) {
var c Chat
var t time.Time
err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs)
c.CreatedAt = stamp(t)
return c, err
}
func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) {
return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid))
}
var idempotencyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) {
text, attachments, ok := parseMessage(w, r)
if !ok {
return
}
input := struct {
Text string `json:"text"`
Attachments []string `json:"attachment_ids"`
}{text, attachments}
keys := r.Header.Values("Idempotency-Key")
if len(keys) != 1 || !idempotencyRE.MatchString(keys[0]) {
bad(w)
return
}
body, _ := json.Marshal(input)
digest := sha256.Sum256(body)
ctx := r.Context()
tx, err := s.db.Begin(ctx)
if err != nil {
unavailable(w)
return
}
defer tx.Rollback(context.Background())
// Serialize only the same scope/key, across processes. Hash collisions only
// serialize unrelated requests; the full unique key still decides identity.
_, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", uid+":"+cid+":"+keys[0])
if err != nil {
unavailable(w)
return
}
var previous, saved []byte
err = tx.QueryRow(ctx, "SELECT body_hash,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()", uid, cid, keys[0]).Scan(&previous, &saved)
if err == nil {
if !bytes.Equal(previous, digest[:]) {
fail(w, 409, "conflict", "Key already used with another message")
return
}
if tx.Commit(ctx) != nil {
unavailable(w)
return
}
w.WriteHeader(201)
_, _ = w.Write(saved)
return
}
if !errors.Is(err, pgx.ErrNoRows) {
unavailable(w)
return
}
// A row lock prevents cleanup of an attachment while a message links it.
for _, id := range attachments {
var found string
err = tx.QueryRow(ctx, "SELECT id::text FROM attachments WHERE id=$1 AND chat_id=$2 FOR KEY SHARE", id, cid).Scan(&found)
if errors.Is(err, pgx.ErrNoRows) {
missing(w)
return
}
if err != nil {
unavailable(w)
return
}
}
var t time.Time
err = tx.QueryRow(ctx, "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t)
if err != nil {
unavailable(w)
return
}
m, err := scanMessage(tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t))
if err != nil {
unavailable(w)
return
}
m.AttachmentIDs = attachments
for i, id := range attachments {
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", m.ID, id, i); err != nil {
unavailable(w)
return
}
}
response, _ := json.Marshal(m)
_, err = tx.Exec(ctx, `INSERT INTO message_requests(user_id,chat_id,key,body_hash,response,expires_at) VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=EXCLUDED.body_hash,response=EXCLUDED.response,expires_at=EXCLUDED.expires_at`, uid, cid, keys[0], digest[:], response)
if err != nil || tx.Commit(ctx) != nil {
unavailable(w)
return
}
reply(w, 201, m)
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) {
scope := "messages:" + cid
limit, c, ok := s.pagination(w, r, scope)
if !ok {
return
}
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1`
args := []any{cid}
if c.ID != "" {
query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)`
args = append(args, c.Time, c.ID)
}
query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1)
args = append(args, limit+1)
rows, err := s.db.Query(r.Context(), query, args...)
if err != nil {
unavailable(w)
return
}
defer rows.Close()
items := []Message{}
for rows.Next() {
var m Message
var created time.Time
err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs)
m.CreatedAt = stamp(created)
if err != nil {
unavailable(w)
return
}
items = append(items, m)
}
if rows.Err() != nil {
unavailable(w)
return
}
var next *string
if len(items) > limit {
items = items[:limit]
last := items[limit-1]
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
}
reply(w, 200, Page[Message]{items, next})
}
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) {
scope := "chats:" + uid
limit, c, ok := s.pagination(w, r, scope)
if !ok {
return
}
query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1"
args := []any{uid}
if c.ID != "" {
query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)"
args = append(args, c.Time, c.ID)
}
query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1)
args = append(args, limit+1)
rows, err := s.db.Query(r.Context(), query, args...)
if err != nil {
unavailable(w)
return
}
defer rows.Close()
items := []Chat{}
for rows.Next() {
chat, err := scanChat(rows)
if err != nil {
unavailable(w)
return
}
items = append(items, chat)
}
if rows.Err() != nil {
unavailable(w)
return
}
var next *string
if len(items) > limit {
items = items[:limit]
last := items[limit-1]
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
}
reply(w, 200, Page[Chat]{items, next})
}