feat(profile): persist candidate edits and enforce company access

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 14:15:16 +03:00
1 parent 3ab6bd91a3
commit 73c7caa225
67 files changed
+5286 -229

No files matched your search

@@ -0,0 +1,538 @@
//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/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
profileusecase "lincodex/backend/internal/usecase/profile"
)
const candidateProfileHTTPTestTimeout = 5 * time.Minute
func TestCandidateProfileOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileHTTPTestTimeout)
defer cancel()
harness := newCandidateProfileHTTPHarness(ctx, t, env)
truncateTables(ctx, t, harness.pool, usersDependentTables...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
candidate := createSessionHTTPUser(ctx, t, harness, "profile-owner@example.test", passwordHash, true)
otherCandidate := createSessionHTTPUser(ctx, t, harness, "profile-other@example.test", passwordHash, true)
employer := createOrganizationHTTPUser(ctx, t, harness, "profile-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
for _, user := range []domain.User{candidate, otherCandidate} {
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", user.ID); err != nil {
t.Fatalf("set candidate profile onboarding step: %v", err)
}
}
candidateCookie, candidateCSRF := loginCandidateProfileHTTP(t, harness, candidate.Email.Address())
otherCookie, otherCSRF := loginCandidateProfileHTTP(t, harness, otherCandidate.Email.Address())
employerCookie, _ := loginCandidateProfileHTTP(t, harness, employer.Email.Address())
initial := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.101:1234")
if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("empty profile = %d Cache-Control=%q, want 200 no-store: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String())
}
var emptyResponse candidateProfileHTTPResponse
if err := json.Unmarshal(initial.Body.Bytes(), &emptyResponse); err != nil {
t.Fatalf("decode empty profile: %v", err)
}
if emptyResponse.Version != 0 || emptyResponse.FullName.Status != "unknown" || len(emptyResponse.ExperienceOverlaps) != 0 {
t.Fatalf("empty profile = %+v, want version 0 and no overlapping periods", emptyResponse)
}
missingAcknowledgement := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Private Profile Owner", false), candidateCookie, candidateCSRF, "192.0.2.102:1234")
if missingAcknowledgement.Code != http.StatusBadRequest || !strings.Contains(missingAcknowledgement.Body.String(), "/experience/1/started_on") {
t.Fatalf("overlapping periods without acknowledgement = %d %s, want field validation", missingAcknowledgement.Code, missingAcknowledgement.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 0, 0)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
firstSave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.103:1234")
if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("save profile = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String())
}
var saved candidateProfileHTTPResponse
if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil {
t.Fatalf("decode saved profile: %v", err)
}
if saved.Version != 1 || saved.FullName.Value == nil || *saved.FullName.Value != "Private Profile Owner" ||
len(saved.ExperienceOverlaps) != 1 || saved.ExperienceOverlaps[0].Status != "confirmed" ||
len(saved.ConfirmedCategories) != 0 {
t.Fatalf("saved profile = %+v, want version 1 with confirmed period overlap", saved)
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
assertCandidateProfileHistoryCannotBeUpdated(t, ctx, harness, candidate.ID)
reversedPeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 0, "2021-01", "2020-12"),
candidateCookie, candidateCSRF, "192.0.2.111:1234")
if reversedPeriod.Code != http.StatusBadRequest || !strings.Contains(reversedPeriod.Body.String(), "/experience/0/ended_on") {
t.Fatalf("reversed experience period = %d %s, want a fixed ended_on validation error", reversedPeriod.Code, reversedPeriod.Body.String())
}
futurePeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 1, "2999-01", nil),
candidateCookie, candidateCSRF, "192.0.2.112:1234")
if futurePeriod.Code != http.StatusBadRequest || !strings.Contains(futurePeriod.Body.String(), "/experience/1/started_on") {
t.Fatalf("future experience period = %d %s, want a fixed started_on validation error", futurePeriod.Code, futurePeriod.Body.String())
}
for _, forbiddenField := range []struct {
name string
value any
}{
{name: "confirmed_categories", value: []any{map[string]any{"specialization": "backend", "grade": "senior"}}},
{name: "user_id", value: uuid.NewString()},
} {
body := candidateProfileUpdateWithUnknownField(t,
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), forbiddenField.name, forbiddenField.value)
response := candidateProfileHTTPRequest(t, harness, http.MethodPut, body, candidateCookie, candidateCSRF, "192.0.2.113:1234")
if response.Code != http.StatusBadRequest {
t.Fatalf("profile update with %s = %d %s, want 400", forbiddenField.name, response.Code, response.Body.String())
}
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
stale := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 0, "Stale Profile Name", true), candidateCookie, candidateCSRF, "192.0.2.104:1234")
requireSessionProblem(t, stale, http.StatusPreconditionFailed, "version_conflict")
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
noOp := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.105:1234")
if noOp.Code != http.StatusOK {
t.Fatalf("no-op profile save = %d %s, want 200", noOp.Code, noOp.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
otherRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", otherCookie, "", "192.0.2.106:1234")
var otherProfile candidateProfileHTTPResponse
if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &otherProfile) != nil ||
otherProfile.Version != 0 || otherProfile.FullName.Value != nil {
t.Fatalf("another candidate's profile = %d %s, want an empty version-0 profile", otherRead.Code, otherRead.Body.String())
}
employerRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", employerCookie, "", "192.0.2.107:1234")
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
for _, foreignPath := range []string{
"/api/v1/me/profile/" + otherCandidate.ID.String(),
"/api/v1/me/profile/" + uuid.NewString(),
} {
foreignRead := harness.request(t, http.MethodGet, foreignPath, "", sessionHTTPTestOrigin, candidateCookie, "", "192.0.2.114:1234")
if foreignRead.Code != http.StatusNotFound || strings.Contains(foreignRead.Body.String(), "Private Profile Owner") {
t.Fatalf("foreign profile path %s = %d %s, want a non-disclosing 404", foreignPath, foreignRead.Code, foreignRead.Body.String())
}
}
// A no-op on an unsaved profile advances onboarding without inventing a
// profile version or a history row.
emptySave := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateEmptyProfileUpdateBody(t), otherCookie, otherCSRF, "192.0.2.108:1234")
if emptySave.Code != http.StatusOK {
t.Fatalf("empty profile save = %d %s, want 200", emptySave.Code, emptySave.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, otherCandidate.ID, 0, 0)
assertCandidateProfileOnboarding(t, ctx, harness, otherCandidate.ID, "candidate_questionnaire")
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("reset candidate onboarding for rollback test: %v", err)
}
removeHistoryFailure := installCandidateProfileHistoryInsertFailure(t, ctx, harness)
historyFailure := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Failed History Write", true), candidateCookie, candidateCSRF, "192.0.2.115:1234")
if historyFailure.Code != http.StatusInternalServerError {
t.Fatalf("profile save with history failure = %d %s, want 500", historyFailure.Code, historyFailure.Body.String())
}
removeHistoryFailure()
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
// Failure after history insertion must also roll back the profile and
// history when the onboarding transition fails in the same transaction.
removeOnboardingFailure := installCandidateProfileOnboardingFailure(t, ctx, harness)
rollbackAttempt := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.116:1234")
if rollbackAttempt.Code != http.StatusInternalServerError {
t.Fatalf("profile save with onboarding failure = %d %s, want 500", rollbackAttempt.Code, rollbackAttempt.Body.String())
}
removeOnboardingFailure()
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile")
unchanged := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.117:1234")
var unchangedProfile candidateProfileHTTPResponse
if unchanged.Code != http.StatusOK || json.Unmarshal(unchanged.Body.Bytes(), &unchangedProfile) != nil ||
unchangedProfile.FullName.Value == nil || *unchangedProfile.FullName.Value != "Private Profile Owner" {
t.Fatalf("profile after failed transaction = %d %s, want old claims", unchanged.Code, unchanged.Body.String())
}
updated := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.118:1234")
var updatedProfile candidateProfileHTTPResponse
if updated.Code != http.StatusOK || json.Unmarshal(updated.Body.Bytes(), &updatedProfile) != nil ||
updatedProfile.Version != 2 || updatedProfile.FullName.Value == nil || *updatedProfile.FullName.Value != "Private Profile Owner Updated" {
t.Fatalf("profile save after rolled-back attempt = %d %s, want version 2", updated.Code, updated.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire")
// Once onboarding has moved past the profile step, saving again does not
// move it back or override its current step.
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_assessment' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("move onboarding to a later step: %v", err)
}
if response := candidateProfileHTTPRequest(t, harness, http.MethodPut,
candidateProfileUpdateBody(t, 2, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.109:1234"); response.Code != http.StatusOK {
t.Fatalf("profile save after later onboarding step = %d %s", response.Code, response.Body.String())
}
assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment")
for _, privateValue := range []string{
candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(),
"Private Profile Owner", "Private Profile Owner Updated", "Stale Profile Name", "Failed History Write",
"Example Private Employer", "Private career history",
} {
if strings.Contains(harness.logs.String(), privateValue) {
t.Fatalf("profile HTTP logs contain private value %q", privateValue)
}
}
// Rebuild the handlers and pool while retaining the session cookie. The
// profile and append-only history remain in PostgreSQL across restarts.
harness.pool.Close()
harness = newCandidateProfileHTTPHarness(ctx, t, env)
restartedRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.110:1234")
var restarted candidateProfileHTTPResponse
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil ||
restarted.Version != 2 || restarted.FullName.Value == nil || *restarted.FullName.Value != "Private Profile Owner Updated" ||
len(restarted.ExperienceOverlaps) != 1 || restarted.ExperienceOverlaps[0].Status != "confirmed" {
t.Fatalf("profile after handler restart = %d %s, want version 2 and stored confirmation", restartedRead.Code, restartedRead.Body.String())
}
assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2)
}
type candidateProfileHTTPResponse struct {
Version int64 `json:"version"`
FullName struct {
Status string `json:"status"`
Value *string `json:"value"`
} `json:"full_name"`
ExperienceOverlaps []struct {
FirstIndex int `json:"first_index"`
SecondIndex int `json:"second_index"`
Status string `json:"status"`
} `json:"experience_overlaps"`
ConfirmedCategories []json.RawMessage `json:"confirmed_categories"`
}
func newCandidateProfileHTTPHarness(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)
}
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),
)
profileHandler := v1.NewProfileHandler(profileusecase.NewService(postgresadapter.NewTransactor(pool), clock.Now))
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler),
)
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 loginCandidateProfileHTTP(t *testing.T, harness *sessionHTTPHarness, email string) (string, string) {
t.Helper()
response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.100:1234")
if response.Code != http.StatusCreated {
t.Fatalf("login profile account = %d %s", 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.Value, body.CSRFToken
}
func candidateProfileHTTPRequest(
t *testing.T,
harness *sessionHTTPHarness,
method, body, cookie, csrf, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
return harness.request(t, method, "/api/v1/me/profile", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr)
}
func candidateProfileUpdateBody(t *testing.T, version int64, name string, confirmOverlap bool) string {
t.Helper()
experience := []map[string]any{
{
"employer_name": "Example Private Employer", "specialization": "backend", "started_on": "2021-01",
"ended_on": "2022-06", "summary": "Private career history", "status": "confirmed",
},
{
"employer_name": "Second Private Employer", "specialization": "backend", "started_on": "2022-01",
"ended_on": "2023-04", "summary": "Another private result", "status": "confirmed",
},
}
acknowledgements := []map[string]any{}
if confirmOverlap {
acknowledgements = append(acknowledgements, map[string]any{
"first_index": 0, "second_index": 1,
"first_period": map[string]any{"started_on": "2021-01", "ended_on": "2022-06"},
"second_period": map[string]any{"started_on": "2022-01", "ended_on": "2023-04"},
})
}
body, err := json.Marshal(map[string]any{
"expected_version": version,
"full_name": map[string]any{"value": name, "status": "confirmed"},
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
"stack": []any{},
"roles": []any{},
"experience": experience,
"confirmed_parallel_periods": acknowledgements,
"soft_skills": []any{},
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
})
if err != nil {
t.Fatalf("marshal profile update: %v", err)
}
return string(body)
}
func candidateProfileUpdateWithExperience(
t *testing.T,
version int64,
name string,
index int,
startedOn string,
endedOn any,
) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal([]byte(candidateProfileUpdateBody(t, version, name, true)), &body); err != nil {
t.Fatalf("decode profile update fixture: %v", err)
}
experience, ok := body["experience"].([]any)
if !ok || index < 0 || index >= len(experience) {
t.Fatalf("profile update fixture has no experience at index %d", index)
}
item, ok := experience[index].(map[string]any)
if !ok {
t.Fatalf("profile update fixture experience at index %d has the wrong type", index)
}
item["started_on"] = startedOn
item["ended_on"] = endedOn
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal profile update fixture: %v", err)
}
return string(encoded)
}
func candidateProfileUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string {
t.Helper()
var body map[string]any
if err := json.Unmarshal([]byte(requestBody), &body); err != nil {
t.Fatalf("decode profile update fixture: %v", err)
}
body[field] = value
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal profile update with %s: %v", field, err)
}
return string(encoded)
}
func candidateEmptyProfileUpdateBody(t *testing.T) string {
t.Helper()
body, err := json.Marshal(map[string]any{
"expected_version": 0,
"full_name": nil,
"contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil},
"stack": []any{}, "roles": []any{}, "experience": []any{},
"confirmed_parallel_periods": []any{}, "soft_skills": []any{},
"terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil},
})
if err != nil {
t.Fatalf("marshal empty profile update: %v", err)
}
return string(body)
}
func assertCandidateProfileRows(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, version, history int64) {
t.Helper()
var profileCount, historyCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profiles WHERE user_id = $1", userID).Scan(&profileCount); err != nil {
t.Fatalf("count stored profiles: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profile_history WHERE user_id = $1", userID).Scan(&historyCount); err != nil {
t.Fatalf("count profile history: %v", err)
}
wantProfileCount := int64(0)
if version > 0 {
wantProfileCount = 1
}
if profileCount != wantProfileCount || historyCount != history {
t.Fatalf("profile rows = %d, history rows = %d; want %d and %d", profileCount, historyCount, wantProfileCount, history)
}
if version > 0 {
var storedVersion int64
if err := harness.pool.QueryRow(ctx, "SELECT version FROM candidate_profiles WHERE user_id = $1", userID).Scan(&storedVersion); err != nil {
t.Fatalf("read stored profile version: %v", err)
}
if storedVersion != version {
t.Fatalf("stored profile version = %d, want %d", storedVersion, version)
}
}
}
func assertCandidateProfileOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) {
t.Helper()
var step string
if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil {
t.Fatalf("read onboarding step: %v", err)
}
if step != want {
t.Fatalf("onboarding step = %q, want %q", step, want)
}
}
func assertCandidateProfileHistoryCannotBeUpdated(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) {
t.Helper()
if _, err := harness.pool.Exec(ctx, "UPDATE candidate_profile_history SET snapshot = snapshot WHERE user_id = $1", userID); err == nil {
t.Fatal("candidate profile history accepted an UPDATE")
}
}
func installCandidateProfileHistoryInsertFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
t.Helper()
const functionName = "reject_candidate_profile_history_insert_for_http_test"
const triggerName = "candidate_profile_http_reject_history_insert"
if _, err := harness.pool.Exec(ctx, `
CREATE FUNCTION reject_candidate_profile_history_insert_for_http_test() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'candidate profile history HTTP test failure';
END;
$$`); err != nil {
t.Fatalf("create history failure function: %v", err)
}
removed := false
remove := func() {
if removed {
return
}
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON candidate_profile_history"); err != nil {
t.Errorf("drop history failure trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
t.Errorf("drop history failure function: %v", err)
}
removed = true
}
t.Cleanup(remove)
if _, err := harness.pool.Exec(ctx, `
CREATE TRIGGER candidate_profile_http_reject_history_insert
BEFORE INSERT ON candidate_profile_history
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_insert_for_http_test()`); err != nil {
t.Fatalf("create history failure trigger: %v", err)
}
return remove
}
func installCandidateProfileOnboardingFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() {
t.Helper()
const functionName = "reject_candidate_profile_onboarding_advance_for_http_test"
const triggerName = "candidate_profile_http_reject_onboarding_advance"
if _, err := harness.pool.Exec(ctx, `
CREATE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF OLD.onboarding_step = 'candidate_profile' AND NEW.onboarding_step = 'candidate_questionnaire' THEN
RAISE EXCEPTION 'candidate profile HTTP test failure';
END IF;
RETURN NEW;
END;
$$`); err != nil {
t.Fatalf("create onboarding failure function: %v", err)
}
removed := false
remove := func() {
if removed {
return
}
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON users"); err != nil {
t.Errorf("drop onboarding failure trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil {
t.Errorf("drop onboarding failure function: %v", err)
}
removed = true
}
t.Cleanup(remove)
if _, err := harness.pool.Exec(ctx, `
CREATE TRIGGER candidate_profile_http_reject_onboarding_advance
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test()`); err != nil {
t.Fatalf("create onboarding failure trigger: %v", err)
}
return remove
}
@@ -35,7 +35,12 @@ var (
candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"}
// candidateProfileTables reference users, so a TRUNCATE of users names
// them through usersDependentTables.
candidateProfileTables = []pgx.Identifier{candidateProfileClaimsTable, candidateProfilesTable}
candidateProfileTables = []pgx.Identifier{
{"candidate_profile_overlap_confirmations"},
{"candidate_profile_history"},
candidateProfileClaimsTable,
candidateProfilesTable,
}
)
// candidateProfileFixture works on the bootstrap database. The tables are
@@ -0,0 +1,265 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/domain"
)
func TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
defer cancel()
harness := newOrganizationHTTPHarness(ctx, t, env)
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, "company-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreignOwner := createOrganizationHTTPUser(ctx, t, harness, "company-foreign-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "company-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidate := createOrganizationHTTPUser(ctx, t, harness, "company-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreignOwner.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
organizationA := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a")
organizationA2 := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a2")
organizationB := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, foreignSession, "company-context-b")
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, recruiter.ID, "recruiter", "active", now)
insertOrganizationHTTPMembership(ctx, t, harness, organizationA, candidate.ID, "owner", "active", now)
ownerRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
if ownerRead.Code != http.StatusOK {
t.Fatalf("owner read = %d %s, want 200", ownerRead.Code, ownerRead.Body.String())
}
for _, test := range []struct {
name string
session organizationHTTPSession
want int
}{
{name: "foreign company", session: foreignSession, want: http.StatusNotFound},
{name: "recruiter membership", session: recruiterSession, want: http.StatusForbidden},
{name: "candidate with manually inserted owner membership", session: candidateSession, want: http.StatusForbidden},
} {
t.Run(test.name, func(t *testing.T) {
response := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", test.session, "")
if response.Code != test.want {
t.Fatalf("company read = %d %s, want %d", response.Code, response.Body.String(), test.want)
}
assertNoCompanyDetails(t, response)
})
}
childForeign := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", foreignSession, "")
if childForeign.Code != http.StatusNotFound {
t.Fatalf("foreign owner on tenant needs route = %d %s, want 404 before fallback", childForeign.Code, childForeign.Body.String())
}
assertNoCompanyDetails(t, childForeign)
childOwner := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if childOwner.Code != http.StatusNotImplemented {
t.Fatalf("owner on currently unimplemented needs route = %d %s, want guarded 501 fallback", childOwner.Code, childOwner.Body.String())
}
candidateHide := organizationHTTPRequest(t, harness, http.MethodPut,
"/api/v1/me/privacy/hidden-organizations/"+organizationA.String(), "", env.Config.AppPublicURL, candidateSession, "")
if candidateHide.Code != http.StatusNotImplemented {
t.Fatalf("candidate-owned hiding route = %d %s, want its own 501 fallback", candidateHide.Code, candidateHide.Body.String())
}
assertNoCompanyDetails(t, candidateHide)
firstPage := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations?limit=1", http.StatusOK)
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first organization page = %+v, want one item and a next cursor", firstPage)
}
if firstPage.Items[0].Membership.Role != "owner" || firstPage.Items[0].Membership.State != "active" {
t.Fatalf("owner directory membership = %+v, want active owner", firstPage.Items[0].Membership)
}
secondPage := readOrganizationDirectory(t, harness, ownerSession,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), http.StatusOK)
if len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil {
t.Fatalf("second organization page = %+v, want one last item", secondPage)
}
if firstPage.Items[0].Organization.ID == secondPage.Items[0].Organization.ID {
t.Fatal("organization directory repeated an item across pages")
}
for _, item := range []organizationDirectoryItem{firstPage.Items[0], secondPage.Items[0]} {
if item.Organization.ID != organizationA.String() && item.Organization.ID != organizationA2.String() {
t.Fatalf("owner directory exposed another account's organization %s", item.Organization.ID)
}
}
foreignCursor := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "", foreignSession, "")
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
foreignDirectory := readOrganizationDirectory(t, harness, foreignSession, "/api/v1/me/organizations", http.StatusOK)
if len(foreignDirectory.Items) != 1 || foreignDirectory.Items[0].Organization.ID != organizationB.String() {
t.Fatalf("foreign owner's directory = %+v, want only %s", foreignDirectory.Items, organizationB)
}
recruiterDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(recruiterDirectory.Items) != 1 || recruiterDirectory.Items[0].Membership.Role != "recruiter" {
t.Fatalf("recruiter's directory = %+v, want its active recruiter membership", recruiterDirectory.Items)
}
candidateDirectory := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/organizations", "", "", candidateSession, "")
requireSessionProblem(t, candidateDirectory, http.StatusForbidden, "forbidden")
assertNoCompanyDetails(t, candidateDirectory)
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(time.Second), organizationA, recruiter.ID,
); err != nil {
t.Fatalf("revoke recruiter membership: %v", err)
}
revokedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", recruiterSession, "")
requireSessionProblem(t, revokedRead, http.StatusNotFound, "not_found")
revokedDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK)
if len(revokedDirectory.Items) != 0 {
t.Fatalf("directory with the same cookie after revocation = %+v, want empty", revokedDirectory.Items)
}
if _, err := harness.pool.Exec(ctx,
"UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3",
now.Add(2*time.Second), organizationA, owner.ID,
); err != nil {
t.Fatalf("revoke owner membership: %v", err)
}
revokedOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "")
requireSessionProblem(t, revokedOwnerRead, http.StatusNotFound, "not_found")
assertNoCompanyDetails(t, revokedOwnerRead)
revokedOwnerChild := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "")
if revokedOwnerChild.Code != http.StatusNotFound {
t.Fatalf("same owner cookie after revocation on tenant route = %d %s, want 404", revokedOwnerChild.Code, revokedOwnerChild.Body.String())
}
assertNoCompanyDetails(t, revokedOwnerChild)
remainingOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet,
"/api/v1/organizations/"+organizationA2.String(), "", "", ownerSession, "")
if remainingOwnerRead.Code != http.StatusOK {
t.Fatalf("same owner cookie for its remaining organization = %d %s, want 200", remainingOwnerRead.Code, remainingOwnerRead.Body.String())
}
remainingOwnerDirectory := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations", http.StatusOK)
if len(remainingOwnerDirectory.Items) != 1 || remainingOwnerDirectory.Items[0].Organization.ID != organizationA2.String() {
t.Fatalf("owner directory after membership revocation = %+v, want only %s", remainingOwnerDirectory.Items, organizationA2)
}
for _, marker := range []string{
owner.Email.Address(), foreignOwner.Email.Address(), recruiter.Email.Address(), candidate.Email.Address(),
"ООО Тестовая компания",
} {
if strings.Contains(harness.logs.String(), marker) {
t.Fatalf("company context logs contain account or profile data %q", marker)
}
}
}
func createCompanyForContextTest(
t *testing.T,
harness *sessionHTTPHarness,
origin string,
session organizationHTTPSession,
idempotencyKey string,
) uuid.UUID {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations",
"{\"name\":\"ООО Тестовая компания\",\"contacts\":{\"website\":\"https://company-context.example.test\",\"email\":\"careers@company-context.example.test\",\"phone\":\"+12025550123\",\"telegram\":\"@companycontext\"}}",
origin, session, idempotencyKey)
if response.Code != http.StatusCreated {
t.Fatalf("create test company = %d %s, want 201", response.Code, response.Body.String())
}
var company struct {
ID uuid.UUID `json:"id"`
}
if err := json.Unmarshal(response.Body.Bytes(), &company); err != nil {
t.Fatalf("decode test company: %v", err)
}
return company.ID
}
func assertNoCompanyDetails(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
body := response.Body.String()
for _, marker := range []string{
"ООО Тестовая компания",
"company-context.example.test",
"careers@company-context.example.test",
"+12025550123",
"@companycontext",
} {
if strings.Contains(body, marker) {
t.Fatalf("denied company response contains company profile data %q", marker)
}
}
}
func insertOrganizationHTTPMembership(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
organizationID uuid.UUID,
userID uuid.UUID,
role, state string,
at time.Time,
) {
t.Helper()
membershipID, err := uuid.NewV7()
if err != nil {
t.Fatalf("NewV7 membership ID: %v", err)
}
if _, err := harness.pool.Exec(ctx, `
INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $6)
`, membershipID, organizationID, userID, role, state, at); err != nil {
t.Fatalf("insert test company membership: %v", err)
}
}
type organizationDirectoryResponse struct {
Items []organizationDirectoryItem `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
type organizationDirectoryItem struct {
Organization struct {
ID string `json:"id"`
} `json:"organization"`
Membership struct {
Role string `json:"role"`
State string `json:"state"`
} `json:"membership"`
}
func readOrganizationDirectory(
t *testing.T,
harness *sessionHTTPHarness,
session organizationHTTPSession,
path string,
wantStatus int,
) organizationDirectoryResponse {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
if response.Code != wantStatus {
t.Fatalf("organization directory = %d %s, want %d", response.Code, response.Body.String(), wantStatus)
}
var directory organizationDirectoryResponse
if err := json.Unmarshal(response.Body.Bytes(), &directory); err != nil {
t.Fatalf("decode organization directory: %v", err)
}
return directory
}
@@ -1149,6 +1149,23 @@ func TestServiceMailSending(t *testing.T) {
if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 {
t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err)
}
scheduled := harness.delivery(ctx, t, deliveryID)
if scheduled.Status() != domain.DeliveryStatusUnknown || scheduled.NextAttemptAt().IsZero() {
t.Fatalf("authorized delivery is %s due %s; want scheduled unknown work", scheduled.Status(), scheduled.NextAttemptAt())
}
dueAfterAuthorization := scheduled.NextAttemptAt().Add(time.Second)
var databaseNow time.Time
if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&databaseNow); err != nil {
t.Fatalf("read database clock after manual retry: %v", err)
}
databaseDueAt := databaseNow.Add(time.Second)
if databaseDueAt.After(dueAfterAuthorization) {
dueAfterAuthorization = databaseDueAt
}
// The CLI uses the real clock; the worker uses the test clock. Align the
// worker with the persisted due time before scripting the next provider
// response, or this subtest leaves that response queued for the next one.
harness.clock.Set(dueAfterAuthorization)
fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"})
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry {
@@ -299,7 +299,7 @@ func newOrganizationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvi
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil)
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}