//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "slices" "strings" "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/usecase/policy" ) const contactReadTimeout = 10 * time.Minute // contactDisclosureHTTP is the contact disclosure as the owner reads it. A // null value is a nil pointer, so a value that leaks shows up as non-nil. type contactDisclosureHTTP struct { InvitationID uuid.UUID `json:"invitation_id"` GrantID uuid.UUID `json:"grant_id"` Fields []string `json:"fields"` GrantedAt time.Time `json:"granted_at"` FullName *string `json:"full_name"` Email *string `json:"email"` Phone *string `json:"phone"` Telegram *string `json:"telegram"` } // TestOrganizationContactReadsAndRevocationOverHTTP covers the contact read // through an accepted invitation and the independent closing of its grant: the // consent C4, the consent C2 and the publication, and the hiding of the // organization. Each subtest uses its own candidates, so the cases do not share // the state of a grant. func TestOrganizationContactReadsAndRevocationOverHTTP(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), contactReadTimeout) 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) } ownerA := account("contact-owner-a@example.test", domain.ScenarioEmployer) ownerB := account("contact-owner-b@example.test", domain.ScenarioEmployer) ownerD := account("contact-owner-d@example.test", domain.ScenarioEmployer) recruiterA := account("contact-recruiter-a@example.test", domain.ScenarioEmployer) sessionOwnerA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) sessionOwnerB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) sessionOwnerD := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerD.Email.Address()) orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerA, "contact-company-a") orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerB, "contact-company-b") orgD := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerD, "contact-company-d") insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiterA.ID, "recruiter", "active", now) sessionRecruiterA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiterA.Email.Address()) identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, now: now} var keySequence int nextKey := func() string { keySequence++ return fmt.Sprintf("contact-read-key-%d", keySequence) } 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) } // Each candidate signs in once: the login limit of one client is shared by // the whole subtest, and every request of a candidate reuses its session. sessions := map[uuid.UUID]organizationHTTPSession{} login := func(candidate domain.User) organizationHTTPSession { t.Helper() if session, ok := sessions[candidate.ID]; ok { return session } session := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) sessions[candidate.ID] = session return session } // newCandidate creates a candidate who holds an email and a phone number, // grants C2, and publishes the card, through the routes the candidate uses. newCandidate := func(email string) domain.User { t.Helper() candidate := account(email, domain.ScenarioCandidate) profiles.save(t, candidate.ID, domain.CandidateProfileInput{ FullName: confirmedDecision("Contact Candidate"), Email: confirmedDecision(email), Phone: confirmedDecision("+70000000000"), }, 0) session := login(candidate) if response := request(http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), session, ""); response.Code != http.StatusOK { t.Fatalf("C2 grant = %d %s, want 200", response.Code, response.Body.String()) } if response := request(http.MethodPut, "/api/v1/me/privacy/publication", `{"expected_version":0,"state":"published","fields":["stack"]}`, session, ""); response.Code != http.StatusOK { t.Fatalf("publication = %d %s, want 200", response.Code, response.Body.String()) } return candidate } // deliver creates a draft for the candidate and sends it from the organization. deliver := func(organizationID uuid.UUID, owner organizationHTTPSession, candidate domain.User) invitationHTTPBody { t.Helper() handle, err := harness.key.ForOrganization(organizationID, candidate.ID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), invitationCreateJSON(t, handle, nil), owner, nextKey()), http.StatusCreated) return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", organizationID, draft.ID), fmt.Sprintf(`{"expected_version":%d}`, draft.Version), owner, nextKey()), http.StatusOK) } acceptResponse := func(candidate domain.User, invitation invitationHTTPBody, key string, fields ...string) *httptest.ResponseRecorder { t.Helper() encoded, err := json.Marshal(map[string]any{ "expected_version": invitation.Version, "terms_version": invitation.TermsVersion, "consent_c4": map[string]any{"text_version": acceptTextVersion, "accepted": true, "fields": fields}, }) if err != nil { t.Fatalf("marshal acceptance: %v", err) } return request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/accept", string(encoded), login(candidate), key) } acceptFields := func(candidate domain.User, invitation invitationHTTPBody, fields ...string) candidateInvitationHTTPBody { t.Helper() return decodeCandidateInvitationHTTP(t, acceptResponse(candidate, invitation, nextKey(), fields...), http.StatusOK) } readContacts := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession) *httptest.ResponseRecorder { t.Helper() return request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/contacts", organizationID, invitationID), "", session, "") } requireDisclosure := func(response *httptest.ResponseRecorder, invitationID, grantID uuid.UUID) contactDisclosureHTTP { t.Helper() if response.Code != http.StatusOK { t.Fatalf("contact read = %d %s, want 200", response.Code, response.Body.String()) } if cache := response.Header().Get("Cache-Control"); cache != "no-store" { t.Fatalf("contact read Cache-Control = %q, want no-store", cache) } var disclosure contactDisclosureHTTP if err := json.Unmarshal(response.Body.Bytes(), &disclosure); err != nil { t.Fatalf("decode contact read %s: %v", response.Body.String(), err) } if disclosure.InvitationID != invitationID || disclosure.GrantID != grantID { t.Fatalf("contact read names invitation %s and grant %s, want %s and %s", disclosure.InvitationID, disclosure.GrantID, invitationID, grantID) } return disclosure } requireNotFound := func(label string, response *httptest.ResponseRecorder) { t.Helper() if response.Code != http.StatusNotFound { t.Fatalf("%s = %d %s, want 404", label, response.Code, response.Body.String()) } requireSessionProblem(t, response, http.StatusNotFound, "not_found") } grantRow := func(invitationID uuid.UUID) (revoked bool, reason string) { t.Helper() var reasonValue *string if err := harness.pool.QueryRow(ctx, `SELECT revoked_at IS NOT NULL, revocation_reason FROM contact_grants WHERE source_invitation_id = $1`, invitationID).Scan(&revoked, &reasonValue); err != nil { t.Fatalf("read grant of %s: %v", invitationID, err) } if reasonValue != nil { reason = *reasonValue } return revoked, reason } requireGrantStatus := func(candidate domain.User, invitationID uuid.UUID, status string, readable bool, reason string) { t.Helper() read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitationID.String(), "", login(candidate), ""), http.StatusOK) grant := decodeContactGrantHTTP(t, read) if grant.Status != status || grant.Readable != readable { t.Fatalf("grant as the candidate reads it = %+v, want status %q readable %v", grant, status, readable) } if reason == "" { if grant.RevocationReason != nil { t.Fatalf("grant reason = %q, want none", *grant.RevocationReason) } return } if grant.RevocationReason == nil || *grant.RevocationReason != reason { t.Fatalf("grant reason = %v, want %q", grant.RevocationReason, reason) } } // requireNoContactValues fails when a response carries a value of the // candidates that the test creates. Only the kinds may appear. requireNoContactValues := func(label, text string) { t.Helper() for _, marker := range []string{"@example.test", "+70000000000", "Contact Candidate"} { if strings.Contains(text, marker) { t.Fatalf("%s carries the contact value %q: %s", label, marker, text) } } } // requireOrganizationAccess reads one invitation as its owner and checks the // contact access of the response: its status and the kinds it lists. requireOrganizationAccess := func(label string, organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) invitationHTTPBody { t.Helper() response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID), "", session, "") invitation := decodeInvitationHTTP(t, response, http.StatusOK) if invitation.ContactAccess.Status != status || !slices.Equal(invitation.ContactAccess.Fields, fields) { t.Fatalf("%s contact access = %+v, want %q with fields %v", label, invitation.ContactAccess, status, fields) } requireNoContactValues(label, response.Body.String()) return invitation } // requireListedAccess checks the contact access of one invitation in the // owner's list, which shows the same states as the single read. requireListedAccess := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) { t.Helper() response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations?limit=100", organizationID), "", session, "") if response.Code != http.StatusOK { t.Fatalf("organization list = %d %s, want 200", response.Code, response.Body.String()) } requireNoContactValues("organization list", response.Body.String()) var page struct { Items []struct { ID uuid.UUID `json:"id"` ContactAccess struct { Status string `json:"status"` Fields []string `json:"fields"` } `json:"contact_access"` } `json:"items"` } if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { t.Fatalf("decode organization list: %v", err) } for _, item := range page.Items { if item.ID != invitationID { continue } if item.ContactAccess.Status != status || !slices.Equal(item.ContactAccess.Fields, fields) { t.Fatalf("listed contact access = %+v, want %q with fields %v", item.ContactAccess, status, fields) } return } t.Fatalf("organization list does not show invitation %s", invitationID) } candidates := []domain.User{} for index := range 6 { candidates = append(candidates, newCandidate(fmt.Sprintf("contact-candidate-%d@example.test", index))) } t.Run("an email-only grant reads the email to the owner and nothing else", func(t *testing.T) { candidate := candidates[0] invitation := deliver(orgA, sessionOwnerA, candidate) requireOrganizationAccess("organization view before the acceptance", orgA, invitation.ID, sessionOwnerA, "not_granted") accepted := acceptFields(candidate, invitation, "email") grantID := decodeContactGrantHTTP(t, accepted).ID requireOrganizationAccess("organization view after the acceptance", orgA, invitation.ID, sessionOwnerA, "available", "email") requireListedAccess(orgA, invitation.ID, sessionOwnerA, "available", "email") first := readContacts(orgA, invitation.ID, sessionOwnerA) disclosure := requireDisclosure(first, invitation.ID, grantID) if len(disclosure.Fields) != 1 || disclosure.Fields[0] != "email" || disclosure.Email == nil || *disclosure.Email != candidate.Email.Address() { t.Fatalf("disclosure = %+v, want the confirmed email only", disclosure) } if disclosure.Phone != nil || disclosure.FullName != nil || disclosure.Telegram != nil { t.Fatalf("disclosure = %+v, want null for every kind the grant does not cover", disclosure) } if again := readContacts(orgA, invitation.ID, sessionOwnerA); again.Code != http.StatusOK || again.Body.String() != first.Body.String() { t.Fatalf("repeated contact read = %d %s, want the same body", again.Code, again.Body.String()) } // Organization B and a non-owner member of A are refused, and so is a // candidate or an anonymous request. requireNotFound("owner of another organization on the path of A", readContacts(orgA, invitation.ID, sessionOwnerB)) requireNotFound("owner of B on its own path with the invitation of A", readContacts(orgB, invitation.ID, sessionOwnerB)) requireSessionProblem(t, readContacts(orgA, invitation.ID, sessionRecruiterA), http.StatusForbidden, "forbidden") requireSessionProblem(t, readContacts(orgA, invitation.ID, login(candidate)), http.StatusForbidden, "forbidden") requireSessionProblem(t, readContacts(orgA, invitation.ID, organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated") // Each successful read is audited with its kinds only, and the read does // not consume the card-view quota. var audited, emailOnly int var actor string if err := harness.pool.QueryRow(ctx, ` SELECT count(*), count(*) FILTER (WHERE field_codes = ARRAY['email']::text []), COALESCE(max(actor_id::text), '') FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidate.ID, orgA). Scan(&audited, &emailOnly, &actor); err != nil { t.Fatalf("read the access audit: %v", err) } if audited != 2 || emailOnly != 2 || actor != ownerA.ID.String() { t.Fatalf("access audit = %d rows, %d of them the email only, by %q; want the two successful reads by the owner", audited, emailOnly, actor) } var viewQuota int if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, orgA).Scan(&viewQuota); err != nil { t.Fatalf("count card view quota: %v", err) } if viewQuota != 0 { t.Fatalf("contact reads consumed %d card-view quota rows, want none", viewQuota) } requireGrantStatus(candidate, invitation.ID, "active", true, "") if logs := harness.logs.String(); strings.Contains(logs, candidate.Email.Address()) || strings.Contains(logs, candidate.ID.String()) { t.Fatal("the server log contains the candidate's email or identifier") } }) t.Run("revoking C4 closes the grant for the URL, the API, and a repeated request, and leaves other organizations", func(t *testing.T) { candidate := candidates[1] inA := deliver(orgA, sessionOwnerA, candidate) grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID inB := deliver(orgB, sessionOwnerB, candidate) grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "email")).ID requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) revoke := request(http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), "", login(candidate), "") if revoke.Code != http.StatusNoContent { t.Fatalf("C4 revoke for A = %d %s, want 204", revoke.Code, revoke.Body.String()) } requireNotFound("contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) requireNotFound("repeated contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) if revoked, reason := grantRow(inA.ID); !revoked || reason != "consent_revoked" { t.Fatalf("grant of A after the C4 revocation: revoked %v reason %q, want consent_revoked", revoked, reason) } if revoked, _ := grantRow(inB.ID); revoked { t.Fatal("the C4 revocation for A closed the grant of B") } requireGrantStatus(candidate, inA.ID, "revoked", false, "consent_revoked") requireGrantStatus(candidate, inB.ID, "active", true, "") requireOrganizationAccess("organization view of A after the C4 revocation", orgA, inA.ID, sessionOwnerA, "closed") requireOrganizationAccess("organization view of B after the C4 revocation", orgB, inB.ID, sessionOwnerB, "available", "email") // The publication stays as it was: the C4 revocation closes only the grant, // and only a new explicit C4 creates a new grant for A. requireNotFound("contact read of the revoked grant", readContacts(orgA, inA.ID, sessionOwnerA)) inAgain := deliver(orgA, sessionOwnerA, candidate) grantAgain := decodeContactGrantHTTP(t, acceptFields(candidate, inAgain, "email")).ID if grantAgain == grantA { t.Fatal("a new C4 reused the revoked grant") } requireDisclosure(readContacts(orgA, inAgain.ID, sessionOwnerA), inAgain.ID, grantAgain) requireNotFound("the revoked grant after a new C4", readContacts(orgA, inA.ID, sessionOwnerA)) requireOrganizationAccess("organization view of the revoked invitation after a new C4", orgA, inA.ID, sessionOwnerA, "closed") requireOrganizationAccess("organization view of the new grant", orgA, inAgain.ID, sessionOwnerA, "available", "email") }) t.Run("hiding the organization closes its grants, and unhiding never reopens them", func(t *testing.T) { candidate := candidates[2] inA := deliver(orgA, sessionOwnerA, candidate) grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID inB := deliver(orgB, sessionOwnerB, candidate) grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "phone")).ID // The candidate may hide only an organization that already appears in // the candidate's access history, so the owner reads the grant first. requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) hide := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") if hide.Code != http.StatusOK { t.Fatalf("hide A = %d %s, want 200", hide.Code, hide.Body.String()) } requireNotFound("contact read while A is hidden", readContacts(orgA, inA.ID, sessionOwnerA)) requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) unhide := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") if unhide.Code != http.StatusNoContent { t.Fatalf("unhide A = %d %s, want 204", unhide.Code, unhide.Body.String()) } requireNotFound("contact read after unhiding A", readContacts(orgA, inA.ID, sessionOwnerA)) requireOrganizationAccess("organization view of A after hiding and unhiding", orgA, inA.ID, sessionOwnerA, "closed") if revoked, reason := grantRow(inA.ID); !revoked || reason != "visibility_closed" { t.Fatalf("grant of A after hiding: revoked %v reason %q, want visibility_closed", revoked, reason) } requireGrantStatus(candidate, inA.ID, "revoked", false, "visibility_closed") requireOrganizationAccess("organization view of A while hidden", orgA, inA.ID, sessionOwnerA, "closed") if revoked, _ := grantRow(inB.ID); revoked { t.Fatal("hiding A closed the grant of B") } // A grant created while the organization is hidden stays stored and blocked, // and it becomes readable when the candidate unhides the organization. inAHidden := deliver(orgA, sessionOwnerA, candidate) hideAgain := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") if hideAgain.Code != http.StatusOK { t.Fatalf("hide A again = %d %s, want 200", hideAgain.Code, hideAgain.Body.String()) } blocked := decodeCandidateInvitationHTTP(t, acceptResponse(candidate, inAHidden, nextKey(), "email"), http.StatusOK) grantHidden := decodeContactGrantHTTP(t, blocked) if grantHidden.Readable || grantHidden.BlockedBy == nil || *grantHidden.BlockedBy != "visibility" { t.Fatalf("grant accepted while hidden = %+v, want blocked by visibility", grantHidden) } requireNotFound("contact read of the blocked grant", readContacts(orgA, inAHidden.ID, sessionOwnerA)) requireOrganizationAccess("organization view of the blocked grant", orgA, inAHidden.ID, sessionOwnerA, "closed") if response := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), ""); response.Code != http.StatusNoContent { t.Fatalf("unhide A after the blocked acceptance = %d %s, want 204", response.Code, response.Body.String()) } requireDisclosure(readContacts(orgA, inAHidden.ID, sessionOwnerA), inAHidden.ID, grantHidden.ID) requireOrganizationAccess("organization view of the blocked grant after unhiding", orgA, inAHidden.ID, sessionOwnerA, "available", "email") }) t.Run("withdrawing C2 closes the grants, and publishing again does not reopen them", func(t *testing.T) { candidate := candidates[3] invitation := deliver(orgD, sessionOwnerD, candidate) grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) revokeC2 := request(http.MethodDelete, "/api/v1/me/consents/c2", "", login(candidate), "") if revokeC2.Code != http.StatusNoContent { t.Fatalf("C2 revoke = %d %s, want 204", revokeC2.Code, revokeC2.Body.String()) } requireNotFound("contact read after C2 revoke", readContacts(orgD, invitation.ID, sessionOwnerD)) requireOrganizationAccess("organization view after the C2 withdrawal", orgD, invitation.ID, sessionOwnerD, "closed") if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { t.Fatalf("grant after C2 revoke: revoked %v reason %q, want visibility_closed", revoked, reason) } if response := request(http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), login(candidate), ""); response.Code != http.StatusOK { t.Fatalf("C2 regrant = %d %s, want 200", response.Code, response.Body.String()) } var version int64 if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { t.Fatalf("read publication version: %v", err) } if response := request(http.MethodPut, "/api/v1/me/privacy/publication", fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":["stack"]}`, version), login(candidate), ""); response.Code != http.StatusOK { t.Fatalf("republication = %d %s, want 200", response.Code, response.Body.String()) } requireNotFound("contact read after republishing", readContacts(orgD, invitation.ID, sessionOwnerD)) requireGrantStatus(candidate, invitation.ID, "revoked", false, "visibility_closed") requireOrganizationAccess("organization view after republishing", orgD, invitation.ID, sessionOwnerD, "closed") }) t.Run("closing the publication closes the grants", func(t *testing.T) { candidate := candidates[4] invitation := deliver(orgD, sessionOwnerD, candidate) grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) var version int64 if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { t.Fatalf("read publication version: %v", err) } closing := request(http.MethodPut, "/api/v1/me/privacy/publication", fmt.Sprintf(`{"expected_version":%d,"state":"closed","fields":[]}`, version), login(candidate), "") if closing.Code != http.StatusOK { t.Fatalf("closing the publication = %d %s, want 200", closing.Code, closing.Body.String()) } requireNotFound("contact read after closing the publication", readContacts(orgD, invitation.ID, sessionOwnerD)) requireOrganizationAccess("organization view after closing the publication", orgD, invitation.ID, sessionOwnerD, "closed") if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { t.Fatalf("grant after closing: revoked %v reason %q, want visibility_closed", revoked, reason) } }) t.Run("the grant index for candidate-wide closing exists", func(t *testing.T) { var indexes int if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM pg_indexes WHERE indexname = 'contact_grants_candidate_active_idx'`).Scan(&indexes); err != nil { t.Fatalf("read the index catalog: %v", err) } if indexes != 1 { t.Fatalf("contact_grants_candidate_active_idx count = %d, want 1", indexes) } }) t.Run("a declined invitation shows not_granted", func(t *testing.T) { candidate := candidates[5] invitation := deliver(orgA, sessionOwnerA, candidate) answer := request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/decline", fmt.Sprintf(`{"expected_version":%d,"reason":"other"}`, invitation.Version), login(candidate), nextKey()) if answer.Code != http.StatusOK { t.Fatalf("decline = %d %s, want 200", answer.Code, answer.Body.String()) } declined := requireOrganizationAccess("organization view of a declined invitation", orgA, invitation.ID, sessionOwnerA, "not_granted") if declined.State != "declined" { t.Fatalf("declined invitation state = %q, want declined", declined.State) } }) // This subtest moves the clock to the response deadline, which ends the // sessions that were created earlier, so it signs in again after the move. // It must stay the last subtest. t.Run("an expired invitation shows not_granted", func(t *testing.T) { candidate := newCandidate("contact-candidate-expired@example.test") invitation := deliver(orgA, sessionOwnerA, candidate) var deadline time.Time if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, invitation.ID).Scan(&deadline); err != nil { t.Fatalf("read the response deadline: %v", err) } harness.clock.Set(deadline) ownerSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) candidateSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) // A read at the deadline expires the invitation before it answers. read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitation.ID.String(), "", candidateSession, ""), http.StatusOK) if read.State != "expired" { t.Fatalf("candidate read at the deadline = %+v, want expired", read) } expired := requireOrganizationAccess("organization view of an expired invitation", orgA, invitation.ID, ownerSession, "not_granted") if expired.State != "expired" { t.Fatalf("expired invitation state = %q, want expired", expired.State) } }) }