Files
lincodex/backend/integration_test/invitation_answer_http_test.go
T

646 lines
36 KiB
Go
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"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/policy"
)
const (
// invitationAnswerMigrationVersion adds the view and the decline: their
// audit events, the stored decline, and the stored decline outcomes.
invitationAnswerMigrationVersion = 39
invitationAnswersRetained = "invitation_answers_retained"
// invitationDeclineComment is the candidate's private comment. It is
// read back by the candidate only.
invitationDeclineComment = "Private decline comment of the candidate"
)
// candidateInvitationHTTPBody is the invitation as the candidate reads it.
type candidateInvitationHTTPBody struct {
ID uuid.UUID `json:"id"`
Organization struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
} `json:"organization"`
State string `json:"state"`
ExpiryReason *string `json:"expiry_reason"`
Version int64 `json:"version"`
TermsVersion int64 `json:"terms_version"`
Terms json.RawMessage `json:"terms"`
ResponseDeadlineAt string `json:"response_deadline_at"`
DeliveredAt string `json:"delivered_at"`
ViewedAt *string `json:"viewed_at"`
RespondedAt *string `json:"responded_at"`
UpdatedAt string `json:"updated_at"`
ContactConsent json.RawMessage `json:"contact_consent"`
Decline *struct {
Reason string `json:"reason"`
Comment *string `json:"comment"`
DeclinedAt string `json:"declined_at"`
} `json:"decline"`
ContactGrant json.RawMessage `json:"contact_grant"`
}
func decodeCandidateInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) candidateInvitationHTTPBody {
t.Helper()
if response.Code != wantStatus {
t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), wantStatus)
}
if response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
}
var body candidateInvitationHTTPBody
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode candidate invitation %s: %v", response.Body.String(), err)
}
return body
}
// invitationAnswerCounts are the rows that a view or a decline may write for
// one invitation, and the C4 consents of its candidate, which neither may
// create.
type invitationAnswerCounts struct {
viewedEvents, declinedEvents, declines, c4Consents int
}
func readInvitationAnswerCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAnswerCounts {
t.Helper()
var counts invitationAnswerCounts
if err := harness.pool.QueryRow(ctx, `
SELECT
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'viewed'),
(SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'declined'),
(SELECT count(*) FROM invitation_declines WHERE invitation_id = $1),
(SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4')`,
invitationID, candidateID).Scan(&counts.viewedEvents, &counts.declinedEvents, &counts.declines, &counts.c4Consents); err != nil {
t.Fatalf("count the rows of an answer: %v", err)
}
return counts
}
func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolated := *env
isolated.Config.DatabaseURL = databaseURL
setupPool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
harness := newInvitationHTTPHarness(ctx, t, &isolated)
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second))
origin := env.Config.AppPublicURL
now := harness.clock.Now()
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
account := func(email string, scenario domain.Scenario) domain.User {
return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now)
}
ownerA, ownerB := account("answer-owner-a@example.test", domain.ScenarioEmployer), account("answer-owner-b@example.test", domain.ScenarioEmployer)
sessionA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address())
sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address())
orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "answer-company-a")
orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "answer-company-b")
var nameA string
if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil {
t.Fatalf("read organization name: %v", err)
}
identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
privacy := candidatePrivacyFixture{
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture,
organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now},
ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
}
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now}
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)
}
}
// Seven published candidates form the visible cohort. The first three
// can sign in.
target := account("answer-target@example.test", domain.ScenarioCandidate)
other := account("answer-other@example.test", domain.ScenarioCandidate)
hider := account("answer-hider@example.test", domain.ScenarioCandidate)
cohort := []domain.User{target, other, hider}
for index := range 4 {
candidate := privacy.candidate(t, fmt.Sprintf("answer-visible-%d@example.test", index))
verifyPrivacyCohortCandidate(t, privacy, candidate)
cohort = append(cohort, candidate)
}
for _, candidate := range cohort {
publishCandidate(candidate)
}
login := func(candidate domain.User) organizationHTTPSession {
return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address())
}
sessionTarget, sessionOther, sessionHider := login(target), login(other), login(hider)
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-answer-key-%d", keySequence)
}
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
}
organizationPath := func(organizationID, invitationID uuid.UUID) string {
return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID)
}
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)
}
deliver := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody {
t.Helper()
draft := draftFor(organizationID, session, candidate, change)
response := request(http.MethodPost, organizationPath(organizationID, draft.ID)+"/send", fmt.Sprintf(`{"expected_version":%d}`, draft.Version), session, nextKey())
return decodeInvitationHTTP(t, response, http.StatusOK)
}
myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() }
declineBody := func(version int64, reason string, comment *string) string {
body := map[string]any{"expected_version": version, "reason": reason}
if comment != nil {
body["comment"] = *comment
}
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal decline: %v", err)
}
return string(encoded)
}
decline := func(session organizationHTTPSession, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder {
return request(http.MethodPost, myPath(invitationID)+"/decline", body, session, key)
}
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", "candidate_handle", "salary_fit", "email", "phone", "telegram", "full_name", "salary_minimum"} {
if strings.Contains(text, `"`+field+`":`) {
t.Errorf("%s contains the key %q: %s", label, field, text)
}
}
}
requireNoDeclineDetails := func(label, text string) {
t.Helper()
for _, private := range []string{invitationDeclineComment, `"decline"`, `"reason"`, `"comment"`} {
if strings.Contains(text, private) {
t.Errorf("%s discloses the decline detail %s: %s", label, private, text)
}
}
}
t.Run("opening the terms records the view and keeps the deadline", func(t *testing.T) {
sent := deliver(orgA, sessionA, target, nil)
read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "")
opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK)
requireNoCandidateData("candidate read", read.Body.String())
if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA ||
opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil ||
string(opened.ContactConsent) != "null" || string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 {
t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened)
}
// A read records nothing: it is free of side effects by contract.
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts.viewedEvents != 0 {
t.Fatalf("a read stored %+v", counts)
}
harness.clock.Advance(time.Hour)
response := request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, "")
viewed := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
requireNoCandidateData("view response", response.Body.String())
if viewed.State != "viewed" || viewed.Version != sent.Version+1 || viewed.TermsVersion != sent.TermsVersion || viewed.ViewedAt == nil ||
viewed.ResponseDeadlineAt != opened.ResponseDeadlineAt || viewed.DeliveredAt != opened.DeliveredAt {
t.Fatalf("viewed = %+v, want viewed with the same deadline %s", viewed, opened.ResponseDeadlineAt)
}
var storedDeadline, storedDelivered time.Time
if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at, delivered_at FROM invitations WHERE id = $1`, sent.ID).
Scan(&storedDeadline, &storedDelivered); err != nil || !storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) {
t.Fatalf("stored deadline = %s after %s, %v; want seven days after the delivery", storedDeadline, storedDelivered, err)
}
// Repeats, concurrent ones included, change nothing and record one
// event.
harness.clock.Advance(time.Hour)
for _, repeat := range parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/view", "", origin, sessionTarget, "", 3) {
again := decodeCandidateInvitationHTTP(t, repeat, http.StatusOK)
if again.Version != viewed.Version || *again.ViewedAt != *viewed.ViewedAt {
t.Fatalf("repeated view = %+v, want the first view", again)
}
}
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1}) {
t.Fatalf("views stored %+v, want one view event", counts)
}
// The organization sees the state and the time of the view only.
organization := decodeInvitationHTTP(t, request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, ""), http.StatusOK)
if organization.State != "viewed" || organization.ViewedAt == nil || *organization.ViewedAt != *viewed.ViewedAt ||
organization.ResponseDeadlineAt == nil || *organization.ResponseDeadlineAt != viewed.ResponseDeadlineAt {
t.Fatalf("organization reads %+v, want the view and the same deadline", organization)
}
// The inbox shows the view as well.
listed := request(http.MethodGet, "/api/v1/me/invitations", "", sessionTarget, "")
if listed.Code != http.StatusOK || !strings.Contains(listed.Body.String(), `"state":"viewed"`) {
t.Fatalf("inbox = %d %s, want the viewed invitation", listed.Code, listed.Body.String())
}
})
t.Run("a decline with the reason other and no comment is an answer without a grant", func(t *testing.T) {
sent := deliver(orgA, sessionA, other, nil)
harness.clock.Advance(time.Minute)
key := nextKey()
response := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key)
declined := decodeCandidateInvitationHTTP(t, response, http.StatusOK)
requireNoCandidateData("decline response", response.Body.String())
if declined.State != "declined" || declined.Version != sent.Version+1 || declined.RespondedAt == nil || declined.Decline == nil ||
declined.Decline.Reason != "other" || declined.Decline.Comment != nil || declined.Decline.DeclinedAt != *declined.RespondedAt ||
string(declined.ContactConsent) != "null" || string(declined.ContactGrant) != "null" ||
declined.ResponseDeadlineAt != *sent.ResponseDeadlineAt {
t.Fatalf("declined = %+v, want declined with the reason other, no comment, and no grant", declined)
}
counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID)
if counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) {
t.Fatalf("decline stored %+v, want one decline event, one decline, and no C4 consent", counts)
}
// The stored answer event is the response that the responsiveness
// metrics count: in time, by the candidate, without a reason.
var actor uuid.UUID
var occurred, deadline time.Time
var fields int
if err := harness.pool.QueryRow(ctx, `
SELECT event.actor_id, event.occurred_at, invitation.response_deadline_at, cardinality(event.changed_fields)
FROM invitation_events AS event JOIN invitations AS invitation ON invitation.id = event.invitation_id
WHERE event.invitation_id = $1 AND event.kind = 'declined'`, sent.ID).Scan(&actor, &occurred, &deadline, &fields); err != nil {
t.Fatalf("read the decline event: %v", err)
}
if actor != other.ID || !occurred.Before(deadline) || fields != 0 {
t.Fatalf("decline event by the candidate %v at %s before %s with %d fields", actor == other.ID, occurred, deadline, fields)
}
// Repeats: the same key replays the original, and the same decline
// with a new key and the older version answers 200 without a second
// event. Another reason or a reused key with another body does not.
original := response.Body.String()
harness.clock.Advance(time.Hour)
if replay := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key); replay.Code != http.StatusOK || replay.Body.String() != original {
t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String())
}
if again := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), nextKey()); again.Code != http.StatusOK || again.Body.String() != original {
t.Fatalf("the same decline with a new key = %d %s, want the original answer", again.Code, again.Body.String())
}
requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(declined.Version, "salary", nil), nextKey()), http.StatusConflict, "state_conflict")
requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version, "stack", nil), key), http.StatusUnprocessableEntity, "idempotency_key_reused")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) {
t.Fatalf("repeats stored %+v, want the first decline only", counts)
}
// A view of a declined invitation changes nothing.
if viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionOther, ""), http.StatusOK); viewed.State != "declined" || viewed.Version != declined.Version {
t.Fatalf("view of a declined invitation = %+v", viewed)
}
// The organization sees the state and the time of the answer only.
organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "")
organization := decodeInvitationHTTP(t, organizationRead, http.StatusOK)
requireNoDeclineDetails("organization read", organizationRead.Body.String())
listed := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), "", sessionA, "")
requireNoDeclineDetails("organization list", listed.Body.String())
if organization.State != "declined" || organization.RespondedAt == nil || *organization.RespondedAt != *declined.RespondedAt ||
organization.ContactAccess.Status != "not_granted" {
t.Fatalf("organization reads %+v, want declined with the time of the answer and no access", organization)
}
})
t.Run("a decline from viewed keeps the comment for the candidate only", func(t *testing.T) {
sent := deliver(orgA, sessionA, target, nil)
viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, ""), http.StatusOK)
comment := invitationDeclineComment
key := nextKey()
// Concurrent requests with one key answer once.
responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline",
declineBody(viewed.Version, "salary", &comment), origin, sessionTarget, key, 2)
if responses[0].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() {
t.Fatalf("concurrent declines = %d %s and %d %s, want one identical 200",
responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String())
}
declined := decodeCandidateInvitationHTTP(t, responses[0], http.StatusOK)
if declined.State != "declined" || declined.Decline == nil || declined.Decline.Reason != "salary" ||
declined.Decline.Comment == nil || *declined.Decline.Comment != comment {
t.Fatalf("declined = %+v, want the reason and the comment read back", declined)
}
reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionTarget, ""), http.StatusOK)
if reread.Decline == nil || reread.Decline.Comment == nil || *reread.Decline.Comment != comment || reread.Version != declined.Version {
t.Fatalf("reread = %+v, want the stored decline", reread)
}
organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "")
requireNoDeclineDetails("organization read", organizationRead.Body.String())
var events string
if err := harness.pool.QueryRow(ctx, `SELECT string_agg(row_to_json(invitation_events)::text, ' ') FROM invitation_events WHERE invitation_id = $1`, sent.ID).Scan(&events); err != nil {
t.Fatalf("read the audit events: %v", err)
}
if strings.Contains(events, comment) || strings.Contains(events, "salary") {
t.Fatalf("audit events hold the decline details: %s", events)
}
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)
tooLong := strings.Repeat("я", 501)
for name, body := range map[string]string{
"white space": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":" "}`,
"unicode spaces": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"  "}`,
"NUL": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"a\u0000b"}`,
"too long": declineBody(fresh.Version, "other", &tooLong),
} {
response := decline(sessionTarget, fresh.ID, body, nextKey())
if response.Code != http.StatusBadRequest {
t.Errorf("%s: decline = %d %s, want 400", name, response.Code, response.Body.String())
}
}
requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"rude"}`, nextKey()), "/reason", "")
requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"other","state":"declined"}`, nextKey()), "", "")
requireInvitationValidation(t, decline(sessionTarget, fresh.ID, declineBody(fresh.Version, "other", nil), ""), "/Idempotency-Key", "")
if counts := readInvitationAnswerCounts(ctx, t, harness, fresh.ID, target.ID); counts.declines != 0 {
t.Fatalf("an invalid decline stored %+v", counts)
}
})
t.Run("another candidate and an employer learn nothing of the invitation", func(t *testing.T) {
sent := deliver(orgA, sessionA, target, 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{
request(http.MethodGet, myPath(invitationID), "", sessionOther, ""),
request(http.MethodPost, myPath(invitationID)+"/view", "", sessionOther, ""),
decline(sessionOther, invitationID, declineBody(sent.Version, "other", nil), nextKey()),
} {
requireSessionProblem(t, response, http.StatusNotFound, "not_found")
if strings.Contains(response.Body.String(), "role_title") || strings.Contains(response.Body.String(), nameA) {
t.Errorf("%s invitation: the refusal shows the terms: %s", name, response.Body.String())
}
}
}
// A draft is not in the candidate's inbox, even for its candidate.
requireSessionProblem(t, request(http.MethodGet, myPath(draft.ID), "", sessionTarget, ""), http.StatusNotFound, "not_found")
requireSessionProblem(t, request(http.MethodPost, myPath(draft.ID)+"/view", "", sessionTarget, ""), http.StatusNotFound, "not_found")
// The sending organization and another one have no candidate inbox.
for _, session := range []organizationHTTPSession{sessionA, sessionB} {
requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", session, ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", session, ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, decline(session, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "forbidden")
}
// Unsafe commands need the session's CSRF token and the exact Origin.
withoutToken := organizationHTTPSession{cookie: sessionTarget.cookie}
requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", withoutToken, ""), http.StatusForbidden, "csrf_check_failed")
requireSessionProblem(t, decline(withoutToken, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "csrf_check_failed")
requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline",
declineBody(sent.Version, "other", nil), "https://attacker.example", sessionTarget, nextKey()), http.StatusForbidden, "csrf_check_failed")
requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated")
requireInvitationValidation(t, request(http.MethodGet, "/api/v1/me/invitations/1", "", sessionTarget, ""), "/invitation_id", "")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{}) {
t.Fatalf("refused callers stored %+v", counts)
}
// The candidate's own list never names another candidate's invitation.
listed := request(http.MethodGet, "/api/v1/me/invitations?limit=100", "", sessionOther, "")
if listed.Code != http.StatusOK || strings.Contains(listed.Body.String(), sent.ID.String()) || strings.Contains(listed.Body.String(), draft.ID.String()) {
t.Fatalf("another candidate's list = %d %s", listed.Code, listed.Body.String())
}
})
t.Run("the hiding of the organization does not hide it from the candidate", func(t *testing.T) {
sent := deliver(orgB, sessionB, hider, nil)
privacy.hide(t, hider.ID, orgB, harness.clock.Now())
read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionHider, ""), http.StatusOK)
if read.Organization.ID != orgB || read.Organization.Name == "" {
t.Fatalf("read after the hiding = %+v, want the sending organization", read.Organization)
}
declined := decodeCandidateInvitationHTTP(t, decline(sessionHider, sent.ID, declineBody(sent.Version, "company", nil), nextKey()), http.StatusOK)
if declined.State != "declined" {
t.Fatalf("decline after the hiding = %+v", declined)
}
})
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 })
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 {
t.Fatalf("a stale decline stored %+v", counts)
}
var stored int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1`, sent.ID).Scan(&stored); err != nil || stored != 0 {
t.Fatalf("stale outcomes = %d, %v; want none", stored, err)
}
// At the deadline the view changes nothing and the decline is late:
// 409 even with a stale version, stored under its key.
// The response shows whole seconds, so the exact stored deadline is
// read from the database.
var exactDeadline time.Time
if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&exactDeadline); err != nil {
t.Fatalf("read the deadline: %v", err)
}
harness.clock.Set(exactDeadline.UTC())
lateSession := login(other)
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)
}
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(sent.Version, "tasks", nil), key), http.StatusConflict, "state_conflict")
if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.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 {
t.Fatalf("stored late refusals = %d, %v; want one per key", stored, err)
}
})
t.Run("keeps the decline comment and candidate values out of logs", func(t *testing.T) {
requireNoCandidateData("server log", harness.logs.String())
if strings.Contains(harness.logs.String(), invitationDeclineComment) {
t.Fatal("the server log holds the decline comment")
}
})
}
func TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback(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, invitationAnswerMigrationVersion)
store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error {
t.Helper()
return fixture.transactor.WithinTransaction(ctx, work)
}
deliverDraft := func(t *testing.T) domain.Invitation {
t.Helper()
draft := fixture.draft(t)
delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("Deliver() error = %v", err)
}
event, err := delivered.DeliveryEvent(fixture.owner.ID)
if err != nil {
t.Fatalf("DeliveryEvent() error = %v", err)
}
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event)
}); err != nil {
t.Fatalf("Deliver() through the repository error = %v", err)
}
return delivered
}
delivered := deliverDraft(t)
viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("RecordView() error = %v", err)
}
viewEvent, err := viewed.AnswerEvent(fixture.candidate.ID)
if err != nil {
t.Fatalf("AnswerEvent() error = %v", err)
}
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent)
}); err != nil {
t.Fatalf("RecordView() through the repository error = %v", err)
}
// A second view of the same version loses the race.
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent)
}); !errors.Is(err, outbound.ErrInvitationVersionConflict) {
t.Fatalf("second RecordView() error = %v, want ErrInvitationVersionConflict", err)
}
comment := "Synthetic decline comment"
declined, declineRecord, err := viewed.Decline(domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther, Comment: &comment}, viewed.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("Decline() error = %v", err)
}
declineEvent, err := declined.AnswerEvent(fixture.candidate.ID)
if err != nil {
t.Fatalf("AnswerEvent() error = %v", err)
}
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
return unit.Invitations().Decline(ctx, viewed.Version(), declined, declineRecord, declineEvent)
}); err != nil {
t.Fatalf("Decline() through the repository error = %v", err)
}
if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error {
read, err := unit.Invitations().GetDecline(ctx, declined.OrganizationID(), declined.ID())
if err == nil && (!read.Choice.Equal(declineRecord.Choice) || !read.DeclinedAt.Equal(declineRecord.DeclinedAt)) {
return fmt.Errorf("stored decline differs: %v", read.Choice.Reason)
}
return err
}); err != nil {
t.Fatalf("GetDecline() error = %v", err)
}
// The database guards the answers against other writers.
_, err = pool.Exec(ctx, `UPDATE invitations SET viewed_at = viewed_at + interval '1 second', version = version + 1 WHERE id = $1`, declined.ID())
assertPgError(t, "move the view", err, privacyIntegrityViolation, "invitations_answer_immutable")
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', responded_at = NULL, version = version + 1 WHERE id = $1`, declined.ID())
assertPgError(t, "leave the decline", err, privacyIntegrityViolation, "invitations_answer_immutable")
_, err = pool.Exec(ctx, `UPDATE invitation_declines SET reason = 'salary' WHERE invitation_id = $1`, declined.ID())
assertPgError(t, "change the decline", err, privacyIntegrityViolation, "invitation_declines_immutable")
_, err = pool.Exec(ctx, `DELETE FROM invitation_declines WHERE invitation_id = $1`, declined.ID())
assertPgError(t, "delete the decline", err, privacyIntegrityViolation, "invitation_declines_immutable")
other := deliverDraft(t)
_, err = pool.Exec(ctx, `INSERT INTO invitation_declines (invitation_id, organization_id, reason, declined_at) VALUES ($1, $2, 'other', now())`,
other.ID(), other.OrganizationID())
assertPgError(t, "decline row of an undeclined invitation", err, privacyIntegrityViolation, "invitation_declines_match_invitation")
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'declined', responded_at = delivered_at + interval '1 minute', updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID())
assertPgError(t, "decline without its record", err, privacyIntegrityViolation, "invitations_decline_recorded")
_, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', version = version + 1 WHERE id = $1`, other.ID())
assertPgError(t, "viewed without a view", err, privacyCheckViolation, "invitations_answer_matches_state")
_, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at)
SELECT $1, id, organization_id, version + 1, terms_version, 'viewed', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), other.ID())
assertPgError(t, "view event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field")
_, err = migrator.DownOne(ctx)
assertPgError(t, "DownOne() with a declined invitation", err, privacyIntegrityViolation, invitationAnswersRetained)
if _, err := pool.Exec(ctx, `TRUNCATE invitation_decline_results, invitation_declines, 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 != invitationAnswerMigrationVersion {
t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAnswerMigrationVersion)
}
var remaining int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('invitation_declines', 'invitation_decline_results')`).Scan(&remaining); err != nil || remaining != 0 {
t.Fatalf("answer tables left after the rollback: %d, %v", remaining, err)
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}