Files
lincodex/backend/integration_test/need_http_test.go
T

447 lines
20 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
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/port/outbound"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
needusecase "lincodex/backend/internal/usecase/need"
"lincodex/backend/internal/usecase/organization"
)
func TestOrganizationNeedOwnerWorkflowOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
defer cancel()
harness := newNeedHTTPHarness(ctx, t, env)
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, "need-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreign := createOrganizationHTTPUser(ctx, t, harness, "need-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "need-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidate := createOrganizationHTTPUser(ctx, t, harness, "need-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
unverified := createOrganizationHTTPUser(ctx, t, harness, "need-unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.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")
organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "need-http-company")
insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now)
basePath := "/api/v1/organizations/" + organizationID.String() + "/needs"
initialSource := `{"title":"Payments backend","source_text":"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."}`
createdResponses := parallelNeedRequests(t, harness, http.MethodPost, basePath, initialSource,
env.Config.AppPublicURL, ownerSession, "need-http-create-1", 2)
if createdResponses[0].Code != http.StatusCreated || createdResponses[1].Code != http.StatusCreated ||
createdResponses[0].Header().Get("Cache-Control") != "no-store" || string(createdResponses[0].Body.Bytes()) != string(createdResponses[1].Body.Bytes()) {
t.Fatalf("concurrent need create responses = %d %s and %d %s, want the same 201 response",
createdResponses[0].Code, createdResponses[0].Body.String(), createdResponses[1].Code, createdResponses[1].Body.String())
}
originalBody := append([]byte(nil), createdResponses[0].Body.Bytes()...)
created := decodeNeedHTTPResponse(t, originalBody)
if created.ID == uuid.Nil || created.Version != 1 || created.RequirementsVersion != 1 || created.Recommendations.Status != string(domain.NeedRecommendationsNotAvailable) {
t.Fatalf("created need identity or recommendation state = %+v", created)
}
if created.Requirements.Specialization.Status != string(domain.NeedValueExtracted) ||
created.Requirements.Specialization.Source == nil || created.Requirements.Specialization.Source.Origin != string(domain.NeedValueExtractedFromText) ||
created.Requirements.Grade.Status != string(domain.NeedValueUnknown) || created.Requirements.Grade.Value != nil {
t.Fatalf("source extraction invented or omitted a need value: %+v", created.Requirements)
}
gotSkills := make([]string, 0, len(created.Requirements.RequiredSkills))
for _, skill := range created.Requirements.RequiredSkills {
if skill.Status == string(domain.NeedItemExtracted) && skill.Source.Origin == string(domain.NeedValueExtractedFromText) {
gotSkills = append(gotSkills, skill.Name)
}
}
if !equalNeedStrings(gotSkills, []string{"Go", "PostgreSQL", "Temporal"}) {
t.Fatalf("extracted required skills = %v, want Go, PostgreSQL, Temporal", gotSkills)
}
if len(created.Readiness.MissingFields) == 0 {
t.Fatal("incomplete source text need has no readiness questions")
}
needPath := basePath + "/" + created.ID.String()
changedKeyBody := `{"title":"Different request"}`
changedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, changedKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
requireSessionProblem(t, changedKey, http.StatusUnprocessableEntity, "idempotency_key_reused")
invalidNUL := organizationHTTPRequest(t, harness, http.MethodPost, basePath,
`{"title":"Bad\u0000title"}`, env.Config.AppPublicURL, ownerSession, "need-http-invalid-nul")
requireSessionProblem(t, invalidNUL, http.StatusBadRequest, "validation_failed")
var invalidProblem struct {
Errors []struct {
Pointer string `json:"pointer"`
} `json:"errors"`
}
if err := json.Unmarshal(invalidNUL.Body.Bytes(), &invalidProblem); err != nil || len(invalidProblem.Errors) == 0 {
t.Fatalf("NUL validation body = %s, decode error %v", invalidNUL.Body.String(), err)
}
updated := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
`{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"}]}`,
env.Config.AppPublicURL, ownerSession, "")
if updated.Code != http.StatusOK {
t.Fatalf("confirm extracted skill = %d %s, want 200", updated.Code, updated.Body.String())
}
confirmed := decodeNeedHTTPResponse(t, updated.Body.Bytes())
if confirmed.Version != 2 || confirmed.RequirementsVersion != 2 || confirmed.Recommendations.Status != string(domain.NeedRecommendationsPending) ||
len(confirmed.Requirements.RequiredSkills) != 1 || confirmed.Requirements.RequiredSkills[0].Name != "Go" ||
confirmed.Requirements.RequiredSkills[0].Status != string(domain.NeedItemConfirmed) {
t.Fatalf("confirmed need state = %+v", confirmed)
}
currentRead := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", ownerSession, "")
if currentRead.Code != http.StatusOK || string(currentRead.Body.Bytes()) == string(originalBody) {
t.Fatalf("current need read = %d %s, want edited current version", currentRead.Code, currentRead.Body.String())
}
immutableReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, initialSource,
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
if immutableReplay.Code != http.StatusCreated || string(immutableReplay.Body.Bytes()) != string(originalBody) {
t.Fatalf("live create replay = %d %s, want the original 201 body %s", immutableReplay.Code, immutableReplay.Body.String(), originalBody)
}
expiryKeyBody := `{"title":"Boundary need"}`
expiryKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if expiryKey.Code != http.StatusCreated {
t.Fatalf("create need for expiry boundary = %d %s, want 201", expiryKey.Code, expiryKey.Body.String())
}
expiryOriginal := decodeNeedHTTPResponse(t, expiryKey.Body.Bytes())
boundary := harness.clock.Now()
expired, err := harness.pool.Exec(ctx,
`UPDATE idempotency_records AS record
SET created_at = $1, expires_at = $2
WHERE EXISTS (
SELECT 1 FROM organization_need_creation_results AS result
WHERE result.scope_hash = record.scope_hash
AND result.snapshot #>> '{need,title}' = 'Boundary need'
)`,
boundary.Add(-outbound.IdempotencyRetention), boundary)
if err != nil {
t.Fatalf("expire need create key at exact 24-hour boundary: %v", err)
}
if expired.RowsAffected() != 1 {
t.Fatalf("expired need create rows = %d, want 1", expired.RowsAffected())
}
reusedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if reusedKey.Code != http.StatusCreated {
t.Fatalf("create after exact 24-hour replay boundary = %d %s, want a new 201", reusedKey.Code, reusedKey.Body.String())
}
replacement := decodeNeedHTTPResponse(t, reusedKey.Body.Bytes())
if replacement.ID == expiryOriginal.ID || replacement.Version != 1 {
t.Fatalf("expired key reused old need snapshot: %+v", replacement)
}
expiredReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if expiredReplay.Code != http.StatusCreated || string(expiredReplay.Body.Bytes()) != string(reusedKey.Body.Bytes()) {
t.Fatalf("replay after expired-key reuse = %d %s, want exact replacement response %s", expiredReplay.Code, expiredReplay.Body.String(), reusedKey.Body.String())
}
identicalUpdates := parallelNeedRequests(t, harness, http.MethodPatch, needPath,
`{"expected_version":2,"title":"Platform engineer"}`, env.Config.AppPublicURL, ownerSession, "", 2)
for index, response := range identicalUpdates {
if response.Code != http.StatusOK {
t.Fatalf("identical concurrent update %d = %d %s, want 200", index, response.Code, response.Body.String())
}
}
concurrentCurrent := decodeNeedHTTPResponse(t, identicalUpdates[0].Body.Bytes())
if concurrentCurrent.Version != 3 || concurrentCurrent.Title != "Platform engineer" {
t.Fatalf("identical concurrent update result = version %d title %q, want version 3", concurrentCurrent.Version, concurrentCurrent.Title)
}
differentUpdates := parallelNeedRequestsWithBodies(t, harness, http.MethodPatch, needPath,
[]string{`{"expected_version":3,"title":"Payments platform"}`, `{"expected_version":3,"title":"Cloud platform"}`},
env.Config.AppPublicURL, ownerSession)
var winner needHTTPResponse
successes := 0
conflicts := 0
for index, response := range differentUpdates {
switch response.Code {
case http.StatusOK:
successes++
winner = decodeNeedHTTPResponse(t, response.Body.Bytes())
case http.StatusPreconditionFailed:
conflicts++
default:
t.Fatalf("different concurrent update %d = %d %s, want 200 or 412", index, response.Code, response.Body.String())
}
}
if successes != 1 || conflicts != 1 || winner.Version != 4 {
t.Fatalf("different concurrent updates had %d successes and %d conflicts; winner = %+v, want one version 4 success", successes, conflicts, winner)
}
staleNoOp := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
fmt.Sprintf(`{"expected_version":3,"title":%q}`, winner.Title), env.Config.AppPublicURL, ownerSession, "")
if staleNoOp.Code != http.StatusOK || decodeNeedHTTPResponse(t, staleNoOp.Body.Bytes()).Version != 4 {
t.Fatalf("stale no-op update = %d %s, want current version 4", staleNoOp.Code, staleNoOp.Body.String())
}
staleInvalid := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
`{"expected_version":3,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"go","status":"confirmed"}]}`,
env.Config.AppPublicURL, ownerSession, "")
requireSessionProblem(t, staleInvalid, http.StatusPreconditionFailed, "version_conflict")
secondNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Second need"}`,
env.Config.AppPublicURL, ownerSession, "need-http-create-2")
thirdNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Third need"}`,
env.Config.AppPublicURL, ownerSession, "need-http-create-3")
if secondNeed.Code != http.StatusCreated || thirdNeed.Code != http.StatusCreated {
t.Fatalf("create needs for pagination = %d %s and %d %s, want 201", secondNeed.Code, secondNeed.Body.String(), thirdNeed.Code, thirdNeed.Body.String())
}
firstPage := readNeedHTTPPage(t, harness, ownerSession, basePath+"?limit=1")
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first need page = %+v, want one item and cursor", firstPage)
}
secondPage := readNeedHTTPPage(t, harness, ownerSession,
basePath+"?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor))
if len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil ||
firstPage.Items[0].ID == secondPage.Items[0].ID {
t.Fatalf("second need page = %+v, want the next distinct item", secondPage)
}
for _, test := range []struct {
name string
session organizationHTTPSession
want int
}{
{name: "foreign owner", session: foreignSession, want: http.StatusNotFound},
{name: "active recruiter", session: recruiterSession, want: http.StatusForbidden},
{name: "candidate", session: candidateSession, want: http.StatusForbidden},
} {
t.Run(test.name, func(t *testing.T) {
response := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", test.session, "")
if response.Code != test.want {
t.Fatalf("need read = %d %s, want %d", response.Code, response.Body.String(), test.want)
}
if strings.Contains(response.Body.String(), "Payments backend") || strings.Contains(response.Body.String(), "PostgreSQL") {
t.Fatalf("denied response contains need data: %s", response.Body.String())
}
})
}
var versionCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2", organizationID, created.ID).Scan(&versionCount); err != nil {
t.Fatalf("read immutable need history: %v", err)
}
if versionCount != 4 {
t.Fatalf("need history rows = %d, want 4", versionCount)
}
}
type needHTTPResponse struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
Requirements struct {
Specialization struct {
Status string `json:"status"`
Value *string `json:"value"`
Source *struct {
Origin string `json:"origin"`
} `json:"source"`
} `json:"specialization"`
Grade struct {
Status string `json:"status"`
Value *string `json:"value"`
} `json:"grade"`
RequiredSkills []struct {
Name string `json:"name"`
Status string `json:"status"`
Source struct {
Origin string `json:"origin"`
} `json:"source"`
} `json:"required_skills"`
} `json:"requirements"`
Readiness struct {
MissingFields []json.RawMessage `json:"missing_fields"`
} `json:"readiness"`
Recommendations struct {
Status string `json:"status"`
} `json:"recommendations"`
}
func decodeNeedHTTPResponse(t *testing.T, encoded []byte) needHTTPResponse {
t.Helper()
var response needHTTPResponse
if err := json.Unmarshal(encoded, &response); err != nil {
t.Fatalf("decode need response: %v", err)
}
return response
}
func equalNeedStrings(left, right []string) bool {
if len(left) != len(right) {
return false
}
for index := range left {
if left[index] != right[index] {
return false
}
}
return true
}
type needHTTPPage struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
func readNeedHTTPPage(t *testing.T, harness *sessionHTTPHarness, session organizationHTTPSession, path string) needHTTPPage {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
if response.Code != http.StatusOK {
t.Fatalf("list organization needs = %d %s, want 200", response.Code, response.Body.String())
}
var page needHTTPPage
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
t.Fatalf("decode need list response: %v", err)
}
return page
}
func parallelNeedRequests(
t *testing.T,
harness *sessionHTTPHarness,
method, path, body, origin string,
session organizationHTTPSession,
idempotencyKey string,
count int,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, count)
var group sync.WaitGroup
start := make(chan struct{})
for index := range count {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, idempotencyKey)
})
}
close(start)
group.Wait()
return responses
}
func parallelNeedRequestsWithBodies(
t *testing.T,
harness *sessionHTTPHarness,
method, path string,
bodies []string,
origin string,
session organizationHTTPSession,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, len(bodies))
var group sync.WaitGroup
start := make(chan struct{})
for index, body := range bodies {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, "")
})
}
close(start)
group.Wait()
return responses
}
func newNeedHTTPHarness(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)
}
needService, err := needusecase.NewService(needusecase.Dependencies{
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
})
if err != nil {
t.Fatalf("need.NewService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(io.Discard, 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)
needHandler := v1.NewNeedHandler(needService)
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler),
)
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 needHTTPPath(organizationID, needID uuid.UUID) string {
return fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID)
}