//go:build integration package integration_test import ( "context" "encoding/json" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" httpadapter "lincodex/backend/internal/adapter/primary/http" "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" "lincodex/backend/internal/adapter/secondary/argon2id" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/usecase/health" "lincodex/backend/internal/usecase/identity" "lincodex/backend/internal/usecase/organization" ) const organizationHTTPTestTimeout = 5 * time.Minute type organizationHTTPSession struct { cookie *http.Cookie csrf string } func TestOrganizationCreationAndOwnerEditingOverHTTP(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) defer cancel() harness := newOrganizationHTTPHarness(ctx, t, env) initialLogs := harness.logs resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) truncateTables(ctx, t, harness.pool, resetTables...) passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) if err != nil { t.Fatalf("HashNewPassword() error = %v", err) } now := harness.clock.Now() owner := createOrganizationHTTPUser(ctx, t, harness, "owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) foreign := createOrganizationHTTPUser(ctx, t, harness, "foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) candidate := createOrganizationHTTPUser(ctx, t, harness, "candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) unverified := createOrganizationHTTPUser(ctx, t, harness, "unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now) ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass, env.Config.AppPublicURL, "", "192.0.2.44:1234") requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified") if len(unverifiedLogin.Header().Values("Set-Cookie")) != 0 { t.Fatal("unverified account received a session cookie") } createBody := "{\"name\":\"ООО Тестовая компания\",\"description\":\"Профиль компании\",\"contacts\":{\"website\":\"https://company.example.test\",\"email\":\"careers@example.test\",\"phone\":\"+74950000000\",\"telegram\":\"@company_careers\"},\"representatives\":[{\"name\":\"Ирина Проверочная\",\"job_title\":\"Руководитель найма\"}]}" createResponses := make(chan *httptest.ResponseRecorder, 2) for range 2 { go func() { createResponses <- organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, env.Config.AppPublicURL, ownerSession, "organization-http-create-1") }() } created := <-createResponses concurrentReplay := <-createResponses if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" { t.Fatalf("create response = %d %s, Cache-Control=%q, want 201 no-store", created.Code, created.Body.String(), created.Header().Get("Cache-Control")) } originalBody := append([]byte(nil), created.Body.Bytes()...) if concurrentReplay.Code != http.StatusCreated || string(concurrentReplay.Body.Bytes()) != string(originalBody) { t.Fatalf("concurrent create = %d %s, want the same 201 body %s", concurrentReplay.Code, concurrentReplay.Body.String(), originalBody) } var creation struct { ID string `json:"id"` Version int64 `json:"version"` Name string `json:"name"` Verification struct { Level string `json:"level"` Basis string `json:"basis"` } `json:"verification"` CandidateCard map[string]json.RawMessage `json:"candidate_card"` } if err := json.Unmarshal(originalBody, &creation); err != nil { t.Fatalf("decode created organization: %v", err) } if creation.ID == "" || creation.Version != 1 || creation.Name != "ООО Тестовая компания" || creation.Verification.Level != "e0" || creation.Verification.Basis != "confirmed_email" { t.Fatalf("created company has unexpected identity or verification: %+v", creation) } for _, key := range []string{"id", "name", "description", "sphere", "contacts", "representatives", "verification_level"} { if _, ok := creation.CandidateCard[key]; !ok { t.Fatalf("candidate card has no %q field: %v", key, creation.CandidateCard) } } for _, key := range []string{"owner", "membership", "role", "email_verified", "user_id", "password"} { if _, ok := creation.CandidateCard[key]; ok { t.Fatalf("candidate card exposes private %q field", key) } } assertOrganizationHTTPCounts(ctx, t, harness.pool, 1, 1, 1, 1) organizationID := creation.ID var storedRole, storedState string if err := harness.pool.QueryRow(ctx, "SELECT role, state FROM memberships WHERE organization_id = $1 AND user_id = $2", organizationID, owner.ID, ).Scan(&storedRole, &storedState); err != nil { t.Fatalf("read creator membership: %v", err) } if storedRole != "owner" || storedState != "active" { t.Fatalf("stored creator membership = %s/%s, want active owner", storedRole, storedState) } updated := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, "{\"expected_version\":1,\"name\":\"ООО Обновленная компания\",\"description\":null}", env.Config.AppPublicURL, ownerSession, "") if updated.Code != http.StatusOK { t.Fatalf("owner update = %d %s, want 200", updated.Code, updated.Body.String()) } var updatedBody struct { Version int64 `json:"version"` Name string `json:"name"` Description *string `json:"description"` Verification struct { Level string `json:"level"` Basis string `json:"basis"` } `json:"verification"` } if err := json.Unmarshal(updated.Body.Bytes(), &updatedBody); err != nil { t.Fatalf("decode updated organization: %v", err) } if updatedBody.Version != 2 || updatedBody.Name != "ООО Обновленная компания" || updatedBody.Description != nil || updatedBody.Verification.Level != "e0" || updatedBody.Verification.Basis != "confirmed_email" { t.Fatalf("updated organization = %+v, want edited profile and unchanged E0", updatedBody) } harness.pool.Close() harness = newOrganizationHTTPHarness(ctx, t, env) restartedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", "", ownerSession, "") if restartedRead.Code != http.StatusOK { t.Fatalf("read with a new handler and pool = %d %s, want 200", restartedRead.Code, restartedRead.Body.String()) } var restartedBody struct { Version int64 `json:"version"` Name string `json:"name"` } if err := json.Unmarshal(restartedRead.Body.Bytes(), &restartedBody); err != nil { t.Fatalf("decode organization after handler restart: %v", err) } if restartedBody.Version != 2 || restartedBody.Name != "ООО Обновленная компания" { t.Fatalf("organization after handler restart = %+v, want the persisted owner update", restartedBody) } staleUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, "{\"expected_version\":1,\"name\":\"ООО Устаревшее изменение\"}", env.Config.AppPublicURL, ownerSession, "") requireSessionProblem(t, staleUpdate, http.StatusPreconditionFailed, "version_conflict") replay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, env.Config.AppPublicURL, ownerSession, "organization-http-create-1") if replay.Code != http.StatusCreated || replay.Header().Get("Cache-Control") != "no-store" || string(replay.Body.Bytes()) != string(originalBody) { t.Fatalf("same-key replay = %d %s, want the exact original 201 body %s", replay.Code, replay.Body.String(), originalBody) } changed := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", "{\"name\":\"ООО Другой запрос\"}", env.Config.AppPublicURL, ownerSession, "organization-http-create-1") requireSessionProblem(t, changed, http.StatusUnprocessableEntity, "idempotency_key_reused") replayTime := harness.clock.Now() expired, err := harness.pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2", replayTime.Add(-2*time.Second), replayTime.Add(-time.Second)) if err != nil { t.Fatalf("expire the original create key: %v", err) } if expired.RowsAffected() != 1 { t.Fatalf("expired idempotency rows = %d, want 1", expired.RowsAffected()) } reused := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, env.Config.AppPublicURL, ownerSession, "organization-http-create-1") if reused.Code != http.StatusCreated { t.Fatalf("create with an expired key = %d %s, want 201", reused.Code, reused.Body.String()) } var reusedBody struct { ID string `json:"id"` } if err := json.Unmarshal(reused.Body.Bytes(), &reusedBody); err != nil { t.Fatalf("decode organization created after key expiration: %v", err) } if reusedBody.ID == organizationID { t.Fatal("expired key replayed the old company instead of creating a new one") } reusedReplay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, env.Config.AppPublicURL, ownerSession, "organization-http-create-1") if reusedReplay.Code != http.StatusCreated || string(reusedReplay.Body.Bytes()) != string(reused.Body.Bytes()) { t.Fatalf("replay after key reuse = %d %s, want the replacement snapshot %s", reusedReplay.Code, reusedReplay.Body.String(), reused.Body.String()) } assertOrganizationHTTPCounts(ctx, t, harness.pool, 2, 2, 2, 1) foreignRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", "", foreignSession, "") requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") foreignUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, "{\"expected_version\":2,\"name\":\"Не владелец\"}", env.Config.AppPublicURL, foreignSession, "") requireSessionProblem(t, foreignUpdate, http.StatusNotFound, "not_found") candidateCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", "{\"name\":\"Кандидат не может создать компанию\"}", env.Config.AppPublicURL, candidateSession, "organization-http-candidate-create") requireSessionProblem(t, candidateCreate, http.StatusForbidden, "forbidden") // The failed owner insert must roll back the organization and idempotency // reservation together. Reusing the same key after removing the constraint // proves the request left no partial state. if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships ADD CONSTRAINT organization_http_reject_owner CHECK (role <> 'owner') NOT VALID"); err != nil { t.Fatalf("install temporary owner failure constraint: %v", err) } t.Cleanup(func() { _, _ = harness.pool.Exec(context.WithoutCancel(ctx), "ALTER TABLE memberships DROP CONSTRAINT IF EXISTS organization_http_reject_owner") }) beforeFailure := readOrganizationHTTPCounts(ctx, t, harness.pool) rollbackBody := "{\"name\":\"ООО Повтор после отката\"}" failedCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") if failedCreate.Code != http.StatusInternalServerError { t.Fatalf("owner insert failure status = %d %s, want 500", failedCreate.Code, failedCreate.Body.String()) } assertOrganizationHTTPCountsEqual(ctx, t, harness.pool, beforeFailure) if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships DROP CONSTRAINT organization_http_reject_owner"); err != nil { t.Fatalf("remove temporary owner failure constraint: %v", err) } recoveredCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") if recoveredCreate.Code != http.StatusCreated { t.Fatalf("create after rollback = %d %s, want 201 with the same idempotency key", recoveredCreate.Code, recoveredCreate.Body.String()) } for _, marker := range []string{ owner.Email.Address(), foreign.Email.Address(), candidate.Email.Address(), unverified.Email.Address(), "Ирина Проверочная", "careers@example.test", "ООО Тестовая компания", "ООО Обновленная компания", } { if strings.Contains(initialLogs.String(), marker) || strings.Contains(harness.logs.String(), marker) { t.Fatalf("organization HTTP logs contain profile or account data %q", marker) } } } func newOrganizationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { t.Helper() pool := env.newPool(ctx, t) store := postgresadapter.NewIdentityStore(pool) hasher, err := argon2id.NewHasher(1) if err != nil { t.Fatalf("NewHasher() error = %v", err) } credentials := identity.NewCredentials(hasher) keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) if err != nil { t.Fatalf("NewKeyring() error = %v", err) } clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} sessionService, err := identity.NewSessionService(identity.SessionDependencies{ Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, }, identity.SessionSettings{ ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, }) if err != nil { t.Fatalf("NewSessionService() error = %v", err) } organizationService, err := organization.NewService(organization.Dependencies{ Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, }) if err != nil { t.Fatalf("organization.NewService() error = %v", err) } logs := &strings.Builder{} logger := slog.New(slog.NewJSONHandler(logs, nil)) responder := problem.NewResponder(logger) healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessionService), v1.WithPublicOrigin(env.Config.AppPublicURL), ) organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), ) router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) if err != nil { t.Fatalf("NewRouter() error = %v", err) } return &sessionHTTPHarness{ pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs, } } func createOrganizationHTTPUser( ctx context.Context, t *testing.T, harness *sessionHTTPHarness, email string, passwordHash domain.PasswordHash, scenario domain.Scenario, verified bool, now time.Time, ) domain.User { t.Helper() address, err := domain.NewEmailAddress(email) if err != nil { t.Fatalf("NewEmailAddress() error = %v", err) } user, err := domain.NewUser(domain.Registration{ Email: address, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: now, }) if err != nil { t.Fatalf("NewUser() error = %v", err) } if err := harness.store.Users().Create(ctx, user); err != nil { t.Fatalf("Create(%q) error = %v", email, err) } if !verified { return user } user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) if err != nil { t.Fatalf("MarkEmailVerified() error = %v", err) } return user } func loginOrganizationHTTP(t *testing.T, harness *sessionHTTPHarness, email string) organizationHTTPSession { t.Helper() response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.40:1234") if response.Code != http.StatusCreated { t.Fatalf("login status = %d %s, want 201", response.Code, response.Body.String()) } var body struct { CSRFToken string `json:"csrf_token"` } if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatalf("decode login response: %v", err) } if body.CSRFToken == "" { t.Fatal("login response has no CSRF token") } return organizationHTTPSession{cookie: requireSessionCookie(t, response), csrf: body.CSRFToken} } func organizationHTTPRequest( t *testing.T, harness *sessionHTTPHarness, method, path, body, origin string, session organizationHTTPSession, idempotencyKey string, ) *httptest.ResponseRecorder { t.Helper() request := httptest.NewRequest(method, path, strings.NewReader(body)) if body != "" { request.Header.Set("Content-Type", "application/json") } if origin != "" { request.Header.Set("Origin", origin) } if session.cookie != nil { request.AddCookie(&http.Cookie{Name: "__Host-lincodex_session", Value: session.cookie.Value}) } if session.csrf != "" { request.Header.Set("X-CSRF-Token", session.csrf) } if idempotencyKey != "" { request.Header.Set("Idempotency-Key", idempotencyKey) } request.RemoteAddr = "192.0.2.41:1234" recorder := httptest.NewRecorder() harness.router.ServeHTTP(recorder, request) return recorder } type organizationHTTPRowCounts struct { organizations int64 representatives int64 memberships int64 results int64 idempotency int64 } func readOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool) organizationHTTPRowCounts { t.Helper() var counts organizationHTTPRowCounts if err := pool.QueryRow(ctx, ` SELECT (SELECT count(*) FROM organizations), (SELECT count(*) FROM organization_representatives), (SELECT count(*) FROM memberships), (SELECT count(*) FROM organization_creation_results), (SELECT count(*) FROM idempotency_records) `).Scan(&counts.organizations, &counts.representatives, &counts.memberships, &counts.results, &counts.idempotency); err != nil { t.Fatalf("read organization transaction counts: %v", err) } return counts } func assertOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizations, representatives, memberships, results int64, ) { t.Helper() counts := readOrganizationHTTPCounts(ctx, t, pool) if counts.organizations != organizations || counts.representatives != representatives || counts.memberships != memberships || counts.results != results { t.Fatalf("organization rows = %+v, want org=%d representatives=%d memberships=%d snapshots=%d", counts, organizations, representatives, memberships, results) } } func assertOrganizationHTTPCountsEqual(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want organizationHTTPRowCounts) { t.Helper() if got := readOrganizationHTTPCounts(ctx, t, pool); got != want { t.Fatalf("failed organization create changed transactional rows: got %+v, want %+v", got, want) } }