test(backend): check company isolation and revocation over every org read

This commit is contained in:
shira committed 2026-10-10 16:49:15 +03:00
1 parent e367553d7c
commit 84454116f2
5 files changed
+837 -2

No files matched your search

@@ -0,0 +1,831 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/evidence"
invitationusecase "lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/matching"
needusecase "lincodex/backend/internal/usecase/need"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/usecase/organization"
profileusecase "lincodex/backend/internal/usecase/profile"
)
const companyIsolationTimeout = 20 * time.Minute
// companyIsolationCohort is the number of candidates with identical cards. A
// card is shown only in a group of at least five, and the scenarios take one
// candidate out of the group at a time, so six keep every card visible.
const companyIsolationCohort = 6
// companyIsolationHarness serves every operation of the minimal path that an
// organization or a candidate reads: the session, the consents, the profile,
// the assessment, the company and its needs, the search, the anonymous card
// and its evidence, the invitations with the contact read, the visibility
// settings, and both notification inboxes. The router mounts the company
// context middleware of the production wiring.
type companyIsolationHarness struct {
*assessmentAttemptHTTPHarness
key domain.CandidateViewPseudonymKey
}
func newCompanyIsolationHarness(ctx context.Context, t *testing.T, env *testEnvironment) *companyIsolationHarness {
t.Helper()
var key domain.CandidateViewPseudonymKey
var organizationHandler *v1.OrganizationHandler
harness := newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env,
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true},
func(parts assessmentHarnessParts) []v1.HandlerOption {
var err error
if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
quota := companyquota.NewService(parts.clock.Now)
views, err := candidateview.NewService(candidateview.Dependencies{
Transactor: parts.transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now),
PseudonymKey: key, Clock: parts.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)
}
settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now})
if err != nil {
t.Fatalf("candidateprivacy.NewService() error = %v", err)
}
organizationService, err := organization.NewService(organization.Dependencies{
Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now,
})
if err != nil {
t.Fatalf("organization.NewService() error = %v", err)
}
needService, err := needusecase.NewService(needusecase.Dependencies{
Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now,
})
if err != nil {
t.Fatalf("need.NewService() error = %v", err)
}
search, err := matching.NewService(matching.Dependencies{
Transactor: parts.transactor, Cards: views.ListVisibleCards, Clock: parts.clock.Now,
Views: func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) {
session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID)
if err != nil {
return nil, err
}
return session, nil
},
})
if err != nil {
t.Fatalf("matching.NewService() error = %v", err)
}
evidenceService, err := evidence.NewService(evidence.Dependencies{
Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
})
if err != nil {
t.Fatalf("evidence.NewService() error = %v", err)
}
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), parts.clock.Now))
if err != nil {
t.Fatalf("NewInvitationNotifier() error = %v", err)
}
invitations, err := invitationusecase.NewService(invitationusecase.Dependencies{
Transactor: parts.transactor, Keyring: parts.keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle,
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
},
Notifier: notifier, Consents: consent.NewService(parts.transactor, parts.clock.Now), Clock: parts.clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
}
// The synthetic notice is the only producer of an employer's inbox
// item today, so its resolver is on.
inbox, err := notification.NewInboxService(parts.transactor,
notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(true)), parts.clock.Now)
if err != nil {
t.Fatalf("notification.NewInboxService() error = %v", err)
}
organizationHandler = v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
return []v1.HandlerOption{
v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)),
v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)),
v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now))),
v1.WithOrganization(organizationHandler),
v1.WithNeed(v1.NewNeedHandler(needService)),
v1.WithMatches(v1.NewMatchHandler(search)),
v1.WithInvitation(v1.NewInvitationHandler(invitations)),
v1.WithNotifications(v1.NewNotificationHandler(inbox)),
}
},
func() []apiadapter.Middleware {
return []apiadapter.Middleware{httpadapter.NewCompanyContextMiddleware(organizationHandler)}
})
return &companyIsolationHarness{assessmentAttemptHTTPHarness: harness, key: key}
}
// isolationCandidate is a candidate of the scenario with the private values
// that no organization may read before an accepted grant, and no log, event,
// or notification may carry.
type isolationCandidate struct {
categoryHTTPCandidate
phone, fullName, employer, location string
}
func (candidate isolationCandidate) privateValues() []string {
return []string{candidate.email, candidate.phone, candidate.fullName, candidate.employer, candidate.location}
}
// isolationCall is one request of a walk with the status that the contract
// gives it.
type isolationCall struct {
name string
method, path string
body string
status int
code string
}
// TestCompanyIsolationAndRevocationOverHTTP is the acceptance walk of the
// company isolation, the revocation, and the projections of the minimal path.
//
// Company A runs the whole path: a need, a search, a card and its evidence,
// an invitation accepted with C4, the contact read, and an inbox item. Company
// B then calls every organization-scoped operation of the contract with its
// own valid session, once on the path of A and once on its own path with the
// identifiers that A's responses named, and each call answers the documented
// refusal, the same as for an identifier that does not exist. Candidates call
// the candidate-scoped operations with the identifiers of another candidate.
// The revocation scenarios check that hiding the organization, revoking C4,
// and withdrawing C2 close the next read at once through the handles of an
// earlier search, the invitation page, and the contact read, and that neither
// a new publication nor a new C2 revives a grant that C4 revocation closed.
// Finally the server log, the outbox, the inbox rows, and the stored email
// requests are scanned for the private values of the candidates.
func TestCompanyIsolationAndRevocationOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), companyIsolationTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newCompanyIsolationHarness(ctx, t, &isolatedEnv)
bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV4(), true)
threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark))
// The policy takes effect when it is stored, which is after the clock of
// the harness was read.
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx}
transactor := postgresadapter.NewTransactor(harness.pool)
consumers := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL)
do := func(who categoryHTTPCandidate, method, path, body string) *httptest.ResponseRecorder {
t.Helper()
key := ""
if method != http.MethodGet {
key = uuid.NewString()
}
return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, method, path, body, sessionHTTPTestOrigin,
who.cookie, who.csrf, key, client.remote())
}
must := func(who categoryHTTPCandidate, method, path, body string, want int) *httptest.ResponseRecorder {
t.Helper()
response := do(who, method, path, body)
if response.Code != want {
t.Fatalf("%s %s = %d %s, want %d", method, path, response.Code, response.Body.String(), want)
}
return response
}
decode := func(response *httptest.ResponseRecorder, target any) {
t.Helper()
if err := json.Unmarshal(response.Body.Bytes(), target); err != nil {
t.Fatalf("decode %s: %v", response.Body.String(), err)
}
}
requireNoStore := func(label string, response *httptest.ResponseRecorder) {
t.Helper()
if cache := response.Header().Get("Cache-Control"); cache != "no-store" {
t.Fatalf("%s Cache-Control = %q, want no-store", label, cache)
}
}
// --- Candidates: a confirmed category, a profile with private values, C2,
// and the same published card.
publishedFields := `["categories","stack","experience","self_assessment","work_formats"]`
candidates := make([]isolationCandidate, 0, companyIsolationCohort)
for index := range companyIsolationCohort {
base := client.candidate(t, fmt.Sprintf("isolation-candidate-%d@example.test", index))
run := client.run(t, base, "backend", "intern", func(int) int { return threshold })
if run.result["outcome"] != "confirmed" {
t.Fatalf("assessment of candidate %d = %v, want confirmed", index, run.result["outcome"])
}
candidate := isolationCandidate{
categoryHTTPCandidate: base,
phone: fmt.Sprintf("+7999000%04d", index),
fullName: fmt.Sprintf("Isolation Secret Name %d", index),
employer: fmt.Sprintf("Isolation Secret Employer %d", index),
location: fmt.Sprintf("Isolation Secret Location %d", index),
}
profile, err := json.Marshal(map[string]any{
"expected_version": 0,
"full_name": map[string]any{"value": candidate.fullName, "status": "confirmed"},
"contacts": map[string]any{
"email": map[string]any{"value": candidate.email, "status": "confirmed"},
"phone": map[string]any{"value": candidate.phone, "status": "confirmed"},
"telegram": nil,
},
"stack": []any{map[string]any{"tag": "go", "status": "confirmed"}},
"roles": []any{map[string]any{"specialization": "backend", "self_assessed_grade": "junior", "status": "confirmed"}},
"experience": []any{map[string]any{
"employer_name": candidate.employer, "specialization": "backend", "started_on": "2020-01",
"ended_on": "2023-12", "summary": "Isolation Secret Summary", "status": "confirmed",
}},
"confirmed_parallel_periods": []any{}, "soft_skills": []any{},
"terms": map[string]any{
"location": map[string]any{"value": candidate.location, "status": "confirmed"}, "relocation": nil,
"salary_minimum": map[string]any{"value": map[string]any{
"amount": 120000, "currency": "RUB", "period": "month", "tax_basis": "net",
}, "status": "confirmed"},
},
})
if err != nil {
t.Fatalf("marshal profile: %v", err)
}
must(base, http.MethodPut, "/api/v1/me/profile", string(profile), http.StatusOK)
must(base, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK)
must(base, http.MethodPut, "/api/v1/me/privacy/publication",
fmt.Sprintf(`{"expected_version":0,"state":"published","fields":%s}`, publishedFields), http.StatusOK)
candidates = append(candidates, candidate)
}
subject, neighbour, drafted := candidates[0], candidates[1], candidates[2]
// Every private value and internal identifier of the candidates. The
// organization side, the logs, and the events must carry none of them.
privateValues := make([]string, 0, len(candidates)*5+1)
candidateIDs := make([]string, 0, len(candidates))
for _, candidate := range candidates {
privateValues = append(privateValues, candidate.privateValues()...)
candidateIDs = append(candidateIDs, candidate.id.String())
}
privateValues = append(privateValues, "Isolation Secret Summary")
requireNoCandidateValues := func(label, text string, withIDs bool) {
t.Helper()
values := privateValues
if withIDs {
values = append(slices.Clone(values), candidateIDs...)
}
for _, value := range values {
if strings.Contains(text, value) {
t.Fatalf("%s carries the private value %q: %s", label, value, text)
}
}
}
// --- Two companies, each with its own owner.
ownerA := client.employer(t, "isolation-owner-a@example.test")
ownerB := client.employer(t, "isolation-owner-b@example.test")
const nameA = "Isolation Company Alpha"
createOrganization := func(owner categoryHTTPCandidate, name string) uuid.UUID {
t.Helper()
response := must(owner, http.MethodPost, "/api/v1/organizations",
fmt.Sprintf(`{"name":%q,"contacts":{"website":"https://isolation.example.test","email":"careers@isolation.example.test","phone":"+12025550123","telegram":"@isolationcompany"}}`, name),
http.StatusCreated)
var created struct {
ID uuid.UUID `json:"id"`
}
decode(response, &created)
return created.ID
}
orgA := createOrganization(ownerA, nameA)
orgB := createOrganization(ownerB, "Isolation Company Beta")
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
orgPath := func(organizationID uuid.UUID, suffix string) string {
return fmt.Sprintf("/api/v1/organizations/%s%s", organizationID, suffix)
}
// --- Company A runs the path and collects the identifiers of its objects.
const needTitle = "Isolation payments backend need"
var need struct {
ID uuid.UUID `json:"id"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
}
decode(must(ownerA, http.MethodPost, orgPath(orgA, "/needs"),
fmt.Sprintf(`{"title":%q,"specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}]}`, needTitle),
http.StatusCreated), &need)
needSearch := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d}`, need.ID, need.RequirementsVersion)
bankSearch := `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`
search := func(owner categoryHTTPCandidate, organizationID uuid.UUID, body string) matchSearchBody {
t.Helper()
response := must(owner, http.MethodPost, orgPath(organizationID, "/matches"), body, http.StatusOK)
requireNoStore("search", response)
requireNoCandidateValues("search result", response.Body.String(), true)
var result matchSearchBody
decode(response, &result)
return result
}
// The handles of this first result are the stored search result that the
// later scenarios reuse after the visibility changes.
firstSearch := search(ownerA, orgA, needSearch)
aliasA := func(candidate isolationCandidate) string {
t.Helper()
alias, err := harness.key.ForOrganization(orgA, candidate.id)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return alias
}
subjectHandle := aliasA(subject)
if _, found := firstSearch.handles()[subjectHandle+"/backend"]; !found {
t.Fatalf("first search of A = %v, want the subject among the results", firstSearch.handles())
}
cardPath := orgPath(orgA, "/candidate-cards/"+subjectHandle)
card := must(ownerA, http.MethodGet, cardPath, "", http.StatusOK)
requireNoStore("card", card)
requireNoCandidateValues("anonymous card", card.Body.String(), true)
evidenceRead := must(ownerA, http.MethodGet, cardPath+"/evidence", "", http.StatusOK)
requireNoStore("evidence", evidenceRead)
requireNoCandidateValues("card evidence", evidenceRead.Body.String(), true)
createDraft := func(owner categoryHTTPCandidate, organizationID uuid.UUID, handle string) invitationHTTPBody {
t.Helper()
return decodeInvitationHTTP(t, do(owner, http.MethodPost, orgPath(organizationID, "/invitations"), invitationCreateJSON(t, handle, nil)), http.StatusCreated)
}
sendDraft := func(owner categoryHTTPCandidate, organizationID uuid.UUID, draft invitationHTTPBody) invitationHTTPBody {
t.Helper()
return decodeInvitationHTTP(t, do(owner, http.MethodPost, orgPath(organizationID, "/invitations/"+draft.ID.String()+"/send"),
fmt.Sprintf(`{"expected_version":%d}`, draft.Version)), http.StatusOK)
}
accept := func(candidate isolationCandidate, invitation invitationHTTPBody, fields ...string) candidateContactGrantHTTP {
t.Helper()
encoded, err := json.Marshal(map[string]any{
"expected_version": invitation.Version, "terms_version": invitation.TermsVersion,
"consent_c4": map[string]any{"text_version": acceptTextVersion, "accepted": true, "fields": fields},
})
if err != nil {
t.Fatalf("marshal acceptance: %v", err)
}
accepted := decodeCandidateInvitationHTTP(t, do(candidate.categoryHTTPCandidate, http.MethodPost,
"/api/v1/me/invitations/"+invitation.ID.String()+"/accept", string(encoded)), http.StatusOK)
return decodeContactGrantHTTP(t, accepted)
}
contactsPath := func(organizationID, invitationID uuid.UUID) string {
return orgPath(organizationID, "/invitations/"+invitationID.String()+"/contacts")
}
accepted := sendDraft(ownerA, orgA, createDraft(ownerA, orgA, subjectHandle))
firstGrant := accept(subject, accepted, "email", "phone")
contacts := must(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), "", http.StatusOK)
requireNoStore("contacts", contacts)
if !strings.Contains(contacts.Body.String(), subject.email) || !strings.Contains(contacts.Body.String(), subject.phone) {
t.Fatalf("contact read of A = %s, want the granted email and phone", contacts.Body.String())
}
// A second invitation stays a draft, so B's changes would be visible on it.
draft := createDraft(ownerA, orgA, aliasA(drafted))
// The candidate's inbox item comes from the outbox event of the send, and
// the owner of A receives a synthetic notice: the only employer item today.
deliverEvent := func(where string, args ...any) {
t.Helper()
var event outbound.ConsumedEvent
var payload string
if err := harness.pool.QueryRow(ctx, `
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
FROM outbox_events WHERE `+where, args...).Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType,
&event.AggregateID, &event.AggregateVersion, &payload, &event.OccurredAt); err != nil {
t.Fatalf("read the outbox event: %v", err)
}
event.Payload = []byte(payload)
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) {
t.Fatalf("the inbox consumer did not apply %s", event.EventType)
}
}
deliverEvent(`event_type = 'invitation.delivered' AND aggregate_id = $1`, accepted.ID)
syntheticEvent := appendSyntheticNotice(ctx, t, transactor, ownerA.id, orgA, harness.clock.Now())
if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, syntheticEvent) {
t.Fatal("the inbox consumer did not apply the synthetic notice")
}
onlyNotification := func(who categoryHTTPCandidate, path string) notificationBody {
t.Helper()
page := decodeNotificationPage(t, do(who, http.MethodGet, path, ""))
if len(page.Items) != 1 {
t.Fatalf("%s lists %d items, want one", path, len(page.Items))
}
return page.Items[0]
}
ownerNotice := onlyNotification(ownerA, orgPath(orgA, "/notifications"))
subjectNotice := onlyNotification(subject.categoryHTTPCandidate, "/api/v1/me/notifications")
requireNoCandidateValues("candidate notification", do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/notifications", "").Body.String(), true)
// readStateOfA is everything that a change by B would show up in.
type stateOfA struct {
organization, need, draft, accepted, contacts, notifications string
}
readStateOfA := func() stateOfA {
t.Helper()
read := func(path string) string {
t.Helper()
return must(ownerA, http.MethodGet, path, "", http.StatusOK).Body.String()
}
return stateOfA{
organization: read(orgPath(orgA, "")), need: read(orgPath(orgA, "/needs/"+need.ID.String())),
draft: read(orgPath(orgA, "/invitations/"+draft.ID.String())), accepted: read(orgPath(orgA, "/invitations/"+accepted.ID.String())),
contacts: read(contactsPath(orgA, accepted.ID)), notifications: read(orgPath(orgA, "/notifications")),
}
}
before := readStateOfA()
// withoutTrace drops the request-specific trace identifier of a problem, so
// two refusals can be compared byte for byte.
withoutTrace := func(response *httptest.ResponseRecorder) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode problem %d %s: %v", response.Code, response.Body.String(), err)
}
delete(body, "trace_id")
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("encode problem: %v", err)
}
return string(encoded)
}
// walk runs every call as who and, for each call that names an object of
// another owner, the same call with a random identifier in its place: an
// existing object of someone else and a missing one answer the same.
walk := func(t *testing.T, who categoryHTTPCandidate, calls []isolationCall, hidden ...uuid.UUID) {
t.Helper()
for _, call := range calls {
response := do(who, call.method, call.path, call.body)
if response.Code != call.status {
t.Errorf("%s: %s %s = %d %s, want %d", call.name, call.method, call.path, response.Code, response.Body.String(), call.status)
continue
}
if call.code != "" {
requireSessionProblem(t, response, call.status, call.code)
}
text := response.Body.String()
requireNoCandidateValues(call.name, text, true)
for _, marker := range []string{nameA, needTitle, "isolation.example.test", "Middle Go developer in the payments team"} {
if strings.Contains(text, marker) {
t.Errorf("%s: the answer names %q of company A: %s", call.name, marker, text)
}
}
for _, id := range hidden {
if !strings.Contains(call.path, id.String()) && !strings.Contains(call.body, id.String()) {
continue
}
missing := do(who, call.method,
strings.ReplaceAll(call.path, id.String(), uuid.NewString()),
strings.ReplaceAll(call.body, id.String(), uuid.NewString()))
if missing.Code != response.Code || withoutTrace(missing) != withoutTrace(response) {
t.Errorf("%s: the object of A answers %d %s, a missing one %d %s; want the same refusal",
call.name, response.Code, withoutTrace(response), missing.Code, withoutTrace(missing))
}
}
}
}
t.Run("company B refuses every organization operation on the objects of A, as for objects that do not exist", func(t *testing.T) {
invitationBody := fmt.Sprintf(`{"expected_version":%d}`, draft.Version)
raiseBody := fmt.Sprintf(`{"expected_version":%d,"salary_to":150000}`, accepted.Version+1)
notFound := func(name, method, path, body string) isolationCall {
return isolationCall{name: name, method: method, path: path, body: body, status: http.StatusNotFound, code: "not_found"}
}
// On the path of A, B has no membership: the documented answer of every
// operation is 404 not_found, before the object is looked up.
onPathOfA := []isolationCall{
notFound("read A", http.MethodGet, orgPath(orgA, ""), ""),
notFound("change A", http.MethodPatch, orgPath(orgA, ""), `{"expected_version":1,"name":"Hijacked by B"}`),
notFound("list needs of A", http.MethodGet, orgPath(orgA, "/needs"), ""),
notFound("create a need in A", http.MethodPost, orgPath(orgA, "/needs"), `{"title":"Need by B"}`),
notFound("read a need of A", http.MethodGet, orgPath(orgA, "/needs/"+need.ID.String()), ""),
notFound("change a need of A", http.MethodPatch, orgPath(orgA, "/needs/"+need.ID.String()), fmt.Sprintf(`{"expected_version":%d,"title":"Hijacked"}`, need.Version)),
notFound("search of A", http.MethodPost, orgPath(orgA, "/matches"), needSearch),
notFound("card of A", http.MethodGet, cardPath, ""),
notFound("evidence of A", http.MethodGet, cardPath+"/evidence", ""),
notFound("list invitations of A", http.MethodGet, orgPath(orgA, "/invitations"), ""),
notFound("draft in A", http.MethodPost, orgPath(orgA, "/invitations"), invitationCreateJSON(t, subjectHandle, nil)),
notFound("read an invitation of A", http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), ""),
notFound("change a draft of A", http.MethodPatch, orgPath(orgA, "/invitations/"+draft.ID.String()), invitationBody),
notFound("send a draft of A", http.MethodPost, orgPath(orgA, "/invitations/"+draft.ID.String()+"/send"), invitationBody),
notFound("withdraw an invitation of A", http.MethodPost, orgPath(orgA, "/invitations/"+draft.ID.String()+"/withdraw"), invitationBody),
notFound("raise the salary of A", http.MethodPost, orgPath(orgA, "/invitations/"+accepted.ID.String()+"/salary-raise"), raiseBody),
notFound("contacts of A", http.MethodGet, contactsPath(orgA, accepted.ID), ""),
notFound("notifications of A", http.MethodGet, orgPath(orgA, "/notifications"), ""),
notFound("mark a notification of A", http.MethodPost, orgPath(orgA, "/notifications/"+ownerNotice.ID.String()+"/read"), ""),
}
walk(t, ownerB, onPathOfA, orgA)
// On its own path the caller is the owner, so each operation reaches
// the lookup of the object, which belongs to A: not found, as for a
// missing one. The candidate handle of A is no handle of another
// company, so a draft refuses it as a field, and a search refuses the
// need of A. Withdrawal and the salary raise are not implemented yet
// and answer 501 for any object. The same holds for B and for a second
// company of A's own owner in the same holding: the holding shares
// quotas, never objects.
orgA2 := createOrganization(ownerA, "Isolation Company Alpha Two")
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
for _, foreign := range []struct {
label string
owner categoryHTTPCandidate
organization uuid.UUID
directory bool
}{
{label: "B", owner: ownerB, organization: orgB, directory: true},
{label: "a second company of the owner of A", owner: ownerA, organization: orgA2},
} {
under := func(name string) string { return name + " under " + foreign.label }
path := func(suffix string) string { return orgPath(foreign.organization, suffix) }
calls := []isolationCall{
notFound(under("a need of A"), http.MethodGet, path("/needs/"+need.ID.String()), ""),
notFound(under("change a need of A"), http.MethodPatch, path("/needs/"+need.ID.String()), fmt.Sprintf(`{"expected_version":%d,"title":"Hijacked"}`, need.Version)),
notFound(under("search by the need of A"), http.MethodPost, path("/matches"), needSearch),
notFound(under("card by a handle of A"), http.MethodGet, path("/candidate-cards/"+subjectHandle), ""),
notFound(under("evidence by a handle of A"), http.MethodGet, path("/candidate-cards/"+subjectHandle+"/evidence"), ""),
{name: under("draft for a handle of A"), method: http.MethodPost, path: path("/invitations"),
body: invitationCreateJSON(t, subjectHandle, nil), status: http.StatusBadRequest, code: "validation_failed"},
notFound(under("an invitation of A"), http.MethodGet, path("/invitations/"+accepted.ID.String()), ""),
notFound(under("change a draft of A"), http.MethodPatch, path("/invitations/"+draft.ID.String()), invitationBody),
notFound(under("send a draft of A"), http.MethodPost, path("/invitations/"+draft.ID.String()+"/send"), invitationBody),
{name: under("withdraw an invitation of A"), method: http.MethodPost, path: path("/invitations/" + draft.ID.String() + "/withdraw"),
body: invitationBody, status: http.StatusNotImplemented, code: "not_implemented"},
{name: under("raise the salary of A"), method: http.MethodPost, path: path("/invitations/" + accepted.ID.String() + "/salary-raise"),
body: raiseBody, status: http.StatusNotImplemented, code: "not_implemented"},
notFound(under("contacts of A"), http.MethodGet, contactsPath(foreign.organization, accepted.ID), ""),
notFound(under("mark a notification of A"), http.MethodPost, path("/notifications/"+ownerNotice.ID.String()+"/read"), ""),
notFound(under("mark the candidate's notification"), http.MethodPost, path("/notifications/"+subjectNotice.ID.String()+"/read"), ""),
}
walk(t, foreign.owner, calls, need.ID, accepted.ID, draft.ID, ownerNotice.ID, subjectNotice.ID)
// A draft cannot be linked to the need of A either.
linked := do(foreign.owner, http.MethodPost, path("/invitations"), invitationCreateJSON(t, aliasA(neighbour), func(body, _ map[string]any) {
body["need"] = map[string]any{"need_id": need.ID, "requirements_version": need.RequirementsVersion}
}))
if linked.Code != http.StatusBadRequest {
t.Errorf("draft %s linked to the need of A = %d %s, want 400", under(""), linked.Code, linked.Body.String())
}
requireNoCandidateValues("linked draft", linked.Body.String(), true)
// The lists show nothing of A.
lists := []string{path("/needs"), path("/invitations"), path("/notifications")}
if foreign.directory {
lists = append(lists, "/api/v1/me/organizations")
}
for _, list := range lists {
response := must(foreign.owner, http.MethodGet, list, "", http.StatusOK)
requireNoStore(list, response)
text := response.Body.String()
markers := []string{need.ID.String(), accepted.ID.String(), draft.ID.String(), ownerNotice.ID.String(), needTitle}
if foreign.directory {
markers = append(markers, orgA.String(), nameA)
}
for _, marker := range markers {
if strings.Contains(text, marker) {
t.Errorf("%s %s names %q of A: %s", list, under(""), marker, text)
}
}
requireNoCandidateValues(list, text, true)
}
// The company's own search reveals the cohort under its own handles.
for handle := range search(foreign.owner, foreign.organization, bankSearch).handles() {
if strings.HasPrefix(handle, subjectHandle) {
t.Errorf("the search %s returns the handle of A %s", under(""), subjectHandle)
}
}
}
// Nothing of A changed, the draft is still a draft, and the owner's
// notification is still unread.
if after := readStateOfA(); after != before {
t.Errorf("the calls of B changed the state of A:\nbefore %+v\nafter %+v", before, after)
}
})
t.Run("a candidate refuses every candidate operation on the objects of another candidate", func(t *testing.T) {
other := neighbour.categoryHTTPCandidate
command := fmt.Sprintf(`{"expected_version":%d}`, accepted.Version+1)
calls := []isolationCall{
{name: "read the invitation of another candidate", method: http.MethodGet, path: "/api/v1/me/invitations/" + accepted.ID.String(),
status: http.StatusNotFound, code: "not_found"},
{name: "open the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/view",
status: http.StatusNotFound, code: "not_found"},
{name: "decline the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/decline",
body: fmt.Sprintf(`{"expected_version":%d,"reason":"other"}`, accepted.Version+1), status: http.StatusNotFound, code: "not_found"},
{name: "accept the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/accept",
body: fmt.Sprintf(`{"expected_version":%d,"terms_version":%d,"consent_c4":{"text_version":%q,"accepted":true,"fields":["email"]}}`,
accepted.Version+1, accepted.TermsVersion, acceptTextVersion), status: http.StatusNotFound, code: "not_found"},
{name: "cancel the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/cancel",
body: command, status: http.StatusNotImplemented, code: "not_implemented"},
{name: "mark the notification of another candidate", method: http.MethodPost, path: "/api/v1/me/notifications/" + subjectNotice.ID.String() + "/read",
status: http.StatusNotFound, code: "not_found"},
}
walk(t, other, calls, accepted.ID, subjectNotice.ID)
for _, path := range []string{"/api/v1/me/invitations", "/api/v1/me/notifications", "/api/v1/me/privacy/access-history"} {
text := must(other, http.MethodGet, path, "", http.StatusOK).Body.String()
if strings.Contains(text, accepted.ID.String()) || strings.Contains(text, subjectNotice.ID.String()) {
t.Errorf("%s of another candidate names the subject's objects: %s", path, text)
}
}
// Revoking C4 for A without a consent of one's own changes nothing of
// the subject's grant.
if response := do(other, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), ""); response.Code >= http.StatusInternalServerError {
t.Errorf("C4 revocation without a consent = %d %s", response.Code, response.Body.String())
}
must(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), "", http.StatusOK)
// An employer is no candidate.
requireSessionProblem(t, do(ownerB, http.MethodGet, "/api/v1/me/invitations/"+accepted.ID.String(), ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, do(ownerB, http.MethodGet, "/api/v1/me/notifications", ""), http.StatusForbidden, "forbidden")
// A candidate is no member of a company.
requireSessionProblem(t, do(other, http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, do(other, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusForbidden, "forbidden")
if after := readStateOfA(); after != before {
t.Errorf("the calls of another candidate changed the state of A:\nbefore %+v\nafter %+v", before, after)
}
})
t.Run("no PDF, snapshot, or stored search result is served", func(t *testing.T) {
// The contract has no PDF, selection snapshot, or stored search
// operation in the MVP. Such a path is an unknown route, not data and
// not a server error, for the owner as well as for anyone else.
for _, path := range []string{
cardPath + "/pdf",
orgPath(orgA, "/matches/"+need.ID.String()),
orgPath(orgA, "/needs/"+need.ID.String()+"/snapshots"),
orgPath(orgA, "/invitations/"+accepted.ID.String()+"/pdf"),
"/api/v1/me/profile/pdf",
} {
for _, who := range []categoryHTTPCandidate{ownerA, ownerB, subject.categoryHTTPCandidate} {
response := do(who, http.MethodGet, path, "")
requireSessionProblem(t, response, http.StatusNotFound, "not_found")
requireNoCandidateValues(path, response.Body.String(), true)
}
}
// A search result is computed for each request and never stored: a GET
// of the search path is no read of an earlier result.
requireSessionProblem(t, do(ownerA, http.MethodGet, orgPath(orgA, "/matches"), ""), http.StatusMethodNotAllowed, "method_not_allowed")
})
hiddenGrant := firstGrant
t.Run("hiding A closes the next read through the old search, the card, the evidence, a draft, and the contacts", func(t *testing.T) {
must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", http.StatusOK)
// The very next requests, with the handle of the earlier result.
requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath, ""), http.StatusNotFound, "not_found")
requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath+"/evidence", ""), http.StatusNotFound, "not_found")
requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusNotFound, "not_found")
requireInvitationValidation(t, do(ownerA, http.MethodPost, orgPath(orgA, "/invitations"), invitationCreateJSON(t, subjectHandle, nil)), "/candidate_handle", "")
if _, found := search(ownerA, orgA, needSearch).handles()[subjectHandle+"/backend"]; found {
t.Fatal("a new search of A still returns the hidden candidate")
}
// The old invitation page shows the access as closed and no value.
page := do(ownerA, http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), "")
if invitation := decodeInvitationHTTP(t, page, http.StatusOK); invitation.ContactAccess.Status != "closed" || len(invitation.ContactAccess.Fields) != 0 {
t.Fatalf("invitation page while hidden = %+v, want closed access", invitation.ContactAccess)
}
requireNoCandidateValues("invitation page while hidden", page.Body.String(), true)
// Unhiding reopens the card for new reads but never the closed grant.
must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", http.StatusNoContent)
must(ownerA, http.MethodGet, cardPath, "", http.StatusOK)
requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusNotFound, "not_found")
grant := decodeContactGrantHTTP(t, decodeCandidateInvitationHTTP(t,
do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/invitations/"+accepted.ID.String(), ""), http.StatusOK))
if grant.ID != hiddenGrant.ID || grant.Status != "revoked" || grant.Readable || grant.RevocationReason == nil || *grant.RevocationReason != "visibility_closed" {
t.Fatalf("grant after hiding and unhiding = %+v, want the same grant revoked for visibility", grant)
}
})
t.Run("revoking C4 closes the next read, and neither C2 again nor a new publication revives the grant", func(t *testing.T) {
invitation := sendDraft(ownerA, orgA, createDraft(ownerA, orgA, subjectHandle))
grant := accept(subject, invitation, "email")
must(ownerA, http.MethodGet, contactsPath(orgA, invitation.ID), "", http.StatusOK)
must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), "", http.StatusNoContent)
requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, invitation.ID), ""), http.StatusNotFound, "not_found")
// C4 does not hide the card: the anonymous card stays readable.
must(ownerA, http.MethodGet, cardPath, "", http.StatusOK)
// The candidate withdraws C2, grants it again, and publishes the card
// again. The card reopens for new reads; the grant that C4 closed does not.
must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/consents/c2", "", http.StatusNoContent)
requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath, ""), http.StatusNotFound, "not_found")
requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath+"/evidence", ""), http.StatusNotFound, "not_found")
must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK)
var publication struct {
Version int64 `json:"version"`
}
var privacy struct {
Publication json.RawMessage `json:"publication"`
}
decode(must(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/privacy", "", http.StatusOK), &privacy)
if err := json.Unmarshal(privacy.Publication, &publication); err != nil {
t.Fatalf("decode publication %s: %v", privacy.Publication, err)
}
must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/privacy/publication",
fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":%s}`, publication.Version, publishedFields), http.StatusOK)
must(ownerA, http.MethodGet, cardPath, "", http.StatusOK)
for _, closed := range []uuid.UUID{invitation.ID, accepted.ID} {
requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, closed), ""), http.StatusNotFound, "not_found")
page := do(ownerA, http.MethodGet, orgPath(orgA, "/invitations/"+closed.String()), "")
if read := decodeInvitationHTTP(t, page, http.StatusOK); read.ContactAccess.Status != "closed" {
t.Fatalf("invitation %s after the new publication = %+v, want closed access", closed, read.ContactAccess)
}
requireNoCandidateValues("invitation page after the new publication", page.Body.String(), true)
}
reread := decodeContactGrantHTTP(t, decodeCandidateInvitationHTTP(t,
do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/invitations/"+invitation.ID.String(), ""), http.StatusOK))
if reread.ID != grant.ID || reread.Status != "revoked" || reread.Readable || reread.RevocationReason == nil || *reread.RevocationReason != "consent_revoked" {
t.Fatalf("grant after C2 again and a new publication = %+v, want it still revoked by the C4 revocation", reread)
}
var active int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM contact_grants
WHERE candidate_id = $1 AND organization_id = $2 AND revoked_at IS NULL`, subject.id, orgA).Scan(&active); err != nil {
t.Fatalf("count active grants: %v", err)
}
if active != 0 {
t.Fatalf("active grants of the subject for A = %d, want none without a new acceptance", active)
}
})
t.Run("the log, the events, the inbox, and the stored email requests carry no private value", func(t *testing.T) {
// The request log, problem log, and every other server log line.
if harness.logs.Len() == 0 {
t.Fatal("the scenario wrote no server log to scan")
}
requireNoCandidateValues("server log", harness.logs.String(), true)
// Event payloads name internal identifiers only where the inbox and
// privacy contracts require them, and never a contact, a name, or a
// profile value.
rows, err := harness.pool.Query(ctx, `SELECT event_type, payload::text FROM outbox_events ORDER BY event_id`)
if err != nil {
t.Fatalf("read outbox: %v", err)
}
events := 0
for rows.Next() {
var eventType, payload string
if err := rows.Scan(&eventType, &payload); err != nil {
t.Fatalf("scan outbox: %v", err)
}
events++
requireNoCandidateValues("outbox event "+eventType, payload, false)
}
rows.Close()
if err := rows.Err(); err != nil {
t.Fatalf("read outbox rows: %v", err)
}
if events == 0 {
t.Fatal("the scenario wrote no outbox event to scan")
}
var inboxRows, mailRequests string
if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(string_agg(row_to_json(entry)::text, ' '), '') FROM notification_inbox_events AS entry`).Scan(&inboxRows); err != nil {
t.Fatalf("read inbox rows: %v", err)
}
requireNoCandidateValues("inbox rows", inboxRows, false)
if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(string_agg(subject || ' ' || body || ' ' || link_path, ' '), '') FROM mail_requests`).Scan(&mailRequests); err != nil {
t.Fatalf("read email requests: %v", err)
}
if mailRequests == "" {
t.Fatal("the scenario stored no email request to scan")
}
requireNoCandidateValues("stored email requests", mailRequests, true)
// The notification as each recipient reads it.
requireNoCandidateValues("candidate notifications", do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/notifications", "").Body.String(), true)
requireNoCandidateValues("organization notifications", do(ownerA, http.MethodGet, orgPath(orgA, "/notifications"), "").Body.String(), true)
// The candidate's own preview of the anonymous card.
preview := must(neighbour.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/privacy/preview", "", http.StatusOK)
requireNoCandidateValues("card preview", preview.Body.String(), true)
})
}