feat(evidence): project skill evidence from confirmed assessments
This commit is contained in:
1 parent
4761508f13
commit
c2a8d17195
94 files changed
+10077
-151
No files matched your search
@@ -112,4 +112,10 @@ Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me
|
||||
|
||||
An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details.
|
||||
|
||||
## Skill evidence
|
||||
|
||||
A confirmed real assessment result leaves one fact of skill evidence per attempt, written by the database in the same transaction that stores the result (migration 35, the trigger on `assessment_attempt_results`, and the function `skill_evidence_project_assessment_result`). The migration also projects the results that already exist. An express run, a failed attempt, and a result without a reviewed category source leave no fact. The skills of an event are tags of its fact, so several tags are still one fact, and an online assessment without a reliable identity confirmation has trust 1.
|
||||
|
||||
The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, query `ListCandidateEvidenceFacts`); an employer reads the permitted projection at `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, which runs the checks of the card read (`candidateview.Service.AuthorizeCategoriesSection`: membership, effective C2 publication, hiding, minimum cohort, quota, access audit) and then the statement `ListOrganizationVisibleEvidence` (effective publication view, `NOT EXISTS` over the hidden organizations, the `categories` field, visible measurements, one fact for each category of the card that supports its confirmed grade, an allowlist of six columns: skill, grade, trust, basis, calibration, year). The preview of the candidate (`GetMyCardPreview`) shows the same section through `ListCandidatePreviewEvidence`. The reads touch only the two evidence tables; `backend/db/evidence_queries_test.go` fails when an evidence query names a result, attempt, answer, signal, or review table. The facts, the tags, and the rules are described in [architecture](../docs/en/ARCHITECTURE.md#skill-evidence). The integration test `TestSkillEvidenceOverHTTP` runs against a real PostgreSQL and covers the fact tied to its result with trust 1, two more tags on one event, an express run and a failed attempt, paging, the organization projection with C2 granted and revoked, a hidden organization, a hidden fact, a card without categories, tags that can join a fact only in its creating transaction, the erasure of an account with facts through both cascade paths, the refusal to roll the migration back while a fact is hidden, and the rebuild after the migration is rolled back and applied again.
|
||||
|
||||
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
|
||||
@@ -112,4 +112,10 @@
|
||||
|
||||
Работодатель с подтвержденной учетной записью и активным членством читает карточку по `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Каждый запрос заново проверяет членство, действующее C2, публикацию, скрытие для этой компании и минимальный размер группы; успешный просмотр и расход квоты записываются в одной транзакции. Закрытая, отозванная, скрытая или подавленная карточка не раскрывается и отвечает так же, как неизвестный псевдоним. Кандидат видит записи об успешных просмотрах карточки в своей истории доступа. Операция чтения контактов и управление грантами C4 пока недоступны; карточка контактов не содержит.
|
||||
|
||||
## Доказательства навыков
|
||||
|
||||
Подтвержденный настоящий результат оценки оставляет один факт доказательства на попытку; его пишет база в той же транзакции, что сохраняет результат (миграция 35, триггер на `assessment_attempt_results` и функция `skill_evidence_project_assessment_result`). Миграция также проецирует уже существующие результаты. Экспресс-прогон, проваленная попытка и результат без проверенного источника категории фактов не оставляют. Навыки события - теги его факта, поэтому несколько тегов остаются одним фактом, а у онлайн-оценки без надежного подтверждения личности доверие 1.
|
||||
|
||||
Кандидат читает факты через `GET /api/v1/me/evidence` (`usecase/evidence/read.go`, запрос `ListCandidateEvidenceFacts`); работодатель читает разрешенную проекцию через `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence`, которая выполняет проверки чтения карточки (`candidateview.Service.AuthorizeCategoriesSection`: членство, действующая публикация с C2, скрытие, минимальная когорта, квота, аудит доступа), а затем запрос `ListOrganizationVisibleEvidence` (представление действующих публикаций, `NOT EXISTS` по скрытым организациям, поле `categories`, видимые измерения, по одному факту на каждую категорию карточки, подтверждающему ее грейд, белый список из шести колонок: навык, грейд, доверие, основание, калибровка, год). Предпросмотр кандидата (`GetMyCardPreview`) показывает тот же раздел через `ListCandidatePreviewEvidence`. Чтения трогают только две таблицы доказательств; `backend/db/evidence_queries_test.go` падает, если запрос доказательств называет таблицу результатов, попыток, ответов, сигналов или проверок. Факты, теги и правила описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#доказательства-навыков). Интеграционный тест `TestSkillEvidenceOverHTTP` выполняется на настоящем PostgreSQL и проверяет: факт, связанный с результатом, с доверием 1, два дополнительных тега одного события, экспресс-прогон и проваленная попытка, постраничное чтение, проекция организации при выданном и отозванном C2, скрытая организация, скрытый факт, карточка без категорий теги, которые могут присоединиться к факту только в создавшей его транзакции, удаление аккаунта с фактами по обоим каскадным путям, отказ откатывать миграцию, пока есть скрытый факт, и перестроение после отката и повторного применения миграции.
|
||||
|
||||
Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
@@ -0,0 +1,125 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`)
|
||||
// evidenceReaders are the only queries that may name the evidence tables.
|
||||
evidenceReaders = []string{"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence"}
|
||||
// evidenceForbiddenSources are tables whose content must never reach the
|
||||
// evidence reads: raw answers and items, results with their scores,
|
||||
// attempts, signals, and the anti-cheat review band.
|
||||
evidenceForbiddenSources = []string{
|
||||
"assessment_attempt_results", "assessment_attempt_items", "assessment_attempts",
|
||||
"assessment_attempt_reviews", "assessment_attempt_origin_marks", "assessment_answer_observations",
|
||||
"assessment_answer_fingerprint_holders", "assessment_answer_family_totals",
|
||||
"assessment_signal_events", "assessment_signal_batches", "assessment_signal_idempotency_outcomes",
|
||||
"assessment_attempt_idempotency_outcomes", "candidate_assessment_categories",
|
||||
"assessment_synthetic_category_reviews", "candidate_profile_claims", "candidate_questionnaires",
|
||||
}
|
||||
)
|
||||
|
||||
// evidenceStatements returns the statement of every query of the query files
|
||||
// by name, with comments removed.
|
||||
func evidenceStatements(t *testing.T) map[string]string {
|
||||
t.Helper()
|
||||
files, err := filepath.Glob("queries/*.sql")
|
||||
if err != nil || len(files) == 0 {
|
||||
t.Fatalf("list the query files = %v, %v", files, err)
|
||||
}
|
||||
statements := make(map[string]string)
|
||||
for _, file := range files {
|
||||
content, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", file, err)
|
||||
}
|
||||
text := string(content)
|
||||
headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1)
|
||||
for index, header := range headers {
|
||||
end := len(text)
|
||||
if index+1 < len(headers) {
|
||||
end = headers[index+1][0]
|
||||
}
|
||||
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
|
||||
statements[text[header[2]:header[3]]] = strings.ToLower(strings.Join(strings.Fields(statement), " "))
|
||||
}
|
||||
}
|
||||
return statements
|
||||
}
|
||||
|
||||
// Only the evidence reads name the projection, and the projection reads
|
||||
// reach no table of raw answers, scores, failures, or anti-cheat data.
|
||||
func TestEvidenceReadsNameOnlyTheProjection(t *testing.T) {
|
||||
statements := evidenceStatements(t)
|
||||
var found []string
|
||||
for name, statement := range statements {
|
||||
if evidenceTableName.MatchString(statement) {
|
||||
found = append(found, name)
|
||||
}
|
||||
}
|
||||
slices.Sort(found)
|
||||
want := slices.Clone(evidenceReaders)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(found, want) {
|
||||
t.Fatalf("queries that name the evidence tables = %v, want only %v", found, want)
|
||||
}
|
||||
for _, name := range evidenceReaders {
|
||||
statement := statements[name]
|
||||
for _, forbidden := range evidenceForbiddenSources {
|
||||
if regexp.MustCompile(`\b` + forbidden + `\b`).MatchString(statement) {
|
||||
t.Errorf("%s reads %s: %s", name, forbidden, statement)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The organization read goes through the effective publication view, excludes
|
||||
// the candidates that hide the organization, requires the categories field,
|
||||
// and returns an allowlist of columns with no identifier.
|
||||
func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) {
|
||||
statement := evidenceStatements(t)["ListOrganizationVisibleEvidence"]
|
||||
if statement == "" {
|
||||
t.Fatal("the organization evidence query is missing")
|
||||
}
|
||||
for _, required := range []string{
|
||||
"from candidate_effective_publications as effective",
|
||||
"from candidate_hidden_organizations as hidden",
|
||||
"not exists",
|
||||
"hidden.organization_id = sqlc.arg(organization_id)",
|
||||
"'categories' = any(effective.fields)",
|
||||
"fact.visibility = 'visible'",
|
||||
"effective.user_id = sqlc.arg(candidate_id)",
|
||||
"select distinct on (skill.skill_code)",
|
||||
"(skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])",
|
||||
"fact.kind = 'measurement'",
|
||||
} {
|
||||
if !strings.Contains(statement, required) {
|
||||
t.Errorf("organization evidence query lacks %q: %s", required, statement)
|
||||
}
|
||||
}
|
||||
selected := statement[len("select"):strings.Index(statement, " from candidate_effective_publications")]
|
||||
for _, private := range []string{"fact.id", "event_id", "result_id", "candidate_id", "visibility"} {
|
||||
if strings.Contains(selected, private) {
|
||||
t.Errorf("organization evidence query selects %q: %s", private, selected)
|
||||
}
|
||||
}
|
||||
// The columns are exactly the skill, the grade, the trust level, and the
|
||||
// year, with the basis and calibration of the method: nothing else of the
|
||||
// fact leaves.
|
||||
const wantSelected = " distinct on (skill.skill_code) skill.skill_code as skill, fact.grade, fact.trust, " +
|
||||
"fact.basis, fact.calibration_status, " +
|
||||
"extract(year from fact.occurred_at at time zone 'utc')::integer as observed_year"
|
||||
if selected != wantSelected {
|
||||
t.Errorf("organization evidence query selects %q, want %q", selected, wantSelected)
|
||||
}
|
||||
if strings.Contains(statement, "candidate_publications") {
|
||||
t.Errorf("organization evidence query reads the publication table directly: %s", statement)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
-- +goose Up
|
||||
-- Skill evidence is a projection of immutable assessment results. One fact is
|
||||
-- one source event; the skills of that event are tags of the fact, so several
|
||||
-- tags never multiply the fact. A fact is written by the database in the same
|
||||
-- transaction as the result that qualifies it, and migration backfills the
|
||||
-- results that already exist. The projection holds no answer, score, item,
|
||||
-- failure, or anti-cheat data: reads of the evidence never touch the result,
|
||||
-- attempt, or review tables.
|
||||
|
||||
CREATE TABLE skill_evidence_facts (
|
||||
id uuid NOT NULL DEFAULT gen_random_uuid(),
|
||||
candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
-- A claim is a statement that nothing confirmed separately (trust 0); a
|
||||
-- measurement is an observed result (trust 1 to 3). Only assessments feed
|
||||
-- this table today, so every stored fact is a measurement.
|
||||
kind text NOT NULL,
|
||||
source_type text NOT NULL,
|
||||
-- The source event and the immutable result of that event. For an
|
||||
-- assessment both are the attempt, because a result is keyed by its attempt.
|
||||
event_id uuid NOT NULL,
|
||||
result_id uuid NOT NULL,
|
||||
attribution text NOT NULL,
|
||||
trust smallint NOT NULL,
|
||||
-- The grade that was passed, the basis of the measurement, and its
|
||||
-- calibration, copied from the category decision of the result.
|
||||
grade text NOT NULL,
|
||||
basis text NOT NULL,
|
||||
calibration_status text NOT NULL,
|
||||
occurred_at timestamptz NOT NULL,
|
||||
-- The candidate may hide a fact; hiding never edits the result.
|
||||
visibility text NOT NULL DEFAULT 'visible',
|
||||
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
-- The transaction that created the fact. Tags are added only in that
|
||||
-- transaction, so a stored fact is never widened afterwards.
|
||||
created_txid bigint NOT NULL DEFAULT (pg_current_xact_id()::text::bigint),
|
||||
CONSTRAINT skill_evidence_facts_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT skill_evidence_facts_event_key UNIQUE (source_type, event_id),
|
||||
CONSTRAINT skill_evidence_facts_result_fk FOREIGN KEY (result_id, candidate_id)
|
||||
REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE,
|
||||
CONSTRAINT skill_evidence_facts_kind CHECK (kind IN ('claim', 'measurement')),
|
||||
CONSTRAINT skill_evidence_facts_source CHECK (source_type IN ('assessment_result')),
|
||||
CONSTRAINT skill_evidence_facts_attribution CHECK (attribution IN ('personal', 'team_role', 'team_unattributed')),
|
||||
CONSTRAINT skill_evidence_facts_trust CHECK (
|
||||
(kind = 'claim' AND trust = 0) OR (kind = 'measurement' AND trust BETWEEN 1 AND 3)
|
||||
),
|
||||
-- An online assessment has no proctoring, so it never reaches the level of
|
||||
-- an in-person check. Level 1 is the level without a reliable identity
|
||||
-- confirmation; level 2 is reserved for a result tied to a confirmed identity.
|
||||
CONSTRAINT skill_evidence_facts_assessment_shape CHECK (
|
||||
source_type <> 'assessment_result'
|
||||
OR (kind = 'measurement' AND trust BETWEEN 1 AND 2 AND attribution = 'personal' AND event_id = result_id)
|
||||
),
|
||||
CONSTRAINT skill_evidence_facts_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')),
|
||||
CONSTRAINT skill_evidence_facts_basis CHECK (basis IN ('synthetic_demo')),
|
||||
CONSTRAINT skill_evidence_facts_calibration CHECK (calibration_status IN ('uncalibrated')),
|
||||
CONSTRAINT skill_evidence_facts_visibility CHECK (visibility IN ('visible', 'hidden'))
|
||||
);
|
||||
|
||||
CREATE INDEX skill_evidence_facts_candidate_idx
|
||||
ON skill_evidence_facts (candidate_id, occurred_at DESC, id DESC);
|
||||
|
||||
CREATE TABLE skill_evidence_skills (
|
||||
fact_id uuid NOT NULL REFERENCES skill_evidence_facts (id) ON DELETE CASCADE,
|
||||
skill_code text NOT NULL,
|
||||
CONSTRAINT skill_evidence_skills_pkey PRIMARY KEY (fact_id, skill_code),
|
||||
-- The specialization codes of the catalog and the closed technology
|
||||
-- taxonomy of the anonymous card.
|
||||
CONSTRAINT skill_evidence_skills_code CHECK (
|
||||
skill_code IN (
|
||||
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
|
||||
'data_analyst', 'ds_ml', 'information_security', 'qa',
|
||||
'go', 'postgresql', 'kafka', 'docker'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- The single rule that decides which result is qualifying evidence: a real
|
||||
-- (root or corrective) result of the basic mode, confirmed, and carried by a
|
||||
-- reviewed category decision that either assigned the grade or left a higher
|
||||
-- one in force. An express training run, a failed attempt, and a result without
|
||||
-- a reviewed source never qualify.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_result_qualifies(source_result assessment_attempt_results) RETURNS boolean
|
||||
LANGUAGE sql IMMUTABLE AS $$
|
||||
SELECT source_result.schema_version = 2
|
||||
AND source_result.kind IN ('root', 'corrective')
|
||||
AND source_result.mode = 'demo_basic'
|
||||
AND source_result.outcome = 'confirmed'
|
||||
AND source_result.category_decision ->> 'status' IN ('assigned', 'unchanged')
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- A fact must match the immutable result it names, so no write path can store
|
||||
-- evidence for an express run, a failed attempt, or another candidate.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_guard_insert() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
source_result assessment_attempt_results%ROWTYPE;
|
||||
BEGIN
|
||||
SELECT * INTO source_result
|
||||
FROM assessment_attempt_results
|
||||
WHERE attempt_id = NEW.result_id AND user_id = NEW.candidate_id;
|
||||
|
||||
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) OR
|
||||
source_result.category_decision ->> 'attempted_grade' IS DISTINCT FROM NEW.grade OR
|
||||
source_result.category_decision ->> 'source' IS DISTINCT FROM NEW.basis OR
|
||||
source_result.category_decision ->> 'calibration_status' IS DISTINCT FROM NEW.calibration_status OR
|
||||
source_result.decided_at <> NEW.occurred_at THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_source_result',
|
||||
MESSAGE = 'skill evidence does not match a qualifying assessment result';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_facts_guard_insert
|
||||
BEFORE INSERT ON skill_evidence_facts
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_guard_insert();
|
||||
|
||||
-- A stored fact never changes except its visibility, and is removed only with
|
||||
-- its owner or its result.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' THEN
|
||||
IF pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
ELSIF ROW(
|
||||
NEW.id, NEW.candidate_id, NEW.kind, NEW.source_type, NEW.event_id, NEW.result_id,
|
||||
NEW.attribution, NEW.trust, NEW.grade, NEW.basis, NEW.calibration_status,
|
||||
NEW.occurred_at, NEW.recorded_at, NEW.created_txid
|
||||
) IS NOT DISTINCT FROM ROW(
|
||||
OLD.id, OLD.candidate_id, OLD.kind, OLD.source_type, OLD.event_id, OLD.result_id,
|
||||
OLD.attribution, OLD.trust, OLD.grade, OLD.basis, OLD.calibration_status,
|
||||
OLD.occurred_at, OLD.recorded_at, OLD.created_txid
|
||||
) THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_facts_immutable',
|
||||
MESSAGE = 'skill evidence facts are immutable except for their visibility';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_facts_refuse_change
|
||||
BEFORE UPDATE OR DELETE ON skill_evidence_facts
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_refuse_change();
|
||||
|
||||
-- A fact without a skill cannot be read or matched, so the check runs at
|
||||
-- commit, after the tags of the same transaction are in place. A fact that the
|
||||
-- same transaction already removed needs no tag.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_facts_require_skill() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = NEW.id) AND
|
||||
NOT EXISTS (SELECT 1 FROM skill_evidence_skills WHERE fact_id = NEW.id) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_require_skill',
|
||||
MESSAGE = 'skill evidence fact has no skill';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE CONSTRAINT TRIGGER skill_evidence_facts_require_skill
|
||||
AFTER INSERT ON skill_evidence_facts
|
||||
DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_require_skill();
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_skills_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
|
||||
RETURN OLD;
|
||||
END IF;
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_immutable',
|
||||
MESSAGE = 'skill evidence tags are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_skills_refuse_change
|
||||
BEFORE UPDATE OR DELETE ON skill_evidence_skills
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_refuse_change();
|
||||
|
||||
-- A tag joins a fact only in the transaction that created the fact: the
|
||||
-- skills of an event are fixed when the event is recorded, and a later write
|
||||
-- cannot widen what an organization may read about it.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_skills_require_new_fact() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM skill_evidence_facts
|
||||
WHERE id = NEW.fact_id AND created_txid = pg_current_xact_id()::text::bigint
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_fact_sealed',
|
||||
MESSAGE = 'skills can only be added in the transaction that created the fact';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_skills_require_new_fact
|
||||
BEFORE INSERT ON skill_evidence_skills
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_require_new_fact();
|
||||
|
||||
-- Projects one stored result. A result that does not qualify writes nothing,
|
||||
-- and a repeat writes nothing, so the function serves both the trigger and the
|
||||
-- backfill. Level 1 is the trust of an online result without a reliable
|
||||
-- identity confirmation.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_project_assessment_result(projected_attempt_id uuid) RETURNS void
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
source_result assessment_attempt_results%ROWTYPE;
|
||||
new_fact_id uuid;
|
||||
BEGIN
|
||||
SELECT * INTO source_result
|
||||
FROM assessment_attempt_results
|
||||
WHERE attempt_id = projected_attempt_id;
|
||||
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
INSERT INTO skill_evidence_facts (
|
||||
candidate_id, kind, source_type, event_id, result_id, attribution, trust,
|
||||
grade, basis, calibration_status, occurred_at
|
||||
) VALUES (
|
||||
source_result.user_id, 'measurement', 'assessment_result', source_result.attempt_id,
|
||||
source_result.attempt_id, 'personal', 1,
|
||||
source_result.category_decision ->> 'attempted_grade',
|
||||
source_result.category_decision ->> 'source',
|
||||
source_result.category_decision ->> 'calibration_status',
|
||||
source_result.decided_at
|
||||
)
|
||||
ON CONFLICT (source_type, event_id) DO NOTHING
|
||||
RETURNING id INTO new_fact_id;
|
||||
|
||||
IF new_fact_id IS NOT NULL THEN
|
||||
INSERT INTO skill_evidence_skills (fact_id, skill_code)
|
||||
VALUES (new_fact_id, source_result.category_decision ->> 'specialization');
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION skill_evidence_project_result_trigger() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM skill_evidence_project_assessment_result(NEW.attempt_id);
|
||||
RETURN NULL;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER skill_evidence_project_result
|
||||
AFTER INSERT ON assessment_attempt_results
|
||||
FOR EACH ROW EXECUTE FUNCTION skill_evidence_project_result_trigger();
|
||||
|
||||
SELECT skill_evidence_project_assessment_result(attempt_id)
|
||||
FROM assessment_attempt_results
|
||||
ORDER BY decided_at, attempt_id;
|
||||
|
||||
-- +goose Down
|
||||
-- The facts are a projection: the results they were derived from stay, and the
|
||||
-- migration projects them again when it is applied again. Hiding a fact is the
|
||||
-- candidate's own decision and cannot be derived from a result, so a rollback
|
||||
-- refuses while any such decision, or any source other than an assessment
|
||||
-- result, would be lost.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM skill_evidence_facts
|
||||
WHERE visibility = 'hidden' OR source_type <> 'assessment_result'
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_retained',
|
||||
MESSAGE = 'skill evidence uses migration 00035 and must be retained';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TRIGGER skill_evidence_project_result ON assessment_attempt_results;
|
||||
DROP FUNCTION skill_evidence_project_result_trigger();
|
||||
DROP FUNCTION skill_evidence_project_assessment_result(uuid);
|
||||
DROP TRIGGER skill_evidence_skills_require_new_fact ON skill_evidence_skills;
|
||||
DROP FUNCTION skill_evidence_skills_require_new_fact();
|
||||
DROP TRIGGER skill_evidence_skills_refuse_change ON skill_evidence_skills;
|
||||
DROP FUNCTION skill_evidence_skills_refuse_change();
|
||||
DROP TRIGGER skill_evidence_facts_require_skill ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_require_skill();
|
||||
DROP TRIGGER skill_evidence_facts_refuse_change ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_refuse_change();
|
||||
DROP TRIGGER skill_evidence_facts_guard_insert ON skill_evidence_facts;
|
||||
DROP FUNCTION skill_evidence_facts_guard_insert();
|
||||
DROP FUNCTION skill_evidence_result_qualifies(assessment_attempt_results);
|
||||
DROP TABLE skill_evidence_skills;
|
||||
DROP TABLE skill_evidence_facts;
|
||||
@@ -0,0 +1,105 @@
|
||||
-- Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
-- failure, or anti-cheat data, and none of these statements names the result,
|
||||
-- attempt, or review tables: evidence is read from its own facts only.
|
||||
|
||||
-- The candidate's own facts, hidden ones included, newest event first. Every
|
||||
-- statement is scoped by the owner; the caller passes the continuation
|
||||
-- position of the previous page, if any, and fetches one extra row.
|
||||
-- name: ListCandidateEvidenceFacts :many
|
||||
SELECT
|
||||
fact.id,
|
||||
fact.kind,
|
||||
fact.source_type,
|
||||
fact.event_id,
|
||||
fact.result_id,
|
||||
fact.attribution,
|
||||
fact.trust,
|
||||
fact.grade,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
fact.occurred_at,
|
||||
fact.visibility,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
|
||||
FROM skill_evidence_skills AS skill
|
||||
WHERE skill.fact_id = fact.id
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS skills
|
||||
FROM skill_evidence_facts AS fact
|
||||
WHERE
|
||||
fact.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (fact.occurred_at, fact.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY fact.occurred_at DESC, fact.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The evidence that one organization may read about one candidate: one fact
|
||||
-- for each category of the card, the fact that supports the confirmed grade
|
||||
-- of that category (the earliest one that passed exactly that grade, so a
|
||||
-- lower grade or a retake adds nothing). The statement selects from the
|
||||
-- effective publication view (published and backed by an unrevoked C2) and
|
||||
-- excludes the candidates that hide the reading organization, so no row means
|
||||
-- nothing to read, whatever the reason. The card must publish the categories
|
||||
-- field and only visible measurements qualify. The categories come from the
|
||||
-- caller as "specialization/grade" pairs taken from the card that was just
|
||||
-- projected, so the answer never names a skill the card does not show. The columns are
|
||||
-- an allowlist: no identifier of the fact, the event, the result, or the
|
||||
-- candidate leaves, the instant is cut to the year, and the basis and the
|
||||
-- calibration (the same for every candidate) say that the fact is a synthetic
|
||||
-- demonstration.
|
||||
-- name: ListOrganizationVisibleEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM candidate_effective_publications AS effective
|
||||
INNER JOIN skill_evidence_facts AS fact
|
||||
ON effective.user_id = fact.candidate_id
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
effective.user_id = sqlc.arg(candidate_id)
|
||||
AND 'categories' = any(effective.fields)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
)
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
|
||||
|
||||
-- The same selection for the candidate's own card preview, so the candidate
|
||||
-- sees what an organization would read. It is scoped by the owner and runs
|
||||
-- after the caller locked the effective C2 and publication; it does not apply
|
||||
-- an organization or a cohort.
|
||||
-- name: ListCandidatePreviewEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM skill_evidence_facts AS fact
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
fact.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
|
||||
@@ -502,6 +502,28 @@ func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
return newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, categories, nil)
|
||||
}
|
||||
|
||||
// assessmentHarnessParts are the shared dependencies of the attempt router, for
|
||||
// a scenario that mounts further business areas on the same router.
|
||||
type assessmentHarnessParts struct {
|
||||
pool *pgxpool.Pool
|
||||
transactor *postgresadapter.Transactor
|
||||
keyring *identity.Keyring
|
||||
clock *testClock
|
||||
}
|
||||
|
||||
// newAssessmentAttemptHTTPHarnessWithOptions builds the attempt router and adds
|
||||
// the handler options that extra returns, if any.
|
||||
func newAssessmentAttemptHTTPHarnessWithOptions(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
extra func(assessmentHarnessParts) []v1.HandlerOption,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
@@ -554,11 +576,15 @@ func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
|
||||
handler := v1.NewHandler(healthHandler, responder,
|
||||
options := []v1.HandlerOption{
|
||||
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler),
|
||||
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
|
||||
v1.WithAssessment(attemptHandler), v1.WithAssessmentSignals(signalHandler),
|
||||
)
|
||||
}
|
||||
if extra != nil {
|
||||
options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...)
|
||||
}
|
||||
handler := v1.NewHandler(healthHandler, responder, options...)
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
|
||||
@@ -49,6 +49,7 @@ var (
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
assessmentAttemptTables = []pgx.Identifier{
|
||||
{"skill_evidence_skills"}, {"skill_evidence_facts"},
|
||||
{"candidate_assessment_categories"}, {"assessment_attempt_results"},
|
||||
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
|
||||
{"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"},
|
||||
|
||||
@@ -250,7 +250,8 @@ func TestPolicyVersions(t *testing.T) {
|
||||
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
|
||||
assessment_signal_events, assessment_signal_batches, assessment_attempt_results,
|
||||
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks,
|
||||
assessment_synthetic_category_reviews, candidate_assessment_categories`},
|
||||
assessment_synthetic_category_reviews, candidate_assessment_categories,
|
||||
skill_evidence_facts, skill_evidence_skills`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,887 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/anonymousprofile"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
const (
|
||||
skillEvidenceHTTPTimeout = 10 * time.Minute
|
||||
// skillEvidenceMigrationVersion creates the skill evidence tables.
|
||||
skillEvidenceMigrationVersion = 35
|
||||
// evidenceCohortSize is the smallest visible group of identical cards, so
|
||||
// the cohort rules of the card leave the category in place.
|
||||
evidenceCohortSize = 5
|
||||
)
|
||||
|
||||
type skillEvidenceHarness struct {
|
||||
*assessmentAttemptHTTPHarness
|
||||
key domain.CandidateViewPseudonymKey
|
||||
}
|
||||
|
||||
func newSkillEvidenceHarness(ctx context.Context, t *testing.T, env *testEnvironment) *skillEvidenceHarness {
|
||||
t.Helper()
|
||||
var key domain.CandidateViewPseudonymKey
|
||||
harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env,
|
||||
assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true},
|
||||
func(parts assessmentHarnessParts) []v1.HandlerOption {
|
||||
var err error
|
||||
if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil {
|
||||
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now)
|
||||
quota := companyquota.NewService(parts.clock.Now)
|
||||
views, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateview.NewService() error = %v", err)
|
||||
}
|
||||
settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateprivacy.NewService() error = %v", err)
|
||||
}
|
||||
evidenceService, err := evidence.NewService(evidence.Dependencies{
|
||||
Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("evidence.NewService() error = %v", err)
|
||||
}
|
||||
return []v1.HandlerOption{
|
||||
v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)),
|
||||
v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)),
|
||||
}
|
||||
})
|
||||
return &skillEvidenceHarness{assessmentAttemptHTTPHarness: harness, key: key}
|
||||
}
|
||||
|
||||
// evidenceFactBody is the owner's fact as the contract declares it.
|
||||
type evidenceFactBody struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Source struct {
|
||||
Type string `json:"type"`
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
ResultID uuid.UUID `json:"result_id"`
|
||||
} `json:"source"`
|
||||
Skills []string `json:"skills"`
|
||||
Result struct {
|
||||
Grade string `json:"grade"`
|
||||
Basis string `json:"basis"`
|
||||
CalibrationStatus string `json:"calibration_status"`
|
||||
} `json:"result"`
|
||||
Attribution string `json:"attribution"`
|
||||
Trust int `json:"trust"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
Visibility string `json:"visibility"`
|
||||
}
|
||||
|
||||
type evidencePageBody struct {
|
||||
Items []evidenceFactBody `json:"items"`
|
||||
Page struct {
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
} `json:"page"`
|
||||
}
|
||||
|
||||
func TestSkillEvidenceOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), skillEvidenceHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newSkillEvidenceHarness(ctx, t, &isolatedEnv)
|
||||
bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true)
|
||||
threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark))
|
||||
client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx}
|
||||
transactor := postgresadapter.NewTransactor(harness.pool)
|
||||
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
|
||||
organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now}
|
||||
privacy := candidatePrivacyFixture{
|
||||
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
|
||||
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
|
||||
}
|
||||
|
||||
get := func(who categoryHTTPCandidate, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return harness.request(t, http.MethodGet, path, "", "", who.cookie, "", client.remote())
|
||||
}
|
||||
readOwn := func(who categoryHTTPCandidate, query string) (evidencePageBody, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/evidence"+query)
|
||||
var page evidencePageBody
|
||||
if response.Code == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatalf("decode own evidence: %v\n%s", err, response.Body.String())
|
||||
}
|
||||
}
|
||||
return page, response
|
||||
}
|
||||
countRows := func(query string, args ...any) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
|
||||
t.Fatalf("count rows: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
passingIntern := func(who categoryHTTPCandidate) attemptRun {
|
||||
t.Helper()
|
||||
run := client.run(t, who, "backend", "intern", func(int) int { return threshold })
|
||||
if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" {
|
||||
t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result)
|
||||
}
|
||||
return run
|
||||
}
|
||||
|
||||
// The cohort: five candidates with the same published category. A card is
|
||||
// shown only inside a group of five identical cards.
|
||||
cohort := make([]categoryHTTPCandidate, 0, evidenceCohortSize)
|
||||
runs := make(map[uuid.UUID]attemptRun, evidenceCohortSize)
|
||||
for index := range evidenceCohortSize {
|
||||
member := client.candidate(t, fmt.Sprintf("evidence-cohort-%d@example.test", index))
|
||||
runs[member.id] = passingIntern(member)
|
||||
cohort = append(cohort, member)
|
||||
}
|
||||
target := cohort[0]
|
||||
targetRun := runs[target.id]
|
||||
consents := make(map[uuid.UUID]uuid.UUID, len(cohort))
|
||||
for _, member := range cohort {
|
||||
c2 := privacy.grant(t, member.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, member.id, c2.ID(), 0, domain.CardFieldCategories)
|
||||
consents[member.id] = c2.ID()
|
||||
}
|
||||
failed := client.candidate(t, "evidence-failed@example.test")
|
||||
failedRun := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 })
|
||||
if failedRun.result["outcome"] != "not_confirmed" {
|
||||
t.Fatalf("failing run = %v, want not_confirmed", failedRun.result["outcome"])
|
||||
}
|
||||
employerAccount := client.employer(t, "evidence-employer@example.test")
|
||||
foreignAccount := client.employer(t, "evidence-foreign@example.test")
|
||||
organizationA := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization A"), now)
|
||||
organizationB := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization B"), now)
|
||||
foreignOrganization := organizations.create(t, domain.User{ID: foreignAccount.id}, organizations.completeProfile(t, "Evidence foreign organization"), now)
|
||||
// The policy and the organizations take effect when they are stored, which
|
||||
// is after the clock of the harness was read, and the card-view quota reads
|
||||
// both at the application time.
|
||||
harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond))
|
||||
organizationPath := func(organizationID uuid.UUID, handle string) string {
|
||||
return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s/evidence", organizationID, handle)
|
||||
}
|
||||
aliasIn := func(organizationID, candidateID uuid.UUID) string {
|
||||
t.Helper()
|
||||
alias, err := harness.key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
return alias
|
||||
}
|
||||
organizationFacts := func(organizationID, candidateID uuid.UUID, categories ...domain.CandidateViewCategory) []domain.EvidenceOrganizationFact {
|
||||
t.Helper()
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ListOrganizationFacts() error = %v", err)
|
||||
}
|
||||
return facts
|
||||
}
|
||||
category := func(specialization domain.SpecializationCode, grade domain.GradeCode) domain.CandidateViewCategory {
|
||||
return domain.CandidateViewCategory{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard}
|
||||
}
|
||||
// A source records a fact together with its tags in one transaction, the
|
||||
// only time tags can join a fact. The helper rebuilds the projection from
|
||||
// the stored results and adds the tags to the fact of one event, as such a
|
||||
// source would.
|
||||
rebuildWithTags := func(eventID uuid.UUID, skills ...string) {
|
||||
t.Helper()
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the rebuild: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results: %v", err)
|
||||
}
|
||||
for _, skill := range skills {
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code)
|
||||
SELECT id, $2 FROM skill_evidence_facts WHERE event_id = $1`, eventID, skill); err != nil {
|
||||
t.Fatalf("tag the event with %s: %v", skill, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit the rebuild: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a confirmed assessment gives one fact tied to its result with trust 1", func(t *testing.T) {
|
||||
if domain.EvidenceTrustOnlineUnconfirmed != 1 {
|
||||
t.Fatalf("the trust of an online result without identity confirmation = %d, want 1", domain.EvidenceTrustOnlineUnconfirmed)
|
||||
}
|
||||
page, response := readOwn(target, "")
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) != 1 ||
|
||||
page.Page.HasMore || page.Page.NextCursor != nil {
|
||||
t.Fatalf("own evidence = %d %q %s, want one no-store fact", response.Code, response.Header().Get("Cache-Control"), response.Body.String())
|
||||
}
|
||||
fact := page.Items[0]
|
||||
decidedAt, err := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
if err != nil {
|
||||
t.Fatalf("parse decided_at: %v", err)
|
||||
}
|
||||
if fact.ID == uuid.Nil || fact.Kind != "measurement" || fact.Source.Type != "assessment_result" ||
|
||||
fact.Source.EventID != targetRun.id || fact.Source.ResultID != targetRun.id ||
|
||||
!slices.Equal(fact.Skills, []string{"backend"}) || fact.Attribution != "personal" ||
|
||||
fact.Trust != int(domain.EvidenceTrustOnlineUnconfirmed) || fact.Visibility != "visible" ||
|
||||
fact.Result.Grade != "intern" || fact.Result.Basis != "synthetic_demo" || fact.Result.CalibrationStatus != "uncalibrated" ||
|
||||
!fact.OccurredAt.Equal(decidedAt) {
|
||||
t.Fatalf("fact = %+v, want a visible online measurement of the intern result %s decided at %s", fact, targetRun.id, decidedAt)
|
||||
}
|
||||
// The same result is readable by its identifier.
|
||||
if status, _ := client.call(t, target, http.MethodGet, "/api/v1/me/assessment-attempts/"+fact.Source.ResultID.String()+"/result", "", ""); status != http.StatusOK {
|
||||
t.Fatalf("result named by the fact = %d, want 200", status)
|
||||
}
|
||||
for _, leak := range []string{"answer", "score", "points", "reference", "seed", "item_", "signal", "review", "not_confirmed"} {
|
||||
if strings.Contains(strings.ToLower(response.Body.String()), leak) {
|
||||
t.Fatalf("own evidence exposes %q: %s", leak, response.Body.String())
|
||||
}
|
||||
}
|
||||
stored := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1 AND trust = 1 AND kind = 'measurement' AND result_id = $2`, target.id, targetRun.id)
|
||||
if stored != 1 {
|
||||
t.Fatalf("stored facts of the result = %d, want 1", stored)
|
||||
}
|
||||
|
||||
// Every owner reads only their own facts; a failed attempt gives none.
|
||||
for _, member := range cohort[1:] {
|
||||
memberPage, _ := readOwn(member, "")
|
||||
if len(memberPage.Items) != 1 || memberPage.Items[0].ID == fact.ID || memberPage.Items[0].Source.ResultID != runs[member.id].id {
|
||||
t.Fatalf("evidence of %s = %+v, want only their own fact", member.email, memberPage.Items)
|
||||
}
|
||||
}
|
||||
if failedPage, response := readOwn(failed, ""); response.Code != http.StatusOK || len(failedPage.Items) != 0 || failedPage.Page.HasMore {
|
||||
t.Fatalf("evidence after a failed attempt = %d %s, want no fact", response.Code, response.Body.String())
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, failed.id) != 0 {
|
||||
t.Fatal("a failed attempt stored a fact")
|
||||
}
|
||||
|
||||
// Access: a guest, an employer, and a malformed request are refused.
|
||||
if response := get(categoryHTTPCandidate{}, "/api/v1/me/evidence"); response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("evidence without a session = %d, want 401", response.Code)
|
||||
}
|
||||
if response := get(employerAccount, "/api/v1/me/evidence"); response.Code != http.StatusForbidden {
|
||||
t.Fatalf("evidence of an employer account = %d, want 403", response.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("several tags of one event stay one independent fact", func(t *testing.T) {
|
||||
rebuildWithTags(targetRun.id, "go", "postgresql")
|
||||
page, response := readOwn(target, "")
|
||||
if len(page.Items) != 1 || !slices.Equal(page.Items[0].Skills, []string{"backend", "go", "postgresql"}) {
|
||||
t.Fatalf("evidence after two more tags = %s, want a single fact with three tags", response.Body.String())
|
||||
}
|
||||
fact := page.Items[0]
|
||||
if facts, events := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id),
|
||||
countRows(`SELECT count(DISTINCT event_id) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id); facts != 1 || events != 1 {
|
||||
t.Fatalf("independent facts = %d over %d events, want 1 over 1", facts, events)
|
||||
}
|
||||
|
||||
// One event is one fact whatever its tags, and the tags are a closed set.
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
SELECT candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at
|
||||
FROM skill_evidence_facts WHERE id = $1`, fact.ID)
|
||||
assertPgError(t, "second fact for one event", err, "23505", "skill_evidence_facts_event_key")
|
||||
// A stored fact is sealed: a later transaction cannot add a tag to it.
|
||||
_, err = harness.pool.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) VALUES ($1, 'qa')`, fact.ID)
|
||||
assertPgError(t, "tag added to a stored fact", err, "23000", "skill_evidence_skills_fact_sealed")
|
||||
_, err = harness.pool.Exec(ctx, `UPDATE skill_evidence_skills SET skill_code = 'qa' WHERE fact_id = $1 AND skill_code = 'go'`, fact.ID)
|
||||
assertPgError(t, "rewrite of a tag", err, "23000", "skill_evidence_skills_immutable")
|
||||
_, err = harness.pool.Exec(ctx, `DELETE FROM skill_evidence_skills WHERE fact_id = $1`, fact.ID)
|
||||
assertPgError(t, "removal of tags", err, "23000", "skill_evidence_skills_immutable")
|
||||
// Inside the creating transaction the tags are still a set from the closed list.
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the tag check: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result($1)`, targetRun.id); err != nil {
|
||||
t.Fatalf("project the result: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `SAVEPOINT repeated`); err != nil {
|
||||
t.Fatalf("savepoint: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'backend' FROM skill_evidence_facts`)
|
||||
assertPgError(t, "repeated tag", err, "23505", "skill_evidence_skills_pkey")
|
||||
if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT repeated`); err != nil {
|
||||
t.Fatalf("roll back to the savepoint: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'rate-limiting' FROM skill_evidence_facts`)
|
||||
assertPgError(t, "tag outside the closed set", err, "23514", "skill_evidence_skills_code")
|
||||
})
|
||||
|
||||
t.Run("a stored fact keeps its result and trust and only its visibility changes", func(t *testing.T) {
|
||||
page, _ := readOwn(target, "")
|
||||
factID := page.Items[0].ID
|
||||
for name, test := range map[string]struct {
|
||||
sql, constraint string
|
||||
code string
|
||||
}{
|
||||
"trust": {`UPDATE skill_evidence_facts SET trust = 2 WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"grade": {`UPDATE skill_evidence_facts SET grade = 'senior' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"attribution": {`UPDATE skill_evidence_facts SET attribution = 'team_role' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"kind": {`UPDATE skill_evidence_facts SET kind = 'claim' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"removal": {`DELETE FROM skill_evidence_facts WHERE id = $1`, "skill_evidence_facts_immutable", "23000"},
|
||||
"bad hiding": {`UPDATE skill_evidence_facts SET visibility = 'public' WHERE id = $1`, "skill_evidence_facts_visibility", "23514"},
|
||||
} {
|
||||
_, err := harness.pool.Exec(ctx, test.sql, factID)
|
||||
assertPgError(t, name, err, test.code, test.constraint)
|
||||
}
|
||||
// A fact is a measurement of level 1 to 3 or a claim of level 0, never both.
|
||||
for name, statement := range map[string]string{
|
||||
"claim above level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, 'claim', source_type, event_id, result_id, attribution, 1, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
"measurement at level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 0, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
"online result in person": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 3, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`,
|
||||
} {
|
||||
if _, err := harness.pool.Exec(ctx, statement, factID); err == nil {
|
||||
t.Errorf("%s was stored", name)
|
||||
}
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE id = $1`, factID); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
hiddenPage, _ := readOwn(target, "")
|
||||
if len(hiddenPage.Items) != 1 || hiddenPage.Items[0].Visibility != "hidden" || hiddenPage.Items[0].Trust != 1 {
|
||||
t.Fatalf("own evidence after hiding = %+v, want the same fact with visibility hidden", hiddenPage.Items)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE id = $1`, factID); err != nil {
|
||||
t.Fatalf("show the fact again: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an express run creates no qualifying evidence, category, or cohort entry", func(t *testing.T) {
|
||||
expressOnly := client.candidate(t, "evidence-express@example.test")
|
||||
beforeBody := readOwnBody(t, get, target)
|
||||
beforeFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`)
|
||||
beforeCategories := countStoredCategories(t, ctx, harness.pool, target.id)
|
||||
expressIDs := make([]uuid.UUID, 0, 2)
|
||||
for _, who := range []categoryHTTPCandidate{target, expressOnly} {
|
||||
expressIDs = append(expressIDs, runPerfectExpress(t, ctx, client, harness.assessmentAttemptHTTPHarness, who))
|
||||
}
|
||||
if afterBody := readOwnBody(t, get, target); afterBody != beforeBody {
|
||||
t.Fatalf("evidence changed after an express run:\n%s\n%s", beforeBody, afterBody)
|
||||
}
|
||||
if page, _ := readOwn(expressOnly, ""); len(page.Items) != 0 {
|
||||
t.Fatalf("evidence after express only = %+v, want none", page.Items)
|
||||
}
|
||||
if afterFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`); afterFacts != beforeFacts {
|
||||
t.Fatalf("facts after express = %d, want the %d before", afterFacts, beforeFacts)
|
||||
}
|
||||
if countStoredCategories(t, ctx, harness.pool, target.id) != beforeCategories || countStoredCategories(t, ctx, harness.pool, expressOnly.id) != 0 {
|
||||
t.Fatal("an express run changed a category")
|
||||
}
|
||||
// The database also refuses a fact whose source is an express result or
|
||||
// a failed attempt, even through a direct write.
|
||||
for name, source := range map[string]struct{ owner, attempt uuid.UUID }{
|
||||
"express result of the owner": {target.id, expressIDs[0]},
|
||||
"express result of an outsider": {expressOnly.id, expressIDs[1]},
|
||||
"failed attempt": {failed.id, failedRun.id},
|
||||
} {
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
VALUES ($1, 'measurement', 'assessment_result', $2, $2, 'personal', 1, 'intern', 'synthetic_demo', 'uncalibrated', now())`, source.owner, source.attempt)
|
||||
assertPgError(t, name, err, "23514", "skill_evidence_facts_source_result")
|
||||
}
|
||||
// Neither run enters the card cohort as a confirmed category.
|
||||
consent := privacy.grant(t, expressOnly.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, expressOnly.id, consent.ID(), 0, domain.CardFieldCategories)
|
||||
sources, err := postgresadapter.NewPrivacyCohortStore(harness.pool).ListVisibleCandidateViewSources(ctx, organizationA.ID())
|
||||
if err != nil {
|
||||
t.Fatalf("ListVisibleCandidateViewSources() error = %v", err)
|
||||
}
|
||||
for _, source := range sources {
|
||||
categories := source.Input("cv1_"+strings.Repeat("A", 43), now).ConfirmedCategories
|
||||
if source.CandidateID() == expressOnly.id && len(categories) != 0 {
|
||||
t.Fatalf("express-only candidate has categories %v in the cohort", categories)
|
||||
}
|
||||
}
|
||||
// Withdraw the express-only publication so that it does not join the cohort of the target.
|
||||
privacy.revokeC2(t, expressOnly.id, now.Add(time.Second))
|
||||
})
|
||||
|
||||
t.Run("the list pages by a cursor bound to its owner", func(t *testing.T) {
|
||||
pager := client.candidate(t, "evidence-pager@example.test")
|
||||
first := passingIntern(pager)
|
||||
moveFinishedAttemptBack(t, ctx, harness.pool, first.id, categoryHTTPPromotionGap)
|
||||
second := client.run(t, pager, "backend", "junior", func(int) int { return threshold })
|
||||
if second.result["outcome"] != "confirmed" {
|
||||
t.Fatalf("promotion run = %v, want confirmed", second.result["outcome"])
|
||||
}
|
||||
firstPage, response := readOwn(pager, "?limit=1")
|
||||
if response.Code != http.StatusOK || len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil ||
|
||||
firstPage.Items[0].Source.ResultID != second.id || firstPage.Items[0].Result.Grade != "junior" {
|
||||
t.Fatalf("first page = %d %s, want the junior fact and a cursor", response.Code, response.Body.String())
|
||||
}
|
||||
secondPage, response := readOwn(pager, "?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor))
|
||||
if response.Code != http.StatusOK || len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil ||
|
||||
secondPage.Items[0].Source.ResultID != first.id || secondPage.Items[0].Result.Grade != "intern" {
|
||||
t.Fatalf("second page = %d %s, want the intern fact and no more", response.Code, response.Body.String())
|
||||
}
|
||||
if firstPage.Items[0].ID == secondPage.Items[0].ID {
|
||||
t.Fatal("two events produced one fact")
|
||||
}
|
||||
for _, query := range []string{"?cursor=" + url.QueryEscape(*firstPage.Page.NextCursor), "?limit=0", "?limit=101", "?cursor=not-a-cursor"} {
|
||||
who := pager
|
||||
if strings.HasPrefix(query, "?cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) {
|
||||
who = target // the cursor belongs to the pager
|
||||
}
|
||||
if response := get(who, "/api/v1/me/evidence"+query); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("evidence query %q = %d %s, want 400", query, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the preview shows the one fact for each category that an organization would read", func(t *testing.T) {
|
||||
type previewBody struct {
|
||||
Card json.RawMessage `json:"card"`
|
||||
Evidence *struct {
|
||||
Items []struct {
|
||||
Skill string `json:"skill"`
|
||||
Grade string `json:"grade"`
|
||||
Trust int `json:"trust"`
|
||||
ObservedYear int `json:"observed_year"`
|
||||
Basis string `json:"basis"`
|
||||
Calibration string `json:"calibration_status"`
|
||||
} `json:"items"`
|
||||
} `json:"evidence"`
|
||||
}
|
||||
preview := func(who categoryHTTPCandidate) previewBody {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/privacy/preview")
|
||||
var body previewBody
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || json.Unmarshal(response.Body.Bytes(), &body) != nil {
|
||||
t.Fatalf("preview of %s = %d %q %s", who.email, response.Code, response.Header().Get("Cache-Control"), response.Body.String())
|
||||
}
|
||||
return body
|
||||
}
|
||||
decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
body := preview(target)
|
||||
if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Skill != "backend" ||
|
||||
body.Evidence.Items[0].Grade != "intern" || body.Evidence.Items[0].Trust != 1 ||
|
||||
body.Evidence.Items[0].Basis != "synthetic_demo" || body.Evidence.Items[0].Calibration != "uncalibrated" || body.Evidence.Items[0].ObservedYear != decidedAt.UTC().Year() {
|
||||
t.Fatalf("preview evidence = %+v, want the backend intern fact of %d", body.Evidence, decidedAt.UTC().Year())
|
||||
}
|
||||
// A closed profile has no card and no evidence section.
|
||||
if closed := preview(failed); string(closed.Card) != "null" || closed.Evidence != nil {
|
||||
t.Fatalf("preview of a closed profile = card %s, evidence %+v, want both null", closed.Card, closed.Evidence)
|
||||
}
|
||||
|
||||
// A candidate with a lower and a higher passed grade: one fact, the one
|
||||
// that supports the confirmed grade, whichever way it is asked for.
|
||||
pagerAccount := client.candidate(t, "evidence-supporting@example.test")
|
||||
lower := passingIntern(pagerAccount)
|
||||
moveFinishedAttemptBack(t, ctx, harness.pool, lower.id, categoryHTTPPromotionGap)
|
||||
higher := client.run(t, pagerAccount, "backend", "junior", func(int) int { return threshold })
|
||||
if higher.result["outcome"] != "confirmed" {
|
||||
t.Fatalf("promotion run = %v, want confirmed", higher.result["outcome"])
|
||||
}
|
||||
consent := privacy.grant(t, pagerAccount.id, domain.ConsentPurposePublication, privacyC2Version, now)
|
||||
privacy.publish(t, pagerAccount.id, consent.ID(), 0, domain.CardFieldCategories)
|
||||
body = preview(pagerAccount)
|
||||
if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Grade != "junior" {
|
||||
t.Fatalf("preview evidence with two passed grades = %+v, want only the junior fact", body.Evidence)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeJunior {
|
||||
t.Fatalf("organization evidence for the junior category = %+v, want the junior fact", facts)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeIntern)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeIntern {
|
||||
t.Fatalf("organization evidence for the intern category = %+v, want the intern fact", facts)
|
||||
}
|
||||
// A hidden fact leaves the preview as it leaves the organization.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, pagerAccount.id); err != nil {
|
||||
t.Fatalf("hide the facts: %v", err)
|
||||
}
|
||||
if body = preview(pagerAccount); body.Evidence == nil || len(body.Evidence.Items) != 0 {
|
||||
t.Fatalf("preview evidence of hidden facts = %+v, want an empty list", body.Evidence)
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 0 {
|
||||
t.Fatalf("organization evidence of hidden facts = %+v, want none", facts)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, pagerAccount.id); err != nil {
|
||||
t.Fatalf("show the facts: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an organization reads the permitted projection only while the card is visible", func(t *testing.T) {
|
||||
handle := aliasIn(organizationA.ID(), target.id)
|
||||
path := organizationPath(organizationA.ID(), handle)
|
||||
response := get(employerAccount, path)
|
||||
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("permitted projection = %d %q %s\n%s", response.Code, response.Header().Get("Cache-Control"), response.Body.String(), harness.logs.String())
|
||||
}
|
||||
decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string))
|
||||
// One fact for the one category of the card, with the skill, the grade,
|
||||
// the trust level, and the year only; the other tags stay with the candidate.
|
||||
wantBody := fmt.Sprintf(`{"items":[{"skill":"backend","grade":"intern","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":%d}]}`, decidedAt.UTC().Year())
|
||||
if strings.TrimSpace(response.Body.String()) != wantBody {
|
||||
t.Fatalf("permitted projection = %s, want %s", response.Body.String(), wantBody)
|
||||
}
|
||||
for _, private := range []string{target.id.String(), targetRun.id.String(), "event_id", "result_id", "occurred_at", "observed_month", "visibility", "answer", "score", "points", "signal", "review", "not_confirmed", `"id"`} {
|
||||
if strings.Contains(response.Body.String(), private) {
|
||||
t.Fatalf("permitted projection exposes %q: %s", private, response.Body.String())
|
||||
}
|
||||
}
|
||||
// The read is a card view: the quota is used once and the candidate sees the access.
|
||||
for range 2 {
|
||||
if again := get(employerAccount, path); again.Code != http.StatusOK {
|
||||
t.Fatalf("repeated projection = %d %s", again.Code, again.Body.String())
|
||||
}
|
||||
}
|
||||
if usage := countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, target.id, organizationA.ID()); usage != 1 {
|
||||
t.Fatalf("card-view quota usage = %d, want one distinct card", usage)
|
||||
}
|
||||
if audits := countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' AND field_codes = ARRAY['categories']::text[]`, target.id, organizationA.ID()); audits != 3 {
|
||||
t.Fatalf("access records of the categories field = %d, want 3", audits)
|
||||
}
|
||||
|
||||
// Access: the roles and the scope of the handle.
|
||||
if response := get(target, path); response.Code != http.StatusForbidden {
|
||||
t.Fatalf("candidate account reads the projection = %d, want 403", response.Code)
|
||||
}
|
||||
if response := get(categoryHTTPCandidate{}, path); response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("guest reads the projection = %d, want 401", response.Code)
|
||||
}
|
||||
for name, other := range map[string]string{
|
||||
"other member's organization": organizationPath(foreignOrganization.ID(), handle),
|
||||
"unknown organization": organizationPath(uuid.New(), handle),
|
||||
"alias of another organization": organizationPath(organizationB.ID(), handle),
|
||||
"unknown alias": organizationPath(organizationA.ID(), "cv1_"+strings.Repeat("A", 43)),
|
||||
} {
|
||||
if response := get(employerAccount, other); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("%s = %d %s, want 404", name, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if response := get(employerAccount, organizationPath(organizationA.ID(), "candidate")); response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("malformed handle = %d, want 400", response.Code)
|
||||
}
|
||||
if response := get(foreignAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("employer without a membership = %d, want 404", response.Code)
|
||||
}
|
||||
|
||||
// The statement itself rechecks the barrier, whatever the caller did.
|
||||
backendIntern := category(domain.SpecializationBackend, domain.GradeIntern)
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 1 ||
|
||||
facts[0].Input() != (domain.EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: domain.GradeIntern, Trust: 1, Basis: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: int32(decidedAt.UTC().Year()),
|
||||
}) {
|
||||
t.Fatalf("repository projection = %+v, want the one backend intern fact", facts)
|
||||
}
|
||||
for name, categories := range map[string][]domain.CandidateViewCategory{
|
||||
"a specialization without a fact": {category(domain.SpecializationQA, domain.GradeIntern)},
|
||||
"a grade the candidate did not pass": {category(domain.SpecializationBackend, domain.GradeSenior)},
|
||||
"no category on the card": nil,
|
||||
} {
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, categories...); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for %s = %+v, want none", name, facts)
|
||||
}
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), uuid.New(), backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for an unknown candidate = %+v, want none", facts)
|
||||
}
|
||||
|
||||
// A hidden fact is absent from what the organization reads.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
hidden := get(employerAccount, path)
|
||||
if hidden.Code != http.StatusOK || strings.TrimSpace(hidden.Body.String()) != `{"items":[]}` {
|
||||
t.Fatalf("projection of a hidden fact = %d %s, want no data", hidden.Code, hidden.Body.String())
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Visibility != "hidden" {
|
||||
t.Fatalf("owner after hiding = %+v, want the fact with visibility hidden", page.Items)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("show the fact: %v", err)
|
||||
}
|
||||
|
||||
// A card that does not publish the categories field carries no evidence.
|
||||
publication := privacy.loadPublication(t, target.id)
|
||||
privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldStack)
|
||||
if response := get(employerAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("projection of a card without categories = %d %s, want 404", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection without the categories field = %+v, want none", facts)
|
||||
}
|
||||
publication = privacy.loadPublication(t, target.id)
|
||||
privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldCategories)
|
||||
if response := get(employerAccount, path); response.Code != http.StatusOK {
|
||||
t.Fatalf("projection after publishing the categories again = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
// Hiding the organization closes it for that organization only.
|
||||
privacy.hide(t, target.id, organizationA.ID(), now.Add(2*time.Second))
|
||||
if response := get(employerAccount, path); response.Code != http.StatusNotFound {
|
||||
t.Fatalf("projection for a hidden organization = %d %s, want 404", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection for a hidden organization = %+v, want none", facts)
|
||||
}
|
||||
if facts := organizationFacts(organizationB.ID(), target.id, backendIntern); len(facts) != 1 {
|
||||
t.Fatalf("repository projection for another organization = %+v, want one fact", facts)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1`, target.id); err != nil {
|
||||
t.Fatalf("lift the hiding: %v", err)
|
||||
}
|
||||
if response := get(employerAccount, path); response.Code != http.StatusOK {
|
||||
t.Fatalf("projection after the hiding was lifted = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
// C2 true, then false: after the revocation there is no data, for any organization.
|
||||
privacy.revokeC2(t, target.id, now.Add(3*time.Second))
|
||||
for _, organization := range []domain.Organization{organizationA, organizationB} {
|
||||
response := get(employerAccount, organizationPath(organization.ID(), aliasIn(organization.ID(), target.id)))
|
||||
if response.Code != http.StatusNotFound || strings.Contains(response.Body.String(), "measurement") {
|
||||
t.Fatalf("projection after the C2 revocation = %d %s, want 404 without data", response.Code, response.Body.String())
|
||||
}
|
||||
if facts := organizationFacts(organization.ID(), target.id, backendIntern); len(facts) != 0 {
|
||||
t.Fatalf("repository projection after the C2 revocation = %+v, want none", facts)
|
||||
}
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 {
|
||||
t.Fatalf("owner evidence after the C2 revocation = %+v, want the fact kept", page.Items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("deleting the account removes its facts through both cascade paths", func(t *testing.T) {
|
||||
erased := client.candidate(t, "evidence-erased@example.test")
|
||||
run := passingIntern(erased)
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, erased.id) != 1 {
|
||||
t.Fatal("the candidate to erase has no fact")
|
||||
}
|
||||
// The ledger and history guards keep a confirmed account; this fixture
|
||||
// lifts them for one transaction, as the deletion procedure will. The
|
||||
// foreign keys and the triggers of the evidence stay on.
|
||||
tx, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin the erasure: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
for _, statement := range []string{
|
||||
`ALTER TABLE consent_records DISABLE TRIGGER USER`,
|
||||
`ALTER TABLE users DISABLE TRIGGER USER`,
|
||||
} {
|
||||
if _, err := tx.Exec(ctx, statement); err != nil {
|
||||
t.Fatalf("lift the retention guards (%s): %v", statement, err)
|
||||
}
|
||||
}
|
||||
// Both paths lead to the fact: the owner of the fact and the result it names.
|
||||
if _, err := tx.Exec(ctx, `ALTER TABLE assessment_attempt_results DISABLE TRIGGER assessment_attempt_result_refuse_mutation`); err != nil {
|
||||
t.Fatalf("lift the result guard: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `ALTER TABLE candidate_assessment_categories DISABLE TRIGGER candidate_assessment_category_refuse_delete`); err != nil {
|
||||
t.Fatalf("lift the category guard: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM consent_records WHERE subject_id = $1`, erased.id); err != nil {
|
||||
t.Fatalf("delete the consent records: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM users WHERE id = $1`, erased.id); err != nil {
|
||||
t.Fatalf("delete the account: %v", err)
|
||||
}
|
||||
for table, column := range map[string]string{
|
||||
"skill_evidence_facts": "candidate_id", "assessment_attempt_results": "user_id",
|
||||
} {
|
||||
var remaining int
|
||||
if err := tx.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s = $1`, table, column), erased.id).Scan(&remaining); err != nil || remaining != 0 {
|
||||
t.Fatalf("rows of %s after the account was deleted = %d (error %v), want 0", table, remaining, err)
|
||||
}
|
||||
}
|
||||
var tags int
|
||||
if err := tx.QueryRow(ctx, `SELECT count(*) FROM skill_evidence_skills AS tag WHERE NOT EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = tag.fact_id)`).Scan(&tags); err != nil || tags != 0 {
|
||||
t.Fatalf("orphan tags = %d (error %v), want 0", tags, err)
|
||||
}
|
||||
// The guards come back before the erasure is committed.
|
||||
for _, statement := range []string{
|
||||
`ALTER TABLE consent_records ENABLE TRIGGER USER`,
|
||||
`ALTER TABLE users ENABLE TRIGGER USER`,
|
||||
`ALTER TABLE assessment_attempt_results ENABLE TRIGGER assessment_attempt_result_refuse_mutation`,
|
||||
`ALTER TABLE candidate_assessment_categories ENABLE TRIGGER candidate_assessment_category_refuse_delete`,
|
||||
} {
|
||||
if _, err := tx.Exec(ctx, statement); err != nil {
|
||||
t.Fatalf("restore the guard (%s): %v", statement, err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit the erasure: %v", err)
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM pg_trigger WHERE tgenabled = 'D' AND NOT tgisinternal`) != 0 {
|
||||
t.Fatal("a trigger stayed disabled after the erasure")
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE result_id = $1`, run.id) != 0 {
|
||||
t.Fatal("a fact of the erased account remains")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the projection is rebuilt from the results and survives the migration", func(t *testing.T) {
|
||||
qualifying := countRows(`
|
||||
SELECT count(*) FROM assessment_attempt_results
|
||||
WHERE schema_version = 2 AND kind IN ('root', 'corrective') AND outcome = 'confirmed'
|
||||
AND category_decision ->> 'status' IN ('assigned', 'unchanged')`)
|
||||
eventsBefore := evidenceEventIDs(t, ctx, harness)
|
||||
// Cohort of five, two promotions of the pager and two of the candidate of the
|
||||
// preview; nothing from the failed or express runs.
|
||||
if want := evidenceCohortSize + 4; qualifying != want || len(eventsBefore) != want {
|
||||
t.Fatalf("qualifying results = %d, facts = %d, want %d of each", qualifying, len(eventsBefore), want)
|
||||
}
|
||||
|
||||
// A fact without a skill cannot be committed.
|
||||
if _, err := harness.pool.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil {
|
||||
t.Fatalf("empty the projection: %v", err)
|
||||
}
|
||||
_, err := harness.pool.Exec(ctx, `
|
||||
INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at)
|
||||
SELECT user_id, 'measurement', 'assessment_result', attempt_id, attempt_id, 'personal', 1, category_decision ->> 'attempted_grade',
|
||||
category_decision ->> 'source', category_decision ->> 'calibration_status', decided_at
|
||||
FROM assessment_attempt_results WHERE attempt_id = $1`, targetRun.id)
|
||||
assertPgError(t, "fact without a skill", err, "23514", "skill_evidence_facts_require_skill")
|
||||
|
||||
if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results again: %v", err)
|
||||
}
|
||||
if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) {
|
||||
t.Fatalf("rebuilt events = %v, want %v", eventsAfter, eventsBefore)
|
||||
}
|
||||
if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil {
|
||||
t.Fatalf("project the stored results a second time: %v", err)
|
||||
}
|
||||
if countRows(`SELECT count(*) FROM skill_evidence_facts`) != qualifying || countRows(`SELECT count(*) FROM skill_evidence_skills`) != qualifying {
|
||||
t.Fatal("a repeated projection duplicated facts or tags")
|
||||
}
|
||||
|
||||
// Rolling the migration back removes the projection and applying it again
|
||||
// derives it once more from the results that stayed.
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
// A fact that the candidate hid is a decision no result can bring back, so
|
||||
// the rollback refuses until nothing is hidden.
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil {
|
||||
t.Fatalf("hide the fact: %v", err)
|
||||
}
|
||||
_, err = migrator.DownOne(ctx)
|
||||
assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained")
|
||||
assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills")
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE event_id = $1`, targetRun.id); err != nil {
|
||||
t.Fatalf("show the fact: %v", err)
|
||||
}
|
||||
rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion-1)
|
||||
assertTablesExist(ctx, t, harness.pool, false, "skill_evidence_facts", "skill_evidence_skills")
|
||||
assertFunctionsExist(ctx, t, harness.pool, false,
|
||||
"skill_evidence_result_qualifies(assessment_attempt_results)", "skill_evidence_project_assessment_result(uuid)")
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) {
|
||||
t.Fatalf("events after the migration was applied again = %v, want %v", eventsAfter, eventsBefore)
|
||||
}
|
||||
if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Trust != 1 || page.Items[0].Source.ResultID != targetRun.id {
|
||||
t.Fatalf("evidence after the migration was applied again = %+v, want the backfilled fact", page.Items)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// readOwnBody returns the raw body of the owner's evidence.
|
||||
func readOwnBody(t *testing.T, get func(categoryHTTPCandidate, string) *httptest.ResponseRecorder, who categoryHTTPCandidate) string {
|
||||
t.Helper()
|
||||
response := get(who, "/api/v1/me/evidence")
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("own evidence = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
return response.Body.String()
|
||||
}
|
||||
|
||||
// evidenceEventIDs lists the source events of the stored facts in a stable order.
|
||||
func evidenceEventIDs(t *testing.T, ctx context.Context, harness *skillEvidenceHarness) []string {
|
||||
t.Helper()
|
||||
rows, err := harness.pool.Query(ctx, `SELECT event_id::text FROM skill_evidence_facts ORDER BY event_id`)
|
||||
if err != nil {
|
||||
t.Fatalf("list evidence events: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
events, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
t.Fatalf("read evidence events: %v", err)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
// runPerfectExpress answers every item of an express training run correctly,
|
||||
// finalizes it, and returns its attempt identifier.
|
||||
func runPerfectExpress(t *testing.T, ctx context.Context, client *categoryHTTPClient, harness *assessmentAttemptHTTPHarness, who categoryHTTPCandidate) uuid.UUID {
|
||||
t.Helper()
|
||||
key := uuid.NewString()
|
||||
status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, key+"-create")
|
||||
var attempt assessmentAnswerHTTPAttempt
|
||||
if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil {
|
||||
t.Fatalf("create express attempt = %d %s", status, body)
|
||||
}
|
||||
version := attempt.Version
|
||||
for _, item := range readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) {
|
||||
status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers",
|
||||
string(assessmentAnswerHTTPBody(t, version, item)), fmt.Sprintf("%s-answer-%d", key, item.Ordinal))
|
||||
var next assessmentAnswerHTTPAttempt
|
||||
if status != http.StatusOK || json.Unmarshal(body, &next) != nil {
|
||||
t.Fatalf("answer express item %d = %d %s", item.Ordinal, status, body)
|
||||
}
|
||||
version = next.Version
|
||||
}
|
||||
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal finalize body: %v", err)
|
||||
}
|
||||
if status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize",
|
||||
string(finalizeBody), key+"-finalize"); status != http.StatusOK {
|
||||
t.Fatalf("finalize express attempt = %d %s", status, body)
|
||||
}
|
||||
if result := client.result(t, who, attempt.ID); result["outcome"] != "demonstration" {
|
||||
t.Fatalf("express result = %v, want a demonstration", result)
|
||||
}
|
||||
return attempt.ID
|
||||
}
|
||||
@@ -4511,6 +4511,13 @@ func (s *Server) handleGetMyAssessmentSignalNoticeRequest(args [0]string, argsEs
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -6379,6 +6386,243 @@ func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsE
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationCandidateEvidenceRequest handles GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
func (s *Server) handleGetOrganizationCandidateEvidenceRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetOrganizationCandidateEvidence"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateEvidenceOperation,
|
||||
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: GetOrganizationCandidateEvidenceOperation,
|
||||
ID: "GetOrganizationCandidateEvidence",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateEvidenceOperation, 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
|
||||
}
|
||||
}
|
||||
params, err := decodeGetOrganizationCandidateEvidenceParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response GetOrganizationCandidateEvidenceRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetOrganizationCandidateEvidenceOperation,
|
||||
OperationSummary: "Read the permitted skill evidence of one currently visible candidate card.",
|
||||
OperationID: "GetOrganizationCandidateEvidence",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}: params.CandidateHandle,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetOrganizationCandidateEvidenceParams
|
||||
Response = GetOrganizationCandidateEvidenceRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetOrganizationCandidateEvidenceParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetOrganizationCandidateEvidence(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
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 := encodeGetOrganizationCandidateEvidenceResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -8367,6 +8611,228 @@ func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMyEvidenceRequest handles ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
func (s *Server) handleListMyEvidenceRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("ListMyEvidence"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/evidence"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyEvidenceOperation,
|
||||
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: ListMyEvidenceOperation,
|
||||
ID: "ListMyEvidence",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, ListMyEvidenceOperation, 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
|
||||
}
|
||||
}
|
||||
params, err := decodeListMyEvidenceParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response ListMyEvidenceRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: ListMyEvidenceOperation,
|
||||
OperationSummary: "List the skill evidence of the current candidate.",
|
||||
OperationID: "ListMyEvidence",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}: params.Limit,
|
||||
{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}: params.Cursor,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = ListMyEvidenceParams
|
||||
Response = ListMyEvidenceRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackListMyEvidenceParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.ListMyEvidence(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.ListMyEvidence(ctx, params)
|
||||
}
|
||||
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 := encodeListMyEvidenceResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleListMyHiddenOrganizationsRequest handles ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -105,6 +105,10 @@ type GetOrganizationCandidateCardRes interface {
|
||||
getOrganizationCandidateCardRes()
|
||||
}
|
||||
|
||||
type GetOrganizationCandidateEvidenceRes interface {
|
||||
getOrganizationCandidateEvidenceRes()
|
||||
}
|
||||
|
||||
type GetOrganizationInvitationContactsRes interface {
|
||||
getOrganizationInvitationContactsRes()
|
||||
}
|
||||
@@ -141,6 +145,10 @@ type ListMyConsentsRes interface {
|
||||
listMyConsentsRes()
|
||||
}
|
||||
|
||||
type ListMyEvidenceRes interface {
|
||||
listMyEvidenceRes()
|
||||
}
|
||||
|
||||
type ListMyHiddenOrganizationsRes interface {
|
||||
listMyHiddenOrganizationsRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -34,6 +34,7 @@ const (
|
||||
GetMySupportCaseOperation OperationName = "GetMySupportCase"
|
||||
GetOrganizationOperation OperationName = "GetOrganization"
|
||||
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
|
||||
GetOrganizationCandidateEvidenceOperation OperationName = "GetOrganizationCandidateEvidence"
|
||||
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
|
||||
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
|
||||
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
|
||||
@@ -43,6 +44,7 @@ const (
|
||||
ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults"
|
||||
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
|
||||
ListMyConsentsOperation OperationName = "ListMyConsents"
|
||||
ListMyEvidenceOperation OperationName = "ListMyEvidence"
|
||||
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
|
||||
ListMyInvitationsOperation OperationName = "ListMyInvitations"
|
||||
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
|
||||
|
||||
@@ -1917,6 +1917,147 @@ func decodeGetOrganizationCandidateCardParams(args [2]string, argsEscaped bool,
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateEvidenceParams is parameters of GetOrganizationCandidateEvidence operation.
|
||||
type GetOrganizationCandidateEvidenceParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
// this organization, checked by the server on every request; the identifier itself grants nothing. An
|
||||
// organization without such a membership and an unknown identifier both answer 404 not_found, so
|
||||
// organizations cannot be enumerated.
|
||||
OrgID uuid.UUID
|
||||
// Organization-scoped opaque candidate alias issued by the current visible card projection. The server
|
||||
// resolves it only for the organization in the path and rechecks current membership, publication
|
||||
// consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all
|
||||
// answer the same 404.
|
||||
CandidateHandle CandidateHandle
|
||||
}
|
||||
|
||||
func unpackGetOrganizationCandidateEvidenceParams(packed middleware.Parameters) (params GetOrganizationCandidateEvidenceParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}
|
||||
params.CandidateHandle = packed[key].(CandidateHandle)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetOrganizationCandidateEvidenceParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationCandidateEvidenceParams, _ error) {
|
||||
// Decode path: org_id.
|
||||
if err := func() error {
|
||||
param := args[0]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[0])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "org_id",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToUUID(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.OrgID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode path: candidate_handle.
|
||||
if err := func() error {
|
||||
param := args[1]
|
||||
if argsEscaped {
|
||||
unescaped, err := url.PathUnescape(args[1])
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "unescape path")
|
||||
}
|
||||
param = unescaped
|
||||
}
|
||||
if len(param) > 0 {
|
||||
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||
Param: "candidate_handle",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotCandidateHandleVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCandidateHandleVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.CandidateHandle = CandidateHandle(paramsDotCandidateHandleVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := params.CandidateHandle.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
|
||||
type GetOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -3027,6 +3168,182 @@ func decodeListMyConsentsParams(args [0]string, argsEscaped bool, r *http.Reques
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMyEvidenceParams is parameters of ListMyEvidence operation.
|
||||
type ListMyEvidenceParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
// `page.has_more` to detect the end.
|
||||
Limit OptInt32 `json:",omitempty,omitzero"`
|
||||
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
|
||||
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
|
||||
Cursor OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackListMyEvidenceParams(packed middleware.Parameters) (params ListMyEvidenceParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Limit = v.(OptInt32)
|
||||
}
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Cursor = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeListMyEvidenceParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyEvidenceParams, _ error) {
|
||||
q := uri.NewQueryDecoder(r.URL.Query())
|
||||
// Set default value for query: limit.
|
||||
{
|
||||
val := int32(20)
|
||||
params.Limit.SetTo(val)
|
||||
}
|
||||
// Decode query: limit.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "limit",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotLimitVal int32
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToInt32(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotLimitVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Limit.SetTo(paramsDotLimitVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Limit.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 100,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(value)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "limit",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode query: cursor.
|
||||
if err := func() error {
|
||||
cfg := uri.QueryParameterDecodingConfig{
|
||||
Name: "cursor",
|
||||
Style: uri.QueryStyleForm,
|
||||
Explode: true,
|
||||
}
|
||||
|
||||
if err := q.HasParam(cfg); err == nil {
|
||||
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotCursorVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCursorVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Cursor.SetTo(paramsDotCursorVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Cursor.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 512,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9_-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "cursor",
|
||||
In: "query",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ListMyHiddenOrganizationsParams is parameters of ListMyHiddenOrganizations operation.
|
||||
type ListMyHiddenOrganizationsParams struct {
|
||||
// Maximum number of items in the page. The server may return fewer items even when more remain; use
|
||||
|
||||
@@ -2472,6 +2472,121 @@ func encodeGetOrganizationCandidateCardResponse(response GetOrganizationCandidat
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationCandidateEvidenceResponse(response GetOrganizationCandidateEvidenceRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationEvidenceHeaders:
|
||||
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 *GetOrganizationCandidateEvidenceBadRequest:
|
||||
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 *GetOrganizationCandidateEvidenceUnauthorized:
|
||||
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 *GetOrganizationCandidateEvidenceForbidden:
|
||||
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 *GetOrganizationCandidateEvidenceNotFound:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(404)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.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 encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -3133,6 +3248,77 @@ func encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWri
|
||||
}
|
||||
}
|
||||
|
||||
func encodeListMyEvidenceResponse(response ListMyEvidenceRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *EvidenceFactListHeaders:
|
||||
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 *ListMyEvidenceBadRequest:
|
||||
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 *ListMyEvidenceUnauthorized:
|
||||
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 *ListMyEvidenceForbidden:
|
||||
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 encodeListMyHiddenOrganizationsResponse(response ListMyHiddenOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *HiddenOrganizationListHeaders:
|
||||
|
||||
@@ -11,46 +11,46 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn9AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn27AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn11AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn83AllowedHeaders = map[string]string{
|
||||
rn85AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn22AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn82AllowedHeaders = map[string]string{
|
||||
rn84AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn67AllowedHeaders = map[string]string{
|
||||
rn69AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn5AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn52AllowedHeaders = map[string]string{
|
||||
rn53AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
@@ -63,17 +63,17 @@ var (
|
||||
rn19AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn84AllowedHeaders = map[string]string{
|
||||
rn86AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn55AllowedHeaders = map[string]string{
|
||||
rn56AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "X-Csrf-Token",
|
||||
}
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
rn81AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn80AllowedHeaders = map[string]string{
|
||||
rn82AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn38AllowedHeaders = map[string]string{
|
||||
@@ -94,25 +94,25 @@ var (
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn45AllowedHeaders = map[string]string{
|
||||
rn46AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn87AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn77AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn85AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn18AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn48AllowedHeaders = map[string]string{
|
||||
rn49AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
)
|
||||
@@ -269,7 +269,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -346,7 +346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -370,7 +370,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
allowedHeaders: rn66AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -450,7 +450,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -572,7 +572,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn83AllowedHeaders,
|
||||
allowedHeaders: rn85AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -665,7 +665,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn82AllowedHeaders,
|
||||
allowedHeaders: rn84AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -692,7 +692,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn67AllowedHeaders,
|
||||
allowedHeaders: rn69AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -903,7 +903,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -937,7 +937,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn52AllowedHeaders,
|
||||
allowedHeaders: rn53AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -950,6 +950,31 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
}
|
||||
|
||||
case 'e': // Prefix: "evidence"
|
||||
|
||||
if l := len("evidence"); len(elem) >= l && elem[0:l] == "evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListMyEvidenceRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -1120,7 +1145,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn84AllowedHeaders,
|
||||
allowedHeaders: rn86AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1300,7 +1325,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn55AllowedHeaders,
|
||||
allowedHeaders: rn56AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1391,7 +1416,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
allowedHeaders: rn81AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1418,7 +1443,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn80AllowedHeaders,
|
||||
allowedHeaders: rn82AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1637,16 +1662,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
args[1] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetOrganizationCandidateCardRequest([2]string{
|
||||
@@ -1664,6 +1688,36 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/evidence"
|
||||
|
||||
if l := len("/evidence"); len(elem) >= l && elem[0:l] == "/evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetOrganizationCandidateEvidenceRequest([2]string{
|
||||
args[0],
|
||||
args[1],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
@@ -1727,7 +1781,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn45AllowedHeaders,
|
||||
allowedHeaders: rn46AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -1807,7 +1861,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn66AllowedHeaders,
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1835,7 +1889,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1865,7 +1919,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn85AllowedHeaders,
|
||||
allowedHeaders: rn87AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1898,7 +1952,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1970,7 +2024,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn48AllowedHeaders,
|
||||
allowedHeaders: rn49AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -2893,6 +2947,31 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
|
||||
}
|
||||
|
||||
case 'e': // Prefix: "evidence"
|
||||
|
||||
if l := len("evidence"); len(elem) >= l && elem[0:l] == "evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListMyEvidenceOperation
|
||||
r.summary = "List the skill evidence of the current candidate."
|
||||
r.operationID = "ListMyEvidence"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/evidence"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -3595,16 +3674,15 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[1] = elem
|
||||
elem = ""
|
||||
args[1] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetOrganizationCandidateCardOperation
|
||||
@@ -3619,6 +3697,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/evidence"
|
||||
|
||||
if l := len("/evidence"); len(elem) >= l && elem[0:l] == "/evidence" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetOrganizationCandidateEvidenceOperation
|
||||
r.summary = "Read the permitted skill evidence of one currently visible candidate card."
|
||||
r.operationID = "GetOrganizationCandidateEvidence"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
|
||||
r.args = args
|
||||
r.count = 2
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
|
||||
@@ -7117,7 +7117,11 @@ func (s *CardCategoryStrength) UnmarshalText(data []byte) error {
|
||||
// leave only through the contact grant of an accepted invitation (C4), and the lowest salary never
|
||||
// leaves.
|
||||
//
|
||||
// - categories: specialization and grade confirmed by an authoritative assessment result.
|
||||
// - categories: specialization and grade confirmed by an authoritative assessment result. With it an
|
||||
// organization receives the confirmed category and, with each category of the card, one supporting
|
||||
// assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and
|
||||
// the basis and calibration that mark a synthetic, uncalibrated demonstration
|
||||
// (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`.
|
||||
// - self_assessment: the candidate's declared specialization and grade, separate from confirmed
|
||||
// categories.
|
||||
// - stack: only recognized technology codes from the server's closed taxonomy.
|
||||
@@ -7231,12 +7235,15 @@ type CardFieldSet []CardField
|
||||
// pseudonym uses a separate preview context and is not an organization's alias. Organization-specific
|
||||
// visibility filters and cohort checks can further generalize or suppress the organization-facing
|
||||
// card. This read creates no view or history record and never reaches an organization. `card` is null
|
||||
// while the profile is closed.
|
||||
// while the profile is closed. `evidence` is what an organization would read in the evidence section
|
||||
// of the card, one supporting assessment fact for each category of the card, and is null exactly when
|
||||
// `card` is null; the organization-facing section can still be generalized or suppressed.
|
||||
// Ref: #/components/schemas/CardPreview
|
||||
type CardPreview struct {
|
||||
State PublicationState `json:"state"`
|
||||
Fields CardFieldSet `json:"fields"`
|
||||
Card NilAnonymousCardContent `json:"card"`
|
||||
Evidence NilOrganizationEvidence `json:"evidence"`
|
||||
GeneratedAt Timestamp `json:"generated_at"`
|
||||
}
|
||||
|
||||
@@ -7255,6 +7262,11 @@ func (s *CardPreview) GetCard() NilAnonymousCardContent {
|
||||
return s.Card
|
||||
}
|
||||
|
||||
// GetEvidence returns the value of Evidence.
|
||||
func (s *CardPreview) GetEvidence() NilOrganizationEvidence {
|
||||
return s.Evidence
|
||||
}
|
||||
|
||||
// GetGeneratedAt returns the value of GeneratedAt.
|
||||
func (s *CardPreview) GetGeneratedAt() Timestamp {
|
||||
return s.GeneratedAt
|
||||
@@ -7275,6 +7287,11 @@ func (s *CardPreview) SetCard(val NilAnonymousCardContent) {
|
||||
s.Card = val
|
||||
}
|
||||
|
||||
// SetEvidence sets the value of Evidence.
|
||||
func (s *CardPreview) SetEvidence(val NilOrganizationEvidence) {
|
||||
s.Evidence = val
|
||||
}
|
||||
|
||||
// SetGeneratedAt sets the value of GeneratedAt.
|
||||
func (s *CardPreview) SetGeneratedAt(val Timestamp) {
|
||||
s.GeneratedAt = val
|
||||
@@ -9672,6 +9689,651 @@ func (EmailVerificationResultEmailVerified) AllValues() []EmailVerificationResul
|
||||
}
|
||||
}
|
||||
|
||||
// Whose contribution the fact is.
|
||||
//
|
||||
// - personal: the candidate's own result. Every assessment fact is personal.
|
||||
// - team_role: a team result with a confirmed role of the candidate.
|
||||
// - team_unattributed: a team result without a confirmed role; it is not a personal skill.
|
||||
//
|
||||
// Only `personal` is produced today.
|
||||
// Ref: #/components/schemas/EvidenceAttribution
|
||||
type EvidenceAttribution string
|
||||
|
||||
const (
|
||||
EvidenceAttributionPersonal EvidenceAttribution = "personal"
|
||||
EvidenceAttributionTeamRole EvidenceAttribution = "team_role"
|
||||
EvidenceAttributionTeamUnattributed EvidenceAttribution = "team_unattributed"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceAttribution values.
|
||||
func (EvidenceAttribution) AllValues() []EvidenceAttribution {
|
||||
return []EvidenceAttribution{
|
||||
EvidenceAttributionPersonal,
|
||||
EvidenceAttributionTeamRole,
|
||||
EvidenceAttributionTeamUnattributed,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceAttribution) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceAttributionPersonal:
|
||||
return []byte(s), nil
|
||||
case EvidenceAttributionTeamRole:
|
||||
return []byte(s), nil
|
||||
case EvidenceAttributionTeamUnattributed:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceAttribution) UnmarshalText(data []byte) error {
|
||||
switch EvidenceAttribution(data) {
|
||||
case EvidenceAttributionPersonal:
|
||||
*s = EvidenceAttributionPersonal
|
||||
return nil
|
||||
case EvidenceAttributionTeamRole:
|
||||
*s = EvidenceAttributionTeamRole
|
||||
return nil
|
||||
case EvidenceAttributionTeamUnattributed:
|
||||
*s = EvidenceAttributionTeamUnattributed
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// What the measurement rests on.
|
||||
//
|
||||
// - synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics
|
||||
// and is not a validated measurement.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceBasis
|
||||
type EvidenceBasis string
|
||||
|
||||
const (
|
||||
EvidenceBasisSyntheticDemo EvidenceBasis = "synthetic_demo"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceBasis values.
|
||||
func (EvidenceBasis) AllValues() []EvidenceBasis {
|
||||
return []EvidenceBasis{
|
||||
EvidenceBasisSyntheticDemo,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceBasis) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceBasisSyntheticDemo:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceBasis) UnmarshalText(data []byte) error {
|
||||
switch EvidenceBasis(data) {
|
||||
case EvidenceBasisSyntheticDemo:
|
||||
*s = EvidenceBasisSyntheticDemo
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Calibration of the method behind the result.
|
||||
//
|
||||
// - uncalibrated: the thresholds are initial values that no measurement has validated.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceCalibrationStatus
|
||||
type EvidenceCalibrationStatus string
|
||||
|
||||
const (
|
||||
EvidenceCalibrationStatusUncalibrated EvidenceCalibrationStatus = "uncalibrated"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceCalibrationStatus values.
|
||||
func (EvidenceCalibrationStatus) AllValues() []EvidenceCalibrationStatus {
|
||||
return []EvidenceCalibrationStatus{
|
||||
EvidenceCalibrationStatusUncalibrated,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceCalibrationStatus) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceCalibrationStatusUncalibrated:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceCalibrationStatus) UnmarshalText(data []byte) error {
|
||||
switch EvidenceCalibrationStatus(data) {
|
||||
case EvidenceCalibrationStatusUncalibrated:
|
||||
*s = EvidenceCalibrationStatusUncalibrated
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// One independent fact of the current candidate. `occurred_at` is when the source event ended; for an
|
||||
// assessment it is the time of the decision. A fact is one source event; the skills of that event are
|
||||
// tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their
|
||||
// visibility, because the candidate owns them.
|
||||
// Ref: #/components/schemas/EvidenceFact
|
||||
type EvidenceFact struct {
|
||||
// Identifier of the fact.
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind EvidenceKind `json:"kind"`
|
||||
Source EvidenceSource `json:"source"`
|
||||
// Skill tags of the event in ascending order.
|
||||
Skills []EvidenceSkillCode `json:"skills"`
|
||||
Result EvidenceResult `json:"result"`
|
||||
Attribution EvidenceAttribution `json:"attribution"`
|
||||
Trust EvidenceTrustLevel `json:"trust"`
|
||||
OccurredAt Timestamp `json:"occurred_at"`
|
||||
Visibility EvidenceVisibility `json:"visibility"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *EvidenceFact) GetID() uuid.UUID {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EvidenceFact) GetKind() EvidenceKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetSource returns the value of Source.
|
||||
func (s *EvidenceFact) GetSource() EvidenceSource {
|
||||
return s.Source
|
||||
}
|
||||
|
||||
// GetSkills returns the value of Skills.
|
||||
func (s *EvidenceFact) GetSkills() []EvidenceSkillCode {
|
||||
return s.Skills
|
||||
}
|
||||
|
||||
// GetResult returns the value of Result.
|
||||
func (s *EvidenceFact) GetResult() EvidenceResult {
|
||||
return s.Result
|
||||
}
|
||||
|
||||
// GetAttribution returns the value of Attribution.
|
||||
func (s *EvidenceFact) GetAttribution() EvidenceAttribution {
|
||||
return s.Attribution
|
||||
}
|
||||
|
||||
// GetTrust returns the value of Trust.
|
||||
func (s *EvidenceFact) GetTrust() EvidenceTrustLevel {
|
||||
return s.Trust
|
||||
}
|
||||
|
||||
// GetOccurredAt returns the value of OccurredAt.
|
||||
func (s *EvidenceFact) GetOccurredAt() Timestamp {
|
||||
return s.OccurredAt
|
||||
}
|
||||
|
||||
// GetVisibility returns the value of Visibility.
|
||||
func (s *EvidenceFact) GetVisibility() EvidenceVisibility {
|
||||
return s.Visibility
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *EvidenceFact) SetID(val uuid.UUID) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EvidenceFact) SetKind(val EvidenceKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetSource sets the value of Source.
|
||||
func (s *EvidenceFact) SetSource(val EvidenceSource) {
|
||||
s.Source = val
|
||||
}
|
||||
|
||||
// SetSkills sets the value of Skills.
|
||||
func (s *EvidenceFact) SetSkills(val []EvidenceSkillCode) {
|
||||
s.Skills = val
|
||||
}
|
||||
|
||||
// SetResult sets the value of Result.
|
||||
func (s *EvidenceFact) SetResult(val EvidenceResult) {
|
||||
s.Result = val
|
||||
}
|
||||
|
||||
// SetAttribution sets the value of Attribution.
|
||||
func (s *EvidenceFact) SetAttribution(val EvidenceAttribution) {
|
||||
s.Attribution = val
|
||||
}
|
||||
|
||||
// SetTrust sets the value of Trust.
|
||||
func (s *EvidenceFact) SetTrust(val EvidenceTrustLevel) {
|
||||
s.Trust = val
|
||||
}
|
||||
|
||||
// SetOccurredAt sets the value of OccurredAt.
|
||||
func (s *EvidenceFact) SetOccurredAt(val Timestamp) {
|
||||
s.OccurredAt = val
|
||||
}
|
||||
|
||||
// SetVisibility sets the value of Visibility.
|
||||
func (s *EvidenceFact) SetVisibility(val EvidenceVisibility) {
|
||||
s.Visibility = val
|
||||
}
|
||||
|
||||
// One page of the facts of the current candidate, newest event first.
|
||||
// Ref: #/components/schemas/EvidenceFactList
|
||||
type EvidenceFactList struct {
|
||||
// Facts of the page.
|
||||
Items []EvidenceFact `json:"items"`
|
||||
Page PageInfo `json:"page"`
|
||||
}
|
||||
|
||||
// GetItems returns the value of Items.
|
||||
func (s *EvidenceFactList) GetItems() []EvidenceFact {
|
||||
return s.Items
|
||||
}
|
||||
|
||||
// GetPage returns the value of Page.
|
||||
func (s *EvidenceFactList) GetPage() PageInfo {
|
||||
return s.Page
|
||||
}
|
||||
|
||||
// SetItems sets the value of Items.
|
||||
func (s *EvidenceFactList) SetItems(val []EvidenceFact) {
|
||||
s.Items = val
|
||||
}
|
||||
|
||||
// SetPage sets the value of Page.
|
||||
func (s *EvidenceFactList) SetPage(val PageInfo) {
|
||||
s.Page = val
|
||||
}
|
||||
|
||||
// EvidenceFactListHeaders wraps EvidenceFactList with response headers.
|
||||
type EvidenceFactListHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
Response EvidenceFactList
|
||||
}
|
||||
|
||||
// GetCacheControl returns the value of CacheControl.
|
||||
func (s *EvidenceFactListHeaders) GetCacheControl() CacheControlNoStore {
|
||||
return s.CacheControl
|
||||
}
|
||||
|
||||
// GetResponse returns the value of Response.
|
||||
func (s *EvidenceFactListHeaders) GetResponse() EvidenceFactList {
|
||||
return s.Response
|
||||
}
|
||||
|
||||
// SetCacheControl sets the value of CacheControl.
|
||||
func (s *EvidenceFactListHeaders) SetCacheControl(val CacheControlNoStore) {
|
||||
s.CacheControl = val
|
||||
}
|
||||
|
||||
// SetResponse sets the value of Response.
|
||||
func (s *EvidenceFactListHeaders) SetResponse(val EvidenceFactList) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
func (*EvidenceFactListHeaders) listMyEvidenceRes() {}
|
||||
|
||||
// Whether a fact is a statement or an observation.
|
||||
//
|
||||
// - claim: something the candidate stated that nothing confirmed separately. Its trust is 0.
|
||||
// - measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to
|
||||
// 3.
|
||||
//
|
||||
// Assessments produce measurements only. A claim never becomes a measurement by repetition, and the
|
||||
// two kinds are stored apart.
|
||||
// Ref: #/components/schemas/EvidenceKind
|
||||
type EvidenceKind string
|
||||
|
||||
const (
|
||||
EvidenceKindClaim EvidenceKind = "claim"
|
||||
EvidenceKindMeasurement EvidenceKind = "measurement"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceKind values.
|
||||
func (EvidenceKind) AllValues() []EvidenceKind {
|
||||
return []EvidenceKind{
|
||||
EvidenceKindClaim,
|
||||
EvidenceKindMeasurement,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceKind) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceKindClaim:
|
||||
return []byte(s), nil
|
||||
case EvidenceKindMeasurement:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceKind) UnmarshalText(data []byte) error {
|
||||
switch EvidenceKind(data) {
|
||||
case EvidenceKindClaim:
|
||||
*s = EvidenceKindClaim
|
||||
return nil
|
||||
case EvidenceKindMeasurement:
|
||||
*s = EvidenceKindMeasurement
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// What the fact says: the grade that was passed and how reliable the method is. It carries no score,
|
||||
// answer, item, failure, or anti-cheat data.
|
||||
// Ref: #/components/schemas/EvidenceResult
|
||||
type EvidenceResult struct {
|
||||
Grade GradeCode `json:"grade"`
|
||||
Basis EvidenceBasis `json:"basis"`
|
||||
CalibrationStatus EvidenceCalibrationStatus `json:"calibration_status"`
|
||||
}
|
||||
|
||||
// GetGrade returns the value of Grade.
|
||||
func (s *EvidenceResult) GetGrade() GradeCode {
|
||||
return s.Grade
|
||||
}
|
||||
|
||||
// GetBasis returns the value of Basis.
|
||||
func (s *EvidenceResult) GetBasis() EvidenceBasis {
|
||||
return s.Basis
|
||||
}
|
||||
|
||||
// GetCalibrationStatus returns the value of CalibrationStatus.
|
||||
func (s *EvidenceResult) GetCalibrationStatus() EvidenceCalibrationStatus {
|
||||
return s.CalibrationStatus
|
||||
}
|
||||
|
||||
// SetGrade sets the value of Grade.
|
||||
func (s *EvidenceResult) SetGrade(val GradeCode) {
|
||||
s.Grade = val
|
||||
}
|
||||
|
||||
// SetBasis sets the value of Basis.
|
||||
func (s *EvidenceResult) SetBasis(val EvidenceBasis) {
|
||||
s.Basis = val
|
||||
}
|
||||
|
||||
// SetCalibrationStatus sets the value of CalibrationStatus.
|
||||
func (s *EvidenceResult) SetCalibrationStatus(val EvidenceCalibrationStatus) {
|
||||
s.CalibrationStatus = val
|
||||
}
|
||||
|
||||
// A skill tag from a closed set - the specialization codes of the catalog and the technology codes of
|
||||
// the anonymous card. An assessment tags its fact with the specialization of the category.
|
||||
// Ref: #/components/schemas/EvidenceSkillCode
|
||||
type EvidenceSkillCode string
|
||||
|
||||
const (
|
||||
EvidenceSkillCodeBackend EvidenceSkillCode = "backend"
|
||||
EvidenceSkillCodeFrontend EvidenceSkillCode = "frontend"
|
||||
EvidenceSkillCodeMobile EvidenceSkillCode = "mobile"
|
||||
EvidenceSkillCodeNetworkEngineer EvidenceSkillCode = "network_engineer"
|
||||
EvidenceSkillCodeDevopsSre EvidenceSkillCode = "devops_sre"
|
||||
EvidenceSkillCodeDataAnalyst EvidenceSkillCode = "data_analyst"
|
||||
EvidenceSkillCodeDsMl EvidenceSkillCode = "ds_ml"
|
||||
EvidenceSkillCodeInformationSecurity EvidenceSkillCode = "information_security"
|
||||
EvidenceSkillCodeQa EvidenceSkillCode = "qa"
|
||||
EvidenceSkillCodeGo EvidenceSkillCode = "go"
|
||||
EvidenceSkillCodePostgresql EvidenceSkillCode = "postgresql"
|
||||
EvidenceSkillCodeKafka EvidenceSkillCode = "kafka"
|
||||
EvidenceSkillCodeDocker EvidenceSkillCode = "docker"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceSkillCode values.
|
||||
func (EvidenceSkillCode) AllValues() []EvidenceSkillCode {
|
||||
return []EvidenceSkillCode{
|
||||
EvidenceSkillCodeBackend,
|
||||
EvidenceSkillCodeFrontend,
|
||||
EvidenceSkillCodeMobile,
|
||||
EvidenceSkillCodeNetworkEngineer,
|
||||
EvidenceSkillCodeDevopsSre,
|
||||
EvidenceSkillCodeDataAnalyst,
|
||||
EvidenceSkillCodeDsMl,
|
||||
EvidenceSkillCodeInformationSecurity,
|
||||
EvidenceSkillCodeQa,
|
||||
EvidenceSkillCodeGo,
|
||||
EvidenceSkillCodePostgresql,
|
||||
EvidenceSkillCodeKafka,
|
||||
EvidenceSkillCodeDocker,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceSkillCode) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceSkillCodeBackend:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeFrontend:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeMobile:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeNetworkEngineer:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDevopsSre:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDataAnalyst:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDsMl:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeInformationSecurity:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeQa:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeGo:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodePostgresql:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeKafka:
|
||||
return []byte(s), nil
|
||||
case EvidenceSkillCodeDocker:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceSkillCode) UnmarshalText(data []byte) error {
|
||||
switch EvidenceSkillCode(data) {
|
||||
case EvidenceSkillCodeBackend:
|
||||
*s = EvidenceSkillCodeBackend
|
||||
return nil
|
||||
case EvidenceSkillCodeFrontend:
|
||||
*s = EvidenceSkillCodeFrontend
|
||||
return nil
|
||||
case EvidenceSkillCodeMobile:
|
||||
*s = EvidenceSkillCodeMobile
|
||||
return nil
|
||||
case EvidenceSkillCodeNetworkEngineer:
|
||||
*s = EvidenceSkillCodeNetworkEngineer
|
||||
return nil
|
||||
case EvidenceSkillCodeDevopsSre:
|
||||
*s = EvidenceSkillCodeDevopsSre
|
||||
return nil
|
||||
case EvidenceSkillCodeDataAnalyst:
|
||||
*s = EvidenceSkillCodeDataAnalyst
|
||||
return nil
|
||||
case EvidenceSkillCodeDsMl:
|
||||
*s = EvidenceSkillCodeDsMl
|
||||
return nil
|
||||
case EvidenceSkillCodeInformationSecurity:
|
||||
*s = EvidenceSkillCodeInformationSecurity
|
||||
return nil
|
||||
case EvidenceSkillCodeQa:
|
||||
*s = EvidenceSkillCodeQa
|
||||
return nil
|
||||
case EvidenceSkillCodeGo:
|
||||
*s = EvidenceSkillCodeGo
|
||||
return nil
|
||||
case EvidenceSkillCodePostgresql:
|
||||
*s = EvidenceSkillCodePostgresql
|
||||
return nil
|
||||
case EvidenceSkillCodeKafka:
|
||||
*s = EvidenceSkillCodeKafka
|
||||
return nil
|
||||
case EvidenceSkillCodeDocker:
|
||||
*s = EvidenceSkillCodeDocker
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// Where the fact comes from. For an assessment the event is the attempt and the result is the
|
||||
// immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two
|
||||
// identifiers are equal because a result is keyed by its attempt.
|
||||
// Ref: #/components/schemas/EvidenceSource
|
||||
type EvidenceSource struct {
|
||||
Type EvidenceSourceType `json:"type"`
|
||||
// Identifier of the source event. One event is one fact, however many skills it is tagged with.
|
||||
EventID uuid.UUID `json:"event_id"`
|
||||
// Identifier of the immutable result that produced the fact.
|
||||
ResultID uuid.UUID `json:"result_id"`
|
||||
}
|
||||
|
||||
// GetType returns the value of Type.
|
||||
func (s *EvidenceSource) GetType() EvidenceSourceType {
|
||||
return s.Type
|
||||
}
|
||||
|
||||
// GetEventID returns the value of EventID.
|
||||
func (s *EvidenceSource) GetEventID() uuid.UUID {
|
||||
return s.EventID
|
||||
}
|
||||
|
||||
// GetResultID returns the value of ResultID.
|
||||
func (s *EvidenceSource) GetResultID() uuid.UUID {
|
||||
return s.ResultID
|
||||
}
|
||||
|
||||
// SetType sets the value of Type.
|
||||
func (s *EvidenceSource) SetType(val EvidenceSourceType) {
|
||||
s.Type = val
|
||||
}
|
||||
|
||||
// SetEventID sets the value of EventID.
|
||||
func (s *EvidenceSource) SetEventID(val uuid.UUID) {
|
||||
s.EventID = val
|
||||
}
|
||||
|
||||
// SetResultID sets the value of ResultID.
|
||||
func (s *EvidenceSource) SetResultID(val uuid.UUID) {
|
||||
s.ResultID = val
|
||||
}
|
||||
|
||||
// Where the fact comes from.
|
||||
//
|
||||
// - assessment_result: a real (root or corrective) assessment result of this platform that confirmed
|
||||
// a grade. An express training run (`demo_express`), a failed attempt, and a result without a
|
||||
// reviewed category source are never a source.
|
||||
//
|
||||
// Adding a value is a contract change.
|
||||
// Ref: #/components/schemas/EvidenceSourceType
|
||||
type EvidenceSourceType string
|
||||
|
||||
const (
|
||||
EvidenceSourceTypeAssessmentResult EvidenceSourceType = "assessment_result"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceSourceType values.
|
||||
func (EvidenceSourceType) AllValues() []EvidenceSourceType {
|
||||
return []EvidenceSourceType{
|
||||
EvidenceSourceTypeAssessmentResult,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceSourceType) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceSourceTypeAssessmentResult:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceSourceType) UnmarshalText(data []byte) error {
|
||||
switch EvidenceSourceType(data) {
|
||||
case EvidenceSourceTypeAssessmentResult:
|
||||
*s = EvidenceSourceTypeAssessmentResult
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
type EvidenceTrustLevel int32
|
||||
|
||||
// Whether the fact may take part in what an organization reads.
|
||||
//
|
||||
// - visible: the fact is eligible for the organization projection. It does not publish the fact: the
|
||||
// projection also needs the published card with the `categories` field and an active C2.
|
||||
// - hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the
|
||||
// confirmed result.
|
||||
//
|
||||
// Ref: #/components/schemas/EvidenceVisibility
|
||||
type EvidenceVisibility string
|
||||
|
||||
const (
|
||||
EvidenceVisibilityVisible EvidenceVisibility = "visible"
|
||||
EvidenceVisibilityHidden EvidenceVisibility = "hidden"
|
||||
)
|
||||
|
||||
// AllValues returns all EvidenceVisibility values.
|
||||
func (EvidenceVisibility) AllValues() []EvidenceVisibility {
|
||||
return []EvidenceVisibility{
|
||||
EvidenceVisibilityVisible,
|
||||
EvidenceVisibilityHidden,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EvidenceVisibility) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EvidenceVisibilityVisible:
|
||||
return []byte(s), nil
|
||||
case EvidenceVisibilityHidden:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EvidenceVisibility) UnmarshalText(data []byte) error {
|
||||
switch EvidenceVisibility(data) {
|
||||
case EvidenceVisibilityVisible:
|
||||
*s = EvidenceVisibilityVisible
|
||||
return nil
|
||||
case EvidenceVisibilityHidden:
|
||||
*s = EvidenceVisibilityHidden
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
type FinalizeMyAssessmentAttemptBadRequest Problem
|
||||
|
||||
func (*FinalizeMyAssessmentAttemptBadRequest) finalizeMyAssessmentAttemptRes() {}
|
||||
@@ -10006,6 +10668,22 @@ type GetOrganizationCandidateCardUnauthorized Problem
|
||||
|
||||
func (*GetOrganizationCandidateCardUnauthorized) getOrganizationCandidateCardRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceBadRequest Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceBadRequest) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceForbidden Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceForbidden) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceNotFound Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceNotFound) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationCandidateEvidenceUnauthorized Problem
|
||||
|
||||
func (*GetOrganizationCandidateEvidenceUnauthorized) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
type GetOrganizationForbidden Problem
|
||||
|
||||
func (*GetOrganizationForbidden) getOrganizationRes() {}
|
||||
@@ -11911,6 +12589,18 @@ type ListMyConsentsUnauthorized Problem
|
||||
|
||||
func (*ListMyConsentsUnauthorized) listMyConsentsRes() {}
|
||||
|
||||
type ListMyEvidenceBadRequest Problem
|
||||
|
||||
func (*ListMyEvidenceBadRequest) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyEvidenceForbidden Problem
|
||||
|
||||
func (*ListMyEvidenceForbidden) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyEvidenceUnauthorized Problem
|
||||
|
||||
func (*ListMyEvidenceUnauthorized) listMyEvidenceRes() {}
|
||||
|
||||
type ListMyHiddenOrganizationsBadRequest Problem
|
||||
|
||||
func (*ListMyHiddenOrganizationsBadRequest) listMyHiddenOrganizationsRes() {}
|
||||
@@ -18185,6 +18875,51 @@ func (o NilOrganizationDescription) Or(d OrganizationDescription) OrganizationDe
|
||||
return d
|
||||
}
|
||||
|
||||
// NewNilOrganizationEvidence returns new NilOrganizationEvidence with value set to v.
|
||||
func NewNilOrganizationEvidence(v OrganizationEvidence) NilOrganizationEvidence {
|
||||
return NilOrganizationEvidence{
|
||||
Value: v,
|
||||
}
|
||||
}
|
||||
|
||||
// NilOrganizationEvidence is nullable OrganizationEvidence.
|
||||
type NilOrganizationEvidence struct {
|
||||
Value OrganizationEvidence
|
||||
Null bool
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *NilOrganizationEvidence) SetTo(v OrganizationEvidence) {
|
||||
o.Null = false
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// IsNull returns true if value is Null.
|
||||
func (o NilOrganizationEvidence) IsNull() bool { return o.Null }
|
||||
|
||||
// SetToNull sets value to null.
|
||||
func (o *NilOrganizationEvidence) SetToNull() {
|
||||
o.Null = true
|
||||
var v OrganizationEvidence
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o NilOrganizationEvidence) Get() (v OrganizationEvidence, ok bool) {
|
||||
if o.Null {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o NilOrganizationEvidence) Or(d OrganizationEvidence) OrganizationEvidence {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewNilOrganizationSphere returns new NilOrganizationSphere with value set to v.
|
||||
func NewNilOrganizationSphere(v OrganizationSphere) NilOrganizationSphere {
|
||||
return NilOrganizationSphere{
|
||||
@@ -22180,6 +22915,133 @@ func (s *OrganizationCreate) SetRepresentatives(val []OrganizationRepresentative
|
||||
|
||||
type OrganizationDescription string
|
||||
|
||||
// The permitted evidence of one candidate card, ordered by skill: at most one fact for each category
|
||||
// of the card (at most nine). The list is empty when no visible fact supports a category of the card.
|
||||
// Ref: #/components/schemas/OrganizationEvidence
|
||||
type OrganizationEvidence struct {
|
||||
// Permitted facts, one for each supported category.
|
||||
Items []OrganizationEvidenceFact `json:"items"`
|
||||
}
|
||||
|
||||
// GetItems returns the value of Items.
|
||||
func (s *OrganizationEvidence) GetItems() []OrganizationEvidenceFact {
|
||||
return s.Items
|
||||
}
|
||||
|
||||
// SetItems sets the value of Items.
|
||||
func (s *OrganizationEvidence) SetItems(val []OrganizationEvidenceFact) {
|
||||
s.Items = val
|
||||
}
|
||||
|
||||
// The one assessment fact that supports a category of the card as an organization reads it: the
|
||||
// earliest visible measurement that passed exactly the confirmed grade of that category. A lower
|
||||
// grade, a retake, the other tags of the event, the source, the basis, the exact time, and every
|
||||
// identifier stay with the candidate. The fact carries no identifier of the fact, the event, the
|
||||
// result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the
|
||||
// skill, the grade, the trust level, and the year, together with the other values of the card, can
|
||||
// narrow a small pool of candidates, and the minimum cohort of the card does not cover the year.
|
||||
// `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from
|
||||
// a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated
|
||||
// measurement. The fact never carries an answer, score, item, failure, signal, or review band.
|
||||
// Ref: #/components/schemas/OrganizationEvidenceFact
|
||||
type OrganizationEvidenceFact struct {
|
||||
Skill EvidenceSkillCode `json:"skill"`
|
||||
Grade GradeCode `json:"grade"`
|
||||
Trust EvidenceTrustLevel `json:"trust"`
|
||||
Basis EvidenceBasis `json:"basis"`
|
||||
CalibrationStatus EvidenceCalibrationStatus `json:"calibration_status"`
|
||||
// Year (UTC) when the assessment ended. The month, day, and time stay with the candidate.
|
||||
ObservedYear int32 `json:"observed_year"`
|
||||
}
|
||||
|
||||
// GetSkill returns the value of Skill.
|
||||
func (s *OrganizationEvidenceFact) GetSkill() EvidenceSkillCode {
|
||||
return s.Skill
|
||||
}
|
||||
|
||||
// GetGrade returns the value of Grade.
|
||||
func (s *OrganizationEvidenceFact) GetGrade() GradeCode {
|
||||
return s.Grade
|
||||
}
|
||||
|
||||
// GetTrust returns the value of Trust.
|
||||
func (s *OrganizationEvidenceFact) GetTrust() EvidenceTrustLevel {
|
||||
return s.Trust
|
||||
}
|
||||
|
||||
// GetBasis returns the value of Basis.
|
||||
func (s *OrganizationEvidenceFact) GetBasis() EvidenceBasis {
|
||||
return s.Basis
|
||||
}
|
||||
|
||||
// GetCalibrationStatus returns the value of CalibrationStatus.
|
||||
func (s *OrganizationEvidenceFact) GetCalibrationStatus() EvidenceCalibrationStatus {
|
||||
return s.CalibrationStatus
|
||||
}
|
||||
|
||||
// GetObservedYear returns the value of ObservedYear.
|
||||
func (s *OrganizationEvidenceFact) GetObservedYear() int32 {
|
||||
return s.ObservedYear
|
||||
}
|
||||
|
||||
// SetSkill sets the value of Skill.
|
||||
func (s *OrganizationEvidenceFact) SetSkill(val EvidenceSkillCode) {
|
||||
s.Skill = val
|
||||
}
|
||||
|
||||
// SetGrade sets the value of Grade.
|
||||
func (s *OrganizationEvidenceFact) SetGrade(val GradeCode) {
|
||||
s.Grade = val
|
||||
}
|
||||
|
||||
// SetTrust sets the value of Trust.
|
||||
func (s *OrganizationEvidenceFact) SetTrust(val EvidenceTrustLevel) {
|
||||
s.Trust = val
|
||||
}
|
||||
|
||||
// SetBasis sets the value of Basis.
|
||||
func (s *OrganizationEvidenceFact) SetBasis(val EvidenceBasis) {
|
||||
s.Basis = val
|
||||
}
|
||||
|
||||
// SetCalibrationStatus sets the value of CalibrationStatus.
|
||||
func (s *OrganizationEvidenceFact) SetCalibrationStatus(val EvidenceCalibrationStatus) {
|
||||
s.CalibrationStatus = val
|
||||
}
|
||||
|
||||
// SetObservedYear sets the value of ObservedYear.
|
||||
func (s *OrganizationEvidenceFact) SetObservedYear(val int32) {
|
||||
s.ObservedYear = val
|
||||
}
|
||||
|
||||
// OrganizationEvidenceHeaders wraps OrganizationEvidence with response headers.
|
||||
type OrganizationEvidenceHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
Response OrganizationEvidence
|
||||
}
|
||||
|
||||
// GetCacheControl returns the value of CacheControl.
|
||||
func (s *OrganizationEvidenceHeaders) GetCacheControl() CacheControlNoStore {
|
||||
return s.CacheControl
|
||||
}
|
||||
|
||||
// GetResponse returns the value of Response.
|
||||
func (s *OrganizationEvidenceHeaders) GetResponse() OrganizationEvidence {
|
||||
return s.Response
|
||||
}
|
||||
|
||||
// SetCacheControl sets the value of CacheControl.
|
||||
func (s *OrganizationEvidenceHeaders) SetCacheControl(val CacheControlNoStore) {
|
||||
s.CacheControl = val
|
||||
}
|
||||
|
||||
// SetResponse sets the value of Response.
|
||||
func (s *OrganizationEvidenceHeaders) SetResponse(val OrganizationEvidence) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
func (*OrganizationEvidenceHeaders) getOrganizationCandidateEvidenceRes() {}
|
||||
|
||||
// OrganizationHeaders wraps Organization with response headers.
|
||||
type OrganizationHeaders struct {
|
||||
CacheControl CacheControlNoStore
|
||||
@@ -29642,6 +30504,7 @@ func (*TooManyRequestsHeaders) createOrganizationNeedRes() {}
|
||||
func (*TooManyRequestsHeaders) createOrganizationRes() {}
|
||||
func (*TooManyRequestsHeaders) declineMyInvitationRes() {}
|
||||
func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {}
|
||||
func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {}
|
||||
func (*TooManyRequestsHeaders) hideOrganizationRes() {}
|
||||
func (*TooManyRequestsHeaders) loginRes() {}
|
||||
func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {}
|
||||
|
||||
@@ -81,6 +81,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
GetMySupportCaseOperation: []string{},
|
||||
GetOrganizationOperation: []string{},
|
||||
GetOrganizationCandidateCardOperation: []string{},
|
||||
GetOrganizationCandidateEvidenceOperation: []string{},
|
||||
GetOrganizationInvitationOperation: []string{},
|
||||
GetOrganizationInvitationContactsOperation: []string{},
|
||||
GetOrganizationNeedOperation: []string{},
|
||||
@@ -89,6 +90,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
ListMyAssessmentResultsOperation: []string{},
|
||||
ListMyCardAccessHistoryOperation: []string{},
|
||||
ListMyConsentsOperation: []string{},
|
||||
ListMyEvidenceOperation: []string{},
|
||||
ListMyHiddenOrganizationsOperation: []string{},
|
||||
ListMyInvitationsOperation: []string{},
|
||||
ListMyOrganizationsOperation: []string{},
|
||||
|
||||
@@ -663,6 +663,13 @@ type Handler interface {
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -841,6 +848,45 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (GetOrganizationCandidateCardRes, error)
|
||||
// GetOrganizationCandidateEvidence implements GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
GetOrganizationCandidateEvidence(ctx context.Context, params GetOrganizationCandidateEvidenceParams) (GetOrganizationCandidateEvidenceRes, error)
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -1069,6 +1115,30 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/me/consents
|
||||
ListMyConsents(ctx context.Context, params ListMyConsentsParams) (ListMyConsentsRes, error)
|
||||
// ListMyEvidence implements ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
ListMyEvidence(ctx context.Context, params ListMyEvidenceParams) (ListMyEvidenceRes, error)
|
||||
// ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -725,6 +725,13 @@ func (UnimplementedHandler) GetMyAssessmentSignalNotice(ctx context.Context) (r
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// `evidence` shows what an organization would read in the evidence section of the card
|
||||
// (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that
|
||||
// supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the
|
||||
// basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an
|
||||
// empty list when the card shows no category or no visible fact supports one. The preview applies no
|
||||
// organization or cohort, so an organization can still receive less.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
//
|
||||
@@ -930,6 +937,48 @@ func (UnimplementedHandler) GetOrganizationCandidateCard(ctx context.Context, pa
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateEvidence implements GetOrganizationCandidateEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server runs the same checks as the card read on every request: active membership,
|
||||
// effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In
|
||||
// addition the card must publish the `categories` field and show at least one category after the
|
||||
// cohort rules, because the evidence explains those categories and discloses nothing beyond them. An
|
||||
// unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden
|
||||
// from this organization, a profile suppressed by the minimum cohort, and a card without categories
|
||||
// all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read
|
||||
// immediately, and a cached response proves nothing.
|
||||
//
|
||||
// The response lists, for each category of the card, the one visible fact that supports its confirmed
|
||||
// grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds
|
||||
// nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the
|
||||
// trust level, the year of the assessment, and the basis and calibration of the method
|
||||
// (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is
|
||||
// a demonstration, not a validated measurement. It carries no identifier of the fact, event, result,
|
||||
// or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band,
|
||||
// or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no
|
||||
// key that joins it to a person, but it is not unlinkable: with the other values of the card it can
|
||||
// narrow a small pool of candidates.
|
||||
//
|
||||
// Reading the evidence is a view of the candidate card: it consumes the organization's current
|
||||
// card-view quota with the same distinct-card rule and is recorded in the access history with the
|
||||
// `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The
|
||||
// response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence
|
||||
func (UnimplementedHandler) GetOrganizationCandidateEvidence(ctx context.Context, params GetOrganizationCandidateEvidenceParams) (r GetOrganizationCandidateEvidenceRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -1185,6 +1234,33 @@ func (UnimplementedHandler) ListMyConsents(ctx context.Context, params ListMyCon
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMyEvidence implements ListMyEvidence operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
// response holds only the caller's own facts. Returns a page, newest event first with the fact
|
||||
// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in
|
||||
// the same transaction that stores the result. Each fact names its source (the event and the result,
|
||||
// which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that
|
||||
// was passed with its basis and calibration, the attribution, the date, the visibility, and the trust
|
||||
// level. An online assessment without a reliable confirmation of the identity has trust 1. One source
|
||||
// event is one fact: its skills are tags of that fact, so several tags never make several facts.
|
||||
//
|
||||
// The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed
|
||||
// attempt, a result without a reviewed category source, and an express training run (`demo_express`)
|
||||
// create no fact, so reading the list before and after an express run shows no new fact. The list
|
||||
// includes facts the candidate hid, with `visibility` `hidden`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or
|
||||
// a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a
|
||||
// cursor of another candidate, answers 400 validation_failed.
|
||||
//
|
||||
// GET /api/v1/me/evidence
|
||||
func (UnimplementedHandler) ListMyEvidence(ctx context.Context, params ListMyEvidenceParams) (r ListMyEvidenceRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
|
||||
|
||||
@@ -6512,6 +6512,24 @@ func (s *CardPreview) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Evidence.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "evidence",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
@@ -8833,6 +8851,397 @@ func (s EmailVerificationResultEmailVerified) Validate() error {
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceAttribution) Validate() error {
|
||||
switch s {
|
||||
case "personal":
|
||||
return nil
|
||||
case "team_role":
|
||||
return nil
|
||||
case "team_unattributed":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceBasis) Validate() error {
|
||||
switch s {
|
||||
case "synthetic_demo":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceCalibrationStatus) Validate() error {
|
||||
switch s {
|
||||
case "uncalibrated":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceFact) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Skills == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 13,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Skills)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
if err := validate.UniqueItems(s.Skills); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Skills {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "skills",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Result.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "result",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Attribution.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "attribution",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Trust.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "trust",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Visibility.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "visibility",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EvidenceFactList) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Items == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 100,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Items)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Items {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "items",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Page.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "page",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EvidenceFactListHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.CacheControl.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "CacheControl",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Response",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceKind) Validate() error {
|
||||
switch s {
|
||||
case "claim":
|
||||
return nil
|
||||
case "measurement":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceResult) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Grade.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "grade",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Basis.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "basis",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.CalibrationStatus.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "calibration_status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceSkillCode) Validate() error {
|
||||
switch s {
|
||||
case "backend":
|
||||
return nil
|
||||
case "frontend":
|
||||
return nil
|
||||
case "mobile":
|
||||
return nil
|
||||
case "network_engineer":
|
||||
return nil
|
||||
case "devops_sre":
|
||||
return nil
|
||||
case "data_analyst":
|
||||
return nil
|
||||
case "ds_ml":
|
||||
return nil
|
||||
case "information_security":
|
||||
return nil
|
||||
case "qa":
|
||||
return nil
|
||||
case "go":
|
||||
return nil
|
||||
case "postgresql":
|
||||
return nil
|
||||
case "kafka":
|
||||
return nil
|
||||
case "docker":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EvidenceSource) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Type.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "type",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceSourceType) Validate() error {
|
||||
switch s {
|
||||
case "assessment_result":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s EvidenceTrustLevel) Validate() error {
|
||||
alias := (int32)(s)
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 0,
|
||||
MaxSet: true,
|
||||
Max: 3,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(alias)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EvidenceVisibility) Validate() error {
|
||||
switch s {
|
||||
case "visible":
|
||||
return nil
|
||||
case "hidden":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *FinalizeMyAssessmentAttemptBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -9379,6 +9788,38 @@ func (s *GetOrganizationCandidateCardUnauthorized) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceNotFound) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationCandidateEvidenceUnauthorized) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetOrganizationForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -10914,6 +11355,30 @@ func (s *ListMyConsentsUnauthorized) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyEvidenceUnauthorized) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ListMyHiddenOrganizationsBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -16322,6 +16787,176 @@ func (s OrganizationDescription) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidence) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if s.Items == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 9,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Items)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Items {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "items",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidenceFact) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Skill.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "skill",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Grade.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "grade",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Trust.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "trust",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Basis.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "basis",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.CalibrationStatus.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "calibration_status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 2000,
|
||||
MaxSet: true,
|
||||
Max: 9999,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.ObservedYear)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "observed_year",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationEvidenceHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.CacheControl.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "CacheControl",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Response",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OrganizationHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
|
||||
@@ -40,6 +40,10 @@ var (
|
||||
// sharedLeafSchemas are the reusable leaves that the privacy family may
|
||||
// refer to; none of them identifies a person or carries a contact.
|
||||
sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"}
|
||||
// previewEvidenceSchemas are the evidence leaves that the preview reaches
|
||||
// to show what an organization would read with the categories. They carry
|
||||
// a skill, a grade, a trust level, a year, and the demonstration labels, and no identifier.
|
||||
previewEvidenceSchemas = []string{"OrganizationEvidence", "OrganizationEvidenceFact", "EvidenceSkillCode", "EvidenceTrustLevel", "EvidenceBasis", "EvidenceCalibrationStatus"}
|
||||
)
|
||||
|
||||
func isPrivacySchema(name string) bool {
|
||||
@@ -262,11 +266,11 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
// What the card and the preview reach is a small closed list of leaves.
|
||||
allowed := []string{
|
||||
allowed := slices.Concat([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview",
|
||||
}
|
||||
}, previewEvidenceSchemas)
|
||||
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
|
||||
if !slices.Contains(allowed, reached) {
|
||||
@@ -286,7 +290,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "Consent") {
|
||||
t.Errorf("%s reaches %s", path, reached)
|
||||
}
|
||||
if !isPrivacySchema(reached) && !slices.Contains(sharedLeafSchemas, reached) && !strings.HasPrefix(reached, "Problem") &&
|
||||
if !isPrivacySchema(reached) && !slices.Contains(sharedLeafSchemas, reached) && !slices.Contains(previewEvidenceSchemas, reached) && !strings.HasPrefix(reached, "Problem") &&
|
||||
reached != "Problem" && reached != "ProblemCode" {
|
||||
t.Errorf("%s reaches %s, which is neither a privacy schema nor a shared leaf", path, reached)
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T)
|
||||
// Card reads lock any active membership inside their read transaction;
|
||||
// the owner-only capability does not apply to that operation.
|
||||
apiadapter.GetOrganizationCandidateCardOperation,
|
||||
apiadapter.GetOrganizationCandidateEvidenceOperation,
|
||||
apiadapter.HideOrganizationOperation,
|
||||
apiadapter.UnhideOrganizationOperation,
|
||||
apiadapter.RevokeMyOrganizationContactConsentOperation,
|
||||
@@ -135,6 +136,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
seen := make(map[string]string, len(ownerCompanyOperations))
|
||||
seenExceptions := make(map[string]bool, len(candidateExceptions))
|
||||
seenCardRead := false
|
||||
seenEvidenceRead := false
|
||||
for path, methods := range document.Paths {
|
||||
for _, operation := range methods {
|
||||
if operation.OperationID == "" {
|
||||
@@ -161,6 +163,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
seenCardRead = true
|
||||
continue
|
||||
}
|
||||
// The evidence of a card is a section of that card: it runs the same
|
||||
// transaction-bound membership, visibility, and quota checks.
|
||||
if operation.OperationID == "GetOrganizationCandidateEvidence" &&
|
||||
path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence" {
|
||||
seenEvidenceRead = true
|
||||
continue
|
||||
}
|
||||
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
|
||||
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
|
||||
seenExceptions[operation.OperationID] = true
|
||||
@@ -182,6 +191,9 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if !seenCardRead {
|
||||
t.Error("transaction-authorized candidate card read is absent or moved")
|
||||
}
|
||||
if !seenEvidenceRead {
|
||||
t.Error("transaction-authorized candidate evidence read is absent or moved")
|
||||
}
|
||||
}
|
||||
|
||||
type companyContextAuthenticator struct {
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/ogen-go/ogen"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
)
|
||||
|
||||
const (
|
||||
evidenceOwnPath = "/api/v1/me/evidence"
|
||||
evidenceOrganizationPath = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence"
|
||||
)
|
||||
|
||||
// evidenceSchemas are the schemas of the evidence family.
|
||||
var evidenceSchemas = []string{
|
||||
"EvidenceKind", "EvidenceSourceType", "EvidenceAttribution", "EvidenceTrustLevel", "EvidenceVisibility",
|
||||
"EvidenceSkillCode", "EvidenceBasis", "EvidenceCalibrationStatus", "EvidenceResult", "EvidenceSource",
|
||||
"EvidenceFact", "EvidenceFactList", "OrganizationEvidenceFact", "OrganizationEvidence",
|
||||
}
|
||||
|
||||
// rawAssessmentPropertyNames are properties that carry raw answers, failures,
|
||||
// per-item data, or anti-cheat data. No organization operation and no evidence
|
||||
// operation may declare one.
|
||||
var rawAssessmentPropertyNames = []string{
|
||||
"answer", "answers", "answer_key", "reference_answer", "raw_score", "basic_score", "pass_points", "pass_mark_basis_points",
|
||||
"scored_items", "uncertainty", "weak_domains", "practice_results", "practice", "signals", "events", "item_instance_id",
|
||||
"items_answered", "seed", "variant", "hidden_checks", "category_decision", "next_step", "not_determined_reason",
|
||||
"band", "reasons", "attempt_id",
|
||||
}
|
||||
|
||||
// Both evidence operations follow the project conventions: the session cookie
|
||||
// alone (they only read), the unauthenticated and forbidden problems, no-store
|
||||
// on the success, and the shared cursor parameters for the paged list. No new
|
||||
// problem code is needed.
|
||||
func TestEvidenceOperationsFollowTheConventions(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
own := operationByID(t, spec, "ListMyEvidence")
|
||||
organization := operationByID(t, spec, "GetOrganizationCandidateEvidence")
|
||||
for _, operation := range []*ogen.Operation{own, organization} {
|
||||
if !slices.Contains(operation.Tags, "evidence") {
|
||||
t.Errorf("%s is not in the evidence tag", operation.OperationID)
|
||||
}
|
||||
if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") {
|
||||
t.Errorf("%s security = %v, want the session cookie without a CSRF token for a read", operation.OperationID, operation.Security)
|
||||
}
|
||||
for _, status := range []string{"400", "401", "403", "default"} {
|
||||
if operation.Responses[status] == nil {
|
||||
t.Errorf("%s does not declare %s", operation.OperationID, status)
|
||||
}
|
||||
}
|
||||
if success := operation.Responses["200"]; success == nil || success.Headers["Cache-Control"] == nil {
|
||||
t.Errorf("%s does not mark its 200 response no-store", operation.OperationID)
|
||||
}
|
||||
if operation.RequestBody != nil {
|
||||
t.Errorf("%s takes a body, but it only reads", operation.OperationID)
|
||||
}
|
||||
}
|
||||
names := []string{}
|
||||
for _, parameter := range own.Parameters {
|
||||
names = append(names, parameterName(parameter))
|
||||
}
|
||||
if !slices.Contains(names, "PageLimit") || !slices.Contains(names, "PageCursor") {
|
||||
t.Errorf("ListMyEvidence parameters = %v, want the shared PageLimit and PageCursor", names)
|
||||
}
|
||||
names = names[:0]
|
||||
for _, parameter := range organization.Parameters {
|
||||
names = append(names, parameterName(parameter))
|
||||
}
|
||||
if !slices.Equal(names, []string{"OrganizationId", "CandidateHandle"}) {
|
||||
t.Errorf("GetOrganizationCandidateEvidence parameters = %v, want the organization and the candidate handle", names)
|
||||
}
|
||||
// The organization read answers an unknown, hidden, unpublished, and
|
||||
// suppressed card alike, and the quota with Retry-After.
|
||||
if organization.Responses["404"] == nil || organization.Responses["429"] == nil {
|
||||
t.Error("GetOrganizationCandidateEvidence must declare 404 and 429")
|
||||
}
|
||||
if own.Responses["404"] != nil {
|
||||
t.Error("ListMyEvidence declares 404: a list has no missing resource")
|
||||
}
|
||||
|
||||
codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"}))
|
||||
for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "not_found", "rate_limited"} {
|
||||
if !slices.Contains(codes, code) {
|
||||
t.Errorf("ProblemCode has no %s", code)
|
||||
}
|
||||
}
|
||||
if spec.Paths[evidenceOwnPath] == nil || spec.Paths[evidenceOrganizationPath] == nil {
|
||||
t.Errorf("the contract lacks the paths %s and %s", evidenceOwnPath, evidenceOrganizationPath)
|
||||
}
|
||||
}
|
||||
|
||||
// A claim and a measurement are different kinds with different trust ranges,
|
||||
// every evidence object is closed, and the organization fact has no identifier
|
||||
// and no exact time.
|
||||
func TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
if got := enumValues(t, spec.Components.Schemas["EvidenceKind"]); !slices.Equal(got, []string{"claim", "measurement"}) {
|
||||
t.Errorf("EvidenceKind = %v, want claim and measurement", got)
|
||||
}
|
||||
trust := spec.Components.Schemas["EvidenceTrustLevel"]
|
||||
if string(trust.Minimum) != "0" || string(trust.Maximum) != "3" {
|
||||
t.Errorf("EvidenceTrustLevel range = %s..%s, want 0..3", trust.Minimum, trust.Maximum)
|
||||
}
|
||||
for _, pair := range []struct {
|
||||
name string
|
||||
want []string
|
||||
}{
|
||||
{"EvidenceFact", []string{"attribution", "id", "kind", "occurred_at", "result", "skills", "source", "trust", "visibility"}},
|
||||
{"EvidenceSource", []string{"event_id", "result_id", "type"}},
|
||||
{"EvidenceResult", []string{"basis", "calibration_status", "grade"}},
|
||||
{"EvidenceFactList", []string{"items", "page"}},
|
||||
{"OrganizationEvidenceFact", []string{"basis", "calibration_status", "grade", "observed_year", "skill", "trust"}},
|
||||
{"OrganizationEvidence", []string{"items"}},
|
||||
} {
|
||||
schema := spec.Components.Schemas[pair.name]
|
||||
if schema == nil {
|
||||
t.Fatalf("the contract has no schema %s", pair.name)
|
||||
}
|
||||
if got := propertyNames(schema); !slices.Equal(got, pair.want) {
|
||||
t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want)
|
||||
}
|
||||
if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
|
||||
t.Errorf("%s accepts unknown properties", pair.name)
|
||||
}
|
||||
if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) {
|
||||
t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want)
|
||||
}
|
||||
}
|
||||
assertNoJSONFields(t, api.OrganizationEvidenceFact{}, []string{"id", "event_id", "result_id", "occurred_at", "visibility", "candidate_id", "user_id"})
|
||||
for _, property := range spec.Components.Schemas["EvidenceFact"].Properties {
|
||||
if property.Name == "skills" && (!property.Schema.UniqueItems || property.Schema.MinItems == nil || *property.Schema.MinItems != 1) {
|
||||
t.Errorf("EvidenceFact.skills must be a non-empty set: one event with several tags is one fact")
|
||||
}
|
||||
}
|
||||
// An organization reads at most one fact for each category of the card.
|
||||
items := spec.Components.Schemas["OrganizationEvidence"].Properties
|
||||
for _, property := range items {
|
||||
if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 9) {
|
||||
t.Errorf("OrganizationEvidence.items maxItems = %v, want 9: one fact for each of the nine possible categories", property.Schema.MaxItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No organization operation reaches raw answers, failures, per-item data, or
|
||||
// anti-cheat data, and neither does the evidence of the candidate. The walk
|
||||
// covers every request body, response, parameter, and header through all
|
||||
// references, so a new organization operation cannot reach an assessment
|
||||
// result, attempt, or signal schema by reuse.
|
||||
func TestNoOrganizationOperationReachesRawAssessmentData(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
index := componentsIndex(t, spec)
|
||||
walked := 0
|
||||
for path, item := range spec.Paths {
|
||||
organizationOperation := strings.HasPrefix(path, "/api/v1/organizations")
|
||||
if !organizationOperation && path != evidenceOwnPath {
|
||||
continue
|
||||
}
|
||||
walked++
|
||||
value := mustJSONValue(t, item)
|
||||
properties := map[string]bool{}
|
||||
declaredPropertyNames(value, properties)
|
||||
for schemaName := range reachableSchemas(index, value) {
|
||||
if strings.HasPrefix(schemaName, "Assessment") || strings.HasPrefix(schemaName, "Practice") ||
|
||||
strings.HasPrefix(schemaName, "ItemContent") || strings.Contains(schemaName, "Signal") ||
|
||||
strings.Contains(schemaName, "Review") {
|
||||
t.Errorf("%s reaches the assessment schema %s", path, schemaName)
|
||||
}
|
||||
declaredPropertyNames(mustJSONValue(t, index["#/components/schemas/"+schemaName]), properties)
|
||||
}
|
||||
if path == evidenceOwnPath && !properties["skills"] {
|
||||
t.Errorf("%s declares no skills property: the walk did not reach the schemas", path)
|
||||
}
|
||||
for _, raw := range rawAssessmentPropertyNames {
|
||||
if properties[raw] {
|
||||
t.Errorf("%s declares the raw assessment property %q", path, raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
if walked < 10 {
|
||||
t.Fatalf("walked only %d organization and evidence paths, want all of them", walked)
|
||||
}
|
||||
}
|
||||
|
||||
// The walk is not vacuous: it reaches the evidence family from both
|
||||
// operations, and the family keeps the failure outcomes out of its enums.
|
||||
func TestEvidenceWalkReachesTheEvidenceFamily(t *testing.T) {
|
||||
spec := parsePublicContract(t)
|
||||
index := componentsIndex(t, spec)
|
||||
for operationID, want := range map[string][]string{
|
||||
"ListMyEvidence": {"EvidenceFact", "EvidenceSource", "EvidenceResult", "EvidenceTrustLevel"},
|
||||
"GetOrganizationCandidateEvidence": {"OrganizationEvidenceFact", "EvidenceSkillCode", "EvidenceTrustLevel"},
|
||||
} {
|
||||
reached := reachableSchemas(index, mustJSONValue(t, operationByID(t, spec, operationID)))
|
||||
for _, name := range want {
|
||||
if !reached[name] {
|
||||
t.Errorf("%s does not reach %s", operationID, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
enums := map[string]bool{}
|
||||
for _, name := range evidenceSchemas {
|
||||
declaredEnumValues(mustJSONValue(t, spec.Components.Schemas[name]), enums)
|
||||
}
|
||||
for _, failure := range []string{"not_confirmed", "not_determined", "failed", "expired", "demonstration", "demo_express", "review", "attention"} {
|
||||
if enums[failure] {
|
||||
t.Errorf("the evidence family declares the enum value %q", failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type Handler struct {
|
||||
assessment *AssessmentHandler
|
||||
assessmentSignals *AssessmentSignalHandler
|
||||
privacy *PrivacyHandler
|
||||
evidence *EvidenceHandler
|
||||
problems *problem.Responder
|
||||
}
|
||||
|
||||
@@ -92,6 +93,12 @@ func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.privacy = privacy }
|
||||
}
|
||||
|
||||
// WithEvidence serves the skill evidence of a candidate and its permitted
|
||||
// organization projection.
|
||||
func WithEvidence(evidence *EvidenceHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.evidence = evidence }
|
||||
}
|
||||
|
||||
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
|
||||
handler := &Handler{health: health, problems: problems}
|
||||
for _, option := range options {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
// EvidenceOperations reads the skill evidence projection.
|
||||
type EvidenceOperations interface {
|
||||
ListMine(ctx context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error)
|
||||
ListForOrganization(ctx context.Context, actorID, organizationID uuid.UUID, handle string) ([]domain.EvidenceOrganizationFact, error)
|
||||
}
|
||||
|
||||
// EvidenceHandler binds the evidence read use cases to the v1 API.
|
||||
type EvidenceHandler struct {
|
||||
operations EvidenceOperations
|
||||
}
|
||||
|
||||
func NewEvidenceHandler(operations EvidenceOperations) *EvidenceHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewEvidenceHandler - operations must not be nil")
|
||||
}
|
||||
return &EvidenceHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyEvidence(ctx context.Context, params api.ListMyEvidenceParams) (api.ListMyEvidenceRes, error) {
|
||||
if handler.evidence == nil {
|
||||
return handler.UnimplementedHandler.ListMyEvidence(ctx, params)
|
||||
}
|
||||
return handler.evidence.ListMyEvidence(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationCandidateEvidence(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationCandidateEvidenceParams,
|
||||
) (api.GetOrganizationCandidateEvidenceRes, error) {
|
||||
if handler.evidence == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
return handler.evidence.GetOrganizationCandidateEvidence(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *EvidenceHandler) ListMyEvidence(ctx context.Context, params api.ListMyEvidenceParams) (api.ListMyEvidenceRes, error) {
|
||||
const location = "EvidenceHandler.ListMyEvidence"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyEvidenceUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvidence)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyEvidenceBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
query := outbound.EvidenceListQuery{CandidateID: principal.UserID, Limit: limit}
|
||||
if cursor != nil {
|
||||
query.After = &outbound.EvidencePosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
}
|
||||
page, err := handler.operations.ListMine(ctx, query)
|
||||
if err != nil {
|
||||
if errors.Is(err, evidence.ErrForbidden) {
|
||||
return (*api.ListMyEvidenceForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.EvidenceFact, 0, len(page.Items))
|
||||
for _, fact := range page.Items {
|
||||
items = append(items, evidenceFactResponse(fact.Snapshot()))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := outbound.EvidencePositionOf(page.Items[len(page.Items)-1])
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorEvidence, last.OccurredAt, last.ID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - encode cursor: %w", location, err)
|
||||
}
|
||||
return &api.EvidenceFactListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.EvidenceFactList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *EvidenceHandler) GetOrganizationCandidateEvidence(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationCandidateEvidenceParams,
|
||||
) (api.GetOrganizationCandidateEvidenceRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationCandidateEvidenceUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
facts, err := handler.operations.ListForOrganization(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateview.ErrForbidden):
|
||||
return (*api.GetOrganizationCandidateEvidenceForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.GetOrganizationCandidateEvidenceNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
|
||||
return (*api.GetOrganizationCandidateEvidenceBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
|
||||
}
|
||||
if limited, ok := candidateViewRateLimited(ctx, err); ok {
|
||||
return limited, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
evidence := organizationEvidenceResponse(facts)
|
||||
return &api.OrganizationEvidenceHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: evidence,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func evidenceFactResponse(fact domain.EvidenceFactSnapshot) api.EvidenceFact {
|
||||
return api.EvidenceFact{
|
||||
ID: fact.ID, Kind: api.EvidenceKind(fact.Kind),
|
||||
Source: api.EvidenceSource{
|
||||
Type: api.EvidenceSourceType(fact.SourceType), EventID: fact.EventID, ResultID: fact.ResultID,
|
||||
},
|
||||
Skills: evidenceSkillsResponse(fact.Skills),
|
||||
Result: evidenceResultResponse(fact.Result),
|
||||
Attribution: api.EvidenceAttribution(fact.Attribution), Trust: api.EvidenceTrustLevel(fact.Trust),
|
||||
OccurredAt: api.Timestamp(fact.OccurredAt), Visibility: api.EvidenceVisibility(fact.Visibility),
|
||||
}
|
||||
}
|
||||
|
||||
// organizationEvidenceResponse maps the allowlisted facts that an
|
||||
// organization, or the preview of the candidate, reads.
|
||||
func organizationEvidenceResponse(facts []domain.EvidenceOrganizationFact) api.OrganizationEvidence {
|
||||
items := make([]api.OrganizationEvidenceFact, 0, len(facts))
|
||||
for _, fact := range facts {
|
||||
input := fact.Input()
|
||||
items = append(items, api.OrganizationEvidenceFact{
|
||||
Skill: api.EvidenceSkillCode(input.Skill), Grade: api.GradeCode(input.Grade),
|
||||
Trust: api.EvidenceTrustLevel(input.Trust), Basis: api.EvidenceBasis(input.Basis),
|
||||
CalibrationStatus: api.EvidenceCalibrationStatus(input.CalibrationStatus), ObservedYear: input.ObservedYear,
|
||||
})
|
||||
}
|
||||
return api.OrganizationEvidence{Items: items}
|
||||
}
|
||||
|
||||
func evidenceSkillsResponse(skills []domain.EvidenceSkillCode) []api.EvidenceSkillCode {
|
||||
response := make([]api.EvidenceSkillCode, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
response = append(response, api.EvidenceSkillCode(skill))
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func evidenceResultResponse(result domain.EvidenceResult) api.EvidenceResult {
|
||||
return api.EvidenceResult{
|
||||
Grade: api.GradeCode(result.Grade), Basis: api.EvidenceBasis(result.Basis),
|
||||
CalibrationStatus: api.EvidenceCalibrationStatus(result.CalibrationStatus),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
)
|
||||
|
||||
type evidenceOperationsStub struct {
|
||||
page outbound.EvidenceFactPage
|
||||
facts []domain.EvidenceOrganizationFact
|
||||
err error
|
||||
query outbound.EvidenceListQuery
|
||||
actorID uuid.UUID
|
||||
orgID uuid.UUID
|
||||
handle string
|
||||
listCalls int
|
||||
}
|
||||
|
||||
func (stub *evidenceOperationsStub) ListMine(_ context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
stub.query = query
|
||||
return stub.page, stub.err
|
||||
}
|
||||
|
||||
func (stub *evidenceOperationsStub) ListForOrganization(_ context.Context, actorID, organizationID uuid.UUID, handle string) ([]domain.EvidenceOrganizationFact, error) {
|
||||
stub.listCalls++
|
||||
stub.actorID, stub.orgID, stub.handle = actorID, organizationID, handle
|
||||
return stub.facts, stub.err
|
||||
}
|
||||
|
||||
func evidenceTestFact(t *testing.T, candidateID uuid.UUID, at time.Time) domain.EvidenceFact {
|
||||
t.Helper()
|
||||
attempt := uuid.New()
|
||||
fact, err := domain.RestoreEvidenceFact(domain.EvidenceFactSnapshot{
|
||||
ID: uuid.New(), CandidateID: candidateID, Kind: domain.EvidenceKindMeasurement,
|
||||
SourceType: domain.EvidenceSourceAssessmentResult, EventID: attempt, ResultID: attempt,
|
||||
Skills: []domain.EvidenceSkillCode{"go", "backend"},
|
||||
Result: domain.EvidenceResult{
|
||||
Grade: domain.GradeJunior, Basis: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated,
|
||||
},
|
||||
Attribution: domain.EvidenceAttributionPersonal, Trust: domain.EvidenceTrustOnlineUnconfirmed,
|
||||
OccurredAt: at, Visibility: domain.EvidenceVisibilityVisible,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v", err)
|
||||
}
|
||||
return fact
|
||||
}
|
||||
|
||||
func TestListMyEvidenceMapsFactsAndPagesWithAnOwnerBoundCursor(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
at := time.Date(2026, 10, 8, 10, 15, 0, 0, time.UTC)
|
||||
stub := &evidenceOperationsStub{page: outbound.EvidenceFactPage{
|
||||
Items: []domain.EvidenceFact{evidenceTestFact(t, userID, at)},
|
||||
HasMore: true,
|
||||
}}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
|
||||
response, err := handler.ListMyEvidence(ctx, api.ListMyEvidenceParams{Limit: api.NewOptInt32(1)})
|
||||
if err != nil {
|
||||
t.Fatalf("ListMyEvidence() error = %v", err)
|
||||
}
|
||||
page, ok := response.(*api.EvidenceFactListHeaders)
|
||||
if !ok || page.CacheControl != api.CacheControlNoStoreNoStore || len(page.Response.Items) != 1 {
|
||||
t.Fatalf("ListMyEvidence() = %#v, want a no-store page of one fact", response)
|
||||
}
|
||||
item := page.Response.Items[0]
|
||||
if item.Trust != 1 || item.Kind != api.EvidenceKindMeasurement || item.Source.EventID != item.Source.ResultID ||
|
||||
len(item.Skills) != 2 || item.Skills[0] != api.EvidenceSkillCodeBackend || item.Result.Grade != api.GradeCodeJunior ||
|
||||
item.Visibility != api.EvidenceVisibilityVisible || !time.Time(item.OccurredAt).Equal(at) {
|
||||
t.Fatalf("fact mapping = %+v", item)
|
||||
}
|
||||
if stub.query.CandidateID != userID || stub.query.Limit != 1 || stub.query.After != nil {
|
||||
t.Fatalf("query = %+v, want the session owner and the first page", stub.query)
|
||||
}
|
||||
cursor, set := page.Response.Page.NextCursor.Get()
|
||||
if !page.Response.Page.HasMore || !set || cursor == "" {
|
||||
t.Fatalf("page info = %+v, want a next cursor", page.Response.Page)
|
||||
}
|
||||
|
||||
// The cursor continues the same owner's list at the last fact of the page.
|
||||
if _, err := handler.ListMyEvidence(ctx, api.ListMyEvidenceParams{Cursor: api.NewOptString(cursor)}); err != nil {
|
||||
t.Fatalf("ListMyEvidence(cursor) error = %v", err)
|
||||
}
|
||||
if stub.query.After == nil || stub.query.After.ID != stub.page.Items[0].Snapshot().ID || !stub.query.After.OccurredAt.Equal(at) {
|
||||
t.Fatalf("continuation = %+v, want the last fact of the previous page", stub.query.After)
|
||||
}
|
||||
|
||||
// A cursor of another candidate, a cursor of another list, and a limit out of range are validation errors.
|
||||
foreign, err := encodePrivacyCursor(uuid.New(), privacyCursorEvidence, at, uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
otherList, err := encodePrivacyCursor(userID, privacyCursorAccess, at, uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
for name, params := range map[string]api.ListMyEvidenceParams{
|
||||
"foreign cursor": {Cursor: api.NewOptString(foreign)},
|
||||
"other list": {Cursor: api.NewOptString(otherList)},
|
||||
"malformed cursor": {Cursor: api.NewOptString("not-a-cursor")},
|
||||
"limit too large": {Limit: api.NewOptInt32(outbound.MaxEvidencePageSize + 1)},
|
||||
} {
|
||||
response, err := handler.ListMyEvidence(ctx, params)
|
||||
if _, bad := response.(*api.ListMyEvidenceBadRequest); err != nil || !bad {
|
||||
t.Errorf("%s = %#v, %v, want 400", name, response, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMyEvidenceMapsAccessFailures(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
stub := &evidenceOperationsStub{err: evidence.ErrForbidden}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
response, err := handler.ListMyEvidence(privacyHTTPContext(userID, ""), api.ListMyEvidenceParams{})
|
||||
if _, forbidden := response.(*api.ListMyEvidenceForbidden); err != nil || !forbidden {
|
||||
t.Fatalf("forbidden actor = %#v, %v, want 403", response, err)
|
||||
}
|
||||
unauthenticated, err := handler.ListMyEvidence(context.Background(), api.ListMyEvidenceParams{})
|
||||
if _, ok := unauthenticated.(*api.ListMyEvidenceUnauthorized); err != nil || !ok {
|
||||
t.Fatalf("no principal = %#v, %v, want 401", unauthenticated, err)
|
||||
}
|
||||
stub.err = errors.New("storage failed")
|
||||
if _, err := handler.ListMyEvidence(privacyHTTPContext(userID, ""), api.ListMyEvidenceParams{}); err == nil {
|
||||
t.Fatal("an unexpected failure was swallowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationEvidenceMapsOnlyTheAllowlistedShape(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
fact, err := domain.NewEvidenceOrganizationFact(domain.EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: domain.GradeJunior, Trust: domain.EvidenceTrustOnlineUnconfirmed,
|
||||
Basis: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: 2026,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewEvidenceOrganizationFact() error = %v", err)
|
||||
}
|
||||
stub := &evidenceOperationsStub{facts: []domain.EvidenceOrganizationFact{fact}}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
params := api.GetOrganizationCandidateEvidenceParams{OrgID: organizationID, CandidateHandle: api.CandidateHandle(handle)}
|
||||
|
||||
response, err := handler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrganizationCandidateEvidence() error = %v", err)
|
||||
}
|
||||
body, ok := response.(*api.OrganizationEvidenceHeaders)
|
||||
if !ok || body.CacheControl != api.CacheControlNoStoreNoStore || len(body.Response.Items) != 1 {
|
||||
t.Fatalf("response = %#v, want a no-store projection of one fact", response)
|
||||
}
|
||||
if stub.actorID != userID || stub.orgID != organizationID || stub.handle != handle {
|
||||
t.Fatalf("scope = actor %s organization %s handle %q", stub.actorID, stub.orgID, stub.handle)
|
||||
}
|
||||
encoded, err := json.Marshal(body.Response)
|
||||
if err != nil {
|
||||
t.Fatalf("encode projection: %v", err)
|
||||
}
|
||||
if want := `{"items":[{"skill":"backend","grade":"junior","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":2026}]}`; string(encoded) != want {
|
||||
t.Fatalf("projection = %s, want %s", encoded, want)
|
||||
}
|
||||
for _, private := range []string{userID.String(), "event_id", "result_id", "occurred_at", "observed_month", "answer", "score", "visibility"} {
|
||||
if strings.Contains(string(encoded), private) {
|
||||
t.Fatalf("organization projection exposes %q: %s", private, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrganizationEvidenceMapsCardFailuresWithoutDistinction(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
handle := api.CandidateHandle("cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
stub := &evidenceOperationsStub{}
|
||||
handler := NewEvidenceHandler(stub)
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
params := api.GetOrganizationCandidateEvidenceParams{OrgID: organizationID, CandidateHandle: handle}
|
||||
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"candidate account": {candidateview.ErrForbidden, "forbidden"},
|
||||
"hidden or unpublished": {candidateview.ErrCandidateCardNotFound, "not_found"},
|
||||
"no membership": {outbound.ErrOrganizationNotFound, "not_found"},
|
||||
"bad handle": {candidateview.ErrInvalidCandidateHandle, "bad_request"},
|
||||
"quota": {&candidateview.RateLimitedError{RetryAt: time.Now().Add(time.Minute)}, "too_many"},
|
||||
} {
|
||||
stub.err = test.err
|
||||
response, err := handler.GetOrganizationCandidateEvidence(ctx, params)
|
||||
if err != nil {
|
||||
t.Errorf("%s: error = %v", name, err)
|
||||
continue
|
||||
}
|
||||
var got string
|
||||
switch response.(type) {
|
||||
case *api.GetOrganizationCandidateEvidenceForbidden:
|
||||
got = "forbidden"
|
||||
case *api.GetOrganizationCandidateEvidenceNotFound:
|
||||
got = "not_found"
|
||||
case *api.GetOrganizationCandidateEvidenceBadRequest:
|
||||
got = "bad_request"
|
||||
case *api.TooManyRequestsHeaders:
|
||||
got = "too_many"
|
||||
}
|
||||
if got != test.want {
|
||||
t.Errorf("%s = %T, want %s", name, response, test.want)
|
||||
}
|
||||
}
|
||||
stub.err = errors.New("storage failed")
|
||||
if _, err := handler.GetOrganizationCandidateEvidence(ctx, params); err == nil {
|
||||
t.Fatal("an unexpected failure was swallowed")
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ const (
|
||||
privacyCursorEvents = 1
|
||||
privacyCursorHidden = 2
|
||||
privacyCursorAccess = 3
|
||||
// privacyCursorEvidence belongs to the skill evidence list, which shares the
|
||||
// owner-bound cursor of the privacy lists.
|
||||
privacyCursorEvidence = 4
|
||||
)
|
||||
|
||||
// CandidateViewOperations serves private previews, owner access history, and
|
||||
@@ -434,7 +437,7 @@ func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID
|
||||
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
|
||||
at = at.UTC()
|
||||
seconds, nanos := at.Unix(), at.Nanosecond()
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorAccess || at.IsZero() ||
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorEvidence || at.IsZero() ||
|
||||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
|
||||
return "", errors.New("privacy cursor requires an owner and valid page position")
|
||||
}
|
||||
@@ -518,7 +521,13 @@ func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
|
||||
} else {
|
||||
card.SetTo(anonymousCardResponse(*preview.Card))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
evidence := api.NilOrganizationEvidence{}
|
||||
if preview.Card == nil {
|
||||
evidence.SetToNull()
|
||||
} else {
|
||||
evidence.SetTo(organizationEvidenceResponse(preview.Evidence))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, Evidence: evidence, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
}
|
||||
|
||||
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.EvidenceRepository = evidenceRepository{}
|
||||
|
||||
func (unit *UnitOfWork) Evidence() outbound.EvidenceRepository {
|
||||
return evidenceRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type evidenceRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListCandidateFacts(
|
||||
ctx context.Context,
|
||||
query outbound.EvidenceListQuery,
|
||||
) (outbound.EvidenceFactPage, error) {
|
||||
const location = "evidenceRepository.ListCandidateFacts"
|
||||
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxEvidencePageSize {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
// The statement fetches one extra row to learn whether another page follows.
|
||||
params := sqlc.ListCandidateEvidenceFactsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
|
||||
params.AfterID = pgUUID(query.After.ID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateEvidenceFacts(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - select facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
page := outbound.EvidenceFactPage{Items: make([]domain.EvidenceFact, 0, min(len(rows), int(query.Limit)))}
|
||||
if len(rows) > int(query.Limit) {
|
||||
page.HasMore = true
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceFactRow(query.CandidateID, row)
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - restore fact: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, fact)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreEvidenceFactRow(candidateID uuid.UUID, row sqlc.ListCandidateEvidenceFactsRow) (domain.EvidenceFact, error) {
|
||||
const location = "restoreEvidenceFactRow"
|
||||
skills := make([]domain.EvidenceSkillCode, 0, len(row.Skills))
|
||||
for _, code := range row.Skills {
|
||||
skills = append(skills, domain.EvidenceSkillCode(code))
|
||||
}
|
||||
trust, err := evidenceTrust(row.Trust)
|
||||
if err != nil {
|
||||
return domain.EvidenceFact{}, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
fact, err := domain.RestoreEvidenceFact(domain.EvidenceFactSnapshot{
|
||||
ID: optionalUUID(row.ID), CandidateID: candidateID, Kind: domain.EvidenceKind(row.Kind),
|
||||
SourceType: domain.EvidenceSourceType(row.SourceType), EventID: optionalUUID(row.EventID),
|
||||
ResultID: optionalUUID(row.ResultID), Skills: skills,
|
||||
Result: domain.EvidenceResult{
|
||||
Grade: domain.GradeCode(row.Grade), Basis: domain.AssessmentCategorySource(row.Basis),
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
|
||||
},
|
||||
Attribution: domain.EvidenceAttribution(row.Attribution), Trust: trust,
|
||||
OccurredAt: timeValueOrZero(row.OccurredAt), Visibility: domain.EvidenceVisibility(row.Visibility),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EvidenceFact{}, fmt.Errorf("%s - stored fact is invalid: %w", location, err)
|
||||
}
|
||||
return fact, nil
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListOrganizationFacts(
|
||||
ctx context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidenceRepository.ListOrganizationFacts"
|
||||
if organizationID == uuid.Nil || candidateID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs, err := evidenceCategoryPairs(categories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return []domain.EvidenceOrganizationFact{}, nil
|
||||
}
|
||||
rows, err := repository.queries.ListOrganizationVisibleEvidence(ctx, sqlc.ListOrganizationVisibleEvidenceParams{
|
||||
Categories: pairs, CandidateID: pgUUID(candidateID), OrganizationID: pgUUID(organizationID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select permitted facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
facts = append(facts, fact)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
func (repository evidenceRepository) ListPreviewFacts(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidenceRepository.ListPreviewFacts"
|
||||
if candidateID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs, err := evidenceCategoryPairs(categories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return []domain.EvidenceOrganizationFact{}, nil
|
||||
}
|
||||
rows, err := repository.queries.ListCandidatePreviewEvidence(ctx, sqlc.ListCandidatePreviewEvidenceParams{
|
||||
Categories: pairs, CandidateID: pgUUID(candidateID),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select preview facts: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
facts := make([]domain.EvidenceOrganizationFact, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
fact, err := restoreEvidenceOrganizationFact(row.Skill, row.Grade, row.Trust, row.Basis, row.CalibrationStatus, row.ObservedYear)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
facts = append(facts, fact)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
// evidenceCategoryPairs renders the categories of a card as the
|
||||
// "specialization/grade" keys that the statements match against a fact.
|
||||
func evidenceCategoryPairs(categories []domain.CandidateViewCategory) ([]string, error) {
|
||||
pairs := make([]string, 0, len(categories))
|
||||
for _, category := range categories {
|
||||
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() {
|
||||
return nil, fmt.Errorf("category is not known: %w", domain.ErrInvalidEvidence)
|
||||
}
|
||||
pairs = append(pairs, string(domain.EvidenceSkillOfSpecialization(category.Specialization))+"/"+string(category.Grade))
|
||||
}
|
||||
return pairs, nil
|
||||
}
|
||||
|
||||
func restoreEvidenceOrganizationFact(skill, grade string, trust int16, basis, calibration string, year int32) (domain.EvidenceOrganizationFact, error) {
|
||||
level, err := evidenceTrust(trust)
|
||||
if err != nil {
|
||||
return domain.EvidenceOrganizationFact{}, err
|
||||
}
|
||||
fact, err := domain.NewEvidenceOrganizationFact(domain.EvidenceOrganizationFactInput{
|
||||
Skill: domain.EvidenceSkillCode(skill), Grade: domain.GradeCode(grade), Trust: level,
|
||||
Basis: domain.AssessmentCategorySource(basis), CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(calibration),
|
||||
ObservedYear: year,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EvidenceOrganizationFact{}, fmt.Errorf("restore permitted fact: %w", err)
|
||||
}
|
||||
return fact, nil
|
||||
}
|
||||
|
||||
// evidenceTrust narrows the stored smallint after checking the range that the
|
||||
// table constraint already guarantees.
|
||||
func evidenceTrust(value int16) (domain.EvidenceTrust, error) {
|
||||
if value < int16(domain.EvidenceTrustStated) || value > int16(domain.EvidenceTrustInPerson) {
|
||||
return 0, fmt.Errorf("stored trust level is out of range: %w", domain.ErrInvalidEvidence)
|
||||
}
|
||||
return domain.EvidenceTrust(value), nil
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: evidence.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const listCandidateEvidenceFacts = `-- name: ListCandidateEvidenceFacts :many
|
||||
|
||||
SELECT
|
||||
fact.id,
|
||||
fact.kind,
|
||||
fact.source_type,
|
||||
fact.event_id,
|
||||
fact.result_id,
|
||||
fact.attribution,
|
||||
fact.trust,
|
||||
fact.grade,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
fact.occurred_at,
|
||||
fact.visibility,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
|
||||
FROM skill_evidence_skills AS skill
|
||||
WHERE skill.fact_id = fact.id
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS skills
|
||||
FROM skill_evidence_facts AS fact
|
||||
WHERE
|
||||
fact.candidate_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (fact.occurred_at, fact.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY fact.occurred_at DESC, fact.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListCandidateEvidenceFactsParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListCandidateEvidenceFactsRow struct {
|
||||
ID pgtype.UUID
|
||||
Kind string
|
||||
SourceType string
|
||||
EventID pgtype.UUID
|
||||
ResultID pgtype.UUID
|
||||
Attribution string
|
||||
Trust int16
|
||||
Grade string
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Visibility string
|
||||
Skills []string
|
||||
}
|
||||
|
||||
// Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
// failure, or anti-cheat data, and none of these statements names the result,
|
||||
// attempt, or review tables: evidence is read from its own facts only.
|
||||
// The candidate's own facts, hidden ones included, newest event first. Every
|
||||
// statement is scoped by the owner; the caller passes the continuation
|
||||
// position of the previous page, if any, and fetches one extra row.
|
||||
func (q *Queries) ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateEvidenceFacts,
|
||||
arg.CandidateID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateEvidenceFactsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateEvidenceFactsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Kind,
|
||||
&i.SourceType,
|
||||
&i.EventID,
|
||||
&i.ResultID,
|
||||
&i.Attribution,
|
||||
&i.Trust,
|
||||
&i.Grade,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.OccurredAt,
|
||||
&i.Visibility,
|
||||
&i.Skills,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCandidatePreviewEvidence = `-- name: ListCandidatePreviewEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM skill_evidence_facts AS fact
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
fact.candidate_id = $1
|
||||
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id
|
||||
`
|
||||
|
||||
type ListCandidatePreviewEvidenceParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Categories []string
|
||||
}
|
||||
|
||||
type ListCandidatePreviewEvidenceRow struct {
|
||||
Skill string
|
||||
Grade string
|
||||
Trust int16
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
// an organization or a cohort.
|
||||
func (q *Queries) ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidatePreviewEvidence, arg.CandidateID, arg.Categories)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidatePreviewEvidenceRow
|
||||
for rows.Next() {
|
||||
var i ListCandidatePreviewEvidenceRow
|
||||
if err := rows.Scan(
|
||||
&i.Skill,
|
||||
&i.Grade,
|
||||
&i.Trust,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.ObservedYear,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listOrganizationVisibleEvidence = `-- name: ListOrganizationVisibleEvidence :many
|
||||
SELECT DISTINCT ON (skill.skill_code)
|
||||
skill.skill_code AS skill,
|
||||
fact.grade,
|
||||
fact.trust,
|
||||
fact.basis,
|
||||
fact.calibration_status,
|
||||
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
|
||||
FROM candidate_effective_publications AS effective
|
||||
INNER JOIN skill_evidence_facts AS fact
|
||||
ON effective.user_id = fact.candidate_id
|
||||
INNER JOIN skill_evidence_skills AS skill
|
||||
ON fact.id = skill.fact_id
|
||||
WHERE
|
||||
effective.user_id = $1
|
||||
AND 'categories' = any(effective.fields)
|
||||
AND (skill.skill_code || '/' || fact.grade) = any($2::text [])
|
||||
AND fact.kind = 'measurement'
|
||||
AND fact.visibility = 'visible'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = $3
|
||||
)
|
||||
ORDER BY skill.skill_code, fact.occurred_at, fact.id
|
||||
`
|
||||
|
||||
type ListOrganizationVisibleEvidenceParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Categories []string
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
type ListOrganizationVisibleEvidenceRow struct {
|
||||
Skill string
|
||||
Grade string
|
||||
Trust int16
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// The evidence that one organization may read about one candidate: one fact
|
||||
// for each category of the card, the fact that supports the confirmed grade
|
||||
// of that category (the earliest one that passed exactly that grade, so a
|
||||
// lower grade or a retake adds nothing). The statement selects from the
|
||||
// effective publication view (published and backed by an unrevoked C2) and
|
||||
// excludes the candidates that hide the reading organization, so no row means
|
||||
// nothing to read, whatever the reason. The card must publish the categories
|
||||
// field and only visible measurements qualify. The categories come from the
|
||||
// caller as "specialization/grade" pairs taken from the card that was just
|
||||
// projected, so the answer never names a skill the card does not show. The columns are
|
||||
// an allowlist: no identifier of the fact, the event, the result, or the
|
||||
// candidate leaves, the instant is cut to the year, and the basis and the
|
||||
// calibration (the same for every candidate) say that the fact is a synthetic
|
||||
// demonstration.
|
||||
func (q *Queries) ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOrganizationVisibleEvidence, arg.CandidateID, arg.Categories, arg.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListOrganizationVisibleEvidenceRow
|
||||
for rows.Next() {
|
||||
var i ListOrganizationVisibleEvidenceRow
|
||||
if err := rows.Scan(
|
||||
&i.Skill,
|
||||
&i.Grade,
|
||||
&i.Trust,
|
||||
&i.Basis,
|
||||
&i.CalibrationStatus,
|
||||
&i.ObservedYear,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -729,6 +729,29 @@ type Session struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SkillEvidenceFact struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
Kind string
|
||||
SourceType string
|
||||
EventID pgtype.UUID
|
||||
ResultID pgtype.UUID
|
||||
Attribution string
|
||||
Trust int16
|
||||
Grade string
|
||||
Basis string
|
||||
CalibrationStatus string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Visibility string
|
||||
RecordedAt pgtype.Timestamptz
|
||||
CreatedTxid int64
|
||||
}
|
||||
|
||||
type SkillEvidenceSkill struct {
|
||||
FactID pgtype.UUID
|
||||
SkillCode string
|
||||
}
|
||||
|
||||
type SupportCase struct {
|
||||
ID pgtype.UUID
|
||||
CaseNumber string
|
||||
|
||||
@@ -550,11 +550,23 @@ type Querier interface {
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
// access relation, which is already visible to the candidate.
|
||||
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
|
||||
// Skill evidence reads. The projection tables hold no answer, score, item,
|
||||
// failure, or anti-cheat data, and none of these statements names the result,
|
||||
// attempt, or review tables: evidence is read from its own facts only.
|
||||
// The candidate's own facts, hidden ones included, newest event first. Every
|
||||
// statement is scoped by the owner; the caller passes the continuation
|
||||
// position of the previous page, if any, and fetches one extra row.
|
||||
ListCandidateEvidenceFacts(ctx context.Context, arg ListCandidateEvidenceFactsParams) ([]ListCandidateEvidenceFactsRow, error)
|
||||
// One page of the candidate's hidden organizations, newest first with the
|
||||
// organization identifier as the tie-breaker. The page continues after the
|
||||
// (hidden_at, organization_id) position of the last record of the previous
|
||||
// page.
|
||||
ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error)
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
// an organization or a cohort.
|
||||
ListCandidatePreviewEvidence(ctx context.Context, arg ListCandidatePreviewEvidenceParams) ([]ListCandidatePreviewEvidenceRow, error)
|
||||
// One page of the candidate's settings history, newest first with the event
|
||||
// identifier as the tie-breaker. The organization name is resolved here, at
|
||||
// read time, and is the current name. The page continues after the
|
||||
@@ -588,6 +600,21 @@ type Querier interface {
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
|
||||
// The evidence that one organization may read about one candidate: one fact
|
||||
// for each category of the card, the fact that supports the confirmed grade
|
||||
// of that category (the earliest one that passed exactly that grade, so a
|
||||
// lower grade or a retake adds nothing). The statement selects from the
|
||||
// effective publication view (published and backed by an unrevoked C2) and
|
||||
// excludes the candidates that hide the reading organization, so no row means
|
||||
// nothing to read, whatever the reason. The card must publish the categories
|
||||
// field and only visible measurements qualify. The categories come from the
|
||||
// caller as "specialization/grade" pairs taken from the card that was just
|
||||
// projected, so the answer never names a skill the card does not show. The columns are
|
||||
// an allowlist: no identifier of the fact, the event, the result, or the
|
||||
// candidate leaves, the instant is cut to the year, and the basis and the
|
||||
// calibration (the same for every candidate) say that the fact is a synthetic
|
||||
// demonstration.
|
||||
ListOrganizationVisibleEvidence(ctx context.Context, arg ListOrganizationVisibleEvidenceParams) ([]ListOrganizationVisibleEvidenceRow, error)
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
// creation time, organization ID) position of the last item of the
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/evidence"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const evidencePoolMaxConns = 4
|
||||
|
||||
func newEvidenceHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.EvidenceHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("evidence operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
key, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - derive projection key: %w", err)
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, evidencePoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
views, err := newCandidateViewService(pool, transactor, key)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create view service: %w", err)
|
||||
}
|
||||
service, err := evidence.NewService(evidence.Dependencies{
|
||||
Transactor: transactor, AuthorizeCategories: views.AuthorizeCategoriesSection,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newEvidenceHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewEvidenceHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -45,6 +45,7 @@ func newAPIHandler(
|
||||
assessmentHandler *v1.AssessmentHandler,
|
||||
assessmentSignalHandler *v1.AssessmentSignalHandler,
|
||||
privacyHandler *v1.PrivacyHandler,
|
||||
evidenceHandler *v1.EvidenceHandler,
|
||||
) *v1.Handler {
|
||||
return v1.NewHandler(health, problems,
|
||||
v1.WithIdentity(identityHandler),
|
||||
@@ -58,6 +59,7 @@ func newAPIHandler(
|
||||
v1.WithAssessment(assessmentHandler),
|
||||
v1.WithAssessmentSignals(assessmentSignalHandler),
|
||||
v1.WithPrivacy(privacyHandler),
|
||||
v1.WithEvidence(evidenceHandler),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
@@ -41,14 +42,7 @@ func newPrivacyHandler(
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now)
|
||||
quota := companyquota.NewService(time.Now)
|
||||
views, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
views, err := newCandidateViewService(pool, transactor, key)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err)
|
||||
@@ -60,3 +54,21 @@ func newPrivacyHandler(
|
||||
}
|
||||
return v1.NewPrivacyHandler(views, privacy, settings.AppPublicURL), pool.Close, nil
|
||||
}
|
||||
|
||||
// newCandidateViewService builds the organization card checks on the given
|
||||
// pool. The privacy handler and the evidence handler each own a pool and a
|
||||
// service, so their connection use stays separate.
|
||||
func newCandidateViewService(
|
||||
pool *pgxpool.Pool,
|
||||
transactor *postgres.Transactor,
|
||||
key domain.CandidateViewPseudonymKey,
|
||||
) (*candidateview.Service, error) {
|
||||
projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now)
|
||||
quota := companyquota.NewService(time.Now)
|
||||
return candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -57,6 +57,7 @@ func initialize(
|
||||
newAssessmentHandler,
|
||||
newAssessmentSignalHandler,
|
||||
newPrivacyHandler,
|
||||
newEvidenceHandler,
|
||||
newSessionSecurity,
|
||||
newRouter,
|
||||
newOutboxRelay,
|
||||
|
||||
@@ -184,46 +184,28 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler)
|
||||
evidenceHandler, cleanup15, err := newEvidenceHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler, evidenceHandler)
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
relay, cleanup15, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup16, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
@@ -242,7 +224,26 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
worker, cleanup17, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
relay, cleanup16, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup17, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
@@ -262,7 +263,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
mailsenderWorker, cleanup18, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
worker, cleanup18, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
@@ -283,7 +284,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup19, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
mailsenderWorker, cleanup19, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
if err != nil {
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
@@ -305,8 +306,32 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup20, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup19()
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
|
||||
return application, func() {
|
||||
cleanup20()
|
||||
cleanup19()
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidEvidence reports a skill evidence value that breaks a rule of the
|
||||
// evidence model.
|
||||
var ErrInvalidEvidence = errors.New("invalid skill evidence")
|
||||
|
||||
// EvidenceKind separates what a person stated from what a system observed. A
|
||||
// claim never becomes a measurement by repetition.
|
||||
type EvidenceKind string
|
||||
|
||||
const (
|
||||
EvidenceKindClaim EvidenceKind = "claim"
|
||||
EvidenceKindMeasurement EvidenceKind = "measurement"
|
||||
)
|
||||
|
||||
// EvidenceSourceType names where a fact comes from.
|
||||
type EvidenceSourceType string
|
||||
|
||||
// EvidenceSourceAssessmentResult is a real (root or corrective) assessment
|
||||
// result that confirmed a grade. An express training run is never a source.
|
||||
const EvidenceSourceAssessmentResult EvidenceSourceType = "assessment_result"
|
||||
|
||||
// EvidenceAttribution says whose contribution a fact is.
|
||||
type EvidenceAttribution string
|
||||
|
||||
const (
|
||||
EvidenceAttributionPersonal EvidenceAttribution = "personal"
|
||||
EvidenceAttributionTeamRole EvidenceAttribution = "team_role"
|
||||
EvidenceAttributionTeamUnattributed EvidenceAttribution = "team_unattributed"
|
||||
)
|
||||
|
||||
// EvidenceTrust is the strength of a confirmation: 0 stated, 1 an observable
|
||||
// online result without a reliable confirmation of the identity or the
|
||||
// authorship, 2 tied to a confirmed identity or an independent party, 3 an
|
||||
// in-person check.
|
||||
type EvidenceTrust uint8
|
||||
|
||||
const (
|
||||
EvidenceTrustStated EvidenceTrust = 0
|
||||
// EvidenceTrustOnlineUnconfirmed is the level of an online assessment: it
|
||||
// is unproctored and nothing confirms who answered. The database function
|
||||
// that projects a result writes this value, and a test keeps the two equal.
|
||||
EvidenceTrustOnlineUnconfirmed EvidenceTrust = 1
|
||||
EvidenceTrustIdentityTied EvidenceTrust = 2
|
||||
EvidenceTrustInPerson EvidenceTrust = 3
|
||||
)
|
||||
|
||||
// EvidenceVisibility says whether a fact may take part in what an
|
||||
// organization reads. It never publishes a fact by itself.
|
||||
type EvidenceVisibility string
|
||||
|
||||
const (
|
||||
EvidenceVisibilityVisible EvidenceVisibility = "visible"
|
||||
EvidenceVisibilityHidden EvidenceVisibility = "hidden"
|
||||
)
|
||||
|
||||
// EvidenceSkillCode is a skill tag from a closed set: the specialization codes
|
||||
// of the catalog and the technology codes of the anonymous card.
|
||||
type EvidenceSkillCode string
|
||||
|
||||
// EvidenceSkillOfSpecialization tags a fact with the specialization of a
|
||||
// category.
|
||||
func EvidenceSkillOfSpecialization(code SpecializationCode) EvidenceSkillCode {
|
||||
return EvidenceSkillCode(code)
|
||||
}
|
||||
|
||||
// IsKnown reports whether code belongs to the closed skill set.
|
||||
func (code EvidenceSkillCode) IsKnown() bool {
|
||||
return SpecializationCode(code).IsKnown() || CandidateViewSkillCode(code).IsKnown()
|
||||
}
|
||||
|
||||
// EvidenceSkillCodes returns the closed skill set in its stored order.
|
||||
func EvidenceSkillCodes() []EvidenceSkillCode {
|
||||
codes := make([]EvidenceSkillCode, 0, len(specializationCodes)+len(candidateViewSkillCodes))
|
||||
for _, code := range specializationCodes {
|
||||
codes = append(codes, EvidenceSkillCode(code))
|
||||
}
|
||||
for _, code := range candidateViewSkillCodes {
|
||||
codes = append(codes, EvidenceSkillCode(code))
|
||||
}
|
||||
return codes
|
||||
}
|
||||
|
||||
// EvidenceResult is what a fact says: the grade that was passed, the basis of
|
||||
// the measurement, and its calibration. It carries no score, answer, item,
|
||||
// failure, or anti-cheat data.
|
||||
type EvidenceResult struct {
|
||||
Grade GradeCode
|
||||
Basis AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
}
|
||||
|
||||
// EvidenceFactSnapshot is the stored shape of one fact of a candidate.
|
||||
type EvidenceFactSnapshot struct {
|
||||
ID uuid.UUID
|
||||
CandidateID uuid.UUID
|
||||
Kind EvidenceKind
|
||||
SourceType EvidenceSourceType
|
||||
// EventID is the source event and ResultID its immutable result. For an
|
||||
// assessment both are the attempt.
|
||||
EventID uuid.UUID
|
||||
ResultID uuid.UUID
|
||||
Skills []EvidenceSkillCode
|
||||
Result EvidenceResult
|
||||
Attribution EvidenceAttribution
|
||||
Trust EvidenceTrust
|
||||
OccurredAt time.Time
|
||||
Visibility EvidenceVisibility
|
||||
}
|
||||
|
||||
// EvidenceFact is one independent fact: one source event. The skills of the
|
||||
// event are tags of the fact, so adding a tag never adds a fact.
|
||||
type EvidenceFact struct {
|
||||
snapshot EvidenceFactSnapshot
|
||||
}
|
||||
|
||||
// RestoreEvidenceFact validates a stored fact against the rules of the model:
|
||||
// the trust level fits the kind, an assessment fact is a personal measurement
|
||||
// below the in-person level, and the skills are known, distinct, and ordered.
|
||||
func RestoreEvidenceFact(snapshot EvidenceFactSnapshot) (EvidenceFact, error) {
|
||||
const location = "domain.RestoreEvidenceFact"
|
||||
if snapshot.ID == uuid.Nil || snapshot.CandidateID == uuid.Nil || snapshot.EventID == uuid.Nil ||
|
||||
snapshot.ResultID == uuid.Nil || snapshot.OccurredAt.IsZero() {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if !snapshot.Kind.valid() || !snapshot.Attribution.valid() || !snapshot.Visibility.valid() ||
|
||||
!validEvidenceTrustForKind(snapshot.Kind, snapshot.Trust) {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - kind, trust, attribution, or visibility is invalid: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if !isOnlineAssessmentEvidence(snapshot) {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - an assessment fact is a personal online measurement of its own attempt: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if err := validateEvidenceResult(snapshot.Result); err != nil {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - result: %w", location, err)
|
||||
}
|
||||
skills, err := canonicalEvidenceSkills(snapshot.Skills)
|
||||
if err != nil {
|
||||
return EvidenceFact{}, fmt.Errorf("%s - skills: %w", location, err)
|
||||
}
|
||||
snapshot.Skills = skills
|
||||
snapshot.OccurredAt = snapshot.OccurredAt.UTC().Truncate(time.Microsecond)
|
||||
return EvidenceFact{snapshot: snapshot}, nil
|
||||
}
|
||||
|
||||
// isOnlineAssessmentEvidence reports whether a fact has the shape of the only
|
||||
// source that exists: a personal measurement of an assessment attempt that is
|
||||
// below the in-person level.
|
||||
func isOnlineAssessmentEvidence(snapshot EvidenceFactSnapshot) bool {
|
||||
return snapshot.SourceType == EvidenceSourceAssessmentResult && snapshot.Kind == EvidenceKindMeasurement &&
|
||||
snapshot.Attribution == EvidenceAttributionPersonal && snapshot.EventID == snapshot.ResultID &&
|
||||
snapshot.Trust <= EvidenceTrustIdentityTied
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of the stored shape.
|
||||
func (fact EvidenceFact) Snapshot() EvidenceFactSnapshot {
|
||||
snapshot := fact.snapshot
|
||||
snapshot.Skills = slices.Clone(snapshot.Skills)
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// IsZero reports whether the fact is the zero value.
|
||||
func (fact EvidenceFact) IsZero() bool { return fact.snapshot.ID == uuid.Nil }
|
||||
|
||||
// Bounds of the year that an organization reads, so a stored value outside a
|
||||
// sane range is refused instead of shown.
|
||||
const (
|
||||
minEvidenceObservedYear = 2000
|
||||
maxEvidenceObservedYear = 9999
|
||||
)
|
||||
|
||||
// EvidenceOrganizationFactInput is the allowlisted shape of the one fact that
|
||||
// supports a category of the card: the skill, the grade that was passed, the
|
||||
// trust level, the year of the event, and the basis and calibration of the
|
||||
// method, which are the same for every candidate. It has no identifier, no
|
||||
// exact time, and no source detail.
|
||||
type EvidenceOrganizationFactInput struct {
|
||||
Skill EvidenceSkillCode
|
||||
Grade GradeCode
|
||||
Trust EvidenceTrust
|
||||
Basis AssessmentCategorySource
|
||||
CalibrationStatus AssessmentCategoryCalibrationStatus
|
||||
ObservedYear int32
|
||||
}
|
||||
|
||||
// EvidenceOrganizationFact is one fact in the organization projection.
|
||||
type EvidenceOrganizationFact struct {
|
||||
input EvidenceOrganizationFactInput
|
||||
}
|
||||
|
||||
// NewEvidenceOrganizationFact validates the allowlisted organization shape. The
|
||||
// fact is always a measurement, so its trust is at least 1.
|
||||
func NewEvidenceOrganizationFact(input EvidenceOrganizationFactInput) (EvidenceOrganizationFact, error) {
|
||||
const location = "domain.NewEvidenceOrganizationFact"
|
||||
if !input.Skill.IsKnown() || !input.Grade.IsKnown() ||
|
||||
!validEvidenceTrustForKind(EvidenceKindMeasurement, input.Trust) {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - skill, grade, or trust is invalid: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
if err := validateEvidenceResult(EvidenceResult{Grade: input.Grade, Basis: input.Basis, CalibrationStatus: input.CalibrationStatus}); err != nil {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - result: %w", location, err)
|
||||
}
|
||||
if input.ObservedYear < minEvidenceObservedYear || input.ObservedYear > maxEvidenceObservedYear {
|
||||
return EvidenceOrganizationFact{}, fmt.Errorf("%s - observed year is out of range: %w", location, ErrInvalidEvidence)
|
||||
}
|
||||
return EvidenceOrganizationFact{input: input}, nil
|
||||
}
|
||||
|
||||
// Input returns the allowlisted shape.
|
||||
func (fact EvidenceOrganizationFact) Input() EvidenceOrganizationFactInput { return fact.input }
|
||||
|
||||
func (kind EvidenceKind) valid() bool {
|
||||
return kind == EvidenceKindClaim || kind == EvidenceKindMeasurement
|
||||
}
|
||||
|
||||
func (attribution EvidenceAttribution) valid() bool {
|
||||
switch attribution {
|
||||
case EvidenceAttributionPersonal, EvidenceAttributionTeamRole, EvidenceAttributionTeamUnattributed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (visibility EvidenceVisibility) valid() bool {
|
||||
return visibility == EvidenceVisibilityVisible || visibility == EvidenceVisibilityHidden
|
||||
}
|
||||
|
||||
// validEvidenceTrustForKind keeps a claim at level 0 and a measurement at
|
||||
// levels 1 to 3.
|
||||
func validEvidenceTrustForKind(kind EvidenceKind, trust EvidenceTrust) bool {
|
||||
switch kind {
|
||||
case EvidenceKindClaim:
|
||||
return trust == EvidenceTrustStated
|
||||
case EvidenceKindMeasurement:
|
||||
return trust >= EvidenceTrustOnlineUnconfirmed && trust <= EvidenceTrustInPerson
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validateEvidenceResult(result EvidenceResult) error {
|
||||
if !result.Grade.IsKnown() || result.Basis != AssessmentCategorySourceSyntheticDemo ||
|
||||
result.CalibrationStatus != AssessmentCategoryCalibrationUncalibrated {
|
||||
return fmt.Errorf("grade, basis, or calibration is not known: %w", ErrInvalidEvidence)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// canonicalEvidenceSkills returns the skills sorted, after checking that there
|
||||
// is at least one, that each is known, and that none repeats.
|
||||
func canonicalEvidenceSkills(skills []EvidenceSkillCode) ([]EvidenceSkillCode, error) {
|
||||
if len(skills) == 0 || len(skills) > len(EvidenceSkillCodes()) {
|
||||
return nil, fmt.Errorf("a fact needs between one and every known skill: %w", ErrInvalidEvidence)
|
||||
}
|
||||
ordered := slices.Clone(skills)
|
||||
slices.SortFunc(ordered, func(left, right EvidenceSkillCode) int { return strings.Compare(string(left), string(right)) })
|
||||
for index, code := range ordered {
|
||||
if !code.IsKnown() {
|
||||
return nil, fmt.Errorf("skill %q is not known: %w", string(code), ErrInvalidEvidence)
|
||||
}
|
||||
if index > 0 && ordered[index-1] == code {
|
||||
return nil, fmt.Errorf("skill %q repeats: %w", string(code), ErrInvalidEvidence)
|
||||
}
|
||||
}
|
||||
return ordered, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func validEvidenceSnapshot() EvidenceFactSnapshot {
|
||||
attempt := uuid.New()
|
||||
return EvidenceFactSnapshot{
|
||||
ID: uuid.New(), CandidateID: uuid.New(), Kind: EvidenceKindMeasurement,
|
||||
SourceType: EvidenceSourceAssessmentResult, EventID: attempt, ResultID: attempt,
|
||||
Skills: []EvidenceSkillCode{"go", "backend"},
|
||||
Result: EvidenceResult{
|
||||
Grade: GradeJunior, Basis: AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: AssessmentCategoryCalibrationUncalibrated,
|
||||
},
|
||||
Attribution: EvidenceAttributionPersonal, Trust: EvidenceTrustOnlineUnconfirmed,
|
||||
OccurredAt: time.Date(2026, 10, 8, 10, 15, 0, 123456789, time.FixedZone("test", 3*60*60)),
|
||||
Visibility: EvidenceVisibilityVisible,
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreEvidenceFactKeepsOneFactWithOrderedTags(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
snapshot := validEvidenceSnapshot()
|
||||
fact, err := RestoreEvidenceFact(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v", err)
|
||||
}
|
||||
got := fact.Snapshot()
|
||||
if !slices.Equal(got.Skills, []EvidenceSkillCode{"backend", "go"}) {
|
||||
t.Fatalf("Skills = %v, want the tags of one event in ascending order", got.Skills)
|
||||
}
|
||||
if got.OccurredAt.Location() != time.UTC || got.OccurredAt.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("OccurredAt = %v, want UTC at microsecond precision", got.OccurredAt)
|
||||
}
|
||||
got.Skills[0] = "qa"
|
||||
if fact.Snapshot().Skills[0] != "backend" {
|
||||
t.Fatal("Snapshot() shares its skill slice with the fact")
|
||||
}
|
||||
if EvidenceTrustOnlineUnconfirmed != 1 {
|
||||
t.Fatalf("online trust = %d, want 1", EvidenceTrustOnlineUnconfirmed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreEvidenceFactRejectsBrokenModelRules(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := map[string]func(*EvidenceFactSnapshot){
|
||||
"claim above level 0": func(s *EvidenceFactSnapshot) { s.Kind = EvidenceKindClaim; s.Trust = EvidenceTrustOnlineUnconfirmed },
|
||||
"measurement at level 0": func(s *EvidenceFactSnapshot) { s.Trust = EvidenceTrustStated },
|
||||
"online result at the in-person level": func(s *EvidenceFactSnapshot) { s.Trust = EvidenceTrustInPerson },
|
||||
"assessment claim": func(s *EvidenceFactSnapshot) { s.Kind = EvidenceKindClaim; s.Trust = EvidenceTrustStated },
|
||||
"team attribution": func(s *EvidenceFactSnapshot) { s.Attribution = EvidenceAttributionTeamUnattributed },
|
||||
"event differs from result": func(s *EvidenceFactSnapshot) { s.ResultID = uuid.New() },
|
||||
"unknown source": func(s *EvidenceFactSnapshot) { s.SourceType = "demo_express" },
|
||||
"no skill": func(s *EvidenceFactSnapshot) { s.Skills = nil },
|
||||
"repeated tag": func(s *EvidenceFactSnapshot) { s.Skills = []EvidenceSkillCode{"go", "go"} },
|
||||
"unknown tag": func(s *EvidenceFactSnapshot) { s.Skills = []EvidenceSkillCode{"rate-limiting"} },
|
||||
"unknown grade": func(s *EvidenceFactSnapshot) { s.Result.Grade = "principal" },
|
||||
"calibration missing": func(s *EvidenceFactSnapshot) { s.Result.CalibrationStatus = "" },
|
||||
"unknown visibility": func(s *EvidenceFactSnapshot) { s.Visibility = "public" },
|
||||
"missing candidate": func(s *EvidenceFactSnapshot) { s.CandidateID = uuid.Nil },
|
||||
"missing time": func(s *EvidenceFactSnapshot) { s.OccurredAt = time.Time{} },
|
||||
}
|
||||
for name, mutate := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
snapshot := validEvidenceSnapshot()
|
||||
mutate(&snapshot)
|
||||
if _, err := RestoreEvidenceFact(snapshot); !errors.Is(err, ErrInvalidEvidence) {
|
||||
t.Fatalf("RestoreEvidenceFact() error = %v, want ErrInvalidEvidence", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvidenceSkillCodesAreTheSpecializationsAndTheCardTechnologies(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
codes := EvidenceSkillCodes()
|
||||
if len(codes) != len(specializationCodes)+len(CandidateViewSkillCodes()) {
|
||||
t.Fatalf("EvidenceSkillCodes() has %d codes", len(codes))
|
||||
}
|
||||
for _, code := range codes {
|
||||
if !code.IsKnown() {
|
||||
t.Errorf("%q is listed but not known", code)
|
||||
}
|
||||
}
|
||||
if EvidenceSkillCode("rate-limiting").IsKnown() || EvidenceSkillCode("").IsKnown() {
|
||||
t.Fatal("a code outside the closed set is known")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEvidenceOrganizationFactChecksTheAllowlistedShape(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
valid := EvidenceOrganizationFactInput{
|
||||
Skill: "backend", Grade: GradeJunior, Trust: EvidenceTrustOnlineUnconfirmed,
|
||||
Basis: AssessmentCategorySourceSyntheticDemo, CalibrationStatus: AssessmentCategoryCalibrationUncalibrated, ObservedYear: 2026,
|
||||
}
|
||||
fact, err := NewEvidenceOrganizationFact(valid)
|
||||
if err != nil || fact.Input() != valid {
|
||||
t.Fatalf("NewEvidenceOrganizationFact() = %+v, %v, want the input back", fact.Input(), err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*EvidenceOrganizationFactInput){
|
||||
"year before the range": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 1999 },
|
||||
"year after the range": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 10000 },
|
||||
"no year": func(i *EvidenceOrganizationFactInput) { i.ObservedYear = 0 },
|
||||
"claim level": func(i *EvidenceOrganizationFactInput) { i.Trust = EvidenceTrustStated },
|
||||
"trust above in person": func(i *EvidenceOrganizationFactInput) { i.Trust = 4 },
|
||||
"unknown skill": func(i *EvidenceOrganizationFactInput) { i.Skill = "rate-limiting" },
|
||||
"no skill": func(i *EvidenceOrganizationFactInput) { i.Skill = "" },
|
||||
"unknown grade": func(i *EvidenceOrganizationFactInput) { i.Grade = "principal" },
|
||||
"no basis": func(i *EvidenceOrganizationFactInput) { i.Basis = "" },
|
||||
"no calibration": func(i *EvidenceOrganizationFactInput) { i.CalibrationStatus = "" },
|
||||
} {
|
||||
input := valid
|
||||
mutate(&input)
|
||||
if _, err := NewEvidenceOrganizationFact(input); !errors.Is(err, ErrInvalidEvidence) {
|
||||
t.Errorf("%s: error = %v, want ErrInvalidEvidence", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
// MaxEvidencePageSize bounds one page of the candidate's own facts.
|
||||
const MaxEvidencePageSize = 100
|
||||
|
||||
// EvidencePosition is the descending key of the candidate's fact list.
|
||||
type EvidencePosition struct {
|
||||
OccurredAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// EvidenceListQuery selects one owner-scoped page of facts.
|
||||
type EvidenceListQuery struct {
|
||||
CandidateID uuid.UUID
|
||||
After *EvidencePosition
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// EvidenceFactPage is one page of the candidate's facts, newest event first.
|
||||
type EvidenceFactPage struct {
|
||||
Items []domain.EvidenceFact
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// EvidencePositionOf creates the continuation key for a fact.
|
||||
func EvidencePositionOf(fact domain.EvidenceFact) EvidencePosition {
|
||||
snapshot := fact.Snapshot()
|
||||
return EvidencePosition{OccurredAt: snapshot.OccurredAt, ID: snapshot.ID}
|
||||
}
|
||||
|
||||
// EvidenceRepository reads the skill evidence projection. It never reads an
|
||||
// assessment result, answer, attempt, or review: the projection is the only
|
||||
// source, so no answer, failure, or anti-cheat datum can reach a caller.
|
||||
type EvidenceRepository interface {
|
||||
// ListCandidateFacts returns one page of the facts that belong to the
|
||||
// candidate, hidden ones included.
|
||||
ListCandidateFacts(ctx context.Context, query EvidenceListQuery) (EvidenceFactPage, error)
|
||||
|
||||
// ListOrganizationFacts returns the evidence that one organization may read
|
||||
// about one candidate: for each category of the card, the one fact that
|
||||
// supports its confirmed grade. The adapter must select from
|
||||
// candidate_effective_publications, exclude the candidates that hide the
|
||||
// organization in the same statement, require the published card to carry
|
||||
// the categories field, and return only visible measurements. The caller
|
||||
// has already authorized the active organization membership and passes the
|
||||
// categories that the card just projected.
|
||||
ListOrganizationFacts(
|
||||
ctx context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error)
|
||||
|
||||
// ListPreviewFacts returns the same selection for the candidate's own card
|
||||
// preview. It applies no organization and no cohort, and the caller has
|
||||
// locked the effective C2 and publication.
|
||||
ListPreviewFacts(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error)
|
||||
}
|
||||
@@ -62,6 +62,7 @@ type UnitOfWork interface {
|
||||
PrivacyCohort() PrivacyCohortRepository
|
||||
PrivacyView() PrivacyViewRepository
|
||||
PrivacySettings() PrivacySettingsRepository
|
||||
Evidence() EvidenceRepository
|
||||
AccountDeletionRequests() AccountDeletionRequests
|
||||
ConsentRevocationEffects() ConsentRevocationEffects
|
||||
OrganizationRepositories
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package candidateview
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// categoriesProjector projects the one test source with the given categories.
|
||||
type categoriesProjector struct {
|
||||
contactAccessProjector
|
||||
|
||||
categories []domain.CandidateViewCategory
|
||||
}
|
||||
|
||||
func (projector categoriesProjector) ProjectSources(organizationID uuid.UUID, sources []domain.CandidateViewSource) ([]domain.AnonymousCandidateViewDTO, error) {
|
||||
views, err := projector.contactAccessProjector.ProjectSources(organizationID, sources)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
views[0].Categories = projector.categories
|
||||
return views, nil
|
||||
}
|
||||
|
||||
type categoriesSectionFixture struct {
|
||||
service *Service
|
||||
contact *contactAccessFixture
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
handle string
|
||||
quotaCalls int
|
||||
}
|
||||
|
||||
func newCategoriesSectionFixture(t *testing.T, categories []domain.CandidateViewCategory, allowed bool, actorScenario domain.Scenario) *categoriesSectionFixture {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
actorID, candidateID := uuid.New(), uuid.New()
|
||||
organization, membership := newContactAccessOrganization(t, actorID, now)
|
||||
actor := domain.User{ID: actorID, Scenario: actorScenario, EmailVerifiedAt: &now}
|
||||
candidate := domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
publication, err := domain.NewCardFieldSet([]domain.CardField{domain.CardFieldCategories})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
source, err := domain.NewCandidateViewSource(candidateID, publication, domain.CandidateViewProfile{}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewSource() error = %v", err)
|
||||
}
|
||||
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("section-view-key"), 2))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
handle, err := key.ForOrganization(organization.ID(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
fixture := &categoriesSectionFixture{
|
||||
contact: &contactAccessFixture{}, actorID: actorID, organizationID: organization.ID(), handle: handle,
|
||||
}
|
||||
unit := contactAccessUnit{
|
||||
users: contactAccessUsers{users: map[uuid.UUID]domain.User{actorID: actor, candidateID: candidate}},
|
||||
organizations: contactAccessOrganizations{organization: organization, membership: membership},
|
||||
view: contactAccessViewRepository{fixture: fixture.contact, source: source},
|
||||
}
|
||||
fixture.service, err = NewService(Dependencies{
|
||||
Transactor: contactAccessTransactor{unit: unit},
|
||||
Projector: categoriesProjector{
|
||||
contactAccessProjector: contactAccessProjector{key: key, source: source}, categories: categories,
|
||||
},
|
||||
PseudonymKey: key,
|
||||
Quota: func(context.Context, outbound.UnitOfWork, domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
fixture.quotaCalls++
|
||||
return outbound.CompanyQuotaDecision{Allowed: allowed, RetryAt: now.Add(time.Minute)}, nil
|
||||
},
|
||||
Clock: func() time.Time { return now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
fixture.contact.audits = nil
|
||||
return fixture
|
||||
}
|
||||
|
||||
func (fixture *categoriesSectionFixture) authorize(t *testing.T, handle string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
t.Helper()
|
||||
var candidateID uuid.UUID
|
||||
var categories []domain.CandidateViewCategory
|
||||
err := fixture.service.transactor.WithinTransaction(context.Background(), func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
candidateID, categories, err = fixture.service.AuthorizeCategoriesSection(ctx, unit, fixture.actorID, fixture.organizationID, handle)
|
||||
return err
|
||||
})
|
||||
return candidateID, categories, err
|
||||
}
|
||||
|
||||
func TestAuthorizeCategoriesSectionNamesTheCategoriesOfTheCurrentCard(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
shown := []domain.CandidateViewCategory{
|
||||
{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard},
|
||||
{Specialization: domain.SpecializationQA, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard},
|
||||
}
|
||||
fixture := newCategoriesSectionFixture(t, shown, true, domain.ScenarioEmployer)
|
||||
|
||||
candidateID, categories, err := fixture.authorize(t, fixture.handle)
|
||||
if err != nil {
|
||||
t.Fatalf("AuthorizeCategoriesSection() error = %v", err)
|
||||
}
|
||||
if candidateID == uuid.Nil || !slices.Equal(categories, shown) {
|
||||
t.Fatalf("section = %s %v, want the candidate and the categories of the card", candidateID, categories)
|
||||
}
|
||||
if fixture.quotaCalls != 1 || len(fixture.contact.audits) != 1 ||
|
||||
fixture.contact.audits[0].Kind() != domain.CandidateCardAccessCardViewed ||
|
||||
!slices.Equal(fixture.contact.audits[0].FieldCodes(), []string{"categories"}) {
|
||||
t.Fatalf("quota calls = %d, audits = %v, want one view of the categories field", fixture.quotaCalls, fixture.contact.audits)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeCategoriesSectionRefusesWithoutLeavingATrace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
categories := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStandard}}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
categories []domain.CandidateViewCategory
|
||||
allowed bool
|
||||
scenario domain.Scenario
|
||||
handle func(*categoriesSectionFixture) string
|
||||
want error
|
||||
wantQuota int
|
||||
}{
|
||||
{name: "a card without categories", allowed: true, scenario: domain.ScenarioEmployer, want: ErrCandidateCardNotFound},
|
||||
{name: "an exhausted quota", categories: categories, scenario: domain.ScenarioEmployer, want: ErrCandidateViewQuotaExceeded, wantQuota: 1},
|
||||
{name: "a candidate account", categories: categories, allowed: true, scenario: domain.ScenarioCandidate, want: ErrForbidden},
|
||||
{
|
||||
name: "a handle of another organization", categories: categories, allowed: true, scenario: domain.ScenarioEmployer,
|
||||
handle: func(*categoriesSectionFixture) string { return "cv1_" + string(bytes.Repeat([]byte("A"), 43)) },
|
||||
want: ErrCandidateCardNotFound,
|
||||
},
|
||||
{
|
||||
name: "a malformed handle", categories: categories, allowed: true, scenario: domain.ScenarioEmployer,
|
||||
handle: func(*categoriesSectionFixture) string { return "candidate" }, want: ErrInvalidCandidateHandle,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newCategoriesSectionFixture(t, test.categories, test.allowed, test.scenario)
|
||||
handle := fixture.handle
|
||||
if test.handle != nil {
|
||||
handle = test.handle(fixture)
|
||||
}
|
||||
_, _, err := fixture.authorize(t, handle)
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("AuthorizeCategoriesSection() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if len(fixture.contact.audits) != 0 || fixture.quotaCalls != test.wantQuota {
|
||||
t.Fatalf("audits = %v, quota calls = %d, want no audit and %d quota calls", fixture.contact.audits, fixture.quotaCalls, test.wantQuota)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -114,23 +115,90 @@ func (service *Service) getOrganizationCardInTransaction(
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
decision, err := service.quota(ctx, unit, organization, candidateID)
|
||||
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
||||
return cardViewAccessEvent(candidateID, organizationID, actorID, view, at)
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - reserve card view: %w", location, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return domain.AnonymousCandidateViewDTO{}, &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
event, err := cardViewAccessEvent(candidateID, organizationID, actorID, view, service.clock())
|
||||
if err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - build access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return domain.AnonymousCandidateViewDTO{}, fmt.Errorf("%s - record access audit: %w", location, err)
|
||||
return domain.AnonymousCandidateViewDTO{}, err
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// reserveCardView consumes the card-view quota and appends the access audit
|
||||
// that auditFor builds. Both commit with the visibility checks that the
|
||||
// caller ran in the same transaction, so a failed read leaves neither behind.
|
||||
func (service *Service) reserveCardView(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
repository outbound.PrivacyViewRepository,
|
||||
organization domain.Organization,
|
||||
candidateID uuid.UUID,
|
||||
location string,
|
||||
auditFor func(at time.Time) (domain.CandidateCardAccess, error),
|
||||
) error {
|
||||
decision, err := service.quota(ctx, unit, organization, candidateID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - reserve card view: %w", location, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
return &RateLimitedError{RetryAt: decision.RetryAt.UTC()}
|
||||
}
|
||||
event, err := auditFor(service.clock())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build access audit: %w", location, err)
|
||||
}
|
||||
if err := repository.RecordCandidateCardAccess(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - record access audit: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AuthorizeCategoriesSection runs the checks of an organization card read
|
||||
// inside the caller's transaction and reports which candidate, and which
|
||||
// categories (specialization and grade), the card shows. It exists for the sections
|
||||
// of a card that explain its categories, such as the permitted evidence: they
|
||||
// must not disclose more than the categories of the current card do.
|
||||
//
|
||||
// The checks are those of GetOrganizationCard: the active membership of the
|
||||
// actor, the effective C2 publication, the hiding of this organization, and
|
||||
// the minimum cohort, all under the same locks. The card must also show at
|
||||
// least one category after the cohort rules, otherwise the answer is
|
||||
// ErrCandidateCardNotFound, the same as for an unknown handle. A successful
|
||||
// call consumes the card-view quota and records the access with the
|
||||
// categories field, so the candidate sees the read in the access history. The
|
||||
// caller reads the section in the same transaction, after this returns.
|
||||
func (service *Service) AuthorizeCategoriesSection(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
const location = "candidateview.Service.AuthorizeCategoriesSection"
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return uuid.Nil, nil, ErrForbidden
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(handle) {
|
||||
return uuid.Nil, nil, ErrInvalidCandidateHandle
|
||||
}
|
||||
organization, repository, candidateID, view, err := service.currentOrganizationCard(ctx, unit, actorID, organizationID, handle, location)
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
}
|
||||
if len(view.Categories) == 0 {
|
||||
return uuid.Nil, nil, ErrCandidateCardNotFound
|
||||
}
|
||||
err = service.reserveCardView(ctx, unit, repository, organization, candidateID, location, func(at time.Time) (domain.CandidateCardAccess, error) {
|
||||
return domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
|
||||
CandidateID: candidateID, OrganizationID: organizationID, ActorID: actorID,
|
||||
Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories}, OccurredAt: at,
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
}
|
||||
return candidateID, slices.Clone(view.Categories), nil
|
||||
}
|
||||
|
||||
func (service *Service) currentOrganizationCard(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
@@ -216,9 +284,13 @@ func projectedViewForHandle(
|
||||
// PreviewResult contains only the candidate's own current publication state
|
||||
// and the strict anonymous-card projection.
|
||||
type PreviewResult struct {
|
||||
Published bool
|
||||
Fields domain.CardFieldSet
|
||||
Card *domain.AnonymousCandidateViewDTO
|
||||
Published bool
|
||||
Fields domain.CardFieldSet
|
||||
Card *domain.AnonymousCandidateViewDTO
|
||||
// Evidence is what an organization would read with the categories of the
|
||||
// card: for each category, the one fact that supports its confirmed grade.
|
||||
// It is empty when the card shows no category.
|
||||
Evidence []domain.EvidenceOrganizationFact
|
||||
GeneratedAt time.Time
|
||||
}
|
||||
|
||||
@@ -266,7 +338,13 @@ func (service *Service) GetMyCardPreview(ctx context.Context, actorID uuid.UUID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build private preview: %w", location, err)
|
||||
}
|
||||
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, GeneratedAt: generatedAt}
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
if len(card.Categories) > 0 {
|
||||
if facts, err = unit.Evidence().ListPreviewFacts(ctx, actorID, card.Categories); err != nil {
|
||||
return fmt.Errorf("%s - read preview evidence: %w", location, err)
|
||||
}
|
||||
}
|
||||
result = PreviewResult{Published: true, Fields: source.PublishedFields(), Card: &card, Evidence: facts, GeneratedAt: generatedAt}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
// Package evidence reads the skill evidence projection. The candidate reads
|
||||
// their own facts; an organization reads only the permitted projection of a
|
||||
// card it is currently allowed to see. The projection holds no answers,
|
||||
// failures, or anti-cheat data, and this package has no way to reach them.
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrForbidden reports an actor of the wrong role or without a verified
|
||||
// email.
|
||||
ErrForbidden = errors.New("skill evidence is forbidden")
|
||||
// ErrInvalidRequest reports a page request outside the contract bounds.
|
||||
ErrInvalidRequest = errors.New("skill evidence request is invalid")
|
||||
// ErrServiceMissing reports an incomplete service wiring.
|
||||
ErrServiceMissing = errors.New("skill evidence service is unavailable")
|
||||
)
|
||||
|
||||
// AuthorizeCategoriesSection runs the shared organization card checks inside
|
||||
// the given transaction: active membership, effective C2 publication, hiding of
|
||||
// the organization, the minimum cohort, the card-view quota, and the access
|
||||
// audit. It returns the candidate and the categories that the card shows. The
|
||||
// candidateview usecase provides it; bootstrap passes it in so this package
|
||||
// does not depend on another usecase.
|
||||
type AuthorizeCategoriesSection func(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) (uuid.UUID, []domain.CandidateViewCategory, error)
|
||||
|
||||
// Dependencies configure the read service.
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
AuthorizeCategories AuthorizeCategoriesSection
|
||||
}
|
||||
|
||||
// Service reads the evidence projection.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
authorizeCategories AuthorizeCategoriesSection
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.AuthorizeCategories == nil {
|
||||
return nil, fmt.Errorf("evidence.NewService - dependencies are missing: %w", ErrServiceMissing)
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, authorizeCategories: deps.AuthorizeCategories}, nil
|
||||
}
|
||||
|
||||
// ListMine returns one owner-scoped page of the candidate's facts, hidden ones
|
||||
// included. The candidate comes from the session and nothing else selects the
|
||||
// owner.
|
||||
func (service *Service) ListMine(ctx context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
const location = "evidence.Service.ListMine"
|
||||
if query.CandidateID == uuid.Nil {
|
||||
return outbound.EvidenceFactPage{}, ErrForbidden
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxEvidencePageSize {
|
||||
return outbound.EvidenceFactPage{}, ErrInvalidRequest
|
||||
}
|
||||
var page outbound.EvidenceFactPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeCandidate(ctx, unit, query.CandidateID); err != nil {
|
||||
return err
|
||||
}
|
||||
var readErr error
|
||||
page, readErr = unit.Evidence().ListCandidateFacts(ctx, query)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("%s - read owner facts: %w", location, readErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.EvidenceFactPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// ListForOrganization returns the permitted facts of the card that the handle
|
||||
// names for the organization. The membership, the publication, the hiding, and
|
||||
// the cohort are rechecked by the card checks, and the repository rechecks the
|
||||
// publication and the hiding again in the statement that reads the facts, so a
|
||||
// change between the two cannot widen the answer. Nothing returned belongs to
|
||||
// a candidate that the organization may not see now.
|
||||
func (service *Service) ListForOrganization(
|
||||
ctx context.Context,
|
||||
actorID, organizationID uuid.UUID,
|
||||
handle string,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
const location = "evidence.Service.ListForOrganization"
|
||||
var facts []domain.EvidenceOrganizationFact
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
candidateID, categories, err := service.authorizeCategories(ctx, unit, actorID, organizationID, handle)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read permitted facts: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return facts, nil
|
||||
}
|
||||
|
||||
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
|
||||
user, err := unit.Users().GetByID(ctx, actorID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return ErrForbidden
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("evidence.authorizeCandidate - read actor account: %w", err)
|
||||
}
|
||||
if !user.EmailVerified() || user.Scenario != domain.ScenarioCandidate {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type evidenceTestTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor evidenceTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
type evidenceTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
users outbound.UserRepository
|
||||
evidence *evidenceTestRepository
|
||||
}
|
||||
|
||||
func (unit evidenceTestUnit) Users() outbound.UserRepository { return unit.users }
|
||||
func (unit evidenceTestUnit) Evidence() outbound.EvidenceRepository { return unit.evidence }
|
||||
|
||||
type evidenceTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
users map[uuid.UUID]domain.User
|
||||
}
|
||||
|
||||
func (repository evidenceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type evidenceTestRepository struct {
|
||||
query outbound.EvidenceListQuery
|
||||
organizationID uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
categories []domain.CandidateViewCategory
|
||||
listCalls int
|
||||
organizationHit int
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListCandidateFacts(_ context.Context, query outbound.EvidenceListQuery) (outbound.EvidenceFactPage, error) {
|
||||
repository.listCalls++
|
||||
repository.query = query
|
||||
return outbound.EvidenceFactPage{}, nil
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListOrganizationFacts(
|
||||
_ context.Context,
|
||||
organizationID, candidateID uuid.UUID,
|
||||
categories []domain.CandidateViewCategory,
|
||||
) ([]domain.EvidenceOrganizationFact, error) {
|
||||
repository.organizationHit++
|
||||
repository.organizationID, repository.candidateID, repository.categories = organizationID, candidateID, categories
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (repository *evidenceTestRepository) ListPreviewFacts(context.Context, uuid.UUID, []domain.CandidateViewCategory) ([]domain.EvidenceOrganizationFact, error) {
|
||||
return nil, errors.New("the organization read must not read the preview")
|
||||
}
|
||||
|
||||
func newEvidenceTestService(t *testing.T, authorize AuthorizeCategoriesSection) (*Service, *evidenceTestRepository, domain.User, domain.User) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
|
||||
candidate := domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &now}
|
||||
employer := domain.User{ID: uuid.New(), Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &now}
|
||||
unverified := domain.User{ID: uuid.New(), Scenario: domain.ScenarioCandidate}
|
||||
repository := &evidenceTestRepository{}
|
||||
unit := evidenceTestUnit{
|
||||
users: evidenceTestUsers{users: map[uuid.UUID]domain.User{
|
||||
candidate.ID: candidate, employer.ID: employer, unverified.ID: unverified,
|
||||
}},
|
||||
evidence: repository,
|
||||
}
|
||||
service, err := NewService(Dependencies{Transactor: evidenceTestTransactor{unit: unit}, AuthorizeCategories: authorize})
|
||||
if err != nil {
|
||||
t.Fatalf("NewService() error = %v", err)
|
||||
}
|
||||
return service, repository, candidate, unverified
|
||||
}
|
||||
|
||||
func noAuthorization(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID, string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
return uuid.Nil, nil, errors.New("the owner read must not run the organization card checks")
|
||||
}
|
||||
|
||||
func TestNewServiceRequiresItsDependencies(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := NewService(Dependencies{AuthorizeCategories: noAuthorization}); !errors.Is(err, ErrServiceMissing) {
|
||||
t.Fatalf("NewService(without transactor) error = %v, want ErrServiceMissing", err)
|
||||
}
|
||||
if _, err := NewService(Dependencies{Transactor: evidenceTestTransactor{}}); !errors.Is(err, ErrServiceMissing) {
|
||||
t.Fatalf("NewService(without card checks) error = %v, want ErrServiceMissing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMineReadsOnlyForAVerifiedCandidate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
service, repository, candidate, unverified := newEvidenceTestService(t, noAuthorization)
|
||||
for name, test := range map[string]struct {
|
||||
query outbound.EvidenceListQuery
|
||||
want error
|
||||
}{
|
||||
"employer account": {outbound.EvidenceListQuery{CandidateID: uuid.New(), Limit: 20}, ErrForbidden},
|
||||
"unverified email": {outbound.EvidenceListQuery{CandidateID: unverified.ID, Limit: 20}, ErrForbidden},
|
||||
"no owner": {outbound.EvidenceListQuery{Limit: 20}, ErrForbidden},
|
||||
"limit below range": {outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: 0}, ErrInvalidRequest},
|
||||
"limit above range": {outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: outbound.MaxEvidencePageSize + 1}, ErrInvalidRequest},
|
||||
} {
|
||||
if _, err := service.ListMine(context.Background(), test.query); !errors.Is(err, test.want) {
|
||||
t.Errorf("%s: error = %v, want %v", name, err, test.want)
|
||||
}
|
||||
}
|
||||
if repository.listCalls != 0 {
|
||||
t.Fatalf("a refused read reached the repository %d times", repository.listCalls)
|
||||
}
|
||||
|
||||
if _, err := service.ListMine(context.Background(), outbound.EvidenceListQuery{CandidateID: candidate.ID, Limit: 20}); err != nil {
|
||||
t.Fatalf("ListMine(candidate) error = %v", err)
|
||||
}
|
||||
if repository.query.CandidateID != candidate.ID || repository.listCalls != 1 {
|
||||
t.Fatalf("repository query = %+v after %d calls, want the owner once", repository.query, repository.listCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListForOrganizationReadsOnlyWhatTheCardChecksName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
organizationID, actorID, candidateID := uuid.New(), uuid.New(), uuid.New()
|
||||
var authorized bool
|
||||
service, repository, _, _ := newEvidenceTestService(t, func(_ context.Context, _ outbound.UnitOfWork, actor, organization uuid.UUID, handle string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
authorized = actor == actorID && organization == organizationID && handle == "handle"
|
||||
return candidateID, []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}}, nil
|
||||
})
|
||||
if _, err := service.ListForOrganization(context.Background(), actorID, organizationID, "handle"); err != nil {
|
||||
t.Fatalf("ListForOrganization() error = %v", err)
|
||||
}
|
||||
if !authorized || repository.organizationID != organizationID || repository.candidateID != candidateID ||
|
||||
len(repository.categories) != 1 || repository.categories[0].Specialization != domain.SpecializationBackend ||
|
||||
repository.categories[0].Grade != domain.GradeIntern {
|
||||
t.Fatalf("read scope = organization %s candidate %s categories %v", repository.organizationID, repository.candidateID, repository.categories)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListForOrganizationStopsWhenTheCardChecksRefuse(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
refusal := errors.New("card checks refused")
|
||||
service, repository, _, _ := newEvidenceTestService(t, func(context.Context, outbound.UnitOfWork, uuid.UUID, uuid.UUID, string) (uuid.UUID, []domain.CandidateViewCategory, error) {
|
||||
return uuid.Nil, nil, refusal
|
||||
})
|
||||
if _, err := service.ListForOrganization(context.Background(), uuid.New(), uuid.New(), "handle"); !errors.Is(err, refusal) {
|
||||
t.Fatalf("ListForOrganization() error = %v, want the refusal of the card checks", err)
|
||||
}
|
||||
if repository.organizationHit != 0 {
|
||||
t.Fatal("facts were read after the card checks refused")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user