//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" "net/url" "slices" "strings" "sync" "testing" "time" "github.com/google/uuid" 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/postgres/sqlc" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/anonymousprofile" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/health" "lincodex/backend/internal/usecase/identity" invitationusecase "lincodex/backend/internal/usecase/invitation" needusecase "lincodex/backend/internal/usecase/need" "lincodex/backend/internal/usecase/notification" "lincodex/backend/internal/usecase/notification/mailtemplate" "lincodex/backend/internal/usecase/organization" "lincodex/backend/internal/usecase/policy" ) const invitationHTTPTimeout = 10 * time.Minute // Private values of the visible candidates. None of them may appear in any // response, problem, or log of the organization's invitation operations. const ( invitationCandidateName = "Hidden Candidate Name" invitationCandidateContact = "hidden-candidate-contact@example.test" invitationCandidateMarker = "Hidden Candidate Employer" ) type invitationHTTPHarness struct { *sessionHTTPHarness key domain.CandidateViewPseudonymKey } func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *invitationHTTPHarness { 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) } key, err := keyring.CandidateViewPseudonymKey() if err != nil { t.Fatalf("CandidateViewPseudonymKey() error = %v", err) } clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} transactor := postgresadapter.NewTransactor(pool) sessionService, err := identity.NewSessionService(identity.SessionDependencies{ Transactor: transactor, 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: transactor, Keyring: keyring, Clock: clock.Now}) if err != nil { t.Fatalf("organization.NewService() error = %v", err) } needService, err := needusecase.NewService(needusecase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock.Now}) if err != nil { t.Fatalf("need.NewService() error = %v", err) } quota := companyquota.NewService(clock.Now) views, err := candidateview.NewService(candidateview.Dependencies{ Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now), PseudonymKey: key, Clock: clock.Now, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveCardView(ctx, unit, organization, candidateID) }, }) if err != nil { t.Fatalf("candidateview.NewService() error = %v", err) } templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) if err != nil { t.Fatalf("NewRenderer() error = %v", err) } notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), clock.Now)) if err != nil { t.Fatalf("NewInvitationNotifier() error = %v", err) } invitationService, err := invitationusecase.NewService(invitationusecase.Dependencies{ Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveInvitation(ctx, unit, organization, invitationID) }, Notifier: notifier, Clock: clock.Now, }) if err != nil { t.Fatalf("invitation.NewService() error = %v", err) } inbox, err := notification.NewInboxService(transactor, notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(false)), clock.Now) if err != nil { t.Fatalf("notification.NewInboxService() 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), v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)), v1.WithNotifications(v1.NewNotificationHandler(inbox)), ) 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 &invitationHTTPHarness{ sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, key: key, } } // invitationHTTPBody is the part of the organization's invitation that the // tests read. Fields that must be absent have no member, so a leak shows up as // an unknown key in the raw text that the tests also scan. type invitationHTTPBody struct { ID uuid.UUID `json:"id"` OrganizationID uuid.UUID `json:"organization_id"` CandidateHandle string `json:"candidate_handle"` Need *struct { NeedID uuid.UUID `json:"need_id"` RequirementsVersion int64 `json:"requirements_version"` } `json:"need"` State string `json:"state"` ExpiryReason *string `json:"expiry_reason"` Version int64 `json:"version"` TermsVersion int64 `json:"terms_version"` Terms json.RawMessage `json:"terms"` ResponsePeriodDays int `json:"response_period_days"` ResponseDeadlineAt *string `json:"response_deadline_at"` SalaryRaiseUsed bool `json:"salary_raise_used"` SalaryFit string `json:"salary_fit"` ContactAccess struct { Status string `json:"status"` Fields []string `json:"fields"` } `json:"contact_access"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeliveredAt *string `json:"delivered_at"` ViewedAt *string `json:"viewed_at"` RespondedAt *string `json:"responded_at"` } type invitationHTTPPage struct { Items []struct { ID uuid.UUID `json:"id"` CandidateHandle string `json:"candidate_handle"` State string `json:"state"` Version int64 `json:"version"` TermsVersion int64 `json:"terms_version"` RoleTitle string `json:"role_title"` Salary struct { SalaryFrom int64 `json:"salary_from"` SalaryTo int64 `json:"salary_to"` TaxBasis string `json:"tax_basis"` } `json:"salary"` } `json:"items"` Page struct { HasMore bool `json:"has_more"` NextCursor *string `json:"next_cursor"` } `json:"page"` } type invitationHTTPProblem struct { Code string `json:"code"` Errors []struct { In string `json:"in"` Pointer string `json:"pointer"` Code string `json:"code"` } `json:"errors"` } func invitationTermsMap() map[string]any { return map[string]any{ "role_title": "Middle Go developer in the payments team", "specialization": "backend", "grade": "middle", "offer_type": "full_time", "tasks": []any{"Move the payout service to an event model", "Review the changes of the team"}, "team": "Six engineers and a team lead\nwho work in two-week iterations", "tech_stack": []any{"Go", "PostgreSQL"}, "work_formats": []any{"remote"}, "location": nil, "communication_method": map[string]any{ "channel": "email", "details": nil, }, "salary": map[string]any{ "salary_from": 100000, "salary_to": 140000, "currency": "RUB", "period": "month", "tax_basis": "net", }, "package": map[string]any{ "bonus": map[string]any{"status": "provided", "description": "Quarterly bonus up to 20% of the salary"}, "equipment": map[string]any{"status": "provided", "description": "Laptop of the employee's choice"}, "training": map[string]any{"status": "not_provided"}, "health_insurance": map[string]any{"status": "not_provided"}, }, } } // invitationCreateJSON builds a create request for the handle and lets the // caller change the request or its terms before it is encoded. func invitationCreateJSON(t *testing.T, handle string, change func(body, terms map[string]any)) string { t.Helper() terms := invitationTermsMap() body := map[string]any{"candidate_handle": handle, "terms": terms} if change != nil { change(body, terms) } encoded, err := json.Marshal(body) if err != nil { t.Fatalf("marshal invitation request: %v", err) } return string(encoded) } func invitationSalary(terms map[string]any) map[string]any { return terms["salary"].(map[string]any) } func decodeInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) invitationHTTPBody { t.Helper() if response.Code != wantStatus { t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), wantStatus) } if response.Header().Get("Cache-Control") != "no-store" { t.Fatalf("Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) } var body invitationHTTPBody if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatalf("decode invitation %s: %v", response.Body.String(), err) } return body } func requireInvitationValidation(t *testing.T, response *httptest.ResponseRecorder, wantPointer, wantFieldCode string) { t.Helper() if response.Code != http.StatusBadRequest { t.Fatalf("response = %d %s, want 400 validation_failed at %s", response.Code, response.Body.String(), wantPointer) } var body invitationHTTPProblem if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatalf("decode problem %s: %v", response.Body.String(), err) } if body.Code != "validation_failed" { t.Fatalf("problem code = %q in %s, want validation_failed", body.Code, response.Body.String()) } for _, field := range body.Errors { if field.Pointer == wantPointer && (wantFieldCode == "" || field.Code == wantFieldCode) { return } } t.Fatalf("problem %s has no error at %s with code %q", response.Body.String(), wantPointer, wantFieldCode) } func invitationCount(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, table string) int { t.Helper() var count int if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&count); err != nil { t.Fatalf("count %s: %v", table, err) } return count } type invitationStoredCounts struct{ invitations, termsVersions, events, results int } func readInvitationCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness) invitationStoredCounts { t.Helper() return invitationStoredCounts{ invitations: invitationCount(ctx, t, harness, "invitations"), termsVersions: invitationCount(ctx, t, harness, "invitation_terms_versions"), events: invitationCount(ctx, t, harness, "invitation_events"), results: invitationCount(ctx, t, harness, "invitation_creation_results"), } } func TestOrganizationInvitationDraftsOverHTTP(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) applyMigrations(ctx, t, databaseURL) isolated := *env isolated.Config.DatabaseURL = databaseURL setupPool := newPoolFor(ctx, t, databaseURL) if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { t.Fatalf("EnsureDemoProductPolicy() error = %v", err) } harness := newInvitationHTTPHarness(ctx, t, &isolated) // The policy takes effect when it is stored, after the clock of the // harness was first read. harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) origin := env.Config.AppPublicURL now := harness.clock.Now() passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) if err != nil { t.Fatalf("HashNewPassword() error = %v", err) } account := func(email string, scenario domain.Scenario) domain.User { return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) } ownerA, ownerB, ownerC := account("invite-owner-a@example.test", domain.ScenarioEmployer), account("invite-owner-b@example.test", domain.ScenarioEmployer), account("invite-owner-c@example.test", domain.ScenarioEmployer) recruiter := account("invite-recruiter@example.test", domain.ScenarioEmployer) candidateAccount := account("invite-candidate-account@example.test", domain.ScenarioCandidate) sessionA, sessionB, sessionC := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerC.Email.Address()) sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address()) sessionCandidate := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidateAccount.Email.Address()) orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "invite-company-a") orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "invite-company-b") orgC := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionC, "invite-company-c") insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now) // The candidates of the cards. Seven identical published candidates form // the visible cohort; the hiding and the revocation below remove them from // one organization at a time. identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} privacy := candidatePrivacyFixture{ ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, } profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} newVisibleCandidate := func(email string, publish bool) domain.User { candidate := privacy.candidate(t, email) verifyPrivacyCohortCandidate(t, privacy, candidate) consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) if publish { privacy.publish(t, candidate.ID, consent.ID(), 0, domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) } profiles.save(t, candidate.ID, domain.CandidateProfileInput{ FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), Stack: privacyCohortConfirmedItems("go"), Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", }), SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), }, 0) if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), }); err != nil { t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) } return candidate } cohort := make([]domain.User, 0, 7) for index := range 7 { cohort = append(cohort, newVisibleCandidate(fmt.Sprintf("invite-visible-%d@example.test", index), true)) } unpublished := newVisibleCandidate("invite-unpublished@example.test", false) revoked := newVisibleCandidate("invite-revoked@example.test", true) privacy.revokeC2(t, revoked.ID, now.Add(time.Minute)) hiddenFromA, hiddenFromB := cohort[0], cohort[1] privacy.hide(t, hiddenFromA.ID, orgA, now) privacy.hide(t, hiddenFromB.ID, orgB, now) for _, candidate := range cohort[2:5] { privacy.hide(t, candidate.ID, orgC, now) } alias := func(organizationID uuid.UUID, candidate domain.User) string { t.Helper() handle, err := harness.key.ForOrganization(organizationID, candidate.ID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } return handle } // Organization C sees four candidates, below the minimum cohort of five, // so none of its cards exists. suppressedForC := alias(orgC, cohort[5]) // A usable candidate of organization A, and the same person as B sees them. target := cohort[3] handleA, handleB := alias(orgA, target), alias(orgB, target) if handleA == handleB { t.Fatal("the same candidate has one handle in two organizations") } createPath := func(organizationID uuid.UUID) string { return fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID) } itemPath := func(organizationID, invitationID uuid.UUID) string { return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) } request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { t.Helper() return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) } var keySequence int nextKey := func() string { keySequence++ return fmt.Sprintf("invitation-http-key-%d", keySequence) } createDraft := func(organizationID uuid.UUID, session organizationHTTPSession, handle string, change func(body, terms map[string]any)) *httptest.ResponseRecorder { t.Helper() return request(http.MethodPost, createPath(organizationID), invitationCreateJSON(t, handle, change), session, nextKey()) } mustCreate := func(change func(body, terms map[string]any)) invitationHTTPBody { t.Helper() return decodeInvitationHTTP(t, createDraft(orgA, sessionA, handleA, change), http.StatusCreated) } candidateMarkers := []string{ invitationCandidateName, invitationCandidateContact, invitationCandidateMarker, target.ID.String(), unpublished.ID.String(), revoked.ID.String(), hiddenFromA.ID.String(), } requireNoCandidateData := func(label string, text string) { t.Helper() for _, marker := range candidateMarkers { if strings.Contains(text, marker) { t.Errorf("%s contains the private marker %q: %s", label, marker, text) } } for _, field := range []string{"candidate_id", "email", "phone", "telegram", "full_name", "salary_minimum", "minimum"} { if strings.Contains(text, `"`+field+`":`) { t.Errorf("%s contains the key %q: %s", label, field, text) } } } t.Run("stores a complete draft with its first terms version and audit", func(t *testing.T) { response := createDraft(orgA, sessionA, handleA, nil) created := decodeInvitationHTTP(t, response, http.StatusCreated) if created.ID == uuid.Nil || created.OrganizationID != orgA || created.State != "draft" || created.Version != 1 || created.TermsVersion != 1 || created.ResponsePeriodDays != 7 || created.ResponseDeadlineAt != nil || created.DeliveredAt != nil || created.ViewedAt != nil || created.RespondedAt != nil || created.ExpiryReason != nil || created.Need != nil || created.SalaryRaiseUsed { t.Fatalf("created draft = %+v, want an unsent version 1 with the default period", created) } if created.CandidateHandle != handleA || created.SalaryFit != "not_available" || created.ContactAccess.Status != "not_granted" || len(created.ContactAccess.Fields) != 0 { t.Fatalf("created draft names %q, fit %q, access %+v; want the card handle, no indicator, and no access", created.CandidateHandle, created.SalaryFit, created.ContactAccess) } requireNoCandidateData("created draft", response.Body.String()) var candidateID uuid.UUID var state string var version, termsVersion int64 if err := harness.pool.QueryRow(ctx, `SELECT candidate_id, state, version, terms_version FROM invitations WHERE id = $1`, created.ID). Scan(&candidateID, &state, &version, &termsVersion); err != nil { t.Fatalf("read the stored draft: %v", err) } if candidateID != target.ID || state != "draft" || version != 1 || termsVersion != 1 { t.Fatalf("stored draft = candidate %s state %s version %d/%d, want the resolved candidate in a version 1 draft", candidateID, state, version, termsVersion) } var from, to int64 var currency, period, basis string if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to, salary_currency, salary_period, salary_tax_basis FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to, ¤cy, &period, &basis); err != nil { t.Fatalf("read the stored terms version: %v", err) } if from != 100000 || to != 140000 || currency != "RUB" || period != "month" || basis != "net" { t.Fatalf("stored money = %d-%d %s %s %s, want whole rubles with their base", from, to, currency, period, basis) } var kind string var eventVersion, eventTerms int64 var actor uuid.UUID var changed []string if err := harness.pool.QueryRow(ctx, `SELECT kind, version, terms_version, actor_id, changed_fields FROM invitation_events WHERE invitation_id = $1`, created.ID). Scan(&kind, &eventVersion, &eventTerms, &actor, &changed); err != nil { t.Fatalf("read the audit event: %v", err) } if kind != "draft_created" || eventVersion != 1 || eventTerms != 1 || actor != ownerA.ID || len(changed) != 0 { t.Fatalf("audit event = %s %d/%d by %s changed %v, want a creation by the owner", kind, eventVersion, eventTerms, actor, changed) } read := request(http.MethodGet, itemPath(orgA, created.ID), "", sessionA, "") reread := decodeInvitationHTTP(t, read, http.StatusOK) requireNoCandidateData("read draft", read.Body.String()) if string(reread.Terms) != string(created.Terms) || reread.Version != 1 || reread.CandidateHandle != handleA { t.Fatalf("read draft differs from the created one: %s", read.Body.String()) } }) t.Run("accepts an explicit package of conditions that are not provided and refuses a left-out condition", func(t *testing.T) { none := func(body, terms map[string]any) { terms["package"] = map[string]any{ "bonus": map[string]any{"status": "not_provided"}, "equipment": map[string]any{"status": "not_provided"}, "training": map[string]any{"status": "not_provided"}, "health_insurance": map[string]any{"status": "not_provided"}, } } created := mustCreate(none) if !strings.Contains(string(created.Terms), `"training":{"status":"not_provided"}`) { t.Fatalf("stored package = %s, want the explicit choice back", created.Terms) } before := readInvitationCounts(ctx, t, harness) requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { delete(terms["package"].(map[string]any), "training") }), "/terms/package/training", "required") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { terms["package"].(map[string]any)["bonus"] = map[string]any{"status": "provided"} }), "/terms/package/bonus/description", "required") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { terms["package"].(map[string]any)["equipment"] = map[string]any{"status": "not_provided", "description": "Laptop"} }), "/terms/package/equipment", "invalid") if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("refused packages stored rows: %+v -> %+v", before, after) } }) t.Run("requires the base, the currency, whole thousands, and a width of 10 to 40 percent", func(t *testing.T) { before := readInvitationCounts(ctx, t, harness) cases := []struct { name string change func(terms map[string]any) pointer string }{ {"no tax basis", func(terms map[string]any) { delete(invitationSalary(terms), "tax_basis") }, "/terms/salary/tax_basis"}, {"unknown tax basis", func(terms map[string]any) { invitationSalary(terms)["tax_basis"] = "before_tax" }, "/terms/salary/tax_basis"}, {"zero lower bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 0 }, "/terms/salary/salary_from"}, {"lower bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100500 }, "/terms/salary/salary_from"}, {"upper bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 140500 }, "/terms/salary/salary_to"}, {"fractional bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100000.5 }, "/terms/salary/salary_from"}, {"foreign currency", func(terms map[string]any) { invitationSalary(terms)["currency"] = "USD" }, "/terms/salary/currency"}, {"yearly period", func(terms map[string]any) { invitationSalary(terms)["period"] = "year" }, "/terms/salary/period"}, {"equal bounds", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 100000 }, "/terms/salary/salary_to"}, {"reversed bounds", func(terms map[string]any) { invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 140000, 100000 }, "/terms/salary/salary_to"}, {"just below 10 percent", func(terms map[string]any) { invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 95000, 104000 }, "/terms/salary/salary_to"}, {"just above 40 percent", func(terms map[string]any) { invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 80000, 121000 }, "/terms/salary/salary_to"}, {"far too wide", func(terms map[string]any) { invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 1000, 100000000 }, "/terms/salary/salary_to"}, } for _, test := range cases { requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { test.change(terms) }), test.pointer, "") } if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("refused ranges stored rows: %+v -> %+v", before, after) } // The exact boundaries are accepted and stored without rounding. for _, boundary := range []struct{ from, to int }{{95000, 105000}, {80000, 120000}, {100000, 140000}} { created := mustCreate(func(body, terms map[string]any) { invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = boundary.from, boundary.to }) var from, to int64 if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to); err != nil { t.Fatalf("read the stored range: %v", err) } if from != int64(boundary.from) || to != int64(boundary.to) { t.Fatalf("stored range = %d-%d, want %d-%d", from, to, boundary.from, boundary.to) } } // The gross base is as valid as the net base and is kept as chosen. gross := mustCreate(func(body, terms map[string]any) { invitationSalary(terms)["tax_basis"] = "gross" }) if !strings.Contains(string(gross.Terms), `"tax_basis":"gross"`) { t.Fatalf("gross draft terms = %s", gross.Terms) } }) t.Run("applies the other rules of the terms with the pointer of the field", func(t *testing.T) { before := readInvitationCounts(ctx, t, harness) requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { terms["work_formats"] = []any{"remote", "office"} }), "/terms/location", "") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { terms["tech_stack"] = []any{"Go", "PostgreSQL", "GO"} }), "/terms/tech_stack/2", "") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { terms["role_title"] = "Bad\u0000title" }), "/terms/role_title", "") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { delete(terms, "communication_method") }), "/terms/communication_method", "required") requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body["response_period_days"] = 5 }), "/response_period_days", "") // A request cannot name the candidate by anything but the handle, set // the state, a version, an indicator, or the candidate's minimum. for _, field := range []string{"candidate_email", "state", "version", "salary_fit", "salary_minimum", "candidate_id"} { response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body[field] = "x" }) if response.Code != http.StatusBadRequest { t.Errorf("a request with %s = %d %s, want 400", field, response.Code, response.Body.String()) } } withLocation := mustCreate(func(body, terms map[string]any) { terms["work_formats"] = []any{"remote", "hybrid"} terms["location"] = "Kazan" body["response_period_days"] = 14 }) if withLocation.ResponsePeriodDays != 14 || !strings.Contains(string(withLocation.Terms), `"location":"Kazan"`) { t.Fatalf("draft with a place of work = %+v", withLocation) } if after := readInvitationCounts(ctx, t, harness); after.invitations != before.invitations+1 { t.Fatalf("rules stored %d invitations, want only the valid one", after.invitations-before.invitations) } }) t.Run("resolves the handle through the visibility barrier and shows nothing of a refused card", func(t *testing.T) { before := readInvitationCounts(ctx, t, harness) refused := map[string]string{ "a handle of another organization": handleB, "a candidate hidden from the company": alias(orgA, hiddenFromA), "a candidate who revoked C2": alias(orgA, revoked), "a candidate who never published": alias(orgA, unpublished), "an unknown handle": "cv1_" + strings.Repeat("Z", 43), } var shapes []string for name, handle := range refused { response := createDraft(orgA, sessionA, handle, nil) requireInvitationValidation(t, response, "/candidate_handle", "") requireNoCandidateData(name, response.Body.String()) var body invitationHTTPProblem if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatalf("decode refusal: %v", err) } shapes = append(shapes, fmt.Sprint(body)) } // Every refusal looks the same, so the answer does not tell which case // applied. for _, shape := range shapes[1:] { if shape != shapes[0] { t.Fatalf("refusals differ: %s and %s", shapes[0], shape) } } // The cohort of organization C is below the minimum, so no card of it // exists and its handles are refused. requireInvitationValidation(t, createDraft(orgC, sessionC, suppressedForC, nil), "/candidate_handle", "") // A malformed handle is refused by the schema. if response := createDraft(orgA, sessionA, "not-a-handle", nil); response.Code != http.StatusBadRequest { t.Fatalf("malformed handle = %d %s, want 400", response.Code, response.Body.String()) } if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("refused handles stored rows: %+v -> %+v", before, after) } // The organization that owns the handle can use it, for its own // invitation only. own := decodeInvitationHTTP(t, createDraft(orgB, sessionB, handleB, nil), http.StatusCreated) if own.OrganizationID != orgB || own.CandidateHandle != handleB { t.Fatalf("organization B draft = %+v, want its own handle", own) } // The same person is a different pseudonym for each organization. if own.CandidateHandle == handleA { t.Fatal("two organizations share a handle") } }) t.Run("replays an idempotent create and refuses a reused key", func(t *testing.T) { before := readInvitationCounts(ctx, t, harness) path := createPath(orgA) body := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Idempotent role" }) responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, path, body, origin, sessionA, "invitation-replay-key", 2) if responses[0].Code != http.StatusCreated || responses[1].Code != http.StatusCreated || responses[0].Body.String() != responses[1].Body.String() { t.Fatalf("concurrent creates = %d %s and %d %s, want one identical 201", responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) } original := responses[0].Body.String() created := decodeInvitationHTTP(t, responses[0], http.StatusCreated) after := readInvitationCounts(ctx, t, harness) if after.invitations != before.invitations+1 || after.events != before.events+1 || after.results != before.results+1 { t.Fatalf("two creates with one key stored %+v -> %+v, want one draft", before, after) } // A change of the draft does not change the replayed response. update := `{"expected_version":1,"response_period_days":3}` decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, created.ID), update, sessionA, ""), http.StatusOK) replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key") if replay.Code != http.StatusCreated || replay.Body.String() != original { t.Fatalf("replay = %d %s, want the original 201", replay.Code, replay.Body.String()) } // The candidate stops being visible: the stored response is replayed, // while a new key is refused. privacy.hide(t, target.ID, orgA, now) defer func() { if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, target.ID, orgA); err != nil { t.Errorf("lift the hiding: %v", err) } }() if replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key"); replay.Code != http.StatusCreated || replay.Body.String() != original { t.Fatalf("replay after hiding = %d %s, want the original 201", replay.Code, replay.Body.String()) } requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, "invitation-after-hiding"), "/candidate_handle", "") changed := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Another role" }) requireSessionProblem(t, request(http.MethodPost, path, changed, sessionA, "invitation-replay-key"), http.StatusUnprocessableEntity, "idempotency_key_reused") if final := readInvitationCounts(ctx, t, harness); final.invitations != after.invitations { t.Fatalf("replays and refusals stored %d invitations", final.invitations-after.invitations) } // The key is scoped by organization: the same key in B is a new request. fromB := createDraft(orgB, sessionB, handleB, nil) if fromB.Code != http.StatusCreated { t.Fatalf("organization B create = %d %s", fromB.Code, fromB.Body.String()) } missingKey := request(http.MethodPost, path, body, sessionA, "") requireInvitationValidation(t, missingKey, "/Idempotency-Key", "") }) t.Run("answers every unauthorized caller without revealing an invitation", func(t *testing.T) { created := mustCreate(nil) own := itemPath(orgA, created.ID) before := readInvitationCounts(ctx, t, harness) requireSessionProblem(t, request(http.MethodGet, own, "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") requireSessionProblem(t, request(http.MethodGet, own, "", sessionCandidate, ""), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodGet, own, "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") // The owner of another organization and an unknown invitation both // answer 404 not_found with the same body shape. foreignRead := request(http.MethodGet, own, "", sessionB, "") requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") unknownRead := request(http.MethodGet, itemPath(orgA, uuid.New()), "", sessionA, "") requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found") // An invitation of organization A is not readable through organization // B's own path either. requireSessionProblem(t, request(http.MethodGet, itemPath(orgB, created.ID), "", sessionB, ""), http.StatusNotFound, "not_found") requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionB, ""), http.StatusNotFound, "not_found") requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionCandidate, ""), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") if foreignRead.Code != unknownRead.Code { t.Fatalf("foreign and unknown invitations answer %d and %d", foreignRead.Code, unknownRead.Code) } if response := request(http.MethodGet, itemPath(orgA, uuid.Nil), "", sessionA, ""); response.Code != http.StatusNotFound { t.Fatalf("nil invitation identifier = %d %s, want 404", response.Code, response.Body.String()) } if response := request(http.MethodGet, createPath(orgA)+"/not-a-uuid", "", sessionA, ""); response.Code != http.StatusBadRequest { t.Fatalf("malformed invitation identifier = %d %s, want 400", response.Code, response.Body.String()) } // Commands: the CSRF token and the origin are required, and a role that // does not own the organization changes nothing. body := invitationCreateJSON(t, handleA, nil) noCSRF := organizationHTTPSession{cookie: sessionA.cookie} requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, noCSRF, nextKey()), http.StatusForbidden, "csrf_check_failed") requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, createPath(orgA), body, "https://attacker.example", sessionA, nextKey()), http.StatusForbidden, "csrf_check_failed") requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionCandidate, nextKey()), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionB, nextKey()), http.StatusNotFound, "not_found") requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated") patch := `{"expected_version":1,"response_period_days":3}` requireSessionProblem(t, request(http.MethodPatch, own, patch, noCSRF, ""), http.StatusForbidden, "csrf_check_failed") requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionRecruiter, ""), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionCandidate, ""), http.StatusForbidden, "forbidden") requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionB, ""), http.StatusNotFound, "not_found") requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, uuid.New()), patch, sessionA, ""), http.StatusNotFound, "not_found") if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("unauthorized calls stored rows: %+v -> %+v", before, after) } current := decodeInvitationHTTP(t, request(http.MethodGet, own, "", sessionA, ""), http.StatusOK) if current.Version != 1 || current.ResponsePeriodDays != 7 { t.Fatalf("an unauthorized patch changed the draft: %+v", current) } }) t.Run("lists the invitations of the organization newest first with a bound cursor", func(t *testing.T) { list := func(organizationID uuid.UUID, session organizationHTTPSession, query string) (*httptest.ResponseRecorder, invitationHTTPPage) { t.Helper() response := request(http.MethodGet, createPath(organizationID)+query, "", session, "") var page invitationHTTPPage if response.Code == http.StatusOK { if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { t.Fatalf("decode page %s: %v", response.Body.String(), err) } } return response, page } total := invitationCount(ctx, t, harness, "invitations WHERE organization_id = '"+orgA.String()+"'") seen := map[uuid.UUID]bool{} var previous time.Time query := "?limit=3" for { response, page := list(orgA, sessionA, query) if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) == 0 { t.Fatalf("list = %d %s", response.Code, response.Body.String()) } requireNoCandidateData("list", response.Body.String()) for _, item := range page.Items { if seen[item.ID] || !strings.HasPrefix(item.CandidateHandle, "cv1_") || item.State != "draft" || item.RoleTitle == "" || item.Salary.TaxBasis == "" { t.Fatalf("listed item %+v is repeated or incomplete", item) } var createdAt time.Time if err := harness.pool.QueryRow(ctx, `SELECT created_at FROM invitations WHERE id = $1 AND organization_id = $2`, item.ID, orgA).Scan(&createdAt); err != nil { t.Fatalf("listed item %s is not an invitation of the organization: %v", item.ID, err) } if !previous.IsZero() && createdAt.After(previous) { t.Fatalf("list is not newest first: %s after %s", createdAt, previous) } previous = createdAt seen[item.ID] = true } if !page.Page.HasMore { break } if page.Page.NextCursor == nil { t.Fatal("a page with more items has no cursor") } query = "?limit=3&cursor=" + url.QueryEscape(*page.Page.NextCursor) } if len(seen) != total { t.Fatalf("pages listed %d invitations, want %d", len(seen), total) } // A cursor belongs to its reader and organization. _, first := list(orgA, sessionA, "?limit=1") if first.Page.NextCursor == nil { t.Fatal("no cursor to test") } for name, response := range map[string]*httptest.ResponseRecorder{ "another organization": request(http.MethodGet, createPath(orgB)+"?cursor="+url.QueryEscape(*first.Page.NextCursor), "", sessionB, ""), "a forged cursor": request(http.MethodGet, createPath(orgA)+"?cursor="+url.QueryEscape(*first.Page.NextCursor+"AA"), "", sessionA, ""), } { if response.Code != http.StatusBadRequest { t.Errorf("%s: list = %d %s, want 400", name, response.Code, response.Body.String()) } } if response, _ := list(orgA, sessionA, "?limit=0"); response.Code != http.StatusBadRequest { t.Errorf("limit 0 = %d, want 400", response.Code) } // Organization B sees only its own invitations. _, others := list(orgB, sessionB, "") for _, item := range others.Items { if seen[item.ID] { t.Fatalf("organization B lists the invitation %s of organization A", item.ID) } } }) t.Run("updates a draft with versions, immutable terms versions, and a no-op rule", func(t *testing.T) { draft := mustCreate(func(body, terms map[string]any) { terms["role_title"] = "Versioned role" }) path := itemPath(orgA, draft.ID) harness.clock.Advance(time.Minute) newTerms := invitationTermsMap() newTerms["role_title"] = "Versioned role, second terms" invitationSalary(newTerms)["salary_to"] = 150000 body, err := json.Marshal(map[string]any{"expected_version": 1, "terms": newTerms}) if err != nil { t.Fatalf("marshal update: %v", err) } updated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(body), sessionA, ""), http.StatusOK) if updated.Version != 2 || updated.TermsVersion != 2 || !strings.Contains(string(updated.Terms), "second terms") || !updated.UpdatedAt.After(draft.UpdatedAt) { t.Fatalf("updated draft = %+v, want version 2 with terms version 2", updated) } // Both terms versions are stored; the first is the original text. var firstRole, secondRole string var firstTo, secondTo int64 for version, target := range map[int]struct { role *string to *int64 }{1: {&firstRole, &firstTo}, 2: {&secondRole, &secondTo}} { if err := harness.pool.QueryRow(ctx, `SELECT terms ->> 'role_title', salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = $2`, draft.ID, version).Scan(target.role, target.to); err != nil { t.Fatalf("read terms version %d: %v", version, err) } } if firstRole != "Versioned role" || firstTo != 140000 || secondRole != "Versioned role, second terms" || secondTo != 150000 { t.Fatalf("terms versions = (%q, %d) and (%q, %d), want the original and the new terms", firstRole, firstTo, secondRole, secondTo) } var kind string var changed []string var termsOfEvent int64 if err := harness.pool.QueryRow(ctx, `SELECT kind, changed_fields, terms_version FROM invitation_events WHERE invitation_id = $1 AND version = 2`, draft.ID). Scan(&kind, &changed, &termsOfEvent); err != nil { t.Fatalf("read the update event: %v", err) } if kind != "draft_updated" || !slices.Equal(changed, []string{"terms"}) || termsOfEvent != 2 { t.Fatalf("update event = %s %v terms %d, want draft_updated for the terms", kind, changed, termsOfEvent) } // A body that changes nothing answers 200 with the current draft, even // with a stale version, and creates no version. before := readInvitationCounts(ctx, t, harness) for _, stale := range []int{1, 2} { noop, err := json.Marshal(map[string]any{"expected_version": stale, "terms": newTerms}) if err != nil { t.Fatalf("marshal no-op: %v", err) } repeated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(noop), sessionA, ""), http.StatusOK) if repeated.Version != 2 || repeated.TermsVersion != 2 { t.Fatalf("no-op with version %d = %+v, want the current version 2", stale, repeated) } } if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("no-op updates stored rows: %+v -> %+v", before, after) } // A stale version is a 412 and nothing is changed or stored. stale, err := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 3}) if err != nil { t.Fatalf("marshal stale update: %v", err) } requireSessionProblem(t, request(http.MethodPatch, path, string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") // A stale version beats a rule violation. invalidTerms := invitationTermsMap() invitationSalary(invalidTerms)["salary_to"] = 500000 staleInvalid, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": invalidTerms}) requireSessionProblem(t, request(http.MethodPatch, path, string(staleInvalid), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") // A current version with a rule violation is a field error. currentInvalid, _ := json.Marshal(map[string]any{"expected_version": 2, "terms": invalidTerms}) requireInvitationValidation(t, request(http.MethodPatch, path, string(currentInvalid), sessionA, ""), "/terms/salary/salary_to", "") if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("refused updates stored rows: %+v -> %+v", before, after) } // A change of the period or the need keeps the terms version. period, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) withPeriod := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(period), sessionA, ""), http.StatusOK) if withPeriod.Version != 3 || withPeriod.TermsVersion != 2 || withPeriod.ResponsePeriodDays != 14 { t.Fatalf("period update = %+v, want version 3 with terms version 2", withPeriod) } if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { t.Fatalf("stored %d terms versions, want 2", got) } // The candidate and the other fixed fields cannot be changed. for _, field := range []string{"candidate_handle", "state", "salary_fit", "organization_id"} { response := request(http.MethodPatch, path, fmt.Sprintf(`{"expected_version":3,%q:"x"}`, field), sessionA, "") if response.Code != http.StatusBadRequest { t.Errorf("update with %s = %d %s, want 400", field, response.Code, response.Body.String()) } } if response := request(http.MethodPatch, path, `{"response_period_days":3}`, sessionA, ""); response.Code != http.StatusBadRequest { t.Errorf("update without expected_version = %d, want 400", response.Code) } }) t.Run("links a draft only to a need of the organization that has had the requirements version", func(t *testing.T) { needA := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionA, orgA, "Invitation need A") needB := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionB, orgB, "Invitation need B") linked := mustCreate(func(body, terms map[string]any) { body["need"] = map[string]any{"need_id": needA.ID, "requirements_version": needA.RequirementsVersion} }) if linked.Need == nil || linked.Need.NeedID != needA.ID || linked.Need.RequirementsVersion != needA.RequirementsVersion { t.Fatalf("linked draft = %+v, want the need reference back", linked.Need) } // Renaming the need makes version 2 without a new requirements version, // so version 2 is not a requirements version the need has had. renamed := request(http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", orgA, needA.ID), `{"expected_version":1,"title":"Renamed invitation need A"}`, sessionA, "") var renamedNeed struct { Version int64 `json:"version"` RequirementsVersion int64 `json:"requirements_version"` } if err := json.Unmarshal(renamed.Body.Bytes(), &renamedNeed); err != nil || renamed.Code != http.StatusOK || renamedNeed.Version != 2 || renamedNeed.RequirementsVersion != needA.RequirementsVersion { t.Fatalf("rename need = %d %s, want version 2 with the same requirements version", renamed.Code, renamed.Body.String()) } before := readInvitationCounts(ctx, t, harness) for name, ref := range map[string]map[string]any{ "a version that only renamed the need": {"need_id": needA.ID, "requirements_version": 2}, "a need of another organization": {"need_id": needB.ID, "requirements_version": needB.RequirementsVersion}, "an unknown need": {"need_id": uuid.New(), "requirements_version": 1}, "a version the need never had": {"need_id": needA.ID, "requirements_version": needA.RequirementsVersion + 5}, } { response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body["need"] = ref }) if response.Code != http.StatusBadRequest { t.Errorf("link to %s = %d %s, want 400", name, response.Code, response.Body.String()) continue } requireInvitationValidation(t, response, "/need", "") } if after := readInvitationCounts(ctx, t, harness); after != before { t.Fatalf("refused links stored rows: %+v -> %+v", before, after) } // The link is informational and can be removed or changed in the draft. path := itemPath(orgA, linked.ID) unlink := decodeInvitationHTTP(t, request(http.MethodPatch, path, `{"expected_version":1,"need":null}`, sessionA, ""), http.StatusOK) if unlink.Need != nil || unlink.Version != 2 || unlink.TermsVersion != 1 { t.Fatalf("unlinked draft = %+v, want version 2 without a need and the same terms version", unlink) } relink := fmt.Sprintf(`{"expected_version":2,"need":{"need_id":%q,"requirements_version":%d}}`, needA.ID, needA.RequirementsVersion) if relinked := decodeInvitationHTTP(t, request(http.MethodPatch, path, relink, sessionA, ""), http.StatusOK); relinked.Need == nil || relinked.Version != 3 { t.Fatalf("relinked draft = %+v", relinked) } foreign := fmt.Sprintf(`{"expected_version":3,"need":{"need_id":%q,"requirements_version":%d}}`, needB.ID, needB.RequirementsVersion) requireInvitationValidation(t, request(http.MethodPatch, path, foreign, sessionA, ""), "/need", "") }) t.Run("refuses to change an invitation that is no longer a draft", func(t *testing.T) { draft := mustCreate(nil) if _, err := harness.pool.Exec(ctx, `UPDATE invitations SET state = 'withdrawn', version = version + 1, updated_at = updated_at WHERE id = $1`, draft.ID); err != nil { t.Fatalf("withdraw the draft: %v", err) } changed, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(changed), sessionA, ""), http.StatusConflict, "state_conflict") // The stale version is compared before the state. stale, _ := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 14}) requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) if read.State != "withdrawn" || read.Version != 2 || read.ResponsePeriodDays != 7 { t.Fatalf("withdrawn invitation = %+v, want it unchanged", read) } }) t.Run("lets only one of two concurrent updates from the same version win", func(t *testing.T) { draft := mustCreate(nil) path := itemPath(orgA, draft.ID) first, second := invitationTermsMap(), invitationTermsMap() first["role_title"], second["role_title"] = "Concurrent role one", "Concurrent role two" bodies := make([]string, 0, 2) for _, terms := range []map[string]any{first, second} { encoded, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": terms}) bodies = append(bodies, string(encoded)) } responses := parallelNeedRequestsWithBodies(t, harness.sessionHTTPHarness, http.MethodPatch, path, bodies, origin, sessionA) statuses := []int{responses[0].Code, responses[1].Code} slices.Sort(statuses) if !slices.Equal(statuses, []int{http.StatusOK, http.StatusPreconditionFailed}) { t.Fatalf("concurrent updates answered %d %s and %d %s, want one 200 and one 412", responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) } if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { t.Fatalf("stored %d terms versions, want 2", got) } if got := invitationCount(ctx, t, harness, "invitation_events WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { t.Fatalf("stored %d events, want 2", got) } }) t.Run("queues concurrent creates and updates of one organization without a deadlock", func(t *testing.T) { // Creates lock the organization, the membership, and the visible cohort; // updates lock the organization, the membership, and the invitation. Both // take the organization lock first, so mixing them never deadlocks // (SQLSTATE 40P01 would surface as a 500). const pairs = 4 drafts := make([]invitationHTTPBody, 0, pairs) for range pairs { drafts = append(drafts, mustCreate(nil)) } before := readInvitationCounts(ctx, t, harness) responses := make([]*httptest.ResponseRecorder, 2*pairs) var group sync.WaitGroup start := make(chan struct{}) for index, draft := range drafts { createBody := invitationCreateJSON(t, handleA, nil) createKey := nextKey() updateTerms := invitationTermsMap() updateTerms["role_title"] = fmt.Sprintf("Concurrent update %d", index) updateBody, err := json.Marshal(map[string]any{"expected_version": 1, "terms": updateTerms}) if err != nil { t.Fatalf("marshal update: %v", err) } group.Go(func() { <-start responses[2*index] = request(http.MethodPost, createPath(orgA), createBody, sessionA, createKey) }) group.Go(func() { <-start responses[2*index+1] = request(http.MethodPatch, itemPath(orgA, draft.ID), string(updateBody), sessionA, "") }) } close(start) group.Wait() for index, response := range responses { want := http.StatusCreated if index%2 == 1 { want = http.StatusOK } if response.Code != want { t.Fatalf("concurrent command %d = %d %s, want %d", index, response.Code, response.Body.String(), want) } } after := readInvitationCounts(ctx, t, harness) if after.invitations != before.invitations+pairs || after.events != before.events+2*pairs { t.Fatalf("concurrent commands stored %+v -> %+v, want %d drafts and %d events", before, after, pairs, 2*pairs) } }) t.Run("keeps every candidate value out of responses and logs", func(t *testing.T) { requireNoCandidateData("server log", harness.logs.String()) var stored string if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(terms::text, ' '), '') || ' ' || coalesce((SELECT string_agg(snapshot::text, ' ') FROM invitation_creation_results), '') FROM invitation_terms_versions`).Scan(&stored); err != nil { t.Fatalf("read stored terms: %v", err) } requireNoCandidateData("stored terms and replay responses", stored) }) } type invitationNeedBody struct { ID uuid.UUID `json:"id"` RequirementsVersion int64 `json:"requirements_version"` } func createNeedForInvitation(t *testing.T, harness *sessionHTTPHarness, origin string, session organizationHTTPSession, organizationID uuid.UUID, title string) invitationNeedBody { t.Helper() response := organizationHTTPRequest(t, harness, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), fmt.Sprintf(`{"title":%q}`, title), origin, session, "need-for-"+strings.ReplaceAll(strings.ToLower(title), " ", "-")) if response.Code != http.StatusCreated { t.Fatalf("create need = %d %s, want 201", response.Code, response.Body.String()) } var need invitationNeedBody if err := json.Unmarshal(response.Body.Bytes(), &need); err != nil || need.ID == uuid.Nil { t.Fatalf("decode need %s: %v", response.Body.String(), err) } return need }