feat(invitations): send invitations into the candidate inbox atomically
This commit is contained in:
1 parent
fc35e27af5
commit
1a067221f7
46 files changed
+3276
-113
No files matched your search
@@ -31,6 +31,11 @@ type companyQuotaFixture struct {
|
||||
organizations organizationFixture
|
||||
policies outbound.PolicyRepository
|
||||
version domain.PolicyVersion
|
||||
// invitationAuthor and invitationCandidate are the accounts of the drafts
|
||||
// that invitation usage names: a charge refers to a stored invitation of
|
||||
// the same organization.
|
||||
invitationAuthor uuid.UUID
|
||||
invitationCandidate uuid.UUID
|
||||
}
|
||||
|
||||
func TestCompanyQuota(t *testing.T) {
|
||||
@@ -59,6 +64,8 @@ func TestCompanyQuota(t *testing.T) {
|
||||
ctx: ctx, pool: pool, clock: clock, transactor: transactor,
|
||||
service: companyquota.NewService(clock.Now), organizations: organizationFixture,
|
||||
policies: policyStore.Policies(), version: version,
|
||||
invitationAuthor: organizationFixture.employer(t, "quota-invitation-author@example.test").ID,
|
||||
invitationCandidate: identity.createUser(t, "quota-invitation-candidate@example.test", domain.ScenarioCandidate, clock.Now().Add(-time.Hour)).ID,
|
||||
}
|
||||
|
||||
t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) {
|
||||
@@ -66,7 +73,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
var firstCandidate uuid.UUID
|
||||
var boundaryCandidate uuid.UUID
|
||||
for range 9 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization))
|
||||
}
|
||||
for index := range 49 {
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
@@ -87,11 +94,12 @@ func TestCompanyQuota(t *testing.T) {
|
||||
results := make(chan result, 4)
|
||||
var workers sync.WaitGroup
|
||||
for range 2 {
|
||||
invitationID := fixture.newInvitationID(t, organization)
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
decision, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
decision, err := fixture.reserveInvitation(organization, invitationID)
|
||||
results <- result{decision: decision, err: err, kind: "invitation"}
|
||||
}()
|
||||
}
|
||||
@@ -156,7 +164,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
call func(domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error)
|
||||
}{
|
||||
{name: "card view at the 24-hour boundary", id: boundaryCandidate, call: fixture.reserveCardView},
|
||||
{name: "invitation remains charged during the first day", id: uuid.New(), call: fixture.reserveInvitation},
|
||||
{name: "invitation remains charged during the first day", id: fixture.newInvitationID(t, organization), call: fixture.reserveInvitation},
|
||||
} {
|
||||
decision, err := step.call(organization, step.id)
|
||||
if err != nil {
|
||||
@@ -174,7 +182,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
fixture.assertQuotaRowCounts(t, organization.ID(), 10, 2)
|
||||
|
||||
fixture.clock.Set(atDay.Add(6 * 24 * time.Hour))
|
||||
newInvitation := uuid.New()
|
||||
newInvitation := fixture.newInvitationID(t, organization)
|
||||
decision, err := fixture.reserveInvitation(organization, newInvitation)
|
||||
if err != nil || !decision.Allowed || decision.Reused {
|
||||
t.Fatalf("ReserveInvitation(at 7 days) = %+v, %v; want a new allowed invitation", decision, err)
|
||||
@@ -183,7 +191,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
|
||||
// The same invitation ID stays idempotent beyond the rolling window,
|
||||
// independently of any request idempotency key used by its caller.
|
||||
oldInvitationID := uuid.New()
|
||||
oldInvitationID := fixture.newInvitationID(t, organization)
|
||||
fixture.reserveInvitationAllowed(t, organization, oldInvitationID)
|
||||
fixture.clock.Advance(8 * 24 * time.Hour)
|
||||
reused, err := fixture.reserveInvitation(organization, oldInvitationID)
|
||||
@@ -195,9 +203,9 @@ func TestCompanyQuota(t *testing.T) {
|
||||
t.Run("E1 enforces the stored 40 and 150 limits", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "e1-boundary", domain.OrganizationVerificationE1)
|
||||
for range 40 {
|
||||
fixture.reserveInvitationAllowed(t, organization, uuid.New())
|
||||
fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization))
|
||||
}
|
||||
deniedInvitation, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
deniedInvitation, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization))
|
||||
if err != nil || deniedInvitation.Allowed || !deniedInvitation.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) {
|
||||
t.Fatalf("E1 invitation 41 = %+v, %v; want denial for one week", deniedInvitation, err)
|
||||
}
|
||||
@@ -229,7 +237,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
fixture.version = activePolicy
|
||||
|
||||
verified, _ := fixture.newOrganization(t, "active-e2", domain.OrganizationVerificationE2)
|
||||
invitation, err := fixture.reserveInvitation(verified, uuid.New())
|
||||
invitation, err := fixture.reserveInvitation(verified, fixture.newInvitationID(t, verified))
|
||||
if err != nil || !invitation.Allowed || invitation.Reused {
|
||||
t.Fatalf("ReserveInvitation(verified E2) = %+v, %v; want an allowed new reservation", invitation, err)
|
||||
}
|
||||
@@ -255,7 +263,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("build forged E2 snapshot: %v", err)
|
||||
}
|
||||
if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, uuid.New()); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, fixture.newInvitationID(t, e0Organization)); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with forged E2 snapshot against stored E0 organization error = %v, want snapshot mismatch", err)
|
||||
}
|
||||
fixture.assertQuotaRowCounts(t, e0Organization.ID(), 0, 0)
|
||||
@@ -285,7 +293,9 @@ func TestCompanyQuota(t *testing.T) {
|
||||
t.Run("candidate deletion clears card-view data but leaves invitation quota evidence", func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "candidate-delete", domain.OrganizationVerificationE0)
|
||||
candidateID := fixture.newCandidateID(t)
|
||||
fixture.reserveInvitationAllowed(t, organization, candidateID)
|
||||
// The charged invitation names another candidate: a candidate with an
|
||||
// invitation cannot be deleted until a deletion procedure settles it.
|
||||
fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization))
|
||||
fixture.reserveCardViewAllowed(t, organization, candidateID)
|
||||
|
||||
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM users WHERE id = $1`, candidateID); err != nil {
|
||||
@@ -298,8 +308,9 @@ func TestCompanyQuota(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "snapshot-check", domain.OrganizationVerificationE0)
|
||||
quota := fixture.quota(t, organization, fixture.version)
|
||||
rollbackMarker := errors.New("test transaction rollback")
|
||||
rolledBackInvitation := fixture.newInvitationID(t, organization)
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, uuid.New())
|
||||
decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, rolledBackInvitation)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -319,7 +330,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
WHERE id = $1`, organization.ID(), fixture.clock.Now().Add(-time.Minute)); err != nil {
|
||||
t.Fatalf("change stored organization verification: %v", err)
|
||||
}
|
||||
staleTrustErr := fixture.reserveWithSnapshot(organization, quota, uuid.New())
|
||||
staleTrustErr := fixture.reserveWithSnapshot(organization, quota, fixture.newInvitationID(t, organization))
|
||||
if !errors.Is(staleTrustErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale organization trust error = %v, want snapshot mismatch", staleTrustErr)
|
||||
}
|
||||
@@ -335,7 +346,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("publish next effective product policy: %v", err)
|
||||
}
|
||||
stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, uuid.New())
|
||||
stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, fixture.newInvitationID(t, policyOrganization))
|
||||
if !errors.Is(stalePolicyErr, outbound.ErrCompanyQuotaSnapshotChanged) {
|
||||
t.Fatalf("reserve with stale policy error = %v, want snapshot mismatch", stalePolicyErr)
|
||||
}
|
||||
@@ -353,7 +364,7 @@ func TestCompanyQuota(t *testing.T) {
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
organization, _ := fixture.newOrganization(t, "denied-"+string(test.level), test.level)
|
||||
_, err := fixture.reserveInvitation(organization, uuid.New())
|
||||
_, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization))
|
||||
if !errors.Is(err, domain.ErrCompanyQuotaDenied) {
|
||||
t.Fatalf("ReserveInvitation(%s) error = %v, want fail-closed denial", test.level, err)
|
||||
}
|
||||
@@ -393,6 +404,34 @@ func (fixture companyQuotaFixture) newOrganization(
|
||||
return stored, owner
|
||||
}
|
||||
|
||||
// newInvitationID stores a draft of the organization and returns its
|
||||
// identifier, so the usage that names it satisfies the foreign key.
|
||||
func (fixture companyQuotaFixture) newInvitationID(t *testing.T, organization domain.Organization) uuid.UUID {
|
||||
t.Helper()
|
||||
invitationID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
t.Fatalf("NewV7() error = %v", err)
|
||||
}
|
||||
draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
|
||||
ID: invitationID, OrganizationID: organization.ID(), CandidateID: fixture.invitationCandidate, ActorID: fixture.invitationAuthor,
|
||||
PolicyVersionID: fixture.version.ID(), At: fixture.clock.Now().Add(-time.Minute),
|
||||
Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationDraft() error = %v", err)
|
||||
}
|
||||
event, err := draft.DraftEvent(fixture.invitationAuthor, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DraftEvent() error = %v", err)
|
||||
}
|
||||
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Invitations().Create(ctx, draft, event)
|
||||
}); err != nil {
|
||||
t.Fatalf("store the draft of the charge: %v", err)
|
||||
}
|
||||
return invitationID
|
||||
}
|
||||
|
||||
func (fixture companyQuotaFixture) newCandidateID(t *testing.T) uuid.UUID {
|
||||
t.Helper()
|
||||
candidate := fixture.organizations.identity.createUser(
|
||||
|
||||
@@ -34,6 +34,8 @@ import (
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
invitationusecase "lincodex/backend/internal/usecase/invitation"
|
||||
needusecase "lincodex/backend/internal/usecase/need"
|
||||
"lincodex/backend/internal/usecase/notification"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
"lincodex/backend/internal/usecase/organization"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
@@ -104,12 +106,29 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro
|
||||
if err != nil {
|
||||
t.Fatalf("candidateview.NewService() error = %v", err)
|
||||
}
|
||||
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer() error = %v", err)
|
||||
}
|
||||
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), clock.Now))
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationNotifier() error = %v", err)
|
||||
}
|
||||
invitationService, err := invitationusecase.NewService(invitationusecase.Dependencies{
|
||||
Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, Clock: clock.Now,
|
||||
Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
|
||||
},
|
||||
Notifier: notifier, Clock: clock.Now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("invitation.NewService() error = %v", err)
|
||||
}
|
||||
inbox, err := notification.NewInboxService(transactor,
|
||||
notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(false)), clock.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("notification.NewInboxService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
@@ -119,6 +138,7 @@ func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnviro
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler),
|
||||
v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)),
|
||||
v1.WithNotifications(v1.NewNotificationHandler(inbox)),
|
||||
)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
|
||||
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
|
||||
|
||||
@@ -0,0 +1,676 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"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/port/outbound"
|
||||
"lincodex/backend/internal/usecase/notification"
|
||||
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const (
|
||||
// invitationSendMigrationVersion adds sending: the delivery event, the
|
||||
// stored send outcomes, and the key of quota usage to invitations.
|
||||
invitationSendMigrationVersion = 38
|
||||
invitationDeliveriesRetained = "invitation_deliveries_retained"
|
||||
// invitationSendE0Quota is the weekly invitation quota of an E0
|
||||
// organization in the demo product policy.
|
||||
invitationSendE0Quota = 10
|
||||
)
|
||||
|
||||
// candidateInvitationPage is the part of the candidate's inbox that the tests
|
||||
// read. A field that must be absent has no member, and the raw text is
|
||||
// scanned as well.
|
||||
type candidateInvitationPage struct {
|
||||
Items []struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Organization struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"organization"`
|
||||
State string `json:"state"`
|
||||
Version int64 `json:"version"`
|
||||
TermsVersion int64 `json:"terms_version"`
|
||||
RoleTitle string `json:"role_title"`
|
||||
WorkFormats []string `json:"work_formats"`
|
||||
ResponseDeadlineAt time.Time `json:"response_deadline_at"`
|
||||
DeliveredAt time.Time `json:"delivered_at"`
|
||||
ViewedAt *string `json:"viewed_at"`
|
||||
} `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
|
||||
// invitationSendCounts are the rows that one send may create, for one
|
||||
// invitation: the invitation, its audit events, the outbox events of the
|
||||
// notification, the charge, and the email request of its candidate.
|
||||
type invitationSendCounts struct {
|
||||
invitations, events, deliveredEvents, outboxDelivered, charges, mailRequests int
|
||||
}
|
||||
|
||||
func readInvitationSendCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationSendCounts {
|
||||
t.Helper()
|
||||
var counts invitationSendCounts
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
(SELECT count(*) FROM invitations WHERE id = $1),
|
||||
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1),
|
||||
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'delivered'),
|
||||
(SELECT count(*) FROM outbox_events WHERE event_type = 'invitation.delivered' AND aggregate_type = 'invitation' AND aggregate_id = $1),
|
||||
(SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1),
|
||||
(SELECT count(*) FROM outbox_events WHERE event_type = 'notification.mail_requested' AND (
|
||||
aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $2)
|
||||
OR aggregate_id IN (SELECT id FROM deliveries WHERE recipient_user_id = $2)))`,
|
||||
invitationID, candidateID).Scan(&counts.invitations, &counts.events, &counts.deliveredEvents, &counts.outboxDelivered,
|
||||
&counts.charges, &counts.mailRequests); err != nil {
|
||||
t.Fatalf("count the rows of a send: %v", err)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
// outboxEnvelope reads one stored outbox event as the envelope a consumer
|
||||
// receives for it.
|
||||
func outboxEnvelope(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, where string, args ...any) outbound.ConsumedEvent {
|
||||
t.Helper()
|
||||
var event outbound.ConsumedEvent
|
||||
var payload string
|
||||
if err := harness.pool.QueryRow(ctx, `
|
||||
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
|
||||
FROM outbox_events WHERE `+where, args...).Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType,
|
||||
&event.AggregateID, &event.AggregateVersion, &payload, &event.OccurredAt); err != nil {
|
||||
t.Fatalf("read the outbox event: %v", err)
|
||||
}
|
||||
event.Payload = []byte(payload)
|
||||
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
|
||||
return event
|
||||
}
|
||||
|
||||
func TestOrganizationInvitationSendOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolated := *env
|
||||
isolated.Config.DatabaseURL = databaseURL
|
||||
setupPool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
||||
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
||||
}
|
||||
harness := newInvitationHTTPHarness(ctx, t, &isolated)
|
||||
// The policy takes effect when it is stored, after the clock of the
|
||||
// harness was first read.
|
||||
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second))
|
||||
origin := env.Config.AppPublicURL
|
||||
now := harness.clock.Now()
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
account := func(email string, scenario domain.Scenario) domain.User {
|
||||
return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now)
|
||||
}
|
||||
ownerA, ownerB := account("send-owner-a@example.test", domain.ScenarioEmployer), account("send-owner-b@example.test", domain.ScenarioEmployer)
|
||||
recruiter := account("send-recruiter@example.test", domain.ScenarioEmployer)
|
||||
sessionA, sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address())
|
||||
sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address())
|
||||
orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "send-company-a")
|
||||
orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "send-company-b")
|
||||
insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now)
|
||||
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)
|
||||
}
|
||||
|
||||
// Seven published candidates form the visible cohort of both
|
||||
// organizations. The first two can sign in to read their inbox.
|
||||
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}
|
||||
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),
|
||||
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)
|
||||
}
|
||||
}
|
||||
target := account("send-target@example.test", domain.ScenarioCandidate)
|
||||
other := account("send-other@example.test", domain.ScenarioCandidate)
|
||||
cohort := []domain.User{target, other}
|
||||
for index := range 5 {
|
||||
candidate := privacy.candidate(t, fmt.Sprintf("send-visible-%d@example.test", index))
|
||||
verifyPrivacyCohortCandidate(t, privacy, candidate)
|
||||
cohort = append(cohort, candidate)
|
||||
}
|
||||
for _, candidate := range cohort {
|
||||
publishCandidate(candidate)
|
||||
}
|
||||
sessionTarget := loginOrganizationHTTP(t, harness.sessionHTTPHarness, target.Email.Address())
|
||||
sessionOther := loginOrganizationHTTP(t, harness.sessionHTTPHarness, other.Email.Address())
|
||||
alias := func(organizationID uuid.UUID, candidate domain.User) string {
|
||||
t.Helper()
|
||||
handle, err := harness.key.ForOrganization(organizationID, candidate.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
return handle
|
||||
}
|
||||
|
||||
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-send-key-%d", keySequence)
|
||||
}
|
||||
itemPath := func(organizationID, invitationID uuid.UUID) string {
|
||||
return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID)
|
||||
}
|
||||
sendPath := func(organizationID, invitationID uuid.UUID) string {
|
||||
return itemPath(organizationID, invitationID) + "/send"
|
||||
}
|
||||
sendBody := func(version int64) string { return fmt.Sprintf(`{"expected_version":%d}`, version) }
|
||||
draftFor := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody {
|
||||
t.Helper()
|
||||
response := request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID),
|
||||
invitationCreateJSON(t, alias(organizationID, candidate), change), session, nextKey())
|
||||
return decodeInvitationHTTP(t, response, http.StatusCreated)
|
||||
}
|
||||
inbox := func(session organizationHTTPSession, query string) (*httptest.ResponseRecorder, candidateInvitationPage) {
|
||||
t.Helper()
|
||||
response := request(http.MethodGet, "/api/v1/me/invitations"+query, "", session, "")
|
||||
var page candidateInvitationPage
|
||||
if response.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatalf("decode inbox %s: %v", response.Body.String(), err)
|
||||
}
|
||||
}
|
||||
return response, page
|
||||
}
|
||||
candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker}
|
||||
for _, candidate := range cohort {
|
||||
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", "email", "phone", "telegram", "full_name", "salary_minimum"} {
|
||||
if strings.Contains(text, `"`+field+`":`) {
|
||||
t.Errorf("%s contains the key %q: %s", label, field, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
consumers := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL)
|
||||
|
||||
t.Run("delivers a draft into the candidate's inbox before any email", func(t *testing.T) {
|
||||
draft := draftFor(orgA, sessionA, target, nil)
|
||||
response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey())
|
||||
sent := decodeInvitationHTTP(t, response, http.StatusOK)
|
||||
requireNoCandidateData("send response", response.Body.String())
|
||||
if sent.State != "delivered" || sent.Version != draft.Version+1 || sent.TermsVersion != draft.TermsVersion ||
|
||||
sent.DeliveredAt == nil || sent.ResponseDeadlineAt == nil || sent.CandidateHandle != draft.CandidateHandle {
|
||||
t.Fatalf("sent invitation = %+v, want the delivered next version of the draft", sent)
|
||||
}
|
||||
deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt)
|
||||
if !deadline.Equal(deliveredAt.Add(7 * 24 * time.Hour)) {
|
||||
t.Fatalf("deadline = %s, want the default 7 days after the delivery %s", deadline, deliveredAt)
|
||||
}
|
||||
|
||||
// The candidate reads it at once: the commit of the send is the
|
||||
// delivery, and no email exists yet.
|
||||
listed, page := inbox(sessionTarget, "")
|
||||
if listed.Code != http.StatusOK || listed.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("inbox = %d %s", listed.Code, listed.Body.String())
|
||||
}
|
||||
requireNoCandidateData("candidate inbox", listed.Body.String())
|
||||
if strings.Contains(listed.Body.String(), "candidate_handle") || strings.Contains(listed.Body.String(), "salary_fit") ||
|
||||
strings.Contains(listed.Body.String(), `"need"`) {
|
||||
t.Fatalf("candidate inbox shows organization-only fields: %s", listed.Body.String())
|
||||
}
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("inbox lists %d invitations, want the one delivered", len(page.Items))
|
||||
}
|
||||
item := page.Items[0]
|
||||
if item.ID != draft.ID || item.State != "delivered" || item.Organization.ID != orgA || item.Organization.Name != nameA ||
|
||||
item.Version != sent.Version || item.RoleTitle == "" || len(item.WorkFormats) != 1 || item.ViewedAt != nil ||
|
||||
!item.DeliveredAt.Equal(deliveredAt) || !item.ResponseDeadlineAt.Equal(deadline) {
|
||||
t.Fatalf("inbox entry = %+v, want the delivered invitation of organization A", item)
|
||||
}
|
||||
var deliveries int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM deliveries WHERE recipient_user_id = $1`, target.ID).Scan(&deliveries); err != nil || deliveries != 0 {
|
||||
t.Fatalf("deliveries for the candidate = %d, %v; want none before the email job ran", deliveries, err)
|
||||
}
|
||||
counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID)
|
||||
if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) {
|
||||
t.Fatalf("send stored %+v, want one invitation, delivery event, outbox event, charge, and email request", counts)
|
||||
}
|
||||
var state string
|
||||
var storedDelivered, storedDeadline time.Time
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT state, delivered_at, response_deadline_at FROM invitations WHERE id = $1`, draft.ID).
|
||||
Scan(&state, &storedDelivered, &storedDeadline); err != nil || state != "delivered" ||
|
||||
!storedDelivered.Truncate(time.Second).Equal(deliveredAt) || !storedDeadline.Truncate(time.Second).Equal(deadline) ||
|
||||
!storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) {
|
||||
t.Fatalf("stored invitation = %s %s %s, %v", state, storedDelivered, storedDeadline, err)
|
||||
}
|
||||
|
||||
// Another candidate and an employer see nothing of it.
|
||||
if _, others := inbox(sessionOther, ""); len(others.Items) != 0 {
|
||||
t.Fatalf("another candidate lists %d invitations", len(others.Items))
|
||||
}
|
||||
requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", sessionA, ""), http.StatusForbidden, "forbidden")
|
||||
requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated")
|
||||
if response, _ := inbox(sessionTarget, "?limit=0"); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("inbox with limit 0 = %d, want 400", response.Code)
|
||||
}
|
||||
|
||||
// The in-platform notification arrives through the outbox, and its
|
||||
// content names the sender and the role, never the candidate.
|
||||
event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID)
|
||||
if !strings.Contains(string(event.Payload), target.ID.String()) || event.AggregateVersion != sent.Version {
|
||||
t.Fatalf("outbox event = %+v, want the recipient and the delivered version", event)
|
||||
}
|
||||
if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) {
|
||||
t.Fatal("the inbox consumer did not apply the event")
|
||||
}
|
||||
notifications := decodeNotificationPage(t, request(http.MethodGet, "/api/v1/me/notifications", "", sessionTarget, ""))
|
||||
if len(notifications.Items) != 1 || notifications.Items[0].Kind != "invitation_delivered" || notifications.Items[0].Content == nil ||
|
||||
!strings.Contains(notifications.Items[0].Content.Summary, nameA) || notifications.Items[0].Content.LinkPath == nil ||
|
||||
*notifications.Items[0].Content.LinkPath != "/candidate/invitations" {
|
||||
t.Fatalf("candidate notifications = %+v, want the invitation notice", notifications.Items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a repeated send stores one invitation, inbox entry, outbox event, and charge", func(t *testing.T) {
|
||||
draft := draftFor(orgA, sessionA, other, nil)
|
||||
key := nextKey()
|
||||
responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), origin, sessionA, key, 2)
|
||||
if responses[0].Code != http.StatusOK || responses[1].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() {
|
||||
t.Fatalf("concurrent sends with one key = %d %s and %d %s, want one identical 200",
|
||||
responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String())
|
||||
}
|
||||
original := responses[0].Body.String()
|
||||
sent := decodeInvitationHTTP(t, responses[0], http.StatusOK)
|
||||
harness.clock.Advance(time.Hour)
|
||||
if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key); replay.Code != http.StatusOK || replay.Body.String() != original {
|
||||
t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String())
|
||||
}
|
||||
// A new key with the version of the draft answers with the invitation
|
||||
// as it is now, without a version conflict or a second charge.
|
||||
again := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK)
|
||||
if again.State != "delivered" || again.Version != sent.Version || *again.DeliveredAt != *sent.DeliveredAt || *again.ResponseDeadlineAt != *sent.ResponseDeadlineAt {
|
||||
t.Fatalf("send with a new key = %s %d %s %s, want %s %d %s %s", again.State, again.Version, *again.DeliveredAt, *again.ResponseDeadlineAt,
|
||||
sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt)
|
||||
}
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version+1), sessionA, key),
|
||||
http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
|
||||
counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID)
|
||||
if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) {
|
||||
t.Fatalf("repeated sends stored %+v, want exactly one of each", counts)
|
||||
}
|
||||
if _, page := inbox(sessionOther, ""); len(page.Items) != 1 || page.Items[0].ID != draft.ID {
|
||||
t.Fatalf("candidate inbox = %+v, want exactly one entry", page.Items)
|
||||
}
|
||||
// The outbox event reaches the inbox once, however often it is
|
||||
// delivered.
|
||||
event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID)
|
||||
deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event)
|
||||
deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event)
|
||||
deliverToInbox(ctx, t, consumers, inboxRenamedConsumer, event)
|
||||
var rows int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE source_id = $1`, draft.ID).Scan(&rows); err != nil || rows != 1 {
|
||||
t.Fatalf("notification rows for the invitation = %d, %v; want 1", rows, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fixes the deadline at the delivery while the mail is stopped and its job is retried", func(t *testing.T) {
|
||||
candidate := cohort[2]
|
||||
draft := draftFor(orgA, sessionA, candidate, func(body, terms map[string]any) { body["response_period_days"] = 3 })
|
||||
sendKey := nextKey()
|
||||
response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey)
|
||||
sent := decodeInvitationHTTP(t, response, http.StatusOK)
|
||||
deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt)
|
||||
if sent.ResponsePeriodDays != 3 || !deadline.Equal(deliveredAt.Add(3*24*time.Hour)) {
|
||||
t.Fatalf("sent = %d days, deadline %s; want 3 days after %s", sent.ResponsePeriodDays, deadline, deliveredAt)
|
||||
}
|
||||
|
||||
// The mail transport is stopped: deliveries are pinned to the
|
||||
// disabled provider and nothing is sent. The email job fails once,
|
||||
// is retried later, and is delivered again by the bus.
|
||||
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer() error = %v", err)
|
||||
}
|
||||
stopped, err := domain.NewMailProviderAccount("disabled", "default")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
||||
}
|
||||
mailJob := notification.NewDeliveryHandler(notification.NewTemplateRenderer(templates), stopped, harness.clock.Now, slog.New(slog.DiscardHandler))
|
||||
event := outboxEnvelope(ctx, t, harness,
|
||||
`event_type = 'notification.mail_requested' AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidate.ID)
|
||||
failure := errors.New("the mail job failed")
|
||||
harness.clock.Advance(2 * time.Hour)
|
||||
if _, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := mailJob.Handle(ctx, unit, event); err != nil {
|
||||
return err
|
||||
}
|
||||
return failure
|
||||
}); !errors.Is(err, failure) {
|
||||
t.Fatalf("failed mail job error = %v, want the injected failure", err)
|
||||
}
|
||||
harness.clock.Advance(time.Hour)
|
||||
for attempt, want := range []bool{true, false} {
|
||||
applied, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return mailJob.Handle(ctx, unit, event)
|
||||
})
|
||||
if err != nil || applied != want {
|
||||
t.Fatalf("mail job attempt %d = %v, %v; want applied %v", attempt, applied, err, want)
|
||||
}
|
||||
}
|
||||
var status, provider, subject, textBody, htmlBody string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT status, provider, subject, text_body, html_body FROM deliveries WHERE recipient_user_id = $1`, candidate.ID).
|
||||
Scan(&status, &provider, &subject, &textBody, &htmlBody); err != nil {
|
||||
t.Fatalf("read the email delivery: %v", err)
|
||||
}
|
||||
if status != "pending" || provider != "disabled" {
|
||||
t.Fatalf("email delivery = %s via %s, want a pending delivery of the stopped transport", status, provider)
|
||||
}
|
||||
requireNoCandidateData("email", subject+"\n"+textBody+"\n"+htmlBody)
|
||||
if !strings.Contains(textBody, "/candidate/invitations") {
|
||||
t.Fatalf("email text has no link to the inbox: %s", textBody)
|
||||
}
|
||||
|
||||
// The business answer stays a success, and the deadline is still the
|
||||
// one fixed at the delivery.
|
||||
if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey); replay.Code != http.StatusOK || replay.Body.String() != response.Body.String() {
|
||||
t.Fatalf("replay after the mail job = %d %s, want the original 200", replay.Code, replay.Body.String())
|
||||
}
|
||||
read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK)
|
||||
if read.State != "delivered" || *read.DeliveredAt != *sent.DeliveredAt || *read.ResponseDeadlineAt != *sent.ResponseDeadlineAt || read.Version != sent.Version {
|
||||
t.Fatalf("invitation after the mail job = %s %d %s %s, want %s %d %s %s", read.State, read.Version, *read.DeliveredAt, *read.ResponseDeadlineAt,
|
||||
sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt)
|
||||
}
|
||||
// The database refuses to move a delivery or a deadline.
|
||||
_, err = harness.pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = response_deadline_at + interval '1 day', version = version + 1 WHERE id = $1`, draft.ID)
|
||||
assertPgError(t, "move the deadline", err, privacyIntegrityViolation, "invitations_history_immutable")
|
||||
})
|
||||
|
||||
t.Run("rechecks the visibility of the candidate and stores the refusal", func(t *testing.T) {
|
||||
candidate := cohort[3]
|
||||
draft := draftFor(orgA, sessionA, candidate, nil)
|
||||
privacy.hide(t, candidate.ID, orgA, now)
|
||||
key := nextKey()
|
||||
refused := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key)
|
||||
requireSessionProblem(t, refused, http.StatusConflict, "state_conflict")
|
||||
requireNoCandidateData("refusal", refused.Body.String())
|
||||
counts := readInvitationSendCounts(ctx, t, harness, draft.ID, candidate.ID)
|
||||
if counts != (invitationSendCounts{invitations: 1, events: 1}) {
|
||||
t.Fatalf("a refused send stored %+v, want only the draft", counts)
|
||||
}
|
||||
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("lift the hiding: %v", err)
|
||||
}
|
||||
// The refusal is stored under its key; a new key sends the draft once
|
||||
// the candidate is visible again.
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusConflict, "state_conflict")
|
||||
if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK); sent.State != "delivered" {
|
||||
t.Fatalf("send after the hiding was lifted = %+v", sent)
|
||||
}
|
||||
|
||||
// A revoked publication answers the same way.
|
||||
revokedCandidate := cohort[4]
|
||||
revokedDraft := draftFor(orgA, sessionA, revokedCandidate, nil)
|
||||
privacy.revokeC2(t, revokedCandidate.ID, now.Add(time.Minute))
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, revokedDraft.ID), sendBody(revokedDraft.Version), sessionA, nextKey()), http.StatusConflict, "state_conflict")
|
||||
if counts := readInvitationSendCounts(ctx, t, harness, revokedDraft.ID, revokedCandidate.ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 {
|
||||
t.Fatalf("a send to a revoked publication stored %+v", counts)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("refuses a stale version without storing it and stores an unknown invitation", func(t *testing.T) {
|
||||
draft := draftFor(orgA, sessionA, target, nil)
|
||||
updated := decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, draft.ID), `{"expected_version":1,"response_period_days":14}`, sessionA, ""), http.StatusOK)
|
||||
key := nextKey()
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusPreconditionFailed, "version_conflict")
|
||||
if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID); counts.deliveredEvents != 0 || counts.charges != 0 {
|
||||
t.Fatalf("a stale send stored %+v", counts)
|
||||
}
|
||||
// Nothing was kept under the key, so the corrected request with the
|
||||
// same key sends the terms that were read.
|
||||
sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(updated.Version), sessionA, key), http.StatusOK)
|
||||
if sent.ResponsePeriodDays != 14 || sent.State != "delivered" {
|
||||
t.Fatalf("send of the read version = %+v", sent)
|
||||
}
|
||||
|
||||
unknownKey, unknownID := nextKey(), uuid.New()
|
||||
for range 2 {
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, unknownID), sendBody(1), sessionA, unknownKey), http.StatusNotFound, "not_found")
|
||||
}
|
||||
foreign := draftFor(orgB, sessionB, target, nil)
|
||||
requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, foreign.ID), sendBody(foreign.Version), sessionA, nextKey()), http.StatusNotFound, "not_found")
|
||||
if counts := readInvitationSendCounts(ctx, t, harness, foreign.ID, target.ID); counts.deliveredEvents != 0 {
|
||||
t.Fatalf("a send through another organization delivered %+v", counts)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("only the active owner sends, with the CSRF token and a key", func(t *testing.T) {
|
||||
draft := draftFor(orgA, sessionA, other, nil)
|
||||
path, body := sendPath(orgA, draft.ID), sendBody(draft.Version)
|
||||
requireSessionProblem(t, request(http.MethodPost, path, body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden")
|
||||
requireSessionProblem(t, request(http.MethodPost, path, body, sessionTarget, nextKey()), http.StatusForbidden, "forbidden")
|
||||
requireSessionProblem(t, request(http.MethodPost, path, body, sessionB, nextKey()), http.StatusNotFound, "not_found")
|
||||
requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{cookie: sessionA.cookie}, nextKey()), http.StatusForbidden, "csrf_check_failed")
|
||||
requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, body, "https://attacker.example", sessionA, nextKey()),
|
||||
http.StatusForbidden, "csrf_check_failed")
|
||||
requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated")
|
||||
requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, ""), "/Idempotency-Key", "")
|
||||
requireInvitationValidation(t, request(http.MethodPost, path, `{"expected_version":1,"state":"delivered"}`, sessionA, nextKey()), "", "")
|
||||
if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID); counts.deliveredEvents != 0 || counts.charges != 0 {
|
||||
t.Fatalf("refused callers delivered %+v", counts)
|
||||
}
|
||||
current := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK)
|
||||
if current.State != "draft" {
|
||||
t.Fatalf("a refused caller changed the draft: %+v", current)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("lists the candidate's inbox newest first with a bound cursor", func(t *testing.T) {
|
||||
var total int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE candidate_id = $1 AND delivered_at IS NOT NULL`, target.ID).Scan(&total); err != nil {
|
||||
t.Fatalf("count delivered invitations: %v", err)
|
||||
}
|
||||
if total < 2 {
|
||||
t.Fatalf("the candidate has %d delivered invitations, want at least 2 to page", total)
|
||||
}
|
||||
seen := map[uuid.UUID]bool{}
|
||||
var previous time.Time
|
||||
query := "?limit=1"
|
||||
for {
|
||||
response, page := inbox(sessionTarget, query)
|
||||
if response.Code != http.StatusOK || len(page.Items) != 1 {
|
||||
t.Fatalf("inbox page = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
item := page.Items[0]
|
||||
if seen[item.ID] || (!previous.IsZero() && item.DeliveredAt.After(previous)) {
|
||||
t.Fatalf("inbox entry %+v is repeated or out of order", item)
|
||||
}
|
||||
seen[item.ID], previous = true, item.DeliveredAt
|
||||
if !page.Page.HasMore {
|
||||
break
|
||||
}
|
||||
query = "?limit=1&cursor=" + *page.Page.NextCursor
|
||||
}
|
||||
if len(seen) != total {
|
||||
t.Fatalf("pages listed %d invitations, want %d", len(seen), total)
|
||||
}
|
||||
_, first := inbox(sessionTarget, "?limit=1")
|
||||
if response, _ := inbox(sessionOther, "?cursor="+*first.Page.NextCursor); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("a cursor of another candidate = %d, want 400", response.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("charges the weekly organization quota once per invitation", func(t *testing.T) {
|
||||
var used int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&used); err != nil {
|
||||
t.Fatalf("count the charges of organization B: %v", err)
|
||||
}
|
||||
for range invitationSendE0Quota - used {
|
||||
draft := draftFor(orgB, sessionB, cohort[5], nil)
|
||||
decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, draft.ID), sendBody(draft.Version), sessionB, nextKey()), http.StatusOK)
|
||||
}
|
||||
over := draftFor(orgB, sessionB, cohort[5], nil)
|
||||
key := nextKey()
|
||||
for range 2 {
|
||||
limited := request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), sessionB, key)
|
||||
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
|
||||
if limited.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("the quota refusal has no Retry-After")
|
||||
}
|
||||
}
|
||||
if counts := readInvitationSendCounts(ctx, t, harness, over.ID, cohort[5].ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 {
|
||||
t.Fatalf("a send over the quota stored %+v", counts)
|
||||
}
|
||||
var charges int
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&charges); err != nil || charges != invitationSendE0Quota {
|
||||
t.Fatalf("charges of organization B = %d, %v; want the quota of %d", charges, err, invitationSendE0Quota)
|
||||
}
|
||||
// The quota of another organization is its own.
|
||||
draft := draftFor(orgA, sessionA, cohort[5], nil)
|
||||
decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK)
|
||||
// A week later the oldest charges expire, and the same key sends: the
|
||||
// refusal was not stored under it. The sessions of the week before
|
||||
// have expired, so the owner signs in again.
|
||||
harness.clock.Advance(8 * 24 * time.Hour)
|
||||
laterB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address())
|
||||
if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), laterB, key), http.StatusOK); sent.State != "delivered" {
|
||||
t.Fatalf("send after the window = %+v", sent)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keeps every candidate value out of logs and stored outcomes", func(t *testing.T) {
|
||||
requireNoCandidateData("server log", harness.logs.String())
|
||||
var stored string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(snapshot::text, ' '), '') FROM invitation_send_results`).Scan(&stored); err != nil {
|
||||
t.Fatalf("read stored outcomes: %v", err)
|
||||
}
|
||||
requireNoCandidateData("stored send outcomes", stored)
|
||||
var mail string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(subject || ' ' || body, ' '), '') FROM mail_requests`).Scan(&mail); err != nil {
|
||||
t.Fatalf("read mail requests: %v", err)
|
||||
}
|
||||
requireNoCandidateData("mail requests", mail)
|
||||
})
|
||||
}
|
||||
|
||||
func mustParseTimestamp(t *testing.T, value string) time.Time {
|
||||
t.Helper()
|
||||
parsed, err := time.Parse(time.RFC3339Nano, value)
|
||||
if err != nil {
|
||||
t.Fatalf("parse timestamp %q: %v", value, err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage(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, invitationSendMigrationVersion)
|
||||
|
||||
// Quota usage names a stored invitation of the same organization.
|
||||
_, err := pool.Exec(ctx, `INSERT INTO company_invitation_quota_usage (organization_id, invitation_id, reserved_at, policy_version_id,
|
||||
verification_level, verification_basis, verification_changed_at, quota_tier)
|
||||
SELECT $1, $2, now(), $3, verification_level, verification_basis, verification_changed_at, verification_level
|
||||
FROM organizations WHERE id = $1`, fixture.organization.ID(), uuid.New(), fixture.policyID.UUID())
|
||||
assertPgError(t, "charge without an invitation", err, privacyForeignKeyViolation, "company_invitation_quota_usage_invitation_fkey")
|
||||
|
||||
draft := fixture.draft(t)
|
||||
delivered, err := draft.Deliver(fixture.now.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)
|
||||
}
|
||||
// A second delivery of the same draft version loses the race.
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event)
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrInvitationVersionConflict) {
|
||||
t.Fatalf("second Deliver() error = %v, want ErrInvitationVersionConflict", err)
|
||||
}
|
||||
|
||||
_, err = migrator.DownOne(ctx)
|
||||
assertPgError(t, "DownOne() with a delivered invitation", err, privacyIntegrityViolation, invitationDeliveriesRetained)
|
||||
if _, err := pool.Exec(ctx, `TRUNCATE invitation_send_results, company_invitation_quota_usage, invitation_creation_results,
|
||||
invitation_events, invitation_terms_versions, invitations`); err != nil {
|
||||
t.Fatalf("clear the invitation tables: %v", err)
|
||||
}
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if err != nil || result.Version != invitationSendMigrationVersion {
|
||||
t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationSendMigrationVersion)
|
||||
}
|
||||
var remaining int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name = 'invitation_send_results'`).Scan(&remaining); err != nil || remaining != 0 {
|
||||
t.Fatalf("send outcomes left after the rollback: %d, %v", remaining, err)
|
||||
}
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("Up() after the rollback error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,8 @@ var (
|
||||
// users and organizations. Creation snapshots reference idempotency records.
|
||||
organizationTables = []pgx.Identifier{
|
||||
{"candidate_card_access_events"},
|
||||
{"invitation_creation_results"}, {"invitation_events"}, {"invitation_terms_versions"}, {"invitations"},
|
||||
{"invitation_creation_results"}, {"invitation_send_results"},
|
||||
{"invitation_events"}, {"invitation_terms_versions"}, {"invitations"},
|
||||
{"organization_need_versions"}, {"organization_needs"},
|
||||
{"organization_need_creation_results"},
|
||||
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
|
||||
|
||||
Reference in new issue
Block a user