feat(storage): add private file layer and isolate SeaweedFS on a storage network

This commit is contained in:
shira committed 2026-10-06 13:51:53 +03:00
1 parent f5b07e8f4d
commit 8378ad45b0
22 files changed
+1668 -40

No files matched your search

+66 -5
View File
@@ -6,13 +6,16 @@ import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"strings"
"testing"
"time"
"github.com/testcontainers/testcontainers-go"
tcexec "github.com/testcontainers/testcontainers-go/exec"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
"github.com/twmb/franz-go/pkg/kadm"
@@ -53,6 +56,11 @@ const (
kafkaStartupTimeout = time.Minute
kafkaReadyTimeout = 30 * time.Second
seaweedfsS3Port = "8333/tcp"
seaweedfsFilerPort = "8888/tcp"
seaweedfsMasterPort = "9333/tcp"
seaweedfsVolumePort = "9340/tcp"
kafkaClientPort = "9092/tcp"
// kafkaListenersFile is written by a post-start hook once the host port is
// mapped; the container entrypoint waits for it before launching the broker.
@@ -71,6 +79,18 @@ const (
kafkaService
)
// seaweedfsEntrypoint mirrors deploy/docker/docker-compose.yml. Each start
// gets random signing keys, so the internal filer and volume HTTP APIs reject
// requests without a JWT minted inside the container.
var seaweedfsEntrypoint = []string{
"/bin/sh", "-ec",
`for name in WEED_JWT_SIGNING_KEY WEED_JWT_SIGNING_READ_KEY WEED_JWT_FILER_SIGNING_KEY WEED_JWT_FILER_SIGNING_READ_KEY; do
export "$name=$(head -c 32 /dev/urandom | base64)"
done
exec /entrypoint.sh "$@"`,
"seaweedfs",
}
// defaultServices form the full readiness environment. Kafka is not part of
// readiness, so it starts only for tests that select kafkaService.
var defaultServices = []service{postgresService, redisService, seaweedfsService}
@@ -252,21 +272,24 @@ func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
t.Helper()
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: seaweedfsImage,
ExposedPorts: []string{"8333/tcp"},
Image: seaweedfsImage,
// Only the S3 port is used by the adapter. The internal ports are
// published so tests can prove they refuse unauthenticated access.
ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort},
Entrypoint: seaweedfsEntrypoint,
Env: map[string]string{
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
"S3_BUCKET": env.Config.SeaweedFSBucket,
},
Cmd: []string{
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0",
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@",
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
},
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
WaitingFor: wait.ForHTTP("/healthz").WithPort("8333/tcp").WithStartupTimeout(seaweedfsStartupTimeout),
WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout),
},
Started: true,
})
@@ -275,7 +298,7 @@ func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
t.Fatalf("start SeaweedFS container: %v", err)
}
env.seaweedfsContainer = container
endpoint, err := container.PortEndpoint(ctx, "8333/tcp", "http")
endpoint, err := container.PortEndpoint(ctx, seaweedfsS3Port, "http")
if err != nil {
t.Fatalf("get SeaweedFS endpoint: %v", err)
}
@@ -284,6 +307,44 @@ func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
waitForStorage(ctx, t, env.SeaweedFS)
}
// seaweedfsInternalEndpoint returns a host URL for an internal SeaweedFS port.
func (env *testEnvironment) seaweedfsInternalEndpoint(ctx context.Context, t *testing.T, port string) string {
t.Helper()
if env.seaweedfsContainer == nil {
t.Fatal("SeaweedFS was not selected in bootstrap")
}
endpoint, err := env.seaweedfsContainer.PortEndpoint(ctx, port, "http")
if err != nil {
t.Fatalf("get SeaweedFS internal endpoint: %v", err)
}
return endpoint
}
// assignSeaweedFSVolume asks the master for a file ID from inside the
// container, where the whitelist allows it, and returns the fid with the
// signed volume write token the master hands out.
func (env *testEnvironment) assignSeaweedFSVolume(ctx context.Context, t *testing.T) (string, string) {
t.Helper()
code, output, err := env.seaweedfsContainer.Exec(ctx, []string{
"sh", "-ec", `curl -sf -D - -o /tmp/assign http://127.0.0.1:9333/dir/assign | sed -n "s/^[Aa]uthorization: //p" | tr -d "\r"; cat /tmp/assign`,
}, tcexec.Multiplexed())
if err != nil || code != 0 {
t.Fatalf("assign SeaweedFS volume: exit %d, %v", code, err)
}
data, err := io.ReadAll(output)
if err != nil {
t.Fatal(err)
}
token, body, _ := strings.Cut(string(data), "\n")
var assignment struct {
FID string `json:"fid"`
}
if err := json.Unmarshal([]byte(body), &assignment); err != nil || assignment.FID == "" || token == "" {
t.Fatalf("unexpected volume assignment: %v", err)
}
return assignment.FID, token
}
func (env *testEnvironment) newStorage(t *testing.T, settings config.Config) *seaweedfs.Storage {
t.Helper()
storage, cleanup, err := seaweedfs.NewStorage(settings)
@@ -0,0 +1,275 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"mime/multipart"
"net/http"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"lincodex/backend/config"
"lincodex/backend/internal/usecase/files"
)
const (
syntheticFileLimit = 1 << 20
// streamIterations exceeds the adapter's per-host connection limit, so a
// leaked response body would block a later Open until it times out.
streamIterations = 50
streamLoopTimeout = 20 * time.Second
)
func TestPrivateFileStoreAgainstSeaweedFS(t *testing.T) {
env := bootstrap(t, seaweedfsService)
ctx := t.Context()
store := files.NewStore(env.SeaweedFS)
policy := newFilePolicy(t, files.NamespaceResume)
payload := bytes.Repeat([]byte("%PDF-1.7 synthetic test document\n"), 8<<10)
digest := sha256.Sum256(payload)
record, err := store.Put(ctx, policy, files.Upload{
// Hide Seek so the upload streams like an HTTP request body.
Body: struct{ io.Reader }{bytes.NewReader(payload)}, Size: int64(len(payload)),
ContentType: "application/pdf", OriginalName: "../Synthetic CV.pdf",
})
if err != nil {
t.Fatalf("upload synthetic file: %v", err)
}
if record.SHA256 != hex.EncodeToString(digest[:]) || record.Size != int64(len(payload)) || record.OriginalName != "Synthetic CV.pdf" {
t.Fatalf("record differs: %+v", record)
}
t.Run("write and read through the adapter", func(t *testing.T) {
assertStoredFile(ctx, t, store, policy, record.Key, payload)
empty, err := store.Put(ctx, policy, files.Upload{Body: bytes.NewReader(nil), ContentType: "application/pdf"})
if err != nil {
t.Fatalf("upload empty file: %v", err)
}
assertStoredFile(ctx, t, store, policy, empty.Key, nil)
})
t.Run("anonymous access is refused", func(t *testing.T) {
objectURL := env.Config.SeaweedFSEndpoint + "/" + env.Config.SeaweedFSBucket + "/" + record.Key
filer := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsFilerPort)
master := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsMasterPort)
for _, probe := range []struct {
name, method, url string
status int
}{
{name: "S3 object", method: http.MethodGet, url: objectURL, status: http.StatusForbidden},
{name: "S3 object with presign-like query", method: http.MethodGet, url: objectURL + "?X-Amz-Algorithm=AWS4-HMAC-SHA256", status: http.StatusForbidden},
{name: "S3 bucket listing", method: http.MethodGet, url: env.Config.SeaweedFSEndpoint + "/" + env.Config.SeaweedFSBucket, status: http.StatusForbidden},
{name: "S3 upload", method: http.MethodPut, url: objectURL + "-anonymous", status: http.StatusForbidden},
{name: "S3 deletion", method: http.MethodDelete, url: objectURL, status: http.StatusForbidden},
{name: "filer object", method: http.MethodGet, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/" + record.Key, status: http.StatusUnauthorized},
{name: "filer listing", method: http.MethodGet, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/", status: http.StatusUnauthorized},
{name: "filer upload", method: http.MethodPut, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/anonymous", status: http.StatusUnauthorized},
{name: "master volume assignment", method: http.MethodGet, url: master + "/dir/assign", status: http.StatusUnauthorized},
{name: "master collection deletion", method: http.MethodGet, url: master + "/col/delete?collection=" + env.Config.SeaweedFSBucket, status: http.StatusUnauthorized},
} {
t.Run(probe.name, func(t *testing.T) {
status, body := unsignedRequest(ctx, t, probe.method, probe.url)
if status != probe.status || bytes.Contains(body, payload[:64]) {
t.Fatalf("unsigned %s returned HTTP %d, want %d", probe.method, status, probe.status)
}
})
}
assertStoredFile(ctx, t, store, policy, record.Key, payload)
if _, err := store.Open(ctx, policy, record.Key+"-anonymous"); !errors.Is(err, files.ErrInvalidKey) {
t.Fatalf("anonymous key was accepted: %v", err)
}
})
t.Run("volume refuses callers outside the container", func(t *testing.T) {
// The master hands out a signed write token with every assignment. The
// volume whitelist must refuse it from any other address, and reads
// need a token that never leaves the container.
fid, token := env.assignSeaweedFSVolume(ctx, t)
volume := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsVolumePort) + "/" + fid
if status, _ := unsignedRequest(ctx, t, http.MethodGet, volume); status != http.StatusUnauthorized {
t.Fatalf("volume read without a token returned HTTP %d", status)
}
if status := volumeUpload(ctx, t, volume, token); status != http.StatusUnauthorized {
t.Fatalf("volume write with the assigned token returned HTTP %d", status)
}
})
t.Run("wrong secret is refused", func(t *testing.T) {
other := env.Config
other.SeaweedFSSecretKey = "wrong-secret"
unauthorized := files.NewStore(env.newStorage(t, other))
if _, err := unauthorized.Open(ctx, policy, record.Key); err == nil || errors.Is(err, files.ErrNotFound) {
t.Fatalf("wrong secret opened a file or looked like absence: %v", err)
}
if _, err := unauthorized.Put(ctx, policy, files.Upload{Body: strings.NewReader("no"), Size: 2, ContentType: "application/pdf"}); err == nil {
t.Fatal("wrong secret uploaded a file")
}
if err := unauthorized.Delete(ctx, policy, record.Key); err == nil {
t.Fatal("wrong secret deleted a file")
}
assertStoredFile(ctx, t, store, policy, record.Key, payload)
})
t.Run("streams are closed", func(t *testing.T) {
// The adapter timeout would eventually release a leaked body, so this
// store waits much longer than the whole loop may take.
patient := env.Config
patient.SeaweedFSTimeout = time.Hour
patientStore := files.NewStore(env.newStorage(t, patient))
loopCtx, cancel := context.WithTimeout(ctx, streamLoopTimeout)
defer cancel()
for range streamIterations {
file, err := patientStore.Open(loopCtx, policy, record.Key)
if err != nil {
t.Fatalf("open after earlier closes: %v", err)
}
if _, err := io.ReadFull(file, make([]byte, 1)); err != nil {
t.Fatal(err)
}
if err := file.Close(); err != nil {
t.Fatal(err)
}
if _, err := file.Read(make([]byte, 1)); err == nil {
t.Fatal("read after close succeeded")
}
}
})
t.Run("size limits abort and leave no object", func(t *testing.T) {
limited := newFilePolicy(t, files.NamespaceProfilePDF)
oversized := bytes.Repeat([]byte("x"), syntheticFileLimit+1)
for _, test := range []struct {
name string
upload files.Upload
want error
}{
{name: "declared over limit", upload: files.Upload{Body: bytes.NewReader(oversized), Size: int64(len(oversized))}, want: files.ErrTooLarge},
{name: "stream past limit", upload: files.Upload{Body: bytes.NewReader(oversized), Size: syntheticFileLimit}, want: files.ErrTooLarge},
{name: "stream past declared size", upload: files.Upload{Body: strings.NewReader("0123456789"), Size: 4}, want: files.ErrTooLarge},
{name: "stream shorter than declared", upload: files.Upload{Body: strings.NewReader("0123"), Size: 10}, want: files.ErrSizeMismatch},
} {
t.Run(test.name, func(t *testing.T) {
test.upload.ContentType = "application/pdf"
test.upload.Body = struct{ io.Reader }{test.upload.Body}
if _, err := store.Put(ctx, limited, test.upload); !errors.Is(err, test.want) {
t.Fatalf("error = %v, want %v", err, test.want)
}
})
}
if keys := listKeys(ctx, t, env.Config, string(files.NamespaceProfilePDF)+"/"); len(keys) != 0 {
t.Fatalf("rejected uploads left %d objects", len(keys))
}
})
t.Run("delete then not found", func(t *testing.T) {
if err := store.Delete(ctx, policy, record.Key); err != nil {
t.Fatal(err)
}
if err := store.Delete(ctx, policy, record.Key); err != nil {
t.Fatalf("repeated deletion: %v", err)
}
if _, err := store.Open(ctx, policy, record.Key); !errors.Is(err, files.ErrNotFound) {
t.Fatalf("deleted file: %v", err)
}
})
}
func newFilePolicy(t *testing.T, namespace files.Namespace) files.Policy {
t.Helper()
policy, err := files.NewPolicy(namespace, syntheticFileLimit, "application/pdf")
if err != nil {
t.Fatal(err)
}
return policy
}
func assertStoredFile(ctx context.Context, t *testing.T, store *files.Store, policy files.Policy, key string, want []byte) {
t.Helper()
file, err := store.Open(ctx, policy, key)
if err != nil {
t.Fatal(err)
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil || !bytes.Equal(data, want) || file.Size != int64(len(want)) || file.ContentType != "application/pdf" {
t.Fatalf("stored file differs: size=%d type=%q error=%v", file.Size, file.ContentType, err)
}
}
func unsignedRequest(ctx context.Context, t *testing.T, method, url string) (int, []byte) {
t.Helper()
request, err := http.NewRequestWithContext(ctx, method, url, strings.NewReader("anonymous"))
if err != nil {
t.Fatal(err)
}
client := &http.Client{Timeout: storageTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
response, err := client.Do(request)
if err != nil {
t.Fatalf("unsigned request: %v", err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
t.Fatalf("read unsigned response: %v", err)
}
return response.StatusCode, body
}
func volumeUpload(ctx context.Context, t *testing.T, url, token string) int {
t.Helper()
var body bytes.Buffer
form := multipart.NewWriter(&body)
part, err := form.CreateFormFile("file", "synthetic.txt")
if err != nil {
t.Fatal(err)
}
if _, err := part.Write([]byte("synthetic")); err != nil {
t.Fatal(err)
}
if err := form.Close(); err != nil {
t.Fatal(err)
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body)
if err != nil {
t.Fatal(err)
}
request.Header.Set("Content-Type", form.FormDataContentType())
request.Header.Set("Authorization", token)
response, err := (&http.Client{Timeout: storageTimeout}).Do(request)
if err != nil {
t.Fatalf("volume upload: %v", err)
}
defer response.Body.Close()
_, _ = io.Copy(io.Discard, response.Body)
return response.StatusCode
}
// listKeys uses a separate signed client to see objects the store never
// returned, such as a partial write under a key the caller did not learn.
func listKeys(ctx context.Context, t *testing.T, settings config.Config, prefix string) []string {
t.Helper()
client := s3.New(s3.Options{
Region: settings.SeaweedFSRegion,
BaseEndpoint: aws.String(settings.SeaweedFSEndpoint),
UsePathStyle: true,
Credentials: credentials.NewStaticCredentialsProvider(settings.SeaweedFSAccessKey, settings.SeaweedFSSecretKey, ""),
})
output, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(settings.SeaweedFSBucket), Prefix: aws.String(prefix)})
if err != nil {
t.Fatalf("list objects: %v", err)
}
keys := make([]string, 0, len(output.Contents))
for _, object := range output.Contents {
keys = append(keys, aws.ToString(object.Key))
}
if aws.ToBool(output.IsTruncated) {
t.Fatalf("listing of %s is truncated", prefix)
}
return keys
}
@@ -40,6 +40,12 @@ var (
)
// NewStorage creates a lazy S3 client. Deployment owns bucket provisioning.
//
// SEAWEEDFS_TIMEOUT bounds connection setup, the TLS handshake, the wait for
// response headers, and whole Delete and readiness calls. It does not bound
// object body transfer in Put and Get: the duration depends on file size and
// client speed, which only the caller knows, so the caller's context and the
// source deadline govern the stream.
func NewStorage(settings config.Config) (*Storage, func(), error) {
if err := settings.ValidateSeaweedFS(); err != nil {
return nil, nil, err
@@ -60,9 +66,9 @@ func NewStorage(settings config.Config) (*Storage, func(), error) {
BaseEndpoint: aws.String(settings.SeaweedFSEndpoint),
UsePathStyle: true,
Credentials: credentials.NewStaticCredentialsProvider(settings.SeaweedFSAccessKey, settings.SeaweedFSSecretKey, ""),
// No Client.Timeout: it would cut long object bodies; see above.
HTTPClient: &http.Client{
Transport: transport,
Timeout: settings.SeaweedFSTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
},
// A non-seekable upload cannot be replayed safely.
@@ -78,8 +84,6 @@ func (storage *Storage) Put(ctx context.Context, key string, body io.Reader, siz
if key == "" || body == nil || size < 0 {
return fmt.Errorf("Storage.Put - validate input: %w", outbound.ErrInvalidObject)
}
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
defer cancel()
_, err := storage.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(storage.bucket),
Key: aws.String(key),
@@ -97,7 +101,9 @@ func (storage *Storage) Get(ctx context.Context, key string) (outbound.Object, e
if key == "" {
return outbound.Object{}, fmt.Errorf("Storage.Get - validate key: %w", outbound.ErrInvalidObject)
}
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
// Close or a read error cancels the request; the transfer itself is bounded
// only by the caller's context.
ctx, cancel := context.WithCancel(ctx)
result, err := storage.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(storage.bucket), Key: aws.String(key)})
if err != nil {
cancel()
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
@@ -81,8 +82,8 @@ func TestStorageGetKeepsBodyAliveUntilClose(t *testing.T) {
}
}
func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
for _, mode := range []string{"caller", "timeout", "close"} {
func TestStorageGetBodyHonorsCancellationAndDeadline(t *testing.T) {
for _, mode := range []string{"caller", "deadline", "close"} {
t.Run(mode, func(t *testing.T) {
disconnected := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -93,13 +94,13 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
close(disconnected)
}))
defer server.Close()
timeout := time.Second
if mode == "timeout" {
timeout = 100 * time.Millisecond
}
storage := newTestStorage(t, server.URL, timeout)
storage := newTestStorage(t, server.URL, time.Second)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
if mode == "deadline" {
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
}
object, err := storage.Get(ctx, "private/file")
if err != nil {
t.Fatal(err)
@@ -110,7 +111,7 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
if err := object.Body.Close(); err != nil {
t.Fatal(err)
}
case "caller", "timeout":
case "caller", "deadline":
want := context.DeadlineExceeded
if mode == "caller" {
cancel()
@@ -129,6 +130,110 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
}
}
func TestStorageStreamsBodiesLongerThanTimeout(t *testing.T) {
const (
timeout = 100 * time.Millisecond
chunks = 5
pause = 60 * time.Millisecond
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPut {
if _, err := io.Copy(io.Discard, r.Body); err != nil {
t.Errorf("read slow upload: %v", err)
}
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Length", strconv.Itoa(chunks))
w.WriteHeader(http.StatusOK)
for range chunks {
_, _ = io.WriteString(w, "x")
w.(http.Flusher).Flush()
time.Sleep(pause)
}
}))
defer server.Close()
storage := newTestStorage(t, server.URL, timeout)
start := time.Now()
source := &slowReader{data: bytes.Repeat([]byte("x"), chunks), pause: pause}
if err := storage.Put(t.Context(), "private/file", source, chunks, "text/plain"); err != nil {
t.Fatalf("slow upload was cut: %v", err)
}
object, err := storage.Get(t.Context(), "private/file")
if err != nil {
t.Fatal(err)
}
defer object.Body.Close()
data, err := io.ReadAll(object.Body)
if err != nil || len(data) != chunks {
t.Fatalf("slow download was cut: %d bytes, %v", len(data), err)
}
if elapsed := time.Since(start); elapsed < 2*timeout {
t.Fatalf("transfers took %v, too fast to prove the timeout does not apply", elapsed)
}
}
func TestStorageBoundsResponseHeaders(t *testing.T) {
const timeout = 100 * time.Millisecond
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-release:
case <-r.Context().Done():
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
defer close(release)
storage := newTestStorage(t, server.URL, timeout)
for name, call := range map[string]func() error{
"get": func() error { _, err := storage.Get(t.Context(), "file"); return err },
"put": func() error { return storage.Put(t.Context(), "file", strings.NewReader("data"), 4, "text/plain") },
} {
t.Run(name, func(t *testing.T) {
start := time.Now()
// The caller's context has no deadline, so this is the adapter bound.
if err := call(); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("stalled headers: %v", err)
}
if elapsed := time.Since(start); elapsed > 10*timeout {
t.Fatalf("response header bound took %v", elapsed)
}
})
}
}
func TestStorageBoundsConnectionSetup(t *testing.T) {
const timeout = 100 * time.Millisecond
// A TEST-NET-1 address (RFC 5737) is never routed, so the dial either
// times out or fails at once; it must not wait for the caller.
storage := newTestStorage(t, "http://192.0.2.1:8333", timeout)
start := time.Now()
if _, err := storage.Get(t.Context(), "file"); err == nil {
t.Fatal("unreachable endpoint returned an object")
}
if elapsed := time.Since(start); elapsed > 10*timeout {
t.Fatalf("dial bound took %v", elapsed)
}
}
type slowReader struct {
data []byte
pause time.Duration
}
func (reader *slowReader) Read(buffer []byte) (int, error) {
if len(reader.data) == 0 {
return 0, io.EOF
}
time.Sleep(reader.pause)
n := copy(buffer[:1], reader.data)
reader.data = reader.data[n:]
return n, nil
}
func TestStorageClassifiesOnlyMissingObjectsAsNotFound(t *testing.T) {
for _, test := range []struct {
name, code string
@@ -22,8 +22,10 @@ type Object struct {
type ObjectStorage interface {
// Put streams exactly size bytes. The caller owns the source reader and must
// ensure a blocking source can be canceled. An error may leave a completed
// object when the server accepted the write before the response was lost.
// ensure a blocking source can be canceled. Adapters bound connection setup
// and the wait for a response, not the body transfer: the caller's context
// governs Put and the Get body. An error may leave a completed object when
// the server accepted the write before the response was lost.
Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error
Get(ctx context.Context, key string) (Object, error)
// Delete succeeds when the object is already absent.
+36
View File
@@ -0,0 +1,36 @@
package files
import (
"crypto/rand"
"encoding/hex"
"strings"
)
// keyRandomBytes gives 128 bits of entropy, so keys are not guessable and
// collisions are negligible without a lookup before the write.
const keyRandomBytes = 16
// newKey returns "<namespace>/<32 lowercase hex characters>". No caller input
// other than the validated policy namespace reaches the key, so file names
// cannot cause path traversal or reveal personal data through object keys.
func newKey(namespace Namespace) string {
var random [keyRandomBytes]byte
// crypto/rand.Read never returns an error; it aborts the process instead.
_, _ = rand.Read(random[:])
return string(namespace) + "/" + hex.EncodeToString(random[:])
}
// ownsKey accepts only keys this policy could have generated. It rejects keys
// from other namespaces and any value a client could have shaped.
func (policy Policy) ownsKey(key string) bool {
random, ok := strings.CutPrefix(key, string(policy.namespace)+"/")
if !policy.valid() || !ok || len(random) != hex.EncodedLen(keyRandomBytes) {
return false
}
for _, char := range random {
if (char < '0' || char > '9') && (char < 'a' || char > 'f') {
return false
}
}
return true
}
+62
View File
@@ -0,0 +1,62 @@
package files
import (
"path"
"strings"
"unicode"
"unicode/utf8"
)
const (
maxOriginalNameBytes = 255
// maxKeptExtensionBytes keeps a normal extension visible after truncation.
maxKeptExtensionBytes = 16
)
// SanitizeOriginalName turns a client-supplied file name into display
// metadata. It keeps only the last path element and removes invalid UTF-8,
// control, format (including bidirectional overrides), line and paragraph
// separator, and private-use characters, and leading or trailing dots and
// spaces. It does not apply Unicode normalization, so visually equal names
// may differ in bytes; never compare names for identity. The result may still
// contain personal data, so it is never used in object keys, logs, or
// employer-facing output. It returns an empty string when nothing usable
// remains.
func SanitizeOriginalName(name string) string {
name = strings.ToValidUTF8(name, "")
name = strings.ReplaceAll(name, `\`, "/")
name = name[strings.LastIndexByte(name, '/')+1:]
name = strings.Map(func(char rune) rune {
if removedFromName(char) {
return -1
}
return char
}, name)
return trimName(truncateName(trimName(name)))
}
func removedFromName(char rune) bool {
return unicode.IsControl(char) || unicode.In(char, unicode.Cf, unicode.Co, unicode.Zl, unicode.Zp)
}
func trimName(name string) string {
return strings.TrimFunc(name, func(char rune) bool { return char == '.' || unicode.IsSpace(char) })
}
// truncateName keeps a short extension and cuts the stem at a rune boundary.
// Trailing dots and spaces exposed by the cut are removed from the stem.
func truncateName(name string) string {
if len(name) <= maxOriginalNameBytes {
return name
}
extension := path.Ext(name)
if len(extension) > maxKeptExtensionBytes {
extension = ""
}
stem := strings.TrimSuffix(name, extension)
stem = stem[:maxOriginalNameBytes-len(extension)]
for !utf8.ValidString(stem) {
stem = stem[:len(stem)-1]
}
return trimName(stem) + extension
}
@@ -0,0 +1,28 @@
package files
// Namespace is the key prefix of one kind of stored file. Every namespace is
// declared here, so two features cannot share one by accident and then read
// or delete each other's files. Add a namespace with the first feature that
// stores such files; the planned owners are noted for reference.
type Namespace string
const (
// NamespaceResume holds uploaded resume files (TASK-070).
NamespaceResume Namespace = "resume"
// NamespaceProfilePDF holds generated standard profile PDFs (FR02).
NamespaceProfilePDF Namespace = "profile-pdf"
// NamespaceAccountExport holds personal data exports (TASK-093, TASK-458).
NamespaceAccountExport Namespace = "account-export"
)
// registeredNamespaces lists every declared namespace for NewPolicy.
var registeredNamespaces = []Namespace{NamespaceResume, NamespaceProfilePDF, NamespaceAccountExport}
func registered(namespace Namespace) bool {
for _, known := range registeredNamespaces {
if namespace == known {
return true
}
}
return false
}
+99
View File
@@ -0,0 +1,99 @@
// Package files is the shared private file layer over the ObjectStorage port.
// It owns technical rules common to every stored file: opaque keys, declared
// content types, streaming size limits, checksums, and cleanup of failed
// writes. Feature packages own their policies and every product rule, such as
// who may read a file, page limits, parsing, and retention.
package files
import (
"errors"
"fmt"
"mime"
"strings"
"lincodex/backend/internal/port/outbound"
)
const maxNamespaceLength = 32
var (
ErrInvalidPolicy = errors.New("invalid file policy")
ErrInvalidUpload = errors.New("invalid file upload")
ErrInvalidKey = errors.New("invalid file key")
ErrUnsupportedType = errors.New("unsupported file content type")
ErrTooLarge = errors.New("file exceeds size limit")
ErrSizeMismatch = errors.New("file size differs from declared size")
// ErrNotFound is the port sentinel, so callers need not import the port.
ErrNotFound = outbound.ErrObjectNotFound
)
// Policy is the storage rule for one kind of file. A feature package defines
// it once; the store enforces it on every write, read, and deletion.
type Policy struct {
namespace Namespace
maxSize int64
contentTypes map[string]struct{}
}
// NewPolicy accepts a declared namespace, a positive size limit in bytes, and
// exact media types without parameters or wildcards.
func NewPolicy(namespace Namespace, maxSize int64, contentTypes ...string) (Policy, error) {
if !registered(namespace) || !validNamespace(namespace) {
return Policy{}, fmt.Errorf("files.NewPolicy - validate namespace: %w", ErrInvalidPolicy)
}
if maxSize <= 0 {
return Policy{}, fmt.Errorf("files.NewPolicy - validate size limit: %w", ErrInvalidPolicy)
}
if len(contentTypes) == 0 {
return Policy{}, fmt.Errorf("files.NewPolicy - validate content types: %w", ErrInvalidPolicy)
}
allowed := make(map[string]struct{}, len(contentTypes))
for _, contentType := range contentTypes {
mediaType, ok := mediaTypeOf(contentType)
if !ok || mediaType != contentType || strings.Contains(mediaType, "*") {
return Policy{}, fmt.Errorf("files.NewPolicy - validate content type: %w", ErrInvalidPolicy)
}
allowed[mediaType] = struct{}{}
}
return Policy{namespace: namespace, maxSize: maxSize, contentTypes: allowed}, nil
}
func (policy Policy) Namespace() Namespace { return policy.namespace }
func (policy Policy) MaxSize() int64 { return policy.maxSize }
func (policy Policy) valid() bool { return policy.namespace != "" }
// allow returns the bare media type stored with the object. Parameters are
// dropped so a caller-declared value cannot smuggle data into the header
// that a later download response repeats.
func (policy Policy) allow(contentType string) (string, bool) {
mediaType, ok := mediaTypeOf(contentType)
if !ok {
return "", false
}
_, allowed := policy.contentTypes[mediaType]
return mediaType, allowed
}
func mediaTypeOf(contentType string) (string, bool) {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil || !strings.Contains(mediaType, "/") {
return "", false
}
return mediaType, true
}
// validNamespace requires lowercase letters, digits, and hyphens, starting
// with a letter, so a namespace is one safe key path element.
func validNamespace(namespace Namespace) bool {
if namespace == "" || len(namespace) > maxNamespaceLength || namespace[0] < 'a' || namespace[0] > 'z' {
return false
}
for _, char := range namespace {
if char != '-' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
return false
}
}
return true
}
+149
View File
@@ -0,0 +1,149 @@
package files
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"time"
"lincodex/backend/internal/port/outbound"
)
// cleanupTimeout bounds deletion of a failed write after the caller's context
// has been canceled.
const cleanupTimeout = 30 * time.Second
// Upload is one file write. Size is the exact declared length in bytes; the
// store does not buffer sources of unknown length. ContentType is the type the
// caller declared or detected and must be allowed by the policy. The store
// does not inspect content.
//
// Body needs its own deadline, for example an HTTP request body after
// http.ResponseController.SetReadDeadline. Put waits for a blocked Read, and
// canceling the context does not interrupt a Read that never returns.
type Upload struct {
Body io.Reader
Size int64
ContentType string
OriginalName string
}
// Record is the content metadata of a stored file. Callers persist it next to
// their own ownership and access rules; the store keeps no index. Key is an
// internal locator: never return it, the bucket, or a storage URL to clients.
//
// Callers follow one order: Put, then persist the Record in their database
// transaction, then Delete the key if that transaction fails. An object
// without a committed record is an orphan that no request can reach.
type Record struct {
Key string
ContentType string
Size int64
SHA256 string
OriginalName string
}
// Store applies a Policy to private object storage. It creates no public or
// presigned URLs; downloads go through an authorized backend endpoint that
// streams File.
type Store struct {
storage outbound.ObjectStorage
}
func NewStore(storage outbound.ObjectStorage) *Store {
return &Store{storage: storage}
}
// Put streams upload to a new opaque key. Any failure after the write started
// deletes the key, so a rejected or interrupted upload normally leaves no
// object. One race remains: when the whole body was sent before the caller
// canceled, the server may still commit after the cleanup Delete returned.
// Such an orphan has no Record, so a planned namespace sweeper that removes
// keys without a record (with backups, TASK-030 and TASK-458) is the final
// cleanup. See Record for the caller's order of operations.
func (store *Store) Put(ctx context.Context, policy Policy, upload Upload) (Record, error) {
if !policy.valid() {
return Record{}, fmt.Errorf("Store.Put - validate policy: %w", ErrInvalidPolicy)
}
if upload.Body == nil || upload.Size < 0 {
return Record{}, fmt.Errorf("Store.Put - validate upload: %w", ErrInvalidUpload)
}
if upload.Size > policy.maxSize {
return Record{}, fmt.Errorf("Store.Put - check declared size: %w", ErrTooLarge)
}
contentType, allowed := policy.allow(upload.ContentType)
if !allowed {
return Record{}, fmt.Errorf("Store.Put - check content type: %w", ErrUnsupportedType)
}
key := newKey(policy.namespace)
reader := newUploadReader(upload.Body, upload.Size)
if err := store.storage.Put(ctx, key, reader, upload.Size, contentType); err != nil {
// The storage error is sanitized; a stream violation explains more.
if reader.err != nil {
err = reader.err
}
return Record{}, store.discard(ctx, key, fmt.Errorf("Store.Put - put object: %w", err))
}
if err := reader.finish(); err != nil {
return Record{}, store.discard(ctx, key, fmt.Errorf("Store.Put - verify stream: %w", err))
}
return Record{
Key: key,
ContentType: contentType,
Size: upload.Size,
SHA256: hex.EncodeToString(reader.sum()),
OriginalName: SanitizeOriginalName(upload.OriginalName),
}, nil
}
// Open streams a file owned by policy. It rejects stored objects that no
// longer satisfy the policy and closes their bodies before returning.
func (store *Store) Open(ctx context.Context, policy Policy, key string) (*File, error) {
if !policy.ownsKey(key) {
return nil, fmt.Errorf("Store.Open - validate key: %w", ErrInvalidKey)
}
object, err := store.storage.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("Store.Open - get object: %w", err)
}
if object.Size < 0 || object.Size > policy.maxSize {
return nil, closeAfter(object.Body, fmt.Errorf("Store.Open - check stored size: %w", ErrTooLarge))
}
contentType, allowed := policy.allow(object.ContentType)
if !allowed {
return nil, closeAfter(object.Body, fmt.Errorf("Store.Open - check stored content type: %w", ErrUnsupportedType))
}
return &File{Size: object.Size, ContentType: contentType, body: object.Body, remaining: object.Size}, nil
}
// Delete removes a file owned by policy. Deleting an absent file succeeds.
func (store *Store) Delete(ctx context.Context, policy Policy, key string) error {
if !policy.ownsKey(key) {
return fmt.Errorf("Store.Delete - validate key: %w", ErrInvalidKey)
}
if err := store.storage.Delete(ctx, key); err != nil {
return fmt.Errorf("Store.Delete - delete object: %w", err)
}
return nil
}
// discard deletes a key after a failed write. Storage may have committed the
// object before the failure was reported, and the caller never learns the key,
// so cleanup runs even when the caller's context is already canceled.
func (store *Store) discard(ctx context.Context, key string, cause error) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if err := store.storage.Delete(ctx, key); err != nil {
return errors.Join(cause, fmt.Errorf("Store.discard - delete failed write: %w", err))
}
return cause
}
func closeAfter(body io.Closer, cause error) error {
if err := body.Close(); err != nil {
return errors.Join(cause, fmt.Errorf("files.closeAfter - close object body: %w", err))
}
return cause
}
@@ -0,0 +1,488 @@
package files
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"regexp"
"strings"
"sync"
"testing"
"testing/iotest"
"lincodex/backend/internal/port/outbound"
)
const testMaxSize = 64
var testKeyPattern = regexp.MustCompile(`^resume/[0-9a-f]{32}$`)
func TestPolicyValidation(t *testing.T) {
for _, test := range []struct {
name string
namespace Namespace
maxSize int64
types []string
}{
{name: "unregistered namespace", namespace: "synthetic", maxSize: 1, types: []string{"application/pdf"}},
{name: "empty namespace", maxSize: 1, types: []string{"application/pdf"}},
{name: "uppercase namespace", namespace: "Resume", maxSize: 1, types: []string{"application/pdf"}},
{name: "path namespace", namespace: "resume/../pdf", maxSize: 1, types: []string{"application/pdf"}},
{name: "leading digit", namespace: "1resume", maxSize: 1, types: []string{"application/pdf"}},
{name: "long namespace", namespace: Namespace(strings.Repeat("a", maxNamespaceLength+1)), maxSize: 1, types: []string{"application/pdf"}},
{name: "zero size", namespace: NamespaceResume, types: []string{"application/pdf"}},
{name: "no types", namespace: NamespaceResume, maxSize: 1},
{name: "wildcard type", namespace: NamespaceResume, maxSize: 1, types: []string{"application/*"}},
{name: "type with parameters", namespace: NamespaceResume, maxSize: 1, types: []string{"text/plain; charset=utf-8"}},
{name: "uppercase type", namespace: NamespaceResume, maxSize: 1, types: []string{"Application/PDF"}},
{name: "malformed type", namespace: NamespaceResume, maxSize: 1, types: []string{"pdf"}},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := NewPolicy(test.namespace, test.maxSize, test.types...); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("invalid policy accepted: %v", err)
}
})
}
policy, err := NewPolicy(NamespaceProfilePDF, 5<<20, "application/pdf")
if err != nil || policy.Namespace() != NamespaceProfilePDF || policy.MaxSize() != 5<<20 {
t.Fatalf("valid policy rejected: %v", err)
}
}
func TestNamespaceFormat(t *testing.T) {
for _, namespace := range []Namespace{"", "Resume", "resume/../pdf", "1resume", "re sume", Namespace(strings.Repeat("a", maxNamespaceLength+1))} {
if validNamespace(namespace) {
t.Fatalf("namespace %q accepted", namespace)
}
}
if !validNamespace("a-1") {
t.Fatal("valid namespace rejected")
}
}
func TestNamespacesAreValidAndUnique(t *testing.T) {
seen := make(map[Namespace]bool, len(registeredNamespaces))
for _, namespace := range registeredNamespaces {
if !validNamespace(namespace) || seen[namespace] {
t.Fatalf("namespace %q is invalid or declared twice", namespace)
}
seen[namespace] = true
}
}
func TestStorePutStreamsRecordAndContent(t *testing.T) {
storage := newFakeStorage()
store := NewStore(storage)
payload := bytes.Repeat([]byte("pdf-bytes"), 5)
digest := sha256.Sum256(payload)
// One byte per read exercises the withheld final chunk on every boundary.
body := iotest.OneByteReader(bytes.NewReader(payload))
record, err := store.Put(t.Context(), testPolicy(t), Upload{
Body: body, Size: int64(len(payload)), ContentType: "Application/PDF; name=evil", OriginalName: `C:\Users\me\..\CV.pdf`,
})
if err != nil {
t.Fatal(err)
}
want := Record{Key: record.Key, ContentType: "application/pdf", Size: int64(len(payload)), SHA256: hex.EncodeToString(digest[:]), OriginalName: "CV.pdf"}
if record != want || !testKeyPattern.MatchString(record.Key) {
t.Fatalf("record = %+v, want %+v with an opaque key", record, want)
}
stored := storage.object(record.Key)
if !bytes.Equal(stored.data, payload) || stored.contentType != "application/pdf" {
t.Fatal("stored object differs from upload")
}
other, err := store.Put(t.Context(), testPolicy(t), Upload{Body: bytes.NewReader(nil), ContentType: "application/pdf"})
if err != nil || other.Key == record.Key || other.Size != 0 || other.SHA256 != hex.EncodeToString(sha256.New().Sum(nil)) {
t.Fatalf("second upload: %+v, %v", other, err)
}
}
func TestStorePutRejectsBeforeWriting(t *testing.T) {
policy := testPolicy(t)
for _, test := range []struct {
name string
policy Policy
upload Upload
want error
}{
{name: "zero policy", upload: Upload{Body: strings.NewReader("x"), Size: 1, ContentType: "application/pdf"}, want: ErrInvalidPolicy},
{name: "nil body", policy: policy, upload: Upload{Size: 1, ContentType: "application/pdf"}, want: ErrInvalidUpload},
{name: "unknown size", policy: policy, upload: Upload{Body: strings.NewReader("x"), Size: -1, ContentType: "application/pdf"}, want: ErrInvalidUpload},
{name: "declared over limit", policy: policy, upload: Upload{Body: strings.NewReader("x"), Size: testMaxSize + 1, ContentType: "application/pdf"}, want: ErrTooLarge},
{name: "type not allowed", policy: policy, upload: Upload{Body: strings.NewReader("x"), Size: 1, ContentType: "text/html"}, want: ErrUnsupportedType},
{name: "malformed type", policy: policy, upload: Upload{Body: strings.NewReader("x"), Size: 1, ContentType: "application/pdf; ="}, want: ErrUnsupportedType},
} {
t.Run(test.name, func(t *testing.T) {
storage := newFakeStorage()
if _, err := NewStore(storage).Put(t.Context(), test.policy, test.upload); !errors.Is(err, test.want) {
t.Fatalf("error = %v, want %v", err, test.want)
}
if storage.puts() != 0 || storage.deletes() != 0 {
t.Fatal("rejected upload reached storage")
}
})
}
}
func TestStorePutAbortsAndDeletesFailedWrites(t *testing.T) {
payload := []byte("0123456789")
sourceErr := errors.New("client disconnected")
for _, test := range []struct {
name string
body io.Reader
size int64
configure func(*fakeStorage)
want error
}{
{name: "longer than declared", body: bytes.NewReader(payload), size: 5, want: ErrTooLarge},
{name: "longer than declared one byte at a time", body: iotest.OneByteReader(bytes.NewReader(payload)), size: 9, want: ErrTooLarge},
{name: "shorter than declared", body: bytes.NewReader(payload), size: 11, want: ErrSizeMismatch},
{name: "source error", body: io.MultiReader(bytes.NewReader(payload[:3]), iotest.ErrReader(sourceErr)), size: 10, want: sourceErr},
{name: "source error after declared size", body: io.MultiReader(bytes.NewReader(payload[:4]), iotest.ErrReader(sourceErr)), size: 4, want: sourceErr},
{
name: "response lost after commit", body: bytes.NewReader(payload), size: 10, want: outbound.ErrObjectStorage,
configure: func(storage *fakeStorage) { storage.putErr = outbound.ErrObjectStorage },
},
{
name: "storage skipped a non-empty body", body: bytes.NewReader(payload), size: 10, want: ErrSizeMismatch,
configure: func(storage *fakeStorage) { storage.skipBody = true },
},
{
name: "storage skipped a body with extra data", body: bytes.NewReader(payload), size: 0, want: ErrTooLarge,
configure: func(storage *fakeStorage) { storage.skipBody = true },
},
} {
t.Run(test.name, func(t *testing.T) {
storage := newFakeStorage()
if test.configure != nil {
test.configure(storage)
}
_, err := NewStore(storage).Put(t.Context(), testPolicy(t), Upload{Body: test.body, Size: test.size, ContentType: "application/pdf"})
if !errors.Is(err, test.want) {
t.Fatalf("error = %v, want %v", err, test.want)
}
if storage.deletes() != 1 || storage.count() != 0 {
t.Fatal("failed write was not deleted")
}
if test.configure == nil && storage.maxReceived() >= test.size && test.size > 0 {
t.Fatal("storage received a complete body for an invalid stream")
}
})
}
}
func TestStorePutCleansUpAfterCallerCancellation(t *testing.T) {
storage := newFakeStorage()
storage.putErr = context.Canceled
ctx, cancel := context.WithCancel(t.Context())
cancel()
_, err := NewStore(storage).Put(ctx, testPolicy(t), Upload{Body: strings.NewReader("data"), Size: 4, ContentType: "application/pdf"})
if !errors.Is(err, context.Canceled) || storage.deletes() != 1 || storage.count() != 0 {
t.Fatalf("canceled write was not cleaned up: %v", err)
}
if storage.deleteContextErr() != nil {
t.Fatal("cleanup used the canceled caller context")
}
}
func TestStorePutReportsCleanupFailure(t *testing.T) {
storage := newFakeStorage()
storage.deleteErr = outbound.ErrObjectStorage
_, err := NewStore(storage).Put(t.Context(), testPolicy(t), Upload{Body: strings.NewReader("too long"), Size: 3, ContentType: "application/pdf"})
if !errors.Is(err, ErrTooLarge) || !errors.Is(err, outbound.ErrObjectStorage) {
t.Fatalf("cleanup failure hidden: %v", err)
}
}
func TestStoreOpenStreamsAndClosesOnEveryPath(t *testing.T) {
policy := testPolicy(t)
key := newKey(NamespaceResume)
for _, test := range []struct {
name string
object fakeObject
want error
}{
{name: "stored size over policy", object: fakeObject{data: make([]byte, testMaxSize+1), contentType: "application/pdf"}, want: ErrTooLarge},
{name: "stored type not allowed", object: fakeObject{data: []byte("x"), contentType: "text/html"}, want: ErrUnsupportedType},
} {
t.Run(test.name, func(t *testing.T) {
storage := newFakeStorage()
storage.put(key, test.object)
if _, err := NewStore(storage).Open(t.Context(), policy, key); !errors.Is(err, test.want) {
t.Fatalf("error = %v, want %v", err, test.want)
}
if !storage.allBodiesClosed() {
t.Fatal("rejected object body was not closed")
}
})
}
t.Run("success", func(t *testing.T) {
storage := newFakeStorage()
storage.put(key, fakeObject{data: []byte("pdf"), contentType: "application/pdf"})
file, err := NewStore(storage).Open(t.Context(), policy, key)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(file)
if err != nil || string(data) != "pdf" || file.Size != 3 || file.ContentType != "application/pdf" {
t.Fatalf("file = %q %d %q, %v", data, file.Size, file.ContentType, err)
}
if storage.allBodiesClosed() {
t.Fatal("body closed before the caller closed the file")
}
if err := file.Close(); err != nil || file.Close() != nil || !storage.allBodiesClosed() {
t.Fatalf("close: %v", err)
}
if _, err := file.Read(make([]byte, 1)); err == nil {
t.Fatal("read after close succeeded")
}
})
t.Run("missing", func(t *testing.T) {
if _, err := NewStore(newFakeStorage()).Open(t.Context(), policy, key); !errors.Is(err, ErrNotFound) {
t.Fatalf("missing file: %v", err)
}
})
}
func TestFileRejectsBodyThatDiffersFromSize(t *testing.T) {
for _, test := range []struct {
name string
body string
size int64
want error
}{
{name: "longer", body: "abcdef", size: 3, want: ErrSizeMismatch},
{name: "shorter", body: "ab", size: 3, want: io.ErrUnexpectedEOF},
} {
t.Run(test.name, func(t *testing.T) {
file := &File{Size: test.size, body: io.NopCloser(strings.NewReader(test.body)), remaining: test.size}
if _, err := io.ReadAll(file); !errors.Is(err, test.want) {
t.Fatalf("error = %v, want %v", err, test.want)
}
})
}
}
func TestStoreRejectsKeysOutsidePolicy(t *testing.T) {
policy := testPolicy(t)
valid := newKey(NamespaceResume)
for _, key := range []string{
"", "resume", "resume/", "/" + valid, "../" + valid, "resume/../pdf/" + valid[len("resume/"):],
newKey(NamespaceProfilePDF), strings.ToUpper(valid), valid + "/x", valid[:len(valid)-1], "resume/CV.pdf",
} {
t.Run(key, func(t *testing.T) {
storage := newFakeStorage()
store := NewStore(storage)
if _, err := store.Open(t.Context(), policy, key); !errors.Is(err, ErrInvalidKey) {
t.Fatalf("Open accepted %q: %v", key, err)
}
if err := store.Delete(t.Context(), policy, key); !errors.Is(err, ErrInvalidKey) {
t.Fatalf("Delete accepted %q: %v", key, err)
}
if storage.gets() != 0 || storage.deletes() != 0 {
t.Fatal("invalid key reached storage")
}
})
}
}
func TestStoreDeleteIsIdempotent(t *testing.T) {
storage := newFakeStorage()
store := NewStore(storage)
key := newKey(NamespaceResume)
storage.put(key, fakeObject{data: []byte("x"), contentType: "application/pdf"})
for range 2 {
if err := store.Delete(t.Context(), testPolicy(t), key); err != nil {
t.Fatal(err)
}
}
if storage.count() != 0 {
t.Fatal("object was not deleted")
}
storage.deleteErr = outbound.ErrObjectStorage
if err := store.Delete(t.Context(), testPolicy(t), key); !errors.Is(err, outbound.ErrObjectStorage) {
t.Fatalf("storage failure hidden: %v", err)
}
}
func TestSanitizeOriginalName(t *testing.T) {
longStem := strings.Repeat("я", maxOriginalNameBytes)
for _, test := range []struct{ name, input, want string }{
{name: "plain", input: "Resume 2026.pdf", want: "Resume 2026.pdf"},
{name: "unix traversal", input: "../../etc/passwd", want: "passwd"},
{name: "windows path", input: `C:\Users\me\CV.pdf`, want: "CV.pdf"},
{name: "control characters", input: "cv\x00\r\n\t.pdf", want: "cv.pdf"},
{name: "bidirectional override", input: "cv\u202efdp.exe", want: "cvfdp.exe"},
{name: "invalid UTF-8", input: "cv\xff\xfe.pdf", want: "cv.pdf"},
{name: "dots and spaces", input: " ..hidden.pdf. ", want: "hidden.pdf"},
{name: "only dots", input: "..", want: ""},
{name: "trailing separator", input: "dir/", want: ""},
{name: "empty", input: "", want: ""},
{name: "long name keeps extension", input: longStem + ".pdf", want: strings.Repeat("я", (maxOriginalNameBytes-len(".pdf"))/2) + ".pdf"},
{name: "line and paragraph separators", input: "cv\u2028\u2029.pdf", want: "cv.pdf"},
{name: "private use", input: "cv\ue000\U000F0000.pdf", want: "cv.pdf"},
{name: "cut exposes trailing dot", input: strings.Repeat("a", maxOriginalNameBytes-len(".pdf")-1) + ".. tail.pdf", want: strings.Repeat("a", maxOriginalNameBytes-len(".pdf")-1) + ".pdf"},
{name: "cut exposes trailing space", input: strings.Repeat("a", maxOriginalNameBytes-len(".pdf")-1) + " tail.pdf", want: strings.Repeat("a", maxOriginalNameBytes-len(".pdf")-1) + ".pdf"},
} {
t.Run(test.name, func(t *testing.T) {
got := SanitizeOriginalName(test.input)
if got != test.want || len(got) > maxOriginalNameBytes {
t.Fatalf("SanitizeOriginalName(%q) = %q, want %q", test.input, got, test.want)
}
})
}
}
func testPolicy(t *testing.T) Policy {
t.Helper()
policy, err := NewPolicy(NamespaceResume, testMaxSize, "application/pdf")
if err != nil {
t.Fatal(err)
}
return policy
}
type fakeObject struct {
data []byte
contentType string
}
// fakeStorage models an HTTP object store: it commits an object as soon as it
// receives the declared number of bytes, even if the request fails later.
type fakeStorage struct {
mu sync.Mutex
objects map[string]fakeObject
bodies []*trackedBody
putCount int
getCount int
deleteCount int
received int64
putErr error
deleteErr error
skipBody bool
deleteCtx error
}
var _ outbound.ObjectStorage = (*fakeStorage)(nil)
func newFakeStorage() *fakeStorage { return &fakeStorage{objects: map[string]fakeObject{}} }
func (storage *fakeStorage) Put(_ context.Context, key string, body io.Reader, size int64, contentType string) error {
storage.mu.Lock()
storage.putCount++
storage.mu.Unlock()
if storage.skipBody {
storage.put(key, fakeObject{contentType: contentType})
return storage.putErr
}
data, err := io.ReadAll(io.LimitReader(body, size))
storage.mu.Lock()
storage.received = max(storage.received, int64(len(data)))
storage.mu.Unlock()
if err != nil || int64(len(data)) < size {
return outbound.ErrObjectStorage
}
storage.put(key, fakeObject{data: data, contentType: contentType})
if _, err := io.Copy(io.Discard, body); err != nil {
return outbound.ErrObjectStorage
}
return storage.putErr
}
func (storage *fakeStorage) Get(_ context.Context, key string) (outbound.Object, error) {
storage.mu.Lock()
defer storage.mu.Unlock()
storage.getCount++
object, ok := storage.objects[key]
if !ok {
return outbound.Object{}, outbound.ErrObjectNotFound
}
body := &trackedBody{Reader: bytes.NewReader(object.data)}
storage.bodies = append(storage.bodies, body)
return outbound.Object{Body: body, Size: int64(len(object.data)), ContentType: object.contentType}, nil
}
func (storage *fakeStorage) Delete(ctx context.Context, key string) error {
storage.mu.Lock()
defer storage.mu.Unlock()
storage.deleteCount++
storage.deleteCtx = ctx.Err()
if storage.deleteErr != nil {
return storage.deleteErr
}
delete(storage.objects, key)
return nil
}
func (storage *fakeStorage) put(key string, object fakeObject) {
storage.mu.Lock()
defer storage.mu.Unlock()
storage.objects[key] = object
}
func (storage *fakeStorage) object(key string) fakeObject {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.objects[key]
}
func (storage *fakeStorage) count() int {
storage.mu.Lock()
defer storage.mu.Unlock()
return len(storage.objects)
}
func (storage *fakeStorage) puts() int {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.putCount
}
func (storage *fakeStorage) gets() int {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.getCount
}
func (storage *fakeStorage) deletes() int {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.deleteCount
}
func (storage *fakeStorage) maxReceived() int64 {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.received
}
func (storage *fakeStorage) deleteContextErr() error {
storage.mu.Lock()
defer storage.mu.Unlock()
return storage.deleteCtx
}
func (storage *fakeStorage) allBodiesClosed() bool {
storage.mu.Lock()
defer storage.mu.Unlock()
for _, body := range storage.bodies {
if !body.closed {
return false
}
}
return len(storage.bodies) > 0
}
type trackedBody struct {
io.Reader
closed bool
}
func (body *trackedBody) Close() error {
body.closed = true
return nil
}
+172
View File
@@ -0,0 +1,172 @@
package files
import (
"crypto/sha256"
"errors"
"fmt"
"hash"
"io"
)
// maxEmptyReads bounds reads that return neither data nor an error.
const maxEmptyReads = 100
// uploadReader gives storage exactly the declared number of bytes and hashes
// them on the way. It withholds the last chunk until the source has ended, so
// a longer source never lets storage receive a complete request body. A short
// source ends the stream early with an error. Storage errors are sanitized,
// so the first violation is kept in err for the caller.
type uploadReader struct {
source io.Reader
limited *io.LimitedReader
hash hash.Hash
ended bool
err error
}
func newUploadReader(source io.Reader, size int64) *uploadReader {
return &uploadReader{source: source, limited: &io.LimitedReader{R: source, N: size}, hash: sha256.New()}
}
func (reader *uploadReader) Read(buffer []byte) (int, error) {
if reader.err != nil {
return 0, reader.err
}
if reader.ended {
return 0, io.EOF
}
if reader.limited.N == 0 {
if err := reader.confirmEnd(); err != nil {
return 0, err
}
return 0, io.EOF
}
n, err := reader.limited.Read(buffer)
if err != nil && !errors.Is(err, io.EOF) {
reader.err = fmt.Errorf("files.uploadReader - read source: %w", err)
return n, reader.err
}
if reader.limited.N > 0 {
if errors.Is(err, io.EOF) {
reader.err = fmt.Errorf("files.uploadReader - source ended early: %w", ErrSizeMismatch)
return n, reader.err
}
reader.hash.Write(buffer[:n])
return n, nil
}
// The declared size is reached. Release the final chunk only when the
// source has nothing more.
if !errors.Is(err, io.EOF) {
if endErr := reader.confirmEnd(); endErr != nil {
return 0, endErr
}
}
reader.ended = true
reader.hash.Write(buffer[:n])
return n, nil
}
// confirmEnd reads one byte past the declared size from the source.
func (reader *uploadReader) confirmEnd() error {
var probe [1]byte
for range maxEmptyReads {
n, err := reader.source.Read(probe[:])
switch {
case n > 0:
reader.err = fmt.Errorf("files.uploadReader - source exceeds declared size: %w", ErrTooLarge)
return reader.err
case errors.Is(err, io.EOF):
reader.ended = true
return nil
case err != nil:
reader.err = fmt.Errorf("files.uploadReader - read source: %w", err)
return reader.err
}
}
reader.err = fmt.Errorf("files.uploadReader - read source: %w", io.ErrNoProgress)
return reader.err
}
// finish verifies the whole source after storage reported success. Storage
// may skip reading an empty body, so the end is confirmed here when needed.
func (reader *uploadReader) finish() error {
if reader.err != nil {
return reader.err
}
if reader.limited.N != 0 {
return fmt.Errorf("files.uploadReader - storage did not consume the body: %w", ErrSizeMismatch)
}
if reader.ended {
return nil
}
return reader.confirmEnd()
}
func (reader *uploadReader) sum() []byte { return reader.hash.Sum(nil) }
// File is an open stored file. The caller must close it, including after a
// read error. The context passed to Open is the only time bound on reading:
// storage limits connection setup and the wait for response headers, not the
// body, so the caller sets a deadline that fits the file size and its client,
// and canceling that context aborts reading. Read fails when the stored body
// is shorter or longer than Size.
type File struct {
Size int64
ContentType string
body io.ReadCloser
remaining int64
ended bool
closed bool
}
func (file *File) Read(buffer []byte) (int, error) {
if file.closed {
return 0, fmt.Errorf("File.Read - read closed file: %w", io.ErrClosedPipe)
}
if file.ended {
return 0, io.EOF
}
if file.remaining == 0 {
return 0, file.confirmEnd()
}
if int64(len(buffer)) > file.remaining {
buffer = buffer[:file.remaining]
}
n, err := file.body.Read(buffer)
file.remaining -= int64(n)
if errors.Is(err, io.EOF) {
if file.remaining > 0 {
return n, fmt.Errorf("File.Read - stored body ended early: %w", io.ErrUnexpectedEOF)
}
file.ended = true
return n, nil
}
return n, err
}
func (file *File) confirmEnd() error {
var probe [1]byte
for range maxEmptyReads {
n, err := file.body.Read(probe[:])
switch {
case n > 0:
return fmt.Errorf("File.Read - stored body exceeds its size: %w", ErrSizeMismatch)
case errors.Is(err, io.EOF):
file.ended = true
return io.EOF
case err != nil:
return err
}
}
return fmt.Errorf("File.Read - read stored body: %w", io.ErrNoProgress)
}
// Close releases the storage response. Repeated calls return nil.
func (file *File) Close() error {
if file.closed {
return nil
}
file.closed = true
return file.body.Close()
}
@@ -63,6 +63,8 @@ services:
networks:
- observability
- app
# SeaweedFS metrics listen only on the storage network.
- storage
restart: unless-stopped
logging:
driver: json-file
@@ -296,6 +298,9 @@ networks:
app:
name: ${APP_NETWORK:-app_default}
external: true
storage:
name: ${APP_STORAGE_NETWORK:-${APP_PROJECT:-app}_storage}
external: true
observability:
internal: true
+29 -1
View File
@@ -62,11 +62,30 @@ services:
seaweedfs:
image: chrislusf/seaweedfs:latest
# The storage network is the primary boundary: besides S3, mini serves
# unauthenticated gRPC (master, filer, volume, S3), an admin server, and
# HTTP APIs that ignore S3 credentials, so only the backend and the
# monitoring Prometheus may join it. S3 requires the access key below;
# -s3.iam=false only removes the IAM management API. As defense in depth,
# each start sets fresh random JWT keys that never leave the container
# (filer and volume HTTP requests need a token), and -whiteList limits
# master and volume HTTP to in-container callers. "@" is the peer of the
# local gRPC sockets that mini uses between its components.
entrypoint:
- /bin/sh
- -ec
- |
for name in WEED_JWT_SIGNING_KEY WEED_JWT_SIGNING_READ_KEY WEED_JWT_FILER_SIGNING_KEY WEED_JWT_FILER_SIGNING_READ_KEY; do
export "$$name=$$(head -c 32 /dev/urandom | base64)"
done
exec /entrypoint.sh "$$@"
- seaweedfs
command:
- mini
- -dir=/data
- -ip=seaweedfs
- -ip=127.0.0.1
- -ip.bind=0.0.0.0
- -whiteList=127.0.0.1,@
- -webdav=false
- -admin.ui=false
- -s3.iam=false
@@ -82,6 +101,8 @@ services:
S3_BUCKET: ${SEAWEEDFS_BUCKET:?Set SEAWEEDFS_BUCKET in the root .env file}
volumes:
- seaweedfs_data:/data
networks:
- storage
expose:
- "8333"
- "9327"
@@ -215,6 +236,9 @@ services:
condition: service_healthy
seaweedfs:
condition: service_healthy
networks:
- default
- storage
expose:
- "8080"
- "9090"
@@ -278,3 +302,7 @@ volumes:
networks:
default:
name: ${APP_NETWORK:-app_default}
# Only SeaweedFS, the backend, and the monitoring Prometheus join it.
storage:
name: ${APP_STORAGE_NETWORK:-${APP_PROJECT:-app}_storage}
internal: true
+7 -4
View File
@@ -21,6 +21,7 @@ spec_dir="${E2E_SPEC_DIR:-$frontend_dir/e2e}"
suffix=$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')
project="lincodex-e2e-$suffix"
network="${project}_default"
storage_network="${project}_storage"
env_file=""
started=0
@@ -61,7 +62,7 @@ done < <(env)
compose() {
env -i "${docker_env[@]}" \
APP_PROJECT="$project" APP_NETWORK="$network" \
APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \
PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \
E2E_UID="$(id -u)" E2E_GID="$(id -g)" \
E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" \
@@ -78,9 +79,11 @@ for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}
fail "Refusing to use existing E2E volume $volume."
fi
done
if docker network inspect "$network" >/dev/null 2>&1; then
fail "Refusing to use existing E2E network $network."
fi
for existing in "$network" "$storage_network"; do
if docker network inspect "$existing" >/dev/null 2>&1; then
fail "Refusing to use existing E2E network $existing."
fi
done
if [[ -n "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ]]; then
fail "Refusing to use existing Compose project $project."
fi
+41 -6
View File
@@ -8,12 +8,13 @@ project=lincodex-smoke
app_network="${project}_default"
port=18080
network="${project}_default"
storage_network="${project}_storage"
started=0
# The smoke stack sends no mail: it uses EMAIL_PROVIDER=disabled from
# .env.example and points mail links at its own loopback port.
compose() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_HTTP_PORT="$port" \
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \
APP_PUBLIC_URL="http://localhost:$port" docker compose \
--env-file "$env_file" \
-p "$project" \
@@ -27,10 +28,12 @@ for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}
exit 2
fi
done
if docker network inspect "$network" >/dev/null 2>&1; then
printf 'Refusing to use existing smoke network %s.\n' "$network" >&2
exit 2
fi
for existing in "$network" "$storage_network"; do
if docker network inspect "$existing" >/dev/null 2>&1; then
printf 'Refusing to use existing smoke network %s.\n' "$existing" >&2
exit 2
fi
done
for dockerfile in "$root/backend/Dockerfile" "$root/frontend/Dockerfile"; do
if [[ ! -f "$dockerfile" ]]; then
printf 'Missing required build file %s.\n' "$dockerfile" >&2
@@ -121,6 +124,38 @@ if [[ "$anonymous" != *"403 Forbidden"* ]]; then
printf 'SeaweedFS did not reject anonymous bucket access: %s\n' "$anonymous" >&2
exit 1
fi
# The storage network is the primary boundary. The frontend stands in for
# every other core container: it must neither resolve nor reach SeaweedFS, by
# name or by its storage address. A DNS or connection failure is a pass.
storage_address=$(docker inspect -f "{{(index .NetworkSettings.Networks \"$storage_network\").IPAddress}}" "$(compose ps -q seaweedfs)")
if [[ -z "$storage_address" ]]; then
printf 'SeaweedFS has no address on %s.\n' "$storage_network" >&2
exit 1
fi
for url in "http://seaweedfs:8333/" "http://$storage_address:8333/"; do
isolation=$(compose exec -T frontend wget -T 5 -S -O /dev/null "$url" 2>&1 || true)
if [[ "$isolation" == *"HTTP/"* ]]; then
printf 'The frontend reached SeaweedFS outside the storage network at %s: %s\n' "$url" "$isolation" >&2
exit 1
fi
done
# Defense in depth inside the storage network. Requests to the container's own
# storage address do not come from loopback, so they stand in for another
# member of that network; the filer, master, and volume HTTP APIs answer 401.
compose exec -T seaweedfs sh -ec '
expect_unauthorized() {
response=$(wget -S -O /dev/null "$1" 2>&1 || true)
case "$response" in
*"401 Unauthorized"*) ;;
*) printf "SeaweedFS %s did not return 401: %s\n" "$1" "$response" >&2; exit 1 ;;
esac
}
expect_unauthorized http://seaweedfs:8888/buckets/
expect_unauthorized http://seaweedfs:9333/dir/assign
fid=$(wget -q -O - http://127.0.0.1:9333/dir/assign | sed -n "s/.*\"fid\":\"\([^\"]*\)\".*/\1/p")
test -n "$fid"
expect_unauthorized "http://seaweedfs:9340/$fid"
'
compose stop seaweedfs
readiness=$(compose exec -T frontend wget -S -O /dev/null http://backend:8080/readyz 2>&1 || true)
if [[ "$readiness" != *"503 Service Unavailable"* ]]; then
@@ -130,4 +165,4 @@ fi
curl --fail --silent --show-error "http://127.0.0.1:$port/api/v1/healthz" >/dev/null
compose up -d --wait --wait-timeout 90 seaweedfs
wait_for_readiness
printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication, and the disabled mail transport.'
printf '%s\n' 'Technical smoke passed: frontend, API routing, PostgreSQL, Redis, SeaweedFS, dependency recovery, storage authentication and network isolation, and the disabled mail transport.'
+17 -2
View File
@@ -48,10 +48,24 @@ PostgreSQL with pgx, sqlc, and goose is the database stack. Developers own SQL;
Redis is part of the core Compose project and connects through `backend/internal/adapter/secondary/redis/` to the outbound cache port. The adapter provides Get/Set/Del with TTL; bootstrap manages client construction and cleanup. The internal /readyz requires PostgreSQL, Redis, and the SeaweedFS bucket to be available. The cache is not a source of truth: future consumers must tolerate key eviction and Redis restarts. Profile, search, resume, and other product caching rules are not implemented yet.
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. Resume uploads, authorization, content limits, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
SeaweedFS runs as a separate server in the core Compose project. `backend/internal/adapter/secondary/seaweedfs/` implements the outbound `ObjectStorage` port through AWS SDK for Go v2: streaming Put/Get and object deletion. SDK and S3 types remain inside the adapter. Bootstrap creates the client; readiness checks the bucket through HeadBucket. Storage stays private to the Docker network; Nginx does not serve its files directly. The shared file layer and the access controls of the SeaweedFS container are described in [Private file storage](#private-file-storage). Resume uploads, authorization, product content rules, and PDF delivery remain future product workflows. The single-node Compose setup persists data and metadata in a volume but provides no HA or off-host backup.
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; no product consumer is registered yet. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
### Private file storage
`backend/internal/usecase/files/` is the shared private file layer over the `ObjectStorage` port. It holds technical rules only. A feature package (resume upload, import, PDF generation, document jobs, exports) defines a `Policy` with a namespace, a size limit in bytes, and exact media types, and owns every product rule: who may read or delete a file, page counts, content inspection, parsing, and retention. The layer is not wired into bootstrap until the first such feature uses it. Namespaces are declared in one place, `namespace.go`, and `NewPolicy` accepts no other value, so two features cannot share a namespace by accident.
- Keys have the form `<namespace>/<32 hex characters>` from 128 random bits. Only the validated policy namespace comes from code; file names and other client input never become part of a key. `Open` and `Delete` accept only keys of their policy's namespace and format, so a client-shaped key, a traversal path, or another feature's key is rejected before storage is called.
- Writes take the exact size. A declared size above the policy limit is rejected before any request. The stream passes through an `io.LimitReader` guard that withholds the last chunk until the source has ended, so a longer or shorter source aborts the request before storage receives a complete body. Any failure after the write started deletes the key, also after caller cancellation. Sources of unknown length are not buffered; a feature that needs them must spool to a bounded temporary file or add multipart upload. The source needs its own deadline, such as `http.ResponseController.SetReadDeadline` on a request body: `Put` waits for a blocked read, and canceling the context does not interrupt it.
- `Put` returns a `Record`: the key, the bare media type, the size, the SHA-256 digest computed while streaming, and the sanitized original name. The layer keeps no index and adds no tables. Callers follow one order: `Put`, then persist the record with their ownership data in a database transaction, then `Delete` the key if that transaction fails. One race remains: when the whole body was sent before the caller canceled, the server may commit after the cleanup `Delete` returned. Such orphans have no record and no request reaches them; a namespace sweeper that removes keys without a record is planned together with backups and exports (TASK-030, TASK-458) and does not exist yet. The original name is display metadata only: it is not stored in SeaweedFS and is never used in keys or logs, but it may still contain personal data. Sanitizing removes path elements, control, format, separator, and private-use characters and does not normalize Unicode. The content type is declared by the caller; detection by content belongs to the document parser.
- `Open` checks that the stored object still fits the policy and closes the response on every rejection. The caller closes the returned `File`; reading fails when the body differs from the stored size. The adapter's `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, and the wait for response headers, not the body transfer of `Put` and `Get`, so the caller's context is the only bound on a long or slow stream. `Delete` is idempotent, and absence maps to `files.ErrNotFound`.
- There are no public URLs. The layer creates no public, permanent, or presigned URLs, and the bucket has no public policy or anonymous ACL. A browser download must go through an authenticated backend endpoint that checks current access and streams `File` with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, so a stored file is never rendered as a page of the application origin. The key, bucket, and storage URL never reach clients.
SeaweedFS access. The primary control is the network: SeaweedFS joins only the internal `storage` Compose network, which the backend and the monitoring Prometheus (for the metrics on port 9327) also join. The frontend, PostgreSQL, Redis, Kafka, and other containers cannot resolve or reach it. This matters because `mini` serves much more than S3. The S3 gateway requires SigV4 credentials: the container's `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` create its only identity, `-s3.iam=false` removes only the IAM management API, and Compose refuses empty credentials because SeaweedFS without any identity accepts anonymous S3 requests. The other listeners do not use S3 credentials: the filer (8888), master (9333), and volume (9340) HTTP APIs; unauthenticated gRPC on 18888, 19333, 19340, and 18333 with server reflection; and an admin server on 23646 with worker gRPC on 33646 that `-admin.ui=false` does not stop and that `mini` cannot disable. Defense in depth inside the storage network: each start sets fresh random JWT signing keys for the filer and volume HTTP APIs, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to callers inside the container. The upstream filer ignores its IP whitelist, so the JWT is its only HTTP control.
Remaining risk, limited to members of the storage network, which today means the backend (and Prometheus): they can reach the unauthenticated gRPC ports 19333, 18888, and 18333 and the admin ports 23646 and 33646. Master gRPC `Assign` returns a file ID with a signed volume write token, filer gRPC `ListEntries` returns object metadata, and entry changes through filer gRPC should be treated as possible. Volume gRPC 19340 refuses such callers. Integration tests verify that a volume write with a token from `Assign` is refused from outside the container (HTTP 401, whitelist) and that a volume read without a token is refused; this was not verified for the admin and worker ports. Low-priority disclosure inside the same network: the master UI and `/cluster/status` and the volume `/status` reveal topology and disk usage. A compromised backend already holds the S3 credentials, so these paths add little for it; any new member of the storage network widens the risk. gRPC mutual TLS would close the gRPC paths and is not configured.
### Transactional outbox
Implemented: migration `backend/db/migrations/00001_create_outbox_events.sql` creates `outbox_events`. Columns:
@@ -385,6 +399,7 @@ backend/
port/inbound/ readiness and event handler input boundaries
usecase/identity/ password validation before hashing (Credentials)
usecase/policy/ publication of policy versions and the demo policy seed
usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums
usecase/notification/ mail requests and the consumer that stores them as deliveries
usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, policy, password hashing, and mail boundaries
@@ -418,7 +433,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with no registered product handler, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with no registered product handler, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
+7 -1
View File
@@ -37,7 +37,13 @@ SeaweedFS uses `chrislusf/seaweedfs:latest` with `weed mini`: master, volume, fi
Set `SEAWEEDFS_ACCESS_KEY` and `SEAWEEDFS_SECRET_KEY` in `.env`, replacing the example values. Compose passes them to the server as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, and passes `SEAWEEDFS_BUCKET` as `S3_BUCKET` to initialize the bucket at startup. This is one administrative credential pair for the local stack, not production service-level access separation. Never provide it to browser clients.
Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION`, and `SEAWEEDFS_TIMEOUT`. Compose supplies endpoint `http://seaweedfs:8333`; a directly launched Go process defaults to `http://localhost:8333`, bucket `lincodex`, region `us-east-1`, and timeout `10s`. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it.
SeaweedFS joins only the internal `storage` network (`APP_STORAGE_NETWORK`, by default `<APP_PROJECT>_storage`). The backend joins it and the default network; the monitoring Prometheus joins it to scrape port 9327, so start the core project before monitoring. No other container can resolve or reach SeaweedFS. This network is the primary control, because the container also serves filer, master, volume, and admin APIs and unauthenticated gRPC that ignore S3 credentials; see [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage) for the list and the remaining risk. Do not add other services to the storage network.
The S3 credentials make S3 itself private: SeaweedFS answers unsigned S3 requests with 403, and Compose refuses to start with empty values because SeaweedFS without any identity accepts anonymous S3 requests. `-s3.iam=false` removes only the IAM management API. As defense in depth, the service entrypoint exports fresh random `WEED_JWT_*` signing keys at every start, so filer and volume HTTP requests need a token that never leaves the container, and `-ip=127.0.0.1` with `-whiteList=127.0.0.1,@` limits master and volume HTTP to in-container callers. The keys are not configuration and need no rotation; restarting the container replaces them. Smoke checks that the frontend cannot reach SeaweedFS by name or by its storage address, that S3 refuses an unsigned request, and that the filer, master, and volume HTTP APIs refuse a caller that is not inside the container.
The stack publishes no object URLs. The bucket has no public read policy or anonymous ACL, and the backend creates no public or presigned links; future downloads go through an authenticated backend endpoint that streams the file. Size and content type limits are per feature policy in `backend/internal/usecase/files/` rather than deployment settings, so there is no extra environment variable. Keep the Nginx request body limit from the upload route aligned with the largest policy when such a route is added.
Backend settings are `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION`, and `SEAWEEDFS_TIMEOUT`. Compose supplies endpoint `http://seaweedfs:8333`; a directly launched Go process defaults to `http://localhost:8333`, bucket `lincodex`, region `us-east-1`, and timeout `10s`. `SEAWEEDFS_TIMEOUT` bounds connection setup, the TLS handshake, the wait for response headers, and whole deletion and readiness calls; it does not bound object upload or download bodies, which follow the caller's context. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it.
Ordinary `down` preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups.
+18 -2
View File
@@ -38,11 +38,11 @@ Security checks run separately: `make -C security check` scans source/dependenci
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product event producer in Kafka (the mail delivery consumer is exercised only by tests), and no real model inference to validate as product behavior.
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product event producer in Kafka (the mail delivery consumer is exercised only by tests), and no real model inference to validate as product behavior.
API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub.
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application.
## Browser E2E suite
@@ -72,6 +72,22 @@ Kafka is not part of `bootstrap(t)` and starts only for tests that select `boots
`kafka_helpers_test.go` contains the helpers. `env.createKafkaTopic(ctx, t, partitions)` creates a topic with a unique random name and registers its deletion in `t.Cleanup` before creation, so the topic is removed even when the test fails. The broker never creates topics on demand: a test creates every topic it uses. `env.newKafkaClient(t, options...)` returns a `kgo` client that closes when `t` finishes. `produceKafkaRecords` and `env.consumeKafkaRecords` have bounded timeouts; the consumer reads partitions from the start without a consumer group, so no group offsets remain. The container is terminated in the cleanup of the test that called bootstrap, including after a failure. `env.pauseKafka(ctx, t)` freezes the broker with `docker pause` and returns a function that resumes it; cleanup also resumes it. A paused broker keeps its port and accepts connections but never answers, which models a hung broker. A stopped and restarted container would get a new host port that neither the advertised listener nor the clients follow, and its tmpfs topics would be gone.
## Private file storage tests
Unit tests in `backend/internal/usecase/files/` use an in-memory storage fake that, like an HTTP object store, commits an object as soon as it receives the declared number of bytes. They cover policy validation, key format and rejection of keys from other namespaces or shaped by clients, name sanitizing, the declared size limit, a source that is longer or shorter than declared (storage never receives a complete body and the key is deleted), cleanup after caller cancellation and after a lost response, a reported cleanup failure, the SHA-256 digest, a stored body that differs from its size, idempotent deletion, closing of the response on every `Open` rejection, and unique, valid declared namespaces. Adapter tests in `backend/internal/adapter/secondary/seaweedfs/` check that an upload and a download that last longer than `SEAWEEDFS_TIMEOUT` complete, while stalled response headers and an unreachable endpoint still fail within that bound.
The SeaweedFS bootstrap uses the same entrypoint and flags as Compose and also publishes the filer, master, and volume ports so tests can probe them. It does not model the Compose storage network; smoke checks that boundary. `TestPrivateFileStoreAgainstSeaweedFS` in `backend/integration_test/files_store_test.go` uses `bootstrap(t, seaweedfsService)` and the real adapter:
- writes and reads a synthetic object and an empty one, checking content, size, type, and digest;
- sends unsigned requests and expects 403 from S3 for object reads (also with a presign-like query), bucket listing, upload, and deletion, and 401 from the filer for object reads, listing, and upload and from the master for volume assignment and collection deletion; the object stays readable afterwards;
- assigns a file ID inside the container and expects 401 from the volume for a read without a token and for a write with the signed token that the master returned;
- checks that a wrong secret cannot open, upload, or delete files and is not reported as absence;
- opens, partly reads, and closes the object more times than the adapter's connection limit with a long storage timeout, so a leaked response body would block the loop;
- rejects uploads over the limit or past or short of the declared size and lists the namespace through a separate signed client to show that no partial object remains;
- deletes the object twice and then gets `files.ErrNotFound`.
The probes run from the host through published ports, so requests do not come from inside the SeaweedFS container, as for another member of the storage network. The gRPC and admin ports are not probed; their remaining exposure is described in [ARCHITECTURE.md](ARCHITECTURE.md#private-file-storage).
## Outbox relay tests
Unit tests (`make -C backend test`) cover the record envelope, key, and headers and an invalid payload that is not quoted in the error (`internal/adapter/secondary/kafka/`), a publish and a topic creation that fail within the produce timeout plus a 2-second scheduling margin when the broker is unreachable (the tests assert the elapsed time), the mapping of an unknown topic to `ErrEventDestinationMissing`, the comparison of an existing topic with the configured layout, the shared backoff schedule with and without jitter (`internal/worker/retry/`), relay passes that mark only acknowledged events, retries after failed `Prepare` calls and passes, no backoff after a pass that published part of its batch while a poison event leads every batch, a new `Prepare` after a missing destination, at most one backlog read per interval, a pass in progress that finishes after cancellation, a pass canceled by the shutdown timeout, a stop during backoff (`internal/worker/outboxrelay/`), the relay and topic settings, including the broker-default replication factor and `min.insync.replicas` (`config/`), SQLSTATE-only database errors and timeouts that would round to no limit (`internal/adapter/secondary/postgres/`), the relay counter and backlog gauges, and an application that runs the relay while serving and stops it with the servers (`internal/bootstrap/`).
+17 -2
View File
@@ -48,10 +48,24 @@ PostgreSQL с pgx, sqlc и goose остается основной базой. S
Redis входит в основной Compose и подключен через `backend/internal/adapter/secondary/redis/` к outbound-порту кеша. Адаптер предоставляет Get/Set/Del с TTL, а bootstrap управляет подключением и закрытием клиента. Внутренний /readyz требует доступности PostgreSQL, Redis и bucket SeaweedFS. Кеш не является источником истины: вытеснение ключей и перезапуск Redis должны быть допустимы для будущих потребителей. Кеширование профилей, поиска, резюме и другие продуктовые правила еще не реализованы.
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Загрузка резюме, проверка прав, ограничения содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
SeaweedFS работает отдельным сервером в основном Compose. `backend/internal/adapter/secondary/seaweedfs/` реализует outbound-порт `ObjectStorage` через AWS SDK for Go v2: потоковые Put/Get и удаление объекта. SDK и S3-типы не выходят за границу адаптера. Bootstrap создает клиент, readiness проверяет bucket через HeadBucket. Хранилище закрыто внутри Docker-сети; Nginx не раздает его файлы напрямую. Общий файловый слой и контроль доступа в контейнере SeaweedFS описаны в разделе [Закрытое файловое хранилище](#закрытое-файловое-хранилище). Загрузка резюме, проверка прав, продуктовые правила содержимого и выдача PDF остаются будущими продуктовыми сценариями. Одноузловой Compose сохраняет данные и метаданные в volume, но не обеспечивает HA или внешнее резервное копирование.
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; продуктовые обработчики пока не зарегистрированы. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
### Закрытое файловое хранилище
`backend/internal/usecase/files/` - общий закрытый файловый слой поверх порта `ObjectStorage`. Он содержит только технические правила. Продуктовый пакет (загрузка резюме, импорт, генерация PDF, задания по документам, выгрузки) задает `Policy` с namespace, лимитом размера в байтах и точными media types и отвечает за все продуктовые правила: кто может читать или удалять файл, число страниц, проверку содержимого, разбор и сроки хранения. Слой не подключен в bootstrap, пока его не использует первый такой сценарий. Namespace объявляются в одном месте, `namespace.go`, и `NewPolicy` не принимает других значений, поэтому два сценария не могут случайно использовать один namespace.
- Ключ имеет вид `<namespace>/<32 hex-символа>` из 128 случайных бит. Из кода приходит только проверенный namespace политики; имена файлов и другой ввод клиента никогда не попадают в ключ. `Open` и `Delete` принимают только ключи namespace и формата своей политики, поэтому ключ, сформированный клиентом, путь с обходом каталогов или ключ другого сценария отклоняется до обращения к хранилищу.
- Запись требует точный размер. Заявленный размер больше лимита политики отклоняется до запроса. Поток проходит через ограничитель на основе `io.LimitReader`, который придерживает последний фрагмент, пока источник не закончился, поэтому более длинный или более короткий источник прерывает запрос раньше, чем хранилище получит полное тело. Любая ошибка после начала записи удаляет ключ, в том числе после отмены контекста вызывающим. Источники неизвестной длины не буферизуются; сценарию, которому они нужны, придется сохранять их в ограниченный временный файл или добавить multipart upload. Источнику нужен собственный дедлайн, например `http.ResponseController.SetReadDeadline` для тела запроса: `Put` ждет заблокированное чтение, и отмена контекста его не прерывает.
- `Put` возвращает `Record`: ключ, media type без параметров, размер, SHA-256, посчитанный во время потока, и очищенное исходное имя файла. Слой не ведет индекс и не добавляет таблиц. Вызывающий соблюдает один порядок: `Put`, затем сохранение записи вместе с данными о владельце в транзакции БД, затем `Delete` ключа, если транзакция не удалась. Остается одна гонка: если тело целиком ушло до отмены вызывающим, сервер может зафиксировать объект уже после завершения очищающего `Delete`. У таких сирот нет записи, и ни один запрос до них не доходит; sweeper по namespace, который удаляет ключи без записи, запланирован вместе с резервным копированием и выгрузками (TASK-030, TASK-458) и пока не существует. Исходное имя - только метаданные для отображения: оно не сохраняется в SeaweedFS и не используется в ключах и логах, но может содержать персональные данные. Очистка удаляет элементы пути, управляющие символы, символы форматирования, разделители строк и абзацев и символы частного использования и не нормализует Unicode. Content type заявляет вызывающий; определение типа по содержимому относится к разбору документов.
- `Open` проверяет, что сохраненный объект по-прежнему соответствует политике, и закрывает ответ при каждом отказе. Возвращенный `File` закрывает вызывающий; чтение завершается ошибкой, если тело отличается от сохраненного размера. `SEAWEEDFS_TIMEOUT` адаптера ограничивает установку соединения, TLS handshake и ожидание заголовков ответа, но не передачу тела в `Put` и `Get`, поэтому длинный или медленный поток ограничивает только контекст вызывающего. `Delete` идемпотентен, отсутствие объекта отображается в `files.ErrNotFound`.
- Публичных URL нет. Слой не создает публичных, постоянных или presigned URL, у bucket нет публичной политики и анонимного ACL. Скачивание в браузере должно идти через аутентифицированный endpoint backend, который проверяет текущие права и передает `File` потоком с `Content-Disposition: attachment` и `X-Content-Type-Options: nosniff`, чтобы сохраненный файл никогда не отображался как страница origin приложения. Ключ, bucket и URL хранилища не попадают к клиентам.
Доступ к SeaweedFS. Основная защита - сеть: SeaweedFS подключен только к внутренней сети Compose `storage`, к которой подключены также backend и Prometheus мониторинга (для метрик на порту 9327). Frontend, PostgreSQL, Redis, Kafka и другие контейнеры не могут ни разрешить его имя, ни достучаться до него. Это важно, потому что `mini` обслуживает гораздо больше, чем S3. S3-шлюз требует подпись SigV4: переменные контейнера `AWS_ACCESS_KEY_ID` и `AWS_SECRET_ACCESS_KEY` создают его единственную identity, `-s3.iam=false` убирает только API управления IAM, а Compose не запускается с пустыми ключами, потому что SeaweedFS без единой identity принимает анонимные S3-запросы. Остальные слушатели S3-ключи не используют: HTTP API filer (8888), master (9333) и volume (9340); gRPC без аутентификации на 18888, 19333, 19340 и 18333 с открытым reflection; admin server на 23646 с gRPC для worker на 33646, который `-admin.ui=false` не останавливает и который в `mini` нельзя отключить. Дополнительная защита внутри сети хранилища: при каждом старте задаются новые случайные ключи подписи JWT для HTTP API filer и volume, а `-ip=127.0.0.1` вместе с `-whiteList=127.0.0.1,@` разрешает HTTP master и volume только вызывающим внутри контейнера. Upstream filer игнорирует свой IP whitelist, поэтому JWT - его единственная защита HTTP.
Оставшийся риск ограничен участниками сети хранилища, то есть сейчас backend (и Prometheus): им доступны gRPC-порты без аутентификации 19333, 18888 и 18333 и admin-порты 23646 и 33646. gRPC `Assign` у master возвращает file ID с подписанным токеном записи в volume, gRPC `ListEntries` у filer возвращает метаданные объектов, изменение записей через gRPC filer следует считать возможным. gRPC volume 19340 таким вызывающим отказывает. Интеграционные тесты подтверждают, что запись в volume с токеном из `Assign` снаружи контейнера отклоняется (HTTP 401, whitelist) и что чтение из volume без токена отклоняется; для admin- и worker-портов это не проверялось. Раскрытие информации низкого приоритета внутри той же сети: UI master, `/cluster/status` и `/status` у volume показывают топологию и занятость диска. Скомпрометированный backend уже владеет S3-ключами, поэтому эти пути мало что ему добавляют; любой новый участник сети хранилища расширяет риск. Взаимный gRPC TLS закрыл бы пути через gRPC и не настроен.
### Transactional outbox
Реализовано: миграция `backend/db/migrations/00001_create_outbox_events.sql` создает `outbox_events`. Колонки:
@@ -385,6 +399,7 @@ backend/
port/inbound/ inbound границы readiness и обработчиков событий
usecase/identity/ проверка пароля до хеширования (Credentials)
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы
usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, политики, хеширования паролей и почты
@@ -418,7 +433,7 @@ backend/
`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий без зарегистрированных продуктовых обработчиков, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
+7 -1
View File
@@ -39,7 +39,13 @@ SeaweedFS использует `chrislusf/seaweedfs:latest` и режим `weed
Задайте `SEAWEEDFS_ACCESS_KEY` и `SEAWEEDFS_SECRET_KEY` в `.env`, заменив примеры собственными значениями. Compose передает их серверу как `AWS_ACCESS_KEY_ID` и `AWS_SECRET_ACCESS_KEY`, а `SEAWEEDFS_BUCKET` как `S3_BUCKET` для создания bucket при старте. Это одна административная пара для локального стенда, а не разграничение прав production-сервисов. Не передавайте ее браузеру.
Backend использует `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION` и `SEAWEEDFS_TIMEOUT`. Compose задает endpoint `http://seaweedfs:8333`; прямой запуск Go по умолчанию использует `http://localhost:8333`, bucket `lincodex`, region `us-east-1` и timeout `10s`. Ключи обязательны. Для прямого запуска нужен отдельно доступный приватный endpoint. Bucket проверяется при readiness; backend не создает его сам.
SeaweedFS подключен только к внутренней сети `storage` (`APP_STORAGE_NETWORK`, по умолчанию `<APP_PROJECT>_storage`). Backend подключен к ней и к сети по умолчанию; Prometheus мониторинга подключается к ней, чтобы опрашивать порт 9327, поэтому основной проект запускается раньше мониторинга. Остальные контейнеры не могут ни разрешить имя SeaweedFS, ни достучаться до него. Эта сеть - основная защита, потому что контейнер также обслуживает API filer, master, volume и admin и gRPC без аутентификации, которые не проверяют S3-ключи; список и оставшийся риск см. в [ARCHITECTURE.md](ARCHITECTURE.md#закрытое-файловое-хранилище). Не добавляйте в сеть хранилища другие сервисы.
S3-ключи делают закрытым сам S3: SeaweedFS отвечает 403 на неподписанные S3-запросы, а Compose не запускается с пустыми значениями, потому что SeaweedFS без единой identity принимает анонимные S3-запросы. `-s3.iam=false` убирает только API управления IAM. Для дополнительной защиты entrypoint сервиса при каждом старте экспортирует новые случайные ключи подписи `WEED_JWT_*`: запросам к HTTP API filer и volume нужен токен, который не покидает контейнер, а `-ip=127.0.0.1` вместе с `-whiteList=127.0.0.1,@` разрешает HTTP master и volume только вызывающим внутри контейнера. Эти ключи не являются настройкой и не требуют ротации: перезапуск контейнера заменяет их. Smoke проверяет, что frontend не достает SeaweedFS ни по имени, ни по адресу в сети хранилища, что S3 отклоняет неподписанный запрос и что HTTP API filer, master и volume отклоняют вызывающего не изнутри контейнера.
Стенд не публикует URL объектов. У bucket нет публичной политики чтения и анонимного ACL, backend не создает публичных или presigned ссылок; будущие скачивания идут через аутентифицированный endpoint backend, который передает файл потоком. Лимиты размера и content type задаются политикой каждого сценария в `backend/internal/usecase/files/`, а не настройками развертывания, поэтому новых переменных окружения нет. Когда появится маршрут загрузки, согласуйте лимит тела запроса в Nginx с самой большой политикой.
Backend использует `SEAWEEDFS_ENDPOINT`, `SEAWEEDFS_ACCESS_KEY`, `SEAWEEDFS_SECRET_KEY`, `SEAWEEDFS_BUCKET`, `SEAWEEDFS_REGION` и `SEAWEEDFS_TIMEOUT`. Compose задает endpoint `http://seaweedfs:8333`; прямой запуск Go по умолчанию использует `http://localhost:8333`, bucket `lincodex`, region `us-east-1` и timeout `10s`. `SEAWEEDFS_TIMEOUT` ограничивает установку соединения, TLS handshake, ожидание заголовков ответа и целиком удаление и проверку readiness; передачу тела при загрузке и скачивании объекта он не ограничивает, ее определяет контекст вызывающего. Ключи обязательны. Для прямого запуска нужен отдельно доступный приватный endpoint. Bucket проверяется при readiness; backend не создает его сам.
Обычный `down` сохраняет volume SeaweedFS. Потеря volume означает потерю объектов и метаданных; перед изменением образа или удалением volume нужен проверенный backup. Это один узел без HA, репликации между узлами или настроенного внешнего резервного копирования.
+18 -2
View File
@@ -38,11 +38,11 @@ make -C ml check-generated использует datamodel-code-generator --check
## Что покрывает текущий каркас
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых источников событий в Kafka (обработчик доставки писем проверяется только тестами) и нет реального model inference, которые можно было бы проверить как бизнес-результат.
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых источников событий в Kafka (обработчик доставки писем проверяется только тестами) и нет реального model inference, которые можно было бы проверить как бизнес-результат.
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket, изоляцию SeaweedFS от frontend (по имени и по адресу в сети хранилища), отказ HTTP API filer, master и volume на запросы не изнутри контейнера SeaweedFS и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения.
## Браузерный E2E набор
@@ -72,6 +72,22 @@ Kafka не входит в `bootstrap(t)` и запускается только
Helpers находятся в `kafka_helpers_test.go`. `env.createKafkaTopic(ctx, t, partitions)` создает топик с уникальным случайным именем и до создания регистрирует его удаление в `t.Cleanup`, поэтому топик удаляется и после падения теста. Брокер не создает топики по запросу: тест сам создает каждый нужный ему топик. `env.newKafkaClient(t, options...)` возвращает клиент `kgo`, который закрывается по завершении `t`. У `produceKafkaRecords` и `env.consumeKafkaRecords` ограниченные таймауты; consumer читает партиции с начала без consumer group, поэтому смещения группы не остаются. Контейнер останавливается и удаляется в cleanup теста, который вызвал bootstrap, в том числе после падения. `env.pauseKafka(ctx, t)` замораживает брокер через `docker pause` и возвращает функцию, которая его возобновляет; cleanup тоже возобновляет брокер. Приостановленный брокер сохраняет порт и принимает соединения, но не отвечает, что моделирует зависший брокер. Остановленный и снова запущенный контейнер получил бы новый порт на хосте, за которым не следуют ни объявленный listener, ни клиенты, а его топики в tmpfs пропали бы.
## Тесты закрытого файлового хранилища
Unit-тесты в `backend/internal/usecase/files/` используют хранилище в памяти, которое, как HTTP-хранилище объектов, фиксирует объект, как только получило заявленное число байтов. Они покрывают проверку политики, формат ключа и отказ для ключей другого namespace или сформированных клиентом, очистку имени файла, лимит заявленного размера, источник длиннее или короче заявленного (хранилище не получает полное тело, ключ удаляется), очистку после отмены контекста вызывающим и после потерянного ответа, сообщение об ошибке очистки, SHA-256, сохраненное тело, которое отличается от своего размера, идемпотентное удаление, закрытие ответа при каждом отказе `Open` и уникальность и корректность объявленных namespace. Тесты адаптера в `backend/internal/adapter/secondary/seaweedfs/` проверяют, что загрузка и скачивание дольше `SEAWEEDFS_TIMEOUT` завершаются, а зависшие заголовки ответа и недоступный endpoint по-прежнему дают ошибку в пределах этого ограничения.
Bootstrap SeaweedFS использует тот же entrypoint и флаги, что и Compose, и дополнительно публикует порты filer, master и volume, чтобы тесты могли их проверить. Сеть хранилища Compose он не моделирует; эту границу проверяет smoke. `TestPrivateFileStoreAgainstSeaweedFS` в `backend/integration_test/files_store_test.go` использует `bootstrap(t, seaweedfsService)` и реальный адаптер:
- записывает и читает синтетический объект и пустой объект, проверяя содержимое, размер, тип и digest;
- отправляет неподписанные запросы и ожидает 403 от S3 для чтения объекта (в том числе с query, похожим на presigned), перечисления bucket, загрузки и удаления, а также 401 от filer для чтения объекта, перечисления и загрузки и от master для назначения volume и удаления collection; после этого объект по-прежнему читается;
- получает file ID внутри контейнера и ожидает 401 от volume на чтение без токена и на запись с подписанным токеном, который вернул master;
- проверяет, что неверный secret не открывает, не загружает и не удаляет файлы и не выдается за отсутствие объекта;
- открывает, частично читает и закрывает объект больше раз, чем допускает лимит соединений адаптера, с долгим timeout хранилища, поэтому незакрытое тело ответа заблокировало бы цикл;
- отклоняет загрузки больше лимита, длиннее или короче заявленного размера и перечисляет namespace отдельным подписанным клиентом, чтобы показать отсутствие частичных объектов;
- удаляет объект дважды и затем получает `files.ErrNotFound`.
Проверки идут с хоста через опубликованные порты, поэтому запросы приходят не изнутри контейнера SeaweedFS, как от другого участника сети хранилища. gRPC- и admin-порты не проверяются; оставшийся риск описан в [ARCHITECTURE.md](ARCHITECTURE.md#закрытое-файловое-хранилище).
## Тесты relay outbox
Unit-тесты (`make -C backend test`) покрывают конверт записи, ключ и заголовки, а также ошибку для некорректного payload без его цитирования (`internal/adapter/secondary/kafka/`), публикацию и создание топика, которые завершаются ошибкой в пределах таймаута публикации плюс 2 секунды запаса на планирование, когда брокер недоступен (тесты проверяют затраченное время), преобразование неизвестного топика в `ErrEventDestinationMissing`, сравнение существующего топика с настроенной раскладкой, общее расписание backoff с jitter и без него (`internal/worker/retry/`), проходы relay, которые отмечают только подтвержденные события, повторы после неудачных `Prepare` и проходов, отсутствие backoff после прохода, который опубликовал часть пачки, пока ядовитое событие стоит первым в каждой пачке, повторный `Prepare` после отсутствующего назначения, не больше одного чтения размера очереди за интервал, проход в работе, который завершается после отмены, проход, отмененный таймаутом остановки, остановку во время backoff (`internal/worker/outboxrelay/`), настройки relay и топика, включая фактор репликации и `min.insync.replicas` по умолчанию брокера (`config/`), ошибки базы только с SQLSTATE и таймауты, которые округлились бы до отсутствия ограничения (`internal/adapter/secondary/postgres/`), счетчик relay и gauge-метрики очереди и приложение, которое запускает relay вместе с серверами и останавливает его вместе с ними (`internal/bootstrap/`).