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

+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/`).