test(identity): add isolated browser mail fixture

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:52:38 +03:00
1 parent 86f562f5b6
commit 24638d46d2
20 files changed
+885 -20

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
# This image is for local registration E2E only. The release path uses
# Dockerfile and never enables the e2e Go build tag.
ARG GO_IMAGE=golang:1.26.8-alpine
ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot
FROM ${GO_IMAGE} AS build
ENV GOTOOLCHAIN=local
WORKDIR /src/backend
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app
FROM ${RUNTIME_IMAGE}
LABEL org.opencontainers.image.title="Lincodex local E2E backend" \
org.opencontainers.image.description="Local registration E2E image with a fixed internal mail fixture endpoint"
WORKDIR /
COPY --from=build /out/app /app
EXPOSE 8080 9090
USER nonroot:nonroot
ENTRYPOINT ["/app"]
+26
View File
@@ -0,0 +1,26 @@
# The fixture is built separately from the application and only by the local
# E2E Compose overlay.
ARG GO_IMAGE=golang:1.26.8-alpine
ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot
FROM ${GO_IMAGE} AS build
ENV GOTOOLCHAIN=local
WORKDIR /src/backend
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/mail-fixture ./cmd/mail-fixture
FROM ${RUNTIME_IMAGE}
LABEL org.opencontainers.image.title="Lincodex local E2E mail fixture" \
org.opencontainers.image.description="Bounded in-memory Resend-compatible receiver for local browser tests"
WORKDIR /
COPY --from=build /out/mail-fixture /mail-fixture
EXPOSE 8025
USER nonroot:nonroot
ENTRYPOINT ["/mail-fixture"]
+84
View File
@@ -0,0 +1,84 @@
//go:build e2e
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
)
const listenAddress = ":8025"
func main() {
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
if err := healthcheck(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
fixture := resendfixture.NewService()
server := &http.Server{
Addr: listenAddress,
Handler: fixture.Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 16 << 10,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
serverErrors := make(chan error, 1)
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
serverErrors <- errors.New("main.run - mail fixture server stopped unexpectedly")
}
}()
select {
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
return errors.New("main.run - mail fixture shutdown failed")
}
return nil
case err := <-serverErrors:
return err
}
}
func healthcheck() error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8025/healthz", nil)
if err != nil {
return errors.New("main.healthcheck - could not build request")
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return errors.New("main.healthcheck - mail fixture is not ready")
}
defer response.Body.Close()
if response.StatusCode != http.StatusNoContent {
return errors.New("main.healthcheck - mail fixture is not ready")
}
return nil
}
@@ -17,6 +17,7 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
@@ -27,7 +28,14 @@ import (
// APIKey is the key the fixture accepts.
const APIKey = "re_fixture_key" //nolint:gosec // A key of the local fixture, not a credential.
const maxRequestBytes = 1 << 20
const (
maxRequestBytes = 32 << 10
maxStoredRequests = 256
maxStoredMessages = 64
)
// InboxToken is a synthetic credential for the isolated browser E2E fixture.
const InboxToken = "local-e2e-mailbox-token" //nolint:gosec // Synthetic bearer token for the local E2E inbox.
// Request is one call that reached the fixture.
type Request struct {
@@ -41,6 +49,16 @@ type Request struct {
Replayed bool
}
// InboxMessage is an accepted fixture message without provider idempotency
// metadata.
type InboxMessage struct {
ID string `json:"id"`
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
}
// Reply is a scripted answer.
type Reply struct {
Status int
@@ -67,6 +85,8 @@ type Server struct {
mu sync.Mutex
requests []Request
messages map[string]message // by idempotency key
inbox []InboxMessage
received int
accepted int
scripted []Reply
clock func() time.Time
@@ -82,16 +102,35 @@ const providerIdempotencyWindow = 24 * time.Hour
// New starts the fixture on a loopback address.
func New() *Server {
server := &Server{messages: make(map[string]message), clock: time.Now}
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
server := NewService()
server.http = httptest.NewServer(server.Handler())
return server
}
// NewService creates the in-memory fixture for the standalone Compose server.
func NewService() *Server {
return &Server{messages: make(map[string]message), clock: time.Now}
}
// Handler exposes the Resend-compatible endpoint and the authenticated E2E
// inbox. The inbox is intentionally limited to this test fixture package.
func (server *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/emails", server.serve)
mux.HandleFunc("/__e2e/inbox", server.serveInbox)
mux.HandleFunc("/healthz", serveHealth)
return mux
}
// URL is the endpoint to give the loopback transport.
func (server *Server) URL() string { return server.http.URL + "/emails" }
// Close stops the fixture.
func (server *Server) Close() { server.http.Close() }
func (server *Server) Close() {
if server.http != nil {
server.http.Close()
}
}
// Script queues answers for the next calls, in order; calls after them are
// accepted as usual.
@@ -138,6 +177,23 @@ func (server *Server) Messages() int {
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
server.arrivals.Add(1)
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
writeError(response, http.StatusNotFound, "not_found")
return
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return
}
server.mu.Lock()
if server.received >= maxStoredRequests {
server.mu.Unlock()
writeError(response, http.StatusServiceUnavailable, "fixture_capacity_exhausted")
return
}
server.received++
server.mu.Unlock()
if delay := time.Duration(server.delay.Load()); delay > 0 {
time.Sleep(delay)
}
@@ -157,11 +213,15 @@ func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, R
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return nil, Request{}, false
}
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes+1))
if err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
if len(payload) > maxRequestBytes {
writeError(response, http.StatusRequestEntityTooLarge, "payload_too_large")
return nil, Request{}, false
}
var body struct {
To []string `json:"to"`
Subject string `json:"subject"`
@@ -172,8 +232,13 @@ func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, R
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
key := request.Header.Get("Idempotency-Key")
if strings.TrimSpace(key) == "" {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
return payload, Request{
IdempotencyKey: request.Header.Get("Idempotency-Key"),
IdempotencyKey: key,
To: body.To,
Subject: body.Subject,
Text: body.Text,
@@ -203,9 +268,24 @@ func (server *Server) handleEmail(response http.ResponseWriter, payload []byte,
writeError(response, reply.Status, reply.Name)
return
}
if !seen && server.accepted >= maxStoredMessages {
server.requests = append(server.requests, record)
server.mu.Unlock()
writeError(response, http.StatusServiceUnavailable, "fixture_capacity_exhausted")
return
}
messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen)
record.Replayed = replayed
server.requests = append(server.requests, record)
if !replayed && !conflict {
server.inbox = append(server.inbox, InboxMessage{
ID: messageID,
To: append([]string(nil), record.To...),
Subject: record.Subject,
Text: record.Text,
HTML: record.HTML,
})
}
server.mu.Unlock()
if conflict {
writeError(response, http.StatusConflict, "invalid_idempotent_request")
@@ -218,6 +298,56 @@ func (server *Server) handleEmail(response http.ResponseWriter, payload []byte,
writeAccepted(response, messageID)
}
func (server *Server) serveInbox(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet || request.URL.Path != "/__e2e/inbox" {
writeError(response, http.StatusNotFound, "not_found")
return
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+InboxToken)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_inbox_token")
return
}
recipient := strings.ToLower(strings.TrimSpace(request.URL.Query().Get("to")))
if recipient == "" || len(recipient) > 254 {
writeError(response, http.StatusBadRequest, "invalid_recipient")
return
}
messages := server.InboxMessages(recipient)
response.Header().Set("Cache-Control", "no-store")
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
_ = json.NewEncoder(response).Encode(struct {
Messages []InboxMessage `json:"messages"`
}{Messages: messages})
}
// InboxMessages returns accepted messages for one exact case-insensitive
// recipient. It never includes provider idempotency keys.
func (server *Server) InboxMessages(recipient string) []InboxMessage {
wanted := strings.ToLower(strings.TrimSpace(recipient))
server.mu.Lock()
defer server.mu.Unlock()
messages := make([]InboxMessage, 0)
for _, message := range server.inbox {
for _, address := range message.To {
if strings.ToLower(address) == wanted {
messages = append(messages, message)
break
}
}
}
return messages
}
func serveHealth(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet || request.URL.Path != "/healthz" {
writeError(response, http.StatusNotFound, "not_found")
return
}
response.WriteHeader(http.StatusNoContent)
}
func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) {
if seen {
if known.body != body {
@@ -1,6 +1,11 @@
package resendfixture_test
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
@@ -65,3 +70,184 @@ func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) {
}
}
}
func TestInboxRequiresAuthenticationAndReturnsOnlyAcceptedMessagesForRecipient(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex <no-reply@example.com>", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
if _, err := sender.Send(t.Context(), newMail(t, "Confirm", "delivery/first")); err != nil {
t.Fatalf("Send() error = %v", err)
}
address := url.QueryEscape("fixture.user@example.com")
inboxURL := strings.TrimSuffix(fixture.URL(), "/emails") + "/__e2e/inbox?to=" + address
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, inboxURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
unauthorized, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("inbox request error = %v", err)
}
_ = unauthorized.Body.Close()
if unauthorized.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthenticated inbox status = %d, want %d", unauthorized.StatusCode, http.StatusUnauthorized)
}
request, err = http.NewRequestWithContext(t.Context(), http.MethodGet, inboxURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.InboxToken)
authorized, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("authenticated inbox request error = %v", err)
}
defer authorized.Body.Close()
if authorized.StatusCode != http.StatusOK {
t.Fatalf("authenticated inbox status = %d, want %d", authorized.StatusCode, http.StatusOK)
}
var result struct {
Messages []resendfixture.InboxMessage `json:"messages"`
}
if err := json.NewDecoder(authorized.Body).Decode(&result); err != nil {
t.Fatalf("decode inbox response error = %v", err)
}
if len(result.Messages) != 1 || result.Messages[0].Subject != "Confirm" {
t.Fatalf("inbox messages = %+v, want the accepted fixture message", result.Messages)
}
if strings.Contains(string(mustReadBody(t, result.Messages[0])), "delivery/first") {
t.Fatal("inbox response unexpectedly includes provider idempotency metadata")
}
otherURL := strings.TrimSuffix(fixture.URL(), "/emails") + "/__e2e/inbox?to=" + url.QueryEscape("other@example.com")
request, err = http.NewRequestWithContext(t.Context(), http.MethodGet, otherURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.InboxToken)
other, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("filtered inbox request error = %v", err)
}
defer other.Body.Close()
if err := json.NewDecoder(other.Body).Decode(&result); err != nil {
t.Fatalf("decode filtered inbox response error = %v", err)
}
if len(result.Messages) != 0 {
t.Fatalf("other recipient inbox = %+v, want no messages", result.Messages)
}
}
func TestFixtureBoundsAcceptedMessages(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
for index := range 64 {
mail := newMail(t, fmt.Sprintf("Message %d", index), fmt.Sprintf("delivery/%d", index))
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("Send(%d) error = %v", index, err)
}
}
if fixture.Messages() != 64 {
t.Fatalf("accepted messages = %d, want 64", fixture.Messages())
}
if _, err := sender.Send(t.Context(), newMail(t, "Overflow", "delivery/overflow")); err != nil {
t.Fatalf("overflow Send() error = %v", err)
}
if fixture.Messages() != 64 {
t.Fatalf("accepted messages after capacity refusal = %d, want 64", fixture.Messages())
}
}
func TestFixtureBoundsRecordedProviderRequests(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
mail := newMail(t, "Repeated message", "delivery/repeated")
for range 256 {
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("Send() error = %v", err)
}
}
if fixture.Messages() != 1 || len(fixture.Requests()) != 256 {
t.Fatalf("fixture state = %d messages and %d requests, want 1 and 256", fixture.Messages(), len(fixture.Requests()))
}
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("capacity refusal Send() error = %v", err)
}
if fixture.Messages() != 1 || len(fixture.Requests()) != 256 {
t.Fatalf("fixture state after capacity refusal = %d messages and %d requests", fixture.Messages(), len(fixture.Requests()))
}
}
func TestWrongProviderKeyDoesNotConsumeFixtureCapacity(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
for range 256 {
request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fixture.URL(), strings.NewReader(`{}`))
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer wrong-key")
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("unauthorized provider request error = %v", err)
}
_ = response.Body.Close()
if response.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthorized provider status = %d, want %d", response.StatusCode, http.StatusUnauthorized)
}
}
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
if _, err := sender.Send(t.Context(), newMail(t, "After unauthorized request", "delivery/authorized")); err != nil {
t.Fatalf("authorized Send() error = %v", err)
}
if fixture.Messages() != 1 {
t.Fatalf("accepted messages = %d, want 1", fixture.Messages())
}
}
func TestFixtureRejectsOversizedProviderRequest(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
payload := `{"to":["fixture.user@example.com"],"subject":"fixture","text":"` + strings.Repeat("x", (32<<10)+1) + `"}`
request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fixture.URL(), strings.NewReader(payload))
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.APIKey)
request.Header.Set("Idempotency-Key", "delivery/oversized")
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("oversized provider request error = %v", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized request status = %d, want %d", response.StatusCode, http.StatusRequestEntityTooLarge)
}
if len(fixture.Requests()) != 0 {
t.Fatalf("oversized requests recorded = %d, want 0", len(fixture.Requests()))
}
}
func mustReadBody(t *testing.T, message resendfixture.InboxMessage) []byte {
t.Helper()
encoded, err := json.Marshal(message)
if err != nil {
t.Fatalf("marshal inbox message: %v", err)
}
return encoded
}
@@ -137,10 +137,14 @@ func newSender(apiKey, from string, timeout time.Duration, endpoint string, now
// settings follow the standard HTTPS_PROXY and NO_PROXY environment, as with
// any Go HTTP client.
func newHTTPClient(timeout time.Duration) *http.Client {
return newHTTPClientWithProxy(timeout, http.ProxyFromEnvironment)
}
func newHTTPClientWithProxy(timeout time.Duration, proxy func(*http.Request) (*url.URL, error)) *http.Client {
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Proxy: proxy,
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
TLSHandshakeTimeout: timeout,
@@ -0,0 +1,20 @@
//go:build e2e
package resend
import "time"
const e2eEndpoint = "http://mail-fixture:8025/emails"
// NewE2ESender is compiled only into the isolated registration E2E image. Its
// endpoint is fixed to the Compose fixture and cannot be selected at runtime.
func NewE2ESender(apiKey, from string, timeout time.Duration) (*Sender, error) {
sender, err := newSender(apiKey, from, timeout, e2eEndpoint, time.Now)
if err != nil {
return nil, err
}
// The local fixture must stay internal even when the host has proxy
// variables configured for ordinary provider traffic.
sender.client = newHTTPClientWithProxy(timeout, nil)
return sender, nil
}
@@ -0,0 +1,23 @@
//go:build e2e
package resend
import (
"net/http"
"testing"
"time"
)
func TestE2ESenderUsesOnlyTheComposeFixtureEndpoint(t *testing.T) {
sender, err := NewE2ESender("re_e2e_fixture_key", "no-reply@example.com", time.Second)
if err != nil {
t.Fatalf("NewE2ESender() error = %v", err)
}
if sender.endpoint != e2eEndpoint {
t.Fatalf("endpoint = %q, want the fixed Compose fixture endpoint", sender.endpoint)
}
transport, ok := sender.client.Transport.(*http.Transport)
if !ok || transport.Proxy != nil {
t.Fatalf("E2E transport proxy = %v, want no proxy", transport)
}
}
+1 -2
View File
@@ -7,7 +7,6 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/port/outbound"
)
@@ -32,7 +31,7 @@ func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSe
case config.EmailProviderDisabled:
sender = disabled.NewSender()
case config.EmailProviderResend:
resendSender, err := resend.NewSender(settings.ResendAPIKey, settings.EmailFrom, settings.EmailTimeout)
resendSender, err := newResendSender(settings.ResendAPIKey, settings.EmailFrom, settings.EmailTimeout)
if err != nil {
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", err)
}
+13
View File
@@ -0,0 +1,13 @@
//go:build !e2e
package bootstrap
import (
"time"
"lincodex/backend/internal/adapter/secondary/mail/resend"
)
func newResendSender(apiKey, from string, timeout time.Duration) (*resend.Sender, error) {
return resend.NewSender(apiKey, from, timeout)
}
@@ -0,0 +1,13 @@
//go:build e2e
package bootstrap
import (
"time"
"lincodex/backend/internal/adapter/secondary/mail/resend"
)
func newResendSender(apiKey, from string, timeout time.Duration) (*resend.Sender, error) {
return resend.NewE2ESender(apiKey, from, timeout)
}
+10 -2
View File
@@ -16,6 +16,7 @@ CORE_FILE := $(ROOT)/deploy/docker/docker-compose.yml
ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml
MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml
E2E_FILE := $(ROOT)/deploy/docker/docker-compose.e2e.yml
E2E_MAIL_FILE := $(ROOT)/deploy/docker/docker-compose.e2e-mail.yml
RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.release.yml
ML_RELEASE_FILE := $(ROOT)/deploy/docker/docker-compose.ml.release.yml
RELEASE_SCRIPT := $(ROOT)/deploy/scripts/release_manifest.py
@@ -37,7 +38,7 @@ RELEASE_MANIFEST_ARG = $(if $(strip $(RELEASE_MANIFEST)),--manifest "$(RELEASE_M
LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag)
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter perimeter-test smoke test-e2e release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter check-e2e-mail perimeter-test smoke test-e2e test-e2e-registration release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean
help: ## Show deployment commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -52,6 +53,7 @@ config: ## Render all Compose files with safe example values
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet
APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet
APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet
APP_PROJECT=lincodex-e2e-mail-config APP_NETWORK=lincodex-e2e-mail-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-mail-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" -f "$(E2E_MAIL_FILE)" --profile e2e config --quiet
build: ## Build local frontend and backend images
APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build
@@ -114,7 +116,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release check-perimeter ## Validate Compose files, CI workflow aggregates, release tooling, and the public perimeter without starting services
check: config check-workflows check-release check-perimeter check-e2e-mail ## Validate Compose files, CI workflow aggregates, release tooling, and network boundaries without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py'
@@ -125,6 +127,9 @@ check-release: ## Test the release manifest tooling, its secret scan, and the Go
check-perimeter: ## Check published ports, the app Nginx paths, limits, and the trusted proxy chain from the files
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py'
check-e2e-mail: ## Check that the mail fixture stays inside the explicit local E2E network
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_e2e_mail.py'
perimeter-test: ## Start throwaway Nginx containers and test denied paths, limits, headers, and forwarded headers over HTTP
LINCODEX_PERIMETER_LIVE=1 DOCKER="$(DOCKER)" PERIMETER_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -v -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py'
@@ -134,6 +139,9 @@ smoke: ## Start an isolated stack and check infrastructure health routes
test-e2e: ## Run the Playwright suite against an isolated throwaway stack
@bash scripts/e2e.sh
test-e2e-registration: ## Run browser registration tests with the local authenticated mail fixture
@bash scripts/e2e.sh --mail-fixture
release-build: ## Build release images with every base image pinned to its resolved digest
@$(RELEASE) build --pull "$(RELEASE_PULL)"
+1 -1
View File
@@ -13,7 +13,7 @@ Configuration for running the application with Docker Compose and Nginx.
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address).
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; see [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; `make -C deploy test-e2e-registration` enables a local Resend-compatible inbox only for registration browser tests. See [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite) for details.
`make -C deploy release-build`, `release-smoke`, and `release-manifest` build the release images with pinned base image digests, check them, and write the manifest to `deploy/release/<tag>/`, which Git ignores; `make -C deploy release-manifest-verify` compares running containers with the manifest, and `make -C deploy release-clean` removes the release images. See the [release manifest](../docs/en/DEPLOY.md#release-manifest).
+1 -1
View File
@@ -13,7 +13,7 @@
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента).
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; см. [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; `make -C deploy test-e2e-registration` включает локальный Resend-compatible inbox только для браузерных тестов регистрации. Подробности см. в [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
`make -C deploy release-build`, `release-smoke` и `release-manifest` собирают образы выпуска с закрепленными digest базовых образов, проверяют их и пишут манифест в `deploy/release/<tag>/` (игнорируется Git); `make -C deploy release-manifest-verify` сверяет запущенные контейнеры с манифестом, а `make -C deploy release-clean` удаляет образы выпуска. См. [манифест выпуска](../docs/ru/DEPLOY.md#манифест-выпуска).
+58
View File
@@ -0,0 +1,58 @@
# Local registration-mail overlay. It is selected only by the explicit
# registration E2E runner, never by default or release E2E.
services:
backend:
build:
context: ../../backend
dockerfile: Dockerfile.e2e
environment:
EMAIL_PROVIDER: resend
EMAIL_ACCOUNT: e2e
EMAIL_FROM: no-reply@example.com
RESEND_API_KEY: re_fixture_key
depends_on:
mail-fixture:
condition: service_healthy
playwright:
environment:
# The runner shares the frontend network namespace, so it can reach
# the fixture without publishing a host port.
E2E_MAILBOX_URL: http://mail-fixture:8025/__e2e/inbox
E2E_MAILBOX_TOKEN: local-e2e-mailbox-token
E2E_MAIL_FIXTURE: "1"
mail-fixture:
build:
context: ../../backend
dockerfile: Dockerfile.mail-fixture
expose:
- "8025"
read_only: true
cap_drop: [ALL]
security_opt: ["no-new-privileges:true"]
healthcheck:
test: ["CMD", "/mail-fixture", "healthcheck"]
interval: 2s
timeout: 3s
retries: 15
start_period: 2s
stop_grace_period: 5s
networks:
- default
logging:
driver: json-file
options:
max-size: 1m
max-file: "2"
deploy:
resources:
limits:
cpus: "0.25"
memory: 128M
networks:
default:
# The fixture and browser can talk on the throwaway app network, but no
# E2E container needs outbound access to a real provider.
internal: true
+99 -7
View File
@@ -2,7 +2,8 @@
# Runs the Playwright suite against an isolated, throwaway Compose stand.
#
# Each run gets a unique project name, a generated env file with random
# secrets and EMAIL_PROVIDER=disabled, no host port, and fresh volumes. The
# secrets, no host port, and fresh volumes. Ordinary mode uses disabled mail;
# --mail-fixture selects the separate local Resend-compatible receiver. The
# stand, its volumes, and its locally built images are removed on every exit.
# Artifacts of the last run stay in frontend/test-results/e2e.
#
@@ -14,20 +15,49 @@
# keep those images, and record passing evidence for the
# release manifest. Specs must be the committed frontend/e2e.
# Only make -C deploy release-e2e sets it.
# Invocation:
# e2e.sh ordinary browser suite with mail disabled
# e2e.sh --mail-fixture local registration suite with a bounded internal
# receiver and no outbound network
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
source "$root/deploy/scripts/e2e_user.sh"
compose_file="$root/deploy/docker/docker-compose.yml"
e2e_file="$root/deploy/docker/docker-compose.e2e.yml"
mail_file="$root/deploy/docker/docker-compose.e2e-mail.yml"
release_file="$root/deploy/docker/docker-compose.release.yml"
release_script="$root/deploy/scripts/release_manifest.py"
release_tag="${LINCODEX_RELEASE_TAG:-}"
mail_fixture=0
if [[ "$#" -gt 1 ]]; then
printf '%s\n' 'Usage: e2e.sh [--mail-fixture]' >&2
exit 2
fi
if [[ "$#" -eq 1 ]]; then
if [[ "$1" != '--mail-fixture' ]]; then
printf '%s\n' 'Usage: e2e.sh [--mail-fixture]' >&2
exit 2
fi
mail_fixture=1
fi
email_provider=disabled
if ((mail_fixture)); then
email_provider=resend
fi
compose_files=(-f "$compose_file" -f "$e2e_file")
up_args=(--build)
if [[ -n "$release_tag" ]]; then
if ((mail_fixture)); then
printf '%s\n' 'The local mail fixture cannot be used for release E2E.' >&2
exit 2
fi
compose_files+=(-f "$release_file")
up_args=(--no-build --pull never)
fi
if ((mail_fixture)); then
compose_files+=(-f "$mail_file")
fi
frontend_dir="$root/frontend"
artifacts_dir="$frontend_dir/test-results/e2e"
spec_dir="${E2E_SPEC_DIR:-$frontend_dir/e2e}"
@@ -66,6 +96,14 @@ fi
for dockerfile in "$root/backend/Dockerfile" "$root/frontend/Dockerfile"; do
[[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile."
done
if ((mail_fixture)); then
for dockerfile in "$root/backend/Dockerfile.e2e" "$root/backend/Dockerfile.mail-fixture"; do
[[ -f "$dockerfile" ]] || fail "Missing required build file $dockerfile."
done
fi
playwright_user=$(e2e_playwright_user \
"$(docker info --format '{{json .SecurityOptions}}')" "$(id -u)" "$(id -g)")
IFS=: read -r playwright_uid playwright_gid <<<"$playwright_user"
# Compose runs with a cleared environment: shell variables such as
# EMAIL_PROVIDER, RESEND_API_KEY, or COMPOSE_FILE must not leak into the
@@ -82,7 +120,7 @@ compose() {
APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \
APP_SUBNET=172.29.82.0/24 APP_FRONTEND_IP=172.29.82.10 \
PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \
E2E_UID="$(id -u)" E2E_GID="$(id -g)" \
E2E_UID="$playwright_uid" E2E_GID="$playwright_gid" \
E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" LINCODEX_RELEASE_TAG="$release_tag" \
docker compose \
--env-file "$env_file" \
@@ -132,8 +170,8 @@ trap 'exit 143' TERM
mkdir -p "$artifacts_dir"
rm -f "$artifacts_dir/stand.log"
# Throwaway configuration with synthetic secrets. The backend sends no mail,
# and APP_PUBLIC_URL is the origin the browser uses inside the stand.
# Throwaway configuration with synthetic secrets. The ordinary suite disables
# mail; registration E2E sends only to the Compose-internal fixture.
env_file=$(mktemp "${TMPDIR:-/tmp}/lincodex-e2e-env.XXXXXX")
chmod 600 "$env_file"
cat >"$env_file" <<EOF
@@ -145,7 +183,7 @@ SEAWEEDFS_ACCESS_KEY=e2e-$suffix
SEAWEEDFS_SECRET_KEY=$(random_secret)
SEAWEEDFS_BUCKET=lincodex
KAFKA_CLUSTER_ID=$(head -c 16 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n')
EMAIL_PROVIDER=disabled
EMAIL_PROVIDER=$email_provider
EMAIL_FROM=no-reply@example.com
EMAIL_TIMEOUT=10s
APP_PUBLIC_URL=http://localhost:8080
@@ -176,12 +214,66 @@ done
exit 1
}
if ((mail_fixture)); then
# Exercise the real Compose DNS path and inbox before browser tests. This
# sends only one synthetic message and verifies idempotent replay.
if ! compose run --rm --no-deps -T playwright node -e '
const fail = () => { console.error("Local mail fixture transport check failed."); process.exit(1); };
try {
const recipient = "fixture-smoke@example.invalid";
const body = JSON.stringify({
from: "no-reply@example.com",
to: [recipient],
subject: "Local fixture check",
text: "Synthetic message for the local E2E fixture.",
});
const headers = {
Authorization: "Bearer re_fixture_key",
"Content-Type": "application/json",
"Idempotency-Key": "registration-fixture-smoke",
};
const send = () => fetch("http://mail-fixture:8025/emails", {
method: "POST", headers, body,
});
const firstResponse = await send();
if (!firstResponse.ok) fail();
const first = await firstResponse.json();
if (typeof first.id !== "string" || first.id.length === 0) fail();
const replayResponse = await send();
if (!replayResponse.ok) fail();
const replay = await replayResponse.json();
if (replay.id !== first.id) fail();
const inboxURL = new URL(process.env.E2E_MAILBOX_URL);
inboxURL.searchParams.set("to", recipient);
const inboxResponse = await fetch(inboxURL, {
headers: { Authorization: `Bearer ${process.env.E2E_MAILBOX_TOKEN}` },
});
if (!inboxResponse.ok) fail();
const inbox = await inboxResponse.json();
if (!Array.isArray(inbox.messages) || inbox.messages.length !== 1) fail();
if (inbox.messages[0].id !== first.id || inbox.messages[0].to[0] !== recipient) fail();
console.log("Local mail fixture accepted, deduplicated, and returned one synthetic inbox message.");
} catch {
fail();
}
'; then
printf '%s\n' 'The local mail fixture transport check failed.' >&2
exit 1
fi
fi
playwright_command=(node node_modules/@playwright/test/cli.js test)
if ((mail_fixture)); then
# Confirmation links contain one-time tokens. Do not save traces with inbox
# responses or token-bearing navigation URLs.
playwright_command+=(--trace off)
fi
set +e
compose run --rm --no-deps -T playwright
compose run --rm --no-deps -T playwright "${playwright_command[@]}"
status=$?
set -e
if ((status != 0)); then
printf 'Playwright failed with exit code %s; traces and screenshots are in %s/results.\n' \
printf 'Playwright failed with exit code %s; browser artifacts are in %s/results.\n' \
"$status" "$artifacts_dir" >&2
elif [[ -n "$release_tag" ]]; then
# The suite passed; bind the result to the image IDs that ran.
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# Rootless Docker maps container root to the owner of a host bind mount. A
# non-root container UID instead maps to a subordinate host UID and cannot
# write the owner's artifact directory. In rootful Docker, match the host UID.
e2e_playwright_user() {
local security_options=$1
local host_uid=$2
local host_gid=$3
if [[ "$security_options" == *'"name=rootless"'* ]]; then
printf '0:0\n'
return
fi
printf '%s:%s\n' "$host_uid" "$host_gid"
}
+153
View File
@@ -0,0 +1,153 @@
"""Boundary checks for the Compose-only registration mail fixture."""
import json
import os
import shutil
import subprocess
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DEPLOY = ROOT / "deploy"
DOCKER = os.environ.get("DOCKER", "docker")
FIXTURE_TOKEN = "local-e2e-mailbox-token"
class E2EUserSelectionTest(unittest.TestCase):
def test_playwright_user_matches_docker_mode(self):
helper = DEPLOY / "scripts" / "e2e_user.sh"
cases = (
('["name=seccomp", "name=rootless"]', "1000", "100", "0:0"),
('["name=seccomp"]', "1000", "100", "1000:100"),
)
for security_options, uid, gid, expected in cases:
with self.subTest(security_options=security_options):
result = subprocess.run(
[
"bash",
"-c",
'source "$1"; e2e_playwright_user "$2" "$3" "$4"',
"e2e-user-test",
str(helper),
security_options,
uid,
gid,
],
check=True,
capture_output=True,
text=True,
)
self.assertEqual(result.stdout.strip(), expected)
def render_compose(file_names, project, extra_env=None):
environment = {
"PATH": os.environ.get("PATH", ""),
"HOME": os.environ.get("HOME", ""),
"APP_PROJECT": project,
"APP_NETWORK": f"{project}_default",
"APP_STORAGE_NETWORK": f"{project}_storage",
"APP_SUBNET": "172.29.82.0/24",
"APP_FRONTEND_IP": "172.29.82.10",
"PLAYWRIGHT_VERSION": "1.0.0",
"E2E_UID": "1000",
"E2E_GID": "1000",
"E2E_SPEC_DIR": str(ROOT / "frontend" / "e2e"),
"E2E_ARTIFACTS_DIR": str(ROOT / "frontend" / "test-results" / "e2e"),
"IDENTITY_KEY_SECRET": "render-only-identity-key-secret",
}
environment.update(extra_env or {})
command = [DOCKER, "compose", "--env-file", str(ROOT / ".env.example"), "-p", project]
for file_name in file_names:
command.extend(["-f", str(DEPLOY / "docker" / file_name)])
result = subprocess.run(
command + ["--profile", "e2e", "config", "--format", "json"],
capture_output=True,
text=True,
env=environment,
check=False,
)
if result.returncode != 0:
raise AssertionError(f"docker compose config failed: {result.stderr}")
return json.loads(result.stdout)
class ComposeMailFixtureTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if shutil.which(DOCKER) is None:
raise unittest.SkipTest("docker CLI is not available")
cls.ordinary = render_compose(
["docker-compose.yml", "docker-compose.e2e.yml"], "e2e-mail-ordinary"
)
cls.fixture = render_compose(
["docker-compose.yml", "docker-compose.e2e.yml", "docker-compose.e2e-mail.yml"],
"e2e-mail-registration",
)
cls.release = render_compose(
["docker-compose.yml", "docker-compose.e2e.yml", "docker-compose.release.yml"],
"e2e-mail-release",
{"LINCODEX_RELEASE_TAG": "000000000000"},
)
def test_ordinary_and_release_e2e_keep_the_production_build_and_disabled_mail(self):
for rendered in (self.ordinary, self.release):
with self.subTest(project=rendered["name"]):
self.assertNotIn("mail-fixture", rendered["services"])
backend = rendered["services"]["backend"]
self.assertEqual(backend["build"]["dockerfile"], "Dockerfile")
self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "disabled")
self.assertNotIn("RESEND_ENDPOINT", backend["environment"])
self.assertNotIn(
"E2E_MAIL_FIXTURE",
rendered["services"]["playwright"].get("environment", {}),
)
def test_fixture_uses_an_e2e_build_and_fixed_synthetic_credentials(self):
services = self.fixture["services"]
backend = services["backend"]
self.assertEqual(backend["build"]["dockerfile"], "Dockerfile.e2e")
self.assertEqual(backend["environment"]["EMAIL_PROVIDER"], "resend")
self.assertEqual(backend["environment"]["RESEND_API_KEY"], "re_fixture_key")
self.assertNotIn("RESEND_ENDPOINT", backend["environment"])
self.assertEqual(
services["playwright"]["environment"]["E2E_MAILBOX_URL"],
"http://mail-fixture:8025/__e2e/inbox",
)
self.assertEqual(services["playwright"]["environment"]["E2E_MAILBOX_TOKEN"], FIXTURE_TOKEN)
self.assertEqual(services["playwright"]["environment"]["E2E_MAIL_FIXTURE"], "1")
self.assertNotIn("E2E_MAIL_FIXTURE", services["frontend"].get("environment", {}))
def test_fixture_has_no_host_port_storage_network_or_outbound_route(self):
services = self.fixture["services"]
fixture = services["mail-fixture"]
self.assertEqual(fixture["build"]["dockerfile"], "Dockerfile.mail-fixture")
self.assertFalse(fixture.get("ports"))
self.assertFalse(services["frontend"].get("ports"))
self.assertFalse(services["backend"].get("ports"))
self.assertEqual(set(fixture["networks"]), {"default"})
self.assertTrue(self.fixture["networks"]["default"]["internal"])
self.assertNotIn("storage", fixture["networks"])
self.assertTrue(fixture["read_only"])
self.assertEqual(fixture["cap_drop"], ["ALL"])
self.assertIn("no-new-privileges:true", fixture["security_opt"])
self.assertEqual(fixture["deploy"]["resources"]["limits"]["memory"], str(128 * 1024 * 1024))
class E2ERunnerModeTest(unittest.TestCase):
def test_release_tag_cannot_enable_the_local_mail_fixture(self):
environment = {"PATH": os.environ.get("PATH", ""), "LINCODEX_RELEASE_TAG": "000000000000"}
result = subprocess.run(
["bash", str(DEPLOY / "scripts" / "e2e.sh"), "--mail-fixture"],
capture_output=True,
text=True,
env=environment,
check=False,
)
self.assertEqual(result.returncode, 2)
self.assertIn("cannot be used for release E2E", result.stderr)
self.assertNotIn("mail-fixture", result.stdout)
if __name__ == "__main__":
unittest.main()
+7
View File
@@ -55,11 +55,18 @@ Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis
- Reads the exact `@playwright/test` version from `frontend/package.json`, checks that the installed package matches it, and runs the suite in the official `mcr.microsoft.com/playwright:v<version>-noble` image with `frontend/` mounted read-only.
- Starts the core stack under a unique project `lincodex-e2e-<random>` with fresh volumes and a generated throwaway env file: random passwords, `EMAIL_PROVIDER=disabled`, no mail transport settings. Shell variables other than Docker client settings do not reach Compose. The run refuses to reuse an existing project, network, or volume.
- Publishes no host port. The browser container shares the frontend container's network namespace, so it opens `http://localhost:8080`, the same loopback origin as `APP_PUBLIC_URL`. The Playwright config refuses a base URL outside a loopback host.
- Runs Playwright with the host UID/GID on rootful Docker; on rootless Docker it uses container UID 0, which maps to the owner of the host artifact directory. The runner drops all capabilities and mounts the source read-only.
- Waits for backend readiness, runs the suite with retries disabled, and returns its exit code; make reports any failure as exit status 2.
- Removes the containers, volumes, network, locally built images, and env file on every exit, including failures and interrupts. Only the cached Playwright image and the build cache remain.
Artifacts of the last run are in `frontend/test-results/e2e/`, which Git ignores; the runner prints the path. `report/` holds the HTML report (`pnpm exec playwright show-report test-results/e2e/report` from `frontend/`). For each failed test, `results/` keeps `trace.zip` and a screenshot (`pnpm exec playwright show-trace <trace.zip>` needs a local browser; trace.playwright.dev opens the file without one). After a failed run, `stand.log` holds the stack logs. `E2E_SPEC_DIR=<dir>` runs specs from another directory, such as a scratch copy, against the same isolated stack.
## Local registration browser tests with a mail fixture
`make -C deploy test-e2e-registration` runs the same disposable browser stack with the additional `docker-compose.e2e-mail.yml` overlay. Only this mode builds the backend with the Go `e2e` build tag: its Resend constructor uses the fixed `http://mail-fixture:8025/emails` endpoint, and Compose supplies a synthetic key. Before Playwright starts, the runner sends one synthetic message through the Compose network, replays the same idempotency key, and verifies the message in the authenticated inbox. The `mail-fixture` service accepts Resend-compatible requests, deduplicates by key, and keeps at most 64 messages and 256 requests of up to 32 KiB each in memory. Its inbox requires bearer authentication, returns only messages for the requested `to`, and is reachable inside the stack. The registration network is marked internal, the fixture is not connected to the storage network, and no host port is published; requests cannot reach an external mail provider. Cleanup removes the containers and inbox.
Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox`, and the synthetic `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. A test requests `GET $E2E_MAILBOX_URL?to=<urlencoded email>` with `Authorization: Bearer $E2E_MAILBOX_TOKEN`; the response contains `messages` with `id`, `to`, `subject`, `text`, and `html` fields. Registration-only tests should skip unless `E2E_MAIL_FIXTURE=1`, because neither ordinary `test-e2e` nor `release-e2e` sets it. Tests must not print message content or a link containing a one-time token. The runner disables Playwright tracing in this mode. The ordinary `test-e2e` still sets `EMAIL_PROVIDER=disabled`, and `release-e2e` uses release images without the fixture and records no evidence for a mail-fixture image. The registration mode refuses to run with `LINCODEX_RELEASE_TAG`.
The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Later business tests create their own synthetic users and records through the public API in the fresh stack of each run; they do not use shared fixtures or real data.
The suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, layout, or accessibility. CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-<n>` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate.
+7
View File
@@ -55,11 +55,18 @@ Deployment smoke проверяет инфраструктурные маршр
- Читает точную версию `@playwright/test` из `frontend/package.json`, проверяет, что установлена та же версия, и запускает набор в официальном образе `mcr.microsoft.com/playwright:v<version>-noble`, где `frontend/` смонтирован только для чтения.
- Поднимает основной стек под уникальным проектом `lincodex-e2e-<random>` со свежими томами и сгенерированным одноразовым env-файлом: случайные пароли, `EMAIL_PROVIDER=disabled`, без настроек почтового транспорта. Переменные оболочки, кроме настроек Docker-клиента, в Compose не попадают. Запуск отказывается переиспользовать существующие проект, сеть или том.
- Не публикует host-порт. Контейнер браузера разделяет сетевое пространство контейнера frontend и открывает `http://localhost:8080`, тот же loopback origin, что и `APP_PUBLIC_URL`. Конфигурация Playwright отклоняет base URL вне loopback-хоста.
- Запускает Playwright с UID/GID хоста в rootful Docker; в rootless Docker использует container UID 0, который соответствует владельцу каталога артефактов на хосте. Runner удаляет все capabilities, исходники смонтированы только для чтения.
- Ждет готовности backend, запускает набор без повторов и возвращает его код завершения; make сообщает о любой ошибке кодом 2.
- При любом завершении, включая ошибку и прерывание, удаляет контейнеры, тома, сеть, локально собранные образы и env-файл. Остаются только закешированный образ Playwright и кеш сборки.
Артефакты последнего прогона лежат в `frontend/test-results/e2e/`, который игнорируется Git; путь печатается в конце. В `report/` лежит HTML-отчет (`pnpm exec playwright show-report test-results/e2e/report` из `frontend/`). Для каждого упавшего теста `results/` сохраняет `trace.zip` и снимок экрана (`pnpm exec playwright show-trace <trace.zip>` требует локального браузера; trace.playwright.dev открывает файл без него). После неуспешного прогона `stand.log` содержит логи стека. `E2E_SPEC_DIR=<dir>` запускает спецификации из другого каталога, например из временной копии, на таком же изолированном стеке.
## Локальный браузерный тест регистрации с почтовым fixture
`make -C deploy test-e2e-registration` запускает тот же одноразовый браузерный стек с дополнительным `docker-compose.e2e-mail.yml` overlay. Только этот режим собирает backend с Go build tag `e2e`: его Resend-конструктор использует фиксированный адрес `http://mail-fixture:8025/emails`, а Compose передает ему синтетический ключ. Перед Playwright runner отправляет через Compose network одно синтетическое письмо, повторяет запрос с тем же idempotency key и проверяет сообщение в аутентифицированном inbox. Сервис `mail-fixture` принимает Resend-совместимые запросы, поддерживает дедупликацию по ключу и хранит в памяти не более 64 сообщений и 256 запросов размером до 32 KiB каждый. Его inbox требует bearer-аутентификацию, отдает только письма для запрошенного `to` и доступен изнутри стека. Сеть регистрации помечена internal, fixture не подключен к сети хранилища, а опубликованных host-портов нет; запросы не могут уйти во внешний почтовый сервис. Очистка удаляет контейнеры и inbox.
Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8025/__e2e/inbox` и синтетический `E2E_MAILBOX_TOKEN=local-e2e-mailbox-token`. Тест запрашивает `GET $E2E_MAILBOX_URL?to=<urlencoded email>` с `Authorization: Bearer $E2E_MAILBOX_TOKEN`; ответ содержит `messages` с полями `id`, `to`, `subject`, `text` и `html`. Registration-only tests должны пропускаться без `E2E_MAIL_FIXTURE=1`, поскольку стандартный `test-e2e` и `release-e2e` его не задают. Тесты не должны выводить содержимое письма или ссылку с одноразовым токеном. В этом режиме runner отключает трассировку Playwright. Обычный `test-e2e` по-прежнему задает `EMAIL_PROVIDER=disabled`, а `release-e2e` использует release-образы без fixture и не пишет evidence для mail-fixture образа. Режим отказывается запускаться с `LINCODEX_RELEASE_TAG`.
Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Будущие бизнес-тесты создают своих синтетических пользователей и записи через публичный API в свежем стеке каждого прогона; общие фикстуры и реальные данные не используются.
Набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium, верстку и доступность. CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-<n>` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate.