feat: restricted S3 credentials, orphan reconciler, upload limits (grade 4)

This commit is contained in:
2026-11-20 04:30:58 +03:00
parent 89e9e7b4d4
commit 1c3011bf28
42 changed files with 1483 additions and 130 deletions
+54 -34
View File
@@ -10,19 +10,21 @@ import (
)
type Config struct {
Host string
Port string
Env string
SessionTTL time.Duration
DatabaseURL string
CacheURL string
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKeyID string
S3SecretAccessKey string
MaxUploadBytes int64
MaxImagePixels int64
Host string
Port string
Env string
SessionTTL time.Duration
DatabaseURL string
CacheURL string
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKeyID string
S3SecretAccessKey string
MaxUploadBytes int64
MaxImagePixels int64
MaxConcurrentUploads int
MaxConcurrentDecodes int
}
func Load() (Config, error) {
@@ -30,27 +32,35 @@ func Load() (Config, error) {
if err != nil || ttl <= 0 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
}
maxUploadBytes, err := positiveInt("MAX_UPLOAD_BYTES", "10485760")
maxUploadBytes, err := positiveInt64("MAX_UPLOAD_BYTES", "10485760")
if err != nil {
return Config{}, err
}
maxImagePixels, err := positiveInt("MAX_IMAGE_PIXELS", "40000000")
maxImagePixels, err := positiveInt64("MAX_IMAGE_PIXELS", "40000000")
if err != nil {
return Config{}, err
}
databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
maxConcurrentUploads, err := positiveInt("MAX_CONCURRENT_UPLOADS", "8")
if err != nil {
return Config{}, err
}
cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url")
maxConcurrentDecodes, err := positiveInt("MAX_CONCURRENT_DECODES", "1")
if err != nil {
return Config{}, err
}
accessKeyID, err := readSecret("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id")
databaseURL, err := ReadSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
if err != nil {
return Config{}, err
}
secretAccessKey, err := readSecret("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key")
cacheURL, err := ReadSecret("CACHE_URL_FILE", "/run/secrets/cache_url")
if err != nil {
return Config{}, err
}
accessKeyID, err := ReadSecret("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id")
if err != nil {
return Config{}, err
}
secretAccessKey, err := ReadSecret("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key")
if err != nil {
return Config{}, err
}
@@ -66,25 +76,27 @@ func Load() (Config, error) {
return Config{}, fmt.Errorf("S3_ENDPOINT must not be empty")
}
return Config{
Host: getenv("APP_HOST", "0.0.0.0"),
Port: getenv("APP_PORT", "8080"),
Env: getenv("APP_ENV", "lab"),
SessionTTL: time.Duration(ttl) * time.Second,
DatabaseURL: databaseURL,
CacheURL: cacheURL,
S3Endpoint: endpoint,
S3Region: getenv("S3_REGION", "us-east-1"),
S3Bucket: bucket,
S3AccessKeyID: accessKeyID,
S3SecretAccessKey: secretAccessKey,
MaxUploadBytes: maxUploadBytes,
MaxImagePixels: maxImagePixels,
Host: getenv("APP_HOST", "0.0.0.0"),
Port: getenv("APP_PORT", "8080"),
Env: getenv("APP_ENV", "lab"),
SessionTTL: time.Duration(ttl) * time.Second,
DatabaseURL: databaseURL,
CacheURL: cacheURL,
S3Endpoint: endpoint,
S3Region: getenv("S3_REGION", "us-east-1"),
S3Bucket: bucket,
S3AccessKeyID: accessKeyID,
S3SecretAccessKey: secretAccessKey,
MaxUploadBytes: maxUploadBytes,
MaxImagePixels: maxImagePixels,
MaxConcurrentUploads: maxConcurrentUploads,
MaxConcurrentDecodes: maxConcurrentDecodes,
}, nil
}
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
func positiveInt(key, def string) (int64, error) {
func positiveInt64(key, def string) (int64, error) {
value, err := strconv.ParseInt(getenv(key, def), 10, 64)
if err != nil || value <= 0 {
return 0, fmt.Errorf("%s must be a positive integer", key)
@@ -92,7 +104,15 @@ func positiveInt(key, def string) (int64, error) {
return value, nil
}
func readSecret(key, def string) (string, error) {
func positiveInt(key, def string) (int, error) {
value, err := strconv.Atoi(getenv(key, def))
if err != nil || value <= 0 {
return 0, fmt.Errorf("%s must be a positive integer", key)
}
return value, nil
}
func ReadSecret(key, def string) (string, error) {
path := getenv(key, def)
b, err := os.ReadFile(path)
if err != nil {
+1 -1
View File
@@ -90,7 +90,7 @@ func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest
auth := service.NewAuthService(store, sessions, ttl)
chats := service.NewChatService(store)
messages := service.NewMessageService(chats, store)
attachments := service.NewAttachmentService(chats, store, newStubObjectStore(), 10485760, 40000000)
attachments := service.NewAttachmentService(chats, store, newStubObjectStore(), 10485760, 40000000, 8, 2)
h := handler.New(users, auth, chats, messages, attachments, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(router.New(h, "test"))
t.Cleanup(srv.Close)
+97
View File
@@ -0,0 +1,97 @@
package reconcile
import (
"sort"
"strings"
"time"
"uuid"
)
type Object struct {
Key string
Size int64
LastModified time.Time
}
type Metadata struct {
ID uuid.UUID
ObjectKey string
ChatID uuid.UUID
CreatedAt time.Time
}
type Orphan struct {
Key string `json:"key"`
SizeBytes int64 `json:"size_bytes"`
LastModified string `json:"last_modified"`
AgeSeconds int64 `json:"age_seconds"`
}
type Missing struct {
ID string `json:"id"`
ObjectKey string `json:"object_key"`
ChatID string `json:"chat_id"`
CreatedAt string `json:"created_at"`
}
type Report struct {
Prefix string `json:"prefix"`
GraceSeconds int64 `json:"grace_seconds"`
DryRun bool `json:"dry_run"`
ScannedObjects int `json:"scanned_objects"`
ScannedRows int `json:"scanned_rows"`
Truncated bool `json:"truncated"`
Orphans []Orphan `json:"orphans"`
Missing []Missing `json:"missing"`
Deleted int `json:"deleted_objects"`
DeleteFailures int `json:"delete_failures"`
DurationMS int64 `json:"duration_ms"`
}
func Plan(objects []Object, rows []Metadata, prefix string, now time.Time, grace time.Duration) ([]Orphan, []Missing) {
referenced := make(map[string]struct{}, len(rows))
existing := make(map[string]struct{}, len(objects))
for _, row := range rows {
referenced[row.ObjectKey] = struct{}{}
}
for _, object := range objects {
existing[object.Key] = struct{}{}
}
orphans := make([]Orphan, 0)
for _, object := range objects {
if !strings.HasPrefix(object.Key, prefix) {
continue
}
if _, ok := referenced[object.Key]; ok {
continue
}
age := now.Sub(object.LastModified)
if age < grace {
continue
}
orphans = append(orphans, Orphan{
Key: object.Key,
SizeBytes: object.Size,
LastModified: object.LastModified.UTC().Format(time.RFC3339),
AgeSeconds: int64(age.Seconds()),
})
}
missing := make([]Missing, 0)
for _, row := range rows {
if _, ok := existing[row.ObjectKey]; ok {
continue
}
missing = append(missing, Missing{
ID: row.ID.String(),
ObjectKey: row.ObjectKey,
ChatID: row.ChatID.String(),
CreatedAt: row.CreatedAt.UTC().Format(time.RFC3339),
})
}
sort.Slice(orphans, func(i, j int) bool { return orphans[i].Key < orphans[j].Key })
sort.Slice(missing, func(i, j int) bool { return missing[i].ObjectKey < missing[j].ObjectKey })
return orphans, missing
}
+75
View File
@@ -0,0 +1,75 @@
package reconcile
import (
"testing"
"time"
"uuid"
)
func TestPlanDetectsOrphansAndMissing(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
usedID, missingID := uuid.New(), uuid.New()
objects := []Object{
{Key: "chats/a/used", Size: 10, LastModified: now.Add(-2 * time.Hour)},
{Key: "chats/a/orphan-old", Size: 20, LastModified: now.Add(-2 * time.Hour)},
{Key: "chats/a/orphan-fresh", Size: 30, LastModified: now.Add(-1 * time.Minute)},
{Key: "other/prefix/ignored", Size: 40, LastModified: now.Add(-2 * time.Hour)},
}
rows := []Metadata{
{ID: usedID, ObjectKey: "chats/a/used", ChatID: uuid.New(), CreatedAt: now.Add(-2 * time.Hour)},
{ID: missingID, ObjectKey: "chats/a/missing", ChatID: uuid.New(), CreatedAt: now.Add(-2 * time.Hour)},
}
orphans, missing := Plan(objects, rows, "chats/", now, time.Hour)
if len(orphans) != 1 || orphans[0].Key != "chats/a/orphan-old" {
t.Fatalf("orphans = %+v, want only chats/a/orphan-old", orphans)
}
if len(missing) != 1 || missing[0].ObjectKey != "chats/a/missing" {
t.Fatalf("missing = %+v, want only chats/a/missing", missing)
}
}
func TestPlanHonoursGraceAndPrefix(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
objects := []Object{
{Key: "chats/a/fresh", Size: 1, LastModified: now.Add(-30 * time.Second)},
{Key: "outside/key", Size: 1, LastModified: now.Add(-48 * time.Hour)},
}
orphans, _ := Plan(objects, nil, "chats/", now, time.Hour)
if len(orphans) != 0 {
t.Fatalf("orphans = %+v, want none", orphans)
}
orphans, _ = Plan(objects, nil, "chats/", now, 0)
if len(orphans) != 1 || orphans[0].Key != "chats/a/fresh" {
t.Fatalf("orphans with zero grace = %+v, want chats/a/fresh", orphans)
}
}
func TestPlanNeverDeletesReferencedObjects(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
objects := []Object{{Key: "chats/a/used", Size: 1, LastModified: now.Add(-100 * time.Hour)}}
rows := []Metadata{{ID: uuid.New(), ObjectKey: "chats/a/used", ChatID: uuid.New(), CreatedAt: now.Add(-100 * time.Hour)}}
orphans, missing := Plan(objects, rows, "chats/", now, 0)
if len(orphans) != 0 {
t.Fatalf("orphans = %+v, want none for referenced object", orphans)
}
if len(missing) != 0 {
t.Fatalf("missing = %+v, want none", missing)
}
}
func TestPlanOutputIsSorted(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
objects := []Object{
{Key: "chats/a/z", LastModified: now.Add(-time.Hour)},
{Key: "chats/a/b", LastModified: now.Add(-time.Hour)},
{Key: "chats/a/m", LastModified: now.Add(-time.Hour)},
}
orphans, _ := Plan(objects, nil, "chats/", now, 0)
if len(orphans) != 3 || orphans[0].Key != "chats/a/b" || orphans[2].Key != "chats/a/z" {
t.Fatalf("orphans are not sorted: %+v", orphans)
}
}
+54 -9
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
@@ -14,19 +15,30 @@ import (
"messenger/internal/domain"
)
type ObjectInfo struct {
Key string
Size int64
LastModified time.Time
}
type Store struct {
client *minio.Client
bucket string
region string
}
func New(endpoint, region, accessKeyID, secretAccessKey, bucket string) (*Store, error) {
func EndpointHost(endpoint string) (string, bool) {
host, secure := endpoint, false
if parsed, err := url.Parse(endpoint); err == nil && parsed.Host != "" {
host = parsed.Host
secure = parsed.Scheme == "https"
}
client, err := minio.New(strings.TrimRight(host, "/"), &minio.Options{
return strings.TrimRight(host, "/"), secure
}
func New(endpoint, region, accessKeyID, secretAccessKey, bucket string) (*Store, error) {
host, secure := EndpointHost(endpoint)
client, err := minio.New(host, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Region: region,
Secure: secure,
@@ -56,17 +68,18 @@ func (s *Store) EnsureBucket(ctx context.Context) error {
}
func (s *Store) Ping(ctx context.Context) error {
_, err := s.client.BucketExists(ctx, s.bucket)
return s.wrap(err)
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return s.wrap(err)
}
if !exists {
return fmt.Errorf("%w: bucket is missing", domain.ErrUnavailable)
}
return nil
}
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType})
if err != nil && minio.ToErrorResponse(err).Code == "NoSuchBucket" {
if ensureErr := s.EnsureBucket(ctx); ensureErr == nil {
_, err = s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{ContentType: contentType})
}
}
return s.wrap(err)
}
@@ -86,6 +99,38 @@ func (s *Store) Delete(ctx context.Context, key string) error {
return s.wrap(s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}))
}
func (s *Store) List(ctx context.Context, prefix string, limit int) ([]ObjectInfo, bool, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
objects := make([]ObjectInfo, 0, 64)
for info := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
if info.Err != nil {
return nil, false, s.wrap(info.Err)
}
if len(objects) >= limit {
return objects, true, nil
}
objects = append(objects, ObjectInfo{Key: info.Key, Size: info.Size, LastModified: info.LastModified})
}
return objects, false, nil
}
func (s *Store) Buckets(ctx context.Context) ([]string, error) {
buckets, err := s.client.ListBuckets(ctx)
if err != nil {
return nil, s.wrap(err)
}
names := make([]string, len(buckets))
for i, bucket := range buckets {
names[i] = bucket.Name
}
return names, nil
}
func (s *Store) RemoveBucket(ctx context.Context, bucket string) error {
return s.wrap(s.client.RemoveBucket(ctx, bucket))
}
func (s *Store) wrap(err error) error {
if err == nil {
return nil
+37 -3
View File
@@ -31,10 +31,21 @@ type AttachmentService struct {
store ObjectStore
maxBytes int64
maxPixels int64
uploads chan struct{}
decodes chan struct{}
}
func NewAttachmentService(chats *ChatService, repo AttachmentRepository, store ObjectStore, maxBytes, maxPixels int64) *AttachmentService {
return &AttachmentService{chats: chats, repo: repo, store: store, maxBytes: maxBytes, maxPixels: maxPixels}
func NewAttachmentService(chats *ChatService, repo AttachmentRepository, store ObjectStore,
maxBytes, maxPixels int64, maxConcurrentUploads, maxConcurrentDecodes int) *AttachmentService {
return &AttachmentService{
chats: chats,
repo: repo,
store: store,
maxBytes: maxBytes,
maxPixels: maxPixels,
uploads: make(chan struct{}, maxConcurrentUploads),
decodes: make(chan struct{}, maxConcurrentDecodes),
}
}
func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatID uuid.UUID, filename, contentType string, body io.Reader) (domain.Attachment, error) {
@@ -47,6 +58,10 @@ func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatI
if contentType != domain.ContentPNG && contentType != domain.ContentJPEG {
return domain.Attachment{}, fmt.Errorf("%w: content type must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
}
if err := acquire(ctx, s.uploads); err != nil {
return domain.Attachment{}, err
}
defer release(s.uploads)
raw, err := readLimited(body, s.maxBytes)
if err != nil {
return domain.Attachment{}, err
@@ -57,7 +72,7 @@ func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatI
if err := checkPixels(raw, s.maxPixels); err != nil {
return domain.Attachment{}, err
}
if err := checkIntegrity(raw); err != nil {
if err := s.decode(ctx, raw); err != nil {
return domain.Attachment{}, err
}
@@ -124,6 +139,25 @@ func (s *AttachmentService) Open(ctx context.Context, actor domain.User, id uuid
return attachment, content, nil
}
func (s *AttachmentService) decode(ctx context.Context, raw []byte) error {
if err := acquire(ctx, s.decodes); err != nil {
return err
}
defer release(s.decodes)
return checkIntegrity(raw)
}
func acquire(ctx context.Context, sem chan struct{}) error {
select {
case sem <- struct{}{}:
return nil
case <-ctx.Done():
return fmt.Errorf("%w: request cancelled while waiting for capacity", domain.ErrUnavailable)
}
}
func release(sem chan struct{}) { <-sem }
func checkFilename(filename string) error {
if n := utf8.RuneCountInString(filename); n < 1 || n > maxFilenameRunes {
return fmt.Errorf("%w: filename must be 1 to 255 characters", domain.ErrInvalidInput)