feat(accounts): add consent settings and organization management
This commit is contained in:
1 parent
24638d46d2
commit
391af7a1ef
83 files changed
+10198
-613
No files matched your search
@@ -0,0 +1,500 @@
|
||||
//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")
|
||||
}
|
||||
@@ -45,9 +45,10 @@ const (
|
||||
const consentSecondC1Version domain.ConsentTextVersion = "c1-2026-10-05"
|
||||
|
||||
var (
|
||||
consentRecordsTable = pgx.Identifier{"consent_records"}
|
||||
consentRecordsTable = pgx.Identifier{"consent_records"}
|
||||
accountDeletionRequestsTable = pgx.Identifier{"account_deletion_requests"}
|
||||
// consentTables reference users, so every TRUNCATE of users names them.
|
||||
consentTables = []pgx.Identifier{consentRecordsTable}
|
||||
consentTables = []pgx.Identifier{consentRecordsTable, accountDeletionRequestsTable}
|
||||
)
|
||||
|
||||
// consentFixture works on the bootstrap database. The ledger rows are
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
)
|
||||
|
||||
const mailRetryMigrationVersion = 17
|
||||
@@ -23,6 +25,7 @@ func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) {
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("Up() error = %v", err)
|
||||
}
|
||||
rollBackToMailRetryVersion(ctx, t, migrator)
|
||||
|
||||
deliveryID := uuid.New()
|
||||
decidedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
@@ -62,6 +65,42 @@ func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func rollBackToMailRetryVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) {
|
||||
t.Helper()
|
||||
for {
|
||||
statuses, err := migrator.Status(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Status() while preparing migration %d: %v", mailRetryMigrationVersion, err)
|
||||
}
|
||||
mailRetryApplied := false
|
||||
laterMigrationApplied := false
|
||||
for _, status := range statuses {
|
||||
if !status.Applied {
|
||||
continue
|
||||
}
|
||||
if status.Version == mailRetryMigrationVersion {
|
||||
mailRetryApplied = true
|
||||
}
|
||||
if status.Version > mailRetryMigrationVersion {
|
||||
laterMigrationApplied = true
|
||||
}
|
||||
}
|
||||
if !mailRetryApplied {
|
||||
t.Fatalf("migration %d is not applied", mailRetryMigrationVersion)
|
||||
}
|
||||
if !laterMigrationApplied {
|
||||
return
|
||||
}
|
||||
result, err := migrator.DownOne(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DownOne() while preparing migration %d: %v", mailRetryMigrationVersion, err)
|
||||
}
|
||||
if result.Version <= mailRetryMigrationVersion {
|
||||
t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, mailRetryMigrationVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func containsAll(value string, fragments ...string) bool {
|
||||
for _, fragment := range fragments {
|
||||
if !strings.Contains(value, fragment) {
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
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/prometheus"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/health"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/organization"
|
||||
)
|
||||
|
||||
const organizationHTTPTestTimeout = 5 * time.Minute
|
||||
|
||||
type organizationHTTPSession struct {
|
||||
cookie *http.Cookie
|
||||
csrf string
|
||||
}
|
||||
|
||||
func TestOrganizationCreationAndOwnerEditingOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
|
||||
defer cancel()
|
||||
harness := newOrganizationHTTPHarness(ctx, t, env)
|
||||
initialLogs := harness.logs
|
||||
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
|
||||
truncateTables(ctx, t, harness.pool, resetTables...)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
now := harness.clock.Now()
|
||||
owner := createOrganizationHTTPUser(ctx, t, harness, "owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
foreign := createOrganizationHTTPUser(ctx, t, harness, "foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
||||
candidate := createOrganizationHTTPUser(ctx, t, harness, "candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
|
||||
unverified := createOrganizationHTTPUser(ctx, t, harness, "unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now)
|
||||
|
||||
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
|
||||
foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address())
|
||||
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
|
||||
unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass,
|
||||
env.Config.AppPublicURL, "", "192.0.2.44:1234")
|
||||
requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified")
|
||||
if len(unverifiedLogin.Header().Values("Set-Cookie")) != 0 {
|
||||
t.Fatal("unverified account received a session cookie")
|
||||
}
|
||||
|
||||
createBody := "{\"name\":\"ООО Тестовая компания\",\"description\":\"Профиль компании\",\"contacts\":{\"website\":\"https://company.example.test\",\"email\":\"careers@example.test\",\"phone\":\"+74950000000\",\"telegram\":\"@company_careers\"},\"representatives\":[{\"name\":\"Ирина Проверочная\",\"job_title\":\"Руководитель найма\"}]}"
|
||||
createResponses := make(chan *httptest.ResponseRecorder, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
createResponses <- organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-create-1")
|
||||
}()
|
||||
}
|
||||
created := <-createResponses
|
||||
concurrentReplay := <-createResponses
|
||||
if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("create response = %d %s, Cache-Control=%q, want 201 no-store", created.Code, created.Body.String(), created.Header().Get("Cache-Control"))
|
||||
}
|
||||
originalBody := append([]byte(nil), created.Body.Bytes()...)
|
||||
if concurrentReplay.Code != http.StatusCreated || string(concurrentReplay.Body.Bytes()) != string(originalBody) {
|
||||
t.Fatalf("concurrent create = %d %s, want the same 201 body %s", concurrentReplay.Code, concurrentReplay.Body.String(), originalBody)
|
||||
}
|
||||
var creation struct {
|
||||
ID string `json:"id"`
|
||||
Version int64 `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Verification struct {
|
||||
Level string `json:"level"`
|
||||
Basis string `json:"basis"`
|
||||
} `json:"verification"`
|
||||
CandidateCard map[string]json.RawMessage `json:"candidate_card"`
|
||||
}
|
||||
if err := json.Unmarshal(originalBody, &creation); err != nil {
|
||||
t.Fatalf("decode created organization: %v", err)
|
||||
}
|
||||
if creation.ID == "" || creation.Version != 1 || creation.Name != "ООО Тестовая компания" ||
|
||||
creation.Verification.Level != "e0" || creation.Verification.Basis != "confirmed_email" {
|
||||
t.Fatalf("created company has unexpected identity or verification: %+v", creation)
|
||||
}
|
||||
for _, key := range []string{"id", "name", "description", "sphere", "contacts", "representatives", "verification_level"} {
|
||||
if _, ok := creation.CandidateCard[key]; !ok {
|
||||
t.Fatalf("candidate card has no %q field: %v", key, creation.CandidateCard)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"owner", "membership", "role", "email_verified", "user_id", "password"} {
|
||||
if _, ok := creation.CandidateCard[key]; ok {
|
||||
t.Fatalf("candidate card exposes private %q field", key)
|
||||
}
|
||||
}
|
||||
assertOrganizationHTTPCounts(ctx, t, harness.pool, 1, 1, 1, 1)
|
||||
organizationID := creation.ID
|
||||
|
||||
var storedRole, storedState string
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
"SELECT role, state FROM memberships WHERE organization_id = $1 AND user_id = $2", organizationID, owner.ID,
|
||||
).Scan(&storedRole, &storedState); err != nil {
|
||||
t.Fatalf("read creator membership: %v", err)
|
||||
}
|
||||
if storedRole != "owner" || storedState != "active" {
|
||||
t.Fatalf("stored creator membership = %s/%s, want active owner", storedRole, storedState)
|
||||
}
|
||||
|
||||
updated := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID,
|
||||
"{\"expected_version\":1,\"name\":\"ООО Обновленная компания\",\"description\":null}",
|
||||
env.Config.AppPublicURL, ownerSession, "")
|
||||
if updated.Code != http.StatusOK {
|
||||
t.Fatalf("owner update = %d %s, want 200", updated.Code, updated.Body.String())
|
||||
}
|
||||
var updatedBody struct {
|
||||
Version int64 `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
Verification struct {
|
||||
Level string `json:"level"`
|
||||
Basis string `json:"basis"`
|
||||
} `json:"verification"`
|
||||
}
|
||||
if err := json.Unmarshal(updated.Body.Bytes(), &updatedBody); err != nil {
|
||||
t.Fatalf("decode updated organization: %v", err)
|
||||
}
|
||||
if updatedBody.Version != 2 || updatedBody.Name != "ООО Обновленная компания" || updatedBody.Description != nil ||
|
||||
updatedBody.Verification.Level != "e0" || updatedBody.Verification.Basis != "confirmed_email" {
|
||||
t.Fatalf("updated organization = %+v, want edited profile and unchanged E0", updatedBody)
|
||||
}
|
||||
harness.pool.Close()
|
||||
harness = newOrganizationHTTPHarness(ctx, t, env)
|
||||
restartedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "",
|
||||
"", ownerSession, "")
|
||||
if restartedRead.Code != http.StatusOK {
|
||||
t.Fatalf("read with a new handler and pool = %d %s, want 200", restartedRead.Code, restartedRead.Body.String())
|
||||
}
|
||||
var restartedBody struct {
|
||||
Version int64 `json:"version"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(restartedRead.Body.Bytes(), &restartedBody); err != nil {
|
||||
t.Fatalf("decode organization after handler restart: %v", err)
|
||||
}
|
||||
if restartedBody.Version != 2 || restartedBody.Name != "ООО Обновленная компания" {
|
||||
t.Fatalf("organization after handler restart = %+v, want the persisted owner update", restartedBody)
|
||||
}
|
||||
staleUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID,
|
||||
"{\"expected_version\":1,\"name\":\"ООО Устаревшее изменение\"}",
|
||||
env.Config.AppPublicURL, ownerSession, "")
|
||||
requireSessionProblem(t, staleUpdate, http.StatusPreconditionFailed, "version_conflict")
|
||||
|
||||
replay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-create-1")
|
||||
if replay.Code != http.StatusCreated || replay.Header().Get("Cache-Control") != "no-store" ||
|
||||
string(replay.Body.Bytes()) != string(originalBody) {
|
||||
t.Fatalf("same-key replay = %d %s, want the exact original 201 body %s", replay.Code, replay.Body.String(), originalBody)
|
||||
}
|
||||
changed := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations",
|
||||
"{\"name\":\"ООО Другой запрос\"}",
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-create-1")
|
||||
requireSessionProblem(t, changed, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
replayTime := harness.clock.Now()
|
||||
expired, err := harness.pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2",
|
||||
replayTime.Add(-2*time.Second), replayTime.Add(-time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("expire the original create key: %v", err)
|
||||
}
|
||||
if expired.RowsAffected() != 1 {
|
||||
t.Fatalf("expired idempotency rows = %d, want 1", expired.RowsAffected())
|
||||
}
|
||||
reused := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-create-1")
|
||||
if reused.Code != http.StatusCreated {
|
||||
t.Fatalf("create with an expired key = %d %s, want 201", reused.Code, reused.Body.String())
|
||||
}
|
||||
var reusedBody struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(reused.Body.Bytes(), &reusedBody); err != nil {
|
||||
t.Fatalf("decode organization created after key expiration: %v", err)
|
||||
}
|
||||
if reusedBody.ID == organizationID {
|
||||
t.Fatal("expired key replayed the old company instead of creating a new one")
|
||||
}
|
||||
reusedReplay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-create-1")
|
||||
if reusedReplay.Code != http.StatusCreated || string(reusedReplay.Body.Bytes()) != string(reused.Body.Bytes()) {
|
||||
t.Fatalf("replay after key reuse = %d %s, want the replacement snapshot %s",
|
||||
reusedReplay.Code, reusedReplay.Body.String(), reused.Body.String())
|
||||
}
|
||||
assertOrganizationHTTPCounts(ctx, t, harness.pool, 2, 2, 2, 1)
|
||||
|
||||
foreignRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "",
|
||||
"", foreignSession, "")
|
||||
requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found")
|
||||
foreignUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID,
|
||||
"{\"expected_version\":2,\"name\":\"Не владелец\"}",
|
||||
env.Config.AppPublicURL, foreignSession, "")
|
||||
requireSessionProblem(t, foreignUpdate, http.StatusNotFound, "not_found")
|
||||
candidateCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations",
|
||||
"{\"name\":\"Кандидат не может создать компанию\"}",
|
||||
env.Config.AppPublicURL, candidateSession, "organization-http-candidate-create")
|
||||
requireSessionProblem(t, candidateCreate, http.StatusForbidden, "forbidden")
|
||||
|
||||
// The failed owner insert must roll back the organization and idempotency
|
||||
// reservation together. Reusing the same key after removing the constraint
|
||||
// proves the request left no partial state.
|
||||
if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships ADD CONSTRAINT organization_http_reject_owner CHECK (role <> 'owner') NOT VALID"); err != nil {
|
||||
t.Fatalf("install temporary owner failure constraint: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = harness.pool.Exec(context.WithoutCancel(ctx), "ALTER TABLE memberships DROP CONSTRAINT IF EXISTS organization_http_reject_owner")
|
||||
})
|
||||
beforeFailure := readOrganizationHTTPCounts(ctx, t, harness.pool)
|
||||
rollbackBody := "{\"name\":\"ООО Повтор после отката\"}"
|
||||
failedCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1")
|
||||
if failedCreate.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("owner insert failure status = %d %s, want 500", failedCreate.Code, failedCreate.Body.String())
|
||||
}
|
||||
assertOrganizationHTTPCountsEqual(ctx, t, harness.pool, beforeFailure)
|
||||
if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships DROP CONSTRAINT organization_http_reject_owner"); err != nil {
|
||||
t.Fatalf("remove temporary owner failure constraint: %v", err)
|
||||
}
|
||||
recoveredCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody,
|
||||
env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1")
|
||||
if recoveredCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create after rollback = %d %s, want 201 with the same idempotency key", recoveredCreate.Code, recoveredCreate.Body.String())
|
||||
}
|
||||
|
||||
for _, marker := range []string{
|
||||
owner.Email.Address(), foreign.Email.Address(), candidate.Email.Address(), unverified.Email.Address(),
|
||||
"Ирина Проверочная", "careers@example.test", "ООО Тестовая компания", "ООО Обновленная компания",
|
||||
} {
|
||||
if strings.Contains(initialLogs.String(), marker) || strings.Contains(harness.logs.String(), marker) {
|
||||
t.Fatalf("organization HTTP logs contain profile or account data %q", marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newOrganizationHTTPHarness(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)}
|
||||
sessionService, 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)
|
||||
}
|
||||
organizationService, err := organization.NewService(organization.Dependencies{
|
||||
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("organization.NewService() error = %v", err)
|
||||
}
|
||||
logs := &strings.Builder{}
|
||||
logger := slog.New(slog.NewJSONHandler(logs, nil))
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil,
|
||||
v1.WithSessionService(sessionService),
|
||||
v1.WithPublicOrigin(env.Config.AppPublicURL),
|
||||
)
|
||||
organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler),
|
||||
)
|
||||
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 createOrganizationHTTPUser(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
email string,
|
||||
passwordHash domain.PasswordHash,
|
||||
scenario domain.Scenario,
|
||||
verified bool,
|
||||
now time.Time,
|
||||
) domain.User {
|
||||
t.Helper()
|
||||
address, err := domain.NewEmailAddress(email)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: address, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser() error = %v", err)
|
||||
}
|
||||
if err := harness.store.Users().Create(ctx, user); err != nil {
|
||||
t.Fatalf("Create(%q) error = %v", email, err)
|
||||
}
|
||||
if !verified {
|
||||
return user
|
||||
}
|
||||
user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond))
|
||||
if err != nil {
|
||||
t.Fatalf("MarkEmailVerified() error = %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
func loginOrganizationHTTP(t *testing.T, harness *sessionHTTPHarness, email string) organizationHTTPSession {
|
||||
t.Helper()
|
||||
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.40:1234")
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("login status = %d %s, want 201", response.Code, response.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
CSRFToken string `json:"csrf_token"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode login response: %v", err)
|
||||
}
|
||||
if body.CSRFToken == "" {
|
||||
t.Fatal("login response has no CSRF token")
|
||||
}
|
||||
return organizationHTTPSession{cookie: requireSessionCookie(t, response), csrf: body.CSRFToken}
|
||||
}
|
||||
|
||||
func organizationHTTPRequest(
|
||||
t *testing.T,
|
||||
harness *sessionHTTPHarness,
|
||||
method, path, body, origin string,
|
||||
session organizationHTTPSession,
|
||||
idempotencyKey string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if origin != "" {
|
||||
request.Header.Set("Origin", origin)
|
||||
}
|
||||
if session.cookie != nil {
|
||||
request.AddCookie(&http.Cookie{Name: "__Host-lincodex_session", Value: session.cookie.Value})
|
||||
}
|
||||
if session.csrf != "" {
|
||||
request.Header.Set("X-CSRF-Token", session.csrf)
|
||||
}
|
||||
if idempotencyKey != "" {
|
||||
request.Header.Set("Idempotency-Key", idempotencyKey)
|
||||
}
|
||||
request.RemoteAddr = "192.0.2.41:1234"
|
||||
recorder := httptest.NewRecorder()
|
||||
harness.router.ServeHTTP(recorder, request)
|
||||
return recorder
|
||||
}
|
||||
|
||||
type organizationHTTPRowCounts struct {
|
||||
organizations int64
|
||||
representatives int64
|
||||
memberships int64
|
||||
results int64
|
||||
idempotency int64
|
||||
}
|
||||
|
||||
func readOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool) organizationHTTPRowCounts {
|
||||
t.Helper()
|
||||
var counts organizationHTTPRowCounts
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
(SELECT count(*) FROM organizations),
|
||||
(SELECT count(*) FROM organization_representatives),
|
||||
(SELECT count(*) FROM memberships),
|
||||
(SELECT count(*) FROM organization_creation_results),
|
||||
(SELECT count(*) FROM idempotency_records)
|
||||
`).Scan(&counts.organizations, &counts.representatives, &counts.memberships, &counts.results, &counts.idempotency); err != nil {
|
||||
t.Fatalf("read organization transaction counts: %v", err)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
func assertOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool,
|
||||
organizations, representatives, memberships, results int64,
|
||||
) {
|
||||
t.Helper()
|
||||
counts := readOrganizationHTTPCounts(ctx, t, pool)
|
||||
if counts.organizations != organizations || counts.representatives != representatives ||
|
||||
counts.memberships != memberships || counts.results != results {
|
||||
t.Fatalf("organization rows = %+v, want org=%d representatives=%d memberships=%d snapshots=%d",
|
||||
counts, organizations, representatives, memberships, results)
|
||||
}
|
||||
}
|
||||
|
||||
func assertOrganizationHTTPCountsEqual(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want organizationHTTPRowCounts) {
|
||||
t.Helper()
|
||||
if got := readOrganizationHTTPCounts(ctx, t, pool); got != want {
|
||||
t.Fatalf("failed organization create changed transactional rows: got %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,12 @@ var (
|
||||
organizationsTable = pgx.Identifier{"organizations"}
|
||||
organizationRepresentativesTable = pgx.Identifier{"organization_representatives"}
|
||||
membershipsTable = pgx.Identifier{"memberships"}
|
||||
organizationCreationResultsTable = pgx.Identifier{"organization_creation_results"}
|
||||
// organizationTables are emptied together: memberships reference both
|
||||
// users and organizations.
|
||||
organizationTables = []pgx.Identifier{membershipsTable, organizationRepresentativesTable, organizationsTable}
|
||||
// users and organizations. Creation snapshots reference idempotency records.
|
||||
organizationTables = []pgx.Identifier{
|
||||
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
|
||||
}
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
|
||||
Reference in new issue
Block a user