feat(lab4): MinIO S3 private bucket, streaming image validation, attachment endpoints, Grade 5 Track 2 reconciler

This commit is contained in:
2026-11-17 02:55:14 +03:00
parent ec540a1a72
commit eaf3963e05
33 changed files with 8458 additions and 21 deletions
+108
View File
@@ -0,0 +1,108 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime uint32 = 1
argonMemory uint32 = 19 * 1024 // 19 MiB (OWASP interactive recommendation)
argonThreads uint8 = 2
argonKeyLen uint32 = 32
argonSaltLen int = 16
)
var dummyHash string
func init() {
h, err := HashPassword("dummy-password-for-constant-time-check")
if err == nil {
dummyHash = h
}
}
// HashPassword hashes a UTF-8 password using Argon2id and returns a PHC-formatted string.
func HashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("failed to generate salt: %w", err)
}
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonTime, argonThreads, b64Salt, b64Hash)
return encoded, nil
}
// VerifyPassword compares a UTF-8 password against an Argon2id PHC string in constant time.
func VerifyPassword(password, encodedHash string) (bool, error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, errors.New("invalid argon2id hash format")
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
return false, err
}
var memory, timeCost uint32
var threads uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
return false, err
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, err
}
expectedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, err
}
computedHash := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(expectedHash)))
if subtle.ConstantTimeCompare(computedHash, expectedHash) == 1 {
return true, nil
}
return false, nil
}
// VerifyDummy runs an Argon2id verification against a dummy hash to prevent timing attacks on unknown usernames.
func VerifyDummy(password string) {
if dummyHash != "" {
_, _ = VerifyPassword(password, dummyHash)
}
}
// GenerateSessionToken generates an opaque 256-bit (32-byte) random token encoded as 64 hex chars,
// along with its SHA-256 hex digest for storage.
func GenerateSessionToken() (rawToken string, tokenHash string, err error) {
buf := make([]byte, 32) // 256 bits of entropy
if _, err := rand.Read(buf); err != nil {
return "", "", fmt.Errorf("failed to generate random token: %w", err)
}
rawToken = hex.EncodeToString(buf)
tokenHash = HashToken(rawToken)
return rawToken, tokenHash, nil
}
// HashToken returns the lowercase SHA-256 hex digest of an opaque session token.
func HashToken(rawToken string) string {
sum := sha256.Sum256([]byte(rawToken))
return hex.EncodeToString(sum[:])
}
+43
View File
@@ -0,0 +1,43 @@
package auth
import (
"strings"
"testing"
)
func TestHashAndVerifyPassword(t *testing.T) {
pw := "Сложный:Пароль:С:Двоеточиями:2026!🚀"
hash, err := HashPassword(pw)
if err != nil {
t.Fatalf("HashPassword failed: %v", err)
}
if !strings.HasPrefix(hash, "$argon2id$v=19$") {
t.Fatalf("expected Argon2id PHC prefix, got: %s", hash)
}
ok, err := VerifyPassword(pw, hash)
if err != nil || !ok {
t.Fatalf("expected password verification to succeed, err=%v, ok=%v", err, ok)
}
okWrong, err := VerifyPassword("WrongPassword-12345!", hash)
if err != nil || okWrong {
t.Fatalf("expected wrong password to fail verification")
}
}
func TestGenerateSessionToken(t *testing.T) {
raw, hash, err := GenerateSessionToken()
if err != nil {
t.Fatalf("GenerateSessionToken failed: %v", err)
}
if len(raw) != 64 {
t.Fatalf("expected 64-char hex raw token (256-bit), got len=%d", len(raw))
}
if len(hash) != 64 {
t.Fatalf("expected 64-char SHA-256 hex digest, got len=%d", len(hash))
}
if HashToken(raw) != hash {
t.Fatalf("HashToken mismatch")
}
}
+662
View File
@@ -0,0 +1,662 @@
package handler
import (
"context"
_ "embed"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/media"
"messenger/internal/model"
"messenger/internal/s3store"
"messenger/internal/store"
)
//go:embed openapi.json
var openAPISpec []byte
const swaggerUIHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MTUCI Messenger API (Lab 4) - Swagger UI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
<style>
body { margin: 0; background: #fafafa; }
.swagger-ui .topbar { display: none; }
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
window.onload = function() {
SwaggerUIBundle({
url: "/openapi.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout"
});
};
</script>
</body>
</html>`
type APIHandler struct {
store store.Store
s3 *s3store.Client
sessionTTL int
idempotencyTTL int
maxUploadBytes int64
maxImagePixels int64
instanceID string
draining atomic.Bool
}
func NewAPIHandler(st store.Store, s3 *s3store.Client, sessionTTL, idempotencyTTL int, maxUploadBytes, maxImagePixels int64, instanceID string) *APIHandler {
if sessionTTL <= 0 {
sessionTTL = 3600
}
if idempotencyTTL <= 0 {
idempotencyTTL = 86400
}
if maxUploadBytes <= 0 {
maxUploadBytes = 10 * 1024 * 1024
}
if maxImagePixels <= 0 {
maxImagePixels = 40_000_000
}
return &APIHandler{
store: st,
s3: s3,
sessionTTL: sessionTTL,
idempotencyTTL: idempotencyTTL,
maxUploadBytes: maxUploadBytes,
maxImagePixels: maxImagePixels,
instanceID: instanceID,
}
}
func (h *APIHandler) SetDraining(v bool) {
h.draining.Store(v)
}
func (h *APIHandler) IsDraining() bool {
return h.draining.Load()
}
func decodeJSON(r *http.Request, dst interface{}) error {
if r.Body == nil {
return errors.New("request body is missing")
}
defer r.Body.Close()
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
if errors.Is(err, io.EOF) {
return errors.New("request body is empty")
}
var unmarshalTypeError *json.UnmarshalTypeError
if errors.As(err, &unmarshalTypeError) {
return fmt.Errorf("field '%s' has incorrect type (expected %s)", unmarshalTypeError.Field, unmarshalTypeError.Type)
}
return fmt.Errorf("malformed JSON or unexpected field: %v", err)
}
if dec.More() {
return errors.New("request body contains multiple JSON values")
}
return nil
}
func writeStoreError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, store.ErrConflict):
WriteError(w, r, http.StatusConflict, "conflict", "resource conflict")
case errors.Is(err, store.ErrNotFound):
WriteError(w, r, http.StatusNotFound, "not_found", "resource not found or access denied")
case errors.Is(err, store.ErrUnauthorized):
WriteBearerUnauthorized(w, r, "unauthorized")
case errors.Is(err, store.ErrUnavailable):
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
case errors.Is(err, store.ErrBadRequest):
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
default:
WriteError(w, r, http.StatusInternalServerError, "internal_error", "internal server error")
}
}
func (h *APIHandler) HandleLiveness(w http.ResponseWriter, r *http.Request) {
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
}
func (h *APIHandler) HandleReadiness(w http.ResponseWriter, r *http.Request) {
if h.IsDraining() {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "instance is draining")
return
}
if err := h.store.Ready(r.Context()); err != nil {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "database dependency is not ready")
return
}
if h.s3 == nil || h.s3.Ready(r.Context()) != nil {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "object storage dependency is not ready")
return
}
WriteJSON(w, r, http.StatusOK, model.HealthResponse{Status: "ok"})
}
func (h *APIHandler) HandleRegisterUser(w http.ResponseWriter, r *http.Request) {
var req model.CreateUserRequest
if err := decodeJSON(r, &req); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
return
}
user, err := h.store.CreateUser(r.Context(), req)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusCreated, user)
}
func (h *APIHandler) HandleCreateSession(w http.ResponseWriter, r *http.Request) {
// Contract: POST /auth/sessions accepts ONLY Authorization: Basic <base64(username:password)>, without JSON body.
if r.Body != nil {
defer r.Body.Close()
var buf [1]byte
n, _ := r.Body.Read(buf[:])
if n > 0 {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "POST /api/v1/auth/sessions must not include a request body")
return
}
}
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
if authHeader == "" {
WriteBasicUnauthorized(w, r, "invalid credentials")
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Basic") {
WriteBasicUnauthorized(w, r, "invalid credentials")
return
}
b64Payload := strings.TrimSpace(parts[1])
decoded, err := base64.StdEncoding.DecodeString(b64Payload)
if err != nil || !utf8.Valid(decoded) {
WriteBasicUnauthorized(w, r, "invalid credentials")
return
}
credParts := strings.SplitN(string(decoded), ":", 2)
if len(credParts) != 2 {
WriteBasicUnauthorized(w, r, "invalid credentials")
return
}
username := credParts[0]
password := credParts[1]
sess, err := h.store.AuthenticateAndCreateSession(r.Context(), username, password, h.sessionTTL)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
return
}
WriteBasicUnauthorized(w, r, "invalid credentials")
return
}
WriteJSON(w, r, http.StatusCreated, sess)
}
func (h *APIHandler) HandleRevokeSession(w http.ResponseWriter, r *http.Request) {
rawToken := GetAuthToken(r.Context())
if rawToken == "" {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
if err := h.store.RevokeSession(r.Context(), rawToken); err != nil {
if errors.Is(err, store.ErrUnavailable) {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
return
}
WriteBearerUnauthorized(w, r, "session already revoked or expired")
return
}
reqID := GetRequestID(r.Context())
w.Header().Set("X-Request-Id", reqID)
w.WriteHeader(http.StatusNoContent)
}
func (h *APIHandler) HandleCurrentUser(w http.ResponseWriter, r *http.Request) {
user := GetAuthUser(r.Context())
if user == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
WriteJSON(w, r, http.StatusOK, user)
}
func (h *APIHandler) HandleCreateChat(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
var req model.CreateChatRequest
if err := decodeJSON(r, &req); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
return
}
chat, err := h.store.CreateChat(r.Context(), caller.ID, req)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusCreated, chat)
}
func (h *APIHandler) HandleListChats(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
limit := 50
limitStr := r.URL.Query().Get("limit")
if limitStr != "" {
l, err := strconv.Atoi(limitStr)
if err != nil || l < 1 || l > 100 {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
return
}
limit = l
}
cursor := r.URL.Query().Get("cursor")
page, err := h.store.ListChats(r.Context(), caller.ID, limit, cursor)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusOK, page)
}
func (h *APIHandler) HandleGetChat(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
return
}
chat, err := h.store.GetChat(r.Context(), caller.ID, chatID)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusOK, chat)
}
func (h *APIHandler) HandleCreateMessage(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
return
}
idemKey := r.Header.Get("Idempotency-Key")
if !store.IdempotencyKeyRegex.MatchString(idemKey) {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "Idempotency-Key header is required and must match ^[A-Za-z0-9._:-]{1,128}$")
return
}
var req model.CreateMessageRequest
if err := decodeJSON(r, &req); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", err.Error())
return
}
msg, err := h.store.CreateMessage(r.Context(), caller.ID, chatID, idemKey, h.idempotencyTTL, req)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusCreated, msg)
}
func (h *APIHandler) HandleListMessages(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
return
}
limit := 50
limitStr := r.URL.Query().Get("limit")
if limitStr != "" {
l, err := strconv.Atoi(limitStr)
if err != nil || l < 1 || l > 100 {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "limit must be an integer between 1 and 100")
return
}
limit = l
}
cursor := r.URL.Query().Get("cursor")
page, err := h.store.ListMessages(r.Context(), caller.ID, chatID, limit, cursor)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusOK, page)
}
func (h *APIHandler) HandleInternalStats(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("reset") == "1" {
h.store.ResetStats()
}
if mode := r.URL.Query().Get("mode"); mode != "" {
h.store.SetCacheMode(mode)
}
WriteJSON(w, r, http.StatusOK, h.store.Stats(r.Context()))
}
func (h *APIHandler) HandleOpenAPISpec(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(openAPISpec)
}
func (h *APIHandler) HandleSwaggerUI(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(swaggerUIHTML))
}
func (h *APIHandler) HandleNotFound(w http.ResponseWriter, r *http.Request) {
WriteError(w, r, http.StatusNotFound, "not_found", fmt.Sprintf("route %s %s not found", r.Method, r.URL.Path))
}
func validateFilename(name string) bool {
if strings.TrimSpace(name) == "" {
return false
}
n := utf8.RuneCountInString(name)
if n < 1 || n > 255 {
return false
}
for _, r := range name {
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
return false
}
}
return true
}
func (h *APIHandler) HandleUploadAttachment(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id UUID")
return
}
filename := r.URL.Query().Get("filename")
if !validateFilename(filename) {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing filename")
return
}
contentTypeHeader := r.Header.Get("Content-Type")
if _, err := media.ParseAllowedContentType(contentTypeHeader); err != nil {
WriteError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be image/png or image/jpeg")
return
}
if r.ContentLength > h.maxUploadBytes {
WriteError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "upload exceeds maximum allowed byte size")
return
}
// Enforce chat membership BEFORE spooling bytes or touching S3
isMember, err := h.store.IsChatMember(r.Context(), caller.ID, chatID)
if err != nil {
writeStoreError(w, r, err)
return
}
if !isMember {
WriteError(w, r, http.StatusNotFound, "not_found", "resource not found or access denied")
return
}
if h.s3 == nil {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "object storage dependency is unavailable")
return
}
r.Body = http.MaxBytesReader(w, r.Body, h.maxUploadBytes+1024)
img, err := media.ValidateAndSpoolImage(r.Body, contentTypeHeader, h.maxUploadBytes, h.maxImagePixels)
if err != nil {
switch {
case errors.Is(err, media.ErrPayloadTooLarge):
WriteError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image exceeds byte or pixel limit")
case errors.Is(err, media.ErrUnsupportedMediaType):
WriteError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "payload is not a valid PNG or JPEG image matching Content-Type")
default:
WriteError(w, r, http.StatusBadRequest, "invalid_request", "failed to read upload stream")
}
return
}
defer img.Cleanup()
attID := uuid.New().String()
objectKey := fmt.Sprintf("attachments/%s/%s", chatID, attID)
if err := h.s3.PutObject(r.Context(), objectKey, img.File, img.SizeBytes, img.ContentType); err != nil {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "object storage temporarily unavailable")
return
}
att, err := h.store.CreateAttachment(r.Context(), model.Attachment{
ID: attID,
ChatID: chatID,
OwnerID: caller.ID,
Filename: filename,
ContentType: img.ContentType,
SizeBytes: img.SizeBytes,
SHA256: img.SHA256,
ObjectKey: objectKey,
})
if err != nil {
// Immediate synchronous compensation: delete the unreferenced S3 object if DB commit failed.
compCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = h.s3.RemoveObject(compCtx, objectKey)
cancel()
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusCreated, att)
}
func (h *APIHandler) HandleGetAttachment(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
attID := r.PathValue("attachment_id")
if _, err := uuid.Parse(attID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id UUID")
return
}
att, err := h.store.GetAttachment(r.Context(), caller.ID, attID)
if err != nil {
writeStoreError(w, r, err)
return
}
WriteJSON(w, r, http.StatusOK, att)
}
func (h *APIHandler) HandleDownloadAttachmentContent(w http.ResponseWriter, r *http.Request) {
caller := GetAuthUser(r.Context())
if caller == nil {
WriteBearerUnauthorized(w, r, "unauthenticated")
return
}
attID := r.PathValue("attachment_id")
if _, err := uuid.Parse(attID); err != nil {
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id UUID")
return
}
variant := r.URL.Query().Get("variant")
if variant != "" && variant != "original" {
if variant == "thumbnail" || variant == "crop" || variant == "optimized" {
WriteError(w, r, http.StatusNotFound, "not_found", "requested variant does not exist")
return
}
WriteError(w, r, http.StatusBadRequest, "invalid_request", "invalid variant query parameter")
return
}
att, err := h.store.GetAttachment(r.Context(), caller.ID, attID)
if err != nil {
writeStoreError(w, r, err)
return
}
if att.Status != "ready" {
WriteError(w, r, http.StatusConflict, "conflict", "attachment is not ready for download")
return
}
if h.s3 == nil {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "object storage temporarily unavailable")
return
}
obj, objSize, err := h.s3.GetObject(r.Context(), att.ObjectKey)
if err != nil {
if errors.Is(err, s3store.ErrObjectNotFound) {
WriteError(w, r, http.StatusConflict, "conflict", "attachment binary object is unavailable")
return
}
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "object storage temporarily unavailable")
return
}
defer obj.Close()
w.Header().Set("Content-Type", att.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(objSize, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Request-Id", GetRequestID(r.Context()))
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, obj)
}
func RegisterRoutes(st store.Store, s3 *s3store.Client, sessionTTL, idempotencyTTL int, maxUploadBytes, maxImagePixels int64, instanceID string) (http.Handler, *APIHandler) {
api := NewAPIHandler(st, s3, sessionTTL, idempotencyTTL, maxUploadBytes, maxImagePixels, instanceID)
mux := http.NewServeMux()
// Documentation & schema
mux.HandleFunc("GET /docs", api.HandleSwaggerUI)
mux.HandleFunc("GET /docs/", api.HandleSwaggerUI)
mux.HandleFunc("GET /openapi.json", api.HandleOpenAPISpec)
// Internal diagnostics for experiments
mux.HandleFunc("GET /internal/stats", api.HandleInternalStats)
mux.HandleFunc("POST /internal/stats", api.HandleInternalStats)
// Public routes
mux.HandleFunc("GET /health/live", api.HandleLiveness)
mux.HandleFunc("GET /health/ready", api.HandleReadiness)
mux.HandleFunc("POST /api/v1/users", api.HandleRegisterUser)
mux.HandleFunc("POST /api/v1/auth/sessions", api.HandleCreateSession)
// Protected Bearer routes
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", RequireBearerAuth(st, api.HandleRevokeSession))
mux.HandleFunc("GET /api/v1/users/me", RequireBearerAuth(st, api.HandleCurrentUser))
mux.HandleFunc("POST /api/v1/chats", RequireBearerAuth(st, api.HandleCreateChat))
mux.HandleFunc("GET /api/v1/chats", RequireBearerAuth(st, api.HandleListChats))
mux.HandleFunc("GET /api/v1/chats/{chat_id}", RequireBearerAuth(st, api.HandleGetChat))
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleCreateMessage))
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", RequireBearerAuth(st, api.HandleListMessages))
mux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", RequireBearerAuth(st, api.HandleUploadAttachment))
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}", RequireBearerAuth(st, api.HandleGetAttachment))
mux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", RequireBearerAuth(st, api.HandleDownloadAttachmentContent))
// Fallback 404 handler
mux.HandleFunc("/", api.HandleNotFound)
var handler http.Handler = mux
handler = LoggingMiddleware(instanceID, handler)
handler = RequestIDMiddleware(handler)
handler = InstanceIDMiddleware(instanceID, handler)
return handler, api
}
+168
View File
@@ -0,0 +1,168 @@
package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/google/uuid"
"messenger/internal/model"
"messenger/internal/store"
)
type contextKey string
const (
requestIDContextKey contextKey = "request_id"
userContextKey contextKey = "user"
tokenContextKey contextKey = "token"
)
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func InstanceIDMiddleware(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", instanceID)
next.ServeHTTP(w, r)
})
}
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := strings.TrimSpace(r.Header.Get("X-Request-Id"))
if reqID == "" {
reqID = uuid.New().String()
}
w.Header().Set("X-Request-Id", reqID)
ctx := context.WithValue(r.Context(), requestIDContextKey, reqID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func LoggingMiddleware(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &loggingResponseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(lrw, r)
reqID, _ := r.Context().Value(requestIDContextKey).(string)
duration := time.Since(start)
logEntry := map[string]interface{}{
"time": time.Now().UTC().Format(time.RFC3339Nano),
"instance_id": instanceID,
"method": r.Method,
"path": r.URL.Path,
"status": lrw.statusCode,
"duration_ms": float64(duration.Microseconds()) / 1000.0,
"request_id": reqID,
"remote_ip": r.RemoteAddr,
}
logBytes, _ := json.Marshal(logEntry)
fmt.Fprintln(os.Stdout, string(logBytes))
})
}
func GetRequestID(ctx context.Context) string {
if val, ok := ctx.Value(requestIDContextKey).(string); ok && val != "" {
return val
}
return uuid.New().String()
}
func WriteError(w http.ResponseWriter, r *http.Request, status int, code, message string) {
reqID := GetRequestID(r.Context())
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Request-Id", reqID)
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(model.ErrorResponse{
Error: model.ErrorDetail{
Code: code,
Message: message,
RequestID: reqID,
},
})
}
func WriteBasicUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
}
func WriteBearerUnauthorized(w http.ResponseWriter, r *http.Request, message string) {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
WriteError(w, r, http.StatusUnauthorized, "unauthorized", message)
}
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, data interface{}) {
reqID := GetRequestID(r.Context())
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Request-Id", reqID)
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(data)
}
func RequireBearerAuth(st store.Store, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Note: X-User-Id is intentionally ignored in Lab 2+ per contract.
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
if authHeader == "" {
WriteBearerUnauthorized(w, r, "missing Authorization header")
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
WriteBearerUnauthorized(w, r, "Bearer authentication required")
return
}
rawToken := strings.TrimSpace(parts[1])
if rawToken == "" || strings.ContainsAny(rawToken, " \t\r\n") {
WriteBearerUnauthorized(w, r, "invalid Bearer token")
return
}
user, err := st.GetUserByToken(r.Context(), rawToken)
if err != nil {
if errors.Is(err, store.ErrUnavailable) {
WriteError(w, r, http.StatusServiceUnavailable, "unavailable", "storage dependency is temporarily unavailable")
return
}
WriteBearerUnauthorized(w, r, "invalid, expired, or revoked session token")
return
}
ctx := context.WithValue(r.Context(), userContextKey, user)
ctx = context.WithValue(ctx, tokenContextKey, rawToken)
next(w, r.WithContext(ctx))
}
}
func GetAuthUser(ctx context.Context) *model.User {
if user, ok := ctx.Value(userContextKey).(*model.User); ok {
return user
}
return nil
}
func GetAuthToken(ctx context.Context) string {
if tok, ok := ctx.Value(tokenContextKey).(string); ok {
return tok
}
return ""
}
File diff suppressed because it is too large Load Diff
+314
View File
@@ -0,0 +1,314 @@
package media
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"hash/crc32"
"image"
"image/jpeg"
"image/png"
"io"
"mime"
"net/http"
"os"
"strings"
)
var (
ErrPayloadTooLarge = errors.New("payload too large")
ErrUnsupportedMediaType = errors.New("unsupported or corrupted media")
ErrBadFilename = errors.New("invalid filename")
)
var pngSignature = []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}
type ValidatedImage struct {
File *os.File
SizeBytes int64
SHA256 string
ContentType string
Width int
Height int
}
func (v *ValidatedImage) Cleanup() {
if v != nil && v.File != nil {
name := v.File.Name()
_ = v.File.Close()
_ = os.Remove(name)
v.File = nil
}
}
func ParseAllowedContentType(headerVal string) (string, error) {
mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(headerVal))
if err != nil {
return "", ErrUnsupportedMediaType
}
mediaType = strings.ToLower(mediaType)
if mediaType != "image/png" && mediaType != "image/jpeg" {
return "", ErrUnsupportedMediaType
}
return mediaType, nil
}
// ValidateAndSpoolImage streams upload bytes into an ephemeral temp file while enforcing
// maxBytes, verifying magic bytes against declared Content-Type, checking pixel limits
// before bitmap allocation, and checking PNG/JPEG container integrity in bounded RAM.
func ValidateAndSpoolImage(r io.Reader, declaredContentType string, maxBytes int64, maxPixels int64) (*ValidatedImage, error) {
ct, err := ParseAllowedContentType(declaredContentType)
if err != nil {
return nil, err
}
if maxBytes <= 0 {
maxBytes = 10 * 1024 * 1024
}
if maxPixels <= 0 {
maxPixels = 40_000_000
}
tmpFile, err := os.CreateTemp("", "lab4-upload-*")
if err != nil {
return nil, fmt.Errorf("create temp spool file: %w", err)
}
cleanupTmp := true
defer func() {
if cleanupTmp && tmpFile != nil {
name := tmpFile.Name()
_ = tmpFile.Close()
_ = os.Remove(name)
}
}()
hasher := sha256.New()
buf := make([]byte, 32*1024)
n, err := io.CopyBuffer(io.MultiWriter(tmpFile, hasher), io.LimitReader(r, maxBytes+1), buf)
if err != nil {
return nil, ErrBadFilename
}
if n == 0 {
return nil, ErrUnsupportedMediaType
}
if n > maxBytes {
return nil, ErrPayloadTooLarge
}
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
// Verify content magic bytes match declared Content-Type (prevents MIME spoofing).
head := make([]byte, 512)
headLen, _ := io.ReadFull(tmpFile, head)
if headLen == 0 {
return nil, ErrUnsupportedMediaType
}
sniffed := http.DetectContentType(head[:headLen])
if ct == "image/png" {
if headLen < len(pngSignature) || !bytes.Equal(head[:8], pngSignature) || sniffed != "image/png" {
return nil, ErrUnsupportedMediaType
}
} else {
if headLen < 3 || head[0] != 0xff || head[1] != 0xd8 || head[2] != 0xff || sniffed != "image/jpeg" {
return nil, ErrUnsupportedMediaType
}
}
// Parse image header BEFORE full pixel decode to prevent decompression-bomb OOMs.
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
cfg, format, err := image.DecodeConfig(tmpFile)
if err != nil {
return nil, ErrUnsupportedMediaType
}
if (ct == "image/png" && format != "png") || (ct == "image/jpeg" && format != "jpeg") {
return nil, ErrUnsupportedMediaType
}
if cfg.Width <= 0 || cfg.Height <= 0 {
return nil, ErrUnsupportedMediaType
}
if int64(cfg.Width) > maxPixels/int64(cfg.Height) {
return nil, ErrPayloadTooLarge
}
// Verify structural integrity in bounded memory.
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
if ct == "image/png" {
if err := verifyPNGChunks(tmpFile); err != nil {
return nil, ErrUnsupportedMediaType
}
if int64(cfg.Width)*int64(cfg.Height) <= 2_000_000 {
_, _ = tmpFile.Seek(0, io.SeekStart)
if _, err := png.Decode(tmpFile); err != nil {
return nil, ErrUnsupportedMediaType
}
}
} else {
if err := verifyJPEGStructure(tmpFile); err != nil {
return nil, ErrUnsupportedMediaType
}
if int64(cfg.Width)*int64(cfg.Height) <= 2_000_000 {
_, _ = tmpFile.Seek(0, io.SeekStart)
if _, err := jpeg.Decode(tmpFile); err != nil {
return nil, ErrUnsupportedMediaType
}
}
}
if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
return nil, err
}
cleanupTmp = false
return &ValidatedImage{
File: tmpFile,
SizeBytes: n,
SHA256: hex.EncodeToString(hasher.Sum(nil)),
ContentType: ct,
Width: cfg.Width,
Height: cfg.Height,
}, nil
}
func verifyPNGChunks(r io.Reader) error {
sig := make([]byte, 8)
if _, err := io.ReadFull(r, sig); err != nil || !bytes.Equal(sig, pngSignature) {
return errors.New("invalid PNG signature")
}
header := make([]byte, 8)
crcBuf := make([]byte, 4)
scratch := make([]byte, 32*1024)
seenIHDR := false
seenIEND := false
for {
_, err := io.ReadFull(r, header)
if err != nil {
return errors.New("truncated PNG chunk")
}
chunkLen := binary.BigEndian.Uint32(header[0:4])
if chunkLen > 10*1024*1024 {
return errors.New("PNG chunk too large")
}
chunkType := string(header[4:8])
if !seenIHDR && chunkType != "IHDR" {
return errors.New("first PNG chunk must be IHDR")
}
if chunkType == "IHDR" {
seenIHDR = true
}
crc := crc32.NewIEEE()
_, _ = crc.Write(header[4:8])
remaining := int64(chunkLen)
for remaining > 0 {
toRead := int64(len(scratch))
if remaining < toRead {
toRead = remaining
}
m, rErr := io.ReadFull(r, scratch[:toRead])
if rErr != nil {
return errors.New("truncated PNG chunk data")
}
_, _ = crc.Write(scratch[:m])
remaining -= int64(m)
}
if _, err := io.ReadFull(r, crcBuf); err != nil {
return errors.New("missing PNG CRC")
}
expectedCRC := binary.BigEndian.Uint32(crcBuf)
if crc.Sum32() != expectedCRC {
return errors.New("PNG CRC mismatch")
}
if chunkType == "IEND" {
seenIEND = true
break
}
}
if !seenIHDR || !seenIEND {
return errors.New("incomplete PNG structure")
}
return nil
}
func verifyJPEGStructure(r io.Reader) error {
br := bufio.NewReaderSize(r, 32*1024)
b0, err := br.ReadByte()
b1, err2 := br.ReadByte()
if err != nil || err2 != nil || b0 != 0xff || b1 != 0xd8 {
return errors.New("missing JPEG SOI")
}
seenSOF := false
seenSOS := false
seenEOI := false
for {
b, err := br.ReadByte()
if err != nil {
break
}
if b != 0xff {
if !seenSOS {
return errors.New("unexpected bytes before JPEG SOS")
}
continue
}
for {
b, err = br.ReadByte()
if err != nil {
return errors.New("truncated JPEG marker")
}
if b != 0xff {
break
}
}
marker := b
if marker == 0x00 || (marker >= 0xd0 && marker <= 0xd7) {
continue
}
if marker == 0xd9 {
seenEOI = true
break
}
if marker == 0x01 || marker == 0xd8 {
continue
}
var lenBuf [2]byte
if _, err := io.ReadFull(br, lenBuf[:]); err != nil {
return errors.New("truncated JPEG segment length")
}
segLen := int(binary.BigEndian.Uint16(lenBuf[:]))
if segLen < 2 {
return errors.New("invalid JPEG segment length")
}
if _, err := io.CopyN(io.Discard, br, int64(segLen-2)); err != nil {
return errors.New("truncated JPEG segment payload")
}
if (marker >= 0xc0 && marker <= 0xc3) || (marker >= 0xc5 && marker <= 0xc7) || (marker >= 0xc9 && marker <= 0xcb) || (marker >= 0xcd && marker <= 0xcf) {
seenSOF = true
}
if marker == 0xda {
seenSOS = true
}
}
if !seenSOF || !seenSOS || !seenEOI {
return errors.New("incomplete JPEG structure")
}
return nil
}
+102
View File
@@ -0,0 +1,102 @@
package model
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type 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 string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ObjectKey string `json:"-"`
}
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type CreateMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids,omitempty"`
}
type ChatPage struct {
Items []Chat `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type MessagePage struct {
Items []Message `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
type HealthResponse struct {
Status string `json:"status"`
}
type CursorData struct {
Scope string `json:"s"`
Time string `json:"t"`
ID string `json:"i"`
}
+173
View File
@@ -0,0 +1,173 @@
package s3store
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 (
ErrObjectNotFound = errors.New("s3 object not found")
ErrS3Unavailable = errors.New("s3 storage unavailable")
)
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
}
type ObjectSummary struct {
Key string
Size int64
LastModified time.Time
}
type Client struct {
mc *minio.Client
bucket string
}
func NewClient(cfg Config) (*Client, error) {
u, err := url.Parse(strings.TrimSpace(cfg.Endpoint))
if err != nil || u.Host == "" {
return nil, fmt.Errorf("invalid S3 endpoint %q", cfg.Endpoint)
}
useSSL := strings.EqualFold(u.Scheme, "https")
region := strings.TrimSpace(cfg.Region)
if region == "" {
region = "us-east-1"
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 800 * time.Millisecond,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 2 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
mc, err := minio.New(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: useSSL,
Region: region,
BucketLookup: minio.BucketLookupPath,
Transport: tr,
MaxRetries: 1,
})
if err != nil {
return nil, fmt.Errorf("create minio client: %w", err)
}
return &Client{
mc: mc,
bucket: cfg.Bucket,
}, nil
}
func (c *Client) Bucket() string {
return c.bucket
}
func (c *Client) Ready(ctx context.Context) error {
rCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
exists, err := c.mc.BucketExists(rCtx, c.bucket)
if err != nil || !exists {
return ErrS3Unavailable
}
return nil
}
func (c *Client) PutObject(ctx context.Context, objectKey string, r io.Reader, size int64, contentType string) error {
pCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, err := c.mc.PutObject(pCtx, c.bucket, objectKey, r, size, minio.PutObjectOptions{
ContentType: contentType,
})
if err != nil {
return fmt.Errorf("%w: %v", ErrS3Unavailable, err)
}
return nil
}
func (c *Client) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, int64, error) {
obj, err := c.mc.GetObject(ctx, c.bucket, objectKey, minio.GetObjectOptions{})
if err != nil {
return nil, 0, fmt.Errorf("%w: %v", ErrS3Unavailable, err)
}
info, err := obj.Stat()
if err != nil {
_ = obj.Close()
errResp := minio.ToErrorResponse(err)
if errResp.Code == "NoSuchKey" || errResp.StatusCode == 404 {
return nil, 0, ErrObjectNotFound
}
return nil, 0, fmt.Errorf("%w: %v", ErrS3Unavailable, err)
}
return obj, info.Size, nil
}
func (c *Client) StatObject(ctx context.Context, objectKey string) (bool, error) {
sCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
_, err := c.mc.StatObject(sCtx, c.bucket, objectKey, minio.StatObjectOptions{})
if err != nil {
errResp := minio.ToErrorResponse(err)
if errResp.Code == "NoSuchKey" || errResp.StatusCode == 404 {
return false, nil
}
return false, fmt.Errorf("%w: %v", ErrS3Unavailable, err)
}
return true, nil
}
func (c *Client) RemoveObject(ctx context.Context, objectKey string) error {
dCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := c.mc.RemoveObject(dCtx, c.bucket, objectKey, minio.RemoveObjectOptions{}); err != nil {
errResp := minio.ToErrorResponse(err)
if errResp.Code == "NoSuchKey" || errResp.StatusCode == 404 {
return nil
}
return fmt.Errorf("%w: %v", ErrS3Unavailable, err)
}
return nil
}
func (c *Client) ListObjects(ctx context.Context, prefix string) ([]ObjectSummary, error) {
lCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
var out []ObjectSummary
for obj := range c.mc.ListObjects(lCtx, c.bucket, minio.ListObjectsOptions{
Prefix: prefix,
Recursive: true,
}) {
if obj.Err != nil {
return nil, fmt.Errorf("%w: %v", ErrS3Unavailable, obj.Err)
}
out = append(out, ObjectSummary{
Key: obj.Key,
Size: obj.Size,
LastModified: obj.LastModified,
})
}
return out, nil
}
File diff suppressed because it is too large Load Diff
+130
View File
@@ -0,0 +1,130 @@
package store
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"regexp"
"time"
"github.com/google/uuid"
"messenger/internal/model"
"messenger/internal/s3store"
)
var (
ErrConflict = errors.New("conflict")
ErrNotFound = errors.New("not found")
ErrBadRequest = errors.New("bad request")
ErrUnauthorized = errors.New("unauthorized")
ErrUnavailable = errors.New("service unavailable")
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
IdempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
)
const TimestampFormat = "2006-01-02T15:04:05.000000Z"
func FormatTime(t time.Time) string {
return t.UTC().Truncate(time.Microsecond).Format(TimestampFormat)
}
func NowUTC() time.Time {
return time.Now().UTC().Truncate(time.Microsecond)
}
type MigrationFile struct {
Version string
SQL string
}
type ReconcileReport struct {
DryRun bool `json:"dry_run"`
GracePeriodSeconds int64 `json:"grace_period_seconds"`
LockAcquired bool `json:"lock_acquired"`
S3ObjectsScanned int `json:"s3_objects_scanned"`
DBRowsScanned int `json:"db_rows_scanned"`
OrphanS3Found []string `json:"orphan_s3_found"`
OrphanS3Deleted []string `json:"orphan_s3_deleted"`
OrphanS3SkippedGrace []string `json:"orphan_s3_skipped_grace"`
MissingS3Found []string `json:"missing_s3_found"`
MissingS3MarkedFailed []string `json:"missing_s3_marked_failed"`
MissingS3Deleted []string `json:"missing_s3_deleted"`
MissingS3SkippedGrace []string `json:"missing_s3_skipped_grace"`
HealthyPreserved int `json:"healthy_preserved"`
S3ListCalls int `json:"s3_list_calls"`
S3RemoveCalls int `json:"s3_remove_calls"`
DBQueries int `json:"db_queries"`
DurationMs float64 `json:"duration_ms"`
}
type StoreStats struct {
SQLQueries int64 `json:"sql_queries"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
SingleflightShared int64 `json:"singleflight_shared"`
CacheMode string `json:"cache_mode"`
WriteMode string `json:"write_mode"`
RedisConnected bool `json:"redis_connected"`
}
type Store interface {
Ready(ctx context.Context) error
RunMigrations(ctx context.Context, migrations []MigrationFile) error
CreateUser(ctx context.Context, req model.CreateUserRequest) (*model.User, error)
AuthenticateAndCreateSession(ctx context.Context, username, password string, ttlSeconds int) (*model.Session, error)
GetUserByToken(ctx context.Context, rawToken string) (*model.User, error)
RevokeSession(ctx context.Context, rawToken string) error
CreateChat(ctx context.Context, callerID string, req model.CreateChatRequest) (*model.Chat, error)
ListChats(ctx context.Context, callerID string, limit int, cursorStr string) (*model.ChatPage, error)
GetChat(ctx context.Context, callerID, chatID string) (*model.Chat, error)
IsChatMember(ctx context.Context, callerID, chatID string) (bool, error)
CreateAttachment(ctx context.Context, att model.Attachment) (*model.Attachment, error)
GetAttachment(ctx context.Context, callerID, attachmentID string) (*model.Attachment, error)
Reconcile(ctx context.Context, s3 *s3store.Client, gracePeriod time.Duration, dryRun bool) (*ReconcileReport, error)
CreateMessage(ctx context.Context, callerID, chatID, idempotencyKey string, idempotencyTTLSeconds int, req model.CreateMessageRequest) (*model.Message, error)
ListMessages(ctx context.Context, callerID, chatID string, limit int, cursorStr string) (*model.MessagePage, error)
Stats(ctx context.Context) StoreStats
ResetStats()
SetCacheMode(mode string)
Close()
}
func EncodeCursor(scope, timestamp, id string) string {
data := model.CursorData{
Scope: scope,
Time: timestamp,
ID: id,
}
b, _ := json.Marshal(data)
return base64.RawURLEncoding.EncodeToString(b)
}
func DecodeCursor(cursorStr, expectedScope string) (time.Time, string, error) {
b, err := base64.RawURLEncoding.DecodeString(cursorStr)
if err != nil {
b, err = base64.URLEncoding.DecodeString(cursorStr)
if err != nil {
b, err = base64.StdEncoding.DecodeString(cursorStr)
if err != nil {
return time.Time{}, "", ErrBadRequest
}
}
}
var data model.CursorData
if err := json.Unmarshal(b, &data); err != nil {
return time.Time{}, "", ErrBadRequest
}
if data.Scope != expectedScope || data.Time == "" || data.ID == "" {
return time.Time{}, "", ErrBadRequest
}
if _, err := uuid.Parse(data.ID); err != nil {
return time.Time{}, "", ErrBadRequest
}
t, err := time.Parse(time.RFC3339Nano, data.Time)
if err != nil {
return time.Time{}, "", ErrBadRequest
}
return t.UTC().Truncate(time.Microsecond), data.ID, nil
}