feat: add private S3 attachments and safe reconciliation

This commit is contained in:
Vladislav Agapov
2026-10-29 16:27:20 +03:00
parent ec540a1a72
commit aca4c4eea9
217 changed files with 15042 additions and 44 deletions
+18
View File
@@ -0,0 +1,18 @@
package admission
import (
"context"
"errors"
)
// ErrRate means the request exhausted a shared rate budget.
var ErrRate = errors.New("shared request rate exceeded")
// ErrSlots means the request exhausted a shared concurrency budget.
var ErrSlots = errors.New("shared execution slots exhausted")
// Distributed defines request admission independently of the backing database.
type Distributed interface {
// Enter reserves global/group or user/group budgets and returns a release operation.
Enter(ctx context.Context, group, user string) (func(), error)
}
+73
View File
@@ -0,0 +1,73 @@
// Package admission bounds request rate and concurrent execution independently of transport.
package admission
import (
"fmt"
"sync"
"time"
)
// Options defines the rate and execution bounds for one limiter.
type Options struct {
// MaxInFlight limits concurrent executions without an admission queue.
MaxInFlight int
// RequestsPerSecond is the token refill rate.
RequestsPerSecond int
// Burst is the maximum number of immediately available tokens.
Burst int
}
// Limiter owns synchronization for the token bucket and execution slots.
// It knows neither HTTP response codes nor application shutdown state.
type Limiter struct {
mu sync.Mutex
rate float64
burst float64
tokens float64
lastRefill time.Time
slots chan struct{}
}
// New validates limits and creates a full token bucket with bounded execution slots.
func New(cfg Options) (*Limiter, error) {
if cfg.MaxInFlight <= 0 || cfg.RequestsPerSecond <= 0 || cfg.Burst <= 0 {
return nil, fmt.Errorf("admission limits must be positive")
}
return &Limiter{
rate: float64(cfg.RequestsPerSecond),
burst: float64(cfg.Burst),
tokens: float64(cfg.Burst),
lastRefill: time.Now(),
slots: make(chan struct{}, cfg.MaxInFlight),
}, nil
}
// Allow refills the token bucket and consumes a token when one is available.
func (limiter *Limiter) Allow(now time.Time) bool {
limiter.mu.Lock()
defer limiter.mu.Unlock()
elapsed := max(0, now.Sub(limiter.lastRefill).Seconds())
limiter.tokens = min(limiter.burst, limiter.tokens+elapsed*limiter.rate)
limiter.lastRefill = now
if limiter.tokens < 1 {
return false
}
limiter.tokens--
return true
}
// Acquire reserves an execution slot without waiting.
func (limiter *Limiter) Acquire() bool {
select {
case limiter.slots <- struct{}{}:
return true
default:
return false
}
}
// Release returns an execution slot previously reserved by Acquire.
// Each successful Acquire must be paired with exactly one Release.
func (limiter *Limiter) Release() {
<-limiter.slots
}
+148
View File
@@ -0,0 +1,148 @@
package admission
import (
"testing"
"testing/synctest"
"time"
)
// TestLimiter_Allow checks token exhaustion and refill with deterministic time.
func TestLimiter_Allow(t *testing.T) {
cases := []struct {
name string
elapsed time.Duration
want bool
}{
{"Negative: exhausted bucket", 0, false},
{"Negative: partial token", time.Millisecond * 500, false},
{"Positive: refilled token", time.Second, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Arrange.
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
if !limiter.Allow(time.Now()) {
t.Fatal("fixture token missing")
}
time.Sleep(tc.elapsed)
// Act.
got := limiter.Allow(time.Now())
// Assert.
if got != tc.want {
t.Fatalf("Allow after %s=%v, want=%v", tc.elapsed, got, tc.want)
}
})
})
}
}
// TestLimiter_Acquire checks available, occupied and released execution slots independently.
func TestLimiter_Acquire(t *testing.T) {
t.Run("Positive: free slot", func(t *testing.T) {
// Arrange.
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
want := true
// Act.
got := limiter.Acquire()
if got {
t.Cleanup(limiter.Release)
}
// Assert.
if got != want {
t.Fatalf("Acquire=%v, want=%v", got, want)
}
})
t.Run("Negative: occupied slot", func(t *testing.T) {
// Arrange.
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
if !limiter.Acquire() {
t.Fatal("fixture slot unavailable")
}
t.Cleanup(limiter.Release)
want := false
// Act.
got := limiter.Acquire()
if got {
t.Cleanup(limiter.Release)
}
// Assert.
if got != want {
t.Fatalf("Acquire=%v, want=%v", got, want)
}
})
t.Run("Positive: released slot", func(t *testing.T) {
// Arrange.
limiter := newTestLimiter(t, Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 1})
if !limiter.Acquire() {
t.Fatal("fixture slot unavailable")
}
limiter.Release()
want := true
// Act.
got := limiter.Acquire()
if got {
t.Cleanup(limiter.Release)
}
// Assert.
if got != want {
t.Fatalf("Acquire=%v, want=%v", got, want)
}
})
}
// newTestLimiter creates a limiter or fails the test on invalid settings.
func newTestLimiter(t *testing.T, options Options) *Limiter {
t.Helper()
limiter, err := New(options)
if err != nil {
t.Fatal(err)
}
return limiter
}
// TestLimiter_New rejects each nonpositive limit independently.
func TestLimiter_New(t *testing.T) {
cases := []struct {
name string
options Options
}{
{"Negative: zero concurrency", Options{MaxInFlight: 0, RequestsPerSecond: 1, Burst: 1}},
{"Negative: negative concurrency", Options{MaxInFlight: -1, RequestsPerSecond: 1, Burst: 1}},
{"Negative: zero refill rate", Options{MaxInFlight: 1, RequestsPerSecond: 0, Burst: 1}},
{"Negative: negative refill rate", Options{MaxInFlight: 1, RequestsPerSecond: -1, Burst: 1}},
{"Negative: zero burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: 0}},
{"Negative: negative burst", Options{MaxInFlight: 1, RequestsPerSecond: 1, Burst: -1}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
options := tc.options
// Act.
limiter, err := New(options)
// Assert.
if err == nil || limiter != nil {
t.Fatalf("invalid options accepted: %v, %v", limiter, err)
}
})
}
}
+53
View File
@@ -0,0 +1,53 @@
// Package config loads and validates the environment configuration of the application.
package config
import "fmt"
// Config groups settings by the component that consumes them.
type Config struct {
// HTTP configures the listener, request limits and shutdown deadline.
HTTP *Controller
// Memory configures the capacity of the process-local store.
Memory *Memory
// Logger configures structured process logging.
Logger *Logger
}
// Default returns independent configuration sections with the documented defaults.
func Default() *Config {
return &Config{
HTTP: defaultController(),
Memory: defaultMemory(),
Logger: &Logger{Level: "info"},
}
}
// New loads environment overrides and rejects invalid settings before startup.
func New() (*Config, error) {
cfg := Default()
if err := cfg.HTTP.loadEnvironment(); err != nil {
return nil, err
}
if err := cfg.Memory.loadEnvironment(); err != nil {
return nil, err
}
cfg.Logger.loadEnvironment()
if err := cfg.Validate(); err != nil {
return nil, err
}
return cfg, nil
}
// Validate verifies the presence and invariants of each configuration section.
func (cfg *Config) Validate() error {
if cfg == nil || cfg.HTTP == nil || cfg.Memory == nil || cfg.Logger == nil {
return fmt.Errorf("HTTP, Memory and Logger configuration sections are required")
}
if err := cfg.HTTP.Validate(); err != nil {
return err
}
if err := cfg.Memory.Validate(); err != nil {
return err
}
return cfg.Logger.Validate()
}
+241
View File
@@ -0,0 +1,241 @@
package config
import "testing"
// TestConfig_New checks individual environment overrides and invalid settings.
func TestConfig_New(t *testing.T) {
t.Run("Positive: APP_PORT override", func(t *testing.T) {
// Arrange.
t.Setenv("APP_PORT", "18080")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.Port != 18080 {
t.Fatalf("APP_PORT=%v, want=%v", cfg.HTTP.Port, 18080)
}
})
t.Run("Positive: REQUEST_TIMEOUT_SECONDS override", func(t *testing.T) {
// Arrange.
t.Setenv("REQUEST_TIMEOUT_SECONDS", "4")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.TimeoutSeconds != 4 {
t.Fatalf("REQUEST_TIMEOUT_SECONDS=%v, want=%v", cfg.HTTP.TimeoutSeconds, 4)
}
})
t.Run("Positive: MAX_MESSAGES override", func(t *testing.T) {
// Arrange.
t.Setenv("MAX_MESSAGES", "25")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.Memory.MaxMessages != 25 {
t.Fatalf("MAX_MESSAGES=%v, want=%v", cfg.Memory.MaxMessages, 25)
}
})
t.Run("Positive: REQUESTS_PER_SECOND override", func(t *testing.T) {
// Arrange.
t.Setenv("REQUESTS_PER_SECOND", "12")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.Admission.RequestsPerSecond != 12 {
t.Fatalf("REQUESTS_PER_SECOND=%v, want=%v", cfg.HTTP.Admission.RequestsPerSecond, 12)
}
})
t.Run("Positive: LOG_LEVEL override", func(t *testing.T) {
// Arrange.
t.Setenv("LOG_LEVEL", "debug")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.Logger.Level != "debug" {
t.Fatalf("LOG_LEVEL=%v, want=%v", cfg.Logger.Level, "debug")
}
})
cases := []struct {
name string
key string
value string
}{
{"port exceeds TCP range", "APP_PORT", "65536"},
{"zero message capacity", "MAX_MESSAGES", "0"},
{"nonnumeric body limit", "MAX_BODY_BYTES", "bad"},
{"shutdown deadline exceeds bound", "SHUTDOWN_TIMEOUT_SECONDS", "10"},
{"hostname instead of bind IP", "APP_HOST", "hostname"},
}
for _, tc := range cases {
t.Run("Negative: "+tc.name, func(t *testing.T) {
// Arrange.
t.Setenv(tc.key, tc.value)
// Act.
cfg, err := New()
// Assert.
if err == nil || cfg != nil {
t.Fatalf("invalid %s=%q returned config=%+v, error=%v", tc.key, tc.value, cfg, err)
}
})
}
}
// TestConfig_Validate rejects one missing section or invalid component per scenario.
func TestConfig_Validate(t *testing.T) {
t.Run("Negative: nil config", func(t *testing.T) {
// Arrange.
var cfg *Config
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "nil config")
}
})
t.Run("Negative: missing HTTP", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.HTTP = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing HTTP")
}
})
t.Run("Negative: missing Memory", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Memory = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing Memory")
}
})
t.Run("Negative: missing Logger", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Logger = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing Logger")
}
})
t.Run("Negative: unknown log level", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Logger.Level = "unknown"
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "unknown log level")
}
})
t.Run("Negative: zero storage capacity", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Memory.MaxUsers = 0
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "zero storage capacity")
}
})
t.Run("Negative: zero concurrency", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.HTTP.Admission.MaxInFlight = 0
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "zero concurrency")
}
})
}
// TestLogger_Validate rejects an absent logging section without panicking.
func TestLogger_Validate(t *testing.T) {
// Arrange.
var cfg *Logger
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatal("nil logger accepted")
}
}
// TestMemory_Validate rejects absent storage settings without panicking.
func TestMemory_Validate(t *testing.T) {
// Arrange.
var cfg *Memory
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatal("nil memory configuration accepted")
}
}
+160
View File
@@ -0,0 +1,160 @@
package config
import (
"fmt"
"net"
"os"
"strconv"
"time"
)
const (
maxTCPPort = 65535
maxShutdownTimeoutSeconds = 9
maxRequestTimeoutSeconds = 15
)
// Controller contains settings owned exclusively by the HTTP transport.
type Controller struct {
// InstanceID identifies this API process to the load balancer diagnostics.
InstanceID string
// Host is the IP address on which the listener binds.
Host string
// Port is the TCP port, in the range 1..65535.
Port int
// TimeoutSeconds limits request reads, response writes and idle connections.
TimeoutSeconds int
// ShutdownTimeoutSeconds bounds draining of active requests; it must not exceed nine seconds.
ShutdownTimeoutSeconds int
// MaxBodyBytes is the maximum accepted request body size before decoding.
MaxBodyBytes int
// MaxConnections bounds simultaneous connections handled by fasthttp.
MaxConnections int
// Admission controls business request throughput and execution concurrency.
Admission Admission
}
// Admission defines shared request policies; health endpoints bypass them.
type Admission struct {
// MaxInFlight is the maximum number of executing requests, with no waiting queue.
MaxInFlight int
// RequestsPerSecond is the token refill rate for the global admission bucket.
RequestsPerSecond int
// Burst is the bucket capacity and maximum immediate request burst.
Burst int
// AuthRate limits public registration/login attempts per second.
AuthRate int
// AuthSlots bounds concurrent password KDF work globally.
AuthSlots int
// UserRate limits each authenticated account across all groups.
UserRate int
// UserSlots bounds concurrency across one account's groups.
UserSlots int
// UserWriteRate limits one account's write attempts per second.
UserWriteRate int
// UserWriteSlots bounds one account's concurrent writes.
UserWriteSlots int
// UserAuthRate limits session-management operations per account.
UserAuthRate int
// UserAuthSlots bounds one account's session-management concurrency.
UserAuthSlots int
}
// defaultController returns the default listener, timeout and admission settings.
func defaultController() *Controller {
return &Controller{
Host: "0.0.0.0",
Port: 8080,
TimeoutSeconds: 3,
ShutdownTimeoutSeconds: 5,
MaxBodyBytes: 10 << 20,
MaxConnections: 16,
Admission: Admission{
MaxInFlight: 32,
RequestsPerSecond: 1000,
Burst: 100,
AuthRate: 100,
AuthSlots: 4,
UserRate: 100,
UserSlots: 8,
UserWriteRate: 50,
UserWriteSlots: 4,
UserAuthRate: 20,
UserAuthSlots: 2,
},
}
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Controller) loadEnvironment() error {
cfg.InstanceID = os.Getenv("INSTANCE_ID")
if host, exists := os.LookupEnv("APP_HOST"); exists {
cfg.Host = host
}
return loadIntegers(
integerSetting{"APP_PORT", &cfg.Port},
integerSetting{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
integerSetting{"SHUTDOWN_TIMEOUT_SECONDS", &cfg.ShutdownTimeoutSeconds},
integerSetting{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
integerSetting{"MAX_CONNECTIONS", &cfg.MaxConnections},
integerSetting{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
integerSetting{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
integerSetting{"REQUEST_BURST", &cfg.Admission.Burst},
integerSetting{"AUTH_RATE", &cfg.Admission.AuthRate},
integerSetting{"AUTH_SLOTS", &cfg.Admission.AuthSlots},
integerSetting{"USER_RATE", &cfg.Admission.UserRate},
integerSetting{"USER_SLOTS", &cfg.Admission.UserSlots},
integerSetting{"USER_WRITE_RATE", &cfg.Admission.UserWriteRate},
integerSetting{"USER_WRITE_SLOTS", &cfg.Admission.UserWriteSlots},
integerSetting{"USER_AUTH_RATE", &cfg.Admission.UserAuthRate},
integerSetting{"USER_AUTH_SLOTS", &cfg.Admission.UserAuthSlots},
)
}
// Validate checks listener addresses, timeouts and admission bounds.
func (cfg *Controller) Validate() error {
if cfg == nil {
return fmt.Errorf("HTTP configuration is required")
}
if cfg.TimeoutSeconds > maxRequestTimeoutSeconds {
return fmt.Errorf("REQUEST_TIMEOUT_SECONDS must not exceed %d", maxRequestTimeoutSeconds)
}
if net.ParseIP(cfg.Host) == nil {
return fmt.Errorf("APP_HOST must be an IP address")
}
if cfg.Port < 1 || cfg.Port > maxTCPPort {
return fmt.Errorf("APP_PORT must be 1..%d", maxTCPPort)
}
if cfg.ShutdownTimeoutSeconds < 1 || cfg.ShutdownTimeoutSeconds > maxShutdownTimeoutSeconds {
return fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..%d", maxShutdownTimeoutSeconds)
}
settings := []integerSetting{
{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
{"MAX_CONNECTIONS", &cfg.MaxConnections},
{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
{"REQUEST_BURST", &cfg.Admission.Burst},
}
for _, setting := range settings {
if err := validatePositive(setting.name, *setting.target); err != nil {
return err
}
}
return nil
}
// Bind returns the listener address, including brackets for IPv6 hosts.
func (cfg *Controller) Bind() string {
return net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
}
// Timeout returns the configured read, write and idle timeout.
func (cfg *Controller) Timeout() time.Duration {
return time.Duration(cfg.TimeoutSeconds) * time.Second
}
// ShutdownTimeout returns the maximum time allowed to drain active requests.
func (cfg *Controller) ShutdownTimeout() time.Duration {
return time.Duration(cfg.ShutdownTimeoutSeconds) * time.Second
}
+41
View File
@@ -0,0 +1,41 @@
package config
import (
"fmt"
"os"
"strconv"
)
const maxConfiguredInteger = 1 << 30
type integerSetting struct {
name string
target *int
}
// loadIntegers parses configured integer overrides and reports invalid values.
func loadIntegers(settings ...integerSetting) error {
for _, setting := range settings {
raw, exists := os.LookupEnv(setting.name)
if !exists {
continue
}
value, err := strconv.Atoi(raw)
if err != nil {
return fmt.Errorf("%s must be an integer", setting.name)
}
if err := validatePositive(setting.name, value); err != nil {
return err
}
*setting.target = value
}
return nil
}
// validatePositive checks that a setting is positive and within the supported range.
func validatePositive(name string, value int) error {
if value < 1 || value > maxConfiguredInteger {
return fmt.Errorf("%s must be between 1 and %d", name, maxConfiguredInteger)
}
return nil
}
+32
View File
@@ -0,0 +1,32 @@
package config
import (
"fmt"
"os"
)
// Logger configures the minimum severity written as structured JSON to stderr.
type Logger struct {
// Level is one of debug, info, warn or error; the default is info.
Level string
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Logger) loadEnvironment() {
if level, exists := os.LookupEnv("LOG_LEVEL"); exists {
cfg.Level = level
}
}
// Validate rejects unsupported levels rather than silently changing verbosity.
func (cfg *Logger) Validate() error {
if cfg == nil {
return fmt.Errorf("Logger configuration is required")
}
switch cfg.Level {
case "debug", "info", "warn", "error":
return nil
default:
return fmt.Errorf("LOG_LEVEL must be debug, info, warn or error")
}
}
+54
View File
@@ -0,0 +1,54 @@
package config
import "fmt"
// Memory defines logical capacity limits; MaxStateBytes is not a measurement of RSS.
type Memory struct {
// MaxUsers limits the number of registered users.
MaxUsers int
// MaxChats limits the number of immutable chats.
MaxChats int
// MaxMessages limits the total number of messages across all chats.
MaxMessages int
// MaxStateBytes limits the logical storage budget, including estimated record overhead.
MaxStateBytes int
}
// defaultMemory returns the default storage capacity limits.
func defaultMemory() *Memory {
return &Memory{
MaxUsers: 10000,
MaxChats: 10000,
MaxMessages: 100000,
MaxStateBytes: 32 << 20,
}
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Memory) loadEnvironment() error {
return loadIntegers(
integerSetting{"MAX_USERS", &cfg.MaxUsers},
integerSetting{"MAX_CHATS", &cfg.MaxChats},
integerSetting{"MAX_MESSAGES", &cfg.MaxMessages},
integerSetting{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
)
}
// Validate rejects disabled, negative and excessively large storage limits.
func (cfg *Memory) Validate() error {
if cfg == nil {
return fmt.Errorf("Memory configuration is required")
}
settings := []integerSetting{
{"MAX_USERS", &cfg.MaxUsers},
{"MAX_CHATS", &cfg.MaxChats},
{"MAX_MESSAGES", &cfg.MaxMessages},
{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
}
for _, setting := range settings {
if err := validatePositive(setting.name, *setting.target); err != nil {
return err
}
}
return nil
}
+35
View File
@@ -0,0 +1,35 @@
package config
import (
"fmt"
"os"
)
// ObjectStore contains only the S3 adapter's connection settings.
type ObjectStore struct {
// Endpoint is host:port, without a URL scheme.
Endpoint string
// Bucket is the private application bucket.
Bucket string
// AccessKey is the restricted service identity.
AccessKey string
// SecretKey is supplied by the runtime secret provider.
SecretKey string
// Secure enables certificate-verified TLS.
Secure bool
}
// NewObjectStore validates S3 settings independently of their use.
func NewObjectStore() (*ObjectStore, error) {
cfg := &ObjectStore{
Endpoint: os.Getenv("S3_ENDPOINT"),
Bucket: os.Getenv("S3_BUCKET"),
AccessKey: os.Getenv("S3_ACCESS_KEY"),
SecretKey: os.Getenv("S3_SECRET_KEY"),
Secure: os.Getenv("S3_TLS") != "false",
}
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, fmt.Errorf("S3 endpoint, bucket and scoped credentials required")
}
return cfg, nil
}
+24
View File
@@ -0,0 +1,24 @@
package config
import "testing"
// TestObjectStoreConfiguration verifies mandatory credentials and opt-in local plaintext.
func TestObjectStoreConfiguration(t *testing.T) {
t.Run("missing credentials", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "")
if _, err := NewObjectStore(); err == nil {
t.Fatal("missing endpoint accepted")
}
})
t.Run("local configuration", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "localhost:9000")
t.Setenv("S3_BUCKET", "attachments")
t.Setenv("S3_ACCESS_KEY", "test")
t.Setenv("S3_SECRET_KEY", "synthetic-only")
t.Setenv("S3_TLS", "false")
cfg, err := NewObjectStore()
if err != nil || cfg.Secure || cfg.Bucket != "attachments" {
t.Fatalf("invalid result: %v", err)
}
})
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"fmt"
"os"
"strings"
)
// Persistence contains database, cache and session settings.
type Persistence struct {
// CursorKey is the shared base64 signing key supplied through a secret.
CursorKey string
// DatabaseURL identifies the PostgreSQL database.
DatabaseURL string
// Shards maps stable identities to Valkey addresses.
Shards map[string]string
// Coordinator names the stable global admission shard.
Coordinator string
// PoolSize bounds connections per dependency.
PoolSize int
// TimeoutMilliseconds bounds each dependency operation.
TimeoutMilliseconds int
// SessionTTLSeconds sets the absolute session lifetime.
SessionTTLSeconds int
}
// NewPersistence loads dependency settings separately from HTTP configuration.
func NewPersistence() (*Persistence, error) {
cfg := &Persistence{
CursorKey: os.Getenv("CURSOR_SIGNING_KEY"),
DatabaseURL: os.Getenv("DATABASE_URL"),
Coordinator: os.Getenv("VALKEY_COORDINATOR"),
Shards: make(map[string]string),
PoolSize: 8,
TimeoutMilliseconds: 1000,
SessionTTLSeconds: 3600,
}
if cfg.Coordinator == "" {
cfg.Coordinator = "shard0"
}
for _, entry := range strings.Split(os.Getenv("VALKEY_SHARDS"), ",") {
id, address, ok := strings.Cut(entry, "=")
if !ok || id == "" || address == "" || cfg.Shards[id] != "" {
return nil, fmt.Errorf("VALKEY_SHARDS requires unique id=address entries")
}
cfg.Shards[id] = address
}
if cfg.DatabaseURL == "" || cfg.Shards[cfg.Coordinator] == "" {
return nil, fmt.Errorf("DATABASE_URL and a configured VALKEY_COORDINATOR are required")
}
if err := loadIntegers(integerSetting{"DEPENDENCY_POOL_SIZE", &cfg.PoolSize}, integerSetting{"DEPENDENCY_TIMEOUT_MS", &cfg.TimeoutMilliseconds}, integerSetting{"SESSION_TTL_SECONDS", &cfg.SessionTTLSeconds}); err != nil {
return nil, err
}
return cfg, nil
}
+34
View File
@@ -0,0 +1,34 @@
package config
import "testing"
// TestPersistenceConfiguration validates independent environment configurations.
func TestPersistenceConfiguration(t *testing.T) {
cases := []struct {
name string
database string
shards string
coordinator string
ttl string
valid bool
}{
{"defaults", "postgres://localhost/test", "shard0=localhost:6379", "", "3600", true},
{"missing database", "", "shard0=localhost:6379", "", "3600", false},
{"missing coordinator", "postgres://localhost/test", "shard1=localhost:6379", "shard0", "3600", false},
{"duplicate shard", "postgres://localhost/test", "shard0=a,shard0=b", "", "3600", false},
{"invalid topology", "postgres://localhost/test", "wrong", "", "3600", false},
{"invalid ttl", "postgres://localhost/test", "shard0=a", "", "no", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DATABASE_URL", tc.database)
t.Setenv("VALKEY_SHARDS", tc.shards)
t.Setenv("VALKEY_COORDINATOR", tc.coordinator)
t.Setenv("SESSION_TTL_SECONDS", tc.ttl)
_, err := NewPersistence()
if (err == nil) != tc.valid {
t.Fatalf("unexpected validation result: %v", err)
}
})
}
}
+8
View File
@@ -0,0 +1,8 @@
package controller
import "go.uber.org/fx"
// RunControllerFx lets Fx own startup, signal handling and graceful shutdown.
func RunControllerFx(lc fx.Lifecycle, ctrl Controller) {
lc.Append(fx.Hook{OnStart: ctrl.Start, OnStop: ctrl.Stop})
}
@@ -0,0 +1,112 @@
package fiber
import (
"context"
"io"
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// Attachments defines file operations required by the HTTP boundary.
type Attachments interface {
// Upload validates and publishes an original.
Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error)
// Get authorizes access to attachment metadata.
Get(context.Context, string, string) (dto.Attachment, error)
// Download returns an authorized original stream.
Download(context.Context, string, string, string) (dto.Attachment, io.ReadCloser, error)
}
// WithAttachments binds the file service during composition before server startup.
func (ctrl *Controller) WithAttachments(attachments Attachments) *Controller {
ctrl.attachments = attachments
return ctrl
}
type attachmentResponse struct {
// ID identifies the uploaded file.
ID string `json:"id"`
// ChatID defines the chat authorization scope.
ChatID string `json:"chat_id"`
// OwnerID identifies the original uploader.
OwnerID string `json:"owner_id"`
// Filename is the validated display name.
Filename string `json:"filename"`
// ContentType describes the verified original format.
ContentType string `json:"content_type"`
// SizeBytes is the encoded original length.
SizeBytes int64 `json:"size_bytes"`
// SHA256 is the original lowercase checksum.
SHA256 string `json:"sha256"`
// Status is the durable publication state.
Status string `json:"status"`
// Variants lists generated variants, empty in lab4.
Variants []string `json:"variants"`
// ErrorCode is null for a ready original.
ErrorCode *string `json:"error_code"`
// CreatedAt is the reservation time.
CreatedAt time.Time `json:"created_at"`
// UpdatedAt is the publication time.
UpdatedAt time.Time `json:"updated_at"`
}
// attachmentResponseOf deliberately omits private S3 coordinates.
func attachmentResponseOf(a dto.Attachment) attachmentResponse {
return attachmentResponse{
ID: a.ID.String(),
ChatID: a.ChatID.String(),
OwnerID: a.OwnerID.String(),
Filename: a.Filename,
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
SHA256: a.SHA256,
Status: a.Status,
Variants: []string{},
CreatedAt: a.CreatedAt,
UpdatedAt: a.UpdatedAt,
}
}
// handleUpload passes raw bounded bytes to application validation.
func (ctrl *Controller) handleUpload(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, err := ctrl.attachments.Upload(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"), ctx.Query("filename"), ctx.Get("Content-Type"), ctx.Body())
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(attachmentResponseOf(a))
}
// handleAttachment returns only the public metadata of an accessible file.
func (ctrl *Controller) handleAttachment(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, err := ctrl.attachments.Get(ctx.UserContext(), identity(ctx), ctx.Params("id"))
if err != nil {
return err
}
return ctx.JSON(attachmentResponseOf(a))
}
// handleContent streams original bytes without redirecting around authorization.
func (ctrl *Controller) handleContent(ctx *fiber.Ctx) error {
if ctrl.attachments == nil {
return service.ErrUnavailable
}
a, reader, err := ctrl.attachments.Download(ctx.UserContext(), identity(ctx), ctx.Params("id"), ctx.Query("variant"))
if err != nil {
return err
}
ctx.Set("Content-Type", a.ContentType)
ctx.Set("X-Content-Type-Options", "nosniff")
return ctx.SendStream(&responseStream{Reader: reader, cleanup: func() {
}}, int(a.SizeBytes))
}
@@ -0,0 +1,102 @@
package fiber
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
type attachmentFixture struct {
attachment dto.Attachment
body []byte
err error
}
// Upload returns the configured application outcome for an HTTP mapping scenario.
func (f attachmentFixture) Upload(context.Context, string, string, string, string, []byte) (dto.Attachment, error) {
return f.attachment, f.err
}
// Get returns the configured metadata outcome for an HTTP mapping scenario.
func (f attachmentFixture) Get(context.Context, string, string) (dto.Attachment, error) {
return f.attachment, f.err
}
// Download returns a stream that fails if the request context is canceled before transmission.
func (f attachmentFixture) Download(ctx context.Context, _, _, _ string) (dto.Attachment, io.ReadCloser, error) {
return f.attachment, &contextReader{Reader: bytes.NewReader(f.body), ctx: ctx}, f.err
}
type contextReader struct {
*bytes.Reader
ctx context.Context
}
// Read verifies the admission context survives until the response is actually read.
func (r *contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.Reader.Read(p)
}
// Close makes the synthetic response stream an owned closer.
func (r *contextReader) Close() error {
return nil
}
// TestAttachmentHTTPMapping exercises early errors, successful metadata and byte-exact streaming.
func TestAttachmentHTTPMapping(t *testing.T) {
cases := []struct {
name string
method string
path string
fixture *attachmentFixture
status int
}{
{"upload unavailable", "POST", "/api/v1/chats/test/attachments", nil, http.StatusServiceUnavailable},
{"metadata unavailable", "GET", "/api/v1/attachments/test", nil, http.StatusServiceUnavailable},
{"download unavailable", "GET", "/api/v1/attachments/test/content", nil, http.StatusServiceUnavailable},
{"upload too large", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrTooLarge}, http.StatusRequestEntityTooLarge},
{"upload unsupported", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{err: service.ErrMedia}, http.StatusUnsupportedMediaType},
{"metadata missing", "GET", "/api/v1/attachments/test", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
{"download missing", "GET", "/api/v1/attachments/test/content", &attachmentFixture{err: service.ErrNotFound}, http.StatusNotFound},
{"upload ready", "POST", "/api/v1/chats/test/attachments", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "ready"}}, http.StatusCreated},
{"metadata ready", "GET", "/api/v1/attachments/test", &attachmentFixture{attachment: dto.Attachment{ID: uuid.New(), Status: "ready"}}, http.StatusOK},
{"download stream", "GET", "/api/v1/attachments/test/content", &attachmentFixture{attachment: dto.Attachment{SizeBytes: 4, ContentType: "image/png"}, body: []byte{0, 1, 2, 3}}, http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctrl := testController(t, nil)
user := call(t, ctrl, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "test_user", "display_name": "Test", "password": "synthetic-password"}, http.StatusCreated)
if tc.fixture != nil {
ctrl.WithAttachments(*tc.fixture)
}
req := httptest.NewRequest(tc.method, tc.path, bytes.NewReader([]byte("fixture")))
req.Header.Set("Authorization", "Bearer "+user["id"].(string))
req.Header.Set("Content-Type", "image/png")
response, err := ctrl.server.Test(req, 10000)
if err != nil {
t.Fatal(err)
}
body, err := io.ReadAll(response.Body)
if closeErr := response.Body.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil || response.StatusCode != tc.status {
t.Fatalf("response status=%d err=%v", response.StatusCode, err)
}
if tc.fixture != nil && tc.fixture.body != nil && !bytes.Equal(body, tc.fixture.body) {
t.Fatalf("stream changed: %v", body)
}
})
}
}
+76
View File
@@ -0,0 +1,76 @@
package fiber
import (
"encoding/base64"
"net/http"
"strings"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
const identityKey = "authenticated-user"
// HandleLogin structurally decodes Basic credentials and delegates authentication.
func (ctrl *Controller) HandleLogin(ctx *fiber.Ctx) error {
scheme, encoded, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
if !ok || !strings.EqualFold(scheme, "Basic") {
return service.ErrUnauthorized
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return service.ErrUnauthorized
}
username, password, ok := strings.Cut(string(decoded), ":")
if !ok {
return service.ErrUnauthorized
}
if len(ctx.Body()) != 0 {
return service.ErrInvalid
}
session, err := ctrl.auth.Login(ctx.UserContext(), username, password)
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(fiber.Map{
"token": session.Token,
"token_type": "Bearer",
"expires_at": session.ExpiresAt,
"user": userResponse(session.User),
})
}
// HandleLogout revokes the current authenticated token before returning no content.
func (ctrl *Controller) HandleLogout(ctx *fiber.Ctx) error {
if err := ctrl.auth.Logout(ctx.UserContext(), bearer(ctx)); err != nil {
return err
}
return ctx.SendStatus(http.StatusNoContent)
}
// bearer extracts a Bearer token without interpreting its identity or validity.
func bearer(ctx *fiber.Ctx) string {
scheme, token, ok := strings.Cut(ctx.Get(fiber.HeaderAuthorization), " ")
if !ok || !strings.EqualFold(scheme, "Bearer") {
return ""
}
return token
}
// identity reads only the identity produced by successful session authentication.
func identity(ctx *fiber.Ctx) string {
value, _ := ctx.Locals(identityKey).(string)
return value
}
// requestGroup selects a bounded policy group from the HTTP operation.
func requestGroup(ctx *fiber.Ctx) string {
if ctx.Path() == "/api/v1/users" || strings.HasPrefix(ctx.Path(), "/api/v1/auth/") {
return "auth"
}
if ctx.Method() == http.MethodGet {
return "read"
}
return "write"
}
+161
View File
@@ -0,0 +1,161 @@
package fiber
import (
"context"
"encoding/base64"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
type sessionFixture struct {
fixtureAuthentication
login func(string, string) (dto.SessionDTO, error)
logoutError error
}
// Login delegates the credentials decoded by the controller to the arranged scenario.
func (f sessionFixture) Login(_ context.Context, username, password string) (dto.SessionDTO, error) {
return f.login(username, password)
}
// Logout returns the prescribed revocation outcome.
func (f sessionFixture) Logout(context.Context, string) error {
return f.logoutError
}
// TestLoginHTTPChecksBasicEncoding verifies independent wire-level login scenarios.
func TestLoginHTTPChecksBasicEncoding(t *testing.T) {
cases := []struct {
name string
header string
body string
status int
}{
{"missing header", "", "", http.StatusUnauthorized},
{"wrong scheme", "Bearer abc", "", http.StatusUnauthorized},
{"bad base64", "Basic %%%", "", http.StatusUnauthorized},
{"no delimiter", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice")), "", http.StatusUnauthorized},
{"unexpected body", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "{}", http.StatusBadRequest},
{"valid colon in password", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "", http.StatusCreated},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctrl := testController(t, nil)
ctrl.auth = sessionFixture{login: func(username, password string) (dto.SessionDTO, error) {
if username != "alice" || password != "long-password:ok" {
t.Fatal("credentials altered")
}
return dto.SessionDTO{Token: "opaque", ExpiresAt: time.Now().UTC().Add(time.Hour), User: dto.UserDTO{ID: uuid.New(), Username: "alice"}}, nil
}}
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader(tc.body))
req.Header.Set("Authorization", tc.header)
response, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != tc.status {
t.Fatalf("got %d want %d", response.StatusCode, tc.status)
}
if tc.status == http.StatusUnauthorized && response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatal("missing Basic challenge")
}
})
}
}
// TestLoginInvalidCredentialsUsesBasicChallenge checks the service rejection mapping.
func TestLoginInvalidCredentialsUsesBasicChallenge(t *testing.T) {
ctrl := testController(t, nil)
ctrl.auth = sessionFixture{login: func(string, string) (dto.SessionDTO, error) {
return dto.SessionDTO{}, service.ErrUnauthorized
}}
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
req.SetBasicAuth("alice", "invalid-password")
response, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatal("incorrect login rejection")
}
}
// TestLogoutHTTPReturnsNoContent checks the authenticated revocation response.
func TestLogoutHTTPReturnsNoContent(t *testing.T) {
ctrl := testController(t, nil)
actor := user(t, ctrl)
req := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
req.Header.Set("Authorization", "Bearer "+actor)
response, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = response.Body.Close()
}()
body, err := io.ReadAll(response.Body)
if err != nil || response.StatusCode != http.StatusNoContent || len(body) != 0 {
t.Fatalf("invalid logout response: %v", err)
}
}
// TestLogoutHTTPPreservesFailure ensures an unsuccessful revoke does not claim success.
func TestLogoutHTTPPreservesFailure(t *testing.T) {
ctrl := testController(t, nil)
actor := user(t, ctrl)
ctrl.auth = sessionFixture{fixtureAuthentication: fixtureAuthentication{ctrl.service}, logoutError: context.DeadlineExceeded}
status, _, err := request(ctrl, http.MethodDelete, "/api/v1/auth/sessions/current", actor, nil)
if err != nil || status != http.StatusInternalServerError {
t.Fatalf("revocation failure hidden: %d %v", status, err)
}
}
// TestLegacyIdentityDoesNotAuthenticate verifies the lab1 header cannot grant access.
func TestLegacyIdentityDoesNotAuthenticate(t *testing.T) {
ctrl := testController(t, nil)
actor := user(t, ctrl)
req := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
req.Header.Set("X-User-Id", actor)
response, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = response.Body.Close()
}()
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Bearer realm="messenger"` {
t.Fatal("legacy identity granted access or missing challenge")
}
}
type unavailableReadiness struct{}
// Ping simulates an unavailable mandatory dependency for readiness mapping.
func (unavailableReadiness) Ping(context.Context) error {
return context.DeadlineExceeded
}
// TestReadinessRejectsDependencyFailure verifies readiness reflects mandatory infrastructure.
func TestReadinessRejectsDependencyFailure(t *testing.T) {
ctrl := testController(t, nil)
ctrl.readiness = unavailableReadiness{}
status, _, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
if err != nil || status != http.StatusServiceUnavailable {
t.Fatalf("incorrect readiness: %d %v", status, err)
}
}
@@ -0,0 +1,69 @@
package fiber
import (
"context"
"encoding/json"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
)
// TestBodyLimitInstanceHeader verifies parser-generated 413 responses over a real TCP listener.
func TestBodyLimitInstanceHeader(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.HTTP.MaxBodyBytes = 64 << 10
cfg.HTTP.InstanceID = "body-limit-test-instance"
})
ctrl.cfg.Host = "127.0.0.1"
ctrl.cfg.Port = 0
address := make(chan string, 1)
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
address <- net.JoinHostPort(data.Host, data.Port)
return nil
})
if err := ctrl.Start(t.Context()); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := ctrl.Stop(ctx); err != nil {
t.Error(err)
}
})
client := &http.Client{Timeout: 3 * time.Second}
// Act.
response, err := client.Post("http://"+<-address+"/api/v1/users", "application/json", strings.NewReader(strings.Repeat("x", ctrl.cfg.MaxBodyBytes+1)))
if err != nil {
t.Fatal(err)
}
defer func() {
if err := response.Body.Close(); err != nil {
t.Error(err)
}
}()
// Assert.
if response.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("status=%d", response.StatusCode)
}
if instance := response.Header.Get("X-Instance-Id"); instance != ctrl.instanceID {
t.Fatalf("instance=%q, want %q", instance, ctrl.instanceID)
}
var body httpmodel.ErrorResponse
if err := json.NewDecoder(response.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body.Error.Code != "payload_too_large" || body.Error.RequestID == "" || body.Error.RequestID != response.Header.Get(headerRequestID) {
t.Fatalf("invalid error envelope: %+v", body)
}
}
@@ -0,0 +1,312 @@
package fiber
import (
"net/http"
"net/url"
"reflect"
"testing"
"github.com/google/uuid"
)
// TestController_ChatsCreate checks membership and request validation in isolated chats.
func TestController_ChatsCreate(t *testing.T) {
t.Run("Positive: caller included", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusCreated, body)
if body["title"] != "Team" || !reflect.DeepEqual(body["member_ids"], []any{actor}) {
t.Fatalf("chat fields changed: %v", body)
}
})
t.Run("Negative: empty members", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: duplicate members", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, actor}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: caller omitted", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
outsider := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{outsider}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: unknown member", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, uuid.NewString()}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: malformed member ID", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": "Team", "member_ids": []string{actor, "invalid"}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: blank title", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]any{"title": " ", "member_ids": []string{actor}})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: malformed JSON", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
payload := []byte(`{`)
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
}
// TestController_ChatsGetByID checks access and the returned chat identity.
func TestController_ChatsGetByID(t *testing.T) {
t.Run("Positive: member reads chat", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor, target := owner, id
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusOK, body)
if body["id"] != id || body["title"] != "Чат" {
t.Fatalf("wrong chat: %v", body)
}
})
t.Run("Negative: outsider", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor, target := user(t, ctrl), id
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusNotFound, body)
assertErrorCode(t, body, "not_found")
})
t.Run("Negative: unknown chat", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
actor, target := owner, uuid.NewString()
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusNotFound, body)
assertErrorCode(t, body, "not_found")
})
t.Run("Negative: malformed chat ID", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
actor, target := owner, "invalid"
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: authentication precedes ID parsing", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor, target := "", "invalid"
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+target, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
})
}
// TestController_ChatsGetPage checks that foreign memberships remain absent from lists.
func TestController_ChatsGetPage(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
chat(t, ctrl, owner)
outsider := user(t, ctrl)
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats", outsider, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusOK, body)
if len(body["items"].([]any)) != 0 || body["next_cursor"] != nil {
t.Fatalf("foreign chat leaked: %v", body)
}
}
// TestController_ChatPagination recovers every chat exactly once across page boundaries.
func TestController_ChatPagination(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
expected := make(map[string]bool)
for range 15 {
expected[chat(t, ctrl, actor)] = true
}
// Act.
items := history(t, ctrl, actor, "/api/v1/chats")
// Assert.
if len(items) != len(expected) {
t.Fatalf("got %d chats, want %d", len(items), len(expected))
}
for _, item := range items {
id := item.(map[string]any)["id"].(string)
if !expected[id] {
t.Fatalf("duplicate or unexpected chat %s", id)
}
delete(expected, id)
}
}
// TestController_ChatCursorScope rejects a continuation issued for another user's list.
func TestController_ChatCursorScope(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
outsider := user(t, ctrl)
chat(t, ctrl, owner)
chat(t, ctrl, owner)
page := call(t, ctrl, http.MethodGet, "/api/v1/chats?limit=1", owner, nil, http.StatusOK)
token := page["next_cursor"].(string)
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(token), outsider, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
}
@@ -0,0 +1,37 @@
package fiber
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
)
// configure initializes the HTTP server, middleware and routes.
func (ctrl *Controller) configure() {
ctrl.createServer()
ctrl.initMiddlewares()
ctrl.initRoutes()
}
// createServer creates Fiber with the configured transport limits and error handler.
func (ctrl *Controller) createServer() {
timeout := ctrl.cfg.Timeout()
ctrl.server = fiber.New(fiber.Config{
AppName: "messenger-lab1",
DisableStartupMessage: true,
Immutable: true,
CaseSensitive: true,
StrictRouting: true,
BodyLimit: ctrl.cfg.MaxBodyBytes,
Concurrency: ctrl.cfg.MaxConnections,
ReadTimeout: timeout,
WriteTimeout: timeout,
IdleTimeout: timeout,
ErrorHandler: ctrl.handleErr,
})
}
// initMiddlewares registers request logging and panic recovery middleware.
func (ctrl *Controller) initMiddlewares() {
ctrl.server.Use(ctrl.request)
ctrl.server.Use(recover.New())
}
@@ -0,0 +1,66 @@
// Package fiber implements the messenger HTTP transport using Fiber.
package fiber
import (
"fmt"
"sync/atomic"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"go.lab260.ru/fielderr"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/controller"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// Controller owns the HTTP server and delegates business operations to Service.
// Its configuration is copied at construction and must not change during serving.
// Fx manages its listener through Start and Stop.
type Controller struct {
attachments Attachments
metrics *httpMetrics
log *zap.Logger
cfg config.Controller
service service.Service
server *fiber.App
errorRegistry *fielderr.Registry
admission admission.Distributed
auth service.Authentication
readiness Readiness
stopping atomic.Bool
instanceID string
serveDone chan error
}
var _ controller.Controller = (*Controller)(nil)
// New validates dependencies and prepares the server without opening a listener.
// Routing, middleware and Fiber configuration are installed by configure.
func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry *fielderr.Registry, limiter admission.Distributed, auth service.Authentication, readiness Readiness) (*Controller, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
if log == nil || svc == nil || registry == nil || limiter == nil || auth == nil || readiness == nil {
return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required")
}
ctrl := &Controller{
metrics: newHTTPMetrics(),
log: log.Named("controller.http.fiber"),
cfg: *cfg,
service: svc,
errorRegistry: registry,
admission: limiter,
auth: auth,
readiness: readiness,
serveDone: make(chan error, 1),
}
ctrl.instanceID = cfg.InstanceID
if ctrl.instanceID == "" {
ctrl.instanceID = uuid.NewString()
}
ctrl.configure()
return ctrl, nil
}
@@ -0,0 +1,321 @@
package fiber
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store/memory"
)
// testController creates an integration fixture with the real controller, service and store.
func testController(t *testing.T, change func(*config.Config)) *Controller {
t.Helper()
cfg := config.Default()
cfg.HTTP.MaxConnections = 256
cfg.HTTP.Admission.RequestsPerSecond = 100000
cfg.HTTP.Admission.Burst = 100000
if change != nil {
change(cfg)
}
repo, err := memory.New(cfg.Memory)
if err != nil {
t.Fatal(err)
}
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
svc, err := production.New(repo, codec)
if err != nil {
t.Fatal(err)
}
registry, err := NewErrorRegistry()
if err != nil {
t.Fatal(err)
}
limiter, err := admission.New(admission.Options{
MaxInFlight: cfg.HTTP.Admission.MaxInFlight,
RequestsPerSecond: cfg.HTTP.Admission.RequestsPerSecond,
Burst: cfg.HTTP.Admission.Burst,
})
if err != nil {
t.Fatal(err)
}
ctrl, err := New(zap.NewNop(), cfg.HTTP, svc, registry, &fixtureAdmission{limiter}, fixtureAuthentication{svc}, fixtureReadiness{})
if err != nil {
t.Fatal(err)
}
return ctrl
}
// request sends a raw test request and decodes its response.
func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) {
req := httptest.NewRequest(method, path, bytes.NewReader(body))
req.Header.Set("Idempotency-Key", uuid.NewString())
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actor != "" {
req.Header.Set("Authorization", "Bearer "+actor)
}
resp, err := ctrl.server.Test(req, 10000)
if err != nil {
return 0, nil, err
}
defer func() {
_ = resp.Body.Close()
}()
b, err := io.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
var data map[string]any
if err = json.Unmarshal(b, &data); err != nil {
return resp.StatusCode, nil, fmt.Errorf("invalid JSON response: %w", err)
}
if resp.Header.Get("X-Request-Id") == "" {
return resp.StatusCode, data, fmt.Errorf("missing request ID")
}
if resp.StatusCode >= http.StatusBadRequest {
envelope, ok := data["error"].(map[string]any)
if !ok || envelope["request_id"] != resp.Header.Get("X-Request-Id") {
return resp.StatusCode, data, fmt.Errorf("invalid error envelope")
}
}
return resp.StatusCode, data, nil
}
// call sends a JSON test request and checks its expected HTTP status.
func call(t *testing.T, ctrl *Controller, method, path, actor string, body any, want int) map[string]any {
t.Helper()
var b []byte
var err error
if raw, ok := body.([]byte); ok {
b = raw
} else if body != nil {
b, err = json.Marshal(body)
if err != nil {
t.Fatal(err)
}
}
status, data, err := request(ctrl, method, path, actor, b)
if err != nil {
t.Fatal(err)
}
if status != want {
t.Fatalf("%s %s: got %d want %d: %v", method, path, status, want, data)
}
return data
}
// user creates a test user and returns its identifier.
func user(t *testing.T, c *Controller) string {
t.Helper()
r := call(t, c, http.MethodPost, "/api/v1/users", "", map[string]any{"username": "u_" + uuid.New().String()[:8], "display_name": "Алиса 👋", "password": "fixture-password-123"}, http.StatusCreated)
return r["id"].(string)
}
// chat creates a test chat containing the supplied user.
func chat(t *testing.T, c *Controller, u string) string {
t.Helper()
r := call(t, c, http.MethodPost, "/api/v1/chats", u, map[string]any{"title": "Чат", "member_ids": []string{u}}, http.StatusCreated)
return r["id"].(string)
}
// TestDuplicateUsernameRace checks username uniqueness under concurrent requests.
func TestDuplicateUsernameRace(t *testing.T) {
// Arrange.
c := testController(t, nil)
results := make(chan int, 10)
failures := make(chan error, 10)
var wg sync.WaitGroup
// Act.
for range 10 {
wg.Go(func() {
status, _, err := request(c, http.MethodPost, "/api/v1/users", "", []byte(`{"username":"same","display_name":"User","password":"fixture-password-123"}`))
if err != nil {
failures <- err
}
results <- status
})
}
wg.Wait()
close(results)
close(failures)
// Assert.
for err := range failures {
t.Error(err)
}
created, conflicts := 0, 0
for s := range results {
switch s {
case http.StatusCreated:
created++
case http.StatusConflict:
conflicts++
default:
t.Errorf("unexpected %d", s)
}
}
if created != 1 || conflicts != 9 {
t.Fatalf("created=%d conflicts=%d", created, conflicts)
}
}
// history collects all test messages by following pagination cursors.
func history(t *testing.T, c *Controller, u, path string) []any {
t.Helper()
var items []any
next := path + "?limit=7"
for range 100 {
r := call(t, c, http.MethodGet, next, u, nil, http.StatusOK)
items = append(items, r["items"].([]any)...)
if r["next_cursor"] == nil {
return items
}
next = path + "?limit=7&cursor=" + url.QueryEscape(r["next_cursor"].(string))
}
t.Fatal("pagination never finished")
return nil
}
// TestConcurrent100Messages10Clients recovers the exact acknowledged records after concurrent writes.
func TestConcurrent100Messages10Clients(t *testing.T) {
// Arrange.
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
ctrl := testController(t, nil)
actor := user(t, ctrl)
chatID := chat(t, ctrl, actor)
path := "/api/v1/chats/" + chatID + "/messages"
acknowledgements := make(chan map[string]any, total)
failures := make(chan error, total)
var writers sync.WaitGroup
// Act.
for client := range clients {
writers.Go(func() {
for index := range messagesPerClient {
text := fmt.Sprintf("client %d message %d", client, index)
payload, err := json.Marshal(map[string]string{"text": text})
if err != nil {
failures <- err
continue
}
status, body, err := request(ctrl, http.MethodPost, path, actor, payload)
if err != nil {
failures <- err
continue
}
if status != http.StatusCreated || body["text"] != text || body["sender_id"] != actor || body["chat_id"] != chatID {
failures <- fmt.Errorf("incorrect acknowledgement: status=%d, body=%v", status, body)
continue
}
acknowledgements <- body
}
})
}
writers.Wait()
close(failures)
close(acknowledgements)
// Assert.
for err := range failures {
t.Error(err)
}
if t.Failed() {
t.FailNow()
}
expected := make(map[string]map[string]any, total)
for message := range acknowledgements {
id, ok := message["id"].(string)
if !ok || id == "" {
t.Fatalf("invalid message ID: %v", message)
}
if _, duplicate := expected[id]; duplicate {
t.Fatalf("duplicate acknowledgement ID %s", id)
}
expected[id] = message
}
if len(expected) != total {
t.Fatalf("acknowledged=%d, want=%d", len(expected), total)
}
items := history(t, ctrl, actor, path)
if len(items) != total {
t.Fatalf("recovered=%d, want=%d", len(items), total)
}
for _, item := range items {
message := item.(map[string]any)
id := message["id"].(string)
if !reflect.DeepEqual(message, expected[id]) {
t.Fatalf("stored record differs from acknowledgement: got=%v, want=%v", message, expected[id])
}
delete(expected, id)
}
}
// TestUnsupportedMediaType checks rejection of unsupported request content types.
func TestUnsupportedMediaType(t *testing.T) {
// Arrange.
c := testController(t, nil)
req := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "text/plain")
// Act.
r, e := c.server.Test(req)
// Assert.
if e != nil {
t.Fatal(e)
}
defer func() {
_ = r.Body.Close()
}()
if r.StatusCode != http.StatusUnsupportedMediaType {
t.Fatalf("status %d", r.StatusCode)
}
}
// TestConfigIndependentState prevents one application instance from accepting another's identity.
func TestConfigIndependentState(t *testing.T) {
// Arrange.
first := testController(t, nil)
actor := user(t, first)
second := testController(t, nil)
// Act.
status, body, err := request(second, http.MethodGet, "/api/v1/users/me", actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
}
// mustJSON encodes fixture payloads and reports preparation failures at the caller.
func mustJSON(t *testing.T, value any) []byte {
t.Helper()
payload, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
return payload
}
+34
View File
@@ -0,0 +1,34 @@
package fiber
import (
"mime"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/strictjson"
)
// decode checks HTTP media type and maps strict JSON decoding errors to API input errors.
func decode(ctx *fiber.Ctx, target any, requiredFields ...string) error {
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
if err != nil || mediaType != fiber.MIMEApplicationJSON {
return errMedia
}
if err := strictjson.DecodeObject(ctx.Body(), target, requiredFields...); err != nil {
return service.ErrInvalid
}
return nil
}
// decodeMessage accepts the optional attachment list without weakening strict JSON validation.
func decodeMessage(ctx *fiber.Ctx, target any) error {
mediaType, _, err := mime.ParseMediaType(ctx.Get(fiber.HeaderContentType))
if err != nil || mediaType != fiber.MIMEApplicationJSON {
return errMedia
}
if err := strictjson.DecodeOptional(ctx.Body(), target, []string{"text"}, []string{"attachment_ids"}); err != nil {
return service.ErrInvalid
}
return nil
}
@@ -0,0 +1,9 @@
package fiber
import "context"
// Readiness checks the dependencies required by the synchronous request path.
type Readiness interface {
// Ping reports whether requests can be safely served.
Ping(context.Context) error
}
@@ -0,0 +1,22 @@
package fiber
const (
// codeInvalid identifies malformed or invalid request input.
codeInvalid = "invalid_request"
// codeUnauthorized identifies an unresolved user identity.
codeUnauthorized = "unauthorized"
// codeNotFound deliberately covers both absent and inaccessible resources.
codeNotFound = "not_found"
// codeConflict identifies a violated uniqueness constraint.
codeConflict = "conflict"
// codeUnavailable identifies temporary admission or persistent capacity exhaustion.
codeUnavailable = "unavailable"
// codeRateLimited identifies exhaustion of the request token bucket.
codeRateLimited = "rate_limited"
// codeTooLarge identifies a request exceeding the transport byte budget.
codeTooLarge = "payload_too_large"
// codeMedia identifies an unsupported request media type.
codeMedia = "unsupported_media_type"
// codeInternal identifies a hidden unexpected failure.
codeInternal = "internal_error"
)
@@ -0,0 +1,33 @@
package fiber
import (
"net/http"
"go.lab260.ru/fielderr"
)
// NewErrorRegistry returns an immutable mapping of application statuses to HTTP codes.
// The registry is injected rather than installed in process-global state, allowing
// independent application instances in integration tests.
func NewErrorRegistry() (*fielderr.Registry, error) {
return fielderr.NewRegistry(
statusDefinition(codeInvalid, http.StatusBadRequest),
statusDefinition(codeUnauthorized, http.StatusUnauthorized),
statusDefinition(codeNotFound, http.StatusNotFound),
statusDefinition(codeConflict, http.StatusConflict),
statusDefinition(codeTooLarge, http.StatusRequestEntityTooLarge),
statusDefinition(codeMedia, http.StatusUnsupportedMediaType),
statusDefinition(codeRateLimited, http.StatusTooManyRequests),
statusDefinition(codeUnavailable, http.StatusServiceUnavailable),
statusDefinition(codeInternal, http.StatusInternalServerError),
)
}
// statusDefinition associates an application error code with its HTTP status.
func statusDefinition(name string, httpStatus int) fielderr.StatusDefinition {
return fielderr.StatusDefinition{
Code: fielderr.NewStatusCode(name),
Name: name,
HTTPStatus: httpStatus,
}
}
+73
View File
@@ -0,0 +1,73 @@
package fiber
import (
"errors"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"go.lab260.ru/fielderr"
"go.uber.org/zap"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// handleErr normalizes a failure and writes the public error envelope.
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
// Parser failures such as BodyLimit rejection bypass request middleware.
ctx.Set("X-Instance-Id", ctrl.instanceID)
requestID := ctx.GetRespHeader(headerRequestID)
if requestID == "" {
requestID = uuid.NewString()
ctx.Set(headerRequestID, requestID)
}
err = publicError(normalizeTransportError(err))
status, ok := fielderr.HTTPStatusFrom(ctrl.errorRegistry, err)
if !ok {
err = errInternal
status = http.StatusInternalServerError
}
if status == http.StatusUnauthorized {
challenge := `Bearer realm="messenger"`
if ctx.Path() == "/api/v1/auth/sessions" && ctx.Method() == http.MethodPost {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
ctx.Set(fiber.HeaderWWWAuthenticate, challenge)
}
if status == http.StatusInternalServerError {
ctrl.log.Error("unexpected request failure", zap.String("request_id", requestID))
}
return ctx.Status(status).JSON(errorResponse(err, requestID))
}
// normalizeTransportError maps Fiber failures to transport-independent application errors.
func normalizeTransportError(err error) error {
transportError, ok := errors.AsType[*fiber.Error](err)
if !ok {
return err
}
switch transportError.Code {
case http.StatusRequestEntityTooLarge:
return errTooLarge
case http.StatusNotFound, http.StatusMethodNotAllowed:
return service.ErrNotFound
case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestHeaderFieldsTooLarge:
return service.ErrInvalid
default:
return errInternal
}
}
// errorResponse builds the public error envelope with its request identifier.
func errorResponse(err error, requestID string) httpmodel.ErrorResponse {
status, _ := fielderr.Status(err)
message, _ := fielderr.PublicMessage(err)
return httpmodel.ErrorResponse{
Error: httpmodel.ErrorDetail{
Code: status.String(),
Message: message,
RequestID: requestID,
},
}
}
@@ -0,0 +1,107 @@
package fiber
import (
"encoding/json"
"errors"
"net/http"
"testing"
"github.com/gofiber/fiber/v2"
"github.com/valyala/fasthttp"
"go.lab260.ru/fielderr"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// TestTransportErrorMapping checks safe API errors for framework-generated failures.
func TestTransportErrorMapping(t *testing.T) {
t.Run("large body", func(t *testing.T) {
if normalizeTransportError(fiber.ErrRequestEntityTooLarge) != errTooLarge {
t.Fatal("incorrect body-limit error")
}
})
t.Run("method not allowed", func(t *testing.T) {
if normalizeTransportError(fiber.ErrMethodNotAllowed) != service.ErrNotFound {
t.Fatal("unexpected method error")
}
})
t.Run("invalid request", func(t *testing.T) {
if normalizeTransportError(fiber.ErrBadRequest) != service.ErrInvalid {
t.Fatal("unexpected input error")
}
})
t.Run("unexpected framework failure", func(t *testing.T) {
if normalizeTransportError(fiber.ErrInternalServerError) != errInternal {
t.Fatal("unexpected failure escaped normalization")
}
})
}
// TestController_handleErr writes a safe, correlated fallback response.
func TestController_handleErr(t *testing.T) {
t.Run("Negative: unknown internal error", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
raw := &fasthttp.RequestCtx{}
ctx := ctrl.server.AcquireCtx(raw)
defer ctrl.server.ReleaseCtx(ctx)
// Act.
err := ctrl.handleErr(ctx, errors.New("private storage secret"))
// Assert.
if err != nil {
t.Fatal(err)
}
if raw.Response.StatusCode() != http.StatusInternalServerError {
t.Fatalf("status=%d", raw.Response.StatusCode())
}
var body httpmodel.ErrorResponse
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
t.Fatal(err)
}
requestID := string(raw.Response.Header.Peek(headerRequestID))
if requestID == "" || body.Error.RequestID != requestID {
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
}
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
t.Fatalf("unsafe fallback: %+v", body)
}
})
t.Run("Negative: missing status mapping", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
registry, err := fielderr.NewRegistry()
if err != nil {
t.Fatal(err)
}
ctrl.errorRegistry = registry
raw := &fasthttp.RequestCtx{}
ctx := ctrl.server.AcquireCtx(raw)
defer ctrl.server.ReleaseCtx(ctx)
// Act.
err = ctrl.handleErr(ctx, service.ErrInvalid)
// Assert.
if err != nil {
t.Fatal(err)
}
if raw.Response.StatusCode() != http.StatusInternalServerError {
t.Fatalf("status=%d", raw.Response.StatusCode())
}
var body httpmodel.ErrorResponse
if err := json.Unmarshal(raw.Response.Body(), &body); err != nil {
t.Fatal(err)
}
requestID := string(raw.Response.Header.Peek(headerRequestID))
if requestID == "" || body.Error.RequestID != requestID {
t.Fatalf("uncorrelated error: %+v, header=%q", body, requestID)
}
if body.Error.Code != "internal_error" || body.Error.Message != "internal server error" {
t.Fatalf("unsafe fallback: %+v", body)
}
})
}
@@ -0,0 +1,61 @@
package fiber
import (
"context"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// fixtureAuthentication isolates HTTP decoding and business authorization from session persistence.
type fixtureAuthentication struct {
service service.Service
}
// Register delegates profile validation to the real business service.
func (f fixtureAuthentication) Register(ctx context.Context, request dto.UsersCreateRequestDTO, _ string) (dto.UserDTO, error) {
return f.service.UsersCreate(ctx, request)
}
// Authenticate uses fixture tokens equal to user IDs exclusively in controller tests.
func (f fixtureAuthentication) Authenticate(ctx context.Context, token string) (string, error) {
return token, f.service.UsersCheckIdentity(ctx, token)
}
// Login is deliberately unsupported by this fixture; real login has separate integration coverage.
func (f fixtureAuthentication) Login(context.Context, string, string) (dto.SessionDTO, error) {
return dto.SessionDTO{}, service.ErrUnauthorized
}
// Logout accepts the fixture session without persistent side effects.
func (f fixtureAuthentication) Logout(context.Context, string) error {
return nil
}
type fixtureReadiness struct{}
// Ping marks isolated controller fixtures ready without external resources.
func (fixtureReadiness) Ping(context.Context) error {
return nil
}
type fixtureAdmission struct {
*admission.Limiter
}
// Enter adapts the deterministic local policy fixture to the distributed boundary.
func (f *fixtureAdmission) Enter(_ context.Context, _, user string) (func(), error) {
if user != "" {
return func() {
}, nil
}
if !f.Allow(time.Now()) {
return nil, admission.ErrRate
}
if !f.Acquire() {
return nil, admission.ErrSlots
}
return f.Release, nil
}
@@ -0,0 +1,98 @@
package fiber
import (
"net/http"
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
)
// HandleUsersCreate decodes registration input and returns the created user.
func (ctrl *Controller) HandleUsersCreate(ctx *fiber.Ctx) error {
var request httpmodel.UsersCreateRequest
if err := decode(ctx, &request, "username", "display_name", "password"); err != nil {
return err
}
user, err := ctrl.auth.Register(ctx.UserContext(), dto.UsersCreateRequestDTO{
Username: request.Username,
DisplayName: request.DisplayName,
}, request.Password)
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(userResponse(user))
}
// HandleUsersGetMe returns the account selected by the validated session.
func (ctrl *Controller) HandleUsersGetMe(ctx *fiber.Ctx) error {
user, err := ctrl.service.UsersGetMe(ctx.UserContext(), identity(ctx))
if err != nil {
return err
}
return ctx.Status(http.StatusOK).JSON(userResponse(user))
}
// HandleChatsCreate decodes the chat payload and returns the new chat.
func (ctrl *Controller) HandleChatsCreate(ctx *fiber.Ctx) error {
var request httpmodel.ChatsCreateRequest
if err := decode(ctx, &request, "title", "member_ids"); err != nil {
return err
}
chat, err := ctrl.service.ChatsCreate(ctx.UserContext(), dto.ChatsCreateRequestDTO{
UserID: identity(ctx),
Title: request.Title,
MemberIDs: request.MemberIDs,
})
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(chatResponse(chat))
}
// HandleChatsGetByID delegates chat authorization and maps the accessible chat.
func (ctrl *Controller) HandleChatsGetByID(ctx *fiber.Ctx) error {
chat, err := ctrl.service.ChatsGetByID(ctx.UserContext(), identity(ctx), ctx.Params("chat_id"))
if err != nil {
return err
}
return ctx.Status(http.StatusOK).JSON(chatResponse(chat))
}
// HandleChatsGetPage returns the service's page of visible chats.
func (ctrl *Controller) HandleChatsGetPage(ctx *fiber.Ctx) error {
page, err := ctrl.service.ChatsGetPage(ctx.UserContext(), pageRequest(ctx))
if err != nil {
return err
}
return ctx.Status(http.StatusOK).JSON(chatPageResponse(page))
}
// HandleMessagesCreate decodes text; the service derives and authorizes the sender.
func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error {
var request httpmodel.MessagesCreateRequest
if err := decodeMessage(ctx, &request); err != nil {
return err
}
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
AttachmentIDs: request.AttachmentIDs,
IdempotencyKey: ctx.Get("Idempotency-Key"),
UserID: identity(ctx),
ChatID: ctx.Params("chat_id"),
Text: request.Text,
})
if err != nil {
return err
}
return ctx.Status(http.StatusCreated).JSON(messageResponse(message))
}
// HandleMessagesGetPage returns the service's ordered history page.
func (ctrl *Controller) HandleMessagesGetPage(ctx *fiber.Ctx) error {
page, err := ctrl.service.MessagesGetPage(ctx.UserContext(), pageRequest(ctx))
if err != nil {
return err
}
return ctx.Status(http.StatusOK).JSON(messagePageResponse(page))
}
@@ -0,0 +1,7 @@
package fiber
const (
headerUserID = "X-User-Id"
headerRequestID = "X-Request-Id"
retryAfterSeconds = 1
)
+28
View File
@@ -0,0 +1,28 @@
package fiber
import (
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// handleLive reports that the server process is running.
func (ctrl *Controller) handleLive(ctx *fiber.Ctx) error {
return ctx.JSON(fiber.Map{"status": "ok"})
}
// handleReady reports readiness unless shutdown has started.
func (ctrl *Controller) handleReady(ctx *fiber.Ctx) error {
if ctrl.stopping.Load() {
return errBusy
}
if err := ctrl.readiness.Ping(ctx.UserContext()); err != nil {
return errBusy
}
return ctrl.handleLive(ctx)
}
// handleNotFound returns the application error for an unmatched route.
func (ctrl *Controller) handleNotFound(_ *fiber.Ctx) error {
return service.ErrNotFound
}
@@ -0,0 +1,70 @@
package fiber
import (
"context"
"net"
"sync"
"go.uber.org/zap"
)
// Start opens the listener synchronously so Fx observes bind errors immediately.
// It must be called once per Controller; Stop terminates the serving goroutine.
func (ctrl *Controller) Start(ctx context.Context) error {
listener, err := net.Listen("tcp", ctrl.cfg.Bind())
if err != nil {
return err
}
ready := make(chan struct{})
go ctrl.serve(&acceptingListener{Listener: listener, ready: ready})
select {
case <-ready:
ctrl.log.Info("http listener started", zap.String("address", listener.Addr().String()))
return nil
case err := <-ctrl.serveDone:
return err
case <-ctx.Done():
_ = listener.Close()
return ctx.Err()
}
}
// acceptingListener signals after fasthttp registers the listener and enters its
// accept loop. An OnListen hook runs earlier and cannot guarantee safe immediate Stop.
type acceptingListener struct {
// Listener is the bound socket owned by the HTTP lifecycle.
net.Listener
ready chan struct{}
once sync.Once
}
// Accept marks the server as started before waiting for the next connection.
func (listener *acceptingListener) Accept() (net.Conn, error) {
listener.once.Do(func() {
close(listener.ready)
})
return listener.Listener.Accept()
}
// serve serves the listener and publishes its terminal result to the lifecycle.
func (ctrl *Controller) serve(listener net.Listener) {
ctrl.serveDone <- ctrl.server.Listener(listener)
}
// Stop disables admission, closes the listener and drains active requests.
// The configured timeout is bounded by the caller's Fx shutdown context.
func (ctrl *Controller) Stop(ctx context.Context) error {
ctrl.stopping.Store(true)
ctx, cancel := context.WithTimeout(ctx, ctrl.cfg.ShutdownTimeout())
defer cancel()
if err := ctrl.server.ShutdownWithContext(ctx); err != nil {
return err
}
select {
case err := <-ctrl.serveDone:
ctrl.log.Info("http listener stopped")
return err
case <-ctx.Done():
return ctx.Err()
}
}
@@ -0,0 +1,132 @@
package fiber
import (
"context"
"errors"
"net"
"net/http"
"testing"
"time"
"github.com/gofiber/fiber/v2"
)
// TestImmediateShutdown checks the startup/stop race without waiting for a first request.
func TestImmediateShutdown(t *testing.T) {
const repetitions = 10
const stopDeadline = time.Second
for range repetitions {
// Arrange.
ctrl := testController(t, nil)
// Select an ephemeral test port after validating the normal application config.
ctrl.cfg.Host = "127.0.0.1"
ctrl.cfg.Port = 0
if err := ctrl.Start(t.Context()); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), stopDeadline)
// Act.
err := ctrl.Stop(ctx)
cancel()
// Assert.
if err != nil {
t.Fatalf("immediate shutdown leaked the listener or serve goroutine: %v", err)
}
}
}
// TestController_Stop_ActiveRequestDeadline bounds draining while a real handler is still running.
func TestController_Stop_ActiveRequestDeadline(t *testing.T) {
// Arrange.
const deadline = 3 * time.Second
ctrl := testController(t, nil)
ctrl.cfg.Host = "127.0.0.1"
ctrl.cfg.Port = 0
// Install one controlled handler to test lifecycle independently of business routes.
ctrl.createServer()
entered := make(chan struct{})
release := make(chan struct{})
address := make(chan string, 1)
ctrl.server.Hooks().OnListen(func(data fiber.ListenData) error {
address <- net.JoinHostPort(data.Host, data.Port)
return nil
})
ctrl.server.Get("/blocked", func(ctx *fiber.Ctx) error {
close(entered)
<-release
return ctx.SendStatus(http.StatusOK)
})
if err := ctrl.Start(t.Context()); err != nil {
t.Fatal(err)
}
client := &http.Client{Timeout: deadline}
completed := make(chan error, 1)
go func() {
response, err := client.Get("http://" + <-address + "/blocked")
if err == nil {
err = response.Body.Close()
}
completed <- err
}()
t.Cleanup(func() {
close(release)
select {
case err := <-completed:
if err != nil {
t.Error(err)
}
case <-time.After(deadline):
t.Error("blocked request did not terminate after release")
}
stopCtx, cancel := context.WithTimeout(context.Background(), deadline)
defer cancel()
if err := ctrl.Stop(stopCtx); err != nil {
t.Error(err)
}
})
select {
case <-entered:
case <-time.After(deadline):
t.Fatal("request did not reach handler")
}
ctx, cancel := context.WithCancel(t.Context())
cancel()
// Act.
err := ctrl.Stop(ctx)
// Assert.
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected canceled drain, got %v", err)
}
if !ctrl.stopping.Load() {
t.Fatal("shutdown did not disable admission")
}
}
// TestCanceledStartup closes its socket while server initialization is still blocked.
func TestCanceledStartup(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
ctrl.cfg.Host = "127.0.0.1"
ctrl.cfg.Port = 0
release := make(chan struct{})
ctrl.server.Hooks().OnListen(func(_ fiber.ListenData) error {
<-release
return nil
})
ctx, cancel := context.WithCancel(t.Context())
cancel()
// Act.
err := ctrl.Start(ctx)
close(release)
// Assert.
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected canceled startup, got %v", err)
}
select {
case <-ctrl.serveDone:
case <-time.After(time.Second):
t.Fatal("serving goroutine leaked after canceled startup")
}
}
+79
View File
@@ -0,0 +1,79 @@
package fiber
import (
"github.com/gofiber/fiber/v2"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/http"
)
// userResponse converts a user DTO into its HTTP representation.
func userResponse(user dto.UserDTO) httpmodel.UserResponse {
return httpmodel.UserResponse{
ID: user.ID.String(),
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: user.CreatedAt,
}
}
// chatResponse converts a chat DTO and its member identifiers into an HTTP response.
func chatResponse(chat dto.ChatDTO) httpmodel.ChatResponse {
members := make([]string, len(chat.MemberIDs))
for index, id := range chat.MemberIDs {
members[index] = id.String()
}
return httpmodel.ChatResponse{
ID: chat.ID.String(),
Title: chat.Title,
MemberIDs: members,
CreatedAt: chat.CreatedAt,
}
}
// messageResponse converts a message DTO into its HTTP representation.
func messageResponse(message dto.MessageDTO) httpmodel.MessageResponse {
ids := append([]string{}, message.AttachmentIDs...)
return httpmodel.MessageResponse{
AttachmentIDs: ids,
ID: message.ID.String(),
ChatID: message.ChatID.String(),
SenderID: message.SenderID.String(),
Text: message.Text,
CreatedAt: message.CreatedAt,
}
}
// pageRequest extracts identity, resource and pagination parameters from the request.
func pageRequest(ctx *fiber.Ctx) dto.PageRequestDTO {
return dto.PageRequestDTO{
UserID: identity(ctx),
ChatID: ctx.Params("chat_id"),
Limit: ctx.Query("limit"),
Cursor: ctx.Query("cursor"),
}
}
// chatPageResponse converts a page of chat DTOs into an HTTP response.
func chatPageResponse(page dto.ChatPageDTO) httpmodel.ChatPageResponse {
response := httpmodel.ChatPageResponse{
Items: make([]httpmodel.ChatResponse, len(page.Items)),
NextCursor: page.NextCursor,
}
for index, chat := range page.Items {
response.Items[index] = chatResponse(chat)
}
return response
}
// messagePageResponse converts a page of message DTOs into an HTTP response.
func messagePageResponse(page dto.MessagePageDTO) httpmodel.MessagePageResponse {
response := httpmodel.MessagePageResponse{
Items: make([]httpmodel.MessageResponse, len(page.Items)),
NextCursor: page.NextCursor,
}
for index, message := range page.Items {
response.Items[index] = messageResponse(message)
}
return response
}
@@ -0,0 +1,270 @@
package fiber
import (
"net/http"
"net/url"
"strings"
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
)
// TestController_MessagesCreate checks message validation and identity-derived sender fields.
func TestController_MessagesCreate(t *testing.T) {
t.Run("Positive: Unicode at rune limit", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := owner
text := strings.Repeat("界", 4000)
payload := mustJSON(t, map[string]string{"text": text})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusCreated, body)
if body["sender_id"] != owner || body["chat_id"] != id || body["text"] != text {
t.Fatalf("message fields changed: %v", body)
}
})
t.Run("Negative: empty text", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := owner
payload := mustJSON(t, map[string]string{"text": ""})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: whitespace text", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := owner
payload := mustJSON(t, map[string]string{"text": " \n\t"})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: text exceeds rune limit", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := owner
payload := mustJSON(t, map[string]string{"text": strings.Repeat("界", 4001)})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: sender spoof", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := owner
outsider := user(t, ctrl)
payload := mustJSON(t, map[string]string{"text": "hello", "sender_id": outsider})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
})
t.Run("Negative: outsider", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := user(t, ctrl)
payload := mustJSON(t, map[string]string{"text": "hello"})
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusNotFound, body)
assertErrorCode(t, body, "not_found")
})
t.Run("Negative: authentication precedes JSON decoding", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
owner := user(t, ctrl)
id := chat(t, ctrl, owner)
actor := ""
payload := []byte(`{`)
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/chats/"+id+"/messages", actor, payload)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
})
}
// TestController_MessagesGetPage rejects invalid pagination separately from access failures.
func TestController_MessagesGetPage(t *testing.T) {
cases := []struct {
name string
query string
outsider bool
status int
code string
}{
{"Negative: zero limit", "limit=0", false, http.StatusBadRequest, "invalid_request"},
{"Negative: limit above maximum", "limit=101", false, http.StatusBadRequest, "invalid_request"},
{"Negative: negative limit", "limit=-1", false, http.StatusBadRequest, "invalid_request"},
{"Negative: nonnumeric limit", "limit=x", false, http.StatusBadRequest, "invalid_request"},
{"Negative: fractional limit", "limit=1.0", false, http.StatusBadRequest, "invalid_request"},
{"Negative: malformed cursor", "cursor=invalid", false, http.StatusBadRequest, "invalid_request"},
{"Negative: outsider", "", true, http.StatusNotFound, "not_found"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
id := chat(t, ctrl, actor)
if tc.outsider {
actor = user(t, ctrl)
}
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+id+"/messages?"+tc.query, actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, tc.status, body)
assertErrorCode(t, body, tc.code)
})
}
}
// TestController_MessageCursorScope rejects a continuation from another chat's history.
func TestController_MessageCursorScope(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
first := chat(t, ctrl, actor)
second := chat(t, ctrl, actor)
path := "/api/v1/chats/" + first + "/messages"
for _, text := range []string{"first", "second"} {
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
}
page := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
token := page["next_cursor"].(string)
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/chats/"+second+"/messages?cursor="+url.QueryEscape(token), actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusBadRequest, body)
assertErrorCode(t, body, "invalid_request")
}
// TestController_MessagePageLimitChange preserves continuation when the client changes page size.
func TestController_MessagePageLimitChange(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
for _, text := range []string{"first", "second", "third"} {
call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": text}, http.StatusCreated)
}
first := call(t, ctrl, http.MethodGet, path+"?limit=1", actor, nil, http.StatusOK)
token := first["next_cursor"].(string)
// Act.
status, body, err := request(ctrl, http.MethodGet, path+"?limit=100&cursor="+url.QueryEscape(token), actor, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusOK, body)
items := body["items"].([]any)
if len(items) != 2 || body["next_cursor"] != nil {
t.Fatalf("unexpected final page: %v", body)
}
if items[0].(map[string]any)["text"] != "second" || items[1].(map[string]any)["text"] != "third" {
t.Fatalf("lost order or skipped messages: %v", items)
}
}
// TestController_MessageCapacity preserves acknowledged data after rejecting an overflow write.
func TestController_MessageCapacity(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.Memory.MaxMessages = 2
})
actor := user(t, ctrl)
path := "/api/v1/chats/" + chat(t, ctrl, actor) + "/messages"
first := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "first"}, http.StatusCreated)
second := call(t, ctrl, http.MethodPost, path, actor, map[string]string{"text": "second"}, http.StatusCreated)
// Act.
status, body, err := request(ctrl, http.MethodPost, path, actor, []byte(`{"text":"rejected"}`))
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusServiceUnavailable, body)
assertErrorCode(t, body, "unavailable")
items := history(t, ctrl, actor, path)
if len(items) != 2 || items[0].(map[string]any)["id"] != first["id"] || items[1].(map[string]any)["id"] != second["id"] {
t.Fatalf("overflow changed acknowledged messages: %v", items)
}
}
+61
View File
@@ -0,0 +1,61 @@
package fiber
import (
"net/http"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// httpMetrics owns a per-server registry with bounded labels and no user identifiers.
type httpMetrics struct {
registry *prometheus.Registry
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
active prometheus.Gauge
}
// newHTTPMetrics creates independent collectors so multiple test servers do not share state.
func newHTTPMetrics() *httpMetrics {
metrics := &httpMetrics{
registry: prometheus.NewRegistry(),
requests: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "messenger_http_requests_total", Help: "Completed requests by route, method and status class."}, []string{"route", "method", "status_class"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "messenger_http_duration_seconds", Help: "Completed request latency.", Buckets: prometheus.DefBuckets}, []string{"route", "method"}),
active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "messenger_http_in_flight", Help: "Currently executing HTTP requests."}),
}
metrics.registry.MustRegister(metrics.requests, metrics.duration, metrics.active)
return metrics
}
// observe records bounded route patterns, methods and status classes after error handling.
func (m *httpMetrics) observe(ctx *fiber.Ctx, elapsed time.Duration) {
route := "unmatched"
if ctx.Route() != nil && ctx.Route().Path != "/" {
route = ctx.Route().Path
}
method := ctx.Method()
switch method {
case http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodHead, http.MethodOptions:
default:
method = "other"
}
status := "5xx"
switch ctx.Response().StatusCode() / 100 {
case 2:
status = "2xx"
case 3:
status = "3xx"
case 4:
status = "4xx"
}
m.requests.WithLabelValues(route, method, status).Inc()
m.duration.WithLabelValues(route, method).Observe(elapsed.Seconds())
}
// handleMetrics exposes this process's Prometheus registry without external backend calls.
func (ctrl *Controller) handleMetrics(ctx *fiber.Ctx) error {
return adaptor.HTTPHandler(promhttp.HandlerFor(ctrl.metrics.registry, promhttp.HandlerOpts{}))(ctx)
}
@@ -0,0 +1,38 @@
package fiber
import (
"net/http"
"testing"
"time"
"github.com/valyala/fasthttp"
)
// TestMetricsBoundUnknownMethods keeps arbitrary client methods out of metric labels.
func TestMetricsBoundUnknownMethods(t *testing.T) {
ctrl := testController(t, nil)
raw := &fasthttp.RequestCtx{}
raw.Request.Header.SetMethod("CUSTOM_RANDOM_METHOD")
raw.Response.SetStatusCode(http.StatusTemporaryRedirect)
ctx := ctrl.server.AcquireCtx(raw)
defer ctrl.server.ReleaseCtx(ctx)
ctrl.metrics.observe(ctx, time.Millisecond)
families, err := ctrl.metrics.registry.Gather()
if err != nil {
t.Fatal(err)
}
found := false
for _, family := range families {
for _, metric := range family.Metric {
for _, label := range metric.Label {
if label.GetValue() == "CUSTOM_RANDOM_METHOD" {
t.Fatal("unbounded method label")
}
found = found || label.GetValue() == "other"
}
}
}
if !found {
t.Fatal("unknown method was not grouped")
}
}
@@ -0,0 +1,73 @@
package fiber
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestMetricsEndpoint exposes completed requests without token or user labels.
func TestMetricsEndpoint(t *testing.T) {
ctrl := testController(t, nil)
call(t, ctrl, http.MethodGet, "/health/live", "", nil, http.StatusOK)
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, "/metrics", nil))
if err != nil {
t.Fatal(err)
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "messenger_http_requests_total") || !strings.Contains(string(body), "messenger_http_duration_seconds_bucket") {
t.Fatalf("invalid metrics response: status %d", resp.StatusCode)
}
if resp.Header.Get("X-Instance-Id") == "" {
t.Fatal("metrics response lacks instance ID")
}
}
// TestInstanceIdentityRemainsStable verifies errors and successes identify the same process.
func TestInstanceIdentityRemainsStable(t *testing.T) {
ctrl := testController(t, nil)
var instance string
for _, path := range []string{"/health/live", "/unknown"} {
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, path, nil))
if err != nil {
t.Fatal(err)
}
if instance == "" {
instance = resp.Header.Get("X-Instance-Id")
}
if instance == "" || resp.Header.Get("X-Instance-Id") != instance {
t.Fatal("unstable instance identity")
}
if err := resp.Body.Close(); err != nil {
t.Fatal(err)
}
}
}
// TestMissingIdempotencyHeader rejects an otherwise valid authenticated write.
func TestMissingIdempotencyHeader(t *testing.T) {
ctrl := testController(t, nil)
caller := user(t, ctrl)
room := chat(t, ctrl, caller)
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room+"/messages", strings.NewReader(`{"text":"valid"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+caller)
resp, err := ctrl.server.Test(req)
if err != nil {
t.Fatal(err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("missing key accepted: %d", resp.StatusCode)
}
}
@@ -0,0 +1,90 @@
package fiber
import (
"context"
"errors"
"strconv"
"time"
"github.com/gofiber/fiber/v2"
"github.com/google/uuid"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/admission"
)
// request assigns a request identifier, handles errors and logs the completed request.
func (ctrl *Controller) request(ctx *fiber.Ctx) error {
ctx.Set(headerRequestID, uuid.NewString())
ctx.Set("X-Instance-Id", ctrl.instanceID)
started := time.Now()
ctrl.metrics.active.Inc()
defer ctrl.metrics.active.Dec()
err := ctx.Next()
if err != nil {
err = ctrl.handleErr(ctx, err)
}
ctrl.logRequest(ctx, time.Since(started))
if ctx.Path() != "/metrics" {
ctrl.metrics.observe(ctx, time.Since(started))
}
return err
}
// logRequest logs request metadata without including message contents.
func (ctrl *Controller) logRequest(ctx *fiber.Ctx, elapsed time.Duration) {
route := "unmatched"
if ctx.Route() != nil {
route = ctx.Route().Path
}
ctrl.log.Info("http request",
zap.String("method", ctx.Method()),
zap.String("route", route),
zap.Int("status", ctx.Response().StatusCode()),
zap.String("request_id", ctx.GetRespHeader(headerRequestID)),
zap.Duration("duration", elapsed),
)
}
// admit reserves global budgets and bounds downstream request work.
func (ctrl *Controller) admit(ctx *fiber.Ctx) error {
if ctrl.stopping.Load() {
return errBusy
}
requestCtx, cancel := context.WithTimeout(ctx.UserContext(), ctrl.cfg.Timeout())
ctx.SetUserContext(requestCtx)
release, err := ctrl.admission.Enter(requestCtx, requestGroup(ctx), "")
if err != nil {
cancel()
return admissionError(ctx, err)
}
defer finishRequest(ctx, func() {
release()
cancel()
})
return ctx.Next()
}
// requireIdentity resolves the session before reserving per-user budgets.
func (ctrl *Controller) requireIdentity(ctx *fiber.Ctx) error {
user, err := ctrl.auth.Authenticate(ctx.UserContext(), bearer(ctx))
if err != nil {
return err
}
ctx.Locals(identityKey, user)
release, err := ctrl.admission.Enter(ctx.UserContext(), requestGroup(ctx), user)
if err != nil {
return admissionError(ctx, err)
}
defer finishRequest(ctx, release)
return ctx.Next()
}
// admissionError maps policy rejection and backend failure into HTTP-owned errors.
func admissionError(ctx *fiber.Ctx, err error) error {
ctx.Set(fiber.HeaderRetryAfter, strconv.Itoa(retryAfterSeconds))
if errors.Is(err, admission.ErrRate) {
return errRateLimited
}
return errBusy
}
@@ -0,0 +1,211 @@
package fiber
import (
"net/http"
"testing"
"testing/synctest"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
)
// TestController_InFlightAdmission checks rejection, recovery and health exemption independently.
func TestController_InFlightAdmission(t *testing.T) {
cases := []struct {
name string
release bool
path string
status int
}{
{"Negative: occupied execution slot", false, "/api/v1/users/me", http.StatusServiceUnavailable},
{"Positive: released execution slot", true, "/api/v1/users/me", http.StatusUnauthorized},
{"Positive: health bypasses occupied slot", false, "/health/live", http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.HTTP.Admission.MaxInFlight = 1
})
if !ctrl.admission.(*fixtureAdmission).Acquire() {
t.Fatal("fixture could not reserve slot")
}
if tc.release {
ctrl.admission.(*fixtureAdmission).Release()
} else {
t.Cleanup(ctrl.admission.(*fixtureAdmission).Release)
}
// Act.
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, tc.status, body)
})
}
}
// TestController_RateAdmission checks exhausted tokens without timing-dependent HTTP setup.
func TestController_RateAdmission(t *testing.T) {
t.Run("/api/v1/users/me", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.HTTP.Admission.RequestsPerSecond = 1
cfg.HTTP.Admission.Burst = 1
})
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
t.Fatal("fixture token missing")
}
expected := http.StatusTooManyRequests
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", "", nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, expected, body)
})
})
t.Run("/health/ready", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
// Arrange.
ctrl := testController(t, func(cfg *config.Config) {
cfg.HTTP.Admission.RequestsPerSecond = 1
cfg.HTTP.Admission.Burst = 1
})
if !ctrl.admission.(*fixtureAdmission).Allow(time.Now()) {
t.Fatal("fixture token missing")
}
expected := http.StatusOK
// Act.
status, body, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, expected, body)
})
})
}
// TestController_Draining checks each endpoint's admission policy during shutdown.
func TestController_Draining(t *testing.T) {
cases := []struct {
name string
path string
status int
}{
{"Negative: readiness disabled", "/health/ready", http.StatusServiceUnavailable},
{"Positive: liveness remains available", "/health/live", http.StatusOK},
{"Negative: business requests rejected", "/api/v1/users/me", http.StatusServiceUnavailable},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
ctrl.stopping.Store(true)
// Act.
status, body, err := request(ctrl, http.MethodGet, tc.path, "", nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, tc.status, body)
})
}
}
// TestController_UnknownRoute checks the public fallback for an unmatched path.
func TestController_UnknownRoute(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
// Act.
status, body, err := request(ctrl, http.MethodGet, "/missing", "", nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusNotFound, body)
assertErrorCode(t, body, "not_found")
}
// TestController_New rejects each missing dependency independently.
func TestController_New(t *testing.T) {
t.Run("Negative: missing configuration", func(t *testing.T) {
// Arrange.
fixture := testController(t, nil)
// Act.
ctrl, err := New(fixture.log, nil, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
// Assert.
if err == nil || ctrl != nil {
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
}
})
t.Run("Negative: missing logger", func(t *testing.T) {
// Arrange.
fixture := testController(t, nil)
// Act.
ctrl, err := New(nil, &fixture.cfg, fixture.service, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
// Assert.
if err == nil || ctrl != nil {
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
}
})
t.Run("Negative: missing service", func(t *testing.T) {
// Arrange.
fixture := testController(t, nil)
// Act.
ctrl, err := New(fixture.log, &fixture.cfg, nil, fixture.errorRegistry, fixture.admission, fixture.auth, fixture.readiness)
// Assert.
if err == nil || ctrl != nil {
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
}
})
t.Run("Negative: missing registry", func(t *testing.T) {
// Arrange.
fixture := testController(t, nil)
// Act.
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, nil, fixture.admission, fixture.auth, fixture.readiness)
// Assert.
if err == nil || ctrl != nil {
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
}
})
t.Run("Negative: missing limiter", func(t *testing.T) {
// Arrange.
fixture := testController(t, nil)
// Act.
ctrl, err := New(fixture.log, &fixture.cfg, fixture.service, fixture.errorRegistry, nil, fixture.auth, fixture.readiness)
// Assert.
if err == nil || ctrl != nil {
t.Fatalf("incomplete controller accepted: %v, %v", ctrl, err)
}
})
}
@@ -0,0 +1,55 @@
package fiber
import (
"errors"
"go.lab260.ru/fielderr"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
var (
errBusy = publicFailure(codeUnavailable, "server is busy")
errRateLimited = publicFailure(codeRateLimited, "request rate exceeded")
errTooLarge = publicFailure(codeTooLarge, "request body is too large")
errMedia = publicFailure(codeMedia, "expected application/json")
errInternal = publicFailure(codeInternal, "internal server error")
)
// publicFailure creates a transport-owned error with a safe API message.
func publicFailure(code, message string) error {
return fielderr.WithStatus(errors.New(message), fielderr.NewStatusCode(code), message)
}
// publicError maps application failures into the public API envelope.
// Unknown errors receive a fixed response without exposing their details.
func publicError(err error) error {
switch {
case errors.Is(err, service.ErrTooLarge):
return errTooLarge
case errors.Is(err, service.ErrMedia):
return errMedia
case errors.Is(err, service.ErrUnavailable):
return publicFailure(codeUnavailable, "dependency unavailable")
case errors.Is(err, service.ErrInvalid):
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeInvalid), "invalid request")
case errors.Is(err, service.ErrUnauthorized):
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnauthorized), "unknown user identity")
case errors.Is(err, service.ErrNotFound):
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeNotFound), "resource not found")
case errors.Is(err, service.ErrConflict):
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeConflict), "username already exists")
case errors.Is(err, service.ErrCapacity):
return fielderr.WithStatus(err, fielderr.NewStatusCode(codeUnavailable), "in-memory storage capacity reached")
case errors.Is(err, errBusy):
return errBusy
case errors.Is(err, errRateLimited):
return errRateLimited
case errors.Is(err, errTooLarge):
return errTooLarge
case errors.Is(err, errMedia):
return errMedia
default:
return errInternal
}
}
@@ -0,0 +1,43 @@
package fiber
import (
"errors"
"fmt"
"testing"
"go.lab260.ru/fielderr"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// TestPublicErrorSafety maps wrapped application failures without exposing internal details.
func TestPublicErrorSafety(t *testing.T) {
t.Run("wrapped application error", func(t *testing.T) {
err := publicError(fmt.Errorf("private database detail: %w", service.ErrConflict))
response := errorResponse(err, "request")
if response.Error.Code != codeConflict || response.Error.Message != "username already exists" {
t.Fatalf("unexpected response: %+v", response)
}
})
t.Run("unknown error", func(t *testing.T) {
err := publicError(errors.New("private database detail"))
if err != errInternal {
t.Fatalf("unexpected public error: %v", err)
}
})
t.Run("foreign public status", func(t *testing.T) {
err := fielderr.WithStatus(errors.New("private detail"), fielderr.NewStatusCode(codeInvalid), "private detail")
if publicError(err) != errInternal {
t.Fatal("untrusted error metadata reached the public response")
}
})
}
// TestPublicErrorUnavailable keeps dependency details out of the public envelope.
func TestPublicErrorUnavailable(t *testing.T) {
err := publicError(fmt.Errorf("private database detail: %w", service.ErrUnavailable))
response := errorResponse(err, "request")
if response.Error.Code != codeUnavailable || response.Error.Message != "dependency unavailable" {
t.Fatalf("unexpected response: %+v", response)
}
}
+26
View File
@@ -0,0 +1,26 @@
package fiber
// initRoutes registers health endpoints and authenticated application routes.
func (ctrl *Controller) initRoutes() {
ctrl.server.Get("/metrics", ctrl.handleMetrics)
ctrl.server.Get("/health/live", ctrl.handleLive)
ctrl.server.Get("/health/ready", ctrl.handleReady)
ctrl.server.Use(ctrl.admit)
ctrl.server.Post("/api/v1/users", ctrl.HandleUsersCreate)
ctrl.server.Post("/api/v1/auth/sessions", ctrl.HandleLogin)
api := ctrl.server.Group("/api/v1", ctrl.requireIdentity)
api.Delete("/auth/sessions/current", ctrl.HandleLogout)
api.Get("/users/me", ctrl.HandleUsersGetMe)
api.Post("/chats", ctrl.HandleChatsCreate)
api.Get("/chats", ctrl.HandleChatsGetPage)
api.Get("/chats/:chat_id", ctrl.HandleChatsGetByID)
api.Post("/chats/:chat_id/attachments", ctrl.handleUpload)
api.Get("/attachments/:id", ctrl.handleAttachment)
api.Get("/attachments/:id/content", ctrl.handleContent)
api.Post("/chats/:chat_id/messages", ctrl.HandleMessagesCreate)
api.Get("/chats/:chat_id/messages", ctrl.HandleMessagesGetPage)
ctrl.server.Use(ctrl.handleNotFound)
}
+40
View File
@@ -0,0 +1,40 @@
package fiber
import (
"io"
"sync"
"github.com/gofiber/fiber/v2"
)
type responseStream struct {
io.Reader
cleanup func()
once sync.Once
}
// Close releases request budgets after fasthttp finishes transmitting the stream.
func (s *responseStream) Close() error {
var err error
s.once.Do(func() {
if closer, ok := s.Reader.(io.Closer); ok {
err = closer.Close()
}
s.cleanup()
})
return err
}
// finishRequest keeps deadlines and admission leases alive until streamed responses close.
func finishRequest(ctx *fiber.Ctx, cleanup func()) {
stream, ok := ctx.Response().BodyStream().(*responseStream)
if !ok {
cleanup()
return
}
previous := stream.cleanup
stream.cleanup = func() {
previous()
cleanup()
}
}
@@ -0,0 +1,130 @@
package fiber
import (
"net/http"
"strings"
"testing"
"github.com/google/uuid"
)
// TestController_UsersCreate checks one registration contract scenario per subtest.
func TestController_UsersCreate(t *testing.T) {
cases := []struct {
name string
body string
status int
}{
{"Positive: valid Unicode display name", `{"password":"fixture-password-123","username":"alice","display_name":"Алиса 👋"}`, http.StatusCreated},
{"Positive: display name at rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 100) + `"}`, http.StatusCreated},
{"Negative: display name exceeds rune limit", `{"password":"fixture-password-123","username":"alice","display_name":"` + strings.Repeat("👋", 101) + `"}`, http.StatusBadRequest},
{"Negative: uppercase username", `{"password":"fixture-password-123","username":"Alice","display_name":"Alice"}`, http.StatusBadRequest},
{"Negative: malformed JSON", `{`, http.StatusBadRequest},
{"Negative: null root", `null`, http.StatusBadRequest},
{"Negative: array root", `[]`, http.StatusBadRequest},
{"Negative: missing fields", `{}`, http.StatusBadRequest},
{"Negative: null field", `{"password":"fixture-password-123","username":"alice","display_name":null}`, http.StatusBadRequest},
{"Negative: wrong field type", `{"password":"fixture-password-123","username":5,"display_name":"Alice"}`, http.StatusBadRequest},
{"Negative: unknown field", `{"password":"fixture-password-123","username":"alice","display_name":"Alice","unknown":"secret"}`, http.StatusBadRequest},
{"Negative: field name case", `{"password":"fixture-password-123","Username":"alice","display_name":"Alice"}`, http.StatusBadRequest},
{"Negative: duplicate field", `{"password":"fixture-password-123","username":"alice","username":"bob","display_name":"Alice"}`, http.StatusBadRequest},
{"Negative: trailing object", `{"password":"fixture-password-123","username":"alice","display_name":"Alice"} {}`, http.StatusBadRequest},
{"Negative: invalid UTF-8", "{\"username\":\"alice\",\"display_name\":\"\xff\"}", http.StatusBadRequest},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
// Act.
status, body, err := request(ctrl, http.MethodPost, "/api/v1/users", "", []byte(tc.body))
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, tc.status, body)
if tc.status == http.StatusBadRequest {
assertErrorCode(t, body, "invalid_request")
return
}
if body["username"] != "alice" || body["display_name"] == "" {
t.Fatalf("registration fields changed: %v", body)
}
if _, err := uuid.Parse(body["id"].(string)); err != nil {
t.Fatalf("invalid assigned ID: %v", err)
}
})
}
}
// TestController_UsersGetMe verifies profile selection and authentication failures.
func TestController_UsersGetMe(t *testing.T) {
t.Run("Positive: own profile", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
actor := user(t, ctrl)
identity := actor
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusOK, body)
if body["id"] != actor || body["display_name"] != "Алиса 👋" {
t.Fatalf("wrong profile: %v", body)
}
})
t.Run("Negative: missing identity", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
identity := ""
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
})
t.Run("Negative: unknown identity", func(t *testing.T) {
// Arrange.
ctrl := testController(t, nil)
identity := uuid.NewString()
// Act.
status, body, err := request(ctrl, http.MethodGet, "/api/v1/users/me", identity, nil)
// Assert.
if err != nil {
t.Fatal(err)
}
assertHTTPStatus(t, status, http.StatusUnauthorized, body)
assertErrorCode(t, body, "unauthorized")
})
}
// assertHTTPStatus reports the response body alongside a mismatched status.
func assertHTTPStatus(t *testing.T, got, want int, body map[string]any) {
t.Helper()
if got != want {
t.Fatalf("status=%d, want=%d, body=%v", got, want, body)
}
}
// assertErrorCode checks the documented error classification independently of status.
func assertErrorCode(t *testing.T, body map[string]any, want string) {
t.Helper()
envelope, ok := body["error"].(map[string]any)
if !ok || envelope["code"] != want {
t.Fatalf("error=%v, want code %q", body, want)
}
}
+12
View File
@@ -0,0 +1,12 @@
// Package controller connects transport lifecycles to Fx.
package controller
import "context"
// Controller is a process-owned transport server.
type Controller interface {
// Start acquires the listener and reports startup errors to the lifecycle owner.
Start(context.Context) error
// Stop stops accepting work and drains active requests within the supplied deadline.
Stop(context.Context) error
}
+119
View File
@@ -0,0 +1,119 @@
// Package cursor signs and verifies resource-bound keyset positions.
package cursor
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
const (
cursorSigningKeyBytes = 32
maxEncodedCursorBytes = 1024
)
// ErrInvalid means a cursor is malformed, tampered with or bound to another resource.
var ErrInvalid = errors.New("invalid cursor")
// Position identifies the last record already returned by keyset pagination.
type Position struct {
// CreatedAt is the creation timestamp of the last returned record.
CreatedAt time.Time
// ID breaks ties between records sharing a timestamp.
ID uuid.UUID
}
// Codec authenticates pagination positions with an immutable process-local key.
type Codec struct {
key [cursorSigningKeyBytes]byte
}
type cursorPayload struct {
// Resource binds the position to a chat history or one user's chat list.
Resource string `json:"r"`
// Time is the creation timestamp of the last record in the previous page.
Time time.Time `json:"t"`
// ID breaks ties between records with the same creation timestamp.
ID uuid.UUID `json:"i"`
}
// New creates a cursor codec with a random process-local signing key.
func New() (*Codec, error) {
codec := &Codec{}
if _, err := rand.Read(codec.key[:]); err != nil {
return nil, err
}
return codec, nil
}
// Encode serializes and signs a pagination position bound to a resource.
func (codec *Codec) Encode(resource string, position Position) (string, error) {
payload, err := json.Marshal(cursorPayload{
Resource: resource,
Time: position.CreatedAt,
ID: position.ID,
})
if err != nil {
return "", fmt.Errorf("encode cursor: %w", err)
}
payload = append(payload, codec.signature(payload)...)
return base64.RawURLEncoding.EncodeToString(payload), nil
}
// Decode verifies the cursor signature and extracts its resource-bound position.
func (codec *Codec) Decode(encoded, resource string) (Position, error) {
if encoded == "" {
return Position{}, nil
}
if len(encoded) > maxEncodedCursorBytes {
return Position{}, ErrInvalid
}
signed, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil || len(signed) <= sha256.Size {
return Position{}, ErrInvalid
}
boundary := len(signed) - sha256.Size
payload, signature := signed[:boundary], signed[boundary:]
if !hmac.Equal(signature, codec.signature(payload)) {
return Position{}, ErrInvalid
}
return decodeCursorPosition(payload, resource)
}
// signature computes the HMAC-SHA256 authentication tag for a cursor payload.
func (codec *Codec) signature(payload []byte) []byte {
mac := hmac.New(sha256.New, codec.key[:])
// hash.Hash.Write is documented to always return a nil error.
_, _ = mac.Write(payload)
return mac.Sum(nil)
}
// decodeCursorPosition validates the decoded cursor resource and timestamp.
func decodeCursorPosition(payload []byte, resource string) (Position, error) {
var cursor cursorPayload
if err := json.Unmarshal(payload, &cursor); err != nil {
return Position{}, ErrInvalid
}
if cursor.Resource != resource || cursor.Time.IsZero() {
return Position{}, ErrInvalid
}
return Position{CreatedAt: cursor.Time, ID: cursor.ID}, nil
}
// NewShared creates a codec from the common 256-bit key provisioned to every replica.
func NewShared(encoded string) (*Codec, error) {
key, err := base64.StdEncoding.DecodeString(encoded)
if err != nil || len(key) != cursorSigningKeyBytes {
return nil, fmt.Errorf("CURSOR_SIGNING_KEY must encode exactly 32 bytes as base64")
}
codec := &Codec{}
copy(codec.key[:], key)
return codec, nil
}
+212
View File
@@ -0,0 +1,212 @@
package cursor
import (
"encoding/base64"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// TestCodec_EncodeDecode preserves the complete position through an authenticated round trip.
func TestCodec_EncodeDecode(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
position := Position{CreatedAt: time.Unix(1700000000, 123456789).UTC(), ID: uuid.New()}
// Act.
encoded, err := codec.Encode("chats:alice", position)
// Assert.
if err != nil {
t.Fatal(err)
}
if encoded == "" {
t.Fatal("encoded position is empty")
}
decoded, err := codec.Decode(encoded, "chats:alice")
if err != nil || decoded != position {
t.Fatalf("decoded=%v, want=%v, error=%v", decoded, position, err)
}
}
// TestCodec_Decode checks first-page behavior and independent rejection conditions.
func TestCodec_Decode(t *testing.T) {
t.Run("Positive: empty token starts first page", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
// Act.
got, err := codec.Decode("", "chats:alice")
// Assert.
if err != nil || got != (Position{}) {
t.Fatalf("first-page position=%v, error=%v", got, err)
}
})
t.Run("Negative: another resource", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := encodeFixture(t, codec, "chats:alice")
// Act.
got, err := codec.Decode(encoded, "chats:bob")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: another process key", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := encodeFixture(t, codec, "chats:alice")
codec = newTestCodec(t)
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: tampered payload", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := encodeFixture(t, codec, "chats:alice")
signed, err := base64.RawURLEncoding.DecodeString(encoded)
if err != nil {
t.Fatal(err)
}
signed[0] ^= 1
encoded = base64.RawURLEncoding.EncodeToString(signed)
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: oversized token", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := strings.Repeat("a", 1025)
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: malformed base64", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := "!invalid!"
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: signed malformed JSON", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := signedPayload(codec, []byte("not JSON"))
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
t.Run("Negative: signed zero timestamp", func(t *testing.T) {
// Arrange.
codec := newTestCodec(t)
encoded := signedPayload(codec, []byte(`{"r":"chats:alice","t":"0001-01-01T00:00:00Z","i":"11111111-1111-1111-1111-111111111111"}`))
// Act.
got, err := codec.Decode(encoded, "chats:alice")
// Assert.
if !errors.Is(err, ErrInvalid) || got != (Position{}) {
t.Fatalf("position=%v, error=%v", got, err)
}
})
}
// signedPayload creates authenticated malformed fixtures to isolate payload validation.
func signedPayload(codec *Codec, payload []byte) string {
return base64.RawURLEncoding.EncodeToString(append(payload, codec.signature(payload)...))
}
// newTestCodec creates an independent signing key for one scenario.
func newTestCodec(t *testing.T) *Codec {
t.Helper()
codec, err := New()
if err != nil {
t.Fatal(err)
}
return codec
}
// encodeFixture prepares a valid token before testing a separate decoding condition.
func encodeFixture(t *testing.T, codec *Codec, resource string) string {
t.Helper()
token, err := codec.Encode(resource, Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
if err != nil {
t.Fatal(err)
}
return token
}
// TestSharedCodec verifies a second process can verify the first process's cursor.
func TestSharedCodec(t *testing.T) {
key := base64.StdEncoding.EncodeToString(make([]byte, 32))
first, err := NewShared(key)
if err != nil {
t.Fatal(err)
}
second, err := NewShared(key)
if err != nil {
t.Fatal(err)
}
position := Position{CreatedAt: time.Now().UTC(), ID: uuid.New()}
encoded, err := first.Encode("chat", position)
if err != nil {
t.Fatal(err)
}
result, err := second.Decode(encoded, "chat")
if err != nil || result != position {
t.Fatalf("cross-replica cursor: %v", err)
}
}
// TestSharedCodecRejectsInvalidKey requires a full 256-bit decoded secret.
func TestSharedCodecRejectsInvalidKey(t *testing.T) {
for _, key := range []string{"", "broken!", base64.StdEncoding.EncodeToString([]byte("short"))} {
t.Run(key, func(t *testing.T) {
if _, err := NewShared(key); err == nil {
t.Fatal("invalid key accepted")
}
})
}
}
+62
View File
@@ -0,0 +1,62 @@
// Package hashring implements immutable consistent hashing with virtual nodes.
package hashring
import (
"cmp"
"crypto/sha256"
"encoding/binary"
"fmt"
"slices"
"sort"
"strconv"
)
type point struct {
hash uint64
node string
}
// Ring maps arbitrary keys to stable node identifiers.
type Ring struct {
points []point
}
// New creates an order-independent ring and rejects ambiguous node identities.
func New(nodes []string, replicas int) (*Ring, error) {
if len(nodes) == 0 || replicas < 1 {
return nil, fmt.Errorf("nodes and positive virtual node count are required")
}
ring := &Ring{}
seen := make(map[string]bool)
for _, node := range nodes {
if node == "" || seen[node] {
return nil, fmt.Errorf("node identifiers must be unique and nonempty")
}
seen[node] = true
for index := range replicas {
ring.points = append(ring.points, point{hash: hash(node + ":" + strconv.Itoa(index)), node: node})
}
}
slices.SortFunc(ring.points, func(a, b point) int {
if order := cmp.Compare(a.hash, b.hash); order != 0 {
return order
}
return cmp.Compare(a.node, b.node)
})
return ring, nil
}
// Owner selects the first virtual node clockwise from the key hash.
func (r *Ring) Owner(key string) string {
value := hash(key)
index := sort.Search(len(r.points), func(index int) bool {
return r.points[index].hash >= value
})
return r.points[index%len(r.points)].node
}
// hash maps a stable string into the ring's 64-bit coordinate space.
func hash(value string) uint64 {
sum := sha256.Sum256([]byte(value))
return binary.BigEndian.Uint64(sum[:8])
}
+73
View File
@@ -0,0 +1,73 @@
package hashring
import (
"fmt"
"testing"
)
// TestExpansionMovesOnlyKeysOwnedByNewNode verifies the consistent hashing invariant.
func TestExpansionMovesOnlyKeysOwnedByNewNode(t *testing.T) {
before, err := New([]string{"a", "b"}, 256)
if err != nil {
t.Fatal(err)
}
after, err := New([]string{"c", "b", "a"}, 256)
if err != nil {
t.Fatal(err)
}
moved := 0
for index := range 100000 {
key := fmt.Sprint(index)
oldOwner, newOwner := before.Owner(key), after.Owner(key)
if oldOwner != newOwner {
moved++
if newOwner != "c" {
t.Fatalf("existing nodes exchanged key %s", key)
}
}
}
fraction := float64(moved) / 100000
if fraction < 0.2 || fraction > 0.45 {
t.Fatalf("unexpected moved fraction: %f", fraction)
}
t.Logf("100000 keys: moved=%d fraction=%.5f", moved, fraction)
}
// TestRingRejectsAmbiguousConfiguration checks independent malformed rings.
func TestRingRejectsAmbiguousConfiguration(t *testing.T) {
cases := []struct {
name string
nodes []string
replicas int
}{
{"empty", nil, 1},
{"zero replicas", []string{"a"}, 0},
{"empty node", []string{""}, 1},
{"duplicate", []string{"a", "a"}, 1},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := New(tc.nodes, tc.replicas); err == nil {
t.Fatal("invalid ring accepted")
}
})
}
}
// TestRingIgnoresInputOrder verifies that replicas agree despite configuration ordering.
func TestRingIgnoresInputOrder(t *testing.T) {
a, err := New([]string{"a", "b"}, 64)
if err != nil {
t.Fatal(err)
}
b, err := New([]string{"b", "a"}, 64)
if err != nil {
t.Fatal(err)
}
for index := range 1000 {
key := fmt.Sprint(index)
if a.Owner(key) != b.Owner(key) {
t.Fatal("node order changes ownership")
}
}
}
+76
View File
@@ -0,0 +1,76 @@
package media
import (
"context"
"fmt"
"time"
)
// ObjectInfo describes an immutable object without its contents.
type ObjectInfo struct {
// Key is the server-assigned private coordinate.
Key string
// ModifiedAt determines eligibility for a grace-protected scan.
ModifiedAt time.Time
}
// OrphanMetadata checks all reservations, not only published files.
type OrphanMetadata interface {
// HasObject reports whether any state references the key.
HasObject(context.Context, string) (bool, error)
}
// OrphanObjects supports resumable listing and single-object cleanup.
type OrphanObjects interface {
// List returns a bounded lexicographic page after the given key.
List(context.Context, string) ([]ObjectInfo, error)
// Remove deletes an explicitly identified unreferenced key.
Remove(context.Context, string) error
}
// OrphanResult reports one page of a safe S3-to-database reconciliation.
type OrphanResult struct {
// Scanned counts objects examined.
Scanned int `json:"scanned"`
// Orphans counts old objects with no metadata reservation.
Orphans int `json:"orphans"`
// Removed counts applied removals.
Removed int `json:"removed"`
// Next resumes the lexicographic scan.
Next string `json:"next"`
}
// ReconcileOrphans protects fresh and referenced objects, and defaults to dry-run at the CLI.
func ReconcileOrphans(ctx context.Context, metadata OrphanMetadata, objects OrphanObjects, after string, grace time.Duration, apply bool) (OrphanResult, error) {
var result OrphanResult
if grace < time.Hour {
return result, fmt.Errorf("reconciliation grace must be at least one hour")
}
entries, err := objects.List(ctx, after)
if err != nil {
return result, err
}
cutoff := time.Now().UTC().Add(-grace)
for _, entry := range entries {
result.Scanned++
result.Next = entry.Key
if entry.ModifiedAt.IsZero() || entry.ModifiedAt.After(cutoff) {
continue
}
referenced, err := metadata.HasObject(ctx, entry.Key)
if err != nil {
return result, err
}
if referenced {
continue
}
result.Orphans++
if apply {
if err := objects.Remove(ctx, entry.Key); err != nil {
return result, err
}
result.Removed++
}
}
return result, nil
}
+102
View File
@@ -0,0 +1,102 @@
package media
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// Inventory supports bounded, resumable scans and guarded state transitions.
type Inventory interface {
// Scan returns the next at most limit metadata records by ID.
Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error)
// Reclaim deletes only an old unfinished unreferenced reservation after claiming it.
Reclaim(context.Context, uuid.UUID, time.Time, bool) (bool, error)
// MarkMissing preserves metadata and references when an original disappears.
MarkMissing(context.Context, uuid.UUID, bool) error
}
// ObjectInventory exposes bounded inspection and explicit removal.
type ObjectInventory interface {
// Exists distinguishes absence from infrastructure failure.
Exists(context.Context, string) (bool, error)
// Remove deletes a single immutable object key.
Remove(context.Context, string) error
}
// ReconcileResult records observations and the continuation cursor without file contents.
type ReconcileResult struct {
// Scanned counts inspected metadata rows.
Scanned int `json:"scanned"`
// Missing counts published originals absent from S3.
Missing int `json:"missing"`
// Abandoned counts old incomplete reservations eligible for cleanup.
Abandoned int `json:"abandoned"`
// Changed counts successful applied repairs, zero for dry run.
Changed int `json:"changed"`
// Next continues scanning without retaining the full database in RAM.
Next uuid.UUID `json:"next"`
}
// Reconcile inspects at most 1000 records and protects active uploads with a one-hour minimum grace.
func Reconcile(ctx context.Context, metadata Inventory, objects ObjectInventory, after uuid.UUID, grace time.Duration, apply bool) (ReconcileResult, error) {
var result ReconcileResult
if grace < time.Hour {
return result, fmt.Errorf("reconciliation grace must be at least one hour")
}
records, err := metadata.Scan(ctx, after, 1000)
if err != nil {
return result, err
}
cutoff := time.Now().UTC().Add(-grace)
for _, a := range records {
result.Scanned++
result.Next = a.ID
if a.CreatedAt.After(cutoff) {
continue
}
exists, err := objects.Exists(ctx, a.ObjectKey)
if err != nil {
return result, err
}
switch {
case a.Status == "uploading" || a.Status == "deleting":
result.Abandoned++
if !apply {
continue
}
claimed, err := metadata.Reclaim(ctx, a.ID, cutoff, false)
if err != nil {
return result, err
}
if !claimed {
continue
}
if err := objects.Remove(ctx, a.ObjectKey); err != nil {
return result, err
}
if _, err := metadata.Reclaim(ctx, a.ID, cutoff, true); err != nil {
return result, err
}
result.Changed++
case !exists:
result.Missing++
if apply && a.Status != "missing" {
if err := metadata.MarkMissing(ctx, a.ID, true); err != nil {
return result, err
}
result.Changed++
}
case a.Status == "missing" && apply:
if err := metadata.MarkMissing(ctx, a.ID, false); err != nil {
return result, err
}
result.Changed++
}
}
return result, nil
}
+159
View File
@@ -0,0 +1,159 @@
package media
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
type reconciliationFixture struct {
records []dto.Attachment
entries []ObjectInfo
exists bool
referenced bool
claim bool
scanErr error
existsErr error
claimErr error
finishErr error
removeErr error
markErr error
listErr error
referenceErr error
removed int
}
// Scan returns an independent bounded fixture page.
func (f *reconciliationFixture) Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error) {
return f.records, f.scanErr
}
// Reclaim injects failures at the claim or finish boundary independently.
func (f *reconciliationFixture) Reclaim(_ context.Context, _ uuid.UUID, _ time.Time, finish bool) (bool, error) {
if finish {
return f.claim, f.finishErr
}
return f.claim, f.claimErr
}
// MarkMissing models availability-state persistence without deleting metadata.
func (f *reconciliationFixture) MarkMissing(context.Context, uuid.UUID, bool) error {
return f.markErr
}
// Exists returns an explicit existence or infrastructure-failure outcome.
func (f *reconciliationFixture) Exists(context.Context, string) (bool, error) {
return f.exists, f.existsErr
}
// Remove counts applied side effects for dry-run and referenced-object assertions.
func (f *reconciliationFixture) Remove(context.Context, string) error {
f.removed++
return f.removeErr
}
// List supplies object timestamps independently of database state.
func (f *reconciliationFixture) List(context.Context, string) ([]ObjectInfo, error) {
return f.entries, f.listErr
}
// HasObject includes reservations so active uploads remain protected.
func (f *reconciliationFixture) HasObject(context.Context, string) (bool, error) {
return f.referenced, f.referenceErr
}
// TestReconciliationSafety exercises interrupted cleanup, age protection and missing-object repair.
func TestReconciliationSafety(t *testing.T) {
fault := errors.New("dependency failure")
old := time.Now().Add(-2 * time.Hour)
cases := []struct {
name string
fixture reconciliationFixture
status string
created time.Time
apply bool
wantErr bool
changed int
}{
{name: "fresh", created: time.Now(), apply: true},
{name: "scan failure", fixture: reconciliationFixture{scanErr: fault}, wantErr: true},
{name: "head failure", fixture: reconciliationFixture{existsErr: fault}, wantErr: true},
{name: "dry abandoned", status: "uploading"},
{name: "abandoned applied", status: "uploading", apply: true, fixture: reconciliationFixture{claim: true}, changed: 1},
{name: "claimed by another", status: "uploading", apply: true},
{name: "claim failure", status: "uploading", apply: true, fixture: reconciliationFixture{claimErr: fault}, wantErr: true},
{name: "delete failure", status: "deleting", apply: true, fixture: reconciliationFixture{claim: true, removeErr: fault}, wantErr: true},
{name: "finish failure", status: "deleting", apply: true, fixture: reconciliationFixture{claim: true, finishErr: fault}, wantErr: true},
{name: "missing dry", status: "ready"},
{name: "missing applied", status: "ready", apply: true, changed: 1},
{name: "mark failure", status: "ready", apply: true, fixture: reconciliationFixture{markErr: fault}, wantErr: true},
{name: "missing repeat", status: "missing", apply: true},
{name: "restored", status: "missing", apply: true, fixture: reconciliationFixture{exists: true}, changed: 1},
{name: "restore failure", status: "missing", apply: true, fixture: reconciliationFixture{exists: true, markErr: fault}, wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
created := tc.created
if created.IsZero() {
created = old
}
f.records = []dto.Attachment{{ID: uuid.New(), Status: tc.status, CreatedAt: created, ObjectKey: "original/test"}}
result, err := Reconcile(t.Context(), &f, &f, uuid.Nil, time.Hour, tc.apply)
if (err != nil) != tc.wantErr || result.Changed != tc.changed {
t.Fatalf("result=%+v error=%v", result, err)
}
})
}
}
// TestOrphanSafety rejects deleting fresh, reserved and unknown-age objects.
func TestOrphanSafety(t *testing.T) {
fault := errors.New("dependency failure")
cases := []struct {
name string
fixture reconciliationFixture
fresh bool
apply bool
wantErr bool
removed int
}{
{name: "fresh", fresh: true, apply: true},
{name: "referenced", fixture: reconciliationFixture{referenced: true}, apply: true},
{name: "dry run"},
{name: "remove", apply: true, removed: 1},
{name: "list failure", fixture: reconciliationFixture{listErr: fault}, wantErr: true},
{name: "metadata failure", fixture: reconciliationFixture{referenceErr: fault}, wantErr: true},
{name: "remove failure", fixture: reconciliationFixture{removeErr: fault}, apply: true, wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
modified := time.Now().Add(-2 * time.Hour)
if tc.fresh {
modified = time.Now()
}
f.entries = []ObjectInfo{{Key: "original/test", ModifiedAt: modified}}
result, err := ReconcileOrphans(t.Context(), &f, &f, "", time.Hour, tc.apply)
if (err != nil) != tc.wantErr || result.Removed != tc.removed {
t.Fatalf("result=%+v error=%v", result, err)
}
})
}
}
// TestGraceCannotBeDisabled rejects unsafe cleanup windows at both scan entrypoints.
func TestGraceCannotBeDisabled(t *testing.T) {
f := &reconciliationFixture{}
if _, err := Reconcile(t.Context(), f, f, uuid.Nil, time.Second, true); err == nil {
t.Fatal("unsafe metadata grace accepted")
}
if _, err := ReconcileOrphans(t.Context(), f, f, "", time.Second, true); err == nil {
t.Fatal("unsafe object grace accepted")
}
}
+55
View File
@@ -0,0 +1,55 @@
package media
import (
"context"
"encoding/json"
"io"
"time"
"github.com/google/uuid"
)
// ReconcileMetadata combines bounded database inventory operations for the operator workflow.
type ReconcileMetadata interface {
Inventory
OrphanMetadata
}
// ReconcileObjects combines object inspection and listing for the operator workflow.
type ReconcileObjects interface {
ObjectInventory
OrphanObjects
}
// RunReconciliation emits one bounded result per page and stops on any uncertain dependency outcome.
func RunReconciliation(ctx context.Context, metadata ReconcileMetadata, objects ReconcileObjects, output io.Writer, apply bool) error {
encoder := json.NewEncoder(output)
after := uuid.Nil
for {
result, err := Reconcile(ctx, metadata, objects, after, time.Hour, apply)
if err != nil {
return err
}
if err := encoder.Encode(result); err != nil {
return err
}
if result.Scanned < 1000 {
break
}
after = result.Next
}
key := ""
for {
result, err := ReconcileOrphans(ctx, metadata, objects, key, time.Hour, apply)
if err != nil {
return err
}
if err := encoder.Encode(result); err != nil {
return err
}
if result.Scanned < 1000 {
return nil
}
key = result.Next
}
}
+92
View File
@@ -0,0 +1,92 @@
package media
import (
"context"
"errors"
"io"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
type pagedFixture struct {
reconciliationFixture
metadataPage int
objectPage int
}
// Scan returns one full fresh page followed by an empty continuation.
func (f *pagedFixture) Scan(context.Context, uuid.UUID, int) ([]dto.Attachment, error) {
f.metadataPage++
if f.metadataPage > 1 {
return nil, nil
}
records := make([]dto.Attachment, 1000)
for i := range records {
records[i] = dto.Attachment{ID: uuid.New(), CreatedAt: time.Now()}
}
return records, nil
}
// List returns one full fresh page followed by an empty continuation.
func (f *pagedFixture) List(context.Context, string) ([]ObjectInfo, error) {
f.objectPage++
if f.objectPage > 1 {
return nil, nil
}
records := make([]ObjectInfo, 1000)
for i := range records {
records[i] = ObjectInfo{Key: uuid.NewString(), ModifiedAt: time.Now()}
}
return records, nil
}
type failingWriter struct {
successful int
}
// Write injects a broken report sink after a fixed number of complete pages.
func (f *failingWriter) Write(data []byte) (int, error) {
if f.successful == 0 {
return 0, io.ErrClosedPipe
}
f.successful--
return len(data), nil
}
// TestReconciliationPagination proves both inventories advance beyond a full page.
func TestReconciliationPagination(t *testing.T) {
f := &pagedFixture{}
if err := RunReconciliation(t.Context(), f, f, io.Discard, false); err != nil {
t.Fatal(err)
}
if f.metadataPage != 2 || f.objectPage != 2 {
t.Fatalf("pages: metadata=%d objects=%d", f.metadataPage, f.objectPage)
}
}
// TestReconciliationStopsOnFailures prevents misleading successful reports after lost evidence or dependencies.
func TestReconciliationStopsOnFailures(t *testing.T) {
fault := errors.New("dependency failure")
cases := []struct {
name string
fixture reconciliationFixture
writer io.Writer
}{
{"metadata", reconciliationFixture{scanErr: fault}, io.Discard},
{"objects", reconciliationFixture{listErr: fault}, io.Discard},
{"first report", reconciliationFixture{}, &failingWriter{}},
{"second report", reconciliationFixture{}, &failingWriter{successful: 1}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
if err := RunReconciliation(t.Context(), &f, &f, tc.writer, false); err == nil {
t.Fatal("failed run reported success")
}
})
}
}
+145
View File
@@ -0,0 +1,145 @@
// Package media implements attachment authorization and the S3 publication protocol.
package media
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"time"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// Metadata persists reservations before object creation.
type Metadata interface {
// Reserve inserts an uploading reservation.
Reserve(context.Context, dto.Attachment) error
// Publish atomically transitions the reservation to ready.
Publish(context.Context, uuid.UUID) (dto.Attachment, error)
// Attachment retrieves metadata by a validated ID.
Attachment(context.Context, uuid.UUID) (dto.Attachment, error)
}
// Objects exposes private object operations without a concrete S3 client.
type Objects interface {
// Put uploads a known bounded length without a multipart buffer.
Put(context.Context, string, string, io.Reader, int64) error
// Get opens an original stream; the caller closes it.
Get(context.Context, string) (io.ReadCloser, error)
}
// Chats authorizes access using the existing business service.
type Chats interface {
// ChatsGetByID checks the caller and membership.
ChatsGetByID(context.Context, string, string) (dto.ChatDTO, error)
}
// Service coordinates bounded validation and durable publication.
type Service struct {
metadata Metadata
objects Objects
chats Chats
slots chan struct{}
}
// New validates required dependencies and caps simultaneous image decoding.
func New(metadata Metadata, objects Objects, chats Chats) (*Service, error) {
if metadata == nil || objects == nil || chats == nil {
return nil, fmt.Errorf("attachment dependencies are required")
}
return &Service{metadata: metadata, objects: objects, chats: chats, slots: make(chan struct{}, 2)}, nil
}
// Upload validates access and original bytes before reserving and publishing.
func (s *Service) Upload(ctx context.Context, user, chat, filename, contentType string, body []byte) (dto.Attachment, error) {
scope, err := s.chats.ChatsGetByID(ctx, user, chat)
if err != nil {
return dto.Attachment{}, err
}
select {
case s.slots <- struct{}{}:
defer func() {
<-s.slots
}()
default:
return dto.Attachment{}, service.ErrUnavailable
}
if err := validateImage(filename, contentType, body); err != nil {
return dto.Attachment{}, err
}
owner, err := uuid.Parse(user)
if err != nil {
return dto.Attachment{}, service.ErrUnauthorized
}
sum := sha256.Sum256(body)
id := uuid.New()
now := time.Now().UTC()
attachment := dto.Attachment{
ID: id,
ChatID: scope.ID,
OwnerID: owner,
Filename: filename,
ContentType: contentType,
SizeBytes: int64(len(body)),
SHA256: hex.EncodeToString(sum[:]),
Status: "uploading",
ObjectKey: "original/" + id.String(),
CreatedAt: now,
UpdatedAt: now,
}
if err := s.metadata.Reserve(ctx, attachment); err != nil {
return dto.Attachment{}, err
}
if err := s.objects.Put(ctx, attachment.ObjectKey, contentType, bytes.NewReader(body), attachment.SizeBytes); err != nil {
return dto.Attachment{}, service.ErrUnavailable
}
// A lost COMMIT acknowledgement must never trigger deletion of a possibly published object.
return s.metadata.Publish(ctx, id)
}
// Get authorizes metadata access without exposing private object coordinates.
func (s *Service) Get(ctx context.Context, user, rawID string) (dto.Attachment, error) {
id, err := uuid.Parse(rawID)
if err != nil {
return dto.Attachment{}, service.ErrInvalid
}
attachment, err := s.metadata.Attachment(ctx, id)
if errors.Is(err, store.ErrNotFound) {
return dto.Attachment{}, service.ErrNotFound
}
if err != nil {
return dto.Attachment{}, err
}
if _, err := s.chats.ChatsGetByID(ctx, user, attachment.ChatID.String()); err != nil {
return dto.Attachment{}, err
}
if attachment.Status != "ready" {
return dto.Attachment{}, service.ErrConflict
}
return attachment, nil
}
// Download validates access and variant before opening the original stream.
func (s *Service) Download(ctx context.Context, user, id, variant string) (dto.Attachment, io.ReadCloser, error) {
attachment, err := s.Get(ctx, user, id)
if err != nil {
return dto.Attachment{}, nil, err
}
if variant != "" && variant != "original" {
return dto.Attachment{}, nil, service.ErrNotFound
}
reader, err := s.objects.Get(ctx, attachment.ObjectKey)
if err != nil {
return dto.Attachment{}, nil, service.ErrUnavailable
}
return attachment, reader, nil
}
+225
View File
@@ -0,0 +1,225 @@
package media
import (
"bytes"
"context"
"errors"
"io"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
type mediaFixture struct {
attachment dto.Attachment
body []byte
authorizeErr error
reserveErr error
publishErr error
getErr error
objectErr error
}
// ChatsGetByID models a single authorization outcome for one scenario.
func (f *mediaFixture) ChatsGetByID(_ context.Context, _, chat string) (dto.ChatDTO, error) {
id, _ := uuid.Parse(chat)
return dto.ChatDTO{ID: id}, f.authorizeErr
}
// Reserve records durable intent before a test object can be written.
func (f *mediaFixture) Reserve(_ context.Context, a dto.Attachment) error {
f.attachment = a
return f.reserveErr
}
// Publish models an acknowledged or uncertain database commit.
func (f *mediaFixture) Publish(_ context.Context, _ uuid.UUID) (dto.Attachment, error) {
f.attachment.Status = "ready"
return f.attachment, f.publishErr
}
// Attachment returns fixture metadata without bypassing service authorization.
func (f *mediaFixture) Attachment(_ context.Context, _ uuid.UUID) (dto.Attachment, error) {
return f.attachment, f.getErr
}
// Put captures exact original bytes or injects an object failure.
func (f *mediaFixture) Put(_ context.Context, _, _ string, r io.Reader, _ int64) error {
if f.objectErr != nil {
return f.objectErr
}
var err error
f.body, err = io.ReadAll(r)
return err
}
// Get returns a separate read cursor over the captured original.
func (f *mediaFixture) Get(_ context.Context, _ string) (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(f.body)), f.objectErr
}
// mediaService constructs an independent service with explicit fixture dependencies.
func mediaService(t *testing.T, f *mediaFixture) *Service {
t.Helper()
s, err := New(f, f, f)
if err != nil {
t.Fatal(err)
}
return s
}
// TestUploadPublication verifies exact bytes and durable publication ordering.
func TestUploadPublication(t *testing.T) {
f := &mediaFixture{}
s := mediaService(t, f)
original := imageBytes(t)
a, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", original)
if err != nil || a.Status != "ready" || a.SizeBytes != int64(len(original)) || len(a.SHA256) != 64 || !bytes.Equal(f.body, original) {
t.Fatalf("upload result: %+v %v", a, err)
}
}
// TestUploadRejectsUnauthorized verifies authorization precedes object creation.
func TestUploadRejectsUnauthorized(t *testing.T) {
f := &mediaFixture{authorizeErr: service.ErrNotFound}
s := mediaService(t, f)
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
if !errors.Is(err, service.ErrNotFound) || f.body != nil {
t.Fatalf("unauthorized upload: %v", err)
}
}
// TestUploadDependencyFailures verifies failed operations are not acknowledged as ready.
func TestUploadDependencyFailures(t *testing.T) {
cases := []struct {
name string
fixture mediaFixture
}{
{name: "reserve", fixture: mediaFixture{reserveErr: service.ErrUnavailable}},
{name: "put", fixture: mediaFixture{objectErr: service.ErrUnavailable}},
{name: "commit acknowledgement", fixture: mediaFixture{publishErr: service.ErrUnavailable}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
s := mediaService(t, &f)
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
if !errors.Is(err, service.ErrUnavailable) {
t.Fatalf("error=%v", err)
}
})
}
}
// TestUploadConcurrencyBound verifies decoding cannot create an unbounded queue.
func TestUploadConcurrencyBound(t *testing.T) {
s := mediaService(t, &mediaFixture{})
s.slots <- struct{}{}
s.slots <- struct{}{}
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", imageBytes(t))
if !errors.Is(err, service.ErrUnavailable) {
t.Fatal(err)
}
}
// TestGetAttachment checks metadata authorization and intermediate state handling.
func TestGetAttachment(t *testing.T) {
cases := []struct {
name string
fixture mediaFixture
id string
want error
}{
{name: "invalid id", id: "bad", want: service.ErrInvalid},
{name: "missing", id: uuid.NewString(), fixture: mediaFixture{getErr: store.ErrNotFound}, want: service.ErrNotFound},
{name: "database unavailable", id: uuid.NewString(), fixture: mediaFixture{getErr: service.ErrUnavailable}, want: service.ErrUnavailable},
{name: "foreign", id: uuid.NewString(), fixture: mediaFixture{authorizeErr: service.ErrNotFound}, want: service.ErrNotFound},
{name: "unfinished", id: uuid.NewString(), fixture: mediaFixture{attachment: dto.Attachment{Status: "uploading"}}, want: service.ErrConflict},
{name: "ready", id: uuid.NewString(), fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
s := mediaService(t, &f)
_, err := s.Get(t.Context(), uuid.NewString(), tc.id)
if !errors.Is(err, tc.want) {
t.Fatalf("got %v want %v", err, tc.want)
}
})
}
}
// TestDownloadOriginal checks byte identity through an independently authorized read.
func TestDownloadOriginal(t *testing.T) {
f := &mediaFixture{attachment: dto.Attachment{Status: "ready"}, body: imageBytes(t)}
s := mediaService(t, f)
_, reader, err := s.Download(t.Context(), uuid.NewString(), uuid.NewString(), "original")
if err != nil {
t.Fatal(err)
}
got, err := io.ReadAll(reader)
if closeErr := reader.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil || !bytes.Equal(got, f.body) {
t.Fatalf("download: %v", err)
}
}
// TestMediaRequiresDependencies rejects incomplete service composition.
func TestMediaRequiresDependencies(t *testing.T) {
if _, err := New(nil, nil, nil); err == nil {
t.Fatal("missing dependencies accepted")
}
}
// TestUploadRejectsInvalidOriginal never reserves invalid file metadata.
func TestUploadRejectsInvalidOriginal(t *testing.T) {
f := &mediaFixture{}
s := mediaService(t, f)
_, err := s.Upload(t.Context(), uuid.NewString(), uuid.NewString(), "a.png", "image/png", []byte("invalid"))
if !errors.Is(err, service.ErrMedia) || f.attachment.ID != uuid.Nil {
t.Fatalf("invalid bytes persisted: %v", err)
}
}
// TestUploadRejectsMalformedOwner does not persist an invalid authenticated identity.
func TestUploadRejectsMalformedOwner(t *testing.T) {
f := &mediaFixture{}
s := mediaService(t, f)
_, err := s.Upload(t.Context(), "bad", uuid.NewString(), "a.png", "image/png", imageBytes(t))
if !errors.Is(err, service.ErrUnauthorized) {
t.Fatal(err)
}
}
// TestDownloadFailures keeps authorization, variant and dependency failures distinct.
func TestDownloadFailures(t *testing.T) {
cases := []struct {
name string
fixture mediaFixture
variant string
want error
}{
{name: "foreign", fixture: mediaFixture{authorizeErr: service.ErrNotFound}, want: service.ErrNotFound},
{name: "variant missing", fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}}, variant: "thumbnail", want: service.ErrNotFound},
{name: "S3 unavailable", fixture: mediaFixture{attachment: dto.Attachment{Status: "ready"}, objectErr: service.ErrUnavailable}, want: service.ErrUnavailable},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := tc.fixture
s := mediaService(t, &f)
_, reader, err := s.Download(t.Context(), uuid.NewString(), uuid.NewString(), tc.variant)
if reader != nil {
_ = reader.Close()
}
if !errors.Is(err, tc.want) {
t.Fatalf("got %v want %v", err, tc.want)
}
})
}
}
+48
View File
@@ -0,0 +1,48 @@
package media
import (
"bytes"
"image"
// Register the only accepted original image decoders.
_ "image/jpeg"
// Register PNG for content validation before storage.
_ "image/png"
"strings"
"unicode"
"unicode/utf8"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
const maxImageBytes = 10 << 20
const maxImagePixels = 40_000_000
// validateImage checks encoded size, display name, actual format and complete decoding.
func validateImage(filename, mime string, body []byte) error {
if len(body) > maxImageBytes {
return service.ErrTooLarge
}
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
return service.ErrInvalid
}
for _, r := range filename {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return service.ErrInvalid
}
}
if mime != "image/png" && mime != "image/jpeg" {
return service.ErrMedia
}
dimensions, format, err := image.DecodeConfig(bytes.NewReader(body))
if err != nil || "image/"+format != mime {
return service.ErrMedia
}
if dimensions.Width < 1 || dimensions.Height < 1 || int64(dimensions.Width)*int64(dimensions.Height) > maxImagePixels {
return service.ErrTooLarge
}
if _, _, err := image.Decode(bytes.NewReader(body)); err != nil {
return service.ErrMedia
}
return nil
}
+65
View File
@@ -0,0 +1,65 @@
package media
import (
"bytes"
"encoding/binary"
"errors"
"hash/crc32"
"image"
"image/png"
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// imageBytes creates a valid independent synthetic PNG fixture.
func imageBytes(t *testing.T) []byte {
t.Helper()
var output bytes.Buffer
if err := png.Encode(&output, image.NewRGBA(image.Rect(0, 0, 3, 2))); err != nil {
t.Fatal(err)
}
return output.Bytes()
}
// TestValidateImage checks file-level rejection independently of persistence.
func TestValidateImage(t *testing.T) {
valid := imageBytes(t)
cases := []struct {
name string
filename string
mime string
body []byte
want error
}{
{"valid", "test.png", "image/png", valid, nil},
{"traversal", "../test.png", "image/png", valid, service.ErrInvalid},
{"backslash", "a\\b", "image/png", valid, service.ErrInvalid},
{"control", "a\n", "image/png", valid, service.ErrInvalid},
{"empty name", "", "image/png", valid, service.ErrInvalid},
{"mime mismatch", "a.jpg", "image/jpeg", valid, service.ErrMedia},
{"unsupported", "a.png", "text/plain", valid, service.ErrMedia},
{"corrupt header", "a.png", "image/png", []byte("bad"), service.ErrMedia},
{"truncated payload", "a.png", "image/png", valid[:len(valid)-12], service.ErrMedia},
{"encoded limit", "a.png", "image/png", make([]byte, maxImageBytes+1), service.ErrTooLarge},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := validateImage(tc.filename, tc.mime, tc.body)
if !errors.Is(err, tc.want) {
t.Fatalf("got %v want %v", err, tc.want)
}
})
}
}
// TestPixelLimitPrecedesDecode rejects a valid PNG header before allocating a huge pixel buffer.
func TestPixelLimitPrecedesDecode(t *testing.T) {
body := append([]byte{}, imageBytes(t)...)
binary.BigEndian.PutUint32(body[16:20], 10000)
binary.BigEndian.PutUint32(body[20:24], 10000)
binary.BigEndian.PutUint32(body[29:33], crc32.ChecksumIEEE(body[12:29]))
if err := validateImage("huge.png", "image/png", body); !errors.Is(err, service.ErrTooLarge) {
t.Fatalf("pixel limit: %v", err)
}
}
+33
View File
@@ -0,0 +1,33 @@
package dto
import (
"time"
"github.com/google/uuid"
)
// Attachment contains private persistence metadata and the public file description.
type Attachment struct {
// ID identifies the immutable upload.
ID uuid.UUID
// ChatID defines the authorization scope.
ChatID uuid.UUID
// OwnerID identifies the uploader.
OwnerID uuid.UUID
// Filename is display-only and never an object path.
Filename string
// ContentType is validated against decoded bytes.
ContentType string
// SizeBytes is the original encoded length.
SizeBytes int64
// SHA256 is the lowercase original checksum.
SHA256 string
// Status is the durable upload state.
Status string
// ObjectKey is private and must not reach HTTP responses.
ObjectKey string
// CreatedAt is the reservation timestamp.
CreatedAt time.Time
// UpdatedAt is the latest durable transition.
UpdatedAt time.Time
}
+118
View File
@@ -0,0 +1,118 @@
// Package dto defines the transport-independent data shared by service and store.
package dto
import (
"time"
"github.com/google/uuid"
)
// UserDTO is the public account profile without credentials.
type UserDTO struct {
// ID is the server-generated user identifier.
ID uuid.UUID
// Username is the unique lowercase ASCII account name.
Username string
// DisplayName is the display label, limited to 100 Unicode code points.
DisplayName string
// CreatedAt is the server-assigned UTC creation time.
CreatedAt time.Time
}
// ChatDTO is a chat with immutable membership.
type ChatDTO struct {
// ID is the server-generated chat identifier.
ID uuid.UUID
// Title is the nonblank title, limited to 100 Unicode code points.
Title string
// MemberIDs contains the fixed set of users allowed to read and write the chat.
MemberIDs []uuid.UUID
// CreatedAt is the server-assigned UTC creation time.
CreatedAt time.Time
}
// MessageDTO is an immutable message stored in a chat.
type MessageDTO struct {
// AttachmentIDs references ordered immutable files in the same chat.
AttachmentIDs []string
// IdempotencyKey identifies a validated retry within the sender and chat scope.
IdempotencyKey string
// ID is the server-generated message identifier.
ID uuid.UUID
// ChatID identifies the owning chat.
ChatID uuid.UUID
// SenderID identifies the user resolved from the request identity.
SenderID uuid.UUID
// Text contains the original text, limited to 4000 Unicode code points.
Text string
// CreatedAt is the server-assigned UTC ordering timestamp.
CreatedAt time.Time
}
// UsersCreateRequestDTO carries untrusted registration values into the service.
type UsersCreateRequestDTO struct {
// Username is the raw requested account name.
Username string
// DisplayName is the raw requested display label.
DisplayName string
}
// ChatsCreateRequestDTO carries untrusted chat creation input.
type ChatsCreateRequestDTO struct {
// UserID is the caller identifier resolved from a validated session.
UserID string
// Title is the raw requested chat title.
Title string
// MemberIDs contains raw user UUIDs; the service checks uniqueness and membership.
MemberIDs []string
}
// MessagesCreateRequestDTO carries untrusted message creation input.
type MessagesCreateRequestDTO struct {
// AttachmentIDs references ordered immutable files in the same chat.
AttachmentIDs []string
// IdempotencyKey identifies a validated retry within the sender and chat scope.
IdempotencyKey string
// UserID is the authenticated caller identifier, never a supplied sender field.
UserID string
// ChatID is the raw chat UUID from the route.
ChatID string
// Text is the unmodified message text to validate.
Text string
}
// PageRequestDTO carries raw pagination values for service-level validation.
type PageRequestDTO struct {
// UserID is the caller identifier resolved from a validated session.
UserID string
// ChatID is the requested chat UUID; it is unused when listing chats.
ChatID string
// Limit is the raw page size; empty selects the contract default.
Limit string
// Cursor is the opaque continuation token; empty starts at the beginning.
Cursor string
}
// PositionDTO is a validated keyset boundary; its zero value starts a history.
type PositionDTO struct {
// CreatedAt is the timestamp of the last record already returned.
CreatedAt time.Time
// ID is the tie-breaking identifier of the last record already returned.
ID uuid.UUID
}
// ChatPageDTO contains an ordered page of accessible chats.
type ChatPageDTO struct {
// Items contains at most the requested number of chats.
Items []ChatDTO
// NextCursor continues the same user-specific list; nil marks its current end.
NextCursor *string
}
// MessagePageDTO contains an ordered page of chat history.
type MessagePageDTO struct {
// Items contains at most the requested number of messages.
Items []MessageDTO
// NextCursor continues the same chat history; nil marks its current end.
NextCursor *string
}
+13
View File
@@ -0,0 +1,13 @@
package dto
import "time"
// SessionDTO is an issued session, exposing the raw token only at creation.
type SessionDTO struct {
// Token contains 256 random bits encoded for a Bearer header.
Token string
// ExpiresAt is an absolute UTC deadline which is not extended by reads.
ExpiresAt time.Time
// User is the authenticated account without credentials.
User UserDTO
}
+102
View File
@@ -0,0 +1,102 @@
// Package http defines the public JSON boundary, separate from DTOs.
package http
import "time"
// UsersCreateRequest is the registration payload.
type UsersCreateRequest struct {
// Password is the unmodified Unicode registration secret.
Password string `json:"password"`
// Username is the unique lowercase ASCII username.
Username string `json:"username"`
// DisplayName is the user-visible name, limited to 100 Unicode code points.
DisplayName string `json:"display_name"`
}
// ChatsCreateRequest is the chat payload.
type ChatsCreateRequest struct {
// Title is the nonblank chat title, limited to 100 Unicode code points.
Title string `json:"title"`
// MemberIDs contains unique user UUIDs, including the caller when creating a chat.
MemberIDs []string `json:"member_ids"`
}
// MessagesCreateRequest is the message payload.
type MessagesCreateRequest struct {
// AttachmentIDs references up to ten files of this chat.
AttachmentIDs []string `json:"attachment_ids"`
// Text contains nonblank text, limited to 4000 Unicode code points.
Text string `json:"text"`
}
// UserResponse is the public user model.
type UserResponse struct {
// ID is the canonical server-generated UUID.
ID string `json:"id"`
// Username is the unique lowercase ASCII username.
Username string `json:"username"`
// DisplayName is the user-visible name, limited to 100 Unicode code points.
DisplayName string `json:"display_name"`
// CreatedAt is the UTC creation time serialized as RFC 3339.
CreatedAt time.Time `json:"created_at"`
}
// ChatResponse is the public chat model.
type ChatResponse struct {
// ID is the canonical server-generated UUID.
ID string `json:"id"`
// Title is the nonblank chat title, limited to 100 Unicode code points.
Title string `json:"title"`
// MemberIDs contains unique user UUIDs, including the caller when creating a chat.
MemberIDs []string `json:"member_ids"`
// CreatedAt is the UTC creation time serialized as RFC 3339.
CreatedAt time.Time `json:"created_at"`
}
// MessageResponse is the public message model.
type MessageResponse struct {
// AttachmentIDs references up to ten files of this chat.
AttachmentIDs []string `json:"attachment_ids"`
// ID is the canonical server-generated UUID.
ID string `json:"id"`
// ChatID is the canonical UUID of the chat containing the message.
ChatID string `json:"chat_id"`
// SenderID is derived from the request identity, never from a client-supplied sender.
SenderID string `json:"sender_id"`
// Text contains nonblank text, limited to 4000 Unicode code points.
Text string `json:"text"`
// CreatedAt is the UTC creation time serialized as RFC 3339.
CreatedAt time.Time `json:"created_at"`
}
// ChatPageResponse contains visible chats.
type ChatPageResponse struct {
// Items contains the ordered page records; an empty page is serialized as an empty array.
Items []ChatResponse `json:"items"`
// NextCursor is the opaque continuation token or null when the current page is last.
NextCursor *string `json:"next_cursor"`
}
// MessagePageResponse contains the requested history page.
type MessagePageResponse struct {
// Items contains the ordered page records; an empty page is serialized as an empty array.
Items []MessageResponse `json:"items"`
// NextCursor is the opaque continuation token or null when the current page is last.
NextCursor *string `json:"next_cursor"`
}
// ErrorResponse is the mandatory error envelope.
type ErrorResponse struct {
// Error contains the safe public error details.
Error ErrorDetail `json:"error"`
}
// ErrorDetail never exposes internal errors or input contents.
type ErrorDetail struct {
// Code is one of the machine-readable error codes declared by the API contract.
Code string `json:"code"`
// Message is a safe public explanation without internal errors or input contents.
Message string `json:"message"`
// RequestID matches the X-Request-Id response header for log correlation.
RequestID string `json:"request_id"`
}
+110
View File
@@ -0,0 +1,110 @@
// Package objectstore adapts the S3 protocol to bounded application operations.
package objectstore
import (
"context"
"fmt"
"io"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
)
const operationTimeout = 15 * time.Second
// Client owns a reusable S3 client and its private bucket scope.
type Client struct {
client *minio.Client
bucket string
}
// New configures a lazy client with explicit service credentials.
func New(cfg *config.ObjectStore) (*Client, error) {
client, err := minio.New(cfg.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: cfg.Secure,
})
if err != nil {
return nil, err
}
return &Client{client: client, bucket: cfg.Bucket}, nil
}
// Put uses one bounded PUT for an already validated original.
func (c *Client) Put(ctx context.Context, key, mime string, reader io.Reader, size int64) error {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
_, err := c.client.PutObject(ctx, c.bucket, key, reader, size, minio.PutObjectOptions{
ContentType: mime,
DisableMultipart: true,
})
return err
}
// Get verifies object availability before handing its bounded stream to the caller.
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
object, err := c.client.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
if err != nil {
cancel()
return nil, err
}
if _, err := object.Stat(); err != nil {
_ = object.Close()
cancel()
return nil, err
}
return &stream{ReadCloser: object, cancel: cancel}, nil
}
type stream struct {
io.ReadCloser
cancel context.CancelFunc
}
// Close releases the connection and its operation deadline.
func (s *stream) Close() error {
defer s.cancel()
return s.ReadCloser.Close()
}
// Ping verifies the bucket is accessible with the configured scoped identity.
func (c *Client) Ping(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
exists, err := c.client.BucketExists(ctx, c.bucket)
if err == nil && !exists {
return fmt.Errorf("private bucket missing")
}
return err
}
// Exists distinguishes a missing object from a failed dependency.
func (c *Client) Exists(ctx context.Context, key string) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
_, err := c.client.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{})
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
return false, nil
}
return err == nil, err
}
// Remove deletes one explicitly claimed immutable object.
func (c *Client) Remove(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
return c.client.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{})
}
// Bootstrap creates a bucket idempotently; no anonymous policy is installed.
func (c *Client) Bootstrap(ctx context.Context) error {
exists, err := c.client.BucketExists(ctx, c.bucket)
if err != nil || exists {
return err
}
return c.client.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{})
}
+193
View File
@@ -0,0 +1,193 @@
package objectstore
import (
"bytes"
"context"
"io"
"net/http"
"os"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/config"
)
// testObjects creates a scoped client against an explicitly isolated S3 server.
func testObjects(t *testing.T) *Client {
t.Helper()
if os.Getenv("S3_ENDPOINT") == "" {
t.Skip("isolated S3_ENDPOINT required")
}
cfg, err := config.NewObjectStore()
if err != nil {
t.Fatal(err)
}
client, err := New(cfg)
if err != nil {
t.Fatal(err)
}
return client
}
// TestOriginalRoundTrip checks real S3 publication, streaming, listing and explicit deletion.
func TestOriginalRoundTrip(t *testing.T) {
client := testObjects(t)
key := "original/" + uuid.NewString()
original := []byte("synthetic original bytes")
if err := client.Put(t.Context(), key, "application/octet-stream", bytes.NewReader(original), int64(len(original))); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := client.Remove(context.Background(), key); err != nil {
t.Error(err)
}
})
reader, err := client.Get(t.Context(), key)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(reader)
if closeErr := reader.Close(); closeErr != nil {
t.Fatal(closeErr)
}
if err != nil || !bytes.Equal(data, original) {
t.Fatalf("original changed: %v", err)
}
found, err := client.Exists(t.Context(), key)
if err != nil || !found {
t.Fatalf("existence: %v", err)
}
entries, err := client.List(t.Context(), "")
if err != nil {
t.Fatal(err)
}
found = false
for _, entry := range entries {
found = found || entry.Key == key
}
if !found {
t.Fatal("original absent from inventory")
}
}
// TestMissingOriginal checks absence is distinct from unavailable S3.
func TestMissingOriginal(t *testing.T) {
client := testObjects(t)
key := "original/" + uuid.NewString()
exists, err := client.Exists(t.Context(), key)
if err != nil || exists {
t.Fatalf("missing: %v", err)
}
if reader, err := client.Get(t.Context(), key); err == nil {
_ = reader.Close()
t.Fatal("missing stream accepted")
}
}
// TestUnavailableS3 returns bounded failures instead of converting them into missing objects.
func TestUnavailableS3(t *testing.T) {
client, err := New(&config.ObjectStore{Endpoint: "127.0.0.1:1", Bucket: "attachments", AccessKey: "test", SecretKey: "test"})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
if err := client.Put(ctx, "original/test", "image/png", bytes.NewReader(nil), 0); err == nil {
t.Fatal("unavailable PUT succeeded")
}
if _, err := client.Get(ctx, "original/test"); err == nil {
t.Fatal("unavailable GET succeeded")
}
if _, err := client.Exists(ctx, "original/test"); err == nil {
t.Fatal("unavailable HEAD classified as missing")
}
if _, err := client.List(ctx, ""); err == nil {
t.Fatal("unavailable LIST succeeded")
}
if err := client.Ping(ctx); err == nil {
t.Fatal("unavailable bucket ready")
}
if err := client.Bootstrap(ctx); err == nil {
t.Fatal("unavailable bootstrap succeeded")
}
}
// TestInvalidEndpoint rejects malformed S3 configuration before a network request.
func TestInvalidEndpoint(t *testing.T) {
if _, err := New(&config.ObjectStore{Endpoint: "http://invalid/path"}); err == nil {
t.Fatal("invalid endpoint accepted")
}
}
// TestBucketBootstrap creates an isolated private bucket twice and verifies scoped credentials cannot access it.
func TestBucketBootstrap(t *testing.T) {
scoped := testObjects(t)
if err := scoped.Ping(t.Context()); err != nil {
t.Fatal(err)
}
cfg, err := config.NewObjectStore()
if err != nil {
t.Fatal(err)
}
secret := os.Getenv("S3_ADMIN_SECRET")
if secret == "" {
t.Skip("isolated S3_ADMIN_SECRET required for bootstrap test")
}
cfg.AccessKey = "operator"
cfg.SecretKey = secret
cfg.Bucket = "test-" + uuid.NewString()
admin, err := New(cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := admin.client.RemoveBucket(context.Background(), cfg.Bucket); err != nil {
t.Error(err)
}
})
if err := admin.Bootstrap(t.Context()); err != nil {
t.Fatal(err)
}
if err := admin.Bootstrap(t.Context()); err != nil {
t.Fatal(err)
}
scoped.bucket = cfg.Bucket
if _, err := scoped.List(t.Context(), ""); err == nil {
t.Fatal("service identity accessed another bucket")
}
}
// TestPrivateBucketRejectsAnonymous verifies object ACL independently of application authorization.
func TestPrivateBucketRejectsAnonymous(t *testing.T) {
client := testObjects(t)
key := "original/" + uuid.NewString()
if err := client.Put(t.Context(), key, "application/octet-stream", bytes.NewReader([]byte("private")), 7); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := client.Remove(context.Background(), key); err != nil {
t.Error(err)
}
})
cfg, err := config.NewObjectStore()
if err != nil {
t.Fatal(err)
}
scheme := "https://"
if !cfg.Secure {
scheme = "http://"
}
httpClient := &http.Client{Timeout: time.Second}
response, err := httpClient.Get(scheme + cfg.Endpoint + "/" + cfg.Bucket + "/" + key)
if err != nil {
t.Fatal(err)
}
if err := response.Body.Close(); err != nil {
t.Fatal(err)
}
if response.StatusCode != http.StatusForbidden {
t.Fatalf("anonymous access status=%d", response.StatusCode)
}
}
+26
View File
@@ -0,0 +1,26 @@
package objectstore
import (
"context"
"github.com/minio/minio-go/v7"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/media"
)
// List bounds each reconciliation page and cancels the SDK producer before returning.
func (c *Client) List(ctx context.Context, after string) ([]media.ObjectInfo, error) {
ctx, cancel := context.WithTimeout(ctx, operationTimeout)
defer cancel()
result := make([]media.ObjectInfo, 0, 1000)
for object := range c.client.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: "original/", StartAfter: after, Recursive: true, MaxKeys: 1000}) {
if object.Err != nil {
return nil, object.Err
}
result = append(result, media.ObjectInfo{Key: object.Key, ModifiedAt: object.LastModified})
if len(result) == 1000 {
break
}
}
return result, nil
}
+54
View File
@@ -0,0 +1,54 @@
// Package password implements a bounded Argon2id password KDF.
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"strings"
"golang.org/x/crypto/argon2"
)
const (
memoryKiB = 19 * 1024
iterations = 2
parallelism = 1
saltBytes = 16
hashBytes = 32
prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
)
// Hasher implements password hashing without transport or storage dependencies.
type Hasher struct{}
// Hash generates a salted Argon2id encoding using fixed resource bounds.
func (Hasher) Hash(password string) (string, error) {
salt := make([]byte, saltBytes)
if _, err := rand.Read(salt); err != nil {
return "", err
}
hash := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes)
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash), nil
}
// Verify accepts only this application's bounded KDF encoding and compares in constant time.
func (Hasher) Verify(encoded, password string) bool {
if !strings.HasPrefix(encoded, prefix) {
return false
}
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
if len(parts) != 2 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
if err != nil || len(salt) != saltBytes {
return false
}
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil || len(expected) != hashBytes {
return false
}
actual := argon2.IDKey([]byte(password), salt, iterations, memoryKiB, parallelism, hashBytes)
return subtle.ConstantTimeCompare(actual, expected) == 1
}
+37
View File
@@ -0,0 +1,37 @@
package password
import (
"strings"
"testing"
)
// TestPasswordRoundTrip verifies long Unicode input without bcrypt-style truncation.
func TestPasswordRoundTrip(t *testing.T) {
password := strings.Repeat("🔐", 128)
hasher := Hasher{}
encoded, err := hasher.Hash(password)
if err != nil {
t.Fatal(err)
}
if !hasher.Verify(encoded, password) || hasher.Verify(encoded, password+"x") {
t.Fatal("password verification mismatch")
}
second, err := hasher.Hash(password)
if err != nil {
t.Fatal(err)
}
if encoded == second {
t.Fatal("salt reused")
}
}
// TestPasswordRejectsInvalidEncoding checks corrupt or unbounded KDF descriptions.
func TestPasswordRejectsInvalidEncoding(t *testing.T) {
for _, encoded := range []string{"", "$argon2id$v=19$m=999999999,t=2,p=1$a$b", prefix + "x", prefix + "%%%$abc", prefix + "YWJj$abc", prefix + "AAAAAAAAAAAAAAAAAAAAAA$%%%", prefix + "AAAAAAAAAAAAAAAAAAAAAA$YWJj"} {
t.Run(encoded, func(t *testing.T) {
if (Hasher{}).Verify(encoded, "password") {
t.Fatal("invalid encoding accepted")
}
})
}
}
+44
View File
@@ -0,0 +1,44 @@
package service
import (
"context"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// Passwords is the password KDF boundary used by authentication.
type Passwords interface {
// Hash creates a salted password encoding.
Hash(password string) (string, error)
// Verify checks the supplied password against its encoding.
Verify(encoded, password string) bool
}
// Accounts persists credentials and session validity independently of HTTP.
type Accounts interface {
// Register atomically stores a profile with credentials.
Register(context.Context, dto.UserDTO, string) (dto.UserDTO, error)
// Credentials looks up the password encoding and account profile.
Credentials(context.Context, string) (dto.UserDTO, string, error)
// SaveSession persists an opaque token digest and absolute expiry.
SaveSession(context.Context, string, uuid.UUID, time.Time) error
// SessionUser resolves an unexpired token digest.
SessionUser(context.Context, string) (uuid.UUID, error)
// RevokeSession invalidates a token digest.
RevokeSession(context.Context, string) error
}
// Authentication defines registration and opaque session operations.
type Authentication interface {
// Register validates registration and persists a password-protected account.
Register(context.Context, dto.UsersCreateRequestDTO, string) (dto.UserDTO, error)
// Login verifies credentials and issues an opaque session.
Login(context.Context, string, string) (dto.SessionDTO, error)
// Authenticate resolves a valid token to its immutable owner.
Authenticate(context.Context, string) (string, error)
// Logout revokes the current token.
Logout(context.Context, string) error
}
+123
View File
@@ -0,0 +1,123 @@
// Package authentication validates credentials and owns the session lifecycle.
package authentication
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"time"
"unicode/utf8"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service/production"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
const (
minimumPasswordRunes = 12
maximumPasswordRunes = 128
tokenBytes = 32
)
// Service performs password and session operations through explicit boundaries.
type Service struct {
accounts service.Accounts
passwords service.Passwords
ttl time.Duration
dummyHash string
}
// New validates dependencies and prepares the unknown-account verification hash.
func New(accounts service.Accounts, passwords service.Passwords, ttl time.Duration) (*Service, error) {
if accounts == nil || passwords == nil || ttl <= 0 {
return nil, fmt.Errorf("accounts, passwords and positive session TTL are required")
}
dummyHash, err := passwords.Hash("unknown-account-dummy-password")
if err != nil {
return nil, err
}
return &Service{accounts: accounts, passwords: passwords, ttl: ttl, dummyHash: dummyHash}, nil
}
// Register checks profile and Unicode password bounds before hashing and persistence.
func (s *Service) Register(ctx context.Context, request dto.UsersCreateRequestDTO, password string) (dto.UserDTO, error) {
user, err := production.PrepareUser(request)
if err != nil || !validPassword(password) {
return dto.UserDTO{}, service.ErrInvalid
}
hash, err := s.passwords.Hash(password)
if err != nil {
return dto.UserDTO{}, err
}
user, err = s.accounts.Register(ctx, user, hash)
if errors.Is(err, store.ErrConflict) {
return dto.UserDTO{}, service.ErrConflict
}
return user, err
}
// Login verifies credentials uniformly and persists a new session before returning its token.
func (s *Service) Login(ctx context.Context, username, password string) (dto.SessionDTO, error) {
if !validPassword(password) {
return dto.SessionDTO{}, service.ErrUnauthorized
}
user, hash, err := s.accounts.Credentials(ctx, username)
if err != nil && !errors.Is(err, store.ErrNotFound) {
return dto.SessionDTO{}, err
}
missing := errors.Is(err, store.ErrNotFound)
if missing {
hash = s.dummyHash
}
if !s.passwords.Verify(hash, password) || missing {
return dto.SessionDTO{}, service.ErrUnauthorized
}
random := make([]byte, tokenBytes)
if _, err := rand.Read(random); err != nil {
return dto.SessionDTO{}, err
}
token := base64.RawURLEncoding.EncodeToString(random)
expiry := time.Now().UTC().Add(s.ttl)
if err := s.accounts.SaveSession(ctx, digest(token), user.ID, expiry); err != nil {
return dto.SessionDTO{}, err
}
return dto.SessionDTO{Token: token, ExpiresAt: expiry, User: user}, nil
}
// Authenticate checks absolute expiry in the source of truth on every request.
func (s *Service) Authenticate(ctx context.Context, token string) (string, error) {
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(decoded) != tokenBytes {
return "", service.ErrUnauthorized
}
id, err := s.accounts.SessionUser(ctx, digest(token))
if errors.Is(err, store.ErrNotFound) {
return "", service.ErrUnauthorized
}
if err != nil {
return "", err
}
return id.String(), nil
}
// Logout removes the current session from the authoritative store.
func (s *Service) Logout(ctx context.Context, token string) error {
return s.accounts.RevokeSession(ctx, digest(token))
}
// digest produces the storage key without persisting the bearer secret.
func digest(token string) string {
hash := sha256.Sum256([]byte(token))
return hex.EncodeToString(hash[:])
}
// validPassword enforces the contract in Unicode code points without truncation.
func validPassword(password string) bool {
count := utf8.RuneCountInString(password)
return utf8.ValidString(password) && count >= minimumPasswordRunes && count <= maximumPasswordRunes
}
@@ -0,0 +1,232 @@
package authentication
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
type accountFixture struct {
user dto.UserDTO
hash string
tokenHash string
expiry time.Time
failure error
registerFailure error
saveFailure error
}
// Register captures one synthetic account or a prescribed persistence failure.
func (f *accountFixture) Register(_ context.Context, user dto.UserDTO, hash string) (dto.UserDTO, error) {
f.user = user
f.hash = hash
return user, f.registerFailure
}
// Credentials returns the fixture account and its password encoding.
func (f *accountFixture) Credentials(context.Context, string) (dto.UserDTO, string, error) {
return f.user, f.hash, f.failure
}
// SaveSession captures the digest and absolute expiry without storing the raw token.
func (f *accountFixture) SaveSession(_ context.Context, hash string, _ uuid.UUID, expiry time.Time) error {
f.tokenHash = hash
f.expiry = expiry
return f.saveFailure
}
// SessionUser implements expiry and revocation for the service unit fixture.
func (f *accountFixture) SessionUser(_ context.Context, hash string) (uuid.UUID, error) {
if f.failure != nil {
return uuid.Nil, f.failure
}
if hash != f.tokenHash || !f.expiry.After(time.Now()) {
return uuid.Nil, store.ErrNotFound
}
return f.user.ID, nil
}
// RevokeSession invalidates the fixture digest.
func (f *accountFixture) RevokeSession(context.Context, string) error {
f.tokenHash = ""
return f.failure
}
type passwordFixture struct {
failure error
}
// Hash creates an intentionally noncryptographic encoding for service-only unit tests.
func (f passwordFixture) Hash(password string) (string, error) {
return "fixture:" + password, f.failure
}
// Verify compares only test fixture encodings; production uses Argon2id.
func (passwordFixture) Verify(encoded, password string) bool {
return encoded == "fixture:"+password
}
// authFixture assembles deterministic service boundaries.
func authFixture(t *testing.T) (*Service, *accountFixture) {
t.Helper()
accounts := &accountFixture{user: dto.UserDTO{ID: uuid.New(), Username: "alice"}, hash: "fixture:synthetic-password"}
s, err := New(accounts, passwordFixture{}, time.Hour)
if err != nil {
t.Fatal(err)
}
return s, accounts
}
// TestRegisterValidatesPassword checks contract boundaries without truncation.
func TestRegisterValidatesPassword(t *testing.T) {
cases := []struct {
name string
password string
valid bool
}{
{"short", "short", false},
{"minimum", strings.Repeat("a", 12), true},
{"unicode maximum", strings.Repeat("🔐", 128), true},
{"too long", strings.Repeat("a", 129), false},
{"invalid UTF8", strings.Repeat("a", 12) + "\xff", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, _ := authFixture(t)
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, tc.password)
if (err == nil) != tc.valid {
t.Fatalf("unexpected registration result: %v", err)
}
})
}
}
// TestRegisterConflictMapsToApplicationError verifies uniqueness error translation.
func TestRegisterConflictMapsToApplicationError(t *testing.T) {
s, accounts := authFixture(t)
accounts.registerFailure = store.ErrConflict
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
if !errors.Is(err, service.ErrConflict) {
t.Fatal(err)
}
}
// TestRegisterHashFailurePreservesCause checks KDF failures before persistence.
func TestRegisterHashFailurePreservesCause(t *testing.T) {
s, _ := authFixture(t)
failure := errors.New("KDF unavailable")
s.passwords = passwordFixture{failure: failure}
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
if !errors.Is(err, failure) {
t.Fatal(err)
}
}
// TestLoginPersistsOnlyTokenDigest checks issued entropy, owner and deadline together.
func TestLoginPersistsOnlyTokenDigest(t *testing.T) {
s, accounts := authFixture(t)
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if err != nil {
t.Fatal(err)
}
if session.Token == accounts.tokenHash || len(accounts.tokenHash) != 64 || session.User.ID != accounts.user.ID || !session.ExpiresAt.Equal(accounts.expiry) {
t.Fatal("invalid issued session")
}
id, err := s.Authenticate(t.Context(), session.Token)
if err != nil || id != accounts.user.ID.String() {
t.Fatalf("session does not authenticate its owner: %v", err)
}
}
// TestLoginRejectsCredentials checks independent authentication rejection scenarios.
func TestLoginRejectsCredentials(t *testing.T) {
cases := []struct {
name string
password string
failure error
expected error
}{
{"short password", "short", nil, service.ErrUnauthorized},
{"wrong password", "incorrect-password", nil, service.ErrUnauthorized},
{"missing account", "synthetic-password", store.ErrNotFound, service.ErrUnauthorized},
{"database unavailable", "synthetic-password", context.DeadlineExceeded, context.DeadlineExceeded},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, accounts := authFixture(t)
accounts.failure = tc.failure
_, err := s.Login(t.Context(), "alice", tc.password)
if !errors.Is(err, tc.expected) {
t.Fatalf("expected %v, got %v", tc.expected, err)
}
})
}
}
// TestLoginDoesNotReturnUnpersistedSession checks failure after successful password verification.
func TestLoginDoesNotReturnUnpersistedSession(t *testing.T) {
s, accounts := authFixture(t)
accounts.saveFailure = context.DeadlineExceeded
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if !errors.Is(err, context.DeadlineExceeded) || session.Token != "" {
t.Fatal("unpersisted session escaped")
}
}
// TestAuthenticateRejectsUnknownToken checks malformed and correctly encoded unknown tokens.
func TestAuthenticateRejectsUnknownToken(t *testing.T) {
for _, token := range []string{"", "%%%", strings.Repeat("A", 43)} {
t.Run(token, func(t *testing.T) {
s, _ := authFixture(t)
if _, err := s.Authenticate(t.Context(), token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal(err)
}
})
}
}
// TestAuthenticatePropagatesDatabaseFailure prevents trusting a token during an outage.
func TestAuthenticatePropagatesDatabaseFailure(t *testing.T) {
s, accounts := authFixture(t)
accounts.failure = context.DeadlineExceeded
if _, err := s.Authenticate(t.Context(), strings.Repeat("A", 43)); !errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
}
}
// TestLogoutRevokesIssuedToken checks that the same token cannot be reused.
func TestLogoutRevokesIssuedToken(t *testing.T) {
s, _ := authFixture(t)
session, err := s.Login(t.Context(), "alice", "synthetic-password")
if err != nil {
t.Fatal(err)
}
if err := s.Logout(t.Context(), session.Token); err != nil {
t.Fatal(err)
}
if _, err := s.Authenticate(t.Context(), session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("revoked token authenticated")
}
}
// TestNewRejectsIncompleteDependencies checks constructor validation and KDF startup failure.
func TestNewRejectsIncompleteDependencies(t *testing.T) {
t.Run("missing accounts", func(t *testing.T) {
if _, err := New(nil, passwordFixture{}, time.Hour); err == nil {
t.Fatal("missing accounts accepted")
}
})
t.Run("hash failure", func(t *testing.T) {
if _, err := New(&accountFixture{}, passwordFixture{failure: context.Canceled}, time.Hour); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
})
}
+17
View File
@@ -0,0 +1,17 @@
package service
import (
"context"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// ProfileCache stores immutable public account profiles; misses fall back to PostgreSQL.
type ProfileCache interface {
// GetProfile returns a cached profile or a miss, including on backend failure.
GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool)
// PutProfile stores a bounded-lifetime profile on a best-effort basis.
PutProfile(context.Context, dto.UserDTO)
}
+12
View File
@@ -0,0 +1,12 @@
package service
import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
// CursorCodec defines the pagination operations required by application services.
type CursorCodec interface {
// Encode signs a position for the specified resource.
Encode(resource string, position cursor.Position) (string, error)
// Decode verifies a token and returns its position; empty tokens start a page sequence.
Decode(encoded, resource string) (cursor.Position, error)
}
+27
View File
@@ -0,0 +1,27 @@
package service
import (
"errors"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
var (
// ErrTooLarge rejects encoded or decoded images beyond policy.
ErrTooLarge = errors.New("image exceeds limit")
// ErrMedia rejects unsupported or corrupted image bytes.
ErrMedia = errors.New("invalid image")
// ErrUnavailable preserves the dependency failure category across service boundaries.
ErrUnavailable = store.ErrUnavailable
// ErrInvalid indicates invalid operation input.
ErrInvalid = errors.New("invalid request")
// ErrUnauthorized indicates an unresolved current user.
ErrUnauthorized = errors.New("unknown user identity")
// ErrNotFound hides both absent and inaccessible resources.
ErrNotFound = errors.New("resource not found")
// ErrConflict indicates a duplicate username.
ErrConflict = errors.New("username already exists")
// ErrCapacity indicates exhausted storage capacity without eviction.
ErrCapacity = errors.New("in-memory storage capacity reached")
)
+36
View File
@@ -0,0 +1,36 @@
// Package service defines the application operations consumed by HTTP controllers.
package service
import (
"context"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// Service validates raw input and enforces identity and membership requirements.
// Implementations must not expose transport-specific types or storage internals.
type Service interface {
// UsersCreate registers a user or reports invalid input, conflict or capacity exhaustion.
UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error)
// UsersCheckIdentity verifies that an identity belongs to an existing user.
UsersCheckIdentity(ctx context.Context, userID string) error
// UsersGetMe resolves the authenticated caller, rejecting malformed or unknown identifiers.
UsersGetMe(ctx context.Context, userID string) (dto.UserDTO, error)
// ChatsCreate validates all members and creates one chat atomically.
ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error)
// ChatsGetByID hides missing and inaccessible chats behind the same not-found result.
ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error)
// ChatsGetPage lists only chats visible to the caller, using resource-bound cursors.
ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error)
// MessagesCreate derives the sender from the identity and appends validated text.
MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error)
// MessagesGetPage authorizes the caller and returns history after a verified cursor.
MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error)
}
+62
View File
@@ -0,0 +1,62 @@
package production
import (
"context"
"slices"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// parseIdentity maps malformed identity values to the authentication error.
func parseIdentity(rawID string) (uuid.UUID, error) {
id, err := parseID(rawID)
if err != nil {
return uuid.Nil, service.ErrUnauthorized
}
return id, nil
}
// requireUserID resolves an existing identity without loading a user profile.
func (s *Service) requireUserID(ctx context.Context, rawID string) (uuid.UUID, error) {
id, err := parseIdentity(rawID)
if err != nil {
return uuid.Nil, err
}
exists, err := s.repo.UsersExist(ctx, []uuid.UUID{id})
if err != nil {
return uuid.Nil, normalizeStoreError(err)
}
if !exists {
return uuid.Nil, service.ErrUnauthorized
}
return id, nil
}
// requireChatMember resolves an existing caller and a chat available to that caller.
func (s *Service) requireChatMember(ctx context.Context, userID, chatID string) (uuid.UUID, dto.ChatDTO, error) {
caller, err := s.requireUserID(ctx, userID)
if err != nil {
return uuid.Nil, dto.ChatDTO{}, err
}
chat, err := s.findChat(ctx, chatID)
if err != nil {
return uuid.Nil, dto.ChatDTO{}, err
}
if !slices.Contains(chat.MemberIDs, caller) {
return uuid.Nil, dto.ChatDTO{}, service.ErrNotFound
}
return caller, chat, nil
}
// findChat parses a chat identifier and translates storage lookup errors.
func (s *Service) findChat(ctx context.Context, rawID string) (dto.ChatDTO, error) {
id, err := parseID(rawID)
if err != nil {
return dto.ChatDTO{}, err
}
chat, err := s.repo.Chat(ctx, id)
return chat, normalizeStoreError(err)
}
+84
View File
@@ -0,0 +1,84 @@
package production
import (
"context"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
type cacheFixture struct {
profile dto.UserDTO
hit bool
writes int
}
// GetProfile returns the arranged optional-cache lookup outcome.
func (f *cacheFixture) GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool) {
return f.profile, f.hit
}
// PutProfile records successful cache population from authoritative data.
func (f *cacheFixture) PutProfile(_ context.Context, user dto.UserDTO) {
f.profile = user
f.writes++
}
// TestProfileCacheHitAvoidsProfileQuery verifies that the cache has a concrete role.
func TestProfileCacheHitAvoidsProfileQuery(t *testing.T) {
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
cache := &cacheFixture{profile: dto.UserDTO{ID: uuid.New()}, hit: true}
svc, err := NewCached(&storeStub{t: t}, codec, cache)
if err != nil {
t.Fatal(err)
}
got, err := svc.UsersGetMe(t.Context(), cache.profile.ID.String())
if err != nil || got.ID != cache.profile.ID {
t.Fatalf("cache hit ignored: %v", err)
}
}
// TestProfileCacheMissPopulatesAfterDatabaseRead checks the authoritative fallback.
func TestProfileCacheMissPopulatesAfterDatabaseRead(t *testing.T) {
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
id := uuid.New()
repo := &storeStub{t: t, user: func(context.Context, uuid.UUID) (dto.UserDTO, error) {
return dto.UserDTO{ID: id}, nil
}}
cache := &cacheFixture{}
svc, err := NewCached(repo, codec, cache)
if err != nil {
t.Fatal(err)
}
got, err := svc.UsersGetMe(t.Context(), id.String())
if err != nil || got.ID != id || cache.writes != 1 {
t.Fatalf("fallback failed: %v", err)
}
}
// TestCachedServiceRejectsMissingDependencies checks explicit service boundaries.
func TestCachedServiceRejectsMissingDependencies(t *testing.T) {
t.Run("store", func(t *testing.T) {
if _, err := NewCached(nil, nil, &cacheFixture{}); err == nil {
t.Fatal("missing store accepted")
}
})
t.Run("cache", func(t *testing.T) {
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
if _, err := NewCached(&storeStub{t: t}, codec, nil); err == nil {
t.Fatal("missing cache accepted")
}
})
}
+47
View File
@@ -0,0 +1,47 @@
package production
import (
"context"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// ChatsCreate resolves the caller, validates the proposed chat and persists it atomically.
func (s *Service) ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error) {
caller, err := s.requireUserID(ctx, request.UserID)
if err != nil {
return dto.ChatDTO{}, err
}
chat, err := prepareChat(request, caller)
if err != nil {
return dto.ChatDTO{}, err
}
if err := s.requireExistingMembers(ctx, chat.MemberIDs); err != nil {
return dto.ChatDTO{}, err
}
created, err := s.repo.CreateChat(ctx, chat)
return created, normalizeStoreError(err)
}
// ChatsGetByID returns a chat only to a current member, hiding its existence otherwise.
func (s *Service) ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error) {
_, chat, err := s.requireChatMember(ctx, userID, chatID)
return chat, err
}
// ChatsGetPage authorizes the caller, loads a page and prepares its continuation.
func (s *Service) ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error) {
caller, err := s.requireUserID(ctx, request.UserID)
if err != nil {
return dto.ChatPageDTO{}, err
}
page, err := s.parsePage(request, chatListResource(caller))
if err != nil {
return dto.ChatPageDTO{}, err
}
items, err := s.repo.Chats(ctx, caller, page.position, page.fetchLimit())
if err != nil {
return dto.ChatPageDTO{}, normalizeStoreError(err)
}
return s.chatPage(items, page)
}
@@ -0,0 +1,207 @@
package production
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// TestService_ChatsGetPage validates access and pagination before issuing a typed store query.
func TestService_ChatsGetPage(t *testing.T) {
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
records := []dto.ChatDTO{
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
}
calls := 0
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
calls++
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
if id != actor || position != expected || limit != 3 {
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
}
return records, nil
}
svc := newStubService(t, repo)
resource := "chats:" + actor.String()
token, err := svc.cursors.Encode(resource, previous)
if err != nil {
t.Fatal(err)
}
input := dto.PageRequestDTO{UserID: actor.String(), Limit: "2", Cursor: token}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
t.Fatalf("calls=%d, page=%+v", calls, got)
}
position, err := svc.cursors.Decode(*got.NextCursor, resource)
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
if err != nil || position != expected {
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
}
})
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
calls := 0
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
calls++
if id != actor || position != (dto.PositionDTO{}) || limit != 51 {
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
}
return []dto.ChatDTO{}, nil
}
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String()}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("calls=%d, page=%+v", calls, got)
}
})
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
svc := newStubService(t, repo)
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
if err != nil {
t.Fatal(err)
}
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: token}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
failure := errors.New("cursor unavailable")
svc := newStubService(t, repo)
svc.cursors = failingCursor{failure: failure}
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: "token"}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: page storage fails", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
failure := errors.New("page unavailable")
repo.chats = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.ChatDTO, error) {
return nil, failure
}
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String()}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
}
// TestService_ChatsGetPage_InvalidLimit rejects invalid limits before reading stored pages.
func TestService_ChatsGetPage_InvalidLimit(t *testing.T) {
cases := []struct {
name string
limit string
}{
{"Negative: zero limit", "0"},
{"Negative: negative limit", "-1"},
{"Negative: limit above maximum", "101"},
{"Negative: nonnumeric limit", "text"},
{"Negative: fractional limit", "1.5"},
{"Negative: integer overflow", "99999999999999999999999999"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String(), Limit: tc.limit}
// Act.
got, err := svc.ChatsGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
}
}
+261
View File
@@ -0,0 +1,261 @@
package production
import (
"context"
"errors"
"reflect"
"slices"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// TestService_ChatsCreate checks membership in one batch and persists only validated chats.
func TestService_ChatsCreate(t *testing.T) {
t.Run("Positive: one membership query and original chat fields", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor, other := uuid.New(), uuid.New()
var queries [][]uuid.UUID
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
queries = append(queries, slices.Clone(ids))
return true, nil
}
var persisted dto.ChatDTO
repo.createChat = func(_ context.Context, input dto.ChatDTO) (dto.ChatDTO, error) {
persisted = input
input.CreatedAt = time.Unix(1700000000, 0).UTC()
return input, nil
}
svc := newStubService(t, repo)
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: " Team 👋 ", MemberIDs: []string{actor.String(), other.String()}}
// Act.
got, err := svc.ChatsCreate(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(queries, [][]uuid.UUID{{actor}, {actor, other}}) {
t.Fatalf("existence queries=%v", queries)
}
if persisted.ID == uuid.Nil || persisted.Title != input.Title || !slices.Equal(persisted.MemberIDs, []uuid.UUID{actor, other}) {
t.Fatalf("wrong persistence input: %+v", persisted)
}
if got.ID != persisted.ID || got.CreatedAt.IsZero() || got.Title != input.Title || !slices.Equal(got.MemberIDs, persisted.MemberIDs) {
t.Fatalf("wrong returned chat: %+v", got)
}
})
t.Run("Negative: unknown member prevents persistence", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor, missing := uuid.New(), uuid.New()
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
return !slices.Contains(ids, missing), nil
}
svc := newStubService(t, repo)
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), missing.String()}}
// Act.
got, err := svc.ChatsCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
t.Run("Negative: membership lookup failure prevents persistence", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor, other := uuid.New(), uuid.New()
failure := errors.New("membership unavailable")
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
if len(ids) == 1 {
return true, nil
}
return false, failure
}
svc := newStubService(t, repo)
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), other.String()}}
// Act.
got, err := svc.ChatsCreate(t.Context(), input)
// Assert.
if !errors.Is(err, failure) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
t.Run("Negative: unknown creator prevents membership and persistence calls", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
repo.usersExist = func(_ context.Context, _ []uuid.UUID) (bool, error) {
return false, nil
}
svc := newStubService(t, repo)
actor := uuid.New()
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String()}}
// Act.
got, err := svc.ChatsCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
// TestService_ChatsCreate_InvalidInput rejects malformed chat fields before checking member existence.
func TestService_ChatsCreate_InvalidInput(t *testing.T) {
actor := uuid.New()
cases := []struct {
name string
title string
members []string
}{
{"Negative: empty member set", "Team", nil},
{"Negative: duplicate member", "Team", []string{actor.String(), actor.String()}},
{"Negative: caller omitted", "Team", []string{uuid.NewString()}},
{"Negative: malformed member ID", "Team", []string{actor.String(), "invalid"}},
{"Negative: blank title", " ", []string{actor.String()}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
calls := 0
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
calls++
if calls != 1 || !slices.Equal(ids, []uuid.UUID{actor}) {
t.Fatalf("unexpected membership check: %v", ids)
}
return true, nil
}
svc := newStubService(t, repo)
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: tc.title, MemberIDs: tc.members}
// Act.
got, err := svc.ChatsCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
if calls != 1 {
t.Fatalf("identity checks=%d, want=1", calls)
}
})
}
}
// TestService_ChatsGetByID authorizes the requested chat and conceals inaccessible records.
func TestService_ChatsGetByID(t *testing.T) {
t.Run("Positive: member receives the complete chat", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
expected := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{actor}, CreatedAt: time.Unix(1700000000, 0).UTC()}
allowChatAccess(repo, actor, expected)
svc := newStubService(t, repo)
// Act.
got, err := svc.ChatsGetByID(t.Context(), actor.String(), expected.ID.String())
// Assert.
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got, expected) {
t.Fatalf("chat=%+v, want=%+v", got, expected)
}
})
t.Run("Negative: outsider receives no chat details", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), Title: "Private", MemberIDs: []uuid.UUID{uuid.New()}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
// Act.
got, err := svc.ChatsGetByID(t.Context(), actor.String(), chat.ID.String())
// Assert.
if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("private chat exposed: %+v, error=%v", got, err)
}
})
t.Run("Negative: malformed chat ID skips chat lookup", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
svc := newStubService(t, repo)
// Act.
got, err := svc.ChatsGetByID(t.Context(), actor.String(), "invalid")
// Assert.
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
// Act.
got, err := svc.ChatsGetByID(t.Context(), "invalid", uuid.NewString())
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
// TestService_ChatsGetByID_StoreErrors translates missing records and retains unexpected failures.
func TestService_ChatsGetByID_StoreErrors(t *testing.T) {
failure := errors.New("chat lookup unavailable")
cases := []struct {
name string
cause error
want error
}{
{"Negative: absent chat", store.ErrNotFound, service.ErrNotFound},
{"Negative: storage unavailable", failure, failure},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
allowIdentity(repo, actor)
repo.chat = func(_ context.Context, _ uuid.UUID) (dto.ChatDTO, error) {
return dto.ChatDTO{}, tc.cause
}
svc := newStubService(t, repo)
// Act.
got, err := svc.ChatsGetByID(t.Context(), actor.String(), uuid.NewString())
// Assert.
if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
}
})
}
}
+75
View File
@@ -0,0 +1,75 @@
package production
import (
"strings"
"unicode/utf8"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// PrepareUser validates registration fields and assigns the new user identifier.
func PrepareUser(request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
if !validUsername(request.Username) || !validText(request.DisplayName, maxDisplayNameRunes) {
return dto.UserDTO{}, service.ErrInvalid
}
return dto.UserDTO{
ID: uuid.New(),
Username: request.Username,
DisplayName: request.DisplayName,
}, nil
}
// prepareChat validates the title and member identifiers before storage access.
func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatDTO, error) {
if !validText(request.Title, maxChatTitleRunes) {
return dto.ChatDTO{}, service.ErrInvalid
}
members, err := parseMembers(request.MemberIDs, caller)
if err != nil {
return dto.ChatDTO{}, err
}
return dto.ChatDTO{
ID: uuid.New(),
Title: request.Title,
MemberIDs: members,
}, nil
}
// prepareMessage validates text and creates a record for the authorized sender and chat.
func prepareMessage(request dto.MessagesCreateRequestDTO, sender, chatID uuid.UUID) (dto.MessageDTO, error) {
if (strings.TrimSpace(request.Text) == "" && len(request.AttachmentIDs) == 0) || !utf8.ValidString(request.Text) || utf8.RuneCountInString(request.Text) > maxMessageRunes || len(request.AttachmentIDs) > 10 || !validIdempotencyKey(request.IdempotencyKey) {
return dto.MessageDTO{}, service.ErrInvalid
}
seen := make(map[string]bool)
for _, id := range request.AttachmentIDs {
if _, err := parseID(id); err != nil || seen[id] {
return dto.MessageDTO{}, service.ErrInvalid
}
seen[id] = true
}
return dto.MessageDTO{
ID: uuid.New(),
ChatID: chatID,
SenderID: sender,
Text: request.Text,
AttachmentIDs: append([]string{}, request.AttachmentIDs...),
IdempotencyKey: request.IdempotencyKey,
}, nil
}
// validIdempotencyKey accepts only the bounded ASCII alphabet from the contract.
func validIdempotencyKey(key string) bool {
if len(key) < 1 || len(key) > 128 {
return false
}
for _, c := range key {
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == ':' || c == '-' {
continue
}
return false
}
return true
}
+23
View File
@@ -0,0 +1,23 @@
package production
import (
"errors"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// normalizeStoreError maps expected storage failures to application errors.
// Unexpected failures retain their cause for the transport's safe fallback.
func normalizeStoreError(err error) error {
switch {
case errors.Is(err, store.ErrNotFound):
return service.ErrNotFound
case errors.Is(err, store.ErrConflict):
return service.ErrConflict
case errors.Is(err, store.ErrCapacity):
return service.ErrCapacity
default:
return err
}
}
+147
View File
@@ -0,0 +1,147 @@
package production
import (
"context"
"testing"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// storeStub permits only the interactions explicitly arranged by each service scenario.
type storeStub struct {
t *testing.T
createUser func(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error)
user func(ctx context.Context, id uuid.UUID) (dto.UserDTO, error)
usersExist func(ctx context.Context, ids []uuid.UUID) (bool, error)
createChat func(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error)
chat func(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error)
chats func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error)
createMessage func(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error)
messages func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error)
}
// CreateUser delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
repo.t.Helper()
if repo.createUser == nil {
repo.t.Fatalf("unexpected store.CreateUser call")
return dto.UserDTO{}, nil
}
return repo.createUser(ctx, user)
}
// User delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
repo.t.Helper()
if repo.user == nil {
repo.t.Fatalf("unexpected store.User call")
return dto.UserDTO{}, nil
}
return repo.user(ctx, id)
}
// UsersExist delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
repo.t.Helper()
if repo.usersExist == nil {
repo.t.Fatalf("unexpected store.UsersExist call")
return false, nil
}
return repo.usersExist(ctx, ids)
}
// CreateChat delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
repo.t.Helper()
if repo.createChat == nil {
repo.t.Fatalf("unexpected store.CreateChat call")
return dto.ChatDTO{}, nil
}
return repo.createChat(ctx, chat)
}
// Chat delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
repo.t.Helper()
if repo.chat == nil {
repo.t.Fatalf("unexpected store.Chat call")
return dto.ChatDTO{}, nil
}
return repo.chat(ctx, id)
}
// Chats delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) Chats(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
repo.t.Helper()
if repo.chats == nil {
repo.t.Fatalf("unexpected store.Chats call")
return nil, nil
}
return repo.chats(ctx, id, position, limit)
}
// CreateMessage delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
repo.t.Helper()
if repo.createMessage == nil {
repo.t.Fatalf("unexpected store.CreateMessage call")
return dto.MessageDTO{}, nil
}
return repo.createMessage(ctx, message)
}
// Messages delegates to the arranged behavior and rejects unexpected storage access.
func (repo *storeStub) Messages(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
repo.t.Helper()
if repo.messages == nil {
repo.t.Fatalf("unexpected store.Messages call")
return nil, nil
}
return repo.messages(ctx, id, position, limit)
}
// newStoreStub creates a repository that fails on every unarranged interaction.
func newStoreStub(t *testing.T) *storeStub {
t.Helper()
return &storeStub{t: t}
}
// newStubService composes the service with controlled storage and a real cursor codec.
func newStubService(t *testing.T, repo *storeStub) *Service {
t.Helper()
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
svc, err := New(repo, codec)
if err != nil {
t.Fatal(err)
}
return svc
}
// allowIdentity permits exactly the arranged actor's existence lookup, never a profile read.
func allowIdentity(repo *storeStub, actor uuid.UUID) {
repo.t.Helper()
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
if len(ids) != 1 || ids[0] != actor {
repo.t.Fatalf("unexpected identity query: %v", ids)
}
return true, nil
}
}
// allowChatAccess supplies a typed chat after checking the lookup key at the service boundary.
func allowChatAccess(repo *storeStub, actor uuid.UUID, chat dto.ChatDTO) {
repo.t.Helper()
allowIdentity(repo, actor)
repo.chat = func(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) {
if id != chat.ID {
repo.t.Fatalf("chat queried for %s, want %s", id, chat.ID)
}
return chat, nil
}
}
+42
View File
@@ -0,0 +1,42 @@
package production
import (
"context"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// parseMembers validates unique member identifiers and requires the caller to be included.
func parseMembers(rawIDs []string, caller uuid.UUID) ([]uuid.UUID, error) {
if len(rawIDs) == 0 || len(rawIDs) > maxChatMembers {
return nil, service.ErrInvalid
}
members := make([]uuid.UUID, 0, len(rawIDs))
seen := make(map[uuid.UUID]bool, len(rawIDs))
for _, rawID := range rawIDs {
id, err := parseID(rawID)
if err != nil || seen[id] {
return nil, service.ErrInvalid
}
seen[id] = true
members = append(members, id)
}
if !seen[caller] {
return nil, service.ErrInvalid
}
return members, nil
}
// requireExistingMembers validates the complete membership set with one storage operation.
func (s *Service) requireExistingMembers(ctx context.Context, members []uuid.UUID) error {
exists, err := s.repo.UsersExist(ctx, members)
if err != nil {
return normalizeStoreError(err)
}
if !exists {
return service.ErrInvalid
}
return nil
}
+38
View File
@@ -0,0 +1,38 @@
package production
import (
"context"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// MessagesCreate authorizes the sender, validates the message and stores it atomically.
func (s *Service) MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error) {
caller, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
if err != nil {
return dto.MessageDTO{}, err
}
message, err := prepareMessage(request, caller, chat.ID)
if err != nil {
return dto.MessageDTO{}, err
}
created, err := s.repo.CreateMessage(ctx, message)
return created, normalizeStoreError(err)
}
// MessagesGetPage authorizes access, loads history and prepares its continuation.
func (s *Service) MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error) {
_, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
if err != nil {
return dto.MessagePageDTO{}, err
}
page, err := s.parsePage(request, messageHistoryResource(chat.ID))
if err != nil {
return dto.MessagePageDTO{}, err
}
items, err := s.repo.Messages(ctx, chat.ID, page.position, page.fetchLimit())
if err != nil {
return dto.MessagePageDTO{}, normalizeStoreError(err)
}
return s.messagePage(items, page)
}
@@ -0,0 +1,231 @@
package production
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// TestService_MessagesGetPage validates access and pagination before issuing a typed store query.
func TestService_MessagesGetPage(t *testing.T) {
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
records := []dto.MessageDTO{
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
}
calls := 0
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
calls++
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
if id != chat.ID || position != expected || limit != 3 {
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
}
return records, nil
}
svc := newStubService(t, repo)
resource := "messages:" + chat.ID.String()
token, err := svc.cursors.Encode(resource, previous)
if err != nil {
t.Fatal(err)
}
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: "2", Cursor: token}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
t.Fatalf("calls=%d, page=%+v", calls, got)
}
position, err := svc.cursors.Decode(*got.NextCursor, resource)
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
if err != nil || position != expected {
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
}
})
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
calls := 0
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
calls++
if id != chat.ID || position != (dto.PositionDTO{}) || limit != 51 {
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
}
return []dto.MessageDTO{}, nil
}
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("calls=%d, page=%+v", calls, got)
}
})
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
if err != nil {
t.Fatal(err)
}
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: token}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
failure := errors.New("cursor unavailable")
svc := newStubService(t, repo)
svc.cursors = failingCursor{failure: failure}
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: "token"}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: page storage fails", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
failure := errors.New("page unavailable")
repo.messages = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.MessageDTO, error) {
return nil, failure
}
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
t.Run("Negative: outsider cannot read message history", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrNotFound) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
}
// TestService_MessagesGetPage_InvalidLimit rejects invalid limits before reading stored pages.
func TestService_MessagesGetPage_InvalidLimit(t *testing.T) {
cases := []struct {
name string
limit string
}{
{"Negative: zero limit", "0"},
{"Negative: negative limit", "-1"},
{"Negative: limit above maximum", "101"},
{"Negative: nonnumeric limit", "text"},
{"Negative: fractional limit", "1.5"},
{"Negative: integer overflow", "99999999999999999999999999"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: tc.limit}
// Act.
got, err := svc.MessagesGetPage(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
t.Fatalf("page=%+v, error=%v", got, err)
}
})
}
}
@@ -0,0 +1,170 @@
package production
import (
"context"
"errors"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// TestService_MessagesCreate authorizes the sender before validating and persisting the message.
func TestService_MessagesCreate(t *testing.T) {
t.Run("Positive: authenticated sender and original text persisted", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
var persisted dto.MessageDTO
repo.createMessage = func(_ context.Context, input dto.MessageDTO) (dto.MessageDTO, error) {
persisted = input
input.CreatedAt = time.Unix(1700000000, 0).UTC()
return input, nil
}
svc := newStubService(t, repo)
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "}
// Act.
got, err := svc.MessagesCreate(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if persisted.ID == uuid.Nil || persisted.SenderID != actor || persisted.ChatID != chat.ID || persisted.Text != input.Text {
t.Fatalf("wrong persistence input: %+v", persisted)
}
if got.ID != persisted.ID || got.SenderID != actor || got.ChatID != chat.ID || got.Text != input.Text || got.CreatedAt.IsZero() {
t.Fatalf("wrong acknowledgement: %+v", got)
}
})
t.Run("Negative: outsider cannot persist messages", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
// Act.
got, err := svc.MessagesCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: "invalid", ChatID: uuid.NewString(), Text: "text"}
// Act.
got, err := svc.MessagesCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
// TestService_MessagesCreate_InvalidText refuses invalid text without attempting persistence.
func TestService_MessagesCreate_InvalidText(t *testing.T) {
cases := []struct {
name string
text string
}{
{"Negative: empty text", ""},
{"Negative: whitespace only", " \t"},
{"Negative: rune limit exceeded", strings.Repeat("界", 4001)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
svc := newStubService(t, repo)
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text}
// Act.
got, err := svc.MessagesCreate(t.Context(), input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
}
// TestService_MessagesCreate_StoreErrors propagates persistence failures without acknowledging a record.
func TestService_MessagesCreate_StoreErrors(t *testing.T) {
failure := errors.New("write unavailable")
cases := []struct {
name string
cause error
want error
}{
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
{"Negative: chat disappeared", store.ErrNotFound, service.ErrNotFound},
{"Negative: unexpected write failure", failure, failure},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
actor := uuid.New()
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
allowChatAccess(repo, actor, chat)
repo.createMessage = func(_ context.Context, _ dto.MessageDTO) (dto.MessageDTO, error) {
return dto.MessageDTO{}, tc.cause
}
svc := newStubService(t, repo)
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
// Act.
got, err := svc.MessagesCreate(t.Context(), input)
// Assert.
if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
}
})
}
}
// TestIdempotencyKeyValidation checks the exact contract alphabet and length independently.
func TestIdempotencyKeyValidation(t *testing.T) {
for _, test := range []struct {
name string
key string
want bool
}{
{name: "missing", key: "", want: false},
{name: "allowed alphabet", key: "aZ09._:-", want: true},
{name: "space", key: "a b", want: false},
{name: "unicode", key: "ключ", want: false},
{name: "maximum", key: strings.Repeat("a", 128), want: true},
{name: "too long", key: strings.Repeat("a", 129), want: false},
} {
t.Run(test.name, func(t *testing.T) {
if got := validIdempotencyKey(test.key); got != test.want {
t.Fatalf("valid=%v want=%v", got, test.want)
}
})
}
}
+49
View File
@@ -0,0 +1,49 @@
package production
import (
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// chatPage adapts the shared page result to the chat response DTO.
func (s *Service) chatPage(items []dto.ChatDTO, page pagination) (dto.ChatPageDTO, error) {
items, next, err := buildPage(items, page, s.cursors, chatPosition)
if err != nil {
return dto.ChatPageDTO{}, err
}
return dto.ChatPageDTO{Items: items, NextCursor: next}, nil
}
// messagePage adapts the shared page result to the message response DTO.
func (s *Service) messagePage(items []dto.MessageDTO, page pagination) (dto.MessagePageDTO, error) {
items, next, err := buildPage(items, page, s.cursors, messagePosition)
if err != nil {
return dto.MessagePageDTO{}, err
}
return dto.MessagePageDTO{Items: items, NextCursor: next}, nil
}
// buildPage trims lookahead and signs the last returned record when more data exists.
// The page limit must be validated before calling this helper.
func buildPage[T any](items []T, page pagination, codec service.CursorCodec, position func(T) cursor.Position) ([]T, *string, error) {
if len(items) <= page.limit {
return items, nil, nil
}
items = items[:page.limit]
next, err := codec.Encode(page.resource, position(items[len(items)-1]))
if err != nil {
return nil, nil, err
}
return items, new(next), nil
}
// chatPosition extracts the stable pagination boundary from a stored chat.
func chatPosition(chat dto.ChatDTO) cursor.Position {
return cursor.Position{CreatedAt: chat.CreatedAt, ID: chat.ID}
}
// messagePosition extracts the stable pagination boundary from a stored message.
func messagePosition(message dto.MessageDTO) cursor.Position {
return cursor.Position{CreatedAt: message.CreatedAt, ID: message.ID}
}
+53
View File
@@ -0,0 +1,53 @@
package production
import (
"reflect"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
// TestService_messagePage checks boundaries and signs the last returned item, not lookahead.
func TestService_messagePage(t *testing.T) {
for _, count := range []int{0, 2, 3} {
names := map[int]string{0: "Positive: empty page", 2: "Positive: exact limit is final", 3: "Positive: lookahead creates continuation"}
t.Run(names[count], func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
items := make([]dto.MessageDTO, count)
for i := range items {
items[i] = dto.MessageDTO{ID: uuid.New(), Text: "message", CreatedAt: time.Unix(int64(i+1), 0).UTC()}
}
expected := items[:min(count, 2)]
// Act.
page, err := svc.messagePage(items, pagination{limit: 2, resource: "messages:chat"})
// Assert.
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(page.Items, expected) {
t.Fatalf("page=%v, want=%v", page.Items, expected)
}
if count <= 2 {
if page.NextCursor != nil {
t.Fatal("final page has a continuation")
}
return
}
if page.NextCursor == nil {
t.Fatal("lookahead did not produce continuation")
}
decoded, err := svc.cursors.Decode(*page.NextCursor, "messages:chat")
want := cursor.Position{ID: items[1].ID, CreatedAt: items[1].CreatedAt}
if err != nil || decoded != want {
t.Fatalf("cursor=%v, want=%v, error=%v", decoded, want, err)
}
})
}
}
+78
View File
@@ -0,0 +1,78 @@
package production
import (
"errors"
"strconv"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
const (
defaultPageLimit = 50
maxPageLimit = 100
// Fetching one extra record determines whether to issue a next cursor.
pageLookahead = 1
)
type pagination struct {
position dto.PositionDTO
limit int
resource string
}
// parsePage validates the page size and resource-bound cursor.
func (s *Service) parsePage(request dto.PageRequestDTO, resource string) (pagination, error) {
limit, err := parseLimit(request.Limit)
if err != nil {
return pagination{}, err
}
position, err := s.cursors.Decode(request.Cursor, resource)
if errors.Is(err, cursor.ErrInvalid) {
return pagination{}, service.ErrInvalid
}
if err != nil {
return pagination{}, err
}
return pagination{
position: dto.PositionDTO{CreatedAt: position.CreatedAt, ID: position.ID},
limit: limit,
resource: resource,
}, nil
}
// parseLimit parses a bounded page size or supplies the default.
func parseLimit(raw string) (int, error) {
if raw == "" {
return defaultPageLimit, nil
}
for _, char := range raw {
if char < '0' || char > '9' {
return 0, service.ErrInvalid
}
}
limit, err := strconv.Atoi(raw)
if err != nil || limit < 1 || limit > maxPageLimit {
return 0, service.ErrInvalid
}
return limit, nil
}
// fetchLimit includes one lookahead record to detect a following page.
func (page pagination) fetchLimit() int {
return page.limit + pageLookahead
}
// chatListResource scopes a cursor to one user's visible chats.
func chatListResource(userID uuid.UUID) string {
return "chats:" + userID.String()
}
// messageHistoryResource scopes a cursor to one chat's message history.
func messageHistoryResource(chatID uuid.UUID) string {
return "messages:" + chatID.String()
}
@@ -0,0 +1,74 @@
package production
import (
"errors"
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
type failingCursor struct {
failure error
}
// Encode injects a signing failure at the service dependency boundary.
func (codec failingCursor) Encode(_ string, _ cursor.Position) (string, error) {
return "", codec.failure
}
// Decode injects a verification failure at the service dependency boundary.
func (codec failingCursor) Decode(_, _ string) (cursor.Position, error) {
return cursor.Position{}, codec.failure
}
// TestService_parsePage translates invalid tokens while retaining unexpected dependency failures.
func TestService_parsePage(t *testing.T) {
failure := errors.New("codec unavailable")
cases := []struct {
name string
cause error
want error
}{
{"Negative: invalid token", cursor.ErrInvalid, service.ErrInvalid},
{"Negative: unavailable codec", failure, failure},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
svc := &Service{cursors: failingCursor{failure: tc.cause}}
input := dto.PageRequestDTO{Cursor: "supplied-token"}
// Act.
page, err := svc.parsePage(input, "messages:chat")
// Assert.
if !errors.Is(err, tc.want) {
t.Fatalf("error=%v, want=%v", err, tc.want)
}
if page != (pagination{}) {
t.Fatalf("failed cursor produced a page: %+v", page)
}
})
}
}
// TestService_messagePage_EncodeFailure returns no partial page when signing fails.
func TestService_messagePage_EncodeFailure(t *testing.T) {
// Arrange.
failure := errors.New("signing unavailable")
svc := &Service{cursors: failingCursor{failure: failure}}
items := []dto.MessageDTO{{Text: "first"}, {Text: "lookahead"}}
// Act.
page, err := svc.messagePage(items, pagination{limit: 1, resource: "messages:chat"})
// Assert.
if !errors.Is(err, failure) {
t.Fatalf("lost signing failure: %v", err)
}
if page.Items != nil || page.NextCursor != nil {
t.Fatalf("partial page escaped: %+v", page)
}
}
+39
View File
@@ -0,0 +1,39 @@
// Package production implements the messenger application operations.
package production
import (
"fmt"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// Service orchestrates operations through storage and cursor interfaces.
type Service struct {
repo store.Interface
cursors service.CursorCodec
cache service.ProfileCache
}
var _ service.Service = (*Service)(nil)
// New creates an application service using explicitly supplied dependencies.
func New(repo store.Interface, cursors service.CursorCodec) (*Service, error) {
if repo == nil || cursors == nil {
return nil, fmt.Errorf("store and cursor codec are required")
}
return &Service{repo: repo, cursors: cursors}, nil
}
// NewCached builds the business service with optional immutable-profile caching.
func NewCached(repo store.Interface, cursors service.CursorCodec, cache service.ProfileCache) (*Service, error) {
instance, err := New(repo, cursors)
if err != nil {
return nil, err
}
if cache == nil {
return nil, fmt.Errorf("profile cache is required")
}
instance.cache = cache
return instance, nil
}
@@ -0,0 +1,39 @@
package production
import (
"testing"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/cursor"
)
// TestService_New rejects each missing dependency separately.
func TestService_New(t *testing.T) {
t.Run("Negative: missing store", func(t *testing.T) {
// Arrange.
codec, err := cursor.New()
if err != nil {
t.Fatal(err)
}
// Act.
svc, err := New(nil, codec)
// Assert.
if err == nil || svc != nil {
t.Fatalf("service=%v, error=%v", svc, err)
}
})
t.Run("Negative: missing codec", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
// Act.
svc, err := New(repo, nil)
// Assert.
if err == nil || svc != nil {
t.Fatalf("service=%v, error=%v", svc, err)
}
})
}
+47
View File
@@ -0,0 +1,47 @@
package production
import (
"context"
"errors"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// UsersCreate validates registration and atomically reserves the unique username.
func (s *Service) UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
user, err := PrepareUser(request)
if err != nil {
return dto.UserDTO{}, err
}
created, err := s.repo.CreateUser(ctx, user)
return created, normalizeStoreError(err)
}
// UsersGetMe loads the current user's profile; malformed and missing identities are unauthorized.
func (s *Service) UsersGetMe(ctx context.Context, rawID string) (dto.UserDTO, error) {
id, err := parseIdentity(rawID)
if err != nil {
return dto.UserDTO{}, err
}
if s.cache != nil {
if cached, ok := s.cache.GetProfile(ctx, id); ok {
return cached, nil
}
}
user, err := s.repo.User(ctx, id)
if errors.Is(err, store.ErrNotFound) {
return dto.UserDTO{}, service.ErrUnauthorized
}
if err == nil && s.cache != nil {
s.cache.PutProfile(ctx, user)
}
return user, normalizeStoreError(err)
}
// UsersCheckIdentity validates the current identity without loading its profile.
func (s *Service) UsersCheckIdentity(ctx context.Context, rawID string) error {
_, err := s.requireUserID(ctx, rawID)
return err
}
+289
View File
@@ -0,0 +1,289 @@
package production
import (
"context"
"errors"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/store"
)
// TestService_UsersCreate validates registration before persistence and preserves storage failures.
func TestService_UsersCreate(t *testing.T) {
t.Run("Positive: validates and persists the original profile", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
expected := dto.UserDTO{Username: "alice", DisplayName: "Алиса 👋", CreatedAt: time.Unix(1700000000, 0).UTC()}
calls := 0
repo.createUser = func(_ context.Context, input dto.UserDTO) (dto.UserDTO, error) {
calls++
if input.ID == uuid.Nil || input.Username != expected.Username || input.DisplayName != expected.DisplayName {
t.Fatalf("wrong persistence input: %+v", input)
}
expected.ID = input.ID
return expected, nil
}
svc := newStubService(t, repo)
input := dto.UsersCreateRequestDTO{Username: expected.Username, DisplayName: expected.DisplayName}
// Act.
got, err := svc.UsersCreate(t.Context(), input)
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || got != expected {
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
}
})
}
// TestService_UsersCreate_InvalidInput refuses malformed registrations without calling storage.
func TestService_UsersCreate_InvalidInput(t *testing.T) {
cases := []struct {
name string
input dto.UsersCreateRequestDTO
}{
{"Negative: short username", dto.UsersCreateRequestDTO{Username: "a", DisplayName: "Alice"}},
{"Negative: uppercase username", dto.UsersCreateRequestDTO{Username: "Alice", DisplayName: "Alice"}},
{"Negative: blank display name", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: " "}},
{"Negative: display name exceeds rune limit", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: strings.Repeat("界", 101)}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange: every store method fails immediately if called.
svc := newStubService(t, newStoreStub(t))
// Act.
got, err := svc.UsersCreate(t.Context(), tc.input)
// Assert.
if !errors.Is(err, service.ErrInvalid) || got != (dto.UserDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
}
// TestService_UsersCreate_StoreErrors preserves the application meaning of persistence failures.
func TestService_UsersCreate_StoreErrors(t *testing.T) {
unexpected := errors.New("storage unavailable")
cases := []struct {
name string
cause error
want error
}{
{"Negative: duplicate username", store.ErrConflict, service.ErrConflict},
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
{"Negative: unexpected failure", unexpected, unexpected},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
repo.createUser = func(_ context.Context, _ dto.UserDTO) (dto.UserDTO, error) {
return dto.UserDTO{}, tc.cause
}
svc := newStubService(t, repo)
// Act.
got, err := svc.UsersCreate(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"})
// Assert.
if !errors.Is(err, tc.want) || got != (dto.UserDTO{}) {
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
}
})
}
}
// TestService_UsersGetMe loads only the requested profile and hides unknown identities.
func TestService_UsersGetMe(t *testing.T) {
t.Run("Positive: returns stored profile", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
expected := dto.UserDTO{ID: uuid.New(), Username: "alice", DisplayName: "Alice", CreatedAt: time.Unix(1700000000, 0).UTC()}
calls := 0
repo.user = func(_ context.Context, id uuid.UUID) (dto.UserDTO, error) {
calls++
if id != expected.ID {
t.Fatalf("profile queried for %s instead of %s", id, expected.ID)
}
return expected, nil
}
svc := newStubService(t, repo)
// Act.
got, err := svc.UsersGetMe(t.Context(), expected.ID.String())
// Assert.
if err != nil {
t.Fatal(err)
}
if calls != 1 || got != expected {
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
}
})
t.Run("Negative: unknown identity", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
return dto.UserDTO{}, store.ErrNotFound
}
svc := newStubService(t, repo)
wantErr := service.ErrUnauthorized
// Act.
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
// Assert.
if !errors.Is(err, wantErr) {
t.Fatalf("error=%v, want=%v", err, wantErr)
}
if got != (dto.UserDTO{}) {
t.Fatalf("failed operation returned a profile: %+v", got)
}
})
t.Run("Negative: storage failure preserved", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
wantErr := errors.New("profile unavailable")
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
return dto.UserDTO{}, wantErr
}
svc := newStubService(t, repo)
// Act.
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
// Assert.
if !errors.Is(err, wantErr) {
t.Fatalf("error=%v, want=%v", err, wantErr)
}
if got != (dto.UserDTO{}) {
t.Fatalf("failed operation returned a profile: %+v", got)
}
})
}
// TestService_UsersGetMe_InvalidIdentity rejects malformed identifiers before any store call.
func TestService_UsersGetMe_InvalidIdentity(t *testing.T) {
cases := []struct {
name string
raw string
}{
{"Negative: missing header", ""},
{"Negative: short ID", "invalid"},
{"Negative: non-UUID characters", strings.Repeat("z", 36)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
// Act.
got, err := svc.UsersGetMe(t.Context(), tc.raw)
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || got != (dto.UserDTO{}) {
t.Fatalf("result=%+v, error=%v", got, err)
}
})
}
}
// TestService_UsersCheckIdentity uses the existence query and never loads a profile.
func TestService_UsersCheckIdentity(t *testing.T) {
t.Run("Positive: existence check without profile loading", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
id := uuid.New()
calls := 0
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
calls++
if !slices.Equal(ids, []uuid.UUID{id}) {
t.Fatalf("queried IDs=%v", ids)
}
return true, nil
}
svc := newStubService(t, repo)
// Act.
err := svc.UsersCheckIdentity(t.Context(), id.String())
// Assert.
if !errors.Is(err, nil) || calls != 1 {
t.Fatalf("calls=%d, error=%v", calls, err)
}
})
t.Run("Negative: identity does not exist", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
id := uuid.New()
calls := 0
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
calls++
if !slices.Equal(ids, []uuid.UUID{id}) {
t.Fatalf("queried IDs=%v", ids)
}
return false, nil
}
svc := newStubService(t, repo)
// Act.
err := svc.UsersCheckIdentity(t.Context(), id.String())
// Assert.
if !errors.Is(err, service.ErrUnauthorized) || calls != 1 {
t.Fatalf("calls=%d, error=%v", calls, err)
}
})
t.Run("Negative: existence lookup fails", func(t *testing.T) {
// Arrange.
repo := newStoreStub(t)
id := uuid.New()
calls := 0
failure := errors.New("identity unavailable")
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
calls++
if !slices.Equal(ids, []uuid.UUID{id}) {
t.Fatalf("queried IDs=%v", ids)
}
return false, failure
}
svc := newStubService(t, repo)
// Act.
err := svc.UsersCheckIdentity(t.Context(), id.String())
// Assert.
if !errors.Is(err, failure) || calls != 1 {
t.Fatalf("calls=%d, error=%v", calls, err)
}
})
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
// Arrange.
svc := newStubService(t, newStoreStub(t))
// Act.
err := svc.UsersCheckIdentity(t.Context(), "invalid")
// Assert.
if !errors.Is(err, service.ErrUnauthorized) {
t.Fatalf("error=%v", err)
}
})
}
+51
View File
@@ -0,0 +1,51 @@
package production
import (
"strings"
"unicode/utf8"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/service"
)
// These bounds come from the mandatory lab1 OpenAPI schema.
const (
minUsernameLength = 3
maxUsernameLength = 32
maxDisplayNameRunes = 100
maxChatTitleRunes = 100
maxChatMembers = 100
maxMessageRunes = 4000
canonicalUUIDLength = len("00000000-0000-0000-0000-000000000000")
)
// validText checks that text is nonblank and within its Unicode length limit.
func validText(value string, maxRunes int) bool {
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
}
// validUsername checks the username length and permitted ASCII characters.
func validUsername(value string) bool {
if len(value) < minUsernameLength || len(value) > maxUsernameLength {
return false
}
for _, char := range value {
if (char < 'a' || char > 'z') && (char < '0' || char > '9') && char != '_' {
return false
}
}
return true
}
// parseID parses a canonical UUID or returns a validation error.
func parseID(value string) (uuid.UUID, error) {
if len(value) != canonicalUUIDLength {
return uuid.Nil, service.ErrInvalid
}
id, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, service.ErrInvalid
}
return id, nil
}
+54
View File
@@ -0,0 +1,54 @@
// Package store defines typed persistence operations and storage errors.
package store
import (
"context"
"errors"
"github.com/google/uuid"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
)
var (
// ErrUnavailable means a required storage dependency cannot serve the operation.
ErrUnavailable = errors.New("storage unavailable")
// ErrNotFound means a record does not exist.
ErrNotFound = errors.New("record not found")
// ErrConflict means a unique constraint failed.
ErrConflict = errors.New("record already exists")
// ErrCapacity means the bounded store cannot accept more data.
ErrCapacity = errors.New("storage capacity reached")
)
// Interface defines persistence operations on validated typed records.
// Implementations own atomicity, unique constraints and storage capacity, but not
// authorization. Callers must validate membership before accessing chat records.
type Interface interface {
// CreateUser atomically enforces username uniqueness and assigns CreatedAt.
CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error)
// User returns a user by ID or ErrNotFound.
User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error)
// UsersExist reports whether every supplied ID exists; an empty set returns true.
UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error)
// CreateChat atomically stores a chat and its member indexes, assigning CreatedAt.
CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error)
// Chat returns a defensive copy of the stored chat or ErrNotFound.
Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error)
// Chats reads up to limit records after position from the user's chat index.
Chats(ctx context.Context, userID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error)
// CreateMessage appends one message atomically and assigns its ordering timestamp.
CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error)
// Messages reads up to limit records strictly after position in one chat.
Messages(ctx context.Context, chatID uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error)
}
+38
View File
@@ -0,0 +1,38 @@
package memory
import "gitea.privcloud.tech/vlad_marlo/mtusi2026lab4/internal/model/dto"
// Conservative logical charges, not measurements of Go allocations or RSS.
// The budget includes record metadata and index entries; HTTP buffers are separate.
const (
userRecordOverheadBytes = 256
chatRecordOverheadBytes = 256
messageRecordOverheadBytes = 256
chatMemberIndexBytes = 128
usernameIndexCopies = 2
)
// userCost calculates the logical storage charge for a user and its index entries.
func userCost(user dto.UserDTO) int {
return userRecordOverheadBytes + len(user.Username)*usernameIndexCopies + len(user.DisplayName)
}
// chatCost calculates the logical storage charge for a chat and its membership index.
func chatCost(chat dto.ChatDTO) int {
return chatRecordOverheadBytes + len(chat.Title) + chatMemberIndexBytes*len(chat.MemberIDs)
}
// messageCost calculates the logical storage charge for a message.
func messageCost(message dto.MessageDTO) int {
return messageRecordOverheadBytes + len(message.Text)
}
// reserve checks and charges capacity while the caller holds the write lock.
// Callers must not perform a fallible operation after reserving this budget.
func (s *Store) reserve(bytes int) bool {
if bytes > s.limits.MaxStateBytes-s.usedBytes {
return false
}
s.usedBytes += bytes
return true
}

Some files were not shown because too many files have changed in this diff Show More