feat(invitations): check contact grants on every read, cap pending invitations, and expire them at the deadline

This commit is contained in:
shira committed 2026-10-09 19:06:50 +03:00
1 parent 676b3c6e24
commit 12a7213d4a
67 files changed
+4255 -149

No files matched your search

@@ -0,0 +1,518 @@
//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)
}
})
}
@@ -59,6 +59,9 @@ func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(t *testing.T) {
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() with the holdings migration error = %v", err)
}
// Later migrations sit above holdings: the rollback subtests undo holdings
// with DownOne, so the schema is taken back to the holdings version first.
rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion)
t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) {
firstHolding := legacyHolding(ctx, t, pool, first)
@@ -418,8 +418,10 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1, declinedEvents: 1, declines: 1}) {
t.Fatalf("decline from viewed stored %+v", counts)
}
// The comment rules of the contract and an unstorable value.
fresh := deliver(orgA, sessionA, target, nil)
// The comment rules of the contract and an unstorable value. The pause
// after the declines above holds their candidates for thirty days, so
// the new invitation goes to a cohort candidate that never declined.
fresh := deliver(orgA, sessionA, cohort[len(cohort)-1], nil)
tooLong := strings.Repeat("я", 501)
for name, body := range map[string]string{
"white space": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":" "}`,
@@ -441,7 +443,10 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
})
t.Run("another candidate and an employer learn nothing of the invitation", func(t *testing.T) {
sent := deliver(orgA, sessionA, target, nil)
// The sent invitation goes to a cohort candidate that never declined, so
// the pause after the declines above does not apply to it. Only the draft
// below is addressed to the candidate who declined.
sent := deliver(orgA, sessionA, cohort[len(cohort)-2], nil)
draft := draftFor(orgA, sessionA, target, nil)
for name, invitationID := range map[string]uuid.UUID{"another candidate's": sent.ID, "unknown": uuid.New()} {
for _, response := range []*httptest.ResponseRecorder{
@@ -496,10 +501,12 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
})
t.Run("a stale version is not stored and a late decline is refused whatever the version", func(t *testing.T) {
sent := deliver(orgA, sessionA, other, func(body, terms map[string]any) { body["response_period_days"] = 3 })
// Hider has no other invitation of this organization, so the pause after
// the declines above does not apply to it.
sent := deliver(orgA, sessionA, hider, func(body, terms map[string]any) { body["response_period_days"] = 3 })
key := nextKey()
requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts.declines != 0 {
requireSessionProblem(t, decline(sessionHider, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts.declines != 0 {
t.Fatalf("a stale decline stored %+v", counts)
}
var stored int
@@ -516,17 +523,20 @@ func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
t.Fatalf("read the deadline: %v", err)
}
harness.clock.Set(exactDeadline.UTC())
lateSession := login(other)
lateSession := login(hider)
// The late view applies the due expiry, so it answers with the expired
// invitation and records no view.
late := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", lateSession, ""), http.StatusOK)
if late.State != "delivered" || late.Version != sent.Version || late.ViewedAt != nil {
t.Fatalf("late view = %+v, want the invitation unchanged", late)
if late.State != "expired" || late.ExpiryReason == nil || *late.ExpiryReason != "invitation_timeout" ||
late.Version != sent.Version+1 || late.ViewedAt != nil {
t.Fatalf("late view = %+v, want the invitation expired by the timeout without a view", late)
}
lateKey := nextKey()
for range 2 {
requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version+3, "tasks", nil), lateKey), http.StatusConflict, "state_conflict")
requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(late.Version+2, "tasks", nil), lateKey), http.StatusConflict, "state_conflict")
}
requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version, "tasks", nil), key), http.StatusConflict, "state_conflict")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{}) {
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts != (invitationAnswerCounts{}) {
t.Fatalf("late commands stored %+v", counts)
}
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1 AND outcome = 'state_conflict'`, sent.ID).Scan(&stored); err != nil || stored != 2 {
@@ -0,0 +1,551 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
identityusecase "lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/policy"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
)
const (
// invitationExpiryMigrationVersion adds the pending limit, the pause, and
// the expiry at the response deadline.
invitationExpiryMigrationVersion = 43
// invitationExpiryJobKind is the kind of the response deadline job.
invitationExpiryJobKind = "invitation.response_deadline"
)
// noopDeliveryNotifier stands in for the notification outbox: these tests
// check the invitation rules, not the events of a delivery.
type noopDeliveryNotifier struct{}
func (noopDeliveryNotifier) InvitationDelivered(context.Context, outbound.UnitOfWork, domain.Invitation) error {
return nil
}
// invitationLimitsFixture drives the invitation usecases against one isolated
// database with the real repositories, quota, consent ledger, and scheduled
// job store. Candidates resolve through a table of handles, because the card
// visibility rules are tested elsewhere.
type invitationLimitsFixture struct {
ctx context.Context
databaseURL string
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
identity identityFixture
organizations organizationFixture
clock *testClock
service *invitationusecase.Service
key domain.CandidateViewPseudonymKey
handles map[string]uuid.UUID
organization domain.Organization
owner domain.User
secondOwner domain.User
}
func newInvitationLimitsFixture(ctx context.Context, t *testing.T, env *testEnvironment, databaseURL string) invitationLimitsFixture {
t.Helper()
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
// The policy takes effect when it is stored, after the first read of the
// clock, as in the HTTP harness.
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)}
transactor := postgresadapter.NewTransactor(pool)
identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()}
owner := organizations.employer(t, "limits-owner@example.test")
confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute))
organization := organizations.create(t, owner, organizations.completeProfile(t, "Limits company"), clock.Now())
secondOwner := identities.createUser(t, "limits-second-owner@example.test", domain.ScenarioEmployer, clock.Now().Add(-time.Hour))
confirmEmail(ctx, t, pool, secondOwner, clock.Now().Add(-time.Minute))
insertOwnerMembership(ctx, t, transactor, organization.ID(), secondOwner.ID, clock.Now())
keyring, err := identityusecase.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)
}
fixture := invitationLimitsFixture{
ctx: ctx, databaseURL: databaseURL, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock,
key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, secondOwner: secondOwner,
}
quota := companyquota.NewService(clock.Now)
service, err := invitationusecase.NewService(invitationusecase.Dependencies{
Transactor: transactor, Keyring: keyring, PseudonymKey: key,
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
candidateID, ok := fixture.handles[handle]
if !ok || organizationID != organization.ID() {
return uuid.Nil, candidateview.ErrCandidateCardNotFound
}
return candidateID, nil
},
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: noopDeliveryNotifier{}, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
}
fixture.service = service
return fixture
}
// insertOwnerMembership adds an active owner, which the MVP allows beside the
// first one: every owner may send and answer for the organization.
func insertOwnerMembership(ctx context.Context, t *testing.T, transactor *postgresadapter.Transactor, organizationID, userID uuid.UUID, at time.Time) {
t.Helper()
membership, err := domain.NewOwnerMembership(organizationID, userID, at)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
if err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Memberships().Insert(ctx, membership)
}); err != nil {
t.Fatalf("insert owner membership: %v", err)
}
}
// confirmEmail marks the account's email confirmed at the given time. The
// invitation commands require a confirmed email of both the employer and the
// candidate.
func confirmEmail(ctx context.Context, t *testing.T, pool *pgxpool.Pool, user domain.User, at time.Time) {
t.Helper()
if _, err := pool.Exec(ctx, `
UPDATE users SET email_verified_at = $2, version = version + 1 WHERE id = $1`, user.ID, at); err != nil {
t.Fatalf("confirm the email of %s: %v", user.ID, err)
}
}
// candidate makes a candidate account that can sign in and gives it a card
// handle for the organization.
func (fixture *invitationLimitsFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour))
confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute))
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
fixture.handles[handle] = user.ID
return user
}
func (fixture *invitationLimitsFixture) handleOf(t *testing.T, candidateID uuid.UUID) string {
t.Helper()
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return handle
}
// need stores a need of the organization with its first requirements version.
func (fixture *invitationLimitsFixture) need(t *testing.T, title string) domain.InvitationNeedRef {
t.Helper()
need := newIntegrationNeed(t, fixture.organization.ID(), title, fixture.clock.Now())
fixture.organizations.createNeed(t, need)
return domain.InvitationNeedRef{NeedID: need.ID(), RequirementsVersion: need.RequirementsVersion()}
}
// draft creates a draft for the candidate, under the need when one is given.
func (fixture *invitationLimitsFixture) draft(
t *testing.T,
actor domain.User,
candidateID uuid.UUID,
need *domain.InvitationNeedRef,
period *int32,
) domain.OrganizationInvitationView {
t.Helper()
key := "create-" + uuid.NewString()
view, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{
ActorID: actor.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key,
CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID),
Need: need, ResponsePeriodDays: period, Terms: invitationStorageTerms(),
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
return view
}
func (fixture *invitationLimitsFixture) sendCommand(actor domain.User, view domain.OrganizationInvitationView) invitationusecase.SendCommand {
return invitationusecase.SendCommand{
ActorID: actor.ID, OrganizationID: fixture.organization.ID(), InvitationID: view.ID,
IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: view.Version,
}
}
// send delivers a draft and fails the test when the send is refused.
func (fixture *invitationLimitsFixture) send(t *testing.T, actor domain.User, view domain.OrganizationInvitationView) domain.OrganizationInvitationView {
t.Helper()
sent, err := fixture.service.Send(fixture.ctx, fixture.sendCommand(actor, view))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
return sent
}
// count reads one number of the database, scoped to the organization.
func (fixture *invitationLimitsFixture) count(t *testing.T, query string, args ...any) int64 {
t.Helper()
var value int64
if err := fixture.pool.QueryRow(fixture.ctx, query, args...).Scan(&value); err != nil {
t.Fatalf("count %q: %v", query, err)
}
return value
}
// enlargeQuota makes the organization E1, whose weekly invitation quota is
// larger than the E0 quota of the demo policy, so that the pending limit is
// the rule under test.
func (fixture *invitationLimitsFixture) enlargeQuota(t *testing.T) {
t.Helper()
if _, err := fixture.pool.Exec(fixture.ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, fixture.organization.ID(), fixture.clock.Now()); err != nil {
t.Fatalf("raise the organization to E1: %v", err)
}
}
func TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t))
fixture.enlargeQuota(t)
candidate := fixture.candidate(t, "limits-candidate-pending@example.test")
need := fixture.need(t, "Pending need")
needRef := need
for index := range 19 {
draft := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil)
fixture.send(t, fixture.owner, draft)
if index == 18 && fixture.count(t, `SELECT count(*) FROM invitations WHERE need_id = $1 AND state = 'delivered'`, need.NeedID) != 19 {
t.Fatal("nineteen invitations are not waiting")
}
}
first := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil)
second := fixture.draft(t, fixture.secondOwner, candidate.ID, &needRef, nil)
var group sync.WaitGroup
results := make([]error, 2)
for index, sender := range []struct {
actor domain.User
view domain.OrganizationInvitationView
}{{fixture.owner, first}, {fixture.secondOwner, second}} {
group.Go(func() {
_, results[index] = fixture.service.Send(ctx, fixture.sendCommand(sender.actor, sender.view))
})
}
group.Wait()
admitted, refused := 0, 0
for _, err := range results {
switch {
case err == nil:
admitted++
case errors.Is(err, invitationusecase.ErrSendBlocked):
refused++
default:
t.Fatalf("concurrent Send() error = %v, want success or ErrSendBlocked", err)
}
}
if admitted != 1 || refused != 1 {
t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused)
}
waiting := fixture.count(t, `
SELECT count(*) FROM invitations
WHERE need_id = $1 AND state IN ('delivered', 'viewed', 'counter')`, need.NeedID)
if waiting != 20 {
t.Fatalf("waiting invitations under the need = %d, want exactly the limit of 20", waiting)
}
if charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, fixture.organization.ID()); charges != 20 {
t.Fatalf("quota charges = %d, want one per admitted send", charges)
}
// The refused draft is still a draft and carries no charge.
refusedDraftState := fixture.count(t, `
SELECT count(*) FROM invitations
WHERE need_id = $1 AND state = 'draft'`, need.NeedID)
if refusedDraftState != 1 {
t.Fatalf("drafts under the need = %d, want the refused draft only", refusedDraftState)
}
}
func TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t))
candidate := fixture.candidate(t, "limits-candidate-pause@example.test")
firstNeed := fixture.need(t, "Declined need")
secondNeed := fixture.need(t, "Another need")
// The candidate receives and declines an invitation under the first need.
first := fixture.draft(t, fixture.owner, candidate.ID, &firstNeed, nil)
sent := fixture.send(t, fixture.owner, first)
declinedAt := sent.DeliveredAt.Add(time.Hour)
fixture.clock.Set(declinedAt)
if _, err := fixture.service.DeclineMine(ctx, invitationusecase.DeclineCommand{
ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
}); err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
// Another owner of the same organization sends under another need.
next := fixture.draft(t, fixture.secondOwner, candidate.ID, &secondNeed, nil)
fixture.clock.Set(declinedAt.Add(29 * 24 * time.Hour))
if _, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); !errors.Is(err, invitationusecase.ErrSendBlocked) {
t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err)
}
if state := fixture.count(t, `SELECT count(*) FROM invitations WHERE id = $1 AND state = 'draft'`, next.ID); state != 1 {
t.Fatal("a send refused by the pause changed the draft")
}
// The same draft goes out on day 30, with a new key.
fixture.clock.Set(declinedAt.Add(30 * 24 * time.Hour))
if view, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); err != nil || view.State != domain.InvitationDelivered {
t.Fatalf("Send(day 30 after the decline) = %v, %v; want delivered", view.State, err)
}
}
func TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t))
threeDays := int32(3)
// Each round delivers a fresh invitation with a three-day deadline and lets
// an acceptance at the deadline race the expiry job.
for round := range 3 {
candidate := fixture.candidate(t, fmt.Sprintf("limits-candidate-race-%d@example.test", round))
draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays)
sent := fixture.send(t, fixture.owner, draft)
deadline := *sent.ResponseDeadlineAt
charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID)
worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock)
fixture.clock.Set(deadline)
acceptCommand := invitationusecase.AcceptCommand{
ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-" + uuid.NewString(),
ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01",
Fields: []domain.ContactField{domain.ContactFieldEmail},
}
var group sync.WaitGroup
var acceptErr error
var runErr error
group.Go(func() {
_, acceptErr = fixture.service.AcceptMine(ctx, acceptCommand)
})
group.Go(func() {
_, runErr = worker.RunDue(ctx)
})
group.Wait()
if runErr != nil {
t.Fatalf("round %d: RunDue() error = %v", round, runErr)
}
if !errors.Is(acceptErr, invitationusecase.ErrAnswerBlocked) {
t.Fatalf("round %d: AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", round, acceptErr)
}
assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges)
if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 {
t.Fatalf("round %d: %d contact grants after a late acceptance, want none", round, grants)
}
if consents := fixture.count(t, `SELECT count(*) FROM consent_records WHERE invitation_id = $1 AND purpose = 'c4'`, sent.ID); consents != 0 {
t.Fatalf("round %d: %d consent C4 records after a late acceptance, want none", round, consents)
}
var jobStatus string
var jobError *string
if err := fixture.pool.QueryRow(ctx, `SELECT status, last_error_class FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`,
invitationExpiryJobKind, sent.ID.String()).Scan(&jobStatus, &jobError); err != nil {
t.Fatalf("round %d: read the deadline job: %v", round, err)
}
if jobStatus != "done" {
t.Fatalf("round %d: the deadline job is %s with error %v, want done", round, jobStatus, jobError)
}
}
}
func TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t))
threeDays := int32(3)
candidate := fixture.candidate(t, "limits-candidate-job-first@example.test")
draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays)
sent := fixture.send(t, fixture.owner, draft)
deadline := *sent.ResponseDeadlineAt
charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID)
// The job runs first at its due time and expires the invitation.
fixture.clock.Set(deadline)
worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock)
if _, err := worker.RunDue(ctx); err != nil {
t.Fatalf("RunDue() error = %v", err)
}
assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges)
// The acceptance that arrives afterwards finds the expiry and grants nothing.
_, err := fixture.service.AcceptMine(ctx, invitationusecase.AcceptCommand{
ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-after-job",
ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01",
Fields: []domain.ContactField{domain.ContactFieldEmail},
})
if !errors.Is(err, invitationusecase.ErrAnswerBlocked) {
t.Fatalf("AcceptMine(after the job) error = %v, want ErrAnswerBlocked", err)
}
if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 {
t.Fatalf("contact grants = %d after the job won, want none", grants)
}
if events := fixture.count(t, `SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'expired'`, sent.ID); events != 1 {
t.Fatalf("expiry events = %d, want one", events)
}
}
// newDeadlineJobWorker builds the scheduled job worker with the response
// deadline handler, against the store of the isolated test database and the
// fixture clock, as the application does.
func newDeadlineJobWorker(ctx context.Context, t *testing.T, databaseURL string, clock *testClock) *jobrunner.Worker {
t.Helper()
pool := newPoolFor(ctx, t, databaseURL)
settings := jobrunner.Settings{
BatchSize: 10, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3,
Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond},
ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second,
}
worker, err := jobrunner.New(
[]inbound.JobHandler{invitationusecase.NewResponseDeadlineJob(clock.Now)},
postgresadapter.NewScheduledJobStore(pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, clock.Now,
)
if err != nil {
t.Fatalf("jobrunner.New() error = %v", err)
}
return worker
}
// assertExpiredAtDeadline checks the stored state of an expired invitation: the
// deadline and terms are kept, the timeout reason is set, the audit event has
// no actor, and the quota charge is unchanged.
func assertExpiredAtDeadline(t *testing.T, fixture invitationLimitsFixture, invitationID uuid.UUID, deadline time.Time, charges int64) {
t.Helper()
var state, reason string
var storedDeadline time.Time
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT state, expiry_reason, response_deadline_at FROM invitations WHERE id = $1`, invitationID).Scan(&state, &reason, &storedDeadline); err != nil {
t.Fatalf("read invitation: %v", err)
}
if state != string(domain.InvitationExpired) || reason != string(domain.InvitationExpiryTimeout) || !storedDeadline.Equal(deadline) {
t.Fatalf("invitation = %s/%s deadline %v, want expired by the timeout at %v", state, reason, storedDeadline, deadline)
}
events := fixture.count(t, `
SELECT count(*) FROM invitation_events
WHERE invitation_id = $1 AND kind = 'expired' AND actor_id IS NULL AND cardinality(changed_fields) = 0`, invitationID)
if events != 1 {
t.Fatalf("expiry events without an actor = %d, want one", events)
}
if stored := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, invitationID); stored != charges {
t.Fatalf("quota charges of the invitation = %d, want the %d of the send", stored, charges)
}
}
func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(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)
}
fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL)
rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion-1)
// A delivery made before the migration has no deadline job yet.
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 := fixture.transactor.WithinTransaction(ctx, 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)
}
deadline := *delivered.Snapshot().ResponseDeadlineAt
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up(43) error = %v", err)
}
var jobs int
var dueAt time.Time
if err := pool.QueryRow(ctx, `
SELECT count(*), coalesce(max(due_at), now())
FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2 AND status = 'pending'`,
invitationExpiryJobKind, delivered.ID().String()).Scan(&jobs, &dueAt); err != nil {
t.Fatalf("read the backfilled job: %v", err)
}
if jobs != 1 || !dueAt.Equal(deadline) {
t.Fatalf("backfilled jobs = %d due %v, want one due at the deadline %v", jobs, dueAt, deadline)
}
// The trigger refuses an expiry that is recorded before the deadline, and
// an expiry of an invitation that is not waiting for an answer.
if _, err := pool.Exec(ctx, `
UPDATE invitations
SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2
WHERE id = $1`, delivered.ID(), deadline.Add(-time.Second)); err == nil {
t.Fatal("an expiry before the deadline was stored")
}
if _, err := pool.Exec(ctx, `
UPDATE invitations
SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2
WHERE id = $1`, delivered.ID(), deadline); err != nil {
t.Fatalf("expiry at the deadline error = %v", err)
}
// A rollback keeps the expiry, which the previous schema cannot represent.
if _, err := migrator.DownOne(ctx); err == nil {
t.Fatal("rollback with an expired invitation succeeded, want it refused")
}
var expired int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE state = 'expired'`).Scan(&expired); err != nil || expired != 1 {
t.Fatalf("expired invitations after the refused rollback = %d, %v; want the stored expiry", expired, err)
}
}
@@ -28,6 +28,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
@@ -130,16 +131,25 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro
if err != nil {
t.Fatalf("notification.NewInboxService() error = %v", err)
}
// The consent and the visibility operations are served too, so the contact
// read can be revoked through the same routes a candidate uses.
privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now})
if err != nil {
t.Fatalf("candidateprivacy.NewService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessionService), v1.WithPublicOrigin(env.Config.AppPublicURL))
organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
consentHandler := v1.NewConsentHandler(consent.NewQueryService(postgresadapter.NewConsentStore(pool), clock.Now), consent.NewService(transactor, clock.Now))
privacyHandler := v1.NewPrivacyHandler(views, privacySettings, 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)),
v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))