feat(profile): add the manual candidate profile contract and storage

This commit is contained in:
shira committed 2026-10-06 21:10:04 +03:00
1 parent d21fd49a42
commit e52ffe7bcb
97 files changed
+20442 -63

No files matched your search

@@ -0,0 +1,311 @@
-- +goose Up
-- The manual candidate profile (PRD FR02, TASK-066): full name and contacts,
-- stack, roles, work experience, soft skills, and desired terms, each value
-- with its confirmation state and provenance. Enum-like columns are text with
-- CHECK constraints, as in the identity tables.
--
-- The rows are personal data of the candidate (names, contacts, work
-- history, the lowest salary), so the application never copies a value into
-- logs, metrics, events, or URLs. Only the owning account reads them; no
-- organization-visible query selects from these tables.
--
-- The profile stands on its own. Nothing here references a resume file, the
-- object storage, the ML service, or an FSP account: a profile that was typed
-- by hand is complete, and a later import adds its own columns or tables
-- (additively) instead of changing the meaning of these.
--
-- A confirmed grade or category is deliberately not stored here. It comes
-- from assessment results, and the self-assessed grade of a role is only a
-- claim inside the value of a role claim, so no statement against these
-- tables can write a confirmed category.
CREATE TABLE candidate_profiles (
-- The account that owns the profile. One profile per candidate; the
-- profile is created by the first save and the app never reads another
-- account's row.
user_id uuid NOT NULL,
-- Optimistic concurrency version, advanced by every save that changes the
-- profile. A first save creates version 1; the contract's version 0 is
-- the absence of a row.
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT candidate_profiles_pkey PRIMARY KEY (user_id),
-- The profile is personal data of the account and goes with it when the
-- account is erased. The retention rules are an open legal question.
CONSTRAINT candidate_profiles_user_id_fkey FOREIGN KEY (
user_id
) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT candidate_profiles_version_positive CHECK (version > 0),
CONSTRAINT candidate_profiles_updated_after_creation CHECK (
updated_at >= created_at
)
);
-- One row per stored claim: a single field (kind full_name, contact_*,
-- terms_*, at ordinal 0) or one item of a list (stack, role, experience,
-- soft_skill, at its position). A field without a value has no row, so the
-- contract's `unknown` state is the absence of the row, and every row holds a
-- value with a status of confirmed or extracted. The whole set of a profile is
-- replaced in one transaction with the version bump.
--
-- The value is jsonb because the kinds have different shapes (a string, a
-- boolean, or an object). Each kind has its own CHECK for the shape and the
-- bounds of the contract, and the domain validates the value in full before
-- it is stored.
CREATE TABLE candidate_profile_claims (
user_id uuid NOT NULL,
kind text NOT NULL,
-- Position in a list, from 0; always 0 for a single field.
ordinal smallint NOT NULL,
value jsonb NOT NULL,
-- confirmed: the candidate typed or confirmed the value. extracted: a
-- suggestion from an imported source that nobody confirmed.
status text NOT NULL,
-- manual, or an import origin (planned: extracted_from_resume, imported).
origin text NOT NULL,
-- Every claim of the profile has trust level 0 whatever its origin;
-- higher levels belong to evidence, which is stored elsewhere. The column
-- states the rule in the schema, so an import can never store a claim
-- with a higher level.
trust_level smallint NOT NULL,
-- Excerpt of the imported document that the value came from. It can hold
-- personal data. NULL for a manual value.
quote text,
-- Opaque label of the extractor version. NULL for a manual value.
extraction_version text,
-- When the candidate typed or confirmed the value; NULL while it is an
-- unconfirmed suggestion.
confirmed_at timestamptz,
CONSTRAINT candidate_profile_claims_pkey PRIMARY KEY (
user_id, kind, ordinal
),
-- The claims belong to the profile row and go with it.
CONSTRAINT candidate_profile_claims_user_id_fkey FOREIGN KEY (
user_id
) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE,
CONSTRAINT candidate_profile_claims_kind_ordinal CHECK (
(
kind IN (
'full_name',
'contact_email',
'contact_phone',
'contact_telegram',
'terms_location',
'terms_relocation',
'terms_salary_minimum'
)
AND ordinal = 0
)
OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29)
OR (kind = 'role' AND ordinal BETWEEN 0 AND 8)
OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19)
OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9)
),
CONSTRAINT candidate_profile_claims_status_known CHECK (
status IN ('confirmed', 'extracted')
),
CONSTRAINT candidate_profile_claims_origin_known CHECK (
origin IN ('manual', 'extracted_from_resume', 'imported')
),
CONSTRAINT candidate_profile_claims_trust_level_zero CHECK (
trust_level = 0
),
-- A confirmed value says when; a suggestion does not.
CONSTRAINT candidate_profile_claims_confirmation CHECK (
(status = 'confirmed' AND confirmed_at IS NOT NULL)
OR (status = 'extracted' AND confirmed_at IS NULL)
),
-- A manual value is confirmed by definition and has no import data. An
-- imported value names its extractor, and an unconfirmed one is always
-- an import.
CONSTRAINT candidate_profile_claims_origin_provenance CHECK (
(
origin = 'manual'
AND status = 'confirmed'
AND quote IS NULL
AND extraction_version IS NULL
)
OR (origin <> 'manual' AND extraction_version IS NOT NULL)
),
CONSTRAINT candidate_profile_claims_quote_format CHECK (
quote IS NULL OR (
char_length(quote) BETWEEN 1 AND 300
AND translate(quote, E'\n', '') !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_extraction_version_format CHECK (
extraction_version IS NULL
OR extraction_version ~ '^[A-Za-z0-9._-]{1,64}$'
),
-- Value shapes. The bounds repeat the schemas of the public contract.
CONSTRAINT candidate_profile_claims_full_name_value CHECK (
kind <> 'full_name' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 200
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_contact_email_value CHECK (
kind <> 'contact_email' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 3 AND 254
AND value #>> '{}' ~ '^[^@\s]+@[^@\s]+$'
)
),
-- E.164, the format of the contact disclosure.
CONSTRAINT candidate_profile_claims_contact_phone_value CHECK (
kind <> 'contact_phone' OR (
jsonb_typeof(value) = 'string'
AND value #>> '{}' ~ '^\+[1-9][0-9]{6,14}$'
)
),
CONSTRAINT candidate_profile_claims_contact_telegram_value CHECK (
kind <> 'contact_telegram' OR (
jsonb_typeof(value) = 'string'
AND value #>> '{}' ~ '^@[A-Za-z0-9_]{5,32}$'
)
),
CONSTRAINT candidate_profile_claims_stack_value CHECK (
kind <> 'stack' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 50
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_soft_skill_value CHECK (
kind <> 'soft_skill' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 50
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_terms_location_value CHECK (
kind <> 'terms_location' OR (
jsonb_typeof(value) = 'string'
AND char_length(value #>> '{}') BETWEEN 1 AND 100
AND value #>> '{}' !~ '^\s|\s$'
AND value #>> '{}' !~ '[[:cntrl:]]'
)
),
CONSTRAINT candidate_profile_claims_terms_relocation_value CHECK (
kind <> 'terms_relocation' OR jsonb_typeof(value) = 'boolean'
),
-- A positive multiple of 1000 up to 100 000 000, in the only currency,
-- period, and tax bases of the MVP.
CONSTRAINT candidate_profile_claims_terms_salary_minimum_value CHECK (
kind <> 'terms_salary_minimum' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY['amount', 'currency', 'period', 'tax_basis']
AND value - 'amount' - 'currency' - 'period' - 'tax_basis'
= '{}'::jsonb
AND jsonb_typeof(value -> 'amount') = 'number'
AND value ->> 'amount' ~ '^([1-9][0-9]{0,4}000|100000000)$'
AND value -> 'currency' = '"RUB"'::jsonb
AND value -> 'period' = '"month"'::jsonb
AND value ->> 'tax_basis' IN ('net', 'gross')
)
),
-- The self-assessed grade is a claim of the role. A confirmed grade is not
-- a key of the value.
CONSTRAINT candidate_profile_claims_role_value CHECK (
kind <> 'role' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY['specialization', 'self_assessed_grade']
AND value - 'specialization' - 'self_assessed_grade' = '{}'::jsonb
AND value ->> 'specialization' IN (
'backend',
'frontend',
'mobile',
'network_engineer',
'devops_sre',
'data_analyst',
'ds_ml',
'information_security',
'qa'
)
AND (
jsonb_typeof(value -> 'self_assessed_grade') = 'null'
OR value ->> 'self_assessed_grade' IN (
'intern', 'junior', 'middle', 'senior'
)
)
)
),
CONSTRAINT candidate_profile_claims_experience_value CHECK (
kind <> 'experience' OR (
jsonb_typeof(value) = 'object'
AND value ?& ARRAY[
'employer_name',
'specialization',
'started_on',
'ended_on',
'summary'
]
AND value - 'employer_name' - 'specialization' - 'started_on'
- 'ended_on' - 'summary' = '{}'::jsonb
AND value ->> 'specialization' IN (
'backend',
'frontend',
'mobile',
'network_engineer',
'devops_sre',
'data_analyst',
'ds_ml',
'information_security',
'qa'
)
AND jsonb_typeof(value -> 'started_on') = 'string'
AND value ->> 'started_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND (
jsonb_typeof(value -> 'ended_on') = 'null'
OR (
jsonb_typeof(value -> 'ended_on') = 'string'
AND value ->> 'ended_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$'
AND value ->> 'ended_on' >= value ->> 'started_on'
)
)
AND (
jsonb_typeof(value -> 'employer_name') = 'null'
OR (
jsonb_typeof(value -> 'employer_name') = 'string'
AND char_length(value ->> 'employer_name') BETWEEN 1 AND 200
AND value ->> 'employer_name' !~ '^\s|\s$'
AND value ->> 'employer_name' !~ '[[:cntrl:]]'
)
)
AND (
jsonb_typeof(value -> 'summary') = 'null'
OR (
jsonb_typeof(value -> 'summary') = 'string'
AND char_length(value ->> 'summary') BETWEEN 1 AND 1000
AND value ->> 'summary' !~ '^\s|\s$'
AND translate(value ->> 'summary', E'\n', '')
!~ '[[:cntrl:]]'
)
)
)
)
);
-- A tag or a skill appears once and a specialization appears in one role. The
-- indexes compare the stored text exactly; the case-insensitive comparison
-- of the contract belongs to the domain, because PostgreSQL lower() depends
-- on the collation.
CREATE UNIQUE INDEX candidate_profile_claims_stack_key
ON candidate_profile_claims (user_id, (value #>> '{}'))
WHERE kind = 'stack';
CREATE UNIQUE INDEX candidate_profile_claims_soft_skill_key
ON candidate_profile_claims (user_id, (value #>> '{}'))
WHERE kind = 'soft_skill';
CREATE UNIQUE INDEX candidate_profile_claims_role_specialization_key
ON candidate_profile_claims (user_id, (value ->> 'specialization'))
WHERE kind = 'role';
-- +goose Down
DROP TABLE candidate_profile_claims;
DROP TABLE candidate_profiles;
+102
View File
@@ -0,0 +1,102 @@
-- Queries of the manual candidate profile (TASK-066). The profile is personal
-- data of the account that owns it: every statement is scoped by user_id, and
-- no statement selects another account's row. None of them names a file, the
-- ML service, or an FSP account, because the profile needs none.
-- Stores the first save of a profile at version 1. No row returns when the
-- account already has a profile, so a first save that lost a race with
-- another first save from another tab can be told apart and answered as a
-- version conflict.
-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
user_id,
version,
created_at,
updated_at
) VALUES (
sqlc.arg(user_id),
1,
sqlc.arg(at),
sqlc.arg(at)
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, created_at, updated_at;
-- Advances the version over the one the caller read, in the same statement.
-- The row lock it takes serializes concurrent saves of one profile. The update
-- time never moves back: an application clock behind the stored time (clock
-- skew between instances) keeps the stored time, which the CHECK
-- candidate_profiles_updated_after_creation also requires. No row
-- returns for a stale version or for an account without a profile, which the
-- caller answers as a version conflict.
-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
version = candidate_profiles.version + 1,
updated_at = GREATEST(candidate_profiles.updated_at, sqlc.arg(at))
WHERE
candidate_profiles.user_id = sqlc.arg(user_id)
AND candidate_profiles.version = sqlc.arg(expected_version)
RETURNING user_id, version, created_at, updated_at;
-- Reads the profile row of an account together with every claim in one
-- statement, so the version and the claims come from one snapshot: a save that
-- commits between two separate reads could pair version N with the claims of
-- N+1. A profile without a claim returns one row with NULL claim columns, and
-- no row at all means the account has not saved a profile (contract version
-- 0). Claims come in a stable order: single fields by kind, list items by
-- position. Never replace this with two statements.
-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
candidate_profiles.version,
candidate_profiles.created_at,
candidate_profiles.updated_at,
candidate_profile_claims.kind,
candidate_profile_claims.ordinal,
candidate_profile_claims.value,
candidate_profile_claims.status,
candidate_profile_claims.origin,
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
WHERE candidate_profiles.user_id = sqlc.arg(user_id)
ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal;
-- Removes the claims that a save replaces. The adapter calls it after the
-- version advanced and before it inserts the new set, in one transaction.
-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = sqlc.arg(user_id);
-- Stores one claim of the new set. Provenance fields are the domain's; the
-- statement never takes a trust level from the caller, because every claim
-- has level 0.
-- name: InsertCandidateProfileClaim :exec
INSERT INTO candidate_profile_claims (
user_id,
kind,
ordinal,
value,
status,
origin,
trust_level,
quote,
extraction_version,
confirmed_at
) VALUES (
sqlc.arg(user_id),
sqlc.arg(kind),
sqlc.arg(ordinal),
sqlc.arg(value),
sqlc.arg(status),
sqlc.arg(origin),
0,
sqlc.narg(quote),
sqlc.narg(extraction_version),
sqlc.narg(confirmed_at)
);
@@ -0,0 +1,612 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
)
const (
candidateProfileTestTimeout = 3 * time.Minute
// concurrentProfileSaves advance one profile at once from the same
// version, each on its own connection.
concurrentProfileSaves = 8
// candidateProfileMigrationVersion creates candidateProfileTables.
candidateProfileMigrationVersion = 13
)
var (
candidateProfilesTable = pgx.Identifier{"candidate_profiles"}
candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"}
// candidateProfileTables reference users, so a TRUNCATE of users names
// them through usersDependentTables.
candidateProfileTables = []pgx.Identifier{candidateProfileClaimsTable, candidateProfilesTable}
)
// candidateProfileFixture works on the bootstrap database. The tables are
// truncated between subtests.
type candidateProfileFixture struct {
ctx context.Context
pool *pgxpool.Pool
queries *sqlc.Queries
identity identityFixture
now time.Time
}
func TestCandidateProfileStorage(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := candidateProfileFixture{
ctx: ctx,
pool: pool,
queries: sqlc.New(pool),
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
now: now,
}
reset := func(t *testing.T) {
t.Helper()
truncateTables(ctx, t, pool, usersDependentTables...)
}
t.Run("saves a profile without a file, the ML service, or an FSP account", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
// Only the name: no resume, no import, no link of any kind.
saved := fixture.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision("Anna Sokolova"),
}, 0)
if saved.Version() != 1 {
t.Fatalf("saved version = %d, want 1 for the first save", saved.Version())
}
read := fixture.load(t, candidate.ID)
name, ok := read.Content().FullName()
if !ok || name.Value() != "Anna Sokolova" || name.Source().Origin() != domain.ProfileOriginManual || name.Source().TrustLevel() != 0 {
t.Fatalf("stored name = %v, want a manual claim of trust level 0", ok)
}
if _, ok := read.Content().Phone(); ok {
t.Fatal("a field that was not sent came back set")
}
// A profile row with no claim at all is allowed too.
other := fixture.candidate(t, "empty@example.com")
fixture.save(t, other.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Placeholder")}, 0)
fixture.save(t, other.ID, domain.CandidateProfileInput{}, 1)
if empty := fixture.load(t, other.ID); empty.Version() != 2 || !empty.Content().Equal(domain.CandidateProfileContent{}) {
t.Fatalf("empty profile = version %d, want version 2 with no claim", empty.Version())
}
})
t.Run("a complete profile survives the round trip with its provenance", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
input := domain.CandidateProfileInput{
FullName: confirmedDecision("Анна Соколова"),
Email: confirmedDecision("anna.sokolova@example.com"),
Phone: confirmedDecision("+79000000000"),
Telegram: confirmedDecision("@anna_sokolova"),
Stack: []domain.ProfileClaimInput[string]{{Value: "PostgreSQL", Status: domain.ProfileClaimConfirmed}, {Value: "Kafka", Status: domain.ProfileClaimConfirmed}},
Roles: []domain.ProfileClaimInput[domain.ProfileRole]{
{Value: domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeMiddle}, Status: domain.ProfileClaimConfirmed},
{Value: domain.ProfileRole{Specialization: domain.SpecializationQA}, Status: domain.ProfileClaimConfirmed},
},
Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{
Value: domain.ProfileExperience{EmployerName: "Example Payments", Specialization: domain.SpecializationBackend, StartedOn: "2022-03", Summary: "Первая строка\nВторая строка"},
Status: domain.ProfileClaimConfirmed,
}, {
Value: domain.ProfileExperience{Specialization: domain.SpecializationQA, StartedOn: "2020-01", EndedOn: "2022-02"},
Status: domain.ProfileClaimConfirmed,
}},
SoftSkills: []domain.ProfileClaimInput[string]{{Value: "Mentoring", Status: domain.ProfileClaimConfirmed}},
Location: confirmedDecision("Казань"),
Relocation: confirmedDecision(true),
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 180000, TaxBasis: domain.ProfileTaxNet}),
}
saved := fixture.save(t, candidate.ID, input, 0)
read := fixture.load(t, candidate.ID)
if !read.Content().Equal(saved.Content()) || read.Version() != 1 || !read.CreatedAt().Equal(fixture.now) || !read.UpdatedAt().Equal(fixture.now) {
t.Fatalf("read profile = version %d, equal %v, want the saved content at version 1", read.Version(), read.Content().Equal(saved.Content()))
}
// A suggestion stored by an import keeps its provenance, and the
// candidate's confirmation keeps it and adds the time.
fixture.insertSuggestion(t, candidate.ID, "contact_phone", 0, `"+79000001111"`)
withSuggestion := fixture.load(t, candidate.ID)
suggestion, ok := withSuggestion.Content().Phone()
if !ok || suggestion.Status() != domain.ProfileClaimExtracted || suggestion.Source().Quote() != "Tel.: +7 900 000-11-11" ||
suggestion.Source().ExtractionVersion() != "resume-rules.2026-10.1" || suggestion.Source().TrustLevel() != 0 {
t.Fatal("the stored suggestion lost its provenance")
}
})
t.Run("the tables hold no link to a file, the ML service, or an FSP account", func(t *testing.T) {
reset(t)
rows, err := pool.Query(ctx, `
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name IN ('candidate_profiles', 'candidate_profile_claims')`)
if err != nil {
t.Fatalf("select columns: %v", err)
}
defer rows.Close()
var columns []string
for rows.Next() {
var table, column string
if err := rows.Scan(&table, &column); err != nil {
t.Fatalf("scan column: %v", err)
}
columns = append(columns, table+"."+column)
}
if err := rows.Err(); err != nil {
t.Fatalf("read columns: %v", err)
}
slices.Sort(columns)
want := []string{
"candidate_profile_claims.confirmed_at", "candidate_profile_claims.extraction_version", "candidate_profile_claims.kind",
"candidate_profile_claims.ordinal", "candidate_profile_claims.origin", "candidate_profile_claims.quote",
"candidate_profile_claims.status", "candidate_profile_claims.trust_level", "candidate_profile_claims.user_id",
"candidate_profile_claims.value",
"candidate_profiles.created_at", "candidate_profiles.updated_at", "candidate_profiles.user_id", "candidate_profiles.version",
}
if !slices.Equal(columns, want) {
t.Fatalf("columns = %v, want exactly %v: no file, ML, FSP, grade, or category column", columns, want)
}
// The only foreign keys point at the account and at the profile row.
var references []string
fkRows, err := pool.Query(ctx, `
SELECT conrelid::regclass::text || ' -> ' || confrelid::regclass::text
FROM pg_constraint
WHERE contype = 'f' AND conrelid IN ('candidate_profiles'::regclass, 'candidate_profile_claims'::regclass)`)
if err != nil {
t.Fatalf("select foreign keys: %v", err)
}
defer fkRows.Close()
for fkRows.Next() {
var reference string
if err := fkRows.Scan(&reference); err != nil {
t.Fatalf("scan foreign key: %v", err)
}
references = append(references, reference)
}
slices.Sort(references)
if !slices.Equal(references, []string{"candidate_profile_claims -> candidate_profiles", "candidate_profiles -> users"}) {
t.Fatalf("foreign keys = %v, want only the account and the profile row", references)
}
})
t.Run("constraints refuse a claim that breaks a rule of the contract", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
type claim struct {
kind, value, status, origin string
ordinal int
trust int
quote, extraction *string
confirmed bool
}
good := claim{kind: "stack", value: `"Go"`, status: "confirmed", origin: "manual", ordinal: 5, confirmed: true}
tests := []struct {
name string
mutate func(*claim)
constraint string
}{
{"trust level above zero", func(c *claim) { c.trust = 1 }, "candidate_profile_claims_trust_level_zero"},
{"unknown kind", func(c *claim) { c.kind = "confirmed_grade" }, "candidate_profile_claims_kind_ordinal"},
{"single field at a position", func(c *claim) { c.kind, c.value, c.ordinal = "full_name", `"Anna"`, 1 }, "candidate_profile_claims_kind_ordinal"},
{"list past its limit", func(c *claim) { c.ordinal = 30 }, "candidate_profile_claims_kind_ordinal"},
// Also breaks the confirmation rule, which sorts first.
{"unknown status", func(c *claim) { c.status = "verified" }, "candidate_profile_claims_confirmation"},
{"unknown origin", func(c *claim) { c.origin = "fsp" }, "candidate_profile_claims_origin_known"},
{"confirmed without a time", func(c *claim) { c.confirmed = false }, "candidate_profile_claims_confirmation"},
{"manual with a quote", func(c *claim) { q := "quote"; c.quote = &q }, "candidate_profile_claims_origin_provenance"},
{"import without an extractor version", func(c *claim) { c.origin = "imported" }, "candidate_profile_claims_origin_provenance"},
{"suggestion that is manual", func(c *claim) { c.status, c.confirmed = "extracted", false }, "candidate_profile_claims_origin_provenance"},
{"extractor version with a space", func(c *claim) { v := "a b"; c.origin, c.extraction = "imported", &v }, "candidate_profile_claims_extraction_version_format"},
{"stack tag with surrounding whitespace", func(c *claim) { c.value = `" Go"` }, "candidate_profile_claims_stack_value"},
{"stack tag that is not a string", func(c *claim) { c.value = `12` }, "candidate_profile_claims_stack_value"},
{"phone outside E.164", func(c *claim) { c.kind, c.value, c.ordinal = "contact_phone", `"8 900 000"`, 0 }, "candidate_profile_claims_contact_phone_value"},
{"telegram without the at sign", func(c *claim) { c.kind, c.value, c.ordinal = "contact_telegram", `"anna"`, 0 }, "candidate_profile_claims_contact_telegram_value"},
{"relocation that is not a boolean", func(c *claim) { c.kind, c.value, c.ordinal = "terms_relocation", `"yes"`, 0 }, "candidate_profile_claims_terms_relocation_value"},
{"salary that is not a multiple of 1000", func(c *claim) {
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180500,"currency":"RUB","period":"month","tax_basis":"net"}`, 0
}, "candidate_profile_claims_terms_salary_minimum_value"},
{"salary in another currency", func(c *claim) {
c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`, 0
}, "candidate_profile_claims_terms_salary_minimum_value"},
{"role with a confirmed grade key", func(c *claim) {
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`, 0
}, "candidate_profile_claims_role_value"},
{"role with an unknown grade", func(c *claim) {
c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":"lead"}`, 0
}, "candidate_profile_claims_role_value"},
{"experience that ends before it starts", func(c *claim) {
c.kind, c.ordinal = "experience", 0
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-05","ended_on":"2024-04","summary":null}`
}, "candidate_profile_claims_experience_value"},
{"experience month out of range", func(c *claim) {
c.kind, c.ordinal = "experience", 0
c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-13","ended_on":null,"summary":null}`
}, "candidate_profile_claims_experience_value"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
c := good
test.mutate(&c)
err := fixture.insertRaw(candidate.ID, c.kind, c.ordinal, c.value, c.status, c.origin, c.trust, c.quote, c.extraction, c.confirmed)
assertConstraintViolation(t, err, "23514", test.constraint)
})
}
// The same row without the mutation is accepted, so each refusal
// above comes from its own rule.
if err := fixture.insertRaw(candidate.ID, good.kind, good.ordinal, good.value, good.status, good.origin, 0, nil, nil, true); err != nil {
t.Fatalf("insert of the valid claim error = %v", err)
}
})
t.Run("a tag, a skill, and a role specialization are stored once", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
insert := func(kind string, ordinal int, value string) error {
return fixture.insertRaw(candidate.ID, kind, ordinal, value, "confirmed", "manual", 0, nil, nil, true)
}
if err := insert("stack", 0, `"Go"`); err != nil {
t.Fatalf("insert tag error = %v", err)
}
assertConstraintViolation(t, insert("stack", 1, `"Go"`), "23505", "candidate_profile_claims_stack_key")
if err := insert("soft_skill", 0, `"Mentoring"`); err != nil {
t.Fatalf("insert skill error = %v", err)
}
assertConstraintViolation(t, insert("soft_skill", 1, `"Mentoring"`), "23505", "candidate_profile_claims_soft_skill_key")
if err := insert("role", 0, `{"specialization":"backend","self_assessed_grade":null}`); err != nil {
t.Fatalf("insert role error = %v", err)
}
assertConstraintViolation(t, insert("role", 1, `{"specialization":"backend","self_assessed_grade":"junior"}`), "23505", "candidate_profile_claims_role_specialization_key")
assertConstraintViolation(t, insert("role", 0, `{"specialization":"qa","self_assessed_grade":null}`), "23505", "candidate_profile_claims_pkey")
})
t.Run("a profile needs an account and claims need a profile", func(t *testing.T) {
reset(t)
err := fixture.insertRawProfile(uuid.Must(uuid.NewV7()), 1)
assertConstraintViolation(t, err, "23503", "candidate_profiles_user_id_fkey")
candidate := fixture.candidate(t, "candidate@example.com")
assertConstraintViolation(t, fixture.insertRawProfile(candidate.ID, 0), "23514", "candidate_profiles_version_positive")
err = fixture.insertRaw(candidate.ID, "full_name", 0, `"Anna"`, "confirmed", "manual", 0, nil, nil, true)
assertConstraintViolation(t, err, "23503", "candidate_profile_claims_user_id_fkey")
})
t.Run("erasing the account removes the profile and its claims", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision("Anna"), Phone: confirmedDecision("+79000000000"),
}, 0)
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); err != nil {
t.Fatalf("delete the account: %v", err)
}
for _, table := range candidateProfileTables {
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM `+table.Sanitize()).Scan(&count); err != nil || count != 0 {
t.Fatalf("%s rows after the erasure = %d, %v, want 0", table[0], count, err)
}
}
})
t.Run("the version guards against a lost concurrent edit", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
// A second first save loses: the row exists.
if _, err := fixture.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)}); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("second InsertCandidateProfile() error = %v, want no row", err)
}
// A stale expected version matches no row.
stale := sqlc.AdvanceCandidateProfileVersionParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 7, At: pgTime(now)}
if _, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, stale); !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("AdvanceCandidateProfileVersion(stale) error = %v, want no row", err)
}
if got := fixture.load(t, candidate.ID).Version(); got != 1 {
t.Fatalf("version after a stale advance = %d, want 1", got)
}
// Eight savers read version 1 and race: exactly one wins.
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
queries := sqlc.New(pool)
var (
group sync.WaitGroup
mutex sync.Mutex
winners int
)
for range concurrentProfileSaves {
group.Go(func() {
_, err := queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(time.Minute)),
})
mutex.Lock()
defer mutex.Unlock()
switch {
case err == nil:
winners++
case !errors.Is(err, pgx.ErrNoRows):
t.Errorf("AdvanceCandidateProfileVersion() error = %v", err)
}
})
}
group.Wait()
if winners != 1 {
t.Fatalf("%d concurrent saves advanced version 1, want exactly one", winners)
}
if got := fixture.load(t, candidate.ID).Version(); got != 2 {
t.Fatalf("version after the race = %d, want 2", got)
}
})
t.Run("two concurrent first saves: one wins and the other sees a conflict", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves)
queries := sqlc.New(pool)
var (
group sync.WaitGroup
mutex sync.Mutex
winners int
losers int
)
for range concurrentProfileSaves {
group.Go(func() {
_, err := queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)})
mutex.Lock()
defer mutex.Unlock()
switch {
case err == nil:
winners++
case errors.Is(err, pgx.ErrNoRows):
losers++ // the caller answers version_conflict
default:
t.Errorf("InsertCandidateProfile() error = %v", err)
}
})
}
group.Wait()
if winners != 1 || losers != concurrentProfileSaves-1 {
t.Fatalf("first saves: %d won and %d lost, want one winner and the rest conflicts", winners, losers)
}
})
t.Run("an earlier application clock never violates the update time rule", func(t *testing.T) {
reset(t)
candidate := fixture.candidate(t, "candidate@example.com")
fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0)
advanced, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{
UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(-time.Hour)),
})
if err != nil {
t.Fatalf("AdvanceCandidateProfileVersion(earlier time) error = %v, want no CHECK violation", err)
}
if advanced.Version != 2 || !advanced.UpdatedAt.Time.Equal(now) {
t.Fatalf("advanced = version %d at %v, want version 2 keeping %v", advanced.Version, advanced.UpdatedAt.Time, now)
}
})
t.Run("each account keeps its own profile", func(t *testing.T) {
reset(t)
first := fixture.candidate(t, "first@example.com")
second := fixture.candidate(t, "second@example.com")
fixture.save(t, first.ID, domain.CandidateProfileInput{FullName: confirmedDecision("First Person")}, 0)
fixture.save(t, second.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Second Person")}, 0)
name, _ := fixture.load(t, second.ID).Content().FullName()
if name.Value() != "Second Person" {
t.Fatal("an account read the profile of another account")
}
})
}
func TestCandidateProfileMigrationRollsBack(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
assertTablesExist(ctx, t, pool, true, "candidate_profiles", "candidate_profile_claims")
for {
result, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("DownOne() error = %v", err)
}
if result.Version == candidateProfileMigrationVersion {
break
}
}
assertTablesExist(ctx, t, pool, false, "candidate_profiles", "candidate_profile_claims")
assertTablesExist(ctx, t, pool, true, "users")
}
func confirmedDecision[V comparable](value V) *domain.ProfileClaimInput[V] {
return &domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed}
}
func pgTime(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} }
func (fixture candidateProfileFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-time.Hour))
}
// save applies input to the stored profile with the domain rules and stores
// the result the way a repository does: a first save inserts version 1, and a
// later one advances the version over expectedVersion and replaces the
// claims, in one transaction.
func (fixture candidateProfileFixture) save(t *testing.T, userID uuid.UUID, input domain.CandidateProfileInput, expectedVersion int64) domain.CandidateProfile {
t.Helper()
profile := fixture.loadOrEmpty(t, userID)
if profile.Version() != expectedVersion {
t.Fatalf("stored version = %d, want %d", profile.Version(), expectedVersion)
}
updated, _, err := profile.Replace(input, expectedVersion, fixture.now)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
rows, err := updated.Content().StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
tx, err := fixture.pool.Begin(fixture.ctx)
if err != nil {
t.Fatalf("begin: %v", err)
}
defer func() { _ = tx.Rollback(fixture.ctx) }()
queries := fixture.queries.WithTx(tx)
id := pgtype.UUID{Bytes: userID, Valid: true}
if expectedVersion == 0 {
_, err = queries.InsertCandidateProfile(fixture.ctx, sqlc.InsertCandidateProfileParams{UserID: id, At: pgTime(fixture.now)})
} else {
_, err = queries.AdvanceCandidateProfileVersion(fixture.ctx, sqlc.AdvanceCandidateProfileVersionParams{UserID: id, ExpectedVersion: expectedVersion, At: pgTime(fixture.now)})
}
if err != nil {
t.Fatalf("store the profile row: %v", err)
}
if err := queries.DeleteCandidateProfileClaims(fixture.ctx, id); err != nil {
t.Fatalf("delete claims: %v", err)
}
for _, row := range rows {
err := queries.InsertCandidateProfileClaim(fixture.ctx, sqlc.InsertCandidateProfileClaimParams{
UserID: id, Kind: row.Kind, Ordinal: int16(row.Ordinal), Value: row.Value, Status: row.Status, Origin: row.Origin,
Quote: optionalText(row.Quote), ExtractionVersion: optionalText(row.ExtractionVersion), ConfirmedAt: optionalTime(row.ConfirmedAt),
})
if err != nil {
t.Fatalf("insert claim %s: %v", row.Kind, err)
}
}
if err := tx.Commit(fixture.ctx); err != nil {
t.Fatalf("commit: %v", err)
}
return fixture.load(t, userID)
}
func optionalText(value string) pgtype.Text { return pgtype.Text{String: value, Valid: value != ""} }
func optionalTime(value time.Time) pgtype.Timestamptz {
return pgtype.Timestamptz{Time: value, Valid: !value.IsZero()}
}
// loadOrEmpty reads the profile with the one statement a repository uses, so
// the version and the claims come from one snapshot. An account without a
// profile gets the empty profile of version 0.
func (fixture candidateProfileFixture) loadOrEmpty(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
t.Helper()
rows, err := fixture.queries.ReadCandidateProfile(fixture.ctx, pgtype.UUID{Bytes: userID, Valid: true})
if err != nil {
t.Fatalf("ReadCandidateProfile() error = %v", err)
}
if len(rows) == 0 {
empty, err := domain.EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
return empty
}
stored := domain.StoredCandidateProfile{UserID: userID, Version: rows[0].Version, CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time}
for _, row := range rows {
if !row.Kind.Valid {
continue // a profile without claims: the LEFT JOIN row has none
}
stored.Claims = append(stored.Claims, domain.StoredProfileClaim{
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value, Status: row.Status.String, Origin: row.Origin.String,
TrustLevel: int(row.TrustLevel.Int16), Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String,
ConfirmedAt: row.ConfirmedAt.Time,
})
}
profile, err := domain.RestoreCandidateProfile(stored)
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
return profile
}
func (fixture candidateProfileFixture) load(t *testing.T, userID uuid.UUID) domain.CandidateProfile {
t.Helper()
profile := fixture.loadOrEmpty(t, userID)
if profile.Version() == 0 {
t.Fatal("the account has no stored profile")
}
return profile
}
// insertSuggestion stores an unconfirmed claim of an import, which no
// operation produces yet, over the stored one of the same kind and position.
func (fixture candidateProfileFixture) insertSuggestion(t *testing.T, userID uuid.UUID, kind string, ordinal int, value string) {
t.Helper()
quote, version := "Tel.: +7 900 000-11-11", "resume-rules.2026-10.1"
if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM candidate_profile_claims WHERE user_id = $1 AND kind = $2 AND ordinal = $3`, userID, kind, ordinal); err != nil {
t.Fatalf("remove the stored claim: %v", err)
}
if err := fixture.insertRaw(userID, kind, ordinal, value, "extracted", "extracted_from_resume", 0, &quote, &version, false); err != nil {
t.Fatalf("insert the suggestion: %v", err)
}
}
func (fixture candidateProfileFixture) insertRaw(
userID uuid.UUID, kind string, ordinal int, value, status, origin string, trust int, quote, extraction *string, confirmed bool,
) error {
var confirmedAt any
if confirmed {
confirmedAt = fixture.now
}
_, err := fixture.pool.Exec(fixture.ctx, `
INSERT INTO candidate_profile_claims
(user_id, kind, ordinal, value, status, origin, trust_level, quote, extraction_version, confirmed_at)
VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10)`,
userID, kind, ordinal, value, status, origin, trust, quote, extraction, confirmedAt)
return err
}
func (fixture candidateProfileFixture) insertRawProfile(userID uuid.UUID, version int64) error {
_, err := fixture.pool.Exec(fixture.ctx,
`INSERT INTO candidate_profiles (user_id, version, created_at, updated_at) VALUES ($1, $2, $3, $3)`,
userID, version, fixture.now)
return err
}
// assertConstraintViolation checks the SQLSTATE and the constraint name, never
// the message: a failing row can quote the personal data it held. PostgreSQL
// reports the first failing CHECK in name order, so a row that breaks two
// rules names the one that sorts first; a caller lists the acceptable ones.
func assertConstraintViolation(t *testing.T, err error, code string, constraints ...string) {
t.Helper()
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
t.Fatalf("error = %v, want a PostgreSQL error %s on %v", err, code, constraints)
}
if pgError.Code != code || !slices.Contains(constraints, pgError.ConstraintName) {
t.Fatalf("error = %s on %q, want %s on one of %v", pgError.Code, pgError.ConstraintName, code, constraints)
}
}
@@ -41,7 +41,7 @@ var (
// usersDependentTables is every table that references users, directly or
// through another table of the list. A TRUNCATE of users must name all of
// them, so a migration that adds such a table adds it here.
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables)
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables)
)
// organizationFixture works on the bootstrap database. The tables are
@@ -21,6 +21,7 @@ var regexMap = map[string]ogenregex.Regexp{
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
@@ -4239,6 +4239,208 @@ func (s *Server) handleGetMyInvitationRequest(args [1]string, argsEscaped bool,
}
}
// handleGetMyProfileRequest handles GetMyProfile operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
// a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
func (s *Server) handleGetMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMyProfile"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/profile"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyProfileOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetMyProfileOperation,
ID: "GetMyProfile",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetMyProfileOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
var rawBody []byte
var response GetMyProfileRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetMyProfileOperation,
OperationSummary: "Read the private profile of the current candidate.",
OperationID: "GetMyProfile",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = GetMyProfileRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetMyProfile(ctx)
return response, err
},
)
} else {
response, err = s.h.GetMyProfile(ctx)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetMyProfileResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetMyQuestionnaireRequest handles GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -8055,6 +8257,269 @@ func (s *Server) handleResendEmailVerificationRequest(args [0]string, argsEscape
}
}
// handleSaveMyProfileRequest handles SaveMyProfile operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The body is the complete new state of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read,
// 0 for the first save. If it is not the current version, the server answers 412 version_conflict and
// changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (s *Server) handleSaveMyProfileRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("SaveMyProfile"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/api/v1/me/profile"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), SaveMyProfileOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: SaveMyProfileOperation,
ID: "SaveMyProfile",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, SaveMyProfileOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, SaveMyProfileOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
var rawBody []byte
request, rawBody, close, err := s.decodeSaveMyProfileRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response SaveMyProfileRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: SaveMyProfileOperation,
OperationSummary: "Replace the private profile of the current candidate.",
OperationID: "SaveMyProfile",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = *CandidateProfileUpdate
Params = struct{}
Response = SaveMyProfileRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.SaveMyProfile(ctx, request)
return response, err
},
)
} else {
response, err = s.h.SaveMyProfile(ctx, request)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeSaveMyProfileResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleSaveMyQuestionnaireRequest handles SaveMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -69,6 +69,10 @@ type GetMyInvitationRes interface {
getMyInvitationRes()
}
type GetMyProfileRes interface {
getMyProfileRes()
}
type GetMyQuestionnaireRes interface {
getMyQuestionnaireRes()
}
@@ -137,6 +141,10 @@ type ResendEmailVerificationRes interface {
resendEmailVerificationRes()
}
type SaveMyProfileRes interface {
saveMyProfileRes()
}
type SaveMyQuestionnaireRes interface {
saveMyQuestionnaireRes()
}
File diff suppressed because it is too large. Load diff
@@ -24,6 +24,7 @@ const (
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
@@ -42,6 +43,7 @@ const (
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RegisterAccountOperation OperationName = "RegisterAccount"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
@@ -1120,6 +1120,85 @@ func (s *Server) decodeResendEmailVerificationRequest(r *http.Request) (
}
}
func (s *Server) decodeSaveMyProfileRequest(r *http.Request) (
req *CandidateProfileUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request CandidateProfileUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeSaveMyQuestionnaireRequest(r *http.Request) (
req *CandidateQuestionnaireUpdate,
rawBody []byte,
@@ -1766,6 +1766,65 @@ func encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseW
}
}
func encodeGetMyProfileResponse(response GetMyProfileRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateProfileHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyProfileUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyProfileForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyQuestionnaireResponse(response GetMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
@@ -3178,6 +3237,89 @@ func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes,
}
}
func encodeSaveMyProfileResponse(response SaveMyProfileRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateProfileHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyProfileBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyProfileUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyProfileForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *SaveMyProfilePreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeSaveMyQuestionnaireResponse(response SaveMyQuestionnaireRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateQuestionnaireHeaders:
@@ -11,16 +11,16 @@ import (
)
var (
rn48AllowedHeaders = map[string]string{
rn49AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn7AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn46AllowedHeaders = map[string]string{
rn47AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn43AllowedHeaders = map[string]string{
rn44AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn25AllowedHeaders = map[string]string{
@@ -29,7 +29,7 @@ var (
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn51AllowedHeaders = map[string]string{
rn52AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn20AllowedHeaders = map[string]string{
@@ -44,12 +44,15 @@ var (
rn17AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn52AllowedHeaders = map[string]string{
rn53AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn31AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn32AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
@@ -62,22 +65,22 @@ var (
rn14AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn35AllowedHeaders = map[string]string{
rn36AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn45AllowedHeaders = map[string]string{
rn46AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn50AllowedHeaders = map[string]string{
rn51AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
rn54AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn16AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn38AllowedHeaders = map[string]string{
rn39AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
)
@@ -234,7 +237,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn48AllowedHeaders,
allowedHeaders: rn49AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -311,7 +314,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn46AllowedHeaders,
allowedHeaders: rn47AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -335,7 +338,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn43AllowedHeaders,
allowedHeaders: rn44AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -488,7 +491,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn51AllowedHeaders,
allowedHeaders: rn52AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -779,7 +782,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn52AllowedHeaders,
allowedHeaders: rn53AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -819,6 +822,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 'p': // Prefix: "profile"
if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r)
case "PUT":
s.handleSaveMyProfileRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn31AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
@@ -837,7 +867,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PUT",
allowedHeaders: rn31AllowedHeaders,
allowedHeaders: rn32AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1049,7 +1079,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn35AllowedHeaders,
allowedHeaders: rn36AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -1129,7 +1159,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn45AllowedHeaders,
allowedHeaders: rn46AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1157,7 +1187,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn50AllowedHeaders,
allowedHeaders: rn51AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1187,7 +1217,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn53AllowedHeaders,
allowedHeaders: rn54AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1265,7 +1295,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn38AllowedHeaders,
allowedHeaders: rn39AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
@@ -2080,6 +2110,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 'p': // Prefix: "profile"
if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetMyProfileOperation
r.summary = "Read the private profile of the current candidate."
r.operationID = "GetMyProfile"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/profile"
r.args = args
r.count = 0
return r, true
case "PUT":
r.name = SaveMyProfileOperation
r.summary = "Replace the private profile of the current candidate."
r.operationID = "SaveMyProfile"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/profile"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case 'q': // Prefix: "questionnaire"
if l := len("questionnaire"); len(elem) >= l && elem[0:l] == "questionnaire" {
File diff suppressed because it is too large. Load diff
@@ -71,6 +71,7 @@ var operationRolesSessionCookie = map[string][]string{
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
@@ -85,6 +86,7 @@ var operationRolesSessionCookie = map[string][]string{
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
@@ -129,6 +131,7 @@ var operationRolesSessionCsrf = map[string][]string{
FinalizeMyAssessmentAttemptOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
@@ -603,6 +603,29 @@ type Handler interface {
//
// GET /api/v1/me/invitations/{invitation_id}
GetMyInvitation(ctx context.Context, params GetMyInvitationParams) (GetMyInvitationRes, error)
// GetMyProfile implements GetMyProfile operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
// a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
GetMyProfile(ctx context.Context) (GetMyProfileRes, error)
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -1038,6 +1061,57 @@ type Handler interface {
//
// POST /api/v1/identity/email-verification-requests
ResendEmailVerification(ctx context.Context, req *EmailVerificationResendRequest) (ResendEmailVerificationRes, error)
// SaveMyProfile implements SaveMyProfile operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The body is the complete new state of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read,
// 0 for the first save. If it is not the current version, the server answers 412 version_conflict and
// changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (SaveMyProfileRes, error)
// SaveMyQuestionnaire implements SaveMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -662,6 +662,32 @@ func (UnimplementedHandler) GetMyInvitation(ctx context.Context, params GetMyInv
return r, ht.ErrNotImplemented
}
// GetMyProfile implements GetMyProfile operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
// a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every
// single field `unknown`, and empty lists rather than 404, so the client reads the version for the
// first save in the same way as for later ones and a missing profile is not an error state.
//
// The profile is personal data that only its owner reads: full name, contacts, work history, and the
// lowest salary. It is a private resource and never an organization-visible one; organizations see a
// candidate through the anonymous card and, after an accepted invitation, through the contact grant,
// and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and
// the server never writes its values to logs, metrics, URLs, or events.
//
// Every value carries its confirmation state and provenance, and every claim has trust level 0. The
// self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results
// establish and which no request writes. The profile needs no file, no ML extraction, and no FSP
// account.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
// answers 403 forbidden.
//
// GET /api/v1/me/profile
func (UnimplementedHandler) GetMyProfile(ctx context.Context) (r GetMyProfileRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyQuestionnaire implements GetMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, never from
@@ -1151,6 +1177,60 @@ func (UnimplementedHandler) ResendEmailVerification(ctx context.Context, req *Em
return r, ht.ErrNotImplemented
}
// SaveMyProfile implements SaveMyProfile operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
// and an allowed Origin. The body is the complete new state of every field and list; see
// CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole.
//
// Every field is optional in substance: a profile can be saved with any subset filled and the rest
// null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or
// link. Which fields are needed to leave the onboarding step candidate_profile is an open product
// question that this contract does not decide; a save on that step advancing the account to
// candidate_questionnaire is planned.
//
// Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion
// keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level,
// confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed
// grade never becomes a confirmed grade or a category.
//
// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read,
// 0 for the first save. If it is not the current version, the server answers 412 version_conflict and
// changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent
// edit from another tab or device is never lost silently. The version travels in the body rather than
// in If-Match because the generated client cannot read the ETag response header yet, as for the
// questionnaire; the status and code are the same as for a failed If-Match.
//
// The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose
// values equal the stored ones, with the same decisions, changes nothing, keeps the version, and
// answers 200 with the current profile even when `expected_version` is older, so a retry after a lost
// response of a successful save succeeds instead of failing with 412. A version above the current one
// never existed and always answers 412 version_conflict, even for an unchanged body.
//
// The save replaces the stored claims as a whole. A suggestion that an import stored and that the
// client did not render and send back with the decision `extracted` is dropped by the save; a client
// therefore sends every suggestion that it received, and a client that read an older version gets 412
// instead of silently dropping a suggestion it never saw.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for an employer), a version above the current one (412), domain
// rules that depend on the body alone (400), then the rules that depend on the stored claims against
// the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when
// `expected_version` is stale, because another save may have confirmed that value, and 400 when it is
// current; an unchanged body (200); any other change over a stale version (412). The schema rejects an
// unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username
// without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is
// not a positive multiple of 1000, and more items than a list allows. The server also rejects a
// repeated tag, skill, or role specialization, a period that ends before it starts or lies in the
// future, and a decision `extracted` for a value that is not a stored suggestion, with 400
// validation_failed and pointers to the items, for example `/roles/1/specialization` or
// `/stack/1/status`. Error bodies never repeat a submitted value.
//
// PUT /api/v1/me/profile
func (UnimplementedHandler) SaveMyProfile(ctx context.Context, req *CandidateProfileUpdate) (r SaveMyProfileRes, _ error) {
return r, ht.ErrNotImplemented
}
// SaveMyQuestionnaire implements SaveMyQuestionnaire operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,455 @@
package httpadapter
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"slices"
"strings"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
)
const profilePath = "/api/v1/me/profile"
// isProfileSchema names the schemas that exist only for the private candidate
// profile. The schemas it shares with other contracts, such as the contact
// value formats, do not match.
func isProfileSchema(name string) bool {
return name == "CandidateProfile" || name == "CandidateProfileUpdate" || strings.HasPrefix(name, "Profile")
}
func propertyNames(schema *ogen.Schema) []string {
names := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
names = append(names, property.Name)
}
slices.Sort(names)
return names
}
func hasSecurity(operation *ogen.Operation, scheme string) bool {
return slices.ContainsFunc(operation.Security, func(requirement ogen.SecurityRequirement) bool {
_, ok := requirement[scheme]
return ok
})
}
// A save of the profile follows the project conventions of a versioned
// replacement: session and CSRF, the version in the body, 412 for a stale one
// and no Idempotency-Key, because replacing the whole state is idempotent.
func TestCandidateProfileOperationsFollowTheConventions(t *testing.T) {
spec := parsePublicContract(t)
get := operationByID(t, spec, "GetMyProfile")
if !hasSecurity(get, "sessionCookie") || hasSecurity(get, "sessionCsrf") {
t.Errorf("GetMyProfile security = %v, want the session cookie only", get.Security)
}
save := operationByID(t, spec, "SaveMyProfile")
if !hasSecurity(save, "sessionCookie") || !hasSecurity(save, "sessionCsrf") {
t.Errorf("SaveMyProfile security = %v, want the session cookie and the CSRF token", save.Security)
}
for _, status := range []string{"400", "401", "403", "412"} {
if _, ok := save.Responses[status]; !ok {
t.Errorf("SaveMyProfile does not declare %s", status)
}
}
if _, ok := save.Responses["409"]; ok {
t.Error("SaveMyProfile declares 409: a stale version is 412 version_conflict")
}
for _, status := range []string{"401", "403"} {
if _, ok := get.Responses[status]; !ok {
t.Errorf("GetMyProfile does not declare %s", status)
}
}
for _, operation := range []*ogen.Operation{get, save} {
for _, parameter := range operation.Parameters {
if strings.EqualFold(parameter.Name, "Idempotency-Key") || strings.EqualFold(parameter.Name, "If-Match") {
t.Errorf("%s takes %s, want the version in the body", operation.OperationID, parameter.Name)
}
}
ok := operation.Responses["200"]
if ok == nil || ok.Headers["Cache-Control"] == nil {
t.Errorf("%s does not mark its 200 response no-store", operation.OperationID)
}
}
update := resolveSchema(t, spec, save.RequestBody.Content["application/json"].Schema)
if !slices.Contains(update.Required, "expected_version") {
t.Error("the profile update does not require expected_version")
}
version := resolveSchema(t, spec, schemaProperty(t, update, "expected_version"))
if string(version.Minimum) != "0" {
t.Error("expected_version does not start at 0, the version of a profile never saved")
}
problem412 := save.Responses["412"]
if problem412 == nil || problem412.Ref == "" {
t.Error("the 412 response is not a reusable response")
}
}
// The self-assessed grade of a role and the confirmed category are different
// facts: only an assessment result confirms a category, so no request carries
// one and every profile claim stays unverified.
func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *testing.T) {
spec := parsePublicContract(t)
profile := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"})
if !slices.Contains(profile.Required, "confirmed_categories") {
t.Error("the profile does not state confirmed categories apart from the claims")
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"})
wantUpdate := []string{"contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
if got := propertyNames(update); !slices.Equal(got, wantUpdate) {
t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate)
}
role := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItemInput"})
if got := propertyNames(role); !slices.Equal(got, []string{"self_assessed_grade", "specialization", "status"}) {
t.Errorf("ProfileRoleItemInput properties = %v, want the self-assessed grade only", got)
}
storedRole := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItem"})
for _, forbidden := range []string{"confirmed_grade", "category", "grade"} {
if slices.Contains(propertyNames(storedRole), forbidden) {
t.Errorf("ProfileRoleItem has %q: a role holds the claim, never a confirmed grade", forbidden)
}
}
category := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileConfirmedCategory"})
for _, field := range []string{"specialization", "grade", "confirmed_at", "attempt_id"} {
if !slices.Contains(category.Required, field) {
t.Errorf("ProfileConfirmedCategory does not require %s: a confirmed category names its assessment", field)
}
}
// The same grade scale and specialization codes as the catalog and the
// questionnaire, not copies of them.
for _, test := range []struct {
schema, property, ref string
}{
{"ProfileConfirmedCategory", "grade", "#/components/schemas/GradeCode"},
{"ProfileConfirmedCategory", "specialization", "#/components/schemas/SpecializationCode"},
{"ProfileRoleItemInput", "specialization", "#/components/schemas/SpecializationCode"},
{"ProfileStackItemInput", "tag", "#/components/schemas/StackTag"},
} {
parent := spec.Components.Schemas[test.schema]
if got := schemaProperty(t, parent, test.property); got.Ref != test.ref {
t.Errorf("%s.%s = %q, want a reference to %s", test.schema, test.property, got.Ref, test.ref)
}
}
// A request cannot set provenance, a trust level, or a confirmed
// category: the request schemas close their objects and name none.
for name, schema := range spec.Components.Schemas {
if !isProfileSchema(name) {
continue
}
if schema.Type == "object" && (schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool) {
t.Errorf("%s accepts unknown fields", name)
}
if !strings.HasSuffix(name, "Input") && name != "CandidateProfileUpdate" {
continue
}
for _, forbidden := range []string{"source", "trust_level", "origin", "confirmed_at", "confirmed_categories", "confirmed_grade", "category", "quote", "extraction_version"} {
if slices.Contains(propertyNames(schema), forbidden) {
t.Errorf("%s accepts %q from the client", name, forbidden)
}
}
}
}
// Every value of the profile carries its confirmation state and its source,
// and the source gives imported claims trust level 0.
func TestCandidateProfileClaimsCarrySourceAndTrustLevelZero(t *testing.T) {
spec := parsePublicContract(t)
source := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimSource"})
for _, field := range []string{"origin", "trust_level", "quote", "extraction_version", "confirmed_at"} {
if !slices.Contains(source.Required, field) {
t.Errorf("ProfileClaimSource does not require %s", field)
}
}
trust := resolveSchema(t, spec, schemaProperty(t, source, "trust_level"))
if string(trust.Minimum) != "0" || string(trust.Maximum) != "0" {
t.Errorf("trust_level range = %s..%s, want exactly 0", trust.Minimum, trust.Maximum)
}
origins := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimOrigin"}))
for _, origin := range []string{"manual", "extracted_from_resume", "imported"} {
if !slices.Contains(origins, origin) {
t.Errorf("ProfileClaimOrigin has no %s", origin)
}
}
for _, name := range []string{
"ProfileFullNameClaim", "ProfileEmailClaim", "ProfilePhoneClaim", "ProfileTelegramClaim",
"ProfileLocationClaim", "ProfileRelocationClaim", "ProfileSalaryMinimumClaim",
} {
claim := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
for _, field := range []string{"status", "value", "source"} {
if !slices.Contains(claim.Required, field) {
t.Errorf("%s does not require %s", name, field)
}
}
}
for _, name := range []string{"ProfileStackItem", "ProfileSoftSkillItem", "ProfileRoleItem", "ProfileExperienceItem"} {
item := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
for _, field := range []string{"status", "source"} {
if !slices.Contains(item.Required, field) {
t.Errorf("%s does not require %s", name, field)
}
}
itemSource := schemaProperty(t, spec.Components.Schemas[name], "source")
if itemSource.Ref != "#/components/schemas/ProfileClaimSource" {
t.Errorf("%s.source = %q, want the shared ProfileClaimSource", name, itemSource.Ref)
}
}
// Contacts reuse the formats of the contact disclosure, so a disclosure
// never has to convert a stored value.
for _, test := range []struct{ schema, ref string }{
{"ProfileFullNameClaim", "#/components/schemas/ContactFullName"},
{"ProfilePhoneClaim", "#/components/schemas/ContactPhoneNumber"},
{"ProfileTelegramClaim", "#/components/schemas/ContactTelegramUsername"},
} {
value := schemaProperty(t, spec.Components.Schemas[test.schema], "value")
if len(value.OneOf) == 0 || value.OneOf[0].Ref != test.ref {
t.Errorf("%s.value = %+v, want %s", test.schema, value, test.ref)
}
}
}
// componentsIndex returns the components of the contract as generic JSON, so
// a reference can be followed by its pointer whatever its kind.
func componentsIndex(t *testing.T, spec *ogen.Spec) map[string]any {
t.Helper()
encoded, err := json.Marshal(spec.Components)
if err != nil {
t.Fatalf("encode the components: %v", err)
}
var kinds map[string]map[string]any
if err := json.Unmarshal(encoded, &kinds); err != nil {
t.Fatalf("decode the components: %v", err)
}
index := map[string]any{}
for kind, components := range kinds {
for name, component := range components {
index["#/components/"+kind+"/"+name] = component
}
}
return index
}
func collectReferences(value any, found *[]string) {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if reference, ok := child.(string); ok && key == "$ref" {
*found = append(*found, reference)
continue
}
collectReferences(child, found)
}
case []any:
for _, child := range typed {
collectReferences(child, found)
}
}
}
// reachableSchemas returns the schema names that start reaches by references.
func reachableSchemas(index map[string]any, start any) map[string]bool {
reached := map[string]bool{}
var pending []string
collectReferences(start, &pending)
for len(pending) > 0 {
reference := pending[len(pending)-1]
pending = pending[:len(pending)-1]
if reached[reference] {
continue
}
reached[reference] = true
if component, ok := index[reference]; ok {
collectReferences(component, &pending)
}
}
names := map[string]bool{}
for reference := range reached {
if name, ok := strings.CutPrefix(reference, "#/components/schemas/"); ok {
names[name] = true
}
}
return names
}
// The private profile holds personal data that an organization must never
// read, so no schema that an organization can see may refer to it, and the
// profile schemas refer to nothing of an organization. The check follows
// references through request bodies, responses, parameters, and headers.
func TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs(t *testing.T) {
spec := parsePublicContract(t)
index := componentsIndex(t, spec)
// The profile family is not empty and its operations reach it.
profileOperations := reachableSchemas(index, mustJSONValue(t, spec.Paths[profilePath]))
if !profileOperations["CandidateProfile"] || !profileOperations["CandidateProfileUpdate"] {
t.Fatalf("the profile path reaches %v, want CandidateProfile and CandidateProfileUpdate", profileOperations)
}
// No schema outside the profile family refers to a profile schema.
for name, schema := range spec.Components.Schemas {
if isProfileSchema(name) {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
if isProfileSchema(reached) {
t.Errorf("%s reaches the private profile schema %s", name, reached)
}
}
}
// No operation of an organization, and none that an organization can
// read, reaches a profile schema.
for path, item := range spec.Paths {
if !strings.HasPrefix(path, "/api/v1/organizations") {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, item)) {
if isProfileSchema(reached) {
t.Errorf("%s reaches the private profile schema %s", path, reached)
}
}
}
// The family refers to no organization, invitation, or need schema except
// the shared money and label leaves it reuses.
shared := []string{"RubAmount", "CurrencyCode", "SalaryPeriod", "SalaryTaxBasis", "NeedVersionLabel"}
for name, schema := range spec.Components.Schemas {
if !isProfileSchema(name) {
continue
}
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
isOrganizationSide := strings.HasPrefix(reached, "Organization") || strings.HasPrefix(reached, "Invitation") ||
strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "CandidateOrganization") || reached == "ContactDisclosure"
if isOrganizationSide && !slices.Contains(shared, reached) {
t.Errorf("%s reaches the organization-side schema %s", name, reached)
}
}
}
}
func mustJSONValue(t *testing.T, value any) any {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatalf("encode a contract value: %v", err)
}
var decoded any
if err := json.Unmarshal(encoded, &decoded); err != nil {
t.Fatalf("decode a contract value: %v", err)
}
return decoded
}
// The generated DTOs keep claims and the private profile apart from the
// organization DTOs at the Go type level too.
func TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests(t *testing.T) {
for _, dto := range []any{api.CandidateProfileUpdate{}, api.ProfileRoleItemInput{}, api.ProfileStackItemInput{}, api.ProfileExperienceItemInput{}} {
assertNoJSONFields(t, dto, []string{
"confirmed_grade", "category", "confirmed_categories", "trust_level", "source", "origin", "version", "updated_at",
})
}
assertNoJSONFields(t, api.ProfileRoleItem{}, []string{"confirmed_grade", "category", "grade", "trust_level"})
}
// The profile operations are in the contract before their business logic: a
// schema failure answers 400 before anything else, a valid request with an
// accepted session answers 501, and a denied session answers 401.
func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) {
const (
stackItem = `{"tag":"PostgreSQL","status":"confirmed"}`
roleItem = `{"specialization":"backend","self_assessed_grade":"middle","status":"confirmed"}`
)
body := func(replace ...string) string {
document := `{"expected_version":0,` +
`"full_name":{"value":"Anna Sokolova","status":"confirmed"},` +
`"contacts":{"email":null,"phone":{"value":"+79000000000","status":"confirmed"},"telegram":null},` +
`"stack":[` + stackItem + `],"roles":[` + roleItem + `],"experience":[],"soft_skills":[],` +
`"terms":{"location":null,"relocation":null,"salary_minimum":{"value":{"amount":180000,"currency":"RUB","period":"month","tax_basis":"net"},"status":"confirmed"}}}`
for index := 0; index+1 < len(replace); index += 2 {
if !strings.Contains(document, replace[index]) {
t.Fatalf("body has no %q to replace", replace[index])
}
document = strings.Replace(document, replace[index], replace[index+1], 1)
}
return document
}
for _, test := range []struct {
name string
body string
statusCode int
pointer string
code string
}{
{name: "a valid profile", body: body(), statusCode: http.StatusNotImplemented},
{name: "a profile saved with nothing set", body: `{"expected_version":3,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`, statusCode: http.StatusNotImplemented},
{name: "missing expected version", body: body(`"expected_version":0,`, ""), statusCode: http.StatusBadRequest, pointer: "/expected_version", code: "required"},
{name: "phone outside E.164", body: body(`+79000000000`, `8 900 000 00 00`), statusCode: http.StatusBadRequest, pointer: "/contacts/phone/value", code: "invalid"},
{name: "decision outside confirmed and extracted", body: body(`"status":"confirmed"}],"roles"`, `"status":"unknown"}],"roles"`), statusCode: http.StatusBadRequest, pointer: "/stack/0/status", code: "invalid"},
{name: "salary not a multiple of 1000", body: body(`180000`, `180500`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/amount", code: "invalid"},
{name: "salary in another currency", body: body(`"RUB"`, `"USD"`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/currency", code: "invalid"},
{name: "grade outside the scale", body: body(`"middle"`, `"lead"`), statusCode: http.StatusBadRequest, pointer: "/roles/0/self_assessed_grade", code: "invalid"},
{name: "confirmed grade sent in a role", body: body(roleItem, strings.Replace(roleItem, `"status"`, `"confirmed_grade":"senior","status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/roles", code: "invalid"},
{name: "confirmed categories sent by the client", body: body(`"experience":[]`, `"experience":[],"confirmed_categories":[]`), statusCode: http.StatusBadRequest, pointer: "", code: "invalid"},
{name: "provenance sent by the client", body: body(stackItem, strings.Replace(stackItem, `"status"`, `"source":{"origin":"imported"},"status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/stack", code: "invalid"},
} {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPut, path: profilePath, body: test.body,
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
})
if test.statusCode == http.StatusNotImplemented {
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
return
}
problemBody := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code}
for _, field := range problemBody.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", problemBody.Errors, want)
})
}
}
func TestProfileAccessBeforeImplementation(t *testing.T) {
for _, test := range []struct {
name string
request identityRequest
}{
{"read without a session", identityRequest{method: http.MethodGet, path: profilePath}},
{"save with a denied session", identityRequest{
method: http.MethodPut, path: profilePath,
body: `{"expected_version":0,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`,
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
}},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test.request), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
@@ -0,0 +1,237 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: candidate.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const advanceCandidateProfileVersion = `-- name: AdvanceCandidateProfileVersion :one
UPDATE candidate_profiles
SET
version = candidate_profiles.version + 1,
updated_at = GREATEST(candidate_profiles.updated_at, $1)
WHERE
candidate_profiles.user_id = $2
AND candidate_profiles.version = $3
RETURNING user_id, version, created_at, updated_at
`
type AdvanceCandidateProfileVersionParams struct {
At pgtype.Timestamptz
UserID pgtype.UUID
ExpectedVersion int64
}
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
// skew between instances) keeps the stored time, which the CHECK
// candidate_profiles_updated_after_creation also requires. No row
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
func (q *Queries) AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error) {
row := q.db.QueryRow(ctx, advanceCandidateProfileVersion, arg.At, arg.UserID, arg.ExpectedVersion)
var i CandidateProfile
err := row.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteCandidateProfileClaims = `-- name: DeleteCandidateProfileClaims :exec
DELETE FROM candidate_profile_claims
WHERE user_id = $1
`
// Removes the claims that a save replaces. The adapter calls it after the
// version advanced and before it inserts the new set, in one transaction.
func (q *Queries) DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteCandidateProfileClaims, userID)
return err
}
const insertCandidateProfile = `-- name: InsertCandidateProfile :one
INSERT INTO candidate_profiles (
user_id,
version,
created_at,
updated_at
) VALUES (
$1,
1,
$2,
$2
)
ON CONFLICT (user_id) DO NOTHING
RETURNING user_id, version, created_at, updated_at
`
type InsertCandidateProfileParams struct {
UserID pgtype.UUID
At pgtype.Timestamptz
}
// Queries of the manual candidate profile (TASK-066). The profile is personal
// data of the account that owns it: every statement is scoped by user_id, and
// no statement selects another account's row. None of them names a file, the
// ML service, or an FSP account, because the profile needs none.
// Stores the first save of a profile at version 1. No row returns when the
// account already has a profile, so a first save that lost a race with
// another first save from another tab can be told apart and answered as a
// version conflict.
func (q *Queries) InsertCandidateProfile(ctx context.Context, arg InsertCandidateProfileParams) (CandidateProfile, error) {
row := q.db.QueryRow(ctx, insertCandidateProfile, arg.UserID, arg.At)
var i CandidateProfile
err := row.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertCandidateProfileClaim = `-- name: InsertCandidateProfileClaim :exec
INSERT INTO candidate_profile_claims (
user_id,
kind,
ordinal,
value,
status,
origin,
trust_level,
quote,
extraction_version,
confirmed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
0,
$7,
$8,
$9
)
`
type InsertCandidateProfileClaimParams struct {
UserID pgtype.UUID
Kind string
Ordinal int16
Value []byte
Status string
Origin string
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
// Stores one claim of the new set. Provenance fields are the domain's; the
// statement never takes a trust level from the caller, because every claim
// has level 0.
func (q *Queries) InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error {
_, err := q.db.Exec(ctx, insertCandidateProfileClaim,
arg.UserID,
arg.Kind,
arg.Ordinal,
arg.Value,
arg.Status,
arg.Origin,
arg.Quote,
arg.ExtractionVersion,
arg.ConfirmedAt,
)
return err
}
const readCandidateProfile = `-- name: ReadCandidateProfile :many
SELECT
candidate_profiles.user_id,
candidate_profiles.version,
candidate_profiles.created_at,
candidate_profiles.updated_at,
candidate_profile_claims.kind,
candidate_profile_claims.ordinal,
candidate_profile_claims.value,
candidate_profile_claims.status,
candidate_profile_claims.origin,
candidate_profile_claims.trust_level,
candidate_profile_claims.quote,
candidate_profile_claims.extraction_version,
candidate_profile_claims.confirmed_at
FROM candidate_profiles
LEFT JOIN candidate_profile_claims
ON candidate_profile_claims.user_id = candidate_profiles.user_id
WHERE candidate_profiles.user_id = $1
ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal
`
type ReadCandidateProfileRow struct {
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Kind pgtype.Text
Ordinal pgtype.Int2
Value []byte
Status pgtype.Text
Origin pgtype.Text
TrustLevel pgtype.Int2
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
// N+1. A profile without a claim returns one row with NULL claim columns, and
// no row at all means the account has not saved a profile (contract version
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
func (q *Queries) ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error) {
rows, err := q.db.Query(ctx, readCandidateProfile, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReadCandidateProfileRow
for rows.Next() {
var i ReadCandidateProfileRow
if err := rows.Scan(
&i.UserID,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.Kind,
&i.Ordinal,
&i.Value,
&i.Status,
&i.Origin,
&i.TrustLevel,
&i.Quote,
&i.ExtractionVersion,
&i.ConfirmedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -42,6 +42,26 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type CandidateProfile struct {
UserID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type CandidateProfileClaim struct {
UserID pgtype.UUID
Kind string
Ordinal int16
Value []byte
Status string
Origin string
TrustLevel int16
Quote pgtype.Text
ExtractionVersion pgtype.Text
ConfirmedAt pgtype.Timestamptz
}
type ConsentRecord struct {
ID pgtype.UUID
SubjectID pgtype.UUID
@@ -14,6 +14,14 @@ type Querier interface {
// Adds recipients to the day and the month row. The caller holds their
// locks from LockMailQuotaRows and has checked both limits.
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
// Advances the version over the one the caller read, in the same statement.
// The row lock it takes serializes concurrent saves of one profile. The update
// time never moves back: an application clock behind the stored time (clock
// skew between instances) keeps the stored time, which the CHECK
// candidate_profiles_updated_after_creation also requires. No row
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
@@ -77,6 +85,9 @@ type Querier interface {
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
// Removes the claims that a save replaces. The adapter calls it after the
// version advanced and before it inserts the new set, in one transaction.
DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
@@ -201,6 +212,19 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
// Queries of the manual candidate profile (TASK-066). The profile is personal
// data of the account that owns it: every statement is scoped by user_id, and
// no statement selects another account's row. None of them names a file, the
// ML service, or an FSP account, because the profile needs none.
// Stores the first save of a profile at version 1. No row returns when the
// account already has a profile, so a first save that lost a race with
// another first save from another tab can be told apart and answered as a
// version conflict.
InsertCandidateProfile(ctx context.Context, arg InsertCandidateProfileParams) (CandidateProfile, error)
// Stores one claim of the new set. Provenance fields are the domain's; the
// statement never takes a trust level from the caller, because every claim
// has level 0.
InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
// subject, purpose, and text version already exists when no row returns;
// the insert then changes nothing and does not abort the transaction.
@@ -342,6 +366,14 @@ type Querier interface {
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
// N+1. A profile without a claim returns one row with NULL claim columns, and
// no row at all means the account has not saved a profile (contract version
// 0). Claims come in a stable order: single fields by kind, list items by
// position. Never replace this with two statements.
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
// Advances a delivery past one attempt and appends the attempt in one
// statement, so both happen or neither does, inside or outside a
// transaction. The update applies only while the stored version still
File diff suppressed because it is too large. Load diff
+564
View File
@@ -0,0 +1,564 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var candidateTestTime = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
// confirmed wraps a value as a confirmed decision.
func confirmed[V comparable](value V) *ProfileClaimInput[V] {
return &ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed}
}
func confirmedItems[V comparable](values ...V) []ProfileClaimInput[V] {
items := make([]ProfileClaimInput[V], 0, len(values))
for _, value := range values {
items = append(items, ProfileClaimInput[V]{Value: value, Status: ProfileClaimConfirmed})
}
return items
}
func completeCandidateProfileInput() CandidateProfileInput {
return CandidateProfileInput{
FullName: confirmed("Anna Sokolova"),
Email: confirmed("anna.sokolova@example.com"),
Phone: confirmed("+79000000000"),
Telegram: confirmed("@anna_sokolova"),
Stack: confirmedItems("PostgreSQL", "Kafka"),
Roles: confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeMiddle}),
Experience: confirmedItems(ProfileExperience{
EmployerName: "Example Payments", Specialization: SpecializationBackend,
StartedOn: "2022-03", Summary: "Moved the payout service to an event model.",
}),
SoftSkills: confirmedItems("Mentoring"),
Location: confirmed("Kazan"),
Relocation: confirmed(false),
SalaryMinimum: confirmed(ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}),
}
}
func mustCandidateContent(t *testing.T, stored CandidateProfileContent, input CandidateProfileInput, at time.Time) CandidateProfileContent {
t.Helper()
content, err := ResolveCandidateProfileContent(stored, input, at)
if err != nil {
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
}
return content
}
// suggestedContent builds stored content with imported, unconfirmed claims
// the way storage restores them, because no operation produces them yet.
func suggestedContent(t *testing.T) CandidateProfileContent {
t.Helper()
suggestion := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{
Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "extracted", Origin: "extracted_from_resume",
Quote: "from the resume", ExtractionVersion: "resume-rules.2026-10.1",
}
}
content, err := RestoreCandidateProfileContent([]StoredProfileClaim{
suggestion(profileKindPhone, 0, `"+79000000000"`),
suggestion(profileKindStack, 0, `"Kafka"`),
suggestion(profileKindStack, 1, `"gRPC"`),
})
if err != nil {
t.Fatalf("RestoreCandidateProfileContent() error = %v", err)
}
return content
}
func TestResolveCandidateProfileContentStoresManualClaimsWithTrustLevelZero(t *testing.T) {
content := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
name, ok := content.FullName()
if !ok || name.Value() != "Anna Sokolova" || name.Status() != ProfileClaimConfirmed {
t.Fatalf("full name = %v, %v, want a confirmed claim", name.Value(), ok)
}
source := name.Source()
if source.Origin() != ProfileOriginManual || source.TrustLevel() != 0 || source.Quote() != "" ||
source.ExtractionVersion() != "" || !source.ConfirmedAt().Equal(candidateTestTime) {
t.Fatalf("source = origin %s, trust %d, confirmed %v, want a manual claim at the save time", source.Origin(), source.TrustLevel(), source.ConfirmedAt())
}
salary, ok := content.SalaryMinimum()
if !ok || salary.Value() != (ProfileSalaryMinimum{Amount: 180000, TaxBasis: ProfileTaxNet}) {
t.Fatalf("salary minimum = %v, %v, want the given amount", salary.Value(), ok)
}
if roles := content.Roles(); len(roles) != 1 || roles[0].Value().SelfAssessedGrade != GradeMiddle {
t.Fatalf("roles = %d, want the self-assessed role", len(roles))
}
if len(content.Stack()) != 2 || len(content.SoftSkills()) != 1 || len(content.Experience()) != 1 {
t.Fatal("lists were not stored")
}
for _, claim := range content.Stack() {
if claim.Source().TrustLevel() != ProfileClaimTrustLevel {
t.Fatalf("trust level = %d, want %d for every claim", claim.Source().TrustLevel(), ProfileClaimTrustLevel)
}
}
}
func TestResolveCandidateProfileContentLeavesAbsentFieldsUnknown(t *testing.T) {
stored := mustCandidateContent(t, CandidateProfileContent{}, completeCandidateProfileInput(), candidateTestTime)
content := mustCandidateContent(t, stored, CandidateProfileInput{}, candidateTestTime.Add(time.Hour))
if _, ok := content.FullName(); ok {
t.Fatal("a field sent as null kept its value, want it removed")
}
if _, ok := content.SalaryMinimum(); ok {
t.Fatal("a salary sent as null kept its value, want it removed")
}
if len(content.Stack()) != 0 || len(content.Roles()) != 0 {
t.Fatal("an empty list kept its items, want the list replaced")
}
}
func TestSuggestionsStayUnconfirmedUntilTheCandidateConfirmsThem(t *testing.T) {
stored := suggestedContent(t)
phone, _ := stored.Phone()
if phone.Status() != ProfileClaimExtracted || phone.Source().TrustLevel() != 0 || !phone.Source().ConfirmedAt().IsZero() {
t.Fatalf("restored suggestion = %v, trust %d, want an unconfirmed claim of trust level 0", phone.Status(), phone.Source().TrustLevel())
}
later := candidateTestTime.Add(time.Hour)
t.Run("extracted keeps a stored suggestion unconfirmed and unchanged", func(t *testing.T) {
input := CandidateProfileInput{
Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted},
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "gRPC", Status: ProfileClaimExtracted}},
}
content := mustCandidateContent(t, stored, input, later)
if !content.Equal(stored) {
t.Fatal("a form sent back unchanged altered the stored suggestions")
}
})
t.Run("confirmed confirms a suggestion and keeps its origin and quote", func(t *testing.T) {
input := CandidateProfileInput{Phone: confirmed("+79000000000"), Stack: confirmedItems("Kafka")}
content := mustCandidateContent(t, stored, input, later)
phone, _ := content.Phone()
source := phone.Source()
if phone.Status() != ProfileClaimConfirmed || source.Origin() != ProfileOriginExtractedFromResume ||
source.Quote() != "from the resume" || source.ExtractionVersion() != "resume-rules.2026-10.1" ||
!source.ConfirmedAt().Equal(later) || source.TrustLevel() != 0 {
t.Fatalf("confirmed suggestion = %s from %s, want confirmed at %v with the import provenance and trust level 0", phone.Status(), source.Origin(), later)
}
})
t.Run("confirmed with another value makes the claim manual", func(t *testing.T) {
content := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000001")}, later)
phone, _ := content.Phone()
if phone.Source().Origin() != ProfileOriginManual || phone.Source().Quote() != "" {
t.Fatalf("changed suggestion origin = %s, want manual without the old quote", phone.Source().Origin())
}
})
t.Run("extracted for a value that is not a stored suggestion is refused", func(t *testing.T) {
input := CandidateProfileInput{
Stack: []ProfileClaimInput[string]{{Value: "Kafka", Status: ProfileClaimExtracted}, {Value: "Made up", Status: ProfileClaimExtracted}},
}
assertProfileFieldError(t, resolveErr(stored, input, later), "/stack/1/status")
})
t.Run("a confirmed value cannot go back to a suggestion", func(t *testing.T) {
confirmedStored := mustCandidateContent(t, stored, CandidateProfileInput{Phone: confirmed("+79000000000")}, later)
input := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
assertProfileFieldError(t, resolveErr(confirmedStored, input, later), "/contacts/phone/status")
})
}
func resolveErr(stored CandidateProfileContent, input CandidateProfileInput, at time.Time) error {
_, err := ResolveCandidateProfileContent(stored, input, at)
return err
}
func assertProfileFieldError(t *testing.T, err error, pointer string) {
t.Helper()
var fieldError *CandidateProfileFieldError
if !errors.Is(err, ErrInvalidCandidateProfile) || !errors.As(err, &fieldError) {
t.Fatalf("error = %v, want ErrInvalidCandidateProfile with a field pointer", err)
}
if fieldError.Pointer != pointer {
t.Fatalf("pointer = %q, want %q (reason %q)", fieldError.Pointer, pointer, fieldError.Reason)
}
}
func TestResolveCandidateProfileContentRejectsInvalidValuesWithPointers(t *testing.T) {
long := strings.Repeat("a", 201)
tests := []struct {
name string
mutate func(*CandidateProfileInput)
pointer string
}{
{"full name with surrounding whitespace", func(in *CandidateProfileInput) { in.FullName = confirmed(" Anna") }, "/full_name/value"},
{"full name too long", func(in *CandidateProfileInput) { in.FullName = confirmed(long) }, "/full_name/value"},
{"email without a domain", func(in *CandidateProfileInput) { in.Email = confirmed("anna") }, "/contacts/email/value"},
{"phone outside E.164", func(in *CandidateProfileInput) { in.Phone = confirmed("8 900 000 00 00") }, "/contacts/phone/value"},
{"telegram without the at sign", func(in *CandidateProfileInput) { in.Telegram = confirmed("anna_sokolova") }, "/contacts/telegram/value"},
{"status missing", func(in *CandidateProfileInput) { in.FullName = &ProfileClaimInput[string]{Value: "Anna"} }, "/full_name/status"},
{"location with a line break", func(in *CandidateProfileInput) { in.Location = confirmed("Kazan\nTatarstan") }, "/terms/location/value"},
{"salary below the step", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180500, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary above the bound", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 101_000_000, TaxBasis: ProfileTaxNet})
}, "/terms/salary_minimum/value/amount"},
{"salary without a tax basis", func(in *CandidateProfileInput) {
in.SalaryMinimum = confirmed(ProfileSalaryMinimum{Amount: 180000})
}, "/terms/salary_minimum/value/tax_basis"},
{"stack tag with surrounding whitespace", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Go", "Kafka ") }, "/stack/1/tag"},
{"stack tag repeated without regard to case", func(in *CandidateProfileInput) { in.Stack = confirmedItems("Kafka", "go", "KAFKA") }, "/stack/2/tag"},
{"too many tags", func(in *CandidateProfileInput) {
in.Stack = confirmedItems(make([]string, maxProfileStackItems+1)...)
}, "/stack"},
{"soft skill repeated", func(in *CandidateProfileInput) { in.SoftSkills = confirmedItems("Mentoring", "mentoring") }, "/soft_skills/1/skill"},
{"role with an unknown specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: "go"})
}, "/roles/0/specialization"},
{"role with an unknown grade", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: "lead"})
}, "/roles/0/self_assessed_grade"},
{"role repeats a specialization", func(in *CandidateProfileInput) {
in.Roles = confirmedItems(ProfileRole{Specialization: SpecializationBackend}, ProfileRole{Specialization: SpecializationQA}, ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior})
}, "/roles/2/specialization"},
{"experience month in a wrong format", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-3"})
}, "/experience/0/started_on"},
{"experience ends before it starts", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", EndedOn: "2024-04"})
}, "/experience/0/ended_on"},
{"experience starts in the future", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2026-11"})
}, "/experience/0/started_on"},
{"experience summary too long", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: strings.Repeat("a", maxProfileSummaryRunes+1)})
}, "/experience/0/summary"},
{"employer with a line break", func(in *CandidateProfileInput) {
in.Experience = confirmedItems(ProfileExperience{EmployerName: "A\nB", Specialization: SpecializationQA, StartedOn: "2024-05"})
}, "/experience/0/employer_name"},
{"too many roles", func(in *CandidateProfileInput) {
roles := make([]ProfileRole, len(specializationCodes)+1)
for index := range roles {
roles[index] = ProfileRole{Specialization: SpecializationBackend}
}
in.Roles = confirmedItems(roles...)
}, "/roles"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := completeCandidateProfileInput()
test.mutate(&input)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
assertProfileFieldError(t, err, test.pointer)
})
}
}
func TestProfileErrorsNeverQuoteSubmittedValues(t *testing.T) {
const secret = "secret-phone-9000000000"
input := completeCandidateProfileInput()
input.Phone = confirmed(secret)
err := resolveErr(CandidateProfileContent{}, input, candidateTestTime)
if err == nil || strings.Contains(err.Error(), secret) {
t.Fatalf("error = %v, want a failure that does not repeat the submitted value", err)
}
}
func TestResolveCandidateProfileContentNormalizesValues(t *testing.T) {
input := completeCandidateProfileInput()
input.Experience = confirmedItems(ProfileExperience{Specialization: SpecializationQA, StartedOn: "2024-05", Summary: "one\r\ntwo"})
content := mustCandidateContent(t, CandidateProfileContent{}, input, candidateTestTime)
if got := content.Experience()[0].Value().Summary; got != "one\ntwo" {
t.Fatalf("summary = %q, want CRLF normalized to LF", got)
}
}
func TestCandidateProfileReplaceTellsAChangeFromANoOp(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil || empty.Version() != 0 || !empty.CreatedAt().IsZero() {
t.Fatalf("EmptyCandidateProfile() = version %d, %v, want version 0", empty.Version(), err)
}
saved, changed, err := empty.Replace(completeCandidateProfileInput(), 0, candidateTestTime)
if err != nil || !changed {
t.Fatalf("Replace() = changed %v, %v, want a change", changed, err)
}
if saved.Version() != 0 || !saved.UpdatedAt().Equal(candidateTestTime) || !saved.CreatedAt().Equal(candidateTestTime) {
t.Fatalf("saved = version %d at %v, want the version left to storage", saved.Version(), saved.UpdatedAt())
}
// Sending the same decisions again changes nothing and keeps the
// confirmation time of the stored claims.
again, changed, err := saved.Replace(completeCandidateProfileInput(), 0, candidateTestTime.Add(time.Hour))
if err != nil || changed {
t.Fatalf("Replace(unchanged) = changed %v, %v, want a no-op", changed, err)
}
name, _ := again.Content().FullName()
if !name.Source().ConfirmedAt().Equal(candidateTestTime) || !again.UpdatedAt().Equal(candidateTestTime) {
t.Fatal("a no-op moved the confirmation or update time")
}
// A time before the last update, from clock skew, never moves it back.
edited := completeCandidateProfileInput()
edited.Location = confirmed("Moscow")
skewed, changed, err := saved.Replace(edited, 0, candidateTestTime.Add(-time.Minute))
if err != nil || !changed || !skewed.UpdatedAt().Equal(candidateTestTime) {
t.Fatalf("Replace(skewed clock) = changed %v, updated %v, %v, want the last update kept", changed, skewed.UpdatedAt(), err)
}
if _, _, err := (CandidateProfile{}).Replace(completeCandidateProfileInput(), 0, candidateTestTime); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("Replace(zero profile) error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := EmptyCandidateProfile(uuid.Nil); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("EmptyCandidateProfile(nil) error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestStoredClaimsRoundTripThroughRestore(t *testing.T) {
stored := suggestedContent(t)
input := completeCandidateProfileInput()
input.Phone = &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}
input.Stack = append(confirmedItems("PostgreSQL"), ProfileClaimInput[string]{Value: "Kafka", Status: ProfileClaimExtracted})
content := mustCandidateContent(t, stored, input, candidateTestTime)
rows, err := content.StoredClaims()
if err != nil {
t.Fatalf("StoredClaims() error = %v", err)
}
for _, row := range rows {
if row.TrustLevel != 0 {
t.Fatalf("row %s has trust level %d, want 0", row.Kind, row.TrustLevel)
}
}
restored, err := RestoreCandidateProfileContent(rows)
if err != nil || !restored.Equal(content) {
t.Fatalf("RestoreCandidateProfileContent() = equal %v, %v, want the same content", restored.Equal(content), err)
}
reversed := slicesReversed(rows)
if again, err := RestoreCandidateProfileContent(reversed); err != nil || !again.Equal(content) {
t.Fatalf("restore of rows in another order = equal %v, %v, want the same content", again.Equal(content), err)
}
}
func slicesReversed(rows []StoredProfileClaim) []StoredProfileClaim {
reversed := make([]StoredProfileClaim, len(rows))
for index, row := range rows {
reversed[len(rows)-1-index] = row
}
return reversed
}
func TestRestoreCandidateProfileContentRefusesRowsThatBreakARule(t *testing.T) {
manual := func(kind string, ordinal int, value string) StoredProfileClaim {
return StoredProfileClaim{Kind: kind, Ordinal: ordinal, Value: []byte(value), Status: "confirmed", Origin: "manual", ConfirmedAt: candidateTestTime}
}
tests := []struct {
name string
rows []StoredProfileClaim
}{
{"unknown kind", []StoredProfileClaim{manual("confirmed_grade", 0, `"senior"`)}},
{"trust level above zero", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.TrustLevel = 1
return row
}()}},
{"manual claim with a quote", []StoredProfileClaim{func() StoredProfileClaim {
row := manual(profileKindFullName, 0, `"Anna"`)
row.Quote = "quote"
return row
}()}},
{"suggestion without an extractor version", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "extracted", Origin: "imported"}}},
{"confirmed claim without a time", []StoredProfileClaim{{Kind: profileKindFullName, Value: []byte(`"Anna"`), Status: "confirmed", Origin: "manual"}}},
{"role with a confirmed grade key", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`)}},
{"role with an unknown specialization", []StoredProfileClaim{manual(profileKindRole, 0, `{"specialization":"go","self_assessed_grade":null}`)}},
{"value of a wrong type", []StoredProfileClaim{manual(profileKindRelocation, 0, `"yes"`)}},
{"value with trailing data", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna" "Anna"`)}},
{"single field twice", []StoredProfileClaim{manual(profileKindFullName, 0, `"Anna"`), manual(profileKindFullName, 0, `"Anna"`)}},
{"list with a gap", []StoredProfileClaim{manual(profileKindStack, 1, `"Go"`)}},
{"list repeats an item", []StoredProfileClaim{manual(profileKindStack, 0, `"Go"`), manual(profileKindStack, 1, `"go"`)}},
{"salary in another currency", []StoredProfileClaim{manual(profileKindSalaryMinimum, 0, `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`)}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := RestoreCandidateProfileContent(test.rows)
if !errors.Is(err, ErrInvalidCandidateProfile) {
t.Fatalf("RestoreCandidateProfileContent() error = %v, want ErrInvalidCandidateProfile", err)
}
if strings.Contains(err.Error(), "Anna") {
t.Fatalf("error = %v, want it not to quote a stored value", err)
}
})
}
}
func TestRestoreCandidateProfileValidatesTheRow(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
stored := StoredCandidateProfile{UserID: userID, Version: 2, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime.Add(time.Hour)}
profile, err := RestoreCandidateProfile(stored)
if err != nil || profile.Version() != 2 || profile.UserID() != userID {
t.Fatalf("RestoreCandidateProfile() = version %d, %v, want the stored profile", profile.Version(), err)
}
for name, mutate := range map[string]func(*StoredCandidateProfile){
"nil user": func(row *StoredCandidateProfile) { row.UserID = uuid.Nil },
"version zero": func(row *StoredCandidateProfile) { row.Version = 0 },
"update before it": func(row *StoredCandidateProfile) { row.UpdatedAt = row.CreatedAt.Add(-time.Second) },
} {
row := stored
mutate(&row)
if _, err := RestoreCandidateProfile(row); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("%s: error = %v, want ErrInvalidCandidateProfile", name, err)
}
}
}
// The profile types must offer no way to state a confirmed grade or a
// category: a confirmed category comes only from an assessment result.
func TestProfileTypesHaveNoConfirmedGradeOrCategory(t *testing.T) {
forbidden := []string{"confirmed", "category", "trust"}
for _, typ := range []reflect.Type{
reflect.TypeFor[ProfileRole](), reflect.TypeFor[ProfileExperience](), reflect.TypeFor[ProfileSalaryMinimum](),
reflect.TypeFor[CandidateProfileInput](), reflect.TypeFor[CandidateProfileContent](), reflect.TypeFor[CandidateProfile](),
} {
for index := range typ.NumField() {
name := strings.ToLower(typ.Field(index).Name)
for _, word := range forbidden {
if strings.Contains(name, word) {
t.Errorf("%s has a field %q, want none that names a confirmed grade, a category, or a trust level", typ.Name(), typ.Field(index).Name)
}
}
}
}
if got := reflect.TypeFor[ProfileRole]().NumField(); got != 2 {
t.Errorf("ProfileRole has %d fields, want the specialization and the self-assessed grade only", got)
}
}
func TestRestoreProfileClaimRefusesInconsistentStatus(t *testing.T) {
manual, err := NewManualProfileClaimSource(candidateTestTime)
if err != nil {
t.Fatalf("NewManualProfileClaimSource() error = %v", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimExtracted, manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("manual suggestion error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimStatus("unknown"), manual); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("unknown status error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := RestoreProfileClaim("x", ProfileClaimConfirmed, ProfileClaimSource{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero source error = %v, want ErrInvalidCandidateProfile", err)
}
if _, err := NewManualProfileClaimSource(time.Time{}); !errors.Is(err, ErrInvalidCandidateProfile) {
t.Errorf("zero time error = %v, want ErrInvalidCandidateProfile", err)
}
}
func TestCandidateProfileValuesAreRedacted(t *testing.T) {
const name, summary, quote = "Anna Sokolova", "Moved the payout service", "from the resume"
userID := uuid.Must(uuid.NewV7())
empty, err := EmptyCandidateProfile(userID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
input := completeCandidateProfileInput()
profile, _, err := empty.Replace(input, 0, candidateTestTime)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
claim, _ := profile.Content().FullName()
experience := profile.Content().Experience()[0]
salary, _ := profile.Content().SalaryMinimum()
suggested, _ := suggestedContent(t).Phone()
type holder struct {
Profile CandidateProfile
Content CandidateProfileContent
Claim ProfileClaim[string]
Experience ProfileClaim[ProfileExperience]
Salary ProfileClaim[ProfileSalaryMinimum]
Suggestion ProfileClaim[string]
Source ProfileClaimSource
}
value := holder{profile, profile.Content(), claim, experience, salary, suggested, suggested.Source()}
var logged bytes.Buffer
slog.New(slog.NewTextHandler(&logged, nil)).Info("profile", "profile", profile, "claim", claim, "holder", value)
outputs := []string{
fmt.Sprintf("%v %+v %#v %s", value, value, value, value),
fmt.Sprintf("%v %+v %#v", profile, profile, profile),
fmt.Sprintf("%v %+v %#v", experience.Value(), salary.Value(), claim),
logged.String(),
}
for _, output := range outputs {
for _, secret := range []string{name, summary, quote, "+79000000000", "180000", "Kazan", "Example Payments"} {
if strings.Contains(output, secret) {
t.Errorf("output %q leaks %q", output, secret)
}
}
}
}
// A client holding an old version gets a version conflict, not a validation
// error, when its decision depends on claims that another save changed.
func TestCandidateProfileReplaceChecksTheVersionBeforeStateDependentRules(t *testing.T) {
userID := uuid.Must(uuid.NewV7())
// Version 5 holds the phone confirmed by another tab.
stored, err := RestoreCandidateProfile(StoredCandidateProfile{
UserID: userID, Version: 5, CreatedAt: candidateTestTime, UpdatedAt: candidateTestTime,
Claims: []StoredProfileClaim{{
Kind: profileKindPhone, Value: []byte(`"+79000000000"`), Status: "confirmed", Origin: "extracted_from_resume",
Quote: "q", ExtractionVersion: "resume-rules.1", ConfirmedAt: candidateTestTime,
}},
})
if err != nil {
t.Fatalf("RestoreCandidateProfile() error = %v", err)
}
later := candidateTestTime.Add(time.Hour)
staleExtracted := CandidateProfileInput{Phone: &ProfileClaimInput[string]{Value: "+79000000000", Status: ProfileClaimExtracted}}
t.Run("stale extracted decision is a conflict", func(t *testing.T) {
if _, _, err := stored.Replace(staleExtracted, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("current version keeps the validation error", func(t *testing.T) {
assertProfileFieldError(t, errOnly(stored.Replace(staleExtracted, 5, later)), "/contacts/phone/status")
})
t.Run("stale body rule stays a validation error", func(t *testing.T) {
bad := CandidateProfileInput{Phone: confirmed("8 900")}
assertProfileFieldError(t, errOnly(stored.Replace(bad, 4, later)), "/contacts/phone/value")
})
t.Run("stale unchanged body is a no-op", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
got, changed, err := stored.Replace(unchanged, 4, later)
if err != nil || changed || got.Version() != 5 {
t.Fatalf("Replace() = changed %v, %v, want a no-op", changed, err)
}
})
t.Run("stale changed body is a conflict", func(t *testing.T) {
changedBody := CandidateProfileInput{Phone: confirmed("+79000000001")}
if _, _, err := stored.Replace(changedBody, 4, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("error = %v, want ErrCandidateProfileVersionConflict", err)
}
})
t.Run("a future version never existed", func(t *testing.T) {
unchanged := CandidateProfileInput{Phone: confirmed("+79000000000")}
for _, version := range []int64{6, 99, -1} {
if _, _, err := stored.Replace(unchanged, version, later); !errors.Is(err, ErrCandidateProfileVersionConflict) {
t.Fatalf("version %d error = %v, want ErrCandidateProfileVersionConflict", version, err)
}
}
})
}
func errOnly(_ CandidateProfile, _ bool, err error) error { return err }