//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "slices" "strings" "sync" "testing" "time" "github.com/google/uuid" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/consent" "lincodex/backend/internal/usecase/policy" ) const ( // invitationAcceptMigrationVersion adds the acceptance: its audit event, the // contact grant, and the outcomes kept under the keys. invitationAcceptMigrationVersion = 40 invitationAcceptancesRetained = "invitation_acceptances_retained" acceptTextVersion = "c4-2026-10-01" ) // candidateContactGrantHTTP is the contact grant as the candidate reads it. type candidateContactGrantHTTP struct { ID uuid.UUID `json:"id"` Fields []string `json:"fields"` Status string `json:"status"` Readable bool `json:"readable"` BlockedBy *string `json:"blocked_by"` TermsVersion int64 `json:"terms_version"` ConsentTextVersion string `json:"consent_text_version"` GrantedAt string `json:"granted_at"` RevokedAt *string `json:"revoked_at"` RevocationReason *string `json:"revocation_reason"` } func decodeContactGrantHTTP(t *testing.T, body candidateInvitationHTTPBody) candidateContactGrantHTTP { t.Helper() var grant candidateContactGrantHTTP if err := json.Unmarshal(body.ContactGrant, &grant); err != nil { t.Fatalf("decode contact grant %s: %v", body.ContactGrant, err) } return grant } // invitationAcceptCounts are the rows that acceptances write for one // invitation, the C4 consents of its candidate, and the outcomes kept under // the keys. type invitationAcceptCounts struct { acceptedEvents, grants, c4Consents, outcomes int } func readInvitationAcceptCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAcceptCounts { t.Helper() var counts invitationAcceptCounts if err := harness.pool.QueryRow(ctx, ` SELECT (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'accepted'), (SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1), (SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4'), (SELECT count(*) FROM invitation_accept_results WHERE invitation_id = $1)`, invitationID, candidateID).Scan(&counts.acceptedEvents, &counts.grants, &counts.c4Consents, &counts.outcomes); err != nil { t.Fatalf("count the rows of an acceptance: %v", err) } return counts } // parallelAcceptRequests sends every acceptance at once, each under its own // key, and returns the responses in the order of the bodies. func parallelAcceptRequests( t *testing.T, harness *invitationHTTPHarness, path, origin string, session organizationHTTPSession, bodies, keys []string, ) []*httptest.ResponseRecorder { t.Helper() responses := make([]*httptest.ResponseRecorder, len(bodies)) var group sync.WaitGroup start := make(chan struct{}) for index := range bodies { group.Go(func() { <-start responses[index] = organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, bodies[index], origin, session, keys[index]) }) } close(start) group.Wait() return responses } // firstAcceptance is the acceptance that later cases of the test repeat. type firstAcceptance struct { candidate domain.User invitation invitationHTTPBody key string body string } func TestCandidateInvitationAcceptOverHTTP(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) 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) } owner := account("accept-owner@example.test", domain.ScenarioEmployer) sessionOwner := loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwner, "accept-company") var nameA string if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { t.Fatalf("read organization name: %v", err) } 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} // Every candidate publishes the card and holds a name, an email, and a phone // number. Telegram is held by none of them. publishCandidate := func(candidate domain.User) { consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) 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), Phone: confirmedDecision("+70000000000"), 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) } } // Seven published candidates form the visible cohort. Each case uses its own // candidate, so the cases do not share the state of an invitation. var candidates []domain.User for index := range 7 { candidate := account(fmt.Sprintf("accept-candidate-%d@example.test", index), domain.ScenarioCandidate) candidates = append(candidates, candidate) publishCandidate(candidate) } login := func(candidate domain.User) organizationHTTPSession { return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) } 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-accept-key-%d", keySequence) } deliver := func(candidate domain.User) invitationHTTPBody { t.Helper() handle, err := harness.key.ForOrganization(orgA, candidate.ID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), invitationCreateJSON(t, handle, nil), sessionOwner, nextKey()), http.StatusCreated) return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", orgA, draft.ID), fmt.Sprintf(`{"expected_version":%d}`, draft.Version), sessionOwner, nextKey()), http.StatusOK) } myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() } acceptBody := func(version, terms int64, text string, fields ...string) string { encoded, err := json.Marshal(map[string]any{ "expected_version": version, "terms_version": terms, "consent_c4": map[string]any{"text_version": text, "accepted": true, "fields": fields}, }) if err != nil { t.Fatalf("marshal acceptance: %v", err) } return string(encoded) } accept := func(candidate domain.User, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder { t.Helper() return request(http.MethodPost, myPath(invitationID)+"/accept", body, login(candidate), key) } // raiseTerms stores the next terms version the way a later raise does, with // a higher salary, and advances the invitation version by one. raiseTerms := func(invitationID uuid.UUID) int64 { t.Helper() if _, err := harness.pool.Exec(ctx, ` INSERT INTO invitation_terms_versions (invitation_id, organization_id, version, terms, salary_from, salary_to, salary_currency, salary_period, salary_tax_basis, created_at) SELECT invitation_id, organization_id, 2, jsonb_set(jsonb_set(terms, '{salary,salary_from}', '120000'::jsonb), '{salary,salary_to}', '160000'::jsonb), 120000, 160000, salary_currency, salary_period, salary_tax_basis, $2 FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, invitationID, harness.clock.Now()); err != nil { t.Fatalf("store the raised terms: %v", err) } var version int64 if err := harness.pool.QueryRow(ctx, ` UPDATE invitations SET terms_version = 2, version = version + 1, updated_at = $2 WHERE id = $1 RETURNING version`, invitationID, harness.clock.Now()).Scan(&version); err != nil { t.Fatalf("raise the invitation: %v", err) } return version } candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} for _, candidate := range candidates { candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address()) } requireNoCandidateData := func(label, 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", "candidate_handle", "salary_fit", "salary_minimum", "full_name", "telegram", "email", "phone"} { if strings.Contains(text, `"`+field+`":`) { t.Errorf("%s contains the key %q: %s", label, field, text) } } } var first firstAcceptance t.Run("an email-only acceptance stores one grant of that field and one consent", func(t *testing.T) { candidate := candidates[0] sent := deliver(candidate) key := nextKey() body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") response := accept(candidate, sent.ID, body, key) accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) requireNoCandidateData("accept response", response.Body.String()) grant := decodeContactGrantHTTP(t, accepted) if accepted.State != "accepted" || accepted.Version != sent.Version+1 || accepted.TermsVersion != sent.TermsVersion || accepted.RespondedAt == nil || accepted.Decline != nil || string(accepted.ContactConsent) != "null" || accepted.ResponseDeadlineAt != *sent.ResponseDeadlineAt || accepted.Organization.Name != nameA { t.Fatalf("accepted = %+v, want the accepted invitation with its deadline and no offer", accepted) } if !slices.Equal(grant.Fields, []string{"email"}) || grant.Status != "active" || grant.ConsentTextVersion != acceptTextVersion || grant.TermsVersion != sent.TermsVersion || grant.RevokedAt != nil || grant.RevocationReason != nil { t.Fatalf("grant = %+v, want the email only, active, under the current text", grant) } // The published profile is not hidden, so the grant is readable now. if !grant.Readable || grant.BlockedBy != nil { t.Fatalf("grant = %+v, want readable while the organization may read the profile", grant) } if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 1}) { t.Fatalf("acceptance stored %+v, want one event, one grant, one C4 consent, and one outcome", counts) } // The grant names the one selected kind, although the profile holds the // phone number too, and the consent names the same kind. var fields, consentFields []string if err := harness.pool.QueryRow(ctx, ` SELECT grant_row.fields, record.field_set FROM contact_grants AS grant_row JOIN consent_records AS record ON record.id = grant_row.consent_record_id WHERE grant_row.source_invitation_id = $1`, sent.ID).Scan(&fields, &consentFields); err != nil { t.Fatalf("read the grant and its consent: %v", err) } if !slices.Equal(fields, []string{"email"}) || !slices.Equal(consentFields, []string{"email"}) { t.Fatalf("stored grant fields = %v and consent fields = %v, want the email only", fields, consentFields) } reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) if decodeContactGrantHTTP(t, reread).ID != grant.ID || reread.Version != accepted.Version { t.Fatalf("reread = %+v, want the same grant and version", reread) } first = firstAcceptance{candidate: candidate, invitation: sent, key: key, body: body} }) t.Run("repeats replay the answer and a different choice is a state conflict", func(t *testing.T) { if first.invitation.ID == uuid.Nil { t.Fatal("the first acceptance did not run") } original := accept(first.candidate, first.invitation.ID, first.body, first.key) if original.Code != http.StatusOK { t.Fatalf("replay = %d %s, want the original 200", original.Code, original.Body.String()) } // The same request under a new key, with the older expected version, // answers the accepted invitation without a second grant or event. again := accept(first.candidate, first.invitation.ID, first.body, nextKey()) if again.Code != http.StatusOK || again.Body.String() != original.Body.String() { t.Fatalf("repeat = %d %s, want the same answer %s", again.Code, again.Body.String(), original.Body.String()) } // Another field set is a different acceptance that the grant refuses. requireSessionProblem(t, accept(first.candidate, first.invitation.ID, acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "email", "phone"), nextKey()), http.StatusConflict, "state_conflict") // A reused key with another body is refused and stores nothing. requireSessionProblem(t, accept(first.candidate, first.invitation.ID, acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "phone"), first.key), http.StatusUnprocessableEntity, "idempotency_key_reused") // Three outcomes: the first acceptance, the repeat, and the refused field set. if counts := readInvitationAcceptCounts(ctx, t, harness, first.invitation.ID, first.candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { t.Fatalf("repeats stored %+v, want the first acceptance, its repeat, and the refusal", counts) } }) t.Run("a stale terms version is refused and nothing is stored, and the raised terms are accepted", func(t *testing.T) { candidate := candidates[1] sent := deliver(candidate) raisedVersion := raiseTerms(sent.ID) // The candidate read the terms of version 1: 412, nothing stored. requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), http.StatusPreconditionFailed, "version_conflict") if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { t.Fatalf("a stale terms version stored %+v", counts) } read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) if read.TermsVersion != 2 || read.Version != raisedVersion || read.State != "delivered" { t.Fatalf("read after the raise = %+v, want the new terms and the delivered state", read) } accepted := decodeCandidateInvitationHTTP(t, accept(candidate, sent.ID, acceptBody(raisedVersion, 2, acceptTextVersion, "email"), nextKey()), http.StatusOK) if accepted.State != "accepted" || accepted.TermsVersion != 2 || decodeContactGrantHTTP(t, accepted).TermsVersion != 2 { t.Fatalf("accepted = %+v, want the raised terms version accepted", accepted) } // The old terms version is a different acceptance once the grant exists. requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), http.StatusConflict, "state_conflict") if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 2}) { t.Fatalf("raised acceptance stored %+v, want one acceptance, one grant, one consent, and the refusal", counts) } }) t.Run("concurrent acceptances make one transition and one grant", func(t *testing.T) { candidate := candidates[2] sent := deliver(candidate) session := login(candidate) path := myPath(sent.ID) + "/accept" body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") responses := parallelAcceptRequests(t, harness, path, origin, session, []string{body, body, body}, []string{nextKey(), nextKey(), nextKey()}) var answers []string for _, response := range responses { accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) if accepted.State != "accepted" { t.Fatalf("concurrent answer = %+v, want accepted", accepted) } answers = append(answers, response.Body.String()) } if !slices.Equal(answers[1:], answers[:len(answers)-1]) { t.Fatalf("concurrent answers differ: %v", answers) } if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { t.Fatalf("concurrent acceptances stored %+v, want one transition, one grant, one consent", counts) } // Two different field sets race: one transition, the other a conflict. other := candidates[3] raced := deliver(other) responses = parallelAcceptRequests(t, harness, myPath(raced.ID)+"/accept", origin, login(other), []string{ acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "email"), acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "phone"), }, []string{nextKey(), nextKey()}) statuses := []int{responses[0].Code, responses[1].Code} slices.Sort(statuses) if !slices.Equal(statuses, []int{http.StatusOK, http.StatusConflict}) { t.Fatalf("raced acceptances = %v, want one 200 and one 409 state_conflict", statuses) } if counts := readInvitationAcceptCounts(ctx, t, harness, raced.ID, other.ID); counts.acceptedEvents != 1 || counts.grants != 1 || counts.c4Consents != 1 { t.Fatalf("raced acceptances stored %+v, want one transition, one grant, one consent", counts) } }) t.Run("a hidden organization accepts without changing the publication or the hiding", func(t *testing.T) { candidate := candidates[4] sent := deliver(candidate) privacy.hide(t, candidate.ID, orgA, harness.clock.Now()) publication := privacy.rawPublication(t, candidate.ID) hidden := privacy.rawHidden(t, candidate.ID) response := accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email"), nextKey()) accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) grant := decodeContactGrantHTTP(t, accepted) if grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != "visibility" || len(grant.Fields) != 1 { t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", grant) } if after := privacy.rawPublication(t, candidate.ID); after != publication { t.Fatalf("the acceptance changed the publication: %s became %s", publication, after) } if after := privacy.rawHidden(t, candidate.ID); after != hidden { t.Fatalf("the acceptance changed the hiding: %s became %s", hidden, after) } // The candidate removes the hiding; the same grant becomes readable. if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, candidate.ID, orgA); err != nil { t.Fatalf("unhide the organization: %v", err) } reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) if grantRead := decodeContactGrantHTTP(t, reread); grantRead.ID != grant.ID || !grantRead.Readable || grantRead.BlockedBy != nil { t.Fatalf("grant after unhiding = %+v, want the same grant readable", grantRead) } }) t.Run("a late acceptance is refused under its key whatever the version", func(t *testing.T) { candidate := candidates[5] sent := deliver(candidate) var deadline time.Time if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&deadline); err != nil { t.Fatalf("read the deadline: %v", err) } harness.clock.Set(deadline.UTC()) key := nextKey() for range 2 { requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(sent.Version+5, sent.TermsVersion, acceptTextVersion, "email"), key), http.StatusConflict, "state_conflict") } if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{outcomes: 1}) { t.Fatalf("late acceptances stored %+v, want one state_conflict outcome and nothing else", counts) } }) t.Run("the consent text and the held kinds are checked before anything is stored", func(t *testing.T) { // The late case moved the clock to a deadline, which ends the owner session. sessionOwner = loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) candidate := candidates[6] sent := deliver(candidate) requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, "c4-2025-01-01", "email"), nextKey()), "/consent_c4/text_version", "") requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email", "telegram"), nextKey()), "/consent_c4/fields/1", "") if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { t.Fatalf("refused consent stored %+v", counts) } read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) if read.State != "delivered" || string(read.ContactGrant) != "null" { t.Fatalf("read after the refusals = %+v, want the delivered invitation without a grant", read) } }) t.Run("the acceptance answers stay out of the server log", func(t *testing.T) { requireNoCandidateData("server log", harness.logs.String()) }) } func TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) migrator := newMigrator(t, databaseURL) if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } // The fixture creates an organization with the schema of the current head. fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) // Migrations added after this one are not part of this guard: the test // rolls them back, so that this migration is the one rolled back below. rollBackAboveVersion(ctx, t, migrator, invitationAcceptMigrationVersion) store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error { t.Helper() return fixture.transactor.WithinTransaction(ctx, work) } deliverDraft := func(t *testing.T) domain.Invitation { t.Helper() draft := fixture.draft(t) delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) if err != nil { t.Fatalf("Deliver() error = %v", err) } event, err := delivered.DeliveryEvent(fixture.owner.ID) if err != nil { t.Fatalf("DeliveryEvent() error = %v", err) } if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) }); err != nil { t.Fatalf("Deliver() through the repository error = %v", err) } return delivered } delivered := deliverDraft(t) acceptedAt := delivered.UpdatedAt().Add(time.Minute) accepted, err := delivered.Accept(delivered.TermsVersion(), acceptedAt) if err != nil { t.Fatalf("Accept() error = %v", err) } acceptEvent, err := accepted.AnswerEvent(fixture.candidate.ID) if err != nil { t.Fatalf("AnswerEvent() error = %v", err) } fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail) if err != nil { t.Fatalf("NewContactFieldSet() error = %v", err) } consents := consent.NewService(fixture.transactor, func() time.Time { return acceptedAt }) if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := unit.Invitations().Accept(ctx, delivered.Version(), accepted, acceptEvent); err != nil { return err } granted, err := consents.GrantContact(ctx, unit, consent.ContactGrantInput{ SubjectID: fixture.candidate.ID, OrganizationID: fixture.organization.ID(), OrganizationName: fixture.organization.Profile().Name(), Fields: fields, InvitationID: delivered.ID(), InvitationTermsVersion: delivered.TermsVersion(), TextVersion: acceptTextVersion, }) if err != nil { return err } grant, err := domain.NewContactGrant(granted.Record, accepted) if err != nil { return err } return unit.ContactGrants().Create(ctx, grant) }); err != nil { t.Fatalf("accept through the repositories error = %v", err) } // The database guards the acceptance and its grant against other writers. _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', responded_at = NULL, version = version + 1 WHERE id = $1`, delivered.ID()) assertPgError(t, "leave the acceptance", err, privacyIntegrityViolation, "invitations_answer_immutable") _, err = pool.Exec(ctx, `UPDATE contact_grants SET fields = '{phone}' WHERE source_invitation_id = $1`, delivered.ID()) assertPgError(t, "change the grant", err, privacyIntegrityViolation, "contact_grants_immutable") _, err = pool.Exec(ctx, `DELETE FROM contact_grants WHERE source_invitation_id = $1`, delivered.ID()) assertPgError(t, "delete the grant", err, privacyIntegrityViolation, "contact_grants_immutable") _, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at) SELECT $1, id, organization_id, version + 1, terms_version, 'accepted', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), delivered.ID()) assertPgError(t, "accepted event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field") // An acceptance without its grant cannot commit. other := deliverDraft(t) _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'accepted', responded_at = delivered_at + interval '1 minute', updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID()) assertPgError(t, "accepted without a grant", err, privacyIntegrityViolation, "invitations_acceptance_recorded") _, err = migrator.DownOne(ctx) assertPgError(t, "DownOne() with an accepted invitation", err, privacyIntegrityViolation, invitationAcceptancesRetained) // The database is isolated to this test: CASCADE also clears the tables that // refer to the consent ledger, such as the publication history of C2. if _, err := pool.Exec(ctx, `TRUNCATE consent_records, invitations, invitation_accept_results, invitation_decline_results, invitation_send_results, invitation_creation_results CASCADE`); err != nil { t.Fatalf("clear the invitation tables: %v", err) } result, err := migrator.DownOne(ctx) if err != nil || result.Version != invitationAcceptMigrationVersion { t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAcceptMigrationVersion) } var remaining int if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('contact_grants', 'invitation_accept_results')`).Scan(&remaining); err != nil || remaining != 0 { t.Fatalf("acceptance tables left after the rollback: %d, %v", remaining, err) } if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() after the rollback error = %v", err) } }