501 lines
28 KiB
Go
501 lines
28 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
httpadapter "lincodex/backend/internal/adapter/primary/http"
|
|
"lincodex/backend/internal/adapter/primary/http/problem"
|
|
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
|
"lincodex/backend/internal/adapter/secondary/argon2id"
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/adapter/secondary/prometheus"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/usecase/consent"
|
|
"lincodex/backend/internal/usecase/health"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
)
|
|
|
|
const consentHTTPTestTimeout = 5 * time.Minute
|
|
|
|
func TestConsentSettingsOverHTTP(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), consentHTTPTestTimeout)
|
|
defer cancel()
|
|
harness := newConsentHTTPHarness(ctx, t, env)
|
|
truncateTables(ctx, t, harness.pool, usersDependentTables...)
|
|
|
|
now := harness.clock.Now()
|
|
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
|
if err != nil {
|
|
t.Fatalf("HashNewPassword() error = %v", err)
|
|
}
|
|
candidate := createSessionHTTPUser(ctx, t, harness, "consent-candidate@example.test", passwordHash, true)
|
|
createConsentHTTPEmployer(ctx, t, harness, "consent-employer@example.test", passwordHash)
|
|
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness, "consent-candidate@example.test", "192.0.2.50:1234")
|
|
employerCookie, employerCSRF := loginConsentHTTP(t, harness, "consent-employer@example.test", "192.0.2.51:1234")
|
|
store := postgresadapter.NewConsentStore(harness.pool)
|
|
reader := consent.NewQueryService(store, time.Now)
|
|
|
|
guestList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", "", "", "192.0.2.52:1234")
|
|
requireSessionProblem(t, guestList, http.StatusUnauthorized, "unauthenticated")
|
|
guestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", "", "", "", "192.0.2.53:1234")
|
|
requireSessionProblem(t, guestDeletion, http.StatusUnauthorized, "unauthenticated")
|
|
assertRowCount(ctx, t, harness.pool, consentTables[0], 0)
|
|
assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0)
|
|
|
|
publicText := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.54:1234")
|
|
if publicText.Code != http.StatusOK {
|
|
t.Fatalf("public C1 text = %d %s", publicText.Code, publicText.Body.String())
|
|
}
|
|
myC2Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c2", "", "", candidateCookie.Value, "", "192.0.2.55:1234")
|
|
if myC2Text.Code != http.StatusOK || myC2Text.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("current C2 text = %d, Cache-Control=%q, body=%s", myC2Text.Code, myC2Text.Header().Get("Cache-Control"), myC2Text.Body.String())
|
|
}
|
|
var c2Text struct {
|
|
Purpose string `json:"purpose"`
|
|
TextVersion string `json:"text_version"`
|
|
Text string `json:"text"`
|
|
}
|
|
if err := json.Unmarshal(myC2Text.Body.Bytes(), &c2Text); err != nil || c2Text.Purpose != "c2" || c2Text.TextVersion == "" || c2Text.Text == "" {
|
|
t.Fatalf("decode current C2 text = %+v, %v", c2Text, err)
|
|
}
|
|
publicC2 := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c2", "", "", "", "", "192.0.2.56:1234")
|
|
requireSessionProblem(t, publicC2, http.StatusBadRequest, "validation_failed")
|
|
|
|
// A newer publication makes the version already shown to the candidate stale.
|
|
newC2Body := "I consent to publication of my candidate card, consent HTTP test revision."
|
|
newC2Version := "c2-consent-http-revision"
|
|
if _, err := harness.pool.Exec(ctx, `
|
|
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
|
|
VALUES ('c2', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`,
|
|
newC2Version, newC2Body, now.Add(-time.Second)); err != nil {
|
|
t.Fatalf("publish a newer C2 text: %v", err)
|
|
}
|
|
staleGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", c2Text.TextVersion, sessionHTTPTestOrigin)
|
|
requireSessionProblem(t, staleGrant, http.StatusBadRequest, "validation_failed")
|
|
assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0)
|
|
|
|
missingOriginGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, "")
|
|
requireSessionProblem(t, missingOriginGrant, http.StatusForbidden, "csrf_check_failed")
|
|
wrongCSRFGrant := consentGrantHTTP(t, harness, candidateCookie, "wrong-token", "c2", newC2Version, sessionHTTPTestOrigin)
|
|
requireSessionProblem(t, wrongCSRFGrant, http.StatusForbidden, "csrf_check_failed")
|
|
assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0)
|
|
|
|
employerGrant := consentGrantHTTP(t, harness, employerCookie, employerCSRF, "c2", newC2Version, sessionHTTPTestOrigin)
|
|
requireSessionProblem(t, employerGrant, http.StatusForbidden, "forbidden")
|
|
assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0)
|
|
|
|
c2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin)
|
|
if c2Grant.Code != http.StatusOK || c2Grant.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("C2 grant = %d, Cache-Control=%q, body=%s", c2Grant.Code, c2Grant.Header().Get("Cache-Control"), c2Grant.Body.String())
|
|
}
|
|
c2Record, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePublication)
|
|
if err != nil || c2Record.TextVersion() != domain.ConsentTextVersion(newC2Version) {
|
|
t.Fatalf("current C2 record = %s, %v", c2Record, err)
|
|
}
|
|
|
|
privacy := candidatePrivacyFixture{
|
|
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool),
|
|
identity: identityFixture{ctx: ctx, pool: harness.pool, store: postgresadapter.NewIdentityStore(harness.pool), now: now},
|
|
ledger: store, now: now,
|
|
}
|
|
privacy.publish(t, candidate.ID, c2Record.ID(), 0, domain.CardFieldStack)
|
|
var privacyEventsBefore int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsBefore); err != nil {
|
|
t.Fatalf("count candidate privacy events before C2 revoke: %v", err)
|
|
}
|
|
var c2EventsBefore int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsBefore); err != nil {
|
|
t.Fatalf("count C2 revocation events before revoke: %v", err)
|
|
}
|
|
wrongOriginRevoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", "https://attacker.example", candidateCookie.Value, candidateCSRF, "192.0.2.57:1234")
|
|
requireSessionProblem(t, wrongOriginRevoke, http.StatusForbidden, "csrf_check_failed")
|
|
if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationPublished {
|
|
t.Fatalf("bad-Origin revoke changed publication to %s", publication.State())
|
|
}
|
|
current, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication)
|
|
if err != nil || !current {
|
|
t.Fatalf("bad-Origin revoke changed the C2 gate: %v, %v", current, err)
|
|
}
|
|
|
|
revokedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.58:1234")
|
|
if revokedC2.Code != http.StatusNoContent {
|
|
t.Fatalf("C2 revoke = %d %s", revokedC2.Code, revokedC2.Body.String())
|
|
}
|
|
current, err = reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication)
|
|
if err != nil || current {
|
|
t.Fatalf("revoked C2 gate = %v, %v; want fail closed", current, err)
|
|
}
|
|
if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationClosed ||
|
|
publication.ClosedReason() != domain.ClosedConsentRevoked || !publication.Fields().IsEmpty() {
|
|
t.Fatalf("revoked C2 publication = %s/%s, want closed and empty", publication.State(), publication.ClosedReason())
|
|
}
|
|
var storedPublicationState string
|
|
var storedPublicationFields []string
|
|
var storedPublicationConsentID uuid.UUID
|
|
if err := harness.pool.QueryRow(ctx, `
|
|
SELECT state, fields, consent_record_id
|
|
FROM candidate_publications
|
|
WHERE user_id = $1`, candidate.ID).Scan(&storedPublicationState, &storedPublicationFields, &storedPublicationConsentID); err != nil {
|
|
t.Fatalf("read stored publication after C2 revoke: %v", err)
|
|
}
|
|
if storedPublicationState != "published" || len(storedPublicationFields) != 1 || storedPublicationFields[0] != string(domain.CardFieldStack) || storedPublicationConsentID != c2Record.ID() {
|
|
t.Fatalf("revocation rewrote publication source row: state=%s fields=%v consent=%s", storedPublicationState, storedPublicationFields, storedPublicationConsentID)
|
|
}
|
|
var privacyEventsAfter, c2EventsAfter int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfter); err != nil {
|
|
t.Fatalf("count candidate privacy events after C2 revoke: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsAfter); err != nil {
|
|
t.Fatalf("count C2 revocation events after revoke: %v", err)
|
|
}
|
|
if privacyEventsAfter != privacyEventsBefore+1 || c2EventsAfter != c2EventsBefore+1 {
|
|
t.Fatalf("C2 revoke effects changed by privacy=%d and outbox=%d, want one each", privacyEventsAfter-privacyEventsBefore, c2EventsAfter-c2EventsBefore)
|
|
}
|
|
repeatedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.59:1234")
|
|
if repeatedC2.Code != http.StatusNoContent {
|
|
t.Fatalf("repeat C2 revoke = %d %s", repeatedC2.Code, repeatedC2.Body.String())
|
|
}
|
|
var c2EventsRepeated int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsRepeated); err != nil {
|
|
t.Fatalf("count C2 revocation events after repeat: %v", err)
|
|
}
|
|
if c2EventsRepeated != c2EventsAfter {
|
|
t.Fatalf("repeat C2 revoke duplicated an outbox event: %d -> %d", c2EventsAfter, c2EventsRepeated)
|
|
}
|
|
newC2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin)
|
|
revokedPublication := privacy.loadPublication(t, candidate.ID)
|
|
if newC2Grant.Code != http.StatusOK || revokedPublication.State() != domain.PublicationClosed ||
|
|
revokedPublication.ClosedReason() != domain.ClosedConsentRevoked || !revokedPublication.Fields().IsEmpty() {
|
|
t.Fatalf("new C2 grant reopened the old publication: status=%d publication=%s", newC2Grant.Code, privacy.loadPublication(t, candidate.ID).State())
|
|
}
|
|
newerC2Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.74:1234")
|
|
if newerC2Revoke.Code != http.StatusNoContent {
|
|
t.Fatalf("revoke newer C2 record = %d %s", newerC2Revoke.Code, newerC2Revoke.Body.String())
|
|
}
|
|
var privacyEventsAfterNewerRevoke int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfterNewerRevoke); err != nil {
|
|
t.Fatalf("count privacy events after newer C2 revoke: %v", err)
|
|
}
|
|
if privacyEventsAfterNewerRevoke != privacyEventsAfter {
|
|
t.Fatalf("revoking newer C2 record duplicated the old publication event: %d -> %d", privacyEventsAfter, privacyEventsAfterNewerRevoke)
|
|
}
|
|
|
|
// C5 has a real current-consent reader; after revocation future import work denies.
|
|
c5Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c5", "", "", candidateCookie.Value, "", "192.0.2.60:1234")
|
|
var c5Current struct {
|
|
TextVersion string `json:"text_version"`
|
|
}
|
|
if c5Text.Code != http.StatusOK || json.Unmarshal(c5Text.Body.Bytes(), &c5Current) != nil {
|
|
t.Fatalf("read C5 text = %d %s", c5Text.Code, c5Text.Body.String())
|
|
}
|
|
c5Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c5", c5Current.TextVersion, sessionHTTPTestOrigin)
|
|
if c5Grant.Code != http.StatusOK {
|
|
t.Fatalf("C5 grant = %d %s", c5Grant.Code, c5Grant.Body.String())
|
|
}
|
|
if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || !allowed {
|
|
t.Fatalf("current C5 gate = %v, %v; want allow", allowed, err)
|
|
}
|
|
c5Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c5", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.61:1234")
|
|
if c5Revoke.Code != http.StatusNoContent {
|
|
t.Fatalf("C5 revoke = %d %s", c5Revoke.Code, c5Revoke.Body.String())
|
|
}
|
|
if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || allowed {
|
|
t.Fatalf("revoked C5 gate = %v, %v; want deny", allowed, err)
|
|
}
|
|
|
|
// C4 revocation takes its target from the path and its fields from the stored records.
|
|
contactText, err := store.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now)
|
|
if err != nil {
|
|
t.Fatalf("read current C4 text: %v", err)
|
|
}
|
|
organizationA, organizationB := uuid.New(), uuid.New()
|
|
for _, organizationID := range []uuid.UUID{organizationA, organizationB} {
|
|
invitationID := uuid.New()
|
|
fieldSet, err := domain.NewContactFieldSet(domain.ContactFieldPhone, domain.ContactFieldEmail)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{
|
|
SubjectID: candidate.ID, OrganizationID: organizationID, OrganizationName: consentOrganizationName,
|
|
Fields: fieldSet, InvitationID: invitationID, InvitationTermsVersion: 2, Text: contactText, GrantedAt: now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("build C4 grant: %v", err)
|
|
}
|
|
if _, created, err := store.ConsentLedger().GrantContact(ctx, grant); err != nil || !created {
|
|
t.Fatalf("store C4 grant = %v, %v", created, err)
|
|
}
|
|
}
|
|
c4Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+organizationA.String(), "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.62:1234")
|
|
if c4Revoke.Code != http.StatusNoContent {
|
|
t.Fatalf("C4 revoke = %d %s", c4Revoke.Code, c4Revoke.Body.String())
|
|
}
|
|
remainingC4, err := store.ConsentLedger().CurrentContact(ctx, candidate.ID, organizationB)
|
|
if err != nil || len(remainingC4) != 1 || remainingC4[0].State() != domain.ConsentStateActive {
|
|
t.Fatalf("C4 for another organization = %v, %v; want one unchanged active record", remainingC4, err)
|
|
}
|
|
var c4Payload struct {
|
|
OrganizationID string `json:"organization_id"`
|
|
Fields []string `json:"fields"`
|
|
}
|
|
var c4PayloadJSON []byte
|
|
if err := harness.pool.QueryRow(ctx, `
|
|
SELECT payload FROM outbox_events
|
|
WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c4' AND payload->>'subject_id' = $1
|
|
ORDER BY position DESC LIMIT 1`, candidate.ID.String()).Scan(&c4PayloadJSON); err != nil {
|
|
t.Fatalf("read C4 revocation intent: %v", err)
|
|
}
|
|
if err := json.Unmarshal(c4PayloadJSON, &c4Payload); err != nil {
|
|
t.Fatalf("decode C4 revocation intent: %v", err)
|
|
}
|
|
if c4Payload.OrganizationID != organizationA.String() || len(c4Payload.Fields) != 2 ||
|
|
c4Payload.Fields[0] != string(domain.ContactFieldEmail) || c4Payload.Fields[1] != string(domain.ContactFieldPhone) {
|
|
t.Fatalf("C4 revocation intent = %+v; want stored organization and field scope", c4Payload)
|
|
}
|
|
|
|
// The history cursor is opaque and tied to the current subject and state filter.
|
|
firstPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1", "", "", candidateCookie.Value, "", "192.0.2.63:1234")
|
|
if firstPage.Code != http.StatusOK || firstPage.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("first consent page = %d, Cache-Control=%q, body=%s", firstPage.Code, firstPage.Header().Get("Cache-Control"), firstPage.Body.String())
|
|
}
|
|
var page struct {
|
|
Items []struct {
|
|
ID string `json:"id"`
|
|
} `json:"items"`
|
|
Page struct {
|
|
HasMore bool `json:"has_more"`
|
|
NextCursor string `json:"next_cursor"`
|
|
} `json:"page"`
|
|
}
|
|
if err := json.Unmarshal(firstPage.Body.Bytes(), &page); err != nil || len(page.Items) != 1 || !page.Page.HasMore || page.Page.NextCursor == "" {
|
|
t.Fatalf("first consent page = %+v, %v", page, err)
|
|
}
|
|
secondPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1&cursor="+page.Page.NextCursor, "", "", candidateCookie.Value, "", "192.0.2.64:1234")
|
|
var next struct {
|
|
Items []struct {
|
|
ID string `json:"id"`
|
|
} `json:"items"`
|
|
}
|
|
if secondPage.Code != http.StatusOK || json.Unmarshal(secondPage.Body.Bytes(), &next) != nil || len(next.Items) != 1 || next.Items[0].ID == page.Items[0].ID {
|
|
t.Fatalf("second consent page = %d %s", secondPage.Code, secondPage.Body.String())
|
|
}
|
|
foreignCursor := harness.request(t, http.MethodGet, "/api/v1/me/consents?cursor="+page.Page.NextCursor, "", "", employerCookie.Value, "", "192.0.2.65:1234")
|
|
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
|
|
employerList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", employerCookie.Value, "", "192.0.2.66:1234")
|
|
var employerHistory struct {
|
|
Items []json.RawMessage `json:"items"`
|
|
}
|
|
if employerList.Code != http.StatusOK || json.Unmarshal(employerList.Body.Bytes(), &employerHistory) != nil || len(employerHistory.Items) != 0 {
|
|
t.Fatalf("employer consent history = %d %s", employerList.Code, employerList.Body.String())
|
|
}
|
|
|
|
// C1 deletion is durable, idempotent, and independent of a later consent grant.
|
|
c1Text := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.67:1234")
|
|
var c1Current struct {
|
|
TextVersion string `json:"text_version"`
|
|
}
|
|
if c1Text.Code != http.StatusOK || json.Unmarshal(c1Text.Body.Bytes(), &c1Current) != nil {
|
|
t.Fatalf("read C1 text = %d %s", c1Text.Code, c1Text.Body.String())
|
|
}
|
|
c1Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin)
|
|
if c1Grant.Code != http.StatusOK {
|
|
t.Fatalf("C1 grant = %d %s", c1Grant.Code, c1Grant.Body.String())
|
|
}
|
|
var deletionEventsBefore int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBefore); err != nil {
|
|
t.Fatalf("count deletion events before request: %v", err)
|
|
}
|
|
badDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, "wrong-token", "192.0.2.68:1234")
|
|
requireSessionProblem(t, badDeletion, http.StatusForbidden, "csrf_check_failed")
|
|
assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0)
|
|
requestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.69:1234")
|
|
if requestDeletion.Code != http.StatusAccepted || requestDeletion.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("account deletion request = %d %s", requestDeletion.Code, requestDeletion.Body.String())
|
|
}
|
|
var firstDeletion struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
}
|
|
if err := json.Unmarshal(requestDeletion.Body.Bytes(), &firstDeletion); err != nil || firstDeletion.ID == "" || firstDeletion.Status != "requested" {
|
|
t.Fatalf("decode deletion request = %+v, %v", firstDeletion, err)
|
|
}
|
|
repeatedDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.70:1234")
|
|
var repeatedBody struct {
|
|
ID string `json:"id"`
|
|
}
|
|
if repeatedDeletion.Code != http.StatusAccepted || json.Unmarshal(repeatedDeletion.Body.Bytes(), &repeatedBody) != nil || repeatedBody.ID != firstDeletion.ID {
|
|
t.Fatalf("repeated deletion request = %d %s", repeatedDeletion.Code, repeatedDeletion.Body.String())
|
|
}
|
|
assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 1)
|
|
var deletionEventsAfter int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfter); err != nil {
|
|
t.Fatalf("count deletion events after request: %v", err)
|
|
}
|
|
if deletionEventsAfter != deletionEventsBefore+1 {
|
|
t.Fatalf("deletion event count changed by %d, want one", deletionEventsAfter-deletionEventsBefore)
|
|
}
|
|
if _, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePersonalData); err == nil {
|
|
t.Fatal("C1 remained active after its deletion request")
|
|
}
|
|
laterC1 := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin)
|
|
if laterC1.Code != http.StatusOK {
|
|
t.Fatalf("later C1 grant = %d %s", laterC1.Code, laterC1.Body.String())
|
|
}
|
|
var activeDeletionID string
|
|
if err := harness.pool.QueryRow(ctx, `SELECT id FROM account_deletion_requests WHERE subject_id = $1 AND status IN ('requested','processing')`, candidate.ID).Scan(&activeDeletionID); err != nil || activeDeletionID != firstDeletion.ID {
|
|
t.Fatalf("active deletion request after later C1 grant = %q, %v", activeDeletionID, err)
|
|
}
|
|
listBeforeRestart := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.71:1234")
|
|
if listBeforeRestart.Code != http.StatusOK {
|
|
t.Fatalf("consent history before API restart = %d %s", listBeforeRestart.Code, listBeforeRestart.Body.String())
|
|
}
|
|
var deletionRowsBeforeRestart, deletionEventsBeforeRestart int64
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsBeforeRestart); err != nil {
|
|
t.Fatalf("count deletion requests before API restart: %v", err)
|
|
}
|
|
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBeforeRestart); err != nil {
|
|
t.Fatalf("count deletion events before API restart: %v", err)
|
|
}
|
|
|
|
// Reconstruct the API and session services over the same database and reuse
|
|
// the existing cookie. History and the durable deletion request survive.
|
|
restartedHarness := newConsentHTTPHarness(ctx, t, env)
|
|
listAfterRestart := restartedHarness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.72:1234")
|
|
if listAfterRestart.Code != http.StatusOK || listAfterRestart.Body.String() != listBeforeRestart.Body.String() {
|
|
t.Fatalf("consent history after API restart = %d %s; before=%s", listAfterRestart.Code, listAfterRestart.Body.String(), listBeforeRestart.Body.String())
|
|
}
|
|
deletionAfterRestart := restartedHarness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.73:1234")
|
|
var deletionAfterRestartBody struct {
|
|
ID string `json:"id"`
|
|
}
|
|
if deletionAfterRestart.Code != http.StatusAccepted || json.Unmarshal(deletionAfterRestart.Body.Bytes(), &deletionAfterRestartBody) != nil || deletionAfterRestartBody.ID != firstDeletion.ID {
|
|
t.Fatalf("deletion request after API restart = %d %s, want durable request %s", deletionAfterRestart.Code, deletionAfterRestart.Body.String(), firstDeletion.ID)
|
|
}
|
|
var deletionRowsAfterRestart, deletionEventsAfterRestart int64
|
|
if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsAfterRestart); err != nil {
|
|
t.Fatalf("count deletion requests after API restart: %v", err)
|
|
}
|
|
if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfterRestart); err != nil {
|
|
t.Fatalf("count deletion events after API restart: %v", err)
|
|
}
|
|
if deletionRowsAfterRestart != deletionRowsBeforeRestart || deletionEventsAfterRestart != deletionEventsBeforeRestart {
|
|
t.Fatalf("API reconstruction duplicated deletion state: rows %d->%d, events %d->%d", deletionRowsBeforeRestart, deletionRowsAfterRestart, deletionEventsBeforeRestart, deletionEventsAfterRestart)
|
|
}
|
|
|
|
if strings.Contains(harness.logs.String(), candidateCookie.Value) || strings.Contains(harness.logs.String(), employerCookie.Value) ||
|
|
strings.Contains(restartedHarness.logs.String(), candidateCookie.Value) {
|
|
t.Fatal("a session token reached request logs")
|
|
}
|
|
}
|
|
|
|
func createConsentHTTPEmployer(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
harness *sessionHTTPHarness,
|
|
email string,
|
|
passwordHash domain.PasswordHash,
|
|
) domain.User {
|
|
t.Helper()
|
|
address, err := domain.NewEmailAddress(email)
|
|
if err != nil {
|
|
t.Fatalf("NewEmailAddress() error = %v", err)
|
|
}
|
|
now := harness.clock.Now().Truncate(time.Microsecond)
|
|
user, err := domain.NewUser(domain.Registration{
|
|
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewUser() error = %v", err)
|
|
}
|
|
if err := harness.store.Users().Create(ctx, user); err != nil {
|
|
t.Fatalf("Create(%s) error = %v", email, err)
|
|
}
|
|
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond))
|
|
if err != nil {
|
|
t.Fatalf("MarkEmailVerified(%s) error = %v", email, err)
|
|
}
|
|
return verified
|
|
}
|
|
|
|
func newConsentHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
|
|
t.Helper()
|
|
pool := env.newPool(ctx, t)
|
|
store := postgresadapter.NewIdentityStore(pool)
|
|
hasher, err := argon2id.NewHasher(1)
|
|
if err != nil {
|
|
t.Fatalf("NewHasher() error = %v", err)
|
|
}
|
|
credentials := identity.NewCredentials(hasher)
|
|
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
|
|
if err != nil {
|
|
t.Fatalf("NewKeyring() error = %v", err)
|
|
}
|
|
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
|
|
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
|
Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(),
|
|
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
|
|
}, identity.SessionSettings{
|
|
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
|
|
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewSessionService() error = %v", err)
|
|
}
|
|
consentStore := postgresadapter.NewConsentStore(pool)
|
|
consentReader := consent.NewQueryService(consentStore, time.Now)
|
|
consentCommands := consent.NewService(postgresadapter.NewTransactor(pool), time.Now)
|
|
logs := &strings.Builder{}
|
|
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
|
responder := problem.NewResponder(logger)
|
|
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
|
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
|
consentHandler := v1.NewConsentHandler(consentReader, consentCommands)
|
|
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler))
|
|
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRouter() error = %v", err)
|
|
}
|
|
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
|
|
}
|
|
|
|
func loginConsentHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) (*http.Cookie, string) {
|
|
t.Helper()
|
|
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr)
|
|
if response.Code != http.StatusCreated {
|
|
t.Fatalf("login %s = %d %s", email, response.Code, response.Body.String())
|
|
}
|
|
cookie := requireSessionCookie(t, response)
|
|
var body struct {
|
|
CSRFToken string `json:"csrf_token"`
|
|
}
|
|
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
|
|
t.Fatalf("decode login CSRF token: %v", err)
|
|
}
|
|
return cookie, body.CSRFToken
|
|
}
|
|
|
|
func consentGrantHTTP(t *testing.T, harness *sessionHTTPHarness, cookie *http.Cookie, csrf, purpose, version, origin string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
body, err := json.Marshal(struct {
|
|
TextVersion string `json:"text_version"`
|
|
Accepted bool `json:"accepted"`
|
|
}{TextVersion: version, Accepted: true})
|
|
if err != nil {
|
|
t.Fatalf("marshal consent grant: %v", err)
|
|
}
|
|
return harness.request(t, http.MethodPut, "/api/v1/me/consents/"+purpose, string(body), origin, cookie.Value, csrf, "192.0.2.80:1234")
|
|
}
|