550 lines
28 KiB
Go
550 lines
28 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"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/postgres/sqlc"
|
|
"lincodex/backend/internal/adapter/secondary/prometheus"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/anonymousprofile"
|
|
"lincodex/backend/internal/usecase/candidateprivacy"
|
|
"lincodex/backend/internal/usecase/candidateview"
|
|
"lincodex/backend/internal/usecase/companyquota"
|
|
"lincodex/backend/internal/usecase/consent"
|
|
"lincodex/backend/internal/usecase/health"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
"lincodex/backend/internal/usecase/policy"
|
|
)
|
|
|
|
const candidatePrivacyHTTPTestTimeout = 5 * time.Minute
|
|
|
|
type candidatePrivacyHTTPHarness struct {
|
|
*sessionHTTPHarness
|
|
key domain.CandidateViewPseudonymKey
|
|
settings *candidateprivacy.Service
|
|
}
|
|
|
|
func TestCandidatePrivacyHTTPReadsRecheckCurrentVisibility(t *testing.T) {
|
|
env := bootstrap(t, postgresService, redisService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyHTTPTestTimeout)
|
|
defer cancel()
|
|
harness := newCandidatePrivacyHTTPHarness(ctx, t, env)
|
|
truncateTables(ctx, t, harness.pool, usersDependentTables...)
|
|
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), harness.clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
|
|
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
|
|
}
|
|
|
|
now := harness.clock.Now()
|
|
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
|
|
organizations := organizationFixture{
|
|
ctx: ctx, pool: harness.pool, identity: identity,
|
|
transactor: postgresadapter.NewTransactor(harness.pool), now: now,
|
|
}
|
|
privacy := candidatePrivacyFixture{
|
|
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
|
|
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
|
|
}
|
|
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, now: now}
|
|
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
|
if err != nil {
|
|
t.Fatalf("HashNewPassword() error = %v", err)
|
|
}
|
|
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-target@example.test", passwordHash, true)
|
|
candidates := []domain.User{candidate}
|
|
for index := 1; index < 5; index++ {
|
|
other := privacy.candidate(t, fmt.Sprintf("privacy-cohort-%d@example.test", index))
|
|
verifyPrivacyCohortCandidate(t, privacy, other)
|
|
candidates = append(candidates, other)
|
|
}
|
|
for _, member := range candidates {
|
|
input := domain.CandidateProfileInput{Stack: privacyCohortConfirmedItems("go")}
|
|
if member.ID == candidate.ID {
|
|
input.FullName = confirmedDecision("Private Candidate Name")
|
|
input.Email = confirmedDecision("private-card-email@example.test")
|
|
}
|
|
profiles.save(t, member.ID, input, 0)
|
|
if member.ID == candidate.ID {
|
|
continue
|
|
}
|
|
c2 := privacy.grant(t, member.ID, domain.ConsentPurposePublication, privacyC2Version, now)
|
|
privacy.publish(t, member.ID, c2.ID(), 0, domain.CardFieldStack)
|
|
}
|
|
|
|
employer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
|
organizationA := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization A"), now)
|
|
organizationB := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization B"), now)
|
|
organizationC := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization C"), now)
|
|
inactiveOrganization := organizations.create(t, employer, organizations.completeProfile(t, "Privacy inactive organization"), now)
|
|
organizations.setMembershipState(t, inactiveOrganization.ID(), employer.ID, domain.MembershipStateLeft)
|
|
foreignEmployer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-foreign-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
|
|
foreignOrganization := organizations.create(t, foreignEmployer, organizations.completeProfile(t, "Privacy foreign organization"), now)
|
|
|
|
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.170:1234")
|
|
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.171:1234")
|
|
initialSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.172:1234")
|
|
if initialSettings.Code != http.StatusOK || initialSettings.Header().Get("Cache-Control") != "no-store" ||
|
|
!strings.Contains(initialSettings.Body.String(), `"state":"closed"`) || !strings.Contains(initialSettings.Body.String(), `"closed_reason":"never_published"`) {
|
|
t.Fatalf("initial privacy settings = %d Cache-Control=%q %s", initialSettings.Code, initialSettings.Header().Get("Cache-Control"), initialSettings.Body.String())
|
|
}
|
|
c2Grant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
|
|
"c2", privacyC2Version, sessionHTTPTestOrigin)
|
|
if c2Grant.Code != http.StatusOK {
|
|
t.Fatalf("C2 grant = %d %s", c2Grant.Code, c2Grant.Body.String())
|
|
}
|
|
publication := harness.request(t, http.MethodPut, "/api/v1/me/privacy/publication",
|
|
`{"expected_version":0,"state":"published","fields":["stack"]}`,
|
|
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.173:1234")
|
|
if publication.Code != http.StatusOK || publication.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("publication = %d Cache-Control=%q %s", publication.Code, publication.Header().Get("Cache-Control"), publication.Body.String())
|
|
}
|
|
|
|
aliasA, err := harness.key.ForOrganization(organizationA.ID(), candidate.ID)
|
|
if err != nil {
|
|
t.Fatalf("ForOrganization(A) error = %v", err)
|
|
}
|
|
aliasB, err := harness.key.ForOrganization(organizationB.ID(), candidate.ID)
|
|
if err != nil {
|
|
t.Fatalf("ForOrganization(B) error = %v", err)
|
|
}
|
|
if aliasA == aliasB {
|
|
t.Fatalf("organization-scoped aliases unexpectedly match: %q", aliasA)
|
|
}
|
|
assertCandidatePrivacyContactPortFixture(t, ctx, harness, employer.ID, organizationA.ID(), candidate.ID, aliasA)
|
|
unknownOrganization := uuid.New()
|
|
for _, test := range []struct {
|
|
name string
|
|
organizationID uuid.UUID
|
|
wantStatus int
|
|
wantCode string
|
|
useCandidate bool
|
|
}{
|
|
{name: "active employer membership", organizationID: organizationA.ID(), wantStatus: http.StatusOK},
|
|
{name: "candidate account", organizationID: organizationA.ID(), wantStatus: http.StatusForbidden, wantCode: "forbidden", useCandidate: true},
|
|
{name: "inactive membership", organizationID: inactiveOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
|
{name: "foreign membership", organizationID: foreignOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
|
{name: "unknown organization", organizationID: unknownOrganization, wantStatus: http.StatusNotFound, wantCode: "not_found"},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
cookie := employerCookie.Value
|
|
if test.useCandidate {
|
|
cookie = candidateCookie.Value
|
|
}
|
|
response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, test.organizationID, aliasA, cookie)
|
|
if response.Code != test.wantStatus {
|
|
t.Fatalf("card response = %d %s, want %d", response.Code, response.Body.String(), test.wantStatus)
|
|
}
|
|
if test.wantCode != "" {
|
|
requireSessionProblem(t, response, test.wantStatus, test.wantCode)
|
|
}
|
|
if test.wantStatus == http.StatusOK {
|
|
if response.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("card Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
|
|
}
|
|
var card struct {
|
|
Pseudonym string `json:"pseudonym"`
|
|
Stack []string `json:"stack"`
|
|
}
|
|
if err := json.Unmarshal(response.Body.Bytes(), &card); err != nil || card.Pseudonym != aliasA || len(card.Stack) != 1 || card.Stack[0] != "go" {
|
|
t.Fatalf("anonymous card = %+v, %v; body=%s", card, err, response.Body.String())
|
|
}
|
|
for _, privateValue := range []string{candidate.ID.String(), candidate.Email.Address(), "Private Candidate Name", "private-card-email@example.test"} {
|
|
if strings.Contains(response.Body.String(), privateValue) {
|
|
t.Errorf("anonymous card contains private value %q", privateValue)
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
|
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationA.ID(), []string{"stack"})
|
|
|
|
preview := harness.request(t, http.MethodGet, "/api/v1/me/privacy/preview", "", "", candidateCookie.Value, "", "192.0.2.174:1234")
|
|
if preview.Code != http.StatusOK || preview.Header().Get("Cache-Control") != "no-store" ||
|
|
strings.Contains(preview.Body.String(), aliasA) || strings.Contains(preview.Body.String(), candidate.ID.String()) {
|
|
t.Fatalf("private preview = %d Cache-Control=%q %s", preview.Code, preview.Header().Get("Cache-Control"), preview.Body.String())
|
|
}
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
|
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
|
|
|
hideA := harness.request(t, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
|
|
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.175:1234")
|
|
if hideA.Code != http.StatusOK || hideA.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("hide organization A = %d Cache-Control=%q %s", hideA.Code, hideA.Header().Get("Cache-Control"), hideA.Body.String())
|
|
}
|
|
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusNotFound {
|
|
t.Fatalf("card after hiding A = %d %s, want generic 404", response.Code, response.Body.String())
|
|
}
|
|
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusOK {
|
|
t.Fatalf("card for B after hiding A = %d %s, want independent organization access", response.Code, response.Body.String())
|
|
}
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
|
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationB.ID(), []string{"stack"})
|
|
unhideA := harness.request(t, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
|
|
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.176:1234")
|
|
if unhideA.Code != http.StatusNoContent {
|
|
t.Fatalf("unhide organization A = %d %s, want 204", unhideA.Code, unhideA.Body.String())
|
|
}
|
|
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusOK {
|
|
t.Fatalf("card after unhiding A = %d %s, want restored visibility while C2 is active", response.Code, response.Body.String())
|
|
}
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
|
|
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 2)
|
|
directHidden, err := harness.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: candidate.ID, Limit: 20})
|
|
if err != nil || len(directHidden.Items) != 0 || directHidden.HasMore {
|
|
t.Fatalf("direct hidden organization list = %+v, %v; want an empty page after unhide", directHidden, err)
|
|
}
|
|
hiddenList := harness.request(t, http.MethodGet, "/api/v1/me/privacy/hidden-organizations", "", "", candidateCookie.Value, "", "192.0.2.177:1234")
|
|
if hiddenList.Code != http.StatusOK || !strings.Contains(hiddenList.Body.String(), `"items":[]`) || hiddenList.Header().Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("hidden organizations after unhide = %d Cache-Control=%q %s", hiddenList.Code, hiddenList.Header().Get("Cache-Control"), hiddenList.Body.String())
|
|
}
|
|
privacyHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/history", "", "", candidateCookie.Value, "", "192.0.2.178:1234")
|
|
if privacyHistory.Code != http.StatusOK || !strings.Contains(privacyHistory.Body.String(), "publication_opened") ||
|
|
!strings.Contains(privacyHistory.Body.String(), "organization_hidden") || !strings.Contains(privacyHistory.Body.String(), "organization_unhidden") {
|
|
t.Fatalf("privacy history = %d %s", privacyHistory.Code, privacyHistory.Body.String())
|
|
}
|
|
accessHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/access-history", "", "", candidateCookie.Value, "", "192.0.2.179:1234")
|
|
if accessHistory.Code != http.StatusOK || accessHistory.Header().Get("Cache-Control") != "no-store" || !strings.Contains(accessHistory.Body.String(), "Privacy organization A") || !strings.Contains(accessHistory.Body.String(), "Privacy organization B") {
|
|
t.Fatalf("card access history = %d Cache-Control=%q %s", accessHistory.Code, accessHistory.Header().Get("Cache-Control"), accessHistory.Body.String())
|
|
}
|
|
|
|
// Hold the candidate account row so the employer read reaches and waits on
|
|
// its FOR SHARE visibility lock. Commit the competing hide only after the
|
|
// lock wait is observed; a visibility recheck must reject the stale cohort.
|
|
lockTx, err := harness.pool.Begin(ctx)
|
|
if err != nil {
|
|
t.Fatalf("begin visibility race transaction: %v", err)
|
|
}
|
|
defer func() { _ = lockTx.Rollback(context.Background()) }()
|
|
if _, err := lockTx.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR UPDATE`, candidate.ID); err != nil {
|
|
t.Fatalf("lock candidate row for visibility race: %v", err)
|
|
}
|
|
aliasC, err := harness.key.ForOrganization(organizationC.ID(), candidate.ID)
|
|
if err != nil {
|
|
t.Fatalf("ForOrganization(C) error = %v", err)
|
|
}
|
|
raceResult := make(chan *httptest.ResponseRecorder, 1)
|
|
go func() {
|
|
raceResult <- candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationC.ID(), aliasC, employerCookie.Value)
|
|
}()
|
|
monitor := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-monitor")
|
|
if waitEvent, waiting := waitForLockWait(ctx, monitor, "candidate-privacy-http"); !waiting || waitEvent == "" {
|
|
t.Fatalf("card read did not wait for candidate visibility lock, wait event %q", waitEvent)
|
|
}
|
|
if _, err := lockTx.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, organizationC.ID(), now.Add(time.Second)); err != nil {
|
|
t.Fatalf("commit concurrent candidate hide fixture: %v", err)
|
|
}
|
|
if err := lockTx.Commit(ctx); err != nil {
|
|
t.Fatalf("commit visibility race transaction: %v", err)
|
|
}
|
|
raceResponse := <-raceResult
|
|
if raceResponse.Code != http.StatusNotFound {
|
|
t.Fatalf("card read that waited behind a hide = %d %s, want generic 404", raceResponse.Code, raceResponse.Body.String())
|
|
}
|
|
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
|
|
|
|
revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.180:1234")
|
|
if revoke.Code != http.StatusNoContent {
|
|
t.Fatalf("C2 revoke = %d %s, want 204", revoke.Code, revoke.Body.String())
|
|
}
|
|
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
|
|
t.Fatalf("card after C2 revoke = %d %s, want generic 404", response.Code, response.Body.String())
|
|
}
|
|
regrant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
|
|
"c2", privacyC2Version, sessionHTTPTestOrigin)
|
|
if regrant.Code != http.StatusOK {
|
|
t.Fatalf("C2 regrant = %d %s", regrant.Code, regrant.Body.String())
|
|
}
|
|
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
|
|
t.Fatalf("card after C2 regrant without republication = %d %s, want generic 404", response.Code, response.Body.String())
|
|
}
|
|
closedSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.181:1234")
|
|
if closedSettings.Code != http.StatusOK || !strings.Contains(closedSettings.Body.String(), `"state":"closed"`) {
|
|
t.Fatalf("settings after C2 revoke and regrant = %d %s, want closed publication", closedSettings.Code, closedSettings.Body.String())
|
|
}
|
|
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
|
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
|
|
}
|
|
|
|
func newCandidatePrivacyHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *candidatePrivacyHTTPHarness {
|
|
t.Helper()
|
|
pool := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-http")
|
|
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)
|
|
}
|
|
key, err := keyring.CandidateViewPseudonymKey()
|
|
if err != nil {
|
|
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
|
}
|
|
clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)}
|
|
transactor := postgresadapter.NewTransactor(pool)
|
|
sessions, err := identity.NewSessionService(identity.SessionDependencies{
|
|
Transactor: transactor, 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)
|
|
consentQueries := consent.NewQueryService(consentStore, clock.Now)
|
|
consentCommands := consent.NewService(transactor, clock.Now)
|
|
privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now})
|
|
if err != nil {
|
|
t.Fatalf("candidateprivacy.NewService() error = %v", err)
|
|
}
|
|
quota := companyquota.NewService(clock.Now)
|
|
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now)
|
|
privacyViews, err := candidateview.NewService(candidateview.Dependencies{
|
|
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: clock.Now,
|
|
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
|
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("candidateview.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(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
|
consentHandler := v1.NewConsentHandler(consentQueries, consentCommands)
|
|
privacyHandler := v1.NewPrivacyHandler(privacyViews, privacySettings, env.Config.AppPublicURL)
|
|
handler := v1.NewHandler(healthHandler, responder,
|
|
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler),
|
|
)
|
|
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
|
|
if err != nil {
|
|
t.Fatalf("NewRouter() error = %v", err)
|
|
}
|
|
return &candidatePrivacyHTTPHarness{
|
|
sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs},
|
|
key: key, settings: privacySettings,
|
|
}
|
|
}
|
|
|
|
func candidatePrivacyCardRequest(t *testing.T, harness *sessionHTTPHarness, organizationID uuid.UUID, handle, cookie string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", organizationID, handle)
|
|
return harness.request(t, http.MethodGet, path, "", "", cookie, "", "192.0.2.190:1234")
|
|
}
|
|
|
|
func assertPrivacyCardAccessCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
|
|
t.Helper()
|
|
var count int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed'`, candidateID, organizationID).Scan(&count); err != nil {
|
|
t.Fatalf("count candidate card access events: %v", err)
|
|
}
|
|
if count != want {
|
|
t.Fatalf("card access event count = %d, want %d", count, want)
|
|
}
|
|
}
|
|
|
|
func assertPrivacyCardViewQuotaCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
|
|
t.Helper()
|
|
var count int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, candidateID, organizationID).Scan(&count); err != nil {
|
|
t.Fatalf("count card-view quota usage: %v", err)
|
|
}
|
|
if count != want {
|
|
t.Fatalf("card-view quota usage count = %d, want %d", count, want)
|
|
}
|
|
}
|
|
|
|
func assertPrivacyCardAccessFields(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want []string) {
|
|
t.Helper()
|
|
var fields []string
|
|
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id LIMIT 1`, candidateID, organizationID).Scan(&fields); err != nil {
|
|
t.Fatalf("read card-view audit fields: %v", err)
|
|
}
|
|
if len(fields) != len(want) {
|
|
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
|
|
}
|
|
for index := range fields {
|
|
if fields[index] != want[index] {
|
|
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
type candidatePrivacyContactGrantState uint8
|
|
|
|
const (
|
|
candidatePrivacyContactGrantAbsent candidatePrivacyContactGrantState = iota
|
|
candidatePrivacyContactGrantActive
|
|
candidatePrivacyContactGrantRevoked
|
|
)
|
|
|
|
type candidatePrivacyContactGrantFixture struct {
|
|
state candidatePrivacyContactGrantState
|
|
workflowAccepted bool
|
|
organizationID uuid.UUID
|
|
candidateID uuid.UUID
|
|
fields domain.ContactFieldSet
|
|
}
|
|
|
|
func (fixture *candidatePrivacyContactGrantFixture) currentFields(organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
|
|
if fixture == nil || fixture.state != candidatePrivacyContactGrantActive ||
|
|
fixture.organizationID != organizationID || fixture.candidateID != candidateID {
|
|
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
|
|
}
|
|
// Workflow acceptance is deliberately not used as authorization evidence.
|
|
return fixture.fields, nil
|
|
}
|
|
|
|
type candidatePrivacyContactTransactor struct {
|
|
inner outbound.Transactor
|
|
fixture *candidatePrivacyContactGrantFixture
|
|
}
|
|
|
|
func (transactor candidatePrivacyContactTransactor) WithinTransaction(
|
|
ctx context.Context,
|
|
fn func(context.Context, outbound.UnitOfWork) error,
|
|
) error {
|
|
return transactor.inner.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
view := candidatePrivacyContactView{
|
|
PrivacyViewRepository: unit.PrivacyView(),
|
|
fixture: transactor.fixture,
|
|
}
|
|
return fn(ctx, candidatePrivacyContactUnit{UnitOfWork: unit, view: view})
|
|
})
|
|
}
|
|
|
|
type candidatePrivacyContactUnit struct {
|
|
outbound.UnitOfWork
|
|
|
|
view outbound.PrivacyViewRepository
|
|
}
|
|
|
|
func (unit candidatePrivacyContactUnit) PrivacyView() outbound.PrivacyViewRepository {
|
|
return unit.view
|
|
}
|
|
|
|
type candidatePrivacyContactView struct {
|
|
outbound.PrivacyViewRepository
|
|
fixture *candidatePrivacyContactGrantFixture
|
|
}
|
|
|
|
func (view candidatePrivacyContactView) CurrentFields(_ context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
|
|
return view.fixture.currentFields(organizationID, candidateID)
|
|
}
|
|
|
|
func assertCandidatePrivacyContactPortFixture(
|
|
t *testing.T,
|
|
ctx context.Context,
|
|
harness *candidatePrivacyHTTPHarness,
|
|
actorID, organizationID, candidateID uuid.UUID,
|
|
handle string,
|
|
) {
|
|
t.Helper()
|
|
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail, domain.ContactFieldPhone)
|
|
if err != nil {
|
|
t.Fatalf("NewContactFieldSet() error = %v", err)
|
|
}
|
|
fixture := &candidatePrivacyContactGrantFixture{
|
|
organizationID: organizationID,
|
|
candidateID: candidateID,
|
|
fields: fields,
|
|
}
|
|
transactor := candidatePrivacyContactTransactor{
|
|
inner: postgresadapter.NewTransactor(harness.pool),
|
|
fixture: fixture,
|
|
}
|
|
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(harness.pool), harness.key, harness.clock.Now)
|
|
quota := companyquota.NewService(harness.clock.Now)
|
|
service, err := candidateview.NewService(candidateview.Dependencies{
|
|
Transactor: transactor, Projector: projector, PseudonymKey: harness.key, Clock: harness.clock.Now,
|
|
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
|
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("candidateview.NewService() error = %v", err)
|
|
}
|
|
|
|
for _, test := range []struct {
|
|
name string
|
|
state candidatePrivacyContactGrantState
|
|
want bool
|
|
}{
|
|
{name: "active grant returns selected fields", state: candidatePrivacyContactGrantActive, want: true},
|
|
{name: "workflow acceptance without a grant stays closed", state: candidatePrivacyContactGrantAbsent},
|
|
{name: "revoked grant stays closed", state: candidatePrivacyContactGrantRevoked},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
fixture.state = test.state
|
|
fixture.workflowAccepted = true
|
|
got, err := service.CurrentContactFields(ctx, actorID, organizationID, handle)
|
|
if test.want {
|
|
if err != nil {
|
|
t.Fatalf("CurrentContactFields() error = %v", err)
|
|
}
|
|
gotFields := got.Fields()
|
|
wantFields := fields.Fields()
|
|
if len(gotFields) != len(wantFields) {
|
|
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
|
|
}
|
|
for index := range wantFields {
|
|
if gotFields[index] != wantFields[index] {
|
|
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
|
|
}
|
|
}
|
|
} else if !errors.Is(err, outbound.ErrContactAccessClosed) {
|
|
t.Fatalf("CurrentContactFields() error = %v, want closed contact access", err)
|
|
}
|
|
assertPrivacyContactAudit(t, ctx, harness.pool, candidateID, organizationID, test.want)
|
|
})
|
|
}
|
|
}
|
|
|
|
func assertPrivacyContactAudit(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, checkFields bool) {
|
|
t.Helper()
|
|
var count int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&count); err != nil {
|
|
t.Fatalf("count contact-read audit events: %v", err)
|
|
}
|
|
if count != 1 {
|
|
t.Fatalf("contact-read audit count = %d, want one successful read and no records for denied reads", count)
|
|
}
|
|
if !checkFields {
|
|
return
|
|
}
|
|
var fields []string
|
|
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&fields); err != nil {
|
|
t.Fatalf("read contact-read audit fields: %v", err)
|
|
}
|
|
if len(fields) != 2 || fields[0] != "email" || fields[1] != "phone" {
|
|
t.Fatalf("contact-read audit fields = %v, want [email phone]", fields)
|
|
}
|
|
}
|