diff --git a/api/README.en.md b/api/README.en.md index ebeed5b..59a1508 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -534,7 +534,7 @@ The `consent` tag covers the consent ledger of the current account (PRD FR01, FR - Purposes (`ConsentPurposeCode`): `c1` personal data processing, `c2` publication of the candidate card, `c3` automatic categorization, `c4` transfer of selected contacts to one organization, `c5` import of FSP results. `ConsentPurpose` stays the subset whose text is public before registration (`c1`), so `GetConsentText` does not widen. - The subject comes from the session; no parameter names an account, so the response holds only the caller's own records. A page lists records newest grant first with cursor pagination; the optional `state` filter takes `active`, `superseded`, or `revoked`, and an unknown value answers 400 with the pointer `/state`. -- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history (TASK-088), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration. +- A `ConsentRecord` has the purpose, the accepted `text_version`, the `source` (`registration`, `consent_settings`, or `invitation_acceptance`), `granted_at`, the computed `state`, and `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A `c4` record also names the `organization` (`ConsentOrganization`, whose `name` is the snapshot the consent text showed, so a later rename does not change it), the contact `fields` (`ContactFieldKind`), the `invitation_id`, and the `invitation_terms_version`; they are null for every other purpose. A `c2` record proves the consent to the publication text; which fields were published, and when, is evidence of the publication history ([Candidate visibility](#candidate-visibility), TASK-088), and a field scope on `c2` records would be an additive change. The record never carries a contact value, the subject, or the text hash: the server stores the SHA-256 of exactly the text the subject saw, and the client never sends or receives it, as for C1 at registration. - The ledger is append-only. A newer text version of a purpose is a new record and the earlier one becomes `superseded` without any change; a revocation stamps the unrevoked records of the purpose, and for `c4` of one organization, once; a later grant is a new record, and a revoked `c4` of an invitation never comes back. Purposes are independent. - Planned, additive: granting C1, C2, C3, and C5 in the consent settings (TASK-063) and revoking any purpose with its consequences (TASK-064), as new operations of this tag; C1 at registration and C4 in `AcceptMyInvitation` already have their own operations. The C4 permission to pass data on to an ATS and the C4 of an application (PRD Q9) are planned as an additive flag and an additional `source` value. @@ -607,6 +607,72 @@ Planned, additive: member invitations, listing, role changes, and removal (TASK- No new problem code is added: the contract reuses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused`, and `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart`, and `TestOrganizationContractFollowsThePRD` pin the generated server and the bundle, and `frontend/src/shared/api/organization-contract.test.ts` pins the generated Zod rules and, at the type level, the absence of role, owner, member, and verification fields in the requests. +### Candidate visibility + +The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD, TASK-088). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). + +| Method and path | operationId | Protection | Success | Specific errors | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | session | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` | +| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | session and CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict`, 412 `version_conflict` | +| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | session | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 | +| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | session and CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 | +| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | session | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 | +| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | session and CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 | +| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | session and CSRF | 204 | 400, 401, 403 | +| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | session | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 | +| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | session | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 | + +Each operation also declares the problem response `default`. No new problem code is added: the contract uses `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict`, and `rate_limited`. An employer account answers 403 `forbidden` on all nine operations. + +Closed by default and three independent settings: + +- A profile is closed by default. A candidate who never published reads `publication.state` `closed`, `closed_reason` `never_published`, an empty field set, and version 0; saving the profile, filling in the questionnaire, or taking an assessment never publishes it. Every setting has its own `version` (0 is "never set"), its own operation, and its own `expected_version` in the body, so a change of one never makes another stale. +- The publication and C2 are separate. The consent C2 stays in the consent ledger (`ListMyConsents`) and proves that the candidate accepted the publication text. `Publication` records which fields are published and when, and refers to the C2 record behind them (`consent_id`, the `id` of a `ConsentRecord` of the same account). It does not duplicate the consent: `state` is `published` only while that record is unrevoked, so a revocation of C2 closes the card at once, and `closed_reason` says `consent_revoked`. A new C2 grant never reopens it: the candidate publishes again and the new publication binds to the new record. The body of `SetMyPublication` names no consent: the server binds the current unrevoked C2 record of the account, and without one answers 409 `state_conflict` (the candidate gives C2 first; the grant operation is planned in the consent settings, TASK-063). +- The search status is not a consent. `SearchStatus` and `SearchStatusUpdate` have no consent, publication, or organization property, no schema of one family reaches another (a test walks the references), and `SetMySearchStatus` changes nothing but the status. A candidate whose profile is closed who sets `looking` becomes visible to no one. +- Hidden organizations are records of the candidate (`HiddenOrganization`: the organization with its current name and `hidden_at`). One record per candidate and organization, at most 1000 per candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published. Hiding and lifting a hiding change neither C2, nor the publication, nor the search status. +- Hiding is a PUT of a state, so it is idempotent and takes no Idempotency-Key: hiding an organization again answers 200 with the original record and writes no history. Lifting is a DELETE that answers 204 whether the organization was hidden or not. + +The search status and its 30 days: + +- `looking` ("Ищу") stores `confirmed_at` and `lapses_at`. The interval is not a constant of the contract or the code: it is `search_status.searching_confirmation_interval_days` of the effective `product` policy version (30 in the demo version 1), read when the status is confirmed. The stored row names the policy version it used and fixes `lapses_at`, so a later policy change moves no stored time. The owner changes the interval by publishing a new policy version. +- After `lapses_at` the status holds as `not_looking` with `lapsed` true. The lapse is computed on every read and never written, so it needs no job and can only narrow: it never publishes, never unhides, and never changes C2 or the hidden organizations. The candidate confirms again with `SetMySearchStatus` and `looking`, which replaces `confirmed_at` and advances the version. A reminder before the lapse is a planned notification. +- A lapsed status is never "more public": the non-public `not_looking` is the only state a lapse reaches. Whether `looking` gates the appearance of a published card in search results is a search contract decision (TASK-185), not decided here. + +The anonymous card and the preview: + +- `CardField` is a closed set of groups of card values that the candidate chooses to publish: `categories` (the categories confirmed by assessment results), `stack`, `experience` (total months), `soft_skills`, `location`, and `relocation`. The full name, any contact, and the lowest salary have no value, so no request can publish them; contacts reach an organization only through the contact grant of an accepted invitation (C4), and the lowest salary never does. A self-assessed grade is not a category and is never published. The server stores and answers the set in ascending order of the codes. +- `AnonymousCardContent` is the card as an organization reads it: a closed object of the six properties above, each null when it is not published or has no value, so the card does not tell the two apart. It has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and no schema of the private profile, a contact, a consent, an invitation, or an organization is reachable from it (`TestAnonymousCardReachesNoProfileOrContactSchema` walks the references). `GetMyCardPreview` returns it with the published fields, or `card` null while the profile is closed, as a private read that creates no view and no history record. The card of an organization's search result (TASK-185) must reuse this content and cannot add a property that identifies the candidate. + +Versions and checks: + +- Both `PUT` operations of the settings follow the profile pattern: the complete new state in the body, `expected_version` in the body (the generated client cannot read the ETag yet), 412 `version_conflict` for a stale or non-existent version, and an unchanged body answers 200 with the current state even over a stale version, so no Idempotency-Key is needed. Order of checks: session (401), CSRF and Origin (403), request validation (400), account scenario (403), a version above the current one (412), an unchanged state (200), a stale version (412), then the C2 for a publication (409). A published state without a field and a closed state with a field answer 400 with the pointer `/fields`; the schema rejects an unknown or repeated card field and unknown properties such as a consent identifier or a confirmation time. `looking` always changes the stored confirmation, so it answers 412 for a stale version even as a repeat. The two 409 `state_conflict` answers are told apart by `errors`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. A closing over a stored publication whose C2 was revoked is a real change (it stores the closing, records `publication_closed`, and revokes the grants); the C2 revocation path (TASK-064) closes the stored publication and revokes the grants in its own transaction. Publishing, hiding, and the history need a verified email (a usecase requirement). `Problem.errors` is not only for `validation_failed`: a `state_conflict` carries one entry as a disambiguator (`consent_required`, `limit_reached`), so a future problem writer must not strip `errors` from non-validation responses. Only values that the candidate confirmed reach the card, a free text value that looks like a contact (email, phone, URL, Telegram link, @handle) is dropped, and adding a card field is a contract change and a migration. +- 404 and anti-enumeration. `HideOrganization` answers the same 404 `not_found`, with the same body and without a different timing, for an organization that does not exist and for one that the candidate cannot see, so it is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned). The identifiers are random, and the general rate limit can answer 429 with Retry-After before any check. `UnhideOrganization` reveals nothing: 204 for any well-formed identifier. A malformed `org_id` answers 400 with the pointer `/org_id`. +- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke that grant with the reason `visibility_closed`, in the same transaction as the change (planned together with the operations; the reason is fixed in the invitation contract). Lifting a hiding or publishing again never reopens a grant. The search status never revokes a grant. + +History: + +- `ListMyPrivacyHistory` returns the append-only history of the settings, newest first (the history stores only the organization identifier, and the current name is resolved when it is read): `publication_opened`, `publication_changed` (with the published fields and the `consent_id` behind them), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden`, and `organization_unhidden` (with the organization's current name). This is the evidence of the published field set and its changes with their times that the C2 record does not carry. A revocation of C2 and a lapse are computed and are not events; the consent history shows the revocation. The history holds no profile value. +- `ListMyCardAccessHistory` returns the accesses of organizations to the card: `card_viewed` and `contact_read`. A view by an organization that has no invitation relation with the candidate has `organization` null; a contact read always names the organization. The entries carry no query or ranking. Its storage comes with the search and contact-read tasks, so the operation is contract-only. + +Open questions for the product owner and the lawyer: + +- The search status values: the contract has `looking` and `not_looking`. Whether the PRD needs a third status such as "open to offers" is not decided; a value is an additive change. +- Whether `looking` gates the appearance of a published card in search (an organization sees only candidates who are searching) or is only a label. This decides the meaning of a lapse for visibility and belongs to the search contract (TASK-185). +- The set of card fields. The six values are a proposal that matches the profile; the PRD card (FR11) may add, split, or drop some, for example a generalized employer industry and size instead of employers, and each is an additive contract change. +- Whether publishing needs a minimum: at least one confirmed category, or a saved profile. The contract only requires one card field and an active C2. +- Whether narrowing the published fields, not only closing the publication or hiding an organization, must revoke the contact grants. The invitation contract says any visibility change after a grant revokes it; this contract revokes on closing and hiding only. +- How a candidate finds an organization to hide before any invitation. The contract hides by identifier and answers 404 for an organization the candidate cannot see, so hiding the current employer in advance needs an organization lookup for candidates (by name or domain), which must itself be safe against enumeration (a minimum query length, a rate limit, public data only). Without it, hiding works only for organizations that have written to the candidate. +- Whether the candidate should learn the name of an organization that viewed the card without an invitation (`CardAccess.organization`), and how long accesses are kept. +- The limit of hidden organizations (1000 now) and the retention of the settings and their history together with the consent evidence (152-FZ, PRD 7.3). The history references the account with `ON DELETE CASCADE`, guarded by two triggers: UPDATE is always refused, and DELETE (and the deletion of the account) is refused while the account is verified, the same condition as the consent ledger; the unverified account cleanup removes the history of an account it deletes, and the account deletion procedure extends the condition. +- Free text in the card (stack tags, soft skills, location) is guarded only by `CardTextLooksLikeContact`, which errs on the side of dropping (Socket.io is dropped, a bare obfuscation can still slip through); the residual risk is closed by TASK-089 with a closed taxonomy instead of free text. +- Whether C2 is a consent to the distribution of personal data under article 10.1 of 152-FZ and needs its own field scope (see Consents); the history keeps the fields and times in the meantime. +- Whether a new C2 text version requires the candidate to consent again for an existing publication. Now a publication stays effective while its C2 record is unrevoked, so a newer text version that the candidate has not accepted does not close it. +- Quasi-identifiers and k-anonymity of the card: a rare combination of location, stack, and experience can identify a candidate even without a name. The generalization of rare features and a minimum group size are acceptance criteria of TASK-089, which builds the card; the contract here only fixes the closed set of fields, the confirmed-values-only rule, and the dropping of free text that looks like a contact. +- Retention and the right to erasure for the settings history. The hide and unhide records are sensitive (they say which employer a candidate avoids). The history is kept like the consent evidence and is not deletable while the account is confirmed; whether a candidate can erase it, when, and how this meets the three-year consent retention (PRD 7.3) is an open legal question. The account deletion procedure extends the delete condition of the table. + +No new problem code is added. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation`, and `TestPrivacyAccessBeforeImplementation` pin the generated server and the bundle, and `frontend/src/shared/api/privacy-contract.test.ts` pins the generated Zod rules, the absence of a consent, a time, a contact, or a salary in the request and card types, and the absence of settings in the organization, invitation, need, profile, and consent files. + ### Generator checks `testdata/openapi-3.2.0.yml` contains test operations that use the components above: pagination, Idempotency-Key, If-Match, ETag, and problem responses. ogen does not resolve external references, so the fixture keeps copies of the api/core components; `scripts/test_contract_copies.py` (part of `make -C api check`) checks that they, the fixture responses, and the ML `Problem` copy match api/core. diff --git a/api/README.md b/api/README.md index 5e1aca5..aea1d35 100644 --- a/api/README.md +++ b/api/README.md @@ -534,7 +534,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Цели (`ConsentPurposeCode`): `c1` - обработка персональных данных, `c2` - публикация карточки кандидата, `c3` - автоматическая категоризация, `c4` - передача выбранных контактов одной организации, `c5` - импорт результатов ФСП. `ConsentPurpose` остается подмножеством, текст которого доступен до регистрации (`c1`), поэтому `GetConsentText` не расширяется. - Субъект берется из сессии; ни один параметр не называет аккаунт, поэтому ответ содержит только собственные записи вызывающего. Страница перечисляет записи от новой выдачи к старой с курсорной пагинацией; необязательный фильтр `state` принимает `active`, `superseded` или `revoked`, а неизвестное значение отвечает 400 с указателем `/state`. -- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации (TASK-088), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. +- `ConsentRecord` содержит цель, принятую `text_version`, `source` (`registration`, `consent_settings` или `invitation_acceptance`), `granted_at`, вычисленное `state`, а также `revoked_at` и `revocation_source` (`consent_settings` или `support_request`). Запись `c4` дополнительно называет `organization` (`ConsentOrganization`, где `name` - снимок названия из текста согласия, поэтому последующее переименование его не меняет), поля контакта `fields` (`ContactFieldKind`), `invitation_id` и `invitation_terms_version`; для остальных целей они равны null. Запись `c2` доказывает согласие с текстом публикации; какие поля и когда опубликованы - доказательства истории публикации ([Видимость кандидата](#видимость-кандидата), TASK-088), а scope полей в записях `c2` был бы аддитивным изменением. Запись никогда не содержит значения контакта, субъекта или хэш текста: сервер хранит SHA-256 ровно того текста, который видел субъект, а клиент его не отправляет и не получает, как и для C1 при регистрации. - Журнал только дополняется. Новая версия текста цели - новая запись, а прежняя становится `superseded` без изменений; отзыв один раз ставит отметку на неотозванные записи цели, а для `c4` - одной организации; последующая выдача - новая запись, и отозванное `c4` приглашения не возвращается. Цели независимы. - Запланировано, аддитивно: выдача C1, C2, C3 и C5 в настройках согласий (TASK-063) и отзыв любой цели с последствиями (TASK-064) новыми операциями этого тега; у C1 при регистрации и C4 в `AcceptMyInvitation` уже есть свои операции. Разрешение C4 на передачу данных в ATS и C4 при отклике (Q9 в PRD) запланированы как аддитивный флаг и дополнительное значение `source`. @@ -607,6 +607,72 @@ ML-сервис отвечает на ошибки той же схемой `Pro Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `version_conflict`, `idempotency_in_progress`, `idempotency_key_reused` и `rate_limited`. `TestOrganizationSchemaValidationPrecedesImplementation`, `TestOrganizationAccessBeforeImplementation`, `TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests`, `TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart` и `TestOrganizationContractFollowsThePRD` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/organization-contract.test.ts` - сгенерированные правила Zod и, на уровне типов, отсутствие полей роли, владельца, участников и уровня проверки в запросах. +### Видимость кандидата + +Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD, TASK-088). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). + +| Метод и путь | operationId | Защита | Успех | Конкретные ошибки | +| --- | --- | --- | --- | --- | +| `GET /api/v1/me/privacy` | `GetMyPrivacySettings` | сессия | 200 `PrivacySettings`, `Cache-Control: no-store` | 401, 403 `forbidden` | +| `PUT /api/v1/me/privacy/publication` | `SetMyPublication` | сессия и CSRF | 200 `Publication`, `Cache-Control: no-store` | 400, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict`, 412 `version_conflict` | +| `GET /api/v1/me/privacy/preview` | `GetMyCardPreview` | сессия | 200 `CardPreview`, `Cache-Control: no-store` | 401, 403 | +| `PUT /api/v1/me/privacy/search-status` | `SetMySearchStatus` | сессия и CSRF | 200 `SearchStatus`, `Cache-Control: no-store` | 400, 401, 403, 412 | +| `GET /api/v1/me/privacy/hidden-organizations` | `ListMyHiddenOrganizations` | сессия | 200 `HiddenOrganizationList`, `Cache-Control: no-store` | 400, 401, 403 | +| `PUT /api/v1/me/privacy/hidden-organizations/{org_id}` | `HideOrganization` | сессия и CSRF | 200 `HiddenOrganization`, `Cache-Control: no-store` | 400, 401, 403, 404 `not_found`, 409 `state_conflict`, 429 | +| `DELETE /api/v1/me/privacy/hidden-organizations/{org_id}` | `UnhideOrganization` | сессия и CSRF | 204 | 400, 401, 403 | +| `GET /api/v1/me/privacy/history` | `ListMyPrivacyHistory` | сессия | 200 `PrivacyEventList`, `Cache-Control: no-store` | 400, 401, 403 | +| `GET /api/v1/me/privacy/access-history` | `ListMyCardAccessHistory` | сессия | 200 `CardAccessList`, `Cache-Control: no-store` | 400, 401, 403 | + +Каждая операция также объявляет problem-ответ `default`. Новый код problem не добавляется: контракт использует `validation_failed`, `unauthenticated`, `forbidden`, `csrf_check_failed`, `not_found`, `state_conflict`, `version_conflict` и `rate_limited`. Аккаунт работодателя получает 403 `forbidden` на всех девяти операциях. + +Закрыто по умолчанию и три независимые настройки: + +- Профиль закрыт по умолчанию. Кандидат, который никогда не публиковал, читает `publication.state` `closed`, `closed_reason` `never_published`, пустой набор полей и версию 0; сохранение профиля, заполнение анкеты и оценка его не публикуют. У каждой настройки своя `version` (0 - "никогда не задавалась"), своя операция и свой `expected_version` в теле, поэтому изменение одной никогда не делает устаревшей другую. +- Публикация и C2 разделены. Согласие C2 остается в журнале согласий (`ListMyConsents`) и доказывает, что кандидат принял текст публикации. `Publication` хранит, какие поля опубликованы и когда, и ссылается на запись C2 за ними (`consent_id` - `id` записи `ConsentRecord` того же аккаунта). Она не дублирует согласие: `state` равен `published`, только пока эта запись не отозвана, поэтому отзыв C2 закрывает карточку сразу, а `closed_reason` показывает `consent_revoked`. Новая выдача C2 карточку не открывает: кандидат публикует заново, и новая публикация привязывается к новой записи. Тело `SetMyPublication` не называет согласие: сервер привязывает текущую неотозванную запись C2 аккаунта, а без нее отвечает 409 `state_conflict` (кандидат сначала дает C2; операция выдачи запланирована в настройках согласий, TASK-063). +- Статус поиска - не согласие. В `SearchStatus` и `SearchStatusUpdate` нет свойств согласия, публикации или организации, схемы одного семейства не достигают другого (тест обходит ссылки), а `SetMySearchStatus` не меняет ничего, кроме статуса. Кандидат с закрытым профилем, который задал `looking`, не становится видимым никому. +- Скрытые организации - записи кандидата (`HiddenOrganization`: организация с ее текущим названием и `hidden_at`). Одна запись на кандидата и организацию, не более 1000 на кандидата. Организация их не читает, не узнает, что скрыта, и видит скрывшего кандидата так же, как неопубликованного. Скрытие и его снятие не меняют ни C2, ни публикацию, ни статус поиска. +- Скрытие - это PUT состояния, поэтому оно идемпотентно и не требует Idempotency-Key: повторное скрытие отвечает 200 с исходной записью и не пишет историю. Снятие - DELETE, который отвечает 204, была организация скрыта или нет. + +Статус поиска и его 30 дней: + +- `looking` ("Ищу") хранит `confirmed_at` и `lapses_at`. Срок - не константа контракта или кода: это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (в демо-версии 1 - 30), прочитанное при подтверждении статуса. Строка называет версию политики, которой воспользовалась, и фиксирует `lapses_at`, поэтому последующее изменение политики не сдвигает сохраненные времена. Владелец меняет срок публикацией новой версии политики. +- После `lapses_at` статус действует как `not_looking` с `lapsed` true. Истечение вычисляется при каждом чтении и нигде не записывается, поэтому не требует задачи и может только сужать: оно никогда не публикует, не снимает скрытие и не меняет C2 или скрытые организации. Кандидат подтверждает снова через `SetMySearchStatus` со значением `looking`, которое заменяет `confirmed_at` и увеличивает версию. Напоминание до истечения - запланированное уведомление. +- Истекший статус никогда не становится "более публичным": единственное состояние, до которого доходит истечение, - непубличное `not_looking`. Влияет ли `looking` на появление опубликованной карточки в выдаче поиска - решение контракта поиска (TASK-185), здесь не принято. + +Анонимная карточка и предпросмотр: + +- `CardField` - закрытый набор групп значений карточки, которые кандидат выбирает публиковать: `categories` (категории, подтвержденные результатами оценки), `stack`, `experience` (суммарно в месяцах), `soft_skills`, `location` и `relocation`. У полного имени, любого контакта и минимальной зарплаты значения нет, поэтому ни один запрос не может их опубликовать; контакты доходят до организации только через контактное разрешение принятого приглашения (C4), а минимальная зарплата не доходит никогда. Самооценка грейда не категория и никогда не публикуется. Сервер хранит и отдает набор в порядке возрастания кодов. +- `AnonymousCardContent` - карточка так, как ее читает организация: закрытый объект из шести свойств выше, каждое равно null, если не опубликовано или значения нет, поэтому карточка не различает эти случаи. В ней нет имени, email, телефона, имени в Telegram, работодателя, суммы зарплаты, идентификатора аккаунта или профиля, и из нее недостижима ни одна схема приватного профиля, контакта, согласия, приглашения или организации (`TestAnonymousCardReachesNoProfileOrContactSchema` обходит ссылки). `GetMyCardPreview` возвращает ее с опубликованными полями или `card` null, пока профиль закрыт, как приватное чтение, которое не создает просмотра и записи в истории. Карточка результата поиска организации (TASK-185) должна использовать это содержимое и не вправе добавлять свойство, идентифицирующее кандидата. + +Версии и проверки: + +- Обе операции `PUT` настроек следуют образцу профиля: полное новое состояние в теле, `expected_version` в теле (сгенерированный клиент пока не читает ETag), 412 `version_conflict` для устаревшей или несуществующей версии, а тело без изменений отвечает 200 с текущим состоянием даже при устаревшей версии, поэтому Idempotency-Key не нужен. Порядок проверок: сессия (401), CSRF и Origin (403), валидация запроса (400), сценарий аккаунта (403), версия выше текущей (412), неизмененное состояние (200), устаревшая версия (412), затем C2 для публикации (409). Состояние `published` без поля и `closed` с полем отвечают 400 с указателем `/fields`; схема отклоняет неизвестное или повторное поле карточки и неизвестные свойства, например идентификатор согласия или время подтверждения. `looking` всегда меняет сохраненное подтверждение, поэтому при устаревшей версии отвечает 412 даже как повтор. Два вида 409 `state_conflict` различаются через `errors`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Закрытие поверх сохраненной публикации с отозванной C2 - настоящее изменение (сохраняет закрытие, пишет `publication_closed` и отзывает разрешения); путь отзыва C2 (TASK-064) сам закрывает сохраненную публикацию и отзывает разрешения в своей транзакции. Публикации, скрытию и истории нужен подтвержденный email (требование юзкейса). `Problem.errors` не только для `validation_failed`: `state_conflict` несет одну запись как уточнение (`consent_required`, `limit_reached`), поэтому будущий писатель problem не должен вырезать `errors` из ответов, не связанных с валидацией. В карточку попадают только подтвержденные значения, свободный текст, похожий на контакт (email, телефон, URL, ссылка Telegram, @handle), отбрасывается, а новое поле карточки - это изменение контракта и миграция. +- 404 и защита от перебора. `HideOrganization` отвечает одинаковым 404 `not_found`, с тем же телом и без другого времени ответа, и для несуществующей организации, и для той, которую кандидат не видит, поэтому операция не позволяет спросить, принадлежит ли идентификатор организации. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован). Идентификаторы случайные, а общий лимит запросов может ответить 429 с Retry-After до любой проверки. `UnhideOrganization` ничего не раскрывает: 204 на любой корректный идентификатор. Некорректный `org_id` отвечает 400 с указателем `/org_id`. +- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (запланировано вместе с операциями; причину задает контракт приглашений). Снятие скрытия и повторная публикация разрешение не возвращают. Статус поиска разрешение никогда не отзывает. + +История: + +- `ListMyPrivacyHistory` возвращает журнал изменений настроек только для добавления, от новых к старым (история хранит только идентификатор организации, а текущее название определяется при чтении): `publication_opened`, `publication_changed` (с опубликованными полями и `consent_id` за ними), `publication_closed`, `search_status_confirmed`, `search_status_cleared`, `organization_hidden` и `organization_unhidden` (с текущим названием организации). Это доказательство набора опубликованных полей и его изменений со временем, которого нет в записи C2. Отзыв C2 и истечение статуса вычисляются и событиями не являются; отзыв показывает история согласий. Значений профиля в истории нет. +- `ListMyCardAccessHistory` возвращает обращения организаций к карточке: `card_viewed` и `contact_read`. У просмотра организацией, не связанной с кандидатом приглашением, `organization` равно null; чтение контактов всегда называет организацию. Записи не несут запроса или ранга. Хранение для них придет с задачами поиска и чтения контактов, поэтому операция только в контракте. + +Открытые вопросы к владельцу продукта и юристу: + +- Значения статуса поиска: в контракте `looking` и `not_looking`. Нужен ли по PRD третий статус, например "открыт к предложениям", не решено; значение - аддитивное изменение. +- Влияет ли `looking` на появление опубликованной карточки в поиске (организация видит только ищущих) или это только метка. Это определяет смысл истечения для видимости и относится к контракту поиска (TASK-185). +- Набор полей карточки. Шесть значений - предложение, согласованное с профилем; карточка в PRD (FR11) может добавить, разделить или убрать часть, например обобщенную отрасль и размер работодателя вместо работодателей, и каждое изменение аддитивно для контракта. +- Нужен ли для публикации минимум: хотя бы одна подтвержденная категория или сохраненный профиль. Контракт требует только одно поле карточки и действующую C2. +- Должно ли сужение опубликованных полей, а не только закрытие публикации или скрытие организации, отзывать контактные разрешения. Контракт приглашений говорит, что любое изменение видимости после разрешения его отзывает; этот контракт отзывает только при закрытии и скрытии. +- Как кандидат находит организацию, чтобы скрыть ее до любого приглашения. Контракт скрывает по идентификатору и отвечает 404 на организацию, которую кандидат не видит, поэтому заранее скрыть текущего работодателя можно только при поиске организаций для кандидата (по названию или домену), который сам должен быть защищен от перебора (минимальная длина запроса, лимит, только публичные данные). Без него скрытие работает только для организаций, которые уже написали кандидату. +- Должен ли кандидат узнавать название организации, которая смотрела карточку без приглашения (`CardAccess.organization`), и сколько хранятся обращения. +- Предел скрытых организаций (сейчас 1000) и срок хранения настроек и их истории вместе с доказательствами согласий (152-ФЗ, PRD 7.3). История ссылается на аккаунт с `ON DELETE CASCADE` под защитой двух триггеров: UPDATE запрещен всегда, а DELETE (и удаление аккаунта) запрещен, пока аккаунт подтвержден, как у журнала согласий; очистка неподтвержденных аккаунтов удаляет историю удаляемого аккаунта, а процедура удаления аккаунта расширит условие. +- Свободный текст в карточке (теги стека, софт-скиллы, место) защищает только `CardTextLooksLikeContact`, который ошибается в сторону отбрасывания (Socket.io отбрасывается, а простая обфускация все же может пройти); остаточный риск закрывает TASK-089 закрытой таксономией вместо свободного текста. +- Является ли C2 согласием на распространение персональных данных по статье 10.1 152-ФЗ и нужна ли ей собственная область полей (см. Согласия); пока поля и времена хранит история. +- Требует ли новая версия текста C2 повторного согласия кандидата для уже существующей публикации. Сейчас публикация действует, пока ее запись C2 не отозвана, поэтому более новая версия текста, которую кандидат не принимал, ее не закрывает. +- Квазиидентификаторы и k-анонимность карточки: редкое сочетание места, стека и опыта может идентифицировать кандидата и без имени. Обобщение редких признаков и минимальный размер группы - критерии приемки TASK-089, который строит карточку; здесь контракт фиксирует только закрытый набор полей, правило "только подтвержденные значения" и отбрасывание свободного текста, похожего на контакт. +- Хранение и право на удаление истории настроек. Записи о скрытии и снятии скрытия чувствительны (они говорят, каких работодателей кандидат избегает). История хранится как доказательства согласий и не удаляется, пока аккаунт подтвержден; может ли кандидат стереть ее, когда и как это согласуется с трехлетним хранением согласий (PRD 7.3) - открытый юридический вопрос. Процедура удаления аккаунта расширит условие удаления таблицы. + +Новый код problem не добавляется. `TestPrivacyOperationsFollowTheConventions`, `TestPublicationAndSearchStatusAreNotConsents`, `TestAnonymousCardReachesNoProfileOrContactSchema`, `TestGeneratedPrivacyDTOsCarryNoServerOwnedFields`, `TestPrivacySchemaValidationPrecedesImplementation` и `TestPrivacyAccessBeforeImplementation` закрепляют сгенерированный сервер и бандл, а `frontend/src/shared/api/privacy-contract.test.ts` - сгенерированные правила Zod, отсутствие согласия, времени, контакта и зарплаты в типах запросов и карточки и отсутствие настроек в файлах организации, приглашения, потребности, профиля и согласий. + ### Проверки генераторов `testdata/openapi-3.2.0.yml` содержит тестовые операции с перечисленными компонентами: пагинацией, Idempotency-Key, If-Match, ETag и problem-ответами. ogen не разрешает внешние ссылки, поэтому фикстура хранит копии компонентов api/core; `scripts/test_contract_copies.py` (входит в `make -C api check`) проверяет, что они, ответы фикстуры и ML-копия `Problem` совпадают с api/core. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index aade093..2195b60 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -4056,3 +4056,230 @@ ProfileStaleVersion: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 9a0b1c2d-3e4f-4a5b-9c7d-8e9f0a1b2c34 +PrivacyPublishedWithoutFields: + summary: A publication without any field + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 3b4c5d6e-7f80-4a91-8b2c-3d4e5f6a7b8c + errors: + - in: body + pointer: /fields + code: invalid + message: A published profile needs at least one field, and a closed one none. +NewCandidatePrivacySettings: + summary: A new candidate with the profile closed + description: Nothing was ever published, announced, or hidden. Every version is 0. + value: + publication: + state: closed + closed_reason: never_published + fields: [] + consent_id: null + published_at: null + version: 0 + search_status: + value: not_looking + lapsed: false + confirmed_at: null + lapses_at: null + version: 0 + hidden_organizations_total: 0 +PublishedCandidatePrivacySettings: + summary: A published profile with a confirmed search status + value: + publication: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: "2026-10-06T09:10:00Z" + version: 1 + search_status: + value: looking + lapsed: false + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 + hidden_organizations_total: 1 +PublicationUpdatePublish: + summary: Publish the confirmed categories and the stack + value: + expected_version: 0 + state: published + fields: + - categories + - stack +PublicationUpdateClose: + summary: Close the publication + value: + expected_version: 1 + state: closed + fields: [] +PublishedPublication: + summary: The publication after the first publish + value: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: "2026-10-06T09:10:00Z" + version: 1 +SearchStatusUpdateLooking: + summary: Set or confirm the status looking + value: + expected_version: 0 + value: looking +LookingSearchStatus: + summary: A confirmed status that lapses after the policy interval + value: + value: looking + lapsed: false + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 +LapsedSearchStatus: + summary: A status that was not confirmed in time + description: The candidate set looking and did not confirm it again, so it holds as not_looking. Nothing else changed; the publication and the hidden organizations are as they were. + value: + value: not_looking + lapsed: true + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 +HiddenOrganizationRecord: + summary: An organization that the candidate hides the profile from + value: + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: "2026-10-06T09:20:00Z" +HiddenOrganizationListPage: + summary: One hidden organization + value: + items: + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: "2026-10-06T09:20:00Z" + page: + has_more: false + next_cursor: null +PublishedCardPreview: + summary: The card of a published profile with two fields + description: The fields that are not published are null. The card carries no name and no contact. + value: + state: published + fields: + - categories + - stack + card: + categories: + - specialization: backend + grade: middle + stack: + - PostgreSQL + - Kafka + experience_months: null + soft_skills: null + location: null + relocation: null + generated_at: "2026-10-06T09:30:00Z" +ClosedCardPreview: + summary: The preview of a closed profile + value: + state: closed + fields: [] + card: null + generated_at: "2026-10-06T09:30:00Z" +PrivacyEventListPage: + summary: A publication, a hiding, and a confirmed status + value: + items: + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9f01 + kind: organization_hidden + occurred_at: "2026-10-06T09:20:00Z" + fields: null + consent_id: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e02 + kind: search_status_confirmed + occurred_at: "2026-10-06T09:12:00Z" + fields: null + consent_id: null + organization: null + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e01 + kind: publication_opened + occurred_at: "2026-10-06T09:10:00Z" + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + organization: null + page: + has_more: false + next_cursor: null +CardAccessListPage: + summary: An anonymous view and a contact read + value: + items: + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a02 + kind: contact_read + occurred_at: "2026-10-07T08:00:00Z" + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a01 + kind: card_viewed + occurred_at: "2026-10-06T12:00:00Z" + organization: null + page: + has_more: false + next_cursor: null +PrivacyStaleVersion: + summary: The change carried a stale expected_version + description: The setting changed, for example in another tab, after the client read it. Nothing was changed; the client reads the settings again and reapplies its edit. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 4c5d6e7f-8091-4ba2-9c3d-4e5f6a7b8c9d +PublicationConsentRequiredConflict: + summary: Publishing without an active C2 consent + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5d6e7f80-91a2-4cb3-8d4e-5f6a7b8c9d0e + errors: + - in: body + pointer: /state + code: consent_required + message: Publishing needs an active C2 consent of the account. +HiddenOrganizationLimitReached: + summary: The candidate hides the maximum number of organizations + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6e7f8091-a2b3-4dc4-9e5f-6a7b8c9d0e1f + errors: + - in: path + pointer: /org_id + code: limit_reached + message: The candidate already hides the maximum number of organizations. diff --git a/api/core/components/parameters.yml b/api/core/components/parameters.yml index ff4e6ce..d4550f1 100644 --- a/api/core/components/parameters.yml +++ b/api/core/components/parameters.yml @@ -129,3 +129,19 @@ MyInvitationId: type: string format: uuid example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f +HiddenOrganizationId: + name: org_id + in: path + required: true + description: >- + Identifier of the organization that the current candidate hides or stops + hiding the profile from. It names the target of a candidate's own + setting and grants the candidate nothing about the organization. Hiding + answers the same 404 not_found for an organization that does not exist + and for one that the candidate cannot see, so organizations cannot be + enumerated; lifting the hiding answers 204 for any well-formed + identifier. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 27c4a97..b623e36 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -624,3 +624,55 @@ ProfileVersionConflict: examples: version_conflict: $ref: ./examples.yml#/ProfileStaleVersion +PrivacyValidationFailed: + description: >- + The body does not match the contract or breaks a visibility rule: an + unknown field, a repeated or unknown card field, a published state with + no field, a closed state with a field, a search status other than + looking and not_looking, or a missing or invalid expected_version; code + validation_failed with body pointers. Nothing was changed. The problem + never repeats a submitted value. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + published_without_fields: + $ref: ./examples.yml#/PrivacyPublishedWithoutFields +PrivacyVersionConflict: + description: >- + `expected_version` is not the current version of the setting; code + version_conflict. Nothing was changed; read the settings again before + retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/PrivacyStaleVersion +PublicationConsentRequired: + description: >- + The profile cannot be published because the account has no active, + unrevoked C2 consent; code state_conflict. Nothing was changed. The + candidate gives C2 in the consent settings first. `errors` holds the entry + `{in: body, pointer: /state, code: consent_required}`. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/PublicationConsentRequiredConflict +HiddenOrganizationLimit: + description: >- + The candidate already hides the maximum number of organizations (1000); + code state_conflict with the entry `{in: path, pointer: /org_id, code: + limit_reached}` in `errors`. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + limit_reached: + $ref: ./examples.yml#/HiddenOrganizationLimitReached diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index e92092b..3084456 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -4874,6 +4874,469 @@ MyOrganizationList: $ref: '#/MyOrganization' page: $ref: '#/PageInfo' +PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale. + examples: + - 2 +SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`. + examples: + - 3 +CardField: + type: string + description: 'A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + + - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. + + - stack: the technology tags of the profile. + + - experience: the total months of work experience, without employers, periods, or descriptions. + + - soft_skills: the soft skills of the profile. + + - location: the city or region of the profile. + + - relocation: whether the candidate is ready to relocate. + + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.' + enum: + - categories + - stack + - experience + - soft_skills + - location + - relocation +CardFieldSet: + type: array + minItems: 0 + maxItems: 6 + uniqueItems: true + description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. + items: + $ref: '#/CardField' +PublicationState: + type: string + description: 'Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.' + enum: + - closed + - published +PublicationClosedReason: + type: string + description: 'Why a closed profile is closed, shown only to the candidate. + + + - never_published: the candidate has never published the profile. + + - closed_by_candidate: the candidate closed the publication. + + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.' + enum: + - never_published + - closed_by_candidate + - consent_revoked +Publication: + type: object + description: 'Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.' + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: '#/PublicationState' + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: '#/PublicationClosedReason' + - type: 'null' + fields: + description: Card fields that organizations may read. Empty exactly when `state` is `closed`. + allOf: + - $ref: '#/CardFieldSet' + consent_id: + description: Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: 'null' + published_at: + description: Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + version: + $ref: '#/PublicationVersion' +PublicationUpdate: + type: object + description: 'The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account''s current unrevoked C2 record, and a client can neither supply nor forge one.' + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: '#/PublicationVersion' + state: + $ref: '#/PublicationState' + fields: + $ref: '#/CardFieldSet' +SearchStatusValue: + type: string + description: 'Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.' + enum: + - looking + - not_looking +SearchStatus: + type: object + description: 'Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.' + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: 'The status that holds now: `looking` only while the confirmation has not lapsed.' + allOf: + - $ref: '#/SearchStatusValue' + lapsed: + type: boolean + description: True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared. + confirmed_at: + description: Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + lapses_at: + description: Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + version: + $ref: '#/SearchStatusVersion' +SearchStatusUpdate: + type: object + description: 'The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.' + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: '#/SearchStatusVersion' + value: + $ref: '#/SearchStatusValue' +PrivacyOrganization: + type: object + description: Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Current name of the organization. Plain text; clients show it as text, never as HTML. +HiddenOrganization: + type: object + description: 'One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.' + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: '#/PrivacyOrganization' + hidden_at: + $ref: '#/Timestamp' +HiddenOrganizationList: + type: object + description: One page of the organizations that the candidate hides the profile from, newest first with the organization identifier as the tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: '#/HiddenOrganization' + page: + $ref: '#/PageInfo' +PrivacySettings: + type: object + description: 'The visibility settings of the current candidate in one read: the publication, the search status, and the number of hidden organizations. The three are independent: each has its own version and its own operation, and a change of one leaves the others as they were. A new account reads a closed profile, `not_looking`, and no hidden organization.' + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: '#/Publication' + search_status: + $ref: '#/SearchStatus' + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. +CardCategory: + type: object + description: A category confirmed by assessment results, as the card shows it. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' +AnonymousCardContent: + type: object + description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search + result are defined by the search contract (TASK-185), which reuses this content. + additionalProperties: false + required: + - categories + - stack + - experience_months + - soft_skills + - location + - relocation + properties: + categories: + type: + - array + - 'null' + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: '#/CardCategory' + stack: + type: + - array + - 'null' + maxItems: 30 + description: Technology tags of the candidate, or null. + items: + $ref: '#/StackTag' + experience_months: + type: + - integer + - 'null' + minimum: 0 + maximum: 1200 + description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null. + soft_skills: + type: + - array + - 'null' + maxItems: 10 + description: Soft skills of the candidate, or null. + items: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: Plain text; clients show it as text, never as HTML. + location: + type: + - string + - 'null' + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML. + relocation: + type: + - boolean + - 'null' + description: Whether the candidate is ready to relocate, or null. +CardPreview: + type: object + description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.' + additionalProperties: false + required: + - state + - fields + - card + - generated_at + properties: + state: + $ref: '#/PublicationState' + fields: + $ref: '#/CardFieldSet' + card: + oneOf: + - $ref: '#/AnonymousCardContent' + - type: 'null' + generated_at: + $ref: '#/Timestamp' +PrivacyEventKind: + type: string + description: 'Kind of a change of the visibility settings that the history records. + + + - publication_opened: the candidate published a closed profile. + + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + + - search_status_confirmed: the candidate set or confirmed `looking`. + + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + + - organization_hidden: the candidate hid the profile from an organization. + + - organization_unhidden: the candidate lifted the hiding for an organization.' + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden +PrivacyEvent: + type: object + description: One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller's own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: '#/PrivacyEventKind' + occurred_at: + $ref: '#/Timestamp' + fields: + description: Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind. + oneOf: + - $ref: '#/CardFieldSet' + - type: 'null' + consent_id: + description: C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: 'null' + organization: + description: Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null. + oneOf: + - $ref: '#/PrivacyOrganization' + - type: 'null' +PrivacyEventList: + type: object + description: One page of the settings history of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: '#/PrivacyEvent' + page: + $ref: '#/PageInfo' +CardAccessKind: + type: string + description: 'How an organization reached the candidate. + + + - card_viewed: an organization read the anonymous card in a search result. + + - contact_read: an organization read the contacts through the contact grant of an accepted invitation.' + enum: + - card_viewed + - contact_read +CardAccess: + type: object + description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: '#/CardAccessKind' + occurred_at: + $ref: '#/Timestamp' + organization: + oneOf: + - $ref: '#/PrivacyOrganization' + - type: 'null' +CardAccessList: + type: object + description: One page of the accesses to the card of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: '#/CardAccess' + page: + $ref: '#/PageInfo' Problem: type: object description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. @@ -4920,7 +5383,7 @@ Problem: errors: type: array maxItems: 100 - description: Field-level reasons for validation_failed. Other codes omit it. + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. items: $ref: '#/ProblemFieldError' ProblemCode: @@ -5010,7 +5473,7 @@ ProblemFieldError: minLength: 1 maxLength: 64 pattern: ^[a-z][a-z0-9_]*$ - description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. message: type: string minLength: 1 diff --git a/api/core/components/schemas/privacy_schemas.yml b/api/core/components/schemas/privacy_schemas.yml new file mode 100644 index 0000000..e6f6fb3 --- /dev/null +++ b/api/core/components/schemas/privacy_schemas.yml @@ -0,0 +1,574 @@ +schemas: + PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the publication setting of the candidate. A candidate who + has never published has version 0 and the profile is closed; every + change that alters the setting advances it by one. The client sends + the version it read as `expected_version`. It is independent of the + versions of the profile and of the search status, so a change of one + never makes another stale. + examples: + - 2 + SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the search status of the candidate. A candidate who never + set the status has version 0 and the status `not_looking`; every + confirmation or change advances it by one. The client sends the + version it read as `expected_version`. + examples: + - 3 + CardField: + type: string + description: |- + A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. + - stack: the technology tags of the profile. + - experience: the total months of work experience, without employers, periods, or descriptions. + - soft_skills: the soft skills of the profile. + - location: the city or region of the profile. + - relocation: whether the candidate is ready to relocate. + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. + enum: + - categories + - stack + - experience + - soft_skills + - location + - relocation + CardFieldSet: + type: array + minItems: 0 + maxItems: 6 + uniqueItems: true + description: >- + Distinct card fields. The server stores them in ascending order of + the codes and answers them in that order, whatever order the client + sent, so equal sets are equal arrays. + items: + $ref: "#/schemas/CardField" + PublicationState: + type: string + description: |- + Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid. + enum: + - closed + - published + PublicationClosedReason: + type: string + description: |- + Why a closed profile is closed, shown only to the candidate. + + - never_published: the candidate has never published the profile. + - closed_by_candidate: the candidate closed the publication. + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record. + enum: + - never_published + - closed_by_candidate + - consent_revoked + Publication: + type: object + description: >- + Publication setting of the candidate card. It is separate from the + consent: the C2 consent in the ledger proves that the candidate + accepted the publication text, and this setting records whether and + which fields are published. `state` is `published` only while the + referenced C2 record is unrevoked, whatever the stored setting says, + so a revocation closes the card at once. The state, the fields, and + the times belong to the history that the C2 consent record does not + carry. + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: "#/schemas/PublicationState" + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: "#/schemas/PublicationClosedReason" + - type: "null" + fields: + description: >- + Card fields that organizations may read. Empty exactly when `state` + is `closed`. + allOf: + - $ref: "#/schemas/CardFieldSet" + consent_id: + description: >- + Identifier of the C2 record of the consent ledger that backs the + current or the last publication, the `id` of a `ConsentRecord` of + this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: "null" + published_at: + description: >- + Moment of the latest change that published or republished the + card, or null while the profile was never published. It stays + after a closing, as the time of the last publication. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + version: + $ref: "#/schemas/PublicationVersion" + PublicationUpdate: + type: object + description: >- + The complete new publication setting. `published` needs a non-empty + set of fields and an active C2 consent of the account; `closed` needs + an empty set and never fails for a missing consent. The body names no + consent: the server binds the publication to the account's current + unrevoked C2 record, and a client can neither supply nor forge one. + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: "#/schemas/PublicationVersion" + state: + $ref: "#/schemas/PublicationState" + fields: + $ref: "#/schemas/CardFieldSet" + SearchStatusValue: + type: string + description: |- + Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls. + enum: + - looking + - not_looking + SearchStatus: + type: object + description: >- + Search status of the candidate as it holds now. The status `looking` + stores the moment of its confirmation and lapses when the + confirmation interval of the product policy passes without a new + confirmation. A lapse only ever narrows: the status falls to + `not_looking`, which is the non-public state, and a lapse never + changes the publication or the hidden organizations. It needs no + stored change, so no process can make a candidate more visible by + expiry, and a lapsed candidate confirms again explicitly. + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: >- + The status that holds now: `looking` only while the confirmation + has not lapsed. + allOf: + - $ref: "#/schemas/SearchStatusValue" + lapsed: + type: boolean + description: >- + True when the candidate set `looking`, did not confirm it again, + and the interval ended, so `value` is `not_looking`. False + otherwise, including a status the candidate cleared. + confirmed_at: + description: >- + Moment of the latest confirmation of `looking`, or null when the + candidate never set it or cleared it. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + lapses_at: + description: >- + Moment at which the confirmed status lapses, fixed when it was + confirmed from the `search_status` section of the product policy + version in force then, or null when `confirmed_at` is null. A + later policy change does not move it; it stays in the past for a + lapsed status. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + version: + $ref: "#/schemas/SearchStatusVersion" + SearchStatusUpdate: + type: object + description: >- + The complete new search status. `looking` is also the confirmation of + a status that still holds or has lapsed: it sets the confirmation time + to now. The body carries no time, interval, or policy version; the + server takes them from the effective product policy. + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: "#/schemas/SearchStatusVersion" + value: + $ref: "#/schemas/SearchStatusValue" + PrivacyOrganization: + type: object + description: >- + Organization as the candidate who hid it reads it. The name is the + current name of the organization. The candidate must already have been + able to see the organization to hide it, so the reference tells them + nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: >- + Current name of the organization. Plain text; clients show it as + text, never as HTML. + HiddenOrganization: + type: object + description: >- + One organization that the candidate hides the profile from. The record + belongs to the candidate: no organization reads it, learns that it was + hidden, or can tell a hidden candidate from one who is not published. + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: "#/schemas/PrivacyOrganization" + hidden_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + HiddenOrganizationList: + type: object + description: >- + One page of the organizations that the candidate hides the profile + from, newest first with the organization identifier as the + tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: "#/schemas/HiddenOrganization" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + PrivacySettings: + type: object + description: >- + The visibility settings of the current candidate in one read: the + publication, the search status, and the number of hidden + organizations. The three are independent: each has its own version and + its own operation, and a change of one leaves the others as they were. + A new account reads a closed profile, `not_looking`, and no hidden + organization. + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: "#/schemas/Publication" + search_status: + $ref: "#/schemas/SearchStatus" + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: >- + Number of organizations that the candidate hides the profile from. + The list is read with `ListMyHiddenOrganizations`. + CardCategory: + type: object + description: A category confirmed by assessment results, as the card shows it. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + AnonymousCardContent: + type: object + description: >- + The anonymous candidate card as an organization reads it. Only values + that the candidate confirmed reach it; an unconfirmed suggestion and an + unknown value never do. A free text value (a stack tag, a soft skill, the + location) that looks like a contact (an email address, a phone number, a + URL or domain, a Telegram link, an @handle) is dropped by the builder + (TASK-089) and never published. It carries + no name, contact, resume text, employer, salary figure, account or + profile identifier, and no schema of the private profile or of a + contact disclosure is reachable from it; a contact reaches an + organization only through the contact grant of an accepted + invitation. Each property is null when its field is not published or + the candidate has no value for it, so the card does not tell the two + apart. The set of properties is closed, and an organization-visible + card must never gain a property that identifies the candidate. The + search ranking and the full card of an organization's search result + are defined by the search contract (TASK-185), which reuses this + content. + additionalProperties: false + required: + - categories + - stack + - experience_months + - soft_skills + - location + - relocation + properties: + categories: + type: + - array + - "null" + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: "#/schemas/CardCategory" + stack: + type: + - array + - "null" + maxItems: 30 + description: Technology tags of the candidate, or null. + items: + $ref: "./questionnaire_schemas.yml#/schemas/StackTag" + experience_months: + type: + - integer + - "null" + minimum: 0 + maximum: 1200 + description: >- + Total months of work experience, summed by the server without the + employers, periods, or descriptions, or null. + soft_skills: + type: + - array + - "null" + maxItems: 10 + description: Soft skills of the candidate, or null. + items: + type: string + minLength: 1 + maxLength: 50 + pattern: '^\S(?:.*\S)?$' + description: Plain text; clients show it as text, never as HTML. + location: + type: + - string + - "null" + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + City or region as free text, never a street address, or null. + Plain text; clients show it as text, never as HTML. + relocation: + type: + - boolean + - "null" + description: Whether the candidate is ready to relocate, or null. + CardPreview: + type: object + description: >- + What an organization that the candidate does not hide the profile from + would read now, computed from the current profile, the current + publication, and the consent ledger. It is a read for the candidate: it + creates no view and no history record, and it never reaches an + organization. `card` is null while the profile is closed. + additionalProperties: false + required: + - state + - fields + - card + - generated_at + properties: + state: + $ref: "#/schemas/PublicationState" + fields: + $ref: "#/schemas/CardFieldSet" + card: + oneOf: + - $ref: "#/schemas/AnonymousCardContent" + - type: "null" + generated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + PrivacyEventKind: + type: string + description: |- + Kind of a change of the visibility settings that the history records. + + - publication_opened: the candidate published a closed profile. + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + - search_status_confirmed: the candidate set or confirmed `looking`. + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + - organization_hidden: the candidate hid the profile from an organization. + - organization_unhidden: the candidate lifted the hiding for an organization. + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden + PrivacyEvent: + type: object + description: >- + One recorded change of the visibility settings of the current + candidate, as evidence of what was published, hidden, or announced and + when. The history is append-only and returns only the caller's own + records. A publication event carries the published fields and the C2 + record behind them; an organization event names the organization; the + other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: "#/schemas/PrivacyEventKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + fields: + description: >- + Published fields after the change for `publication_opened` and + `publication_changed`, an empty set for `publication_closed`, and + null for every other kind. + oneOf: + - $ref: "#/schemas/CardFieldSet" + - type: "null" + consent_id: + description: >- + C2 record that backs the publication, for `publication_opened` and + `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: "null" + organization: + description: >- + Organization of `organization_hidden` and `organization_unhidden` + with its current name, resolved when the history is read (the event + stores only the identifier), or null. + oneOf: + - $ref: "#/schemas/PrivacyOrganization" + - type: "null" + PrivacyEventList: + type: object + description: >- + One page of the settings history of the current candidate, newest + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: "#/schemas/PrivacyEvent" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + CardAccessKind: + type: string + description: |- + How an organization reached the candidate. + + - card_viewed: an organization read the anonymous card in a search result. + - contact_read: an organization read the contacts through the contact grant of an accepted invitation. + enum: + - card_viewed + - contact_read + CardAccess: + type: object + description: >- + One access of an organization to the card or the contacts of the + current candidate. `organization` is null for a view by an + organization that has no invitation relation with the candidate, so the + history shows that the card was viewed without naming a company that + the candidate cannot otherwise see; whether the candidate should learn + the name is an open product question. The record carries no query, + ranking, or search filter of the organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: "#/schemas/CardAccessKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + organization: + oneOf: + - $ref: "#/schemas/PrivacyOrganization" + - type: "null" + CardAccessList: + type: object + description: >- + One page of the accesses to the card of the current candidate, newest + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: "#/schemas/CardAccess" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/components/schemas/problem_schemas.yml b/api/core/components/schemas/problem_schemas.yml index d26369f..6668c15 100644 --- a/api/core/components/schemas/problem_schemas.yml +++ b/api/core/components/schemas/problem_schemas.yml @@ -61,7 +61,7 @@ schemas: type: array maxItems: 100 description: >- - Field-level reasons for validation_failed. Other codes omit it. + Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. items: $ref: "#/schemas/ProblemFieldError" ProblemCode: @@ -138,8 +138,10 @@ schemas: pattern: "^[a-z][a-z0-9_]*$" description: >- Stable field reason. Current values are `required` (missing value) - and `invalid` (malformed value or a value outside the schema). - Clients must tolerate new values. + and `invalid` (malformed value or a value outside the schema), and, + on a state_conflict, `consent_required` (the operation needs a + consent that is not active) and `limit_reached` (a per-account + bound is reached). Clients must tolerate new values. message: type: string minLength: 1 diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index 7ce5784..93f426c 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -23,6 +23,8 @@ tags: description: 'Hiring needs of an organization: requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. Access comes only from an active membership in the organization; a need never requires a vacancy.' - name: invitation description: 'Invitations from an organization to one candidate: drafts with complete terms, immutable terms versions, sending, the candidate''s inbox, acceptance with the consent C4, structured declines, withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms.' + - name: privacy + description: 'Visibility of the current candidate: the publication of the anonymous card (a setting that refers to the C2 consent of the ledger and never replaces it), the search status that is not a consent, the organizations that the candidate hides the profile from, the preview of the card, and the history of the settings and of the accesses. Everything is closed by default, and no change makes a candidate more visible than they chose. No schema here reaches a contact, a name, or the lowest salary.' - name: consent description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.' - name: support @@ -2148,6 +2150,380 @@ paths: $ref: '#/components/responses/Unauthenticated' default: $ref: '#/components/responses/Problem' + /api/v1/me/privacy: + get: + operationId: GetMyPrivacySettings + summary: Read the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns the publication of the candidate card, the search status, and the number of hidden organizations in one read. The response is `Cache-Control: no-store`. + + A profile is closed by default. A candidate who never published reads `publication.state` `closed` with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or an assessment changes these settings. The C2 consent, the search status, and the hidden organizations are three independent settings: the C2 record in the consent ledger proves that the candidate accepted the publication text, the publication records which fields are published, and the search status is a statement of the candidate that is not a consent. A change of one never changes another, and none of them ever makes the candidate more visible by itself: the search status lapses to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + '200': + description: The visibility settings of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PrivacySettings' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidatePrivacySettings' + published_and_looking: + $ref: '#/components/examples/PublishedCandidatePrivacySettings' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/publication: + put: + operationId: SetMyPublication + summary: Publish or close the anonymous candidate card. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. + + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + + The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first publication. If it is not the current version the server answers 412 version_conflict and changes nothing. The version travels in the body rather than in If-Match because the generated client cannot read the ETag header yet. A body that equals the stored setting changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a retry after a lost response succeeds without an Idempotency-Key. A version above the current one never existed and always answers 412. Every change is recorded in the settings history with its time, the fields, and the C2 record. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), rules that depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown card field, and more fields than there are groups; a published state with no field, and a closed state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicationUpdate' + examples: + publish: + $ref: '#/components/examples/PublicationUpdatePublish' + close: + $ref: '#/components/examples/PublicationUpdateClose' + responses: + '200': + description: The saved publication with its new version, or the current one when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Publication' + examples: + published: + $ref: '#/components/examples/PublishedPublication' + '400': + $ref: '#/components/responses/PrivacyValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/PublicationConsentRequired' + '412': + $ref: '#/components/responses/PrivacyVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/preview: + get: + operationId: GetMyCardPreview + summary: Preview the anonymous card that organizations would read. + description: |- + Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`. + + The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + '200': + description: The anonymous card as organizations would read it now. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CardPreview' + examples: + published: + $ref: '#/components/examples/PublishedCardPreview' + closed: + $ref: '#/components/examples/ClosedCardPreview' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/search-status: + put: + operationId: SetMySearchStatus + summary: Set or confirm the search status of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. The status is a statement of the candidate and never a consent. It changes neither the C2 consent, nor the publication, nor the hidden organizations, and it does not close or open any contact grant; a candidate whose profile is closed who sets `looking` becomes visible to no one. + + `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from the `search_status` section of the effective product policy (30 days in the demo policy, `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it replaces the confirmation time with now and advances the version, also after a lapse. The body carries no time, interval, or policy version. + + After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The lapse is computed and written nowhere, so it needs no job, it can never make the candidate more visible, and it never touches the publication or the hidden organizations. A reminder before the lapse is a planned notification, not a part of this operation. + + Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the status; a stale or non-existent version answers 412 version_conflict and changes nothing. `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. `looking` always changes the stored confirmation, so a retry of a confirmation whose response was lost with the old version answers 412 and the client reads the status again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), an unchanged `not_looking` (200), then a stale version (412). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SearchStatusUpdate' + examples: + looking: + $ref: '#/components/examples/SearchStatusUpdateLooking' + responses: + '200': + description: The saved search status with its new version, or the current one when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SearchStatus' + examples: + looking: + $ref: '#/components/examples/LookingSearchStatus' + lapsed: + $ref: '#/components/examples/LapsedSearchStatus' + '400': + $ref: '#/components/responses/PrivacyValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/PrivacyVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/hidden-organizations: + get: + operationId: ListMyHiddenOrganizations + summary: List the organizations that the candidate hides the profile from. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records and no request can name another account. Returns a page of the hidden organizations, newest first with the organization identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The records belong to the candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, no card, no contact read. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the hidden organizations of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/HiddenOrganizationList' + examples: + page: + $ref: '#/components/examples/HiddenOrganizationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/hidden-organizations/{org_id}: + put: + operationId: HideOrganization + summary: Hide the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body: the path names the organization and the candidate comes from the session. The hiding is a record that belongs to the candidate and references the organization; it changes neither the C2 consent, nor the publication, nor the search status. + + The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. + + Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it. + + A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. + + Hiding an organization that holds an active contact grant of the candidate revokes that grant with the reason `visibility_closed` in the same transaction (planned together with the invitation operations). Lifting the hiding never reopens a grant. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), the organization and its visibility to the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like every visibility change, hiding needs a verified email (a usecase requirement). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/HiddenOrganizationId' + responses: + '200': + description: 'The organization is hidden from the candidate profile: the new record or the one that existed.' + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/HiddenOrganization' + examples: + hidden: + $ref: '#/components/examples/HiddenOrganizationRecord' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/HiddenOrganizationLimit' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: UnhideOrganization + summary: Lift the hiding of the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or does not exist, so the operation reveals nothing about the organization, and a repeat after a lost response succeeds. The record is deleted, the settings history keeps the event `organization_unhidden` only when a record was deleted. + + Lifting the hiding makes the candidate readable by that organization again only if the profile is published and the organization otherwise may read it. It changes neither the C2 consent, nor the publication, nor the search status, and it never reopens a contact grant that the hiding closed. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), then the deletion (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/HiddenOrganizationId' + responses: + '204': + description: The organization is not hidden from the candidate profile. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/history: + get: + operationId: ListMyPrivacyHistory + summary: List the changes of the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records. Returns a page of the settings history, newest first with the event identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The history is append-only evidence of what the candidate published, hid, and announced, and when. A publication event keeps the published fields and the C2 record behind them, which is what the consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the field set). A revocation of C2 and a lapse of the search status are computed and are not events here; the consent history shows the revocation. The history never contains a profile value. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the settings history of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PrivacyEventList' + examples: + page: + $ref: '#/components/examples/PrivacyEventListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/access-history: + get: + operationId: ListMyCardAccessHistory + summary: List the accesses of organizations to the card of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. + + The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the accesses to the card of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CardAccessList' + examples: + page: + $ref: '#/components/examples/CardAccessListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' /api/v1/me/support-cases: get: operationId: ListMySupportCases @@ -2357,7 +2733,7 @@ components: errors: type: array maxItems: 100 - description: Field-level reasons for validation_failed. Other codes omit it. + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. items: $ref: '#/components/schemas/ProblemFieldError' ProblemCode: @@ -2428,7 +2804,7 @@ components: minLength: 1 maxLength: 64 pattern: ^[a-z][a-z0-9_]*$ - description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. message: type: string minLength: 1 @@ -7827,6 +8203,450 @@ components: $ref: '#/components/schemas/MyOrganization' page: $ref: '#/components/schemas/PageInfo' + PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale. + examples: + - 2 + SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`. + examples: + - 3 + CardField: + type: string + description: |- + A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + - categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published. + - stack: the technology tags of the profile. + - experience: the total months of work experience, without employers, periods, or descriptions. + - soft_skills: the soft skills of the profile. + - location: the city or region of the profile. + - relocation: whether the candidate is ready to relocate. + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. + enum: + - categories + - stack + - experience + - soft_skills + - location + - relocation + CardFieldSet: + type: array + minItems: 0 + maxItems: 6 + uniqueItems: true + description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. + items: + $ref: '#/components/schemas/CardField' + PublicationState: + type: string + description: |- + Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid. + enum: + - closed + - published + PublicationClosedReason: + type: string + description: |- + Why a closed profile is closed, shown only to the candidate. + + - never_published: the candidate has never published the profile. + - closed_by_candidate: the candidate closed the publication. + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record. + enum: + - never_published + - closed_by_candidate + - consent_revoked + Publication: + type: object + description: 'Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.' + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: '#/components/schemas/PublicationState' + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: '#/components/schemas/PublicationClosedReason' + - type: 'null' + fields: + description: Card fields that organizations may read. Empty exactly when `state` is `closed`. + allOf: + - $ref: '#/components/schemas/CardFieldSet' + consent_id: + description: Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: 'null' + published_at: + description: Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + version: + $ref: '#/components/schemas/PublicationVersion' + PublicationUpdate: + type: object + description: 'The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account''s current unrevoked C2 record, and a client can neither supply nor forge one.' + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: '#/components/schemas/PublicationVersion' + state: + $ref: '#/components/schemas/PublicationState' + fields: + $ref: '#/components/schemas/CardFieldSet' + SearchStatusValue: + type: string + description: |- + Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls. + enum: + - looking + - not_looking + SearchStatus: + type: object + description: 'Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.' + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: 'The status that holds now: `looking` only while the confirmation has not lapsed.' + allOf: + - $ref: '#/components/schemas/SearchStatusValue' + lapsed: + type: boolean + description: True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared. + confirmed_at: + description: Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + lapses_at: + description: Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + version: + $ref: '#/components/schemas/SearchStatusVersion' + SearchStatusUpdate: + type: object + description: 'The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.' + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: '#/components/schemas/SearchStatusVersion' + value: + $ref: '#/components/schemas/SearchStatusValue' + PrivacyOrganization: + type: object + description: Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Current name of the organization. Plain text; clients show it as text, never as HTML. + HiddenOrganization: + type: object + description: 'One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.' + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: '#/components/schemas/PrivacyOrganization' + hidden_at: + $ref: '#/components/schemas/Timestamp' + HiddenOrganizationList: + type: object + description: One page of the organizations that the candidate hides the profile from, newest first with the organization identifier as the tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: '#/components/schemas/HiddenOrganization' + page: + $ref: '#/components/schemas/PageInfo' + PrivacySettings: + type: object + description: 'The visibility settings of the current candidate in one read: the publication, the search status, and the number of hidden organizations. The three are independent: each has its own version and its own operation, and a change of one leaves the others as they were. A new account reads a closed profile, `not_looking`, and no hidden organization.' + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: '#/components/schemas/Publication' + search_status: + $ref: '#/components/schemas/SearchStatus' + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. + CardCategory: + type: object + description: A category confirmed by assessment results, as the card shows it. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + AnonymousCardContent: + type: object + description: The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization's search result are defined by the search contract (TASK-185), which reuses this content. + additionalProperties: false + required: + - categories + - stack + - experience_months + - soft_skills + - location + - relocation + properties: + categories: + type: + - array + - 'null' + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: '#/components/schemas/CardCategory' + stack: + type: + - array + - 'null' + maxItems: 30 + description: Technology tags of the candidate, or null. + items: + $ref: '#/components/schemas/StackTag' + experience_months: + type: + - integer + - 'null' + minimum: 0 + maximum: 1200 + description: Total months of work experience, summed by the server without the employers, periods, or descriptions, or null. + soft_skills: + type: + - array + - 'null' + maxItems: 10 + description: Soft skills of the candidate, or null. + items: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: Plain text; clients show it as text, never as HTML. + location: + type: + - string + - 'null' + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML. + relocation: + type: + - boolean + - 'null' + description: Whether the candidate is ready to relocate, or null. + CardPreview: + type: object + description: 'What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.' + additionalProperties: false + required: + - state + - fields + - card + - generated_at + properties: + state: + $ref: '#/components/schemas/PublicationState' + fields: + $ref: '#/components/schemas/CardFieldSet' + card: + oneOf: + - $ref: '#/components/schemas/AnonymousCardContent' + - type: 'null' + generated_at: + $ref: '#/components/schemas/Timestamp' + PrivacyEventKind: + type: string + description: |- + Kind of a change of the visibility settings that the history records. + + - publication_opened: the candidate published a closed profile. + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + - search_status_confirmed: the candidate set or confirmed `looking`. + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + - organization_hidden: the candidate hid the profile from an organization. + - organization_unhidden: the candidate lifted the hiding for an organization. + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden + PrivacyEvent: + type: object + description: One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller's own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: '#/components/schemas/PrivacyEventKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + fields: + description: Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind. + oneOf: + - $ref: '#/components/schemas/CardFieldSet' + - type: 'null' + consent_id: + description: C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: 'null' + organization: + description: Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null. + oneOf: + - $ref: '#/components/schemas/PrivacyOrganization' + - type: 'null' + PrivacyEventList: + type: object + description: One page of the settings history of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: '#/components/schemas/PrivacyEvent' + page: + $ref: '#/components/schemas/PageInfo' + CardAccessKind: + type: string + description: |- + How an organization reached the candidate. + + - card_viewed: an organization read the anonymous card in a search result. + - contact_read: an organization read the contacts through the contact grant of an accepted invitation. + enum: + - card_viewed + - contact_read + CardAccess: + type: object + description: One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: '#/components/schemas/CardAccessKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + organization: + oneOf: + - $ref: '#/components/schemas/PrivacyOrganization' + - type: 'null' + CardAccessList: + type: object + description: One page of the accesses to the card of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: '#/components/schemas/CardAccess' + page: + $ref: '#/components/schemas/PageInfo' HealthResponse: type: object additionalProperties: false @@ -7945,6 +8765,15 @@ components: type: string format: uuid example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + HiddenOrganizationId: + name: org_id + in: path + required: true + description: Identifier of the organization that the current candidate hides or stops hiding the profile from. It names the target of a candidate's own setting and grants the candidate nothing about the organization. Hiding answers the same 404 not_found for an organization that does not exist and for one that the candidate cannot see, so organizations cannot be enumerated; lifting the hiding answers 204 for any well-formed identifier. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 headers: ETag: description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. @@ -8435,6 +9264,42 @@ components: examples: version_conflict: $ref: '#/components/examples/OrganizationStaleVersion' + PrivacyValidationFailed: + description: 'The body does not match the contract or breaks a visibility rule: an unknown field, a repeated or unknown card field, a published state with no field, a closed state with a field, a search status other than looking and not_looking, or a missing or invalid expected_version; code validation_failed with body pointers. Nothing was changed. The problem never repeats a submitted value.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + published_without_fields: + $ref: '#/components/examples/PrivacyPublishedWithoutFields' + PrivacyVersionConflict: + description: '`expected_version` is not the current version of the setting; code version_conflict. Nothing was changed; read the settings again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/PrivacyStaleVersion' + PublicationConsentRequired: + description: 'The profile cannot be published because the account has no active, unrevoked C2 consent; code state_conflict. Nothing was changed. The candidate gives C2 in the consent settings first. `errors` holds the entry `{in: body, pointer: /state, code: consent_required}`.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/PublicationConsentRequiredConflict' + HiddenOrganizationLimit: + description: 'The candidate already hides the maximum number of organizations (1000); code state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`. Nothing was changed.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + limit_reached: + $ref: '#/components/examples/HiddenOrganizationLimitReached' securitySchemes: sessionCookie: type: apiKey @@ -12174,6 +13039,233 @@ components: page: has_more: false next_cursor: null + NewCandidatePrivacySettings: + summary: A new candidate with the profile closed + description: Nothing was ever published, announced, or hidden. Every version is 0. + value: + publication: + state: closed + closed_reason: never_published + fields: [] + consent_id: null + published_at: null + version: 0 + search_status: + value: not_looking + lapsed: false + confirmed_at: null + lapses_at: null + version: 0 + hidden_organizations_total: 0 + PublishedCandidatePrivacySettings: + summary: A published profile with a confirmed search status + value: + publication: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: '2026-10-06T09:10:00Z' + version: 1 + search_status: + value: looking + lapsed: false + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + hidden_organizations_total: 1 + PublicationUpdatePublish: + summary: Publish the confirmed categories and the stack + value: + expected_version: 0 + state: published + fields: + - categories + - stack + PublicationUpdateClose: + summary: Close the publication + value: + expected_version: 1 + state: closed + fields: [] + PublishedPublication: + summary: The publication after the first publish + value: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: '2026-10-06T09:10:00Z' + version: 1 + PrivacyPublishedWithoutFields: + summary: A publication without any field + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 3b4c5d6e-7f80-4a91-8b2c-3d4e5f6a7b8c + errors: + - in: body + pointer: /fields + code: invalid + message: A published profile needs at least one field, and a closed one none. + PublicationConsentRequiredConflict: + summary: Publishing without an active C2 consent + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5d6e7f80-91a2-4cb3-8d4e-5f6a7b8c9d0e + errors: + - in: body + pointer: /state + code: consent_required + message: Publishing needs an active C2 consent of the account. + PrivacyStaleVersion: + summary: The change carried a stale expected_version + description: The setting changed, for example in another tab, after the client read it. Nothing was changed; the client reads the settings again and reapplies its edit. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 4c5d6e7f-8091-4ba2-9c3d-4e5f6a7b8c9d + PublishedCardPreview: + summary: The card of a published profile with two fields + description: The fields that are not published are null. The card carries no name and no contact. + value: + state: published + fields: + - categories + - stack + card: + categories: + - specialization: backend + grade: middle + stack: + - PostgreSQL + - Kafka + experience_months: null + soft_skills: null + location: null + relocation: null + generated_at: '2026-10-06T09:30:00Z' + ClosedCardPreview: + summary: The preview of a closed profile + value: + state: closed + fields: [] + card: null + generated_at: '2026-10-06T09:30:00Z' + SearchStatusUpdateLooking: + summary: Set or confirm the status looking + value: + expected_version: 0 + value: looking + LookingSearchStatus: + summary: A confirmed status that lapses after the policy interval + value: + value: looking + lapsed: false + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + LapsedSearchStatus: + summary: A status that was not confirmed in time + description: The candidate set looking and did not confirm it again, so it holds as not_looking. Nothing else changed; the publication and the hidden organizations are as they were. + value: + value: not_looking + lapsed: true + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + HiddenOrganizationListPage: + summary: One hidden organization + value: + items: + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: '2026-10-06T09:20:00Z' + page: + has_more: false + next_cursor: null + HiddenOrganizationRecord: + summary: An organization that the candidate hides the profile from + value: + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: '2026-10-06T09:20:00Z' + HiddenOrganizationLimitReached: + summary: The candidate hides the maximum number of organizations + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6e7f8091-a2b3-4dc4-9e5f-6a7b8c9d0e1f + errors: + - in: path + pointer: /org_id + code: limit_reached + message: The candidate already hides the maximum number of organizations. + PrivacyEventListPage: + summary: A publication, a hiding, and a confirmed status + value: + items: + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9f01 + kind: organization_hidden + occurred_at: '2026-10-06T09:20:00Z' + fields: null + consent_id: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e02 + kind: search_status_confirmed + occurred_at: '2026-10-06T09:12:00Z' + fields: null + consent_id: null + organization: null + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e01 + kind: publication_opened + occurred_at: '2026-10-06T09:10:00Z' + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + organization: null + page: + has_more: false + next_cursor: null + CardAccessListPage: + summary: An anonymous view and a contact read + value: + items: + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a02 + kind: contact_read + occurred_at: '2026-10-07T08:00:00Z' + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a01 + kind: card_viewed + occurred_at: '2026-10-06T12:00:00Z' + organization: null + page: + has_more: false + next_cursor: null SupportCaseListPage: summary: The last page of the case summaries of the current account value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 77f55f3..6b0bdfd 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -50,6 +50,16 @@ tags: withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms. + - name: privacy + description: >- + Visibility of the current candidate: the publication of the anonymous + card (a setting that refers to the C2 consent of the ledger and never + replaces it), the search status that is not a consent, the + organizations that the candidate hides the profile from, the preview + of the card, and the history of the settings and of the accesses. + Everything is closed by default, and no change makes a candidate more + visible than they chose. No schema here reaches a contact, a name, or + the lowest salary. - name: consent description: >- The consent ledger of the current account: the independent consents @@ -137,6 +147,22 @@ paths: $ref: ./routes/candidate_invitation_cancel.yml /api/v1/me/consents: $ref: ./routes/consents.yml + /api/v1/me/privacy: + $ref: ./routes/candidate_privacy.yml + /api/v1/me/privacy/publication: + $ref: ./routes/candidate_privacy_publication.yml + /api/v1/me/privacy/preview: + $ref: ./routes/candidate_privacy_preview.yml + /api/v1/me/privacy/search-status: + $ref: ./routes/candidate_privacy_search_status.yml + /api/v1/me/privacy/hidden-organizations: + $ref: ./routes/candidate_privacy_hidden_organizations.yml + /api/v1/me/privacy/hidden-organizations/{org_id}: + $ref: ./routes/candidate_privacy_hidden_organization.yml + /api/v1/me/privacy/history: + $ref: ./routes/candidate_privacy_history.yml + /api/v1/me/privacy/access-history: + $ref: ./routes/candidate_privacy_access_history.yml /api/v1/me/support-cases: $ref: ./routes/support_cases.yml /api/v1/me/support-cases/{case_id}: @@ -741,6 +767,54 @@ components: $ref: ./components/schemas.yml#/MyOrganization MyOrganizationList: $ref: ./components/schemas.yml#/MyOrganizationList + PublicationVersion: + $ref: ./components/schemas.yml#/PublicationVersion + SearchStatusVersion: + $ref: ./components/schemas.yml#/SearchStatusVersion + CardField: + $ref: ./components/schemas.yml#/CardField + CardFieldSet: + $ref: ./components/schemas.yml#/CardFieldSet + PublicationState: + $ref: ./components/schemas.yml#/PublicationState + PublicationClosedReason: + $ref: ./components/schemas.yml#/PublicationClosedReason + Publication: + $ref: ./components/schemas.yml#/Publication + PublicationUpdate: + $ref: ./components/schemas.yml#/PublicationUpdate + SearchStatusValue: + $ref: ./components/schemas.yml#/SearchStatusValue + SearchStatus: + $ref: ./components/schemas.yml#/SearchStatus + SearchStatusUpdate: + $ref: ./components/schemas.yml#/SearchStatusUpdate + PrivacyOrganization: + $ref: ./components/schemas.yml#/PrivacyOrganization + HiddenOrganization: + $ref: ./components/schemas.yml#/HiddenOrganization + HiddenOrganizationList: + $ref: ./components/schemas.yml#/HiddenOrganizationList + PrivacySettings: + $ref: ./components/schemas.yml#/PrivacySettings + CardCategory: + $ref: ./components/schemas.yml#/CardCategory + AnonymousCardContent: + $ref: ./components/schemas.yml#/AnonymousCardContent + CardPreview: + $ref: ./components/schemas.yml#/CardPreview + PrivacyEventKind: + $ref: ./components/schemas.yml#/PrivacyEventKind + PrivacyEvent: + $ref: ./components/schemas.yml#/PrivacyEvent + PrivacyEventList: + $ref: ./components/schemas.yml#/PrivacyEventList + CardAccessKind: + $ref: ./components/schemas.yml#/CardAccessKind + CardAccess: + $ref: ./components/schemas.yml#/CardAccess + CardAccessList: + $ref: ./components/schemas.yml#/CardAccessList parameters: IdempotencyKey: $ref: ./components/parameters.yml#/IdempotencyKey @@ -762,6 +836,8 @@ components: $ref: ./components/parameters.yml#/InvitationId MyInvitationId: $ref: ./components/parameters.yml#/MyInvitationId + HiddenOrganizationId: + $ref: ./components/parameters.yml#/HiddenOrganizationId headers: ETag: $ref: ./components/headers.yml#/ETag @@ -854,6 +930,14 @@ components: $ref: ./components/responses.yml#/OrganizationValidationFailed OrganizationVersionConflict: $ref: ./components/responses.yml#/OrganizationVersionConflict + PrivacyValidationFailed: + $ref: ./components/responses.yml#/PrivacyValidationFailed + PrivacyVersionConflict: + $ref: ./components/responses.yml#/PrivacyVersionConflict + PublicationConsentRequired: + $ref: ./components/responses.yml#/PublicationConsentRequired + HiddenOrganizationLimit: + $ref: ./components/responses.yml#/HiddenOrganizationLimit securitySchemes: sessionCookie: type: apiKey diff --git a/api/core/routes/candidate_privacy.yml b/api/core/routes/candidate_privacy.yml new file mode 100644 index 0000000..980f184 --- /dev/null +++ b/api/core/routes/candidate_privacy.yml @@ -0,0 +1,34 @@ +get: + operationId: GetMyPrivacySettings + summary: Read the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns the publication of the candidate card, the search status, and the number of hidden organizations in one read. The response is `Cache-Control: no-store`. + + A profile is closed by default. A candidate who never published reads `publication.state` `closed` with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or an assessment changes these settings. The C2 consent, the search status, and the hidden organizations are three independent settings: the C2 record in the consent ledger proves that the candidate accepted the publication text, the publication records which fields are published, and the search status is a statement of the candidate that is not a consent. A change of one never changes another, and none of them ever makes the candidate more visible by itself: the search status lapses to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + "200": + description: The visibility settings of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PrivacySettings + examples: + new_candidate: + $ref: ../components/examples.yml#/NewCandidatePrivacySettings + published_and_looking: + $ref: ../components/examples.yml#/PublishedCandidatePrivacySettings + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_access_history.yml b/api/core/routes/candidate_privacy_access_history.yml new file mode 100644 index 0000000..36d988d --- /dev/null +++ b/api/core/routes/candidate_privacy_access_history.yml @@ -0,0 +1,39 @@ +get: + operationId: ListMyCardAccessHistory + summary: List the accesses of organizations to the card of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. + + The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the accesses to the card of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CardAccessList + examples: + page: + $ref: ../components/examples.yml#/CardAccessListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_hidden_organization.yml b/api/core/routes/candidate_privacy_hidden_organization.yml new file mode 100644 index 0000000..463915e --- /dev/null +++ b/api/core/routes/candidate_privacy_hidden_organization.yml @@ -0,0 +1,81 @@ +put: + operationId: HideOrganization + summary: Hide the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body: the path names the organization and the candidate comes from the session. The hiding is a record that belongs to the candidate and references the organization; it changes neither the C2 consent, nor the publication, nor the search status. + + The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. + + Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it. + + A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. + + Hiding an organization that holds an active contact grant of the candidate revokes that grant with the reason `visibility_closed` in the same transaction (planned together with the invitation operations). Lifting the hiding never reopens a grant. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), the organization and its visibility to the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like every visibility change, hiding needs a verified email (a usecase requirement). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/HiddenOrganizationId + responses: + "200": + description: >- + The organization is hidden from the candidate profile: the new record + or the one that existed. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/HiddenOrganization + examples: + hidden: + $ref: ../components/examples.yml#/HiddenOrganizationRecord + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/HiddenOrganizationLimit + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: UnhideOrganization + summary: Lift the hiding of the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or does not exist, so the operation reveals nothing about the organization, and a repeat after a lost response succeeds. The record is deleted, the settings history keeps the event `organization_unhidden` only when a record was deleted. + + Lifting the hiding makes the candidate readable by that organization again only if the profile is published and the organization otherwise may read it. It changes neither the C2 consent, nor the publication, nor the search status, and it never reopens a contact grant that the hiding closed. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), then the deletion (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/HiddenOrganizationId + responses: + "204": + description: The organization is not hidden from the candidate profile. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_hidden_organizations.yml b/api/core/routes/candidate_privacy_hidden_organizations.yml new file mode 100644 index 0000000..513dffb --- /dev/null +++ b/api/core/routes/candidate_privacy_hidden_organizations.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyHiddenOrganizations + summary: List the organizations that the candidate hides the profile from. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records and no request can name another account. Returns a page of the hidden organizations, newest first with the organization identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The records belong to the candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, no card, no contact read. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the hidden organizations of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/HiddenOrganizationList + examples: + page: + $ref: ../components/examples.yml#/HiddenOrganizationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_history.yml b/api/core/routes/candidate_privacy_history.yml new file mode 100644 index 0000000..5c20ce1 --- /dev/null +++ b/api/core/routes/candidate_privacy_history.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyPrivacyHistory + summary: List the changes of the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records. Returns a page of the settings history, newest first with the event identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The history is append-only evidence of what the candidate published, hid, and announced, and when. A publication event keeps the published fields and the C2 record behind them, which is what the consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the field set). A revocation of C2 and a lapse of the search status are computed and are not events here; the consent history shows the revocation. The history never contains a profile value. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the settings history of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PrivacyEventList + examples: + page: + $ref: ../components/examples.yml#/PrivacyEventListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_preview.yml b/api/core/routes/candidate_privacy_preview.yml new file mode 100644 index 0000000..4c5e6a9 --- /dev/null +++ b/api/core/routes/candidate_privacy_preview.yml @@ -0,0 +1,34 @@ +get: + operationId: GetMyCardPreview + summary: Preview the anonymous card that organizations would read. + description: |- + Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`. + + The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + "200": + description: The anonymous card as organizations would read it now. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CardPreview + examples: + published: + $ref: ../components/examples.yml#/PublishedCardPreview + closed: + $ref: ../components/examples.yml#/ClosedCardPreview + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_publication.yml b/api/core/routes/candidate_privacy_publication.yml new file mode 100644 index 0000000..938e593 --- /dev/null +++ b/api/core/routes/candidate_privacy_publication.yml @@ -0,0 +1,56 @@ +put: + operationId: SetMyPublication + summary: Publish or close the anonymous candidate card. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. + + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + + The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first publication. If it is not the current version the server answers 412 version_conflict and changes nothing. The version travels in the body rather than in If-Match because the generated client cannot read the ETag header yet. A body that equals the stored setting changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a retry after a lost response succeeds without an Idempotency-Key. A version above the current one never existed and always answers 412. Every change is recorded in the settings history with its time, the fields, and the C2 record. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), rules that depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown card field, and more fields than there are groups; a published state with no field, and a closed state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PublicationUpdate + examples: + publish: + $ref: ../components/examples.yml#/PublicationUpdatePublish + close: + $ref: ../components/examples.yml#/PublicationUpdateClose + responses: + "200": + description: >- + The saved publication with its new version, or the current one when + the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Publication + examples: + published: + $ref: ../components/examples.yml#/PublishedPublication + "400": + $ref: ../components/responses.yml#/PrivacyValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "409": + $ref: ../components/responses.yml#/PublicationConsentRequired + "412": + $ref: ../components/responses.yml#/PrivacyVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_search_status.yml b/api/core/routes/candidate_privacy_search_status.yml new file mode 100644 index 0000000..0f3813f --- /dev/null +++ b/api/core/routes/candidate_privacy_search_status.yml @@ -0,0 +1,54 @@ +put: + operationId: SetMySearchStatus + summary: Set or confirm the search status of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. The status is a statement of the candidate and never a consent. It changes neither the C2 consent, nor the publication, nor the hidden organizations, and it does not close or open any contact grant; a candidate whose profile is closed who sets `looking` becomes visible to no one. + + `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from the `search_status` section of the effective product policy (30 days in the demo policy, `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it replaces the confirmation time with now and advances the version, also after a lapse. The body carries no time, interval, or policy version. + + After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The lapse is computed and written nowhere, so it needs no job, it can never make the candidate more visible, and it never touches the publication or the hidden organizations. A reminder before the lapse is a planned notification, not a part of this operation. + + Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the status; a stale or non-existent version answers 412 version_conflict and changes nothing. `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. `looking` always changes the stored confirmation, so a retry of a confirmation whose response was lost with the old version answers 412 and the client reads the status again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), an unchanged `not_looking` (200), then a stale version (412). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SearchStatusUpdate + examples: + looking: + $ref: ../components/examples.yml#/SearchStatusUpdateLooking + responses: + "200": + description: >- + The saved search status with its new version, or the current one + when the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SearchStatus + examples: + looking: + $ref: ../components/examples.yml#/LookingSearchStatus + lapsed: + $ref: ../components/examples.yml#/LapsedSearchStatus + "400": + $ref: ../components/responses.yml#/PrivacyValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "412": + $ref: ../components/responses.yml#/PrivacyVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/testdata/openapi-3.2.0.yml b/api/testdata/openapi-3.2.0.yml index 335283a..522461c 100644 --- a/api/testdata/openapi-3.2.0.yml +++ b/api/testdata/openapi-3.2.0.yml @@ -224,7 +224,7 @@ components: errors: type: array maxItems: 100 - description: Field-level reasons for validation_failed. Other codes omit it. + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. items: $ref: "#/components/schemas/ProblemFieldError" ProblemCode: @@ -295,7 +295,7 @@ components: minLength: 1 maxLength: 64 pattern: ^[a-z][a-z0-9_]*$ - description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. message: type: string minLength: 1 diff --git a/backend/db/migrations/00015_create_candidate_privacy.sql b/backend/db/migrations/00015_create_candidate_privacy.sql new file mode 100644 index 0000000..dbf76c7 --- /dev/null +++ b/backend/db/migrations/00015_create_candidate_privacy.sql @@ -0,0 +1,440 @@ +-- +goose Up +-- Visibility of the candidate card (PRD FR02 and FR12, TASK-088): the +-- publication, the search status, the organizations the candidate hides the +-- profile from, and the history of these settings. Enum-like columns are text +-- with CHECK constraints, as in the other tables. +-- +-- A profile is closed by default: nothing here is created with the profile +-- or with the account, and a missing row means "closed", "not looking", or +-- "not hidden". Every row is written by an explicit act of the candidate. +-- +-- The three settings are separate tables on purpose. The consent C2 stays in +-- the consent ledger and proves that the candidate accepted the publication +-- text; candidate_publications refers to that record and records what the +-- ledger deliberately does not (which fields, and when). The search status is +-- a statement of the candidate, never a consent, so it has no consent column +-- and no statement of one table writes another table. No row stores a +-- profile value, a name, or a contact: the rows hold card field codes, +-- identifiers, and times. + +-- Card field codes in the canonical form of the stored sets: distinct, +-- without NULLs, known, in ascending byte order. A canonical form makes equal +-- sets equal arrays. The set is empty for a closed publication. The codes +-- are the contract's CardField, which never includes the name, a contact, or +-- the lowest salary. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 6 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'soft_skills', 'stack' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- A composite foreign key below needs a unique key over the ledger columns +-- it names. The record id is already unique, so this adds no restriction; it +-- lets a publication refer to a C2 record of its own account and no other. +CREATE UNIQUE INDEX consent_records_id_subject_purpose_key +ON consent_records (id, subject_id, purpose); + +-- One row per candidate, created by the first explicit publication. A row +-- exists only after the candidate published once, so a new profile has no +-- row and is closed. state is the stored setting; the effective state also +-- needs the referenced C2 record to be unrevoked, which the read query joins +-- from the ledger. A revocation therefore closes the card at once without any +-- write here, and a later C2 grant opens nothing: a publication is bound to +-- the record that backed it, and republishing binds it to the new one. +CREATE TABLE candidate_publications ( + user_id uuid NOT NULL, + -- published: organizations may read the fields. closed: the candidate + -- closed the publication; the row keeps the last published time and the + -- C2 record as evidence. + state text NOT NULL, + -- Card field codes in canonical order; empty exactly when closed. + fields text [] NOT NULL, + -- The C2 record that backed the latest publication. Always the C2 of this + -- account: the foreign key names the subject and the purpose. + consent_record_id uuid NOT NULL, + consent_purpose text GENERATED ALWAYS AS ('c2') STORED, + -- The time of the latest change that published or republished the card. + published_at timestamptz NOT NULL, + -- The time the candidate closed the publication; NULL while published. + closed_at timestamptz, + -- Optimistic concurrency version; the first publication creates 1 and + -- the contract's version 0 is the absence of a row. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_publications_pkey PRIMARY KEY (user_id), + CONSTRAINT candidate_publications_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + -- Consent evidence outlives a careless delete of the setting: the record + -- cannot be deleted while a publication refers to it. + CONSTRAINT candidate_publications_consent_fkey FOREIGN KEY ( + consent_record_id, user_id, consent_purpose + ) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT, + CONSTRAINT candidate_publications_state_known CHECK ( + state IN ('published', 'closed') + ), + CONSTRAINT candidate_publications_fields_canonical CHECK ( + candidate_card_fields_are_canonical(fields) + ), + CONSTRAINT candidate_publications_state_shape CHECK ( + ( + state = 'published' + AND cardinality(fields) > 0 + AND closed_at IS NULL + ) + OR ( + state = 'closed' + AND cardinality(fields) = 0 + AND closed_at IS NOT NULL + AND closed_at >= published_at + ) + ), + CONSTRAINT candidate_publications_version_positive CHECK (version > 0), + CONSTRAINT candidate_publications_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- The search status of the candidate. A status that was never set has no row +-- (not_looking). looking stores the confirmation time and the lapse time, +-- which the application fixes from the search_status section of the product +-- policy version in force at the confirmation, and the version it used. The +-- lapse itself is computed by comparing lapses_at with the clock and is never +-- written: no process turns an expired status into a more public state. +-- Nothing here refers to a consent, the publication, or the hidden +-- organizations. +CREATE TABLE candidate_search_statuses ( + user_id uuid NOT NULL, + status text NOT NULL, + -- The latest confirmation of looking; NULL for not_looking. + confirmed_at timestamptz, + -- When the confirmed status lapses; NULL for not_looking. + lapses_at timestamptz, + -- The policy version whose interval produced lapses_at; NULL for + -- not_looking. Policy versions are immutable and never deleted. A trigger + -- below checks the reference instead of a foreign key, because a foreign + -- key would make PostgreSQL refuse TRUNCATE of policy_versions before its + -- own immutability trigger could answer. + policy_version_id uuid, + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_search_statuses_pkey PRIMARY KEY (user_id), + CONSTRAINT candidate_search_statuses_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_search_statuses_status_known CHECK ( + status IN ('looking', 'not_looking') + ), + -- looking always carries its confirmation, lapse, and policy version; + -- not_looking carries none of them. + CONSTRAINT candidate_search_statuses_confirmation CHECK ( + ( + status = 'looking' + AND confirmed_at IS NOT NULL + AND lapses_at IS NOT NULL + AND policy_version_id IS NOT NULL + AND lapses_at > confirmed_at + ) + OR ( + status = 'not_looking' + AND confirmed_at IS NULL + AND lapses_at IS NULL + AND policy_version_id IS NULL + ) + ), + CONSTRAINT candidate_search_statuses_version_positive CHECK (version > 0), + CONSTRAINT candidate_search_statuses_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- Stands in for a foreign key to policy_versions: an unknown policy version +-- raises SQLSTATE 23503 under the constraint name that the foreign key would +-- have had. Policy versions are immutable and cannot be deleted, so checking +-- when the reference is written is enough. +-- +goose StatementBegin +CREATE FUNCTION candidate_search_statuses_check_policy() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.policy_version_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM policy_versions WHERE id = NEW.policy_version_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'candidate_search_statuses_policy_fkey', + TABLE = 'candidate_search_statuses', + MESSAGE = 'search status references an unknown policy version'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_search_statuses_check_policy +BEFORE INSERT OR UPDATE OF policy_version_id ON candidate_search_statuses +FOR EACH ROW EXECUTE FUNCTION candidate_search_statuses_check_policy(); + +-- The organizations a candidate hides the profile from. The record belongs to +-- the candidate and references the organization; no organization reads it. +-- One record per pair, so a hiding is unique. The primary key starts with the +-- candidate, which serves every candidate-scoped read. Organizations are never +-- deleted by the application, so RESTRICT keeps a hiding from silently +-- disappearing with one. +CREATE TABLE candidate_hidden_organizations ( + user_id uuid NOT NULL, + organization_id uuid NOT NULL, + hidden_at timestamptz NOT NULL, + CONSTRAINT candidate_hidden_organizations_pkey PRIMARY KEY ( + user_id, organization_id + ), + CONSTRAINT candidate_hidden_organizations_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_hidden_organizations_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT +); + +-- Serves the candidate's list, newest first. +CREATE INDEX candidate_hidden_organizations_listing_idx +ON candidate_hidden_organizations (user_id, hidden_at DESC, organization_id DESC); + +-- Serves the organization side, which has to exclude hidden candidates from +-- its reads without learning who hid it. +CREATE INDEX candidate_hidden_organizations_organization_idx +ON candidate_hidden_organizations (organization_id, user_id); + +-- Bounds the hidden list of one candidate. The trigger serializes the inserts +-- of one candidate through a lock on the account row (a no-key update lock, +-- which does not block other readers of the account), counts the committed +-- rows, and refuses the insert over the bound with SQLSTATE 23514 and the +-- constraint name candidate_hidden_organizations_limit, which the adapter +-- maps to a port sentinel without reading the message. Raising the bound +-- also raises the maximum of the contract's hidden_organizations_total. +-- +goose StatementBegin +CREATE FUNCTION candidate_hidden_organizations_enforce_limit() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM 1 FROM users WHERE id = NEW.user_id FOR NO KEY UPDATE; + IF ( + SELECT count(*) FROM candidate_hidden_organizations + WHERE user_id = NEW.user_id + ) >= 1000 THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'candidate_hidden_organizations_limit', + TABLE = 'candidate_hidden_organizations', + MESSAGE = 'a candidate hides at most 1000 organizations'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_hidden_organizations_enforce_limit +BEFORE INSERT ON candidate_hidden_organizations +FOR EACH ROW EXECUTE FUNCTION candidate_hidden_organizations_enforce_limit(); + +-- The append-only history of the settings: what the candidate published, +-- announced, and hid, and when. It keeps the published field set and its +-- changes with their times, which the C2 record of the ledger does not carry. +-- A revocation of C2 and a lapse of the search status are computed and are not +-- events. The rows hold identifiers, card field codes, and times; never a +-- profile value or a name. The hide and unhide records are sensitive: they say +-- which employer a candidate avoids. +-- +-- It is evidence like the consent ledger. A trigger refuses every UPDATE, and +-- refuses DELETE while the account is confirmed (the same condition as +-- consent_records_refuse_delete, which the retention rule and the account +-- deletion procedure extend in their own migration). The account reference +-- cascades, so the unverified account cleanup removes the rows of an account +-- it deletes and a confirmed account is protected by the trigger. +-- TRUNCATE stays allowed for test isolation. +CREATE TABLE candidate_privacy_events ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + occurred_at timestamptz NOT NULL, + -- The published field set after a publication event; empty for a closing; + -- NULL for every other kind. + fields text [], + -- The C2 record behind a publication or republication; NULL otherwise. + consent_record_id uuid, + consent_purpose text GENERATED ALWAYS AS ( + CASE WHEN consent_record_id IS NOT NULL THEN 'c2' END + ) STORED, + -- The organization of a hiding event. Only the identifier is kept: the + -- candidate's read resolves the current name, so the history holds no + -- text about an organization. + organization_id uuid, + CONSTRAINT candidate_privacy_events_pkey PRIMARY KEY (id), + CONSTRAINT candidate_privacy_events_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + -- MATCH SIMPLE skips the check while consent_purpose is NULL. + CONSTRAINT candidate_privacy_events_consent_fkey FOREIGN KEY ( + consent_record_id, user_id, consent_purpose + ) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT, + CONSTRAINT candidate_privacy_events_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT candidate_privacy_events_kind_known CHECK ( + kind IN ( + 'publication_opened', 'publication_changed', 'publication_closed', + 'search_status_confirmed', 'search_status_cleared', + 'organization_hidden', 'organization_unhidden' + ) + ), + CONSTRAINT candidate_privacy_events_shape CHECK ( + ( + kind IN ('publication_opened', 'publication_changed') + AND fields IS NOT NULL + AND cardinality(fields) > 0 + AND candidate_card_fields_are_canonical(fields) + AND consent_record_id IS NOT NULL + AND organization_id IS NULL + ) + OR ( + kind = 'publication_closed' + AND fields IS NOT NULL + AND cardinality(fields) = 0 + AND consent_record_id IS NULL + AND organization_id IS NULL + ) + OR ( + kind IN ('search_status_confirmed', 'search_status_cleared') + AND fields IS NULL + AND consent_record_id IS NULL + AND organization_id IS NULL + ) + OR ( + kind IN ('organization_hidden', 'organization_unhidden') + AND fields IS NULL + AND consent_record_id IS NULL + AND organization_id IS NOT NULL + ) + ) +); + +-- Serves the candidate's history, newest first. +CREATE INDEX candidate_privacy_events_user_occurred_idx +ON candidate_privacy_events (user_id, occurred_at DESC, id DESC); + +-- Refuses every UPDATE of an event with SQLSTATE 23000 and the constraint +-- name candidate_privacy_events_immutable. The message quotes no row value. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_immutable', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events are append-only: record a new event instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_refuse_update +BEFORE UPDATE ON candidate_privacy_events +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_update(); + +-- Allows deleting an event only while its account is not confirmed: the +-- unverified account cleanup. The history of a confirmed account is evidence +-- and stays (SQLSTATE 23000, constraint candidate_privacy_events_retained). +-- The retention rule and the right to erasure extend this condition in their +-- own migration. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.user_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_retained', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_refuse_delete +BEFORE DELETE ON candidate_privacy_events +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_delete(); + +-- The cascade of the account deletion runs after the account row is gone, so +-- the delete trigger above cannot see that the account was confirmed. This +-- trigger on users refuses deleting a confirmed account that has history, with +-- the same constraint name, before the cascade starts. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_protect_account() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.email_verified_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM candidate_privacy_events WHERE user_id = OLD.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_retained', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_protect_account +BEFORE DELETE ON users +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_protect_account(); + +-- The only way an organization-facing read may see a publication: published +-- by the candidate AND backed by a C2 record that is not revoked. Every read +-- on behalf of an organization (the search, the card, the contact read) must +-- select from this view and must add NOT EXISTS over +-- candidate_hidden_organizations for the reading organization. Reading +-- candidate_publications directly is reserved for the candidate's own +-- settings queries; a test over db/queries enforces the list. +CREATE VIEW candidate_effective_publications +WITH (security_invoker = true) AS +SELECT + publication.user_id, + publication.fields, + publication.published_at, + publication.version +FROM candidate_publications AS publication +INNER JOIN consent_records AS consent + ON consent.id = publication.consent_record_id +WHERE publication.state = 'published' AND consent.revoked_at IS NULL; + +-- +goose Down +DROP VIEW candidate_effective_publications; +DROP TRIGGER candidate_privacy_events_protect_account ON users; +DROP FUNCTION candidate_privacy_events_protect_account(); +DROP TABLE candidate_privacy_events; +DROP FUNCTION candidate_privacy_events_refuse_delete(); +DROP FUNCTION candidate_privacy_events_refuse_update(); +DROP TABLE candidate_hidden_organizations; +DROP FUNCTION candidate_hidden_organizations_enforce_limit(); +DROP TABLE candidate_search_statuses; +DROP FUNCTION candidate_search_statuses_check_policy(); +DROP TABLE candidate_publications; +DROP INDEX consent_records_id_subject_purpose_key; +DROP FUNCTION candidate_card_fields_are_canonical(text []); diff --git a/backend/db/privacy_queries_test.go b/backend/db/privacy_queries_test.go new file mode 100644 index 0000000..54e3f54 --- /dev/null +++ b/backend/db/privacy_queries_test.go @@ -0,0 +1,81 @@ +package db + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +// directPublicationReaders are the only queries that may name the table +// candidate_publications. The first three are the candidate's own settings +// queries; every read on behalf of an organization must go through the view +// candidate_effective_publications (published and backed by an unrevoked C2) +// and exclude the hidden organizations, as ReadPublicationVisibleToOrganization +// does. A new query that reads the table directly fails this test, so it +// cannot leak a closed or revoked publication by accident. +// +// Only queries/*.sql are covered: the project keeps SQL in sqlc queries and +// migrations, and the standards forbid raw SQL in Go code. +var directPublicationReaders = []string{ + "ReadCandidatePublication", + "InsertCandidatePublication", + "UpdateCandidatePublication", +} + +var ( + // sqlc accepts both comment forms and tolerates trailing whitespace. + queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`) + // Any mention of the marker, to count headers that the pattern missed. + queryMarkerPattern = regexp.MustCompile(`(?i)name:\s*\w+\s+:\w+`) + publicationTableName = regexp.MustCompile(`(?i)\bcandidate_publications\b`) + effectiveViewName = regexp.MustCompile(`(?i)\bcandidate_effective_publications\b`) + hiddenTableName = regexp.MustCompile(`(?i)\bcandidate_hidden_organizations\b`) + lineComment = regexp.MustCompile(`(?m)--.*$`) + blockComment = regexp.MustCompile(`(?s)/\*.*?\*/`) +) + +func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { + files, err := filepath.Glob("queries/*.sql") + if err != nil || len(files) == 0 { + t.Fatalf("list the query files = %v, %v", files, err) + } + var found []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) + if markers := len(queryMarkerPattern.FindAllString(text, -1)); markers != len(headers) { + t.Fatalf("%s has %d query markers but %d parsed headers: use the sqlc header form so every query is checked", file, markers, len(headers)) + } + for index, header := range headers { + end := len(text) + if index+1 < len(headers) { + end = headers[index+1][0] + } + // Comments may name the table; statements may not. + statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") + name := text[header[2]:header[3]] + if publicationTableName.MatchString(statement) { + found = append(found, name) + } + if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) { + t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name) + } + } + } + slices.Sort(found) + want := slices.Clone(directPublicationReaders) + slices.Sort(want) + if !slices.Equal(found, want) { + t.Fatalf("queries that name candidate_publications = %v, want only %v: organization-facing reads use candidate_effective_publications", found, want) + } + if strings.Contains(strings.Join(found, ","), "Visible") { + t.Fatal("the organization-facing read names the table directly") + } +} diff --git a/backend/db/queries/privacy.sql b/backend/db/queries/privacy.sql new file mode 100644 index 0000000..331961f --- /dev/null +++ b/backend/db/queries/privacy.sql @@ -0,0 +1,302 @@ +-- Queries of the candidate visibility settings (TASK-088): the publication of +-- the card, the search status, the hidden organizations, and the history of +-- these settings. Every statement is scoped by the candidate's user_id, and +-- no statement selects another account's row. No statement reads or writes a +-- profile value, a name, or a contact. A candidate with no row is closed, not +-- looking, and hides nobody; no statement creates a row except an explicit +-- act of the candidate. + +-- Reads the publication with the revocation state of the C2 record behind it +-- in one statement, so the stored setting and the ledger come from one +-- snapshot. The effective state is computed from them: published only while +-- consent_revoked_at is NULL. No row means the candidate never published. +-- name: ReadCandidatePublication :one +SELECT + candidate_publications.user_id, + candidate_publications.state, + candidate_publications.fields, + candidate_publications.consent_record_id, + candidate_publications.published_at, + candidate_publications.closed_at, + candidate_publications.version, + candidate_publications.created_at, + candidate_publications.updated_at, + consent_records.revoked_at AS consent_revoked_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE candidate_publications.user_id = sqlc.arg(user_id); + +-- Stores the first publication at version 1. No row returns when the account +-- already has a row, so a first publication that lost a race with another +-- one is answered as a version conflict. The foreign key refuses a record +-- that is not a C2 record of this account. +-- name: InsertCandidatePublication :one +INSERT INTO candidate_publications ( + user_id, + state, + fields, + consent_record_id, + published_at, + closed_at, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(state), + sqlc.arg(fields), + sqlc.arg(consent_record_id), + sqlc.arg(published_at), + sqlc.narg(closed_at), + 1, + sqlc.arg(at), + sqlc.arg(at) +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version; + +-- Replaces the publication over the version the caller read and advances the +-- version in the same statement. No row returns for a stale version, which +-- the caller answers as a version conflict. The update time never moves back, +-- as in the profile. +-- name: UpdateCandidatePublication :one +UPDATE candidate_publications +SET + state = sqlc.arg(state), + fields = sqlc.arg(fields), + consent_record_id = sqlc.arg(consent_record_id), + published_at = sqlc.arg(published_at), + closed_at = sqlc.narg(closed_at), + version = candidate_publications.version + 1, + updated_at = greatest(candidate_publications.updated_at, sqlc.arg(at)) +WHERE + candidate_publications.user_id = sqlc.arg(user_id) + AND candidate_publications.version = sqlc.arg(expected_version) +RETURNING user_id, version; + +-- No row means the status was never set, which reads as not looking. The +-- lapse is computed by the caller from lapses_at and its clock and is never +-- written. +-- name: ReadCandidateSearchStatus :one +SELECT + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +FROM candidate_search_statuses +WHERE user_id = sqlc.arg(user_id); + +-- Stores the first status at version 1; no row returns when one exists. +-- name: InsertCandidateSearchStatus :one +INSERT INTO candidate_search_statuses ( + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(status), + sqlc.narg(confirmed_at), + sqlc.narg(lapses_at), + sqlc.narg(policy_version_id), + 1, + sqlc.arg(at), + sqlc.arg(at) +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version; + +-- Replaces the status over the version the caller read. Looking also stores +-- the new confirmation, lapse time, and policy version; not looking clears +-- them. It never names the publication or the hidden organizations. +-- name: UpdateCandidateSearchStatus :one +UPDATE candidate_search_statuses +SET + status = sqlc.arg(status), + confirmed_at = sqlc.narg(confirmed_at), + lapses_at = sqlc.narg(lapses_at), + policy_version_id = sqlc.narg(policy_version_id), + version = candidate_search_statuses.version + 1, + updated_at = greatest(candidate_search_statuses.updated_at, sqlc.arg(at)) +WHERE + candidate_search_statuses.user_id = sqlc.arg(user_id) + AND candidate_search_statuses.version = sqlc.arg(expected_version) +RETURNING user_id, version; + +-- Hides one organization. No row returns when the pair already exists, and +-- the caller reads the existing record with its original time. The foreign key +-- refuses an unknown organization (SQLSTATE 23503); the caller answers it +-- exactly like an organization the candidate cannot see. The trigger refuses +-- the 1001st record (candidate_hidden_organizations_limit). The trigger runs +-- before the conflict check, so the caller reads the existing record first +-- and a repeat at the limit is never refused. +-- name: InsertCandidateHiddenOrganization :one +INSERT INTO candidate_hidden_organizations ( + user_id, + organization_id, + hidden_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(organization_id), + sqlc.arg(at) +) +ON CONFLICT (user_id, organization_id) DO NOTHING +RETURNING user_id, organization_id, hidden_at; + +-- Reads one hiding of the candidate with the current name of the +-- organization. +-- name: GetCandidateHiddenOrganization :one +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND candidate_hidden_organizations.organization_id = sqlc.arg(organization_id); + +-- Lifts one hiding. No row returns when the organization was not hidden, so +-- the caller writes the history event only for a real deletion and answers +-- 204 either way. +-- name: DeleteCandidateHiddenOrganization :one +DELETE FROM candidate_hidden_organizations +WHERE user_id = sqlc.arg(user_id) AND organization_id = sqlc.arg(organization_id) +RETURNING organization_id; + +-- 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. +-- name: ListCandidateHiddenOrganizations :many +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_hidden_at)::timestamptz IS NULL + OR ( + candidate_hidden_organizations.hidden_at, + candidate_hidden_organizations.organization_id + ) < ( + sqlc.narg(after_hidden_at)::timestamptz, + sqlc.narg(after_organization_id)::uuid + ) + ) +ORDER BY + candidate_hidden_organizations.hidden_at DESC, + candidate_hidden_organizations.organization_id DESC +LIMIT sqlc.arg(row_limit); + +-- Counts the hiding records of one candidate for the settings read. +-- name: CountCandidateHiddenOrganizations :one +SELECT count(*) AS total +FROM candidate_hidden_organizations +WHERE user_id = sqlc.arg(user_id); + +-- Appends one event to the settings history. The row holds identifiers, card +-- field codes, and times, never a name; the caller +-- writes it in the transaction of the change it records. +-- name: InsertCandidatePrivacyEvent :exec +INSERT INTO candidate_privacy_events ( + id, + user_id, + kind, + occurred_at, + fields, + consent_record_id, + organization_id +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(occurred_at), + sqlc.narg(fields), + sqlc.narg(consent_record_id), + sqlc.narg(organization_id) +); + +-- 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 +-- (occurred_at, id) position of the last event of the previous page. +-- name: ListCandidatePrivacyEvents :many +SELECT + candidate_privacy_events.id, + candidate_privacy_events.kind, + candidate_privacy_events.occurred_at, + candidate_privacy_events.fields, + candidate_privacy_events.consent_record_id, + candidate_privacy_events.organization_id, + organizations.name AS organization_name +FROM candidate_privacy_events +LEFT JOIN organizations + ON organizations.id = candidate_privacy_events.organization_id +WHERE + candidate_privacy_events.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (candidate_privacy_events.occurred_at, candidate_privacy_events.id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY + candidate_privacy_events.occurred_at DESC, + candidate_privacy_events.id DESC +LIMIT sqlc.arg(row_limit); + +-- Takes the candidate's current unrevoked C2 record for a publication and +-- keeps it locked until the transaction ends. The share lock conflicts with +-- the revocation stamp (an UPDATE of the row), so a revocation either commits +-- before this statement, which then returns no row and the publication is +-- refused, or waits until the publication transaction commits and closes the +-- card right after. The caller must run it in the transaction that writes the +-- publication and must re-read the effective state (ReadCandidatePublication) +-- in that transaction to build its response. +-- name: LockCurrentC2Record :one +SELECT id +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c2' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +FOR SHARE; + +-- The organization-facing read of a candidate's publication: the effective +-- view (published and backed by an unrevoked C2) and no hiding of the reading +-- organization. No row means the organization reads nothing, whichever of +-- the reasons applies, so it cannot tell a hidden candidate from an +-- unpublished one. Every organization-facing read of a publication starts +-- from this shape (TASK-185, TASK-089, TASK-090). +-- name: ReadPublicationVisibleToOrganization :one +SELECT + effective.user_id, + effective.fields, + effective.published_at +FROM candidate_effective_publications AS effective +WHERE + effective.user_id = sqlc.arg(user_id) + 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) + ); diff --git a/backend/integration_test/candidate_privacy_test.go b/backend/integration_test/candidate_privacy_test.go new file mode 100644 index 0000000..9f57433 --- /dev/null +++ b/backend/integration_test/candidate_privacy_test.go @@ -0,0 +1,1056 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/policy" +) + +const ( + candidatePrivacyTestTimeout = 3 * time.Minute + privacyForeignKeyViolation = "23503" + privacyCheckViolation = "23514" + privacyIntegrityViolation = "23000" + privacyC2Version = "c2-2026-10-01" + privacyC1Version = "c1-2026-10-01" +) + +var ( + candidatePublicationsTable = pgx.Identifier{"candidate_publications"} + candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"} + candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"} + candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"} + // candidatePrivacyTables reference users, organizations, and the consent + // ledger, so every TRUNCATE of those names them through + // usersDependentTables. + candidatePrivacyTables = []pgx.Identifier{ + candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, candidateSearchStatusesTable, candidatePublicationsTable, + } +) + +// candidatePrivacyFixture works on the bootstrap database. The tables are +// truncated between subtests; the product policy is immutable and shared. +type candidatePrivacyFixture struct { + ctx context.Context + pool *pgxpool.Pool + queries *sqlc.Queries + identity identityFixture + organizations organizationFixture + ledger *postgresadapter.ConsentStore + policy domain.PolicyVersion + now time.Time +} + +func TestCandidatePrivacyStorage(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + policies := postgresadapter.NewPolicyStore(pool) + if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + latest, err := policies.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil { + t.Fatalf("GetLatest(product) error = %v", err) + } + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now}, + ledger: postgresadapter.NewConsentStore(pool), + policy: latest, + now: now, + } + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("a new profile has no published state and nothing hidden", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + // Saving a full profile, as the profile contract does, opens nothing. + profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now} + profiles.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna Sokolova")}, 0) + + for _, table := range candidatePrivacyTables { + assertRowCount(ctx, t, pool, table, 0) + } + if _, err := fixture.queries.ReadCandidatePublication(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("ReadCandidatePublication() error = %v, want no row: the profile is closed by default", err) + } + if _, err := fixture.queries.ReadCandidateSearchStatus(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("ReadCandidateSearchStatus() error = %v, want no row", err) + } + if total, err := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); err != nil || total != 0 { + t.Fatalf("CountCandidateHiddenOrganizations() = %d, %v, want 0", total, err) + } + // The domain reads the absence as a closed profile at version 0. + closed, err := domain.NewPublication(candidate.ID) + if err != nil || closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedNeverPublished || closed.Version() != 0 { + t.Fatalf("NewPublication() = %v %v v%d, %v, want closed and never published", closed.State(), closed.ClosedReason(), closed.Version(), err) + } + }) + + t.Run("publication refers to the C2 record and a revocation closes it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack, domain.CardFieldCategories) + if published.State() != domain.PublicationPublished || published.Version() != 1 || published.ConsentRecordID() != c2.ID() || + !published.Fields().Equal(domainFields(t, domain.CardFieldCategories, domain.CardFieldStack)) { + t.Fatalf("stored publication = %v v%d, want published at version 1 under the C2 record", published.State(), published.Version()) + } + + // Revoking C2 in the ledger closes the card with no write to the setting. + before := fixture.rawPublication(t, candidate.ID) + fixture.revokeC2(t, candidate.ID, now) + if after := fixture.rawPublication(t, candidate.ID); after != before { + t.Fatalf("revoking C2 changed the stored publication: %+v -> %+v", before, after) + } + revoked := fixture.loadPublication(t, candidate.ID) + if revoked.State() != domain.PublicationClosed || revoked.ClosedReason() != domain.ClosedConsentRevoked || !revoked.Fields().IsEmpty() { + t.Fatalf("after the revocation = %v (%v), want closed because the consent was revoked", revoked.State(), revoked.ClosedReason()) + } + + // A new C2 grant publishes nothing by itself. + newC2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Minute)) + if again := fixture.loadPublication(t, candidate.ID); again.State() != domain.PublicationClosed { + t.Fatalf("a new C2 grant left the card %v, want closed until the candidate publishes again", again.State()) + } + reopened := fixture.publish(t, candidate.ID, newC2.ID(), 1, domain.CardFieldStack) + if reopened.State() != domain.PublicationPublished || reopened.ConsentRecordID() != newC2.ID() || reopened.Version() != 2 { + t.Fatalf("republished = %v v%d under %s, want the new record at version 2", reopened.State(), reopened.Version(), reopened.ConsentRecordID()) + } + + // Closing is an explicit change that keeps the evidence. + change, err := reopened.Apply(mustPublicationRequest(t, domain.PublicationClosed), 2, uuid.Nil, now.Add(time.Hour)) + if err != nil || !change.Changed { + t.Fatalf("Apply(close) = %+v, %v", change, err) + } + fixture.storePublication(t, change.Publication, 2) + closed := fixture.loadPublication(t, candidate.ID) + if closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 3 || !closed.PublishedAt().Equal(reopened.PublishedAt()) { + t.Fatalf("closed = %v (%v) v%d, want closed by the candidate with the last publication time", closed.State(), closed.ClosedReason(), closed.Version()) + } + }) + + t.Run("the publication row refuses a consent that is not the account's C2 and fields that are not card fields", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + other := fixture.candidate(t, "other@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + otherC2 := fixture.grant(t, other.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + c1 := fixture.grant(t, candidate.ID, domain.ConsentPurposePersonalData, privacyC1Version, now.Add(-time.Hour)) + + insert := func(user uuid.UUID, consent uuid.UUID, state string, fields []string, closedAt pgtype.Timestamptz) error { + _, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(user), State: state, Fields: fields, ConsentRecordID: uuidParam(consent), + PublishedAt: timeParam(now), ClosedAt: closedAt, At: timeParam(now), + }) + return err + } + for _, test := range []struct { + name string + err error + sqlstate string + }{ + {"another account's C2", insert(candidate.ID, otherC2.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"a C1 record", insert(candidate.ID, c1.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"an unknown record", insert(candidate.ID, uuid.New(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"the full name as a field", insert(candidate.ID, c2.ID(), "published", []string{"full_name"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"a phone as a field", insert(candidate.ID, c2.ID(), "published", []string{"phone"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"fields out of order", insert(candidate.ID, c2.ID(), "published", []string{"stack", "categories"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"a repeated field", insert(candidate.ID, c2.ID(), "published", []string{"stack", "stack"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"published without a field", insert(candidate.ID, c2.ID(), "published", []string{}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"closed with a field", insert(candidate.ID, c2.ID(), "closed", []string{"stack"}, timeParam(now)), privacyCheckViolation}, + {"an unknown state", insert(candidate.ID, c2.ID(), "draft", []string{"stack"}, pgtype.Timestamptz{}), privacyCheckViolation}, + } { + if code := sqlState(test.err); code != test.sqlstate { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate) + } + } + assertRowCount(ctx, t, pool, candidatePublicationsTable, 0) + + // A C2 record that a publication refers to cannot be deleted. + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, c2.ID()) + if code := sqlState(err); code == "" { + t.Fatal("a C2 record behind a publication was deleted") + } + }) + + t.Run("a stale version updates nothing and a first publication is created once", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + + _, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: uuidParam(c2.ID()), + PublishedAt: timeParam(now), At: timeParam(now), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a second first-publication error = %v, want no row", err) + } + _, err = fixture.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), ExpectedVersion: 0, State: "published", Fields: []string{"location"}, ConsentRecordID: uuidParam(c2.ID()), + PublishedAt: timeParam(now), At: timeParam(now), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("an update over a stale version error = %v, want no row", err) + } + if got := fixture.loadPublication(t, candidate.ID); got.Version() != 1 || !got.Fields().Equal(domainFields(t, domain.CardFieldStack)) { + t.Fatal("a stale update changed the publication") + } + }) + + t.Run("looking stores its confirmation under the policy version and lapses without a write", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + status := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now) + if status.StoredValue() != domain.SearchStatusLooking || !status.ConfirmedAt().Equal(now) || status.PolicyVersionID() != fixture.policy.ID() || status.Version() != 1 { + t.Fatalf("stored status = %v confirmed %v under %v, want looking confirmed now under the policy version", status.StoredValue(), status.ConfirmedAt(), status.PolicyVersionID()) + } + // The interval is the one of the policy version, 30 days in the demo. + interval := fixture.policy.Policy().SearchStatus.SearchingConfirmationInterval.Duration() + if !status.LapsesAt().Equal(now.Add(interval)) { + t.Fatalf("lapses at %v, want %v", status.LapsesAt(), now.Add(interval)) + } + + before := fixture.rawSearchStatus(t, candidate.ID) + lapsedAt := status.LapsesAt().Add(time.Second) + if loaded := fixture.loadSearchStatus(t, candidate.ID); loaded.Effective(lapsedAt) != domain.SearchStatusNotLooking || !loaded.Lapsed(lapsedAt) || loaded.Effective(now) != domain.SearchStatusLooking { + t.Fatal("the stored status does not lapse at its lapse time") + } + if fixture.rawSearchStatus(t, candidate.ID) != before { + t.Fatal("a lapse changed the stored status: it must be computed, never written") + } + + // Confirming again after the lapse is an explicit change over the current version. + confirmed := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, lapsedAt) + if confirmed.Version() != 2 || !confirmed.ConfirmedAt().Equal(lapsedAt) || confirmed.Effective(lapsedAt) != domain.SearchStatusLooking { + t.Fatalf("confirmed again = v%d %v, want version 2 and looking", confirmed.Version(), confirmed.Effective(lapsedAt)) + } + cleared := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, lapsedAt.Add(time.Hour)) + if cleared.StoredValue() != domain.SearchStatusNotLooking || !cleared.ConfirmedAt().IsZero() || cleared.Version() != 3 { + t.Fatalf("cleared = %v v%d, want not_looking carrying no confirmation", cleared.StoredValue(), cleared.Version()) + } + }) + + t.Run("the status row refuses a looking without its confirmation and has no link to a consent", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + insert := func(status string, confirmed, lapses pgtype.Timestamptz, policyID pgtype.UUID) error { + _, err := fixture.queries.InsertCandidateSearchStatus(ctx, sqlc.InsertCandidateSearchStatusParams{ + UserID: uuidParam(candidate.ID), Status: status, ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(now), + }) + return err + } + policyID := uuidParam(fixture.policy.ID().UUID()) + for _, test := range []struct { + name string + err error + sqlstate string + }{ + {"looking without a confirmation", insert("looking", pgtype.Timestamptz{}, pgtype.Timestamptz{}, policyID), privacyCheckViolation}, + {"looking without a lapse time", insert("looking", timeParam(now), pgtype.Timestamptz{}, policyID), privacyCheckViolation}, + {"looking that lapses before it is confirmed", insert("looking", timeParam(now), timeParam(now.Add(-time.Hour)), policyID), privacyCheckViolation}, + {"looking without a policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), pgtype.UUID{}), privacyCheckViolation}, + {"looking under an unknown policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), uuidParam(uuid.New())), privacyForeignKeyViolation}, + {"not looking with a confirmation", insert("not_looking", timeParam(now), timeParam(now.Add(time.Hour)), policyID), privacyCheckViolation}, + {"an unknown status", insert("open", pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{}), privacyCheckViolation}, + } { + if code := sqlState(test.err); code != test.sqlstate { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate) + } + } + + // The status is not a consent: its only foreign key is the account; the policy version is checked by a trigger. + rows, err := pool.Query(ctx, ` + SELECT confrelid::regclass::text FROM pg_constraint + WHERE conrelid = 'candidate_search_statuses'::regclass AND contype = 'f' ORDER BY 1`) + if err != nil { + t.Fatalf("list the foreign keys: %v", err) + } + references, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil || !slices.Equal(references, []string{"users"}) { + t.Fatalf("candidate_search_statuses references %v (%v), want only users (the policy version is checked by a trigger)", references, err) + } + var consentColumns int + if err := pool.QueryRow(ctx, ` + SELECT count(*) FROM information_schema.columns + WHERE table_name IN ('candidate_search_statuses', 'candidate_hidden_organizations') AND column_name LIKE '%consent%'`).Scan(&consentColumns); err != nil || consentColumns != 0 { + t.Fatalf("the status and hiding tables have %d consent columns (%v), want none", consentColumns, err) + } + }) + + t.Run("the search status leaves C2, the publication, and the hidden organizations as they were", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldCategories, domain.CardFieldLocation) + fixture.hide(t, candidate.ID, organization.ID(), now) + + consentBefore := fixture.rawConsentRecords(t, candidate.ID) + publicationBefore := fixture.rawPublication(t, candidate.ID) + hiddenBefore := fixture.rawHidden(t, candidate.ID) + + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now.Add(time.Minute)) + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, now.Add(2*time.Minute)) + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, now.Add(3*time.Minute)) + + if fixture.rawConsentRecords(t, candidate.ID) != consentBefore { + t.Error("updating the search status changed the consent ledger") + } + if fixture.rawPublication(t, candidate.ID) != publicationBefore { + t.Error("updating the search status changed the publication") + } + if fixture.rawHidden(t, candidate.ID) != hiddenBefore { + t.Error("updating the search status changed the hidden organizations") + } + if published := fixture.loadPublication(t, candidate.ID); published.State() != domain.PublicationPublished || published.Version() != 1 { + t.Fatal("updating the search status changed the effective publication") + } + }) + + t.Run("a hidden organization belongs to the candidate and is unique", func(t *testing.T) { + reset(t) + first := fixture.candidate(t, "first@example.com") + second := fixture.candidate(t, "second@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now) + + fixture.hide(t, first.ID, acme.ID(), now) + // The pair is unique: a second insert returns no row and keeps the original time. + _, err := fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID()), At: timeParam(now.Add(time.Hour)), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("hiding the same organization twice error = %v, want no row", err) + } + record, err := fixture.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())}) + if err != nil || !record.HiddenAt.Time.Equal(now) || record.OrganizationName != "Acme Synthetic LLC" { + t.Fatalf("GetCandidateHiddenOrganization() = %+v, %v, want the original record with the current name", record, err) + } + if _, err := fixture.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, first.ID, acme.ID(), now); sqlState(err) != organizationUniqueViolation { + t.Fatalf("a raw duplicate hiding SQLSTATE = %q, want %s", sqlState(err), organizationUniqueViolation) + } + + // Another candidate hides the same organization independently and reads only their own records. + fixture.hide(t, second.ID, acme.ID(), now.Add(time.Minute)) + fixture.hide(t, second.ID, globex.ID(), now.Add(2*time.Minute)) + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(first.ID)); total != 1 { + t.Fatalf("the first candidate has %d hidden organizations, want 1", total) + } + page, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{UserID: uuidParam(second.ID), RowLimit: 1}) + if err != nil || len(page) != 1 || uuid.UUID(page[0].OrganizationID.Bytes) != globex.ID() { + t.Fatalf("first page = %+v, %v, want the newest hiding", page, err) + } + next, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{ + UserID: uuidParam(second.ID), RowLimit: 10, AfterHiddenAt: page[0].HiddenAt, AfterOrganizationID: page[0].OrganizationID, + }) + if err != nil || len(next) != 1 || uuid.UUID(next[0].OrganizationID.Bytes) != acme.ID() { + t.Fatalf("next page = %+v, %v, want the older hiding", next, err) + } + + // An unknown organization is refused by the reference, and the caller + // answers it as it answers an organization the candidate cannot see. + _, err = fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(first.ID), OrganizationID: uuidParam(uuid.New()), At: timeParam(now), + }) + if sqlState(err) != privacyForeignKeyViolation { + t.Fatalf("hiding an unknown organization SQLSTATE = %q, want %s", sqlState(err), privacyForeignKeyViolation) + } + // Lifting a hiding deletes it once; a repeat deletes nothing. + lift := sqlc.DeleteCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())} + if deleted, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); err != nil || uuid.UUID(deleted.Bytes) != acme.ID() { + t.Fatalf("DeleteCandidateHiddenOrganization() = %v, %v, want the organization", deleted, err) + } + if _, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a repeated delete error = %v, want no row", err) + } + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(second.ID)); total != 2 { + t.Fatalf("lifting the first candidate's hiding left the second with %d records, want 2", total) + } + // The organization cannot be deleted while a candidate hides it. + if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, globex.ID()); sqlState(err) == "" { + t.Fatal("an organization that a candidate hides was deleted") + } + }) + + t.Run("a candidate hides at most 1000 organizations", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + limit := domain.MaxHiddenOrganizations + // The organizations are created in bulk with one owner; the deferred + // owner trigger sees the membership of the same transaction. + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit+1); err != nil { + t.Fatalf("create organizations: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil { + t.Fatalf("create memberships: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3`, candidate.ID, now, limit); err != nil { + t.Fatalf("hide %d organizations: %v", limit, err) + } + _, err = tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id DESC LIMIT 1 OFFSET 0`, candidate.ID, now) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyCheckViolation || pgError.ConstraintName != "candidate_hidden_organizations_limit" { + t.Fatalf("hiding organization %d error = %v, want SQLSTATE %s on candidate_hidden_organizations_limit", limit+1, err, privacyCheckViolation) + } + }) + + t.Run("the history is append-only and keeps the published fields with their times", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + change, err := published.Apply(mustPublicationRequest(t, domain.PublicationPublished, domain.CardFieldStack, domain.CardFieldLocation), 1, c2.ID(), now.Add(time.Minute)) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + fixture.storePublication(t, change.Publication, 1) + fixture.recordPublicationEvent(t, change, now.Add(time.Minute)) + fixture.hide(t, candidate.ID, organization.ID(), now.Add(2*time.Minute)) + + page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10}) + if err != nil || len(page) != 3 { + t.Fatalf("ListCandidatePrivacyEvents() = %d rows, %v, want 3", len(page), err) + } + kinds := []string{page[0].Kind, page[1].Kind, page[2].Kind} + if !slices.Equal(kinds, []string{"organization_hidden", "publication_changed", "publication_opened"}) { + t.Fatalf("event kinds = %v, want newest first", kinds) + } + if !slices.Equal(page[1].Fields, []string{"location", "stack"}) || uuid.UUID(page[1].ConsentRecordID.Bytes) != c2.ID() || !page[1].OccurredAt.Time.Equal(now.Add(time.Minute)) { + t.Fatalf("the change event = %v under %v at %v, want the published fields, the C2 record, and the time", page[1].Fields, page[1].ConsentRecordID, page[1].OccurredAt.Time) + } + if page[0].OrganizationName.String != "Acme Synthetic LLC" { + t.Fatalf("the hiding event names %q, want the current name resolved at read time", page[0].OrganizationName.String) + } + var nameColumns int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'candidate_privacy_events' AND column_name LIKE '%name%'`).Scan(&nameColumns); err != nil || nameColumns != 0 { + t.Fatalf("the history table has %d name columns (%v), want none: it stores identifiers only", nameColumns, err) + } + // Pagination continues after the position of the last row. + next, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{ + UserID: uuidParam(candidate.ID), RowLimit: 10, AfterOccurredAt: page[0].OccurredAt, AfterID: page[0].ID, + }) + if err != nil || len(next) != 2 { + t.Fatalf("next page = %d rows, %v, want 2", len(next), err) + } + + // Append-only: no UPDATE, and no DELETE once the account is confirmed. + for _, test := range []struct{ statement, constraint string }{ + {`UPDATE candidate_privacy_events SET occurred_at = occurred_at + interval '1 hour'`, "candidate_privacy_events_immutable"}, + } { + _, err := pool.Exec(ctx, test.statement) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyIntegrityViolation || pgError.ConstraintName != test.constraint { + t.Fatalf("%q error = %v, want SQLSTATE %s on %s", test.statement, err, privacyIntegrityViolation, test.constraint) + } + } + if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $2 WHERE id = $1`, candidate.ID, now); err != nil { + t.Fatalf("confirm the account: %v", err) + } + _, err = pool.Exec(ctx, `DELETE FROM candidate_privacy_events`) + var retained *pgconn.PgError + if !errors.As(err, &retained) || retained.Code != privacyIntegrityViolation || retained.ConstraintName != "candidate_privacy_events_retained" { + t.Fatalf("deleting the history of a confirmed account error = %v, want SQLSTATE %s on candidate_privacy_events_retained", err, privacyIntegrityViolation) + } + for name, params := range map[string]sqlc.InsertCandidatePrivacyEventParams{ + "a publication without fields": {Kind: "publication_opened", Fields: []string{}, ConsentRecordID: uuidParam(c2.ID())}, + "a publication without a consent": {Kind: "publication_changed", Fields: []string{"stack"}}, + "a hiding without an organization": {Kind: "organization_hidden"}, + "a status event with an organization": {Kind: "search_status_cleared", OrganizationID: uuidParam(organization.ID())}, + "a closing with a field": {Kind: "publication_closed", Fields: []string{"stack"}}, + "an unknown kind": {Kind: "published"}, + } { + params.ID, params.UserID, params.OccurredAt = uuidParam(uuid.Must(uuid.NewV7())), uuidParam(candidate.ID), timeParam(now) + if err := fixture.queries.InsertCandidatePrivacyEvent(ctx, params); sqlState(err) != privacyCheckViolation { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", name, sqlState(err), err, privacyCheckViolation) + } + } + // An account with history cannot be deleted until a procedure handles it. + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); sqlState(err) == "" { + t.Fatal("an account with consent and privacy history was deleted") + } + }) + + t.Run("closing over a revoked C2 stores the closing and records it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + fixture.revokeC2(t, candidate.ID, now) + + revoked := fixture.loadPublication(t, candidate.ID) + change, err := revoked.Apply(mustPublicationRequest(t, domain.PublicationClosed), 1, uuid.Nil, now.Add(time.Minute)) + if err != nil || !change.Changed || change.Event != domain.PrivacyEventPublicationClosed { + t.Fatalf("Apply(close over a revoked C2) = %+v, %v, want a recorded closing", change, err) + } + fixture.storePublication(t, change.Publication, 1) + fixture.recordPublicationEvent(t, change, now.Add(time.Minute)) + + var stored string + if err := pool.QueryRow(ctx, `SELECT state FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&stored); err != nil || stored != "closed" { + t.Fatalf("stored state = %q (%v), want the row normalized to closed", stored, err) + } + if closed := fixture.loadPublication(t, candidate.ID); closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 2 { + t.Fatalf("closed = %v v%d, want closed by the candidate at version 2", closed.ClosedReason(), closed.Version()) + } + page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10}) + if err != nil || len(page) != 2 || page[0].Kind != "publication_closed" { + t.Fatalf("history = %d rows, %v, want the closing newest", len(page), err) + } + }) + + t.Run("an organization reads a publication only through the effective view and not when hidden", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now) + read := func(organization uuid.UUID) error { + _, err := fixture.queries.ReadPublicationVisibleToOrganization(ctx, sqlc.ReadPublicationVisibleToOrganizationParams{ + UserID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization), + }) + return err + } + if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a closed-by-default profile read error = %v, want no row", err) + } + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + if err := read(acme.ID()); err != nil { + t.Fatalf("a published profile read error = %v, want a row", err) + } + fixture.hide(t, candidate.ID, acme.ID(), now) + if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a hidden organization read error = %v, want no row, the same as an unpublished profile", err) + } + if err := read(globex.ID()); err != nil { + t.Fatalf("another organization read error = %v, want a row", err) + } + fixture.revokeC2(t, candidate.ID, now) + if err := read(globex.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a read after the C2 revocation error = %v, want no row", err) + } + _ = published + }) + + t.Run("a revocation racing with a publication either refuses it or closes the card after it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + // The publication holds the share lock: the revocation waits for it. + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + locked, err := fixture.queries.WithTx(tx).LockCurrentC2Record(ctx, uuidParam(candidate.ID)) + if err != nil || uuid.UUID(locked.Bytes) != c2.ID() { + t.Fatalf("LockCurrentC2Record() = %v, %v, want the C2 record", locked, err) + } + if _, err := fixture.queries.WithTx(tx).InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: locked, PublishedAt: timeParam(now), At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidatePublication() error = %v", err) + } + revoked := make(chan error, 1) + go func() { + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: candidate.ID, Purpose: domain.ConsentPurposePublication, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now.Add(time.Minute), + }) + if err == nil { + _, err = fixture.ledger.ConsentLedger().Revoke(ctx, revocation) + } + revoked <- err + }() + select { + case err := <-revoked: + t.Fatalf("the revocation did not wait for the publication transaction (error = %v)", err) + case <-time.After(300 * time.Millisecond): + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit: %v", err) + } + if err := <-revoked; err != nil { + t.Fatalf("the revocation error = %v", err) + } + if after := fixture.loadPublication(t, candidate.ID); after.State() != domain.PublicationClosed || after.ClosedReason() != domain.ClosedConsentRevoked { + t.Fatalf("after the race = %v (%v), want closed because the consent was revoked", after.State(), after.ClosedReason()) + } + + // A revocation that committed first leaves nothing to lock: the publication is refused. + if _, err := fixture.queries.LockCurrentC2Record(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("LockCurrentC2Record() after the revocation error = %v, want no row", err) + } + }) + + t.Run("the unverified account cleanup removes its hidden organizations and history and spares a confirmed account", func(t *testing.T) { + reset(t) + stale := fixture.candidate(t, "stale@example.com") + confirmed := fixture.candidate(t, "confirmed@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + fixture.hide(t, stale.ID, acme.ID(), now) + fixture.hide(t, confirmed.ID, acme.ID(), now) + if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $3 WHERE id = ANY($1) OR id = $2`, []uuid.UUID{confirmed.ID}, employer.ID, now); err != nil { + t.Fatalf("confirm the accounts: %v", err) + } + deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10}) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the one unverified account", deleted, err) + } + assertRowCount(ctx, t, pool, candidateHiddenOrganizationsTable, 1) + assertRowCount(ctx, t, pool, candidatePrivacyEventsTable, 1) + // A confirmed account is not deleted through the history either. + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, confirmed.ID); sqlState(err) == "" { + t.Fatal("a confirmed account with privacy history was deleted") + } + }) + + t.Run("the cleanup deletes unverified accounts with a C2, a publication, and history, whatever the C2 history", func(t *testing.T) { + reset(t) + // The cleanup deletes the consent records and the account in one + // statement of data-modifying CTEs. The cascade from the account to the + // publication, which the restricting reference to the C2 record would + // block, depends on the order in which PostgreSQL applies them; this + // scenario fails if a change to the statement or to the references + // breaks that order. + full := fixture.candidate(t, "full@example.com") + fullC2 := fixture.grant(t, full.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, full.ID, fullC2.ID(), 0, domain.CardFieldStack) + + regranted := fixture.candidate(t, "regranted@example.com") + oldC2 := fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-2*time.Hour)) + fixture.publish(t, regranted.ID, oldC2.ID(), 0, domain.CardFieldLocation) + fixture.revokeC2(t, regranted.ID, now.Add(-time.Hour)) + fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-30*time.Minute)) + + consentOnly := fixture.candidate(t, "consent-only@example.com") + fixture.grant(t, consentOnly.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10}) + if err != nil || deleted != 3 { + t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the three unverified accounts", deleted, err) + } + for _, table := range slices.Concat(candidatePrivacyTables, []pgx.Identifier{consentRecordsTable, {"users"}}) { + assertRowCount(ctx, t, pool, table, 0) + } + }) + + t.Run("concurrent hidings at the bound let exactly one through", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + const parallel = 8 + limit := domain.MaxHiddenOrganizations + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1 FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel); err != nil { + t.Fatalf("create organizations: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil { + t.Fatalf("create memberships: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM (SELECT id FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3) AS first`, candidate.ID, now, limit-1); err != nil { + t.Fatalf("hide %d organizations: %v", limit-1, err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit: %v", err) + } + rows, err := pool.Query(ctx, ` + SELECT id FROM organizations WHERE name LIKE 'Bulk %' AND id NOT IN (SELECT organization_id FROM candidate_hidden_organizations)`) + if err != nil { + t.Fatalf("list the free organizations: %v", err) + } + free, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID]) + if err != nil || len(free) != parallel { + t.Fatalf("free organizations = %d, %v, want %d", len(free), err, parallel) + } + results := make([]error, parallel) + var wait sync.WaitGroup + for index := range parallel { + wait.Add(1) + go func() { + defer wait.Done() + _, results[index] = pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, free[index], now) + }() + } + wait.Wait() + succeeded := 0 + for _, err := range results { + var pgError *pgconn.PgError + switch { + case err == nil: + succeeded++ + case errors.As(err, &pgError) && pgError.ConstraintName == "candidate_hidden_organizations_limit": + default: + t.Fatalf("a concurrent hiding error = %v, want success or the limit", err) + } + } + if succeeded != 1 { + t.Fatalf("%d concurrent hidings succeeded at the bound, want exactly 1", succeeded) + } + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); int(total) != limit { + t.Fatalf("hidden organizations = %d, want exactly %d", total, limit) + } + }) + + t.Run("the privacy tables hold no profile value, name, contact, or file", func(t *testing.T) { + rows, err := pool.Query(ctx, ` + SELECT table_name || '.' || column_name FROM information_schema.columns + WHERE table_schema = 'public' AND table_name LIKE 'candidate\_%' AND table_name IN ( + 'candidate_publications', 'candidate_search_statuses', 'candidate_hidden_organizations', 'candidate_privacy_events') + ORDER BY 1`) + if err != nil { + t.Fatalf("list the columns: %v", err) + } + columns, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("collect the columns: %v", err) + } + for _, column := range columns { + for _, forbidden := range []string{"email", "phone", "telegram", "contact", "full_name", "salary", "resume", "file", "value", "claim"} { + if containsWord(column, forbidden) { + t.Errorf("the column %s looks like %q", column, forbidden) + } + } + } + }) +} + +func containsWord(column, word string) bool { + for _, part := range splitIdentifier(column) { + if part == word { + return true + } + } + return false +} + +func splitIdentifier(identifier string) []string { + var parts []string + start := 0 + for index, character := range identifier { + if character == '_' || character == '.' { + parts = append(parts, identifier[start:index]) + start = index + 1 + } + } + return append(parts, identifier[start:]) +} + +func sqlState(err error) string { + var pgError *pgconn.PgError + if errors.As(err, &pgError) { + return pgError.Code + } + return "" +} + +func uuidParam(id uuid.UUID) pgtype.UUID { return pgtype.UUID{Bytes: id, Valid: true} } + +func timeParam(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} } + +func domainFields(t *testing.T, fields ...domain.CardField) domain.CardFieldSet { + t.Helper() + set, err := domain.NewCardFieldSet(fields) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + return set +} + +func mustPublicationRequest(t *testing.T, state domain.PublicationState, fields ...domain.CardField) domain.PublicationRequest { + t.Helper() + request, err := domain.NewPublicationRequest(state, fields) + if err != nil { + t.Fatalf("NewPublicationRequest() error = %v", err) + } + return request +} + +func (fixture candidatePrivacyFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-24*time.Hour)) +} + +func (fixture candidatePrivacyFixture) grant(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, version domain.ConsentTextVersion, at time.Time) domain.ConsentRecord { + t.Helper() + text, err := fixture.ledger.ConsentTexts().Get(fixture.ctx, purpose, version) + if err != nil { + t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err) + } + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), + Source: domain.ConsentSourceConsentSettings, GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + record, created, err := fixture.ledger.ConsentLedger().Grant(fixture.ctx, grant) + if err != nil || !created { + t.Fatalf("Grant(%s) = %v, %v, want a new record", purpose, created, err) + } + return record +} + +func (fixture candidatePrivacyFixture) revokeC2(t *testing.T, subject uuid.UUID, at time.Time) { + t.Helper() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: domain.ConsentPurposePublication, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + if revoked, err := fixture.ledger.ConsentLedger().Revoke(fixture.ctx, revocation); err != nil || len(revoked) == 0 { + t.Fatalf("Revoke(c2) = %v, %v, want the record", revoked, err) + } +} + +// loadPublication reads the stored setting with its ledger state the way a +// repository does and returns the closed default when there is no row. +func (fixture candidatePrivacyFixture) loadPublication(t *testing.T, userID uuid.UUID) domain.Publication { + t.Helper() + row, err := fixture.queries.ReadCandidatePublication(fixture.ctx, uuidParam(userID)) + if errors.Is(err, pgx.ErrNoRows) { + publication, err := domain.NewPublication(userID) + if err != nil { + t.Fatalf("NewPublication() error = %v", err) + } + return publication + } + if err != nil { + t.Fatalf("ReadCandidatePublication() error = %v", err) + } + publication, err := domain.RestorePublication(domain.StoredPublication{ + UserID: userID, State: row.State, Fields: row.Fields, ConsentRecordID: row.ConsentRecordID.Bytes, + PublishedAt: row.PublishedAt.Time, ClosedAt: row.ClosedAt.Time, Version: row.Version, ConsentRevoked: row.ConsentRevokedAt.Valid, + }) + if err != nil { + t.Fatalf("RestorePublication() error = %v", err) + } + return publication +} + +// publish applies a publication request over expectedVersion with the given +// C2 record and stores the result the way a repository does. +func (fixture candidatePrivacyFixture) publish(t *testing.T, userID, consent uuid.UUID, expectedVersion int64, fields ...domain.CardField) domain.Publication { + t.Helper() + current := fixture.loadPublication(t, userID) + change, err := current.Apply(mustPublicationRequest(t, domain.PublicationPublished, fields...), expectedVersion, consent, fixture.now) + if err != nil || !change.Changed { + t.Fatalf("Apply(publish) = %+v, %v, want a change", change, err) + } + fixture.storePublication(t, change.Publication, expectedVersion) + fixture.recordPublicationEvent(t, change, fixture.now) + return fixture.loadPublication(t, userID) +} + +func (fixture candidatePrivacyFixture) storePublication(t *testing.T, publication domain.Publication, expectedVersion int64) { + t.Helper() + closedAt := pgtype.Timestamptz{} + if !publication.ClosedAt().IsZero() { + closedAt = timeParam(publication.ClosedAt()) + } + if expectedVersion == 0 { + if _, err := fixture.queries.InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(), + ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now), + }); err != nil { + t.Fatalf("InsertCandidatePublication() error = %v", err) + } + return + } + if _, err := fixture.queries.UpdateCandidatePublication(fixture.ctx, sqlc.UpdateCandidatePublicationParams{ + UserID: uuidParam(publication.UserID()), ExpectedVersion: expectedVersion, State: string(publication.StoredState()), Fields: publication.StoredFields(), + ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now), + }); err != nil { + t.Fatalf("UpdateCandidatePublication() error = %v", err) + } +} + +func (fixture candidatePrivacyFixture) recordPublicationEvent(t *testing.T, change domain.PublicationChange, at time.Time) { + t.Helper() + event, err := domain.NewPublicationEvent(change, at) + if err != nil { + t.Fatalf("NewPublicationEvent() error = %v", err) + } + params := sqlc.InsertCandidatePrivacyEventParams{ + ID: uuidParam(event.ID()), UserID: uuidParam(event.UserID()), Kind: string(event.Kind()), OccurredAt: timeParam(event.OccurredAt()), + } + if event.HasFieldSet() { + params.Fields = event.Fields().Codes() + } + if event.ConsentRecordID() != uuid.Nil { + params.ConsentRecordID = uuidParam(event.ConsentRecordID()) + } + if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, params); err != nil { + t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err) + } +} + +func (fixture candidatePrivacyFixture) loadSearchStatus(t *testing.T, userID uuid.UUID) domain.SearchStatus { + t.Helper() + row, err := fixture.queries.ReadCandidateSearchStatus(fixture.ctx, uuidParam(userID)) + if errors.Is(err, pgx.ErrNoRows) { + status, err := domain.NewSearchStatus(userID) + if err != nil { + t.Fatalf("NewSearchStatus() error = %v", err) + } + return status + } + if err != nil { + t.Fatalf("ReadCandidateSearchStatus() error = %v", err) + } + status, err := domain.RestoreSearchStatus(domain.StoredSearchStatus{ + UserID: userID, Status: row.Status, ConfirmedAt: row.ConfirmedAt.Time, LapsesAt: row.LapsesAt.Time, + PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), Version: row.Version, + }) + if err != nil { + t.Fatalf("RestoreSearchStatus() error = %v", err) + } + return status +} + +// setSearchStatus applies a status request with the stored policy version and +// stores the result the way a repository does. +func (fixture candidatePrivacyFixture) setSearchStatus(t *testing.T, userID uuid.UUID, value domain.SearchStatusValue, expectedVersion int64, at time.Time) domain.SearchStatus { + t.Helper() + confirmation, err := domain.NewSearchStatusConfirmation(fixture.policy.ID(), fixture.policy.Policy().SearchStatus) + if err != nil { + t.Fatalf("NewSearchStatusConfirmation() error = %v", err) + } + change, err := fixture.loadSearchStatus(t, userID).Apply(value, expectedVersion, confirmation, at) + if err != nil || !change.Changed { + t.Fatalf("Apply(%s) = %+v, %v, want a change", value, change, err) + } + next := change.Status + confirmed, lapses, policyID := pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{} + if next.StoredValue() == domain.SearchStatusLooking { + confirmed, lapses, policyID = timeParam(next.ConfirmedAt()), timeParam(next.LapsesAt()), uuidParam(next.PolicyVersionID().UUID()) + } + if expectedVersion == 0 { + _, err = fixture.queries.InsertCandidateSearchStatus(fixture.ctx, sqlc.InsertCandidateSearchStatusParams{ + UserID: uuidParam(userID), Status: string(next.StoredValue()), ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at), + }) + } else { + _, err = fixture.queries.UpdateCandidateSearchStatus(fixture.ctx, sqlc.UpdateCandidateSearchStatusParams{ + UserID: uuidParam(userID), ExpectedVersion: expectedVersion, Status: string(next.StoredValue()), + ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at), + }) + } + if err != nil { + t.Fatalf("store the search status: %v", err) + } + return fixture.loadSearchStatus(t, userID) +} + +// hide stores a hiding and its history event the way a repository does. +func (fixture candidatePrivacyFixture) hide(t *testing.T, userID, organizationID uuid.UUID, at time.Time) { + t.Helper() + hidden, err := domain.NewHiddenOrganization(userID, organizationID, at) + if err != nil { + t.Fatalf("NewHiddenOrganization() error = %v", err) + } + if _, err := fixture.queries.InsertCandidateHiddenOrganization(fixture.ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(hidden.UserID()), OrganizationID: uuidParam(hidden.OrganizationID()), At: timeParam(hidden.HiddenAt()), + }); err != nil { + t.Fatalf("InsertCandidateHiddenOrganization() error = %v", err) + } + event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationHidden, userID, organizationID, at) + if err != nil { + t.Fatalf("NewOrganizationEvent() error = %v", err) + } + if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, sqlc.InsertCandidatePrivacyEventParams{ + ID: uuidParam(event.ID()), UserID: uuidParam(userID), Kind: string(event.Kind()), OccurredAt: timeParam(at), + OrganizationID: uuidParam(organizationID), + }); err != nil { + t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err) + } +} + +// The raw readers return a comparable text of the rows, so a test can prove +// that an operation left a table exactly as it was. +func (fixture candidatePrivacyFixture) rawPublication(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(p::text, ';'), '') FROM candidate_publications p WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawSearchStatus(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(s::text, ';'), '') FROM candidate_search_statuses s WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawHidden(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(h::text, ';' ORDER BY organization_id), '') FROM candidate_hidden_organizations h WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawConsentRecords(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(c::text, ';' ORDER BY id), '') FROM consent_records c WHERE subject_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawRows(t *testing.T, query string, userID uuid.UUID) string { + t.Helper() + var text string + if err := fixture.pool.QueryRow(fixture.ctx, query, userID).Scan(&text); err != nil { + t.Fatalf("read raw rows: %v", err) + } + return text +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go index 7cba410..f864322 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -41,7 +41,7 @@ var ( // usersDependentTables is every table that references users, directly or // through another table of the list. A TRUNCATE of users must name all of // them, so a migration that adds such a table adds it here. - usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables) + usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidatePrivacyTables) ) // organizationFixture works on the bootstrap database. The tables are diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 76597cf..960c680 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -4014,6 +4014,208 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped } } +// handleGetMyCardPreviewRequest handles GetMyCardPreview operation. +// +// Requires the session cookie of a candidate account. Returns the card exactly as an organization that +// the candidate does not hide the profile from would read it now, built from the current profile, the +// current publication, and the consent ledger. The response is `Cache-Control: no-store`. +// +// The preview is a private read for the candidate: it creates no view, leaves no access record, and is +// never shown to an organization. While the profile is closed `card` is null. `card` is +// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no +// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, +// or account or profile identifier, and each property is null when it is not published or has no +// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with +// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A +// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, +// an @handle) is dropped from the card, so the preview shows exactly what an organization would read. +// The self-assessed grade is not a category and never appears; categories come only from assessment +// results. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/privacy/preview +func (s *Server) handleGetMyCardPreviewRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyCardPreview"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/preview"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyCardPreviewOperation, + 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: GetMyCardPreviewOperation, + ID: "GetMyCardPreview", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyCardPreviewOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetMyCardPreviewRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyCardPreviewOperation, + OperationSummary: "Preview the anonymous card that organizations would read.", + OperationID: "GetMyCardPreview", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetMyCardPreviewRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyCardPreview(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetMyCardPreview(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyCardPreviewResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyInvitationRequest handles GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -4239,6 +4441,206 @@ func (s *Server) handleGetMyInvitationRequest(args [1]string, argsEscaped bool, } } +// handleGetMyPrivacySettingsRequest handles GetMyPrivacySettings operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, never from +// a request parameter. Returns the publication of the candidate card, the search status, and the +// number of hidden organizations in one read. The response is `Cache-Control: no-store`. +// +// A profile is closed by default. A candidate who never published reads `publication.state` `closed` +// with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the +// profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or +// an assessment changes these settings. The C2 consent, the search status, and the hidden +// organizations are three independent settings: the C2 record in the consent ledger proves that the +// candidate accepted the publication text, the publication records which fields are published, and the +// search status is a statement of the candidate that is not a consent. A change of one never changes +// another, and none of them ever makes the candidate more visible by itself: the search status lapses +// to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/privacy +func (s *Server) handleGetMyPrivacySettingsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyPrivacySettings"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyPrivacySettingsOperation, + 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: GetMyPrivacySettingsOperation, + ID: "GetMyPrivacySettings", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyPrivacySettingsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetMyPrivacySettingsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyPrivacySettingsOperation, + OperationSummary: "Read the visibility settings of the current candidate.", + OperationID: "GetMyPrivacySettings", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetMyPrivacySettingsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyPrivacySettings(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetMyPrivacySettings(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyPrivacySettingsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyProfileRequest handles GetMyProfile operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -5900,6 +6302,476 @@ func (s *Server) handleGetSpecializationCatalogRequest(args [0]string, argsEscap } } +// handleHideOrganizationRequest handles HideOrganization operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The request has no body: the path names the organization and the candidate +// comes from the session. The hiding is a record that belongs to the candidate and references the +// organization; it changes neither the C2 consent, nor the publication, nor the search status. +// +// The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization +// that is already hidden answers 200 with the existing record and its original `hidden_at`, changes +// nothing, and writes no history record. There is one record per candidate and organization. +// +// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot +// see answer the same 404 not_found, with the same body and without a timing or an error code that +// tells them apart, so the operation is not a way to ask whether an identifier belongs to an +// organization. The candidate can see an organization that has sent them an invitation, and the +// organizations that a candidate lookup will list (planned; see the open questions of the contract). +// The response names the organization only after that check, with its current name. The identifiers +// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and +// the record never reveals to an organization that a candidate hides it. +// +// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the +// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from +// other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the +// limit. +// +// Hiding an organization that holds an active contact grant of the candidate revokes that grant with +// the reason `visibility_closed` in the same transaction (planned together with the invitation +// operations). Lifting the hiding never reopens a grant. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the +// path (400), account scenario (403 forbidden for an employer), the organization and its visibility to +// the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like +// every visibility change, hiding needs a verified email (a usecase requirement). +// +// PUT /api/v1/me/privacy/hidden-organizations/{org_id} +func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("HideOrganization"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations/{org_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), HideOrganizationOperation, + 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: HideOrganizationOperation, + ID: "HideOrganization", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, HideOrganizationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, HideOrganizationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeHideOrganizationParams(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 HideOrganizationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: HideOrganizationOperation, + OperationSummary: "Hide the candidate profile from one organization.", + OperationID: "HideOrganization", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = HideOrganizationParams + Response = HideOrganizationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackHideOrganizationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.HideOrganization(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.HideOrganization(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 := encodeHideOrganizationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleListMyCardAccessHistoryRequest handles ListMyCardAccessHistory operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only accesses to the caller's own card. Returns a page, newest first with the record +// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. +// +// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the +// contacts through an active contact grant (`contact_read`). Reading the history is not an access and +// writes nothing. A view of the card by an organization that has no invitation relation with the +// candidate carries `organization` null, so the candidate sees that the card was viewed without +// learning a company that they cannot otherwise see; a contact read always names the organization, +// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking +// of the organization, and no organization the candidate hides ever appears as a viewer, because a +// hidden organization cannot read the card. +// +// The storage of accesses is planned with the card and contact operations of the organization side +// (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 +// not_implemented after the session and request checks. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/access-history +func (s *Server) handleListMyCardAccessHistoryRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyCardAccessHistory"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/access-history"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyCardAccessHistoryOperation, + 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: ListMyCardAccessHistoryOperation, + ID: "ListMyCardAccessHistory", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyCardAccessHistoryOperation, 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 := decodeListMyCardAccessHistoryParams(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 ListMyCardAccessHistoryRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyCardAccessHistoryOperation, + OperationSummary: "List the accesses of organizations to the card of the current candidate.", + OperationID: "ListMyCardAccessHistory", + 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 = ListMyCardAccessHistoryParams + Response = ListMyCardAccessHistoryRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyCardAccessHistoryParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyCardAccessHistory(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyCardAccessHistory(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 := encodeListMyCardAccessHistoryResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMyConsentsRequest handles ListMyConsents operation. // // Requires the session cookie of a candidate or an employer account. The subject comes from the @@ -6131,6 +7003,220 @@ func (s *Server) handleListMyConsentsRequest(args [0]string, argsEscaped bool, w } } +// handleListMyHiddenOrganizationsRequest handles ListMyHiddenOrganizations operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only the caller's own records and no request can name another account. Returns a page +// of the hidden organizations, newest first with the organization identifier as the tie-breaker, with +// cursor pagination. The response is `Cache-Control: no-store`. +// +// The records belong to the candidate. An organization never reads them, never learns that it is +// hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, +// no card, no contact read. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/hidden-organizations +func (s *Server) handleListMyHiddenOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyHiddenOrganizations"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyHiddenOrganizationsOperation, + 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: ListMyHiddenOrganizationsOperation, + ID: "ListMyHiddenOrganizations", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyHiddenOrganizationsOperation, 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 := decodeListMyHiddenOrganizationsParams(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 ListMyHiddenOrganizationsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyHiddenOrganizationsOperation, + OperationSummary: "List the organizations that the candidate hides the profile from.", + OperationID: "ListMyHiddenOrganizations", + 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 = ListMyHiddenOrganizationsParams + Response = ListMyHiddenOrganizationsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyHiddenOrganizationsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyHiddenOrganizations(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyHiddenOrganizations(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 := encodeListMyHiddenOrganizationsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMyInvitationsRequest handles ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -6574,6 +7660,222 @@ func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bo } } +// handleListMyPrivacyHistoryRequest handles ListMyPrivacyHistory operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only the caller's own records. Returns a page of the settings history, newest first +// with the event identifier as the tie-breaker, with cursor pagination. The response is +// `Cache-Control: no-store`. +// +// The history is append-only evidence of what the candidate published, hid, and announced, and when. A +// publication event keeps the published fields and the C2 record behind them, which is what the +// consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the +// field set). A revocation of C2 and a lapse of the search status are computed and are not events +// here; the consent history shows the revocation. The history never contains a profile value. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/history +func (s *Server) handleListMyPrivacyHistoryRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyPrivacyHistory"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/history"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyPrivacyHistoryOperation, + 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: ListMyPrivacyHistoryOperation, + ID: "ListMyPrivacyHistory", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyPrivacyHistoryOperation, 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 := decodeListMyPrivacyHistoryParams(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 ListMyPrivacyHistoryRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyPrivacyHistoryOperation, + OperationSummary: "List the changes of the visibility settings of the current candidate.", + OperationID: "ListMyPrivacyHistory", + 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 = ListMyPrivacyHistoryParams + Response = ListMyPrivacyHistoryRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyPrivacyHistoryParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyPrivacyHistory(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyPrivacyHistory(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 := encodeListMyPrivacyHistoryResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMySupportCasesRequest handles ListMySupportCases operation. // // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that @@ -9041,6 +10343,514 @@ func (s *Server) handleSendOrganizationInvitationRequest(args [2]string, argsEsc } } +// handleSetMyPublicationRequest handles SetMyPublication operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new publication setting: `state` `published` with +// the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; +// the search status and the hidden organizations stay as they were. +// +// Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger +// (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of +// the account and binds the publication to that record, so a client sends no consent identifier and +// cannot forge one. Without one the server answers 409 state_conflict with the entry +// `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every +// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, +// TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction +// that writes the publication, so a revocation that races with a publication either commits first (the +// publication is refused) or closes the card right after. A revocation of C2 closes the card at once, +// because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the +// candidate publishes again under the new record. The revocation path itself (TASK-064) closes the +// stored publication and revokes the contact grants in its own transaction. A closing sent over a +// stored publication whose C2 was revoked is a real change: it stores the closing, records +// `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility +// change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only +// accounts without such records). Publishing never adds a field that the body did not name, and a new +// `CardField` value is never published for a candidate who did not choose it. +// +// The field set contains only the groups of `CardField`. The full name, contacts, and the lowest +// salary have no value there, so no body can publish them. Only values that the candidate confirmed +// ever reach the card. Contacts reach an organization only through the contact grant (C4), and a +// profile that is published or closed changes none of the grants that exist; closing the publication, +// and hiding an organization that holds a grant, revoke the contact grants concerned with the reason +// `visibility_closed` in the same transaction as the change (planned together with the operations, see +// the invitation contract). +// +// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, +// 0 for the first publication. If it is not the current version the server answers 412 +// version_conflict and changes nothing. The version travels in the body rather than in If-Match +// because the generated client cannot read the ETag header yet. A body that equals the stored setting +// changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a +// retry after a lost response succeeds without an Idempotency-Key. A version above the current one +// never existed and always answers 412. Every change is recorded in the settings history with its +// time, the fields, and the C2 record. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), a version above the current one (412), rules that +// depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 +// for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown +// card field, and more fields than there are groups; a published state with no field, and a closed +// state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never +// repeat a submitted value. +// +// PUT /api/v1/me/privacy/publication +func (s *Server) handleSetMyPublicationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SetMyPublication"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/publication"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SetMyPublicationOperation, + 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: SetMyPublicationOperation, + ID: "SetMyPublication", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SetMyPublicationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, SetMyPublicationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSetMyPublicationRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SetMyPublicationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SetMyPublicationOperation, + OperationSummary: "Publish or close the anonymous candidate card.", + OperationID: "SetMyPublication", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *PublicationUpdate + Params = struct{} + Response = SetMyPublicationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SetMyPublication(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.SetMyPublication(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSetMyPublicationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleSetMySearchStatusRequest handles SetMySearchStatus operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. +// The status is a statement of the candidate and never a consent. It changes neither the C2 consent, +// nor the publication, nor the hidden organizations, and it does not close or open any contact grant; +// a candidate whose profile is closed who sets `looking` becomes visible to no one. +// +// `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from +// the `search_status` section of the effective product policy (30 days in the demo policy, +// `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time +// then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it +// replaces the confirmation time with now and advances the version, also after a lapse. The body +// carries no time, interval, or policy version. +// +// After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The +// lapse is computed and written nowhere, so it needs no job, it can never make the candidate more +// visible, and it never touches the publication or the hidden organizations. A reminder before the +// lapse is a planned notification, not a part of this operation. +// +// Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the +// status; a stale or non-existent version answers 412 version_conflict and changes nothing. +// `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. +// `looking` always changes the stored confirmation, so a retry of a confirmation whose response was +// lost with the old version answers 412 and the client reads the status again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), a version above the current one (412), an +// unchanged `not_looking` (200), then a stale version (412). +// +// PUT /api/v1/me/privacy/search-status +func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("SetMySearchStatus"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/search-status"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), SetMySearchStatusOperation, + 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: SetMySearchStatusOperation, + ID: "SetMySearchStatus", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, SetMySearchStatusOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, SetMySearchStatusOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + request, rawBody, close, err := s.decodeSetMySearchStatusRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response SetMySearchStatusRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: SetMySearchStatusOperation, + OperationSummary: "Set or confirm the search status of the current candidate.", + OperationID: "SetMySearchStatus", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *SearchStatusUpdate + Params = struct{} + Response = SetMySearchStatusRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.SetMySearchStatus(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.SetMySearchStatus(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeSetMySearchStatusResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleSubmitMyAssessmentAnswerRequest handles SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -9329,6 +11139,236 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap } } +// handleUnhideOrganizationRequest handles UnhideOrganization operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. +// The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or +// does not exist, so the operation reveals nothing about the organization, and a repeat after a lost +// response succeeds. The record is deleted, the settings history keeps the event +// `organization_unhidden` only when a record was deleted. +// +// Lifting the hiding makes the candidate readable by that organization again only if the profile is +// published and the organization otherwise may read it. It changes neither the C2 consent, nor the +// publication, nor the search status, and it never reopens a contact grant that the hiding closed. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the +// path (400), account scenario (403 forbidden for an employer), then the deletion (204). +// +// DELETE /api/v1/me/privacy/hidden-organizations/{org_id} +func (s *Server) handleUnhideOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("UnhideOrganization"), + semconv.HTTPRequestMethodKey.String("DELETE"), + semconv.HTTPRouteKey.String("/api/v1/me/privacy/hidden-organizations/{org_id}"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), UnhideOrganizationOperation, + 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: UnhideOrganizationOperation, + ID: "UnhideOrganization", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, UnhideOrganizationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, UnhideOrganizationOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeUnhideOrganizationParams(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 UnhideOrganizationRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: UnhideOrganizationOperation, + OperationSummary: "Lift the hiding of the candidate profile from one organization.", + OperationID: "UnhideOrganization", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "org_id", + In: "path", + }: params.OrgID, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = UnhideOrganizationParams + Response = UnhideOrganizationRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackUnhideOrganizationParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.UnhideOrganization(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.UnhideOrganization(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 := encodeUnhideOrganizationResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleUpdateOrganizationRequest handles UpdateOrganization operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 80d8e12..be3faf7 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -65,10 +65,18 @@ type GetMyAssessmentResultRes interface { getMyAssessmentResultRes() } +type GetMyCardPreviewRes interface { + getMyCardPreviewRes() +} + type GetMyInvitationRes interface { getMyInvitationRes() } +type GetMyPrivacySettingsRes interface { + getMyPrivacySettingsRes() +} + type GetMyProfileRes interface { getMyProfileRes() } @@ -97,10 +105,22 @@ type GetOrganizationRes interface { getOrganizationRes() } +type HideOrganizationRes interface { + hideOrganizationRes() +} + +type ListMyCardAccessHistoryRes interface { + listMyCardAccessHistoryRes() +} + type ListMyConsentsRes interface { listMyConsentsRes() } +type ListMyHiddenOrganizationsRes interface { + listMyHiddenOrganizationsRes() +} + type ListMyInvitationsRes interface { listMyInvitationsRes() } @@ -109,6 +129,10 @@ type ListMyOrganizationsRes interface { listMyOrganizationsRes() } +type ListMyPrivacyHistoryRes interface { + listMyPrivacyHistoryRes() +} + type ListMySupportCasesRes interface { listMySupportCasesRes() } @@ -153,10 +177,22 @@ type SendOrganizationInvitationRes interface { sendOrganizationInvitationRes() } +type SetMyPublicationRes interface { + setMyPublicationRes() +} + +type SetMySearchStatusRes interface { + setMySearchStatusRes() +} + type SubmitMyAssessmentAnswerRes interface { submitMyAssessmentAnswerRes() } +type UnhideOrganizationRes interface { + unhideOrganizationRes() +} + type UpdateOrganizationInvitationRes interface { updateOrganizationInvitationRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index 867b707..329a039 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -493,6 +493,246 @@ func (s *AccountScenario) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AnonymousCardContent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AnonymousCardContent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("categories") + if s.Categories == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range s.Categories { + elem.Encode(e) + } + e.ArrEnd() + } + } + { + e.FieldStart("stack") + if s.Stack == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range s.Stack { + elem.Encode(e) + } + e.ArrEnd() + } + } + { + e.FieldStart("experience_months") + s.ExperienceMonths.Encode(e) + } + { + e.FieldStart("soft_skills") + if s.SoftSkills == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range s.SoftSkills { + e.Str(elem) + } + e.ArrEnd() + } + } + { + e.FieldStart("location") + s.Location.Encode(e) + } + { + e.FieldStart("relocation") + s.Relocation.Encode(e) + } +} + +var jsonFieldsNameOfAnonymousCardContent = [6]string{ + 0: "categories", + 1: "stack", + 2: "experience_months", + 3: "soft_skills", + 4: "location", + 5: "relocation", +} + +// Decode decodes AnonymousCardContent from json. +func (s *AnonymousCardContent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AnonymousCardContent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "categories": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + s.Categories = make([]CardCategory, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CardCategory + if err := elem.Decode(d); err != nil { + return err + } + s.Categories = append(s.Categories, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"categories\"") + } + case "stack": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + s.Stack = make([]StackTag, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem StackTag + if err := elem.Decode(d); err != nil { + return err + } + s.Stack = append(s.Stack, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"stack\"") + } + case "experience_months": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ExperienceMonths.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"experience_months\"") + } + case "soft_skills": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + s.SoftSkills = make([]string, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem string + v, err := d.Str() + elem = string(v) + if err != nil { + return err + } + s.SoftSkills = append(s.SoftSkills, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"soft_skills\"") + } + case "location": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Location.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"location\"") + } + case "relocation": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Relocation.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"relocation\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AnonymousCardContent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAnonymousCardContent) { + name = jsonFieldsNameOfAnonymousCardContent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AnonymousCardContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AnonymousCardContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentAnswer as json. func (s AssessmentAnswer) Encode(e *jx.Encoder) { switch s.Type { @@ -6659,6 +6899,669 @@ func (s *CandidateQuestionnaireUpdate) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *CardAccess) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CardAccess) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("organization") + s.Organization.Encode(e) + } +} + +var jsonFieldsNameOfCardAccess = [4]string{ + 0: "id", + 1: "kind", + 2: "occurred_at", + 3: "organization", +} + +// Decode decodes CardAccess from json. +func (s *CardAccess) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardAccess to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + case "organization": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CardAccess") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCardAccess) { + name = jsonFieldsNameOfCardAccess[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CardAccess) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardAccess) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CardAccessKind as json. +func (s CardAccessKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CardAccessKind from json. +func (s *CardAccessKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardAccessKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CardAccessKind(v) { + case CardAccessKindCardViewed: + *s = CardAccessKindCardViewed + case CardAccessKindContactRead: + *s = CardAccessKindContactRead + default: + *s = CardAccessKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CardAccessKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardAccessKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CardAccessList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CardAccessList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfCardAccessList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes CardAccessList from json. +func (s *CardAccessList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardAccessList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]CardAccess, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CardAccess + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CardAccessList") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCardAccessList) { + name = jsonFieldsNameOfCardAccessList[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CardAccessList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardAccessList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CardCategory) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CardCategory) encodeFields(e *jx.Encoder) { + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("grade") + s.Grade.Encode(e) + } +} + +var jsonFieldsNameOfCardCategory = [2]string{ + 0: "specialization", + 1: "grade", +} + +// Decode decodes CardCategory from json. +func (s *CardCategory) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardCategory to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "specialization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Specialization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"specialization\"") + } + case "grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Grade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"grade\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CardCategory") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCardCategory) { + name = jsonFieldsNameOfCardCategory[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CardCategory) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardCategory) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CardField as json. +func (s CardField) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes CardField from json. +func (s *CardField) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardField to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch CardField(v) { + case CardFieldCategories: + *s = CardFieldCategories + case CardFieldStack: + *s = CardFieldStack + case CardFieldExperience: + *s = CardFieldExperience + case CardFieldSoftSkills: + *s = CardFieldSoftSkills + case CardFieldLocation: + *s = CardFieldLocation + case CardFieldRelocation: + *s = CardFieldRelocation + default: + *s = CardField(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CardField) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardField) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes CardFieldSet as json. +func (s CardFieldSet) Encode(e *jx.Encoder) { + unwrapped := []CardField(s) + + if unwrapped == nil { + e.Null() + } else { + e.ArrStart() + for _, elem := range unwrapped { + elem.Encode(e) + } + e.ArrEnd() + } +} + +// Decode decodes CardFieldSet from json. +func (s *CardFieldSet) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardFieldSet to nil") + } + var unwrapped []CardField + if err := func() error { + switch tt := d.Next(); tt { + case jx.Null: + if err := d.Skip(); err != nil { + return err + } + default: + unwrapped = make([]CardField, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem CardField + if err := elem.Decode(d); err != nil { + return err + } + unwrapped = append(unwrapped, elem) + return nil + }); err != nil { + return err + } + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = CardFieldSet(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s CardFieldSet) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardFieldSet) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *CardPreview) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *CardPreview) encodeFields(e *jx.Encoder) { + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("fields") + if s.Fields == nil { + e.Null() + } else { + s.Fields.Encode(e) + } + } + { + e.FieldStart("card") + s.Card.Encode(e) + } + { + e.FieldStart("generated_at") + s.GeneratedAt.Encode(e) + } +} + +var jsonFieldsNameOfCardPreview = [4]string{ + 0: "state", + 1: "fields", + 2: "card", + 3: "generated_at", +} + +// Decode decodes CardPreview from json. +func (s *CardPreview) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode CardPreview to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "state": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "fields": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Fields.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "card": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Card.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"card\"") + } + case "generated_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.GeneratedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"generated_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode CardPreview") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00001111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfCardPreview) { + name = jsonFieldsNameOfCardPreview[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *CardPreview) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *CardPreview) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *CatalogDirection) Encode(e *jx.Encoder) { e.ObjStart() @@ -12741,6 +13644,82 @@ func (s *GetMyAssessmentResultUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyCardPreviewForbidden as json. +func (s *GetMyCardPreviewForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyCardPreviewForbidden from json. +func (s *GetMyCardPreviewForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyCardPreviewForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyCardPreviewForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyCardPreviewForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyCardPreviewForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyCardPreviewUnauthorized as json. +func (s *GetMyCardPreviewUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyCardPreviewUnauthorized from json. +func (s *GetMyCardPreviewUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyCardPreviewUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyCardPreviewUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyCardPreviewUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyCardPreviewUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyInvitationBadRequest as json. func (s *GetMyInvitationBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -12893,6 +13872,82 @@ func (s *GetMyInvitationUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyPrivacySettingsForbidden as json. +func (s *GetMyPrivacySettingsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyPrivacySettingsForbidden from json. +func (s *GetMyPrivacySettingsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyPrivacySettingsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyPrivacySettingsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyPrivacySettingsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyPrivacySettingsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyPrivacySettingsUnauthorized as json. +func (s *GetMyPrivacySettingsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyPrivacySettingsUnauthorized from json. +func (s *GetMyPrivacySettingsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyPrivacySettingsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyPrivacySettingsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyPrivacySettingsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyPrivacySettingsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyProfileForbidden as json. func (s *GetMyProfileForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -13943,6 +14998,426 @@ func (s *HealthResponseStatus) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *HiddenOrganization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *HiddenOrganization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("organization") + s.Organization.Encode(e) + } + { + e.FieldStart("hidden_at") + s.HiddenAt.Encode(e) + } +} + +var jsonFieldsNameOfHiddenOrganization = [2]string{ + 0: "organization", + 1: "hidden_at", +} + +// Decode decodes HiddenOrganization from json. +func (s *HiddenOrganization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HiddenOrganization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "organization": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + case "hidden_at": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.HiddenAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"hidden_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode HiddenOrganization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfHiddenOrganization) { + name = jsonFieldsNameOfHiddenOrganization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HiddenOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HiddenOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *HiddenOrganizationList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *HiddenOrganizationList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfHiddenOrganizationList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes HiddenOrganizationList from json. +func (s *HiddenOrganizationList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HiddenOrganizationList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]HiddenOrganization, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem HiddenOrganization + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode HiddenOrganizationList") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfHiddenOrganizationList) { + name = jsonFieldsNameOfHiddenOrganizationList[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HiddenOrganizationList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HiddenOrganizationList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes HideOrganizationBadRequest as json. +func (s *HideOrganizationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes HideOrganizationBadRequest from json. +func (s *HideOrganizationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HideOrganizationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = HideOrganizationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HideOrganizationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HideOrganizationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes HideOrganizationConflict as json. +func (s *HideOrganizationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes HideOrganizationConflict from json. +func (s *HideOrganizationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HideOrganizationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = HideOrganizationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HideOrganizationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HideOrganizationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes HideOrganizationForbidden as json. +func (s *HideOrganizationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes HideOrganizationForbidden from json. +func (s *HideOrganizationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HideOrganizationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = HideOrganizationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HideOrganizationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HideOrganizationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes HideOrganizationNotFound as json. +func (s *HideOrganizationNotFound) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes HideOrganizationNotFound from json. +func (s *HideOrganizationNotFound) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HideOrganizationNotFound to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = HideOrganizationNotFound(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HideOrganizationNotFound) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HideOrganizationNotFound) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes HideOrganizationUnauthorized as json. +func (s *HideOrganizationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes HideOrganizationUnauthorized from json. +func (s *HideOrganizationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode HideOrganizationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = HideOrganizationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *HideOrganizationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *HideOrganizationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *IdentityRequestAccepted) Encode(e *jx.Encoder) { e.ObjStart() @@ -16890,6 +18365,120 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyCardAccessHistoryBadRequest as json. +func (s *ListMyCardAccessHistoryBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyCardAccessHistoryBadRequest from json. +func (s *ListMyCardAccessHistoryBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyCardAccessHistoryBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyCardAccessHistoryBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyCardAccessHistoryBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyCardAccessHistoryBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyCardAccessHistoryForbidden as json. +func (s *ListMyCardAccessHistoryForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyCardAccessHistoryForbidden from json. +func (s *ListMyCardAccessHistoryForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyCardAccessHistoryForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyCardAccessHistoryForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyCardAccessHistoryForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyCardAccessHistoryForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyCardAccessHistoryUnauthorized as json. +func (s *ListMyCardAccessHistoryUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyCardAccessHistoryUnauthorized from json. +func (s *ListMyCardAccessHistoryUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyCardAccessHistoryUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyCardAccessHistoryUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyCardAccessHistoryUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyCardAccessHistoryUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyConsentsBadRequest as json. func (s *ListMyConsentsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -16966,6 +18555,120 @@ func (s *ListMyConsentsUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyHiddenOrganizationsBadRequest as json. +func (s *ListMyHiddenOrganizationsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyHiddenOrganizationsBadRequest from json. +func (s *ListMyHiddenOrganizationsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyHiddenOrganizationsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyHiddenOrganizationsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyHiddenOrganizationsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyHiddenOrganizationsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyHiddenOrganizationsForbidden as json. +func (s *ListMyHiddenOrganizationsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyHiddenOrganizationsForbidden from json. +func (s *ListMyHiddenOrganizationsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyHiddenOrganizationsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyHiddenOrganizationsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyHiddenOrganizationsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyHiddenOrganizationsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyHiddenOrganizationsUnauthorized as json. +func (s *ListMyHiddenOrganizationsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyHiddenOrganizationsUnauthorized from json. +func (s *ListMyHiddenOrganizationsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyHiddenOrganizationsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyHiddenOrganizationsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyHiddenOrganizationsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyHiddenOrganizationsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyInvitationsBadRequest as json. func (s *ListMyInvitationsBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -17194,6 +18897,120 @@ func (s *ListMyOrganizationsUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyPrivacyHistoryBadRequest as json. +func (s *ListMyPrivacyHistoryBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyPrivacyHistoryBadRequest from json. +func (s *ListMyPrivacyHistoryBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyPrivacyHistoryBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyPrivacyHistoryBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyPrivacyHistoryBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyPrivacyHistoryBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyPrivacyHistoryForbidden as json. +func (s *ListMyPrivacyHistoryForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyPrivacyHistoryForbidden from json. +func (s *ListMyPrivacyHistoryForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyPrivacyHistoryForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyPrivacyHistoryForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyPrivacyHistoryForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyPrivacyHistoryForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyPrivacyHistoryUnauthorized as json. +func (s *ListMyPrivacyHistoryUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyPrivacyHistoryUnauthorized from json. +func (s *ListMyPrivacyHistoryUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyPrivacyHistoryUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyPrivacyHistoryUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyPrivacyHistoryUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyPrivacyHistoryUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMySupportCasesBadRequest as json. func (s *ListMySupportCasesBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -23266,6 +25083,50 @@ func (s *NewPassword) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AnonymousCardContent as json. +func (o NilAnonymousCardContent) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes AnonymousCardContent from json. +func (o *NilAnonymousCardContent) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAnonymousCardContent to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AnonymousCardContent + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAnonymousCardContent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAnonymousCardContent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentItem as json. func (o NilAssessmentItem) Encode(e *jx.Encoder) { if o.Null { @@ -24194,6 +26055,52 @@ func (s *NilGradeCode) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes int as json. +func (o NilInt) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Int(int(o.Value)) +} + +// Decode decodes int from json. +func (o *NilInt) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilInt to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v int + o.Value = v + o.Null = true + return nil + } + o.Null = false + v, err := d.Int() + if err != nil { + return err + } + o.Value = int(v) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilInt) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilInt) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes int32 as json. func (o NilInt32) Encode(e *jx.Encoder) { if o.Null { @@ -25032,6 +26939,50 @@ func (s *NilPracticeVerdict) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes PrivacyOrganization as json. +func (o NilPrivacyOrganization) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + o.Value.Encode(e) +} + +// Decode decodes PrivacyOrganization from json. +func (o *NilPrivacyOrganization) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilPrivacyOrganization to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v PrivacyOrganization + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilPrivacyOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilPrivacyOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ProfileClaimQuote as json. func (o NilProfileClaimQuote) Encode(e *jx.Encoder) { if o.Null { @@ -25648,6 +27599,50 @@ func (s *NilProfileYearMonth) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes PublicationClosedReason as json. +func (o NilPublicationClosedReason) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes PublicationClosedReason from json. +func (o *NilPublicationClosedReason) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilPublicationClosedReason to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v PublicationClosedReason + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilPublicationClosedReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilPublicationClosedReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes SalaryRange as json. func (o NilSalaryRange) Encode(e *jx.Encoder) { if o.Null { @@ -31690,6 +33685,591 @@ func (s *PracticeVerdict) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *PrivacyEvent) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PrivacyEvent) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("kind") + s.Kind.Encode(e) + } + { + e.FieldStart("occurred_at") + s.OccurredAt.Encode(e) + } + { + e.FieldStart("fields") + if s.Fields == nil { + e.Null() + } else { + s.Fields.Encode(e) + } + } + { + e.FieldStart("consent_id") + s.ConsentID.Encode(e) + } + { + e.FieldStart("organization") + s.Organization.Encode(e) + } +} + +var jsonFieldsNameOfPrivacyEvent = [6]string{ + 0: "id", + 1: "kind", + 2: "occurred_at", + 3: "fields", + 4: "consent_id", + 5: "organization", +} + +// Decode decodes PrivacyEvent from json. +func (s *PrivacyEvent) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PrivacyEvent to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "kind": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Kind.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"kind\"") + } + case "occurred_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.OccurredAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"occurred_at\"") + } + case "fields": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Fields.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "consent_id": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.ConsentID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"consent_id\"") + } + case "organization": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Organization.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"organization\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PrivacyEvent") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPrivacyEvent) { + name = jsonFieldsNameOfPrivacyEvent[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PrivacyEvent) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PrivacyEvent) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PrivacyEventKind as json. +func (s PrivacyEventKind) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PrivacyEventKind from json. +func (s *PrivacyEventKind) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PrivacyEventKind to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PrivacyEventKind(v) { + case PrivacyEventKindPublicationOpened: + *s = PrivacyEventKindPublicationOpened + case PrivacyEventKindPublicationChanged: + *s = PrivacyEventKindPublicationChanged + case PrivacyEventKindPublicationClosed: + *s = PrivacyEventKindPublicationClosed + case PrivacyEventKindSearchStatusConfirmed: + *s = PrivacyEventKindSearchStatusConfirmed + case PrivacyEventKindSearchStatusCleared: + *s = PrivacyEventKindSearchStatusCleared + case PrivacyEventKindOrganizationHidden: + *s = PrivacyEventKindOrganizationHidden + case PrivacyEventKindOrganizationUnhidden: + *s = PrivacyEventKindOrganizationUnhidden + default: + *s = PrivacyEventKind(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PrivacyEventKind) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PrivacyEventKind) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PrivacyEventList) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PrivacyEventList) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfPrivacyEventList = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes PrivacyEventList from json. +func (s *PrivacyEventList) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PrivacyEventList to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]PrivacyEvent, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem PrivacyEvent + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PrivacyEventList") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPrivacyEventList) { + name = jsonFieldsNameOfPrivacyEventList[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PrivacyEventList) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PrivacyEventList) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PrivacyOrganization) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PrivacyOrganization) encodeFields(e *jx.Encoder) { + { + e.FieldStart("id") + json.EncodeUUID(e, s.ID) + } + { + e.FieldStart("name") + e.Str(s.Name) + } +} + +var jsonFieldsNameOfPrivacyOrganization = [2]string{ + 0: "id", + 1: "name", +} + +// Decode decodes PrivacyOrganization from json. +func (s *PrivacyOrganization) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PrivacyOrganization to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "id": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + v, err := json.DecodeUUID(d) + s.ID = v + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"id\"") + } + case "name": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Str() + s.Name = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"name\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PrivacyOrganization") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPrivacyOrganization) { + name = jsonFieldsNameOfPrivacyOrganization[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PrivacyOrganization) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PrivacyOrganization) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PrivacySettings) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PrivacySettings) encodeFields(e *jx.Encoder) { + { + e.FieldStart("publication") + s.Publication.Encode(e) + } + { + e.FieldStart("search_status") + s.SearchStatus.Encode(e) + } + { + e.FieldStart("hidden_organizations_total") + e.Int(s.HiddenOrganizationsTotal) + } +} + +var jsonFieldsNameOfPrivacySettings = [3]string{ + 0: "publication", + 1: "search_status", + 2: "hidden_organizations_total", +} + +// Decode decodes PrivacySettings from json. +func (s *PrivacySettings) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PrivacySettings to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "publication": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Publication.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"publication\"") + } + case "search_status": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.SearchStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"search_status\"") + } + case "hidden_organizations_total": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Int() + s.HiddenOrganizationsTotal = int(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"hidden_organizations_total\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PrivacySettings") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPrivacySettings) { + name = jsonFieldsNameOfPrivacySettings[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PrivacySettings) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PrivacySettings) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *Problem) Encode(e *jx.Encoder) { e.ObjStart() @@ -36270,6 +38850,429 @@ func (s *ProfileYearMonth) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *Publication) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *Publication) encodeFields(e *jx.Encoder) { + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("closed_reason") + s.ClosedReason.Encode(e) + } + { + e.FieldStart("fields") + if s.Fields == nil { + e.Null() + } else { + s.Fields.Encode(e) + } + } + { + e.FieldStart("consent_id") + s.ConsentID.Encode(e) + } + { + e.FieldStart("published_at") + s.PublishedAt.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } +} + +var jsonFieldsNameOfPublication = [6]string{ + 0: "state", + 1: "closed_reason", + 2: "fields", + 3: "consent_id", + 4: "published_at", + 5: "version", +} + +// Decode decodes Publication from json. +func (s *Publication) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode Publication to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "state": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "closed_reason": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.ClosedReason.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"closed_reason\"") + } + case "fields": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Fields.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + case "consent_id": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.ConsentID.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"consent_id\"") + } + case "published_at": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.PublishedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"published_at\"") + } + case "version": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode Publication") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPublication) { + name = jsonFieldsNameOfPublication[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *Publication) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *Publication) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PublicationClosedReason as json. +func (s PublicationClosedReason) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PublicationClosedReason from json. +func (s *PublicationClosedReason) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PublicationClosedReason to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PublicationClosedReason(v) { + case PublicationClosedReasonNeverPublished: + *s = PublicationClosedReasonNeverPublished + case PublicationClosedReasonClosedByCandidate: + *s = PublicationClosedReasonClosedByCandidate + case PublicationClosedReasonConsentRevoked: + *s = PublicationClosedReasonConsentRevoked + default: + *s = PublicationClosedReason(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PublicationClosedReason) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PublicationClosedReason) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PublicationState as json. +func (s PublicationState) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes PublicationState from json. +func (s *PublicationState) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PublicationState to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch PublicationState(v) { + case PublicationStateClosed: + *s = PublicationStateClosed + case PublicationStatePublished: + *s = PublicationStatePublished + default: + *s = PublicationState(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PublicationState) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PublicationState) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *PublicationUpdate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *PublicationUpdate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("state") + s.State.Encode(e) + } + { + e.FieldStart("fields") + if s.Fields == nil { + e.Null() + } else { + s.Fields.Encode(e) + } + } +} + +var jsonFieldsNameOfPublicationUpdate = [3]string{ + 0: "expected_version", + 1: "state", + 2: "fields", +} + +// Decode decodes PublicationUpdate from json. +func (s *PublicationUpdate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PublicationUpdate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "state": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.State.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"state\"") + } + case "fields": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.Fields.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"fields\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode PublicationUpdate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfPublicationUpdate) { + name = jsonFieldsNameOfPublicationUpdate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *PublicationUpdate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PublicationUpdate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes PublicationVersion as json. +func (s PublicationVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes PublicationVersion from json. +func (s *PublicationVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode PublicationVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = PublicationVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s PublicationVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *PublicationVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *QuestionnaireSpecialization) Encode(e *jx.Encoder) { e.ObjStart() @@ -37697,6 +40700,351 @@ func (s *SaveMyQuestionnaireUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *SearchStatus) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SearchStatus) encodeFields(e *jx.Encoder) { + { + e.FieldStart("value") + s.Value.Encode(e) + } + { + e.FieldStart("lapsed") + e.Bool(s.Lapsed) + } + { + e.FieldStart("confirmed_at") + s.ConfirmedAt.Encode(e) + } + { + e.FieldStart("lapses_at") + s.LapsesAt.Encode(e) + } + { + e.FieldStart("version") + s.Version.Encode(e) + } +} + +var jsonFieldsNameOfSearchStatus = [5]string{ + 0: "value", + 1: "lapsed", + 2: "confirmed_at", + 3: "lapses_at", + 4: "version", +} + +// Decode decodes SearchStatus from json. +func (s *SearchStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SearchStatus to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "value": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + case "lapsed": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Bool() + s.Lapsed = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lapsed\"") + } + case "confirmed_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.ConfirmedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"confirmed_at\"") + } + case "lapses_at": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.LapsesAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"lapses_at\"") + } + case "version": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Version.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SearchStatus") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00011111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfSearchStatus) { + name = jsonFieldsNameOfSearchStatus[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SearchStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SearchStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *SearchStatusUpdate) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *SearchStatusUpdate) encodeFields(e *jx.Encoder) { + { + e.FieldStart("expected_version") + s.ExpectedVersion.Encode(e) + } + { + e.FieldStart("value") + s.Value.Encode(e) + } +} + +var jsonFieldsNameOfSearchStatusUpdate = [2]string{ + 0: "expected_version", + 1: "value", +} + +// Decode decodes SearchStatusUpdate from json. +func (s *SearchStatusUpdate) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SearchStatusUpdate to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "expected_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.ExpectedVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"expected_version\"") + } + case "value": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Value.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"value\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode SearchStatusUpdate") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfSearchStatusUpdate) { + name = jsonFieldsNameOfSearchStatusUpdate[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SearchStatusUpdate) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SearchStatusUpdate) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SearchStatusValue as json. +func (s SearchStatusValue) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes SearchStatusValue from json. +func (s *SearchStatusValue) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SearchStatusValue to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch SearchStatusValue(v) { + case SearchStatusValueLooking: + *s = SearchStatusValueLooking + case SearchStatusValueNotLooking: + *s = SearchStatusValueNotLooking + default: + *s = SearchStatusValue(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SearchStatusValue) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SearchStatusValue) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SearchStatusVersion as json. +func (s SearchStatusVersion) Encode(e *jx.Encoder) { + unwrapped := int64(s) + + e.Int64(unwrapped) +} + +// Decode decodes SearchStatusVersion from json. +func (s *SearchStatusVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SearchStatusVersion to nil") + } + var unwrapped int64 + if err := func() error { + v, err := d.Int64() + unwrapped = int64(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SearchStatusVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s SearchStatusVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SearchStatusVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes SendOrganizationInvitationBadRequest as json. func (s *SendOrganizationInvitationBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -38072,6 +41420,348 @@ func (s *Session) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes SetMyPublicationBadRequest as json. +func (s *SetMyPublicationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMyPublicationBadRequest from json. +func (s *SetMyPublicationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMyPublicationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMyPublicationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMyPublicationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMyPublicationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMyPublicationConflict as json. +func (s *SetMyPublicationConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMyPublicationConflict from json. +func (s *SetMyPublicationConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMyPublicationConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMyPublicationConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMyPublicationConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMyPublicationConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMyPublicationForbidden as json. +func (s *SetMyPublicationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMyPublicationForbidden from json. +func (s *SetMyPublicationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMyPublicationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMyPublicationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMyPublicationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMyPublicationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMyPublicationPreconditionFailed as json. +func (s *SetMyPublicationPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMyPublicationPreconditionFailed from json. +func (s *SetMyPublicationPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMyPublicationPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMyPublicationPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMyPublicationPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMyPublicationPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMyPublicationUnauthorized as json. +func (s *SetMyPublicationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMyPublicationUnauthorized from json. +func (s *SetMyPublicationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMyPublicationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMyPublicationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMyPublicationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMyPublicationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMySearchStatusBadRequest as json. +func (s *SetMySearchStatusBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMySearchStatusBadRequest from json. +func (s *SetMySearchStatusBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMySearchStatusBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMySearchStatusBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMySearchStatusBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMySearchStatusBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMySearchStatusForbidden as json. +func (s *SetMySearchStatusForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMySearchStatusForbidden from json. +func (s *SetMySearchStatusForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMySearchStatusForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMySearchStatusForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMySearchStatusForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMySearchStatusForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMySearchStatusPreconditionFailed as json. +func (s *SetMySearchStatusPreconditionFailed) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMySearchStatusPreconditionFailed from json. +func (s *SetMySearchStatusPreconditionFailed) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMySearchStatusPreconditionFailed to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMySearchStatusPreconditionFailed(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMySearchStatusPreconditionFailed) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMySearchStatusPreconditionFailed) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes SetMySearchStatusUnauthorized as json. +func (s *SetMySearchStatusUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes SetMySearchStatusUnauthorized from json. +func (s *SetMySearchStatusUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode SetMySearchStatusUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = SetMySearchStatusUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *SetMySearchStatusUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *SetMySearchStatusUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes SkillName as json. func (s SkillName) Encode(e *jx.Encoder) { unwrapped := string(s) @@ -42520,6 +46210,120 @@ func (s *Timestamp) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes UnhideOrganizationBadRequest as json. +func (s *UnhideOrganizationBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UnhideOrganizationBadRequest from json. +func (s *UnhideOrganizationBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UnhideOrganizationBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UnhideOrganizationBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UnhideOrganizationBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UnhideOrganizationBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UnhideOrganizationForbidden as json. +func (s *UnhideOrganizationForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UnhideOrganizationForbidden from json. +func (s *UnhideOrganizationForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UnhideOrganizationForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UnhideOrganizationForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UnhideOrganizationForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UnhideOrganizationForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes UnhideOrganizationUnauthorized as json. +func (s *UnhideOrganizationUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes UnhideOrganizationUnauthorized from json. +func (s *UnhideOrganizationUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode UnhideOrganizationUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = UnhideOrganizationUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *UnhideOrganizationUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *UnhideOrganizationUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes UpdateOrganizationBadRequest as json. func (s *UpdateOrganizationBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index d4271e2..18ed2e8 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -23,7 +23,9 @@ const ( GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" + GetMyCardPreviewOperation OperationName = "GetMyCardPreview" GetMyInvitationOperation OperationName = "GetMyInvitation" + GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings" GetMyProfileOperation OperationName = "GetMyProfile" GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" GetMySupportCaseOperation OperationName = "GetMySupportCase" @@ -32,9 +34,13 @@ const ( GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + HideOrganizationOperation OperationName = "HideOrganization" + ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory" ListMyConsentsOperation OperationName = "ListMyConsents" + ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" ListMyInvitationsOperation OperationName = "ListMyInvitations" ListMyOrganizationsOperation OperationName = "ListMyOrganizations" + ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" ListMySupportCasesOperation OperationName = "ListMySupportCases" ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" @@ -46,7 +52,10 @@ const ( SaveMyProfileOperation OperationName = "SaveMyProfile" SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" + SetMyPublicationOperation OperationName = "SetMyPublication" + SetMySearchStatusOperation OperationName = "SetMySearchStatus" SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" + UnhideOrganizationOperation OperationName = "UnhideOrganization" UpdateOrganizationOperation OperationName = "UpdateOrganization" UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed" diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 2dcacdd..a6e5760 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -1982,6 +1982,252 @@ func decodeGetOrganizationNeedParams(args [2]string, argsEscaped bool, r *http.R return params, nil } +// HideOrganizationParams is parameters of HideOrganization operation. +type HideOrganizationParams struct { + // Identifier of the organization that the current candidate hides or stops hiding the profile from. It + // names the target of a candidate's own setting and grants the candidate nothing about the + // organization. Hiding answers the same 404 not_found for an organization that does not exist and for + // one that the candidate cannot see, so organizations cannot be enumerated; lifting the hiding answers + // 204 for any well-formed identifier. + OrgID uuid.UUID +} + +func unpackHideOrganizationParams(packed middleware.Parameters) (params HideOrganizationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + return params +} + +func decodeHideOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params HideOrganizationParams, _ 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, + } + } + return params, nil +} + +// ListMyCardAccessHistoryParams is parameters of ListMyCardAccessHistory operation. +type ListMyCardAccessHistoryParams 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 unpackListMyCardAccessHistoryParams(packed middleware.Parameters) (params ListMyCardAccessHistoryParams) { + { + 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 decodeListMyCardAccessHistoryParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyCardAccessHistoryParams, _ 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 +} + // ListMyConsentsParams is parameters of ListMyConsents operation. type ListMyConsentsParams struct { // Lists only the records in this state; omit it for the whole history. @@ -2225,6 +2471,182 @@ func decodeListMyConsentsParams(args [0]string, argsEscaped bool, r *http.Reques 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 + // `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 unpackListMyHiddenOrganizationsParams(packed middleware.Parameters) (params ListMyHiddenOrganizationsParams) { + { + 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 decodeListMyHiddenOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyHiddenOrganizationsParams, _ 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 +} + // ListMyInvitationsParams is parameters of ListMyInvitations operation. type ListMyInvitationsParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use @@ -2577,6 +2999,182 @@ func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.R return params, nil } +// ListMyPrivacyHistoryParams is parameters of ListMyPrivacyHistory operation. +type ListMyPrivacyHistoryParams 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 unpackListMyPrivacyHistoryParams(packed middleware.Parameters) (params ListMyPrivacyHistoryParams) { + { + 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 decodeListMyPrivacyHistoryParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyPrivacyHistoryParams, _ 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 +} + // ListMySupportCasesParams is parameters of ListMySupportCases operation. type ListMySupportCasesParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use @@ -3874,6 +4472,76 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h return params, nil } +// UnhideOrganizationParams is parameters of UnhideOrganization operation. +type UnhideOrganizationParams struct { + // Identifier of the organization that the current candidate hides or stops hiding the profile from. It + // names the target of a candidate's own setting and grants the candidate nothing about the + // organization. Hiding answers the same 404 not_found for an organization that does not exist and for + // one that the candidate cannot see, so organizations cannot be enumerated; lifting the hiding answers + // 204 for any well-formed identifier. + OrgID uuid.UUID +} + +func unpackUnhideOrganizationParams(packed middleware.Parameters) (params UnhideOrganizationParams) { + { + key := middleware.ParameterKey{ + Name: "org_id", + In: "path", + } + params.OrgID = packed[key].(uuid.UUID) + } + return params +} + +func decodeUnhideOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UnhideOrganizationParams, _ 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, + } + } + return params, nil +} + // UpdateOrganizationParams is parameters of UpdateOrganization operation. type UpdateOrganizationParams struct { // Identifier of an organization. Access comes only from an active membership of the session account in diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 2afb019..276429a 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -1357,6 +1357,164 @@ func (s *Server) decodeSendOrganizationInvitationRequest(r *http.Request) ( } } +func (s *Server) decodeSetMyPublicationRequest(r *http.Request) ( + req *PublicationUpdate, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request PublicationUpdate + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + +func (s *Server) decodeSetMySearchStatusRequest(r *http.Request) ( + req *SearchStatusUpdate, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request SearchStatusUpdate + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) ( req *AssessmentAnswerSubmission, rawBody []byte, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index fe985d7..1990573 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -1683,6 +1683,65 @@ func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w ht } } +func encodeGetMyCardPreviewResponse(response GetMyCardPreviewRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CardPreviewHeaders: + 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 *GetMyCardPreviewUnauthorized: + 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 *GetMyCardPreviewForbidden: + 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 encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateInvitationHeaders: @@ -1766,6 +1825,65 @@ func encodeGetMyInvitationResponse(response GetMyInvitationRes, w http.ResponseW } } +func encodeGetMyPrivacySettingsResponse(response GetMyPrivacySettingsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *PrivacySettingsHeaders: + 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 *GetMyPrivacySettingsUnauthorized: + 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 *GetMyPrivacySettingsForbidden: + 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 encodeGetMyProfileResponse(response GetMyProfileRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateProfileHeaders: @@ -2300,6 +2418,204 @@ func encodeGetSpecializationCatalogResponse(response *SpecializationCatalog, w h return nil } +func encodeHideOrganizationResponse(response HideOrganizationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *HiddenOrganizationHeaders: + 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 *HideOrganizationBadRequest: + 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 *HideOrganizationUnauthorized: + 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 *HideOrganizationForbidden: + 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 *HideOrganizationNotFound: + 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 *HideOrganizationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + 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 encodeListMyCardAccessHistoryResponse(response ListMyCardAccessHistoryRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *CardAccessListHeaders: + 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 *ListMyCardAccessHistoryBadRequest: + 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 *ListMyCardAccessHistoryUnauthorized: + 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 *ListMyCardAccessHistoryForbidden: + 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 encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *ConsentRecordListHeaders: @@ -2359,6 +2675,77 @@ func encodeListMyConsentsResponse(response ListMyConsentsRes, w http.ResponseWri } } +func encodeListMyHiddenOrganizationsResponse(response ListMyHiddenOrganizationsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *HiddenOrganizationListHeaders: + 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 *ListMyHiddenOrganizationsBadRequest: + 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 *ListMyHiddenOrganizationsUnauthorized: + 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 *ListMyHiddenOrganizationsForbidden: + 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 encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateInvitationListHeaders: @@ -2501,6 +2888,77 @@ func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.R } } +func encodeListMyPrivacyHistoryResponse(response ListMyPrivacyHistoryRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *PrivacyEventListHeaders: + 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 *ListMyPrivacyHistoryBadRequest: + 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 *ListMyPrivacyHistoryUnauthorized: + 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 *ListMyPrivacyHistoryForbidden: + 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 encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *SupportCaseListHeaders: @@ -3554,6 +4012,184 @@ func encodeSendOrganizationInvitationResponse(response SendOrganizationInvitatio } } +func encodeSetMyPublicationResponse(response SetMyPublicationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *PublicationHeaders: + 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 *SetMyPublicationBadRequest: + 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 *SetMyPublicationUnauthorized: + 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 *SetMyPublicationForbidden: + 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 *SetMyPublicationConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *SetMyPublicationPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + +func encodeSetMySearchStatusResponse(response SetMySearchStatusRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *SearchStatusHeaders: + 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 *SetMySearchStatusBadRequest: + 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 *SetMySearchStatusUnauthorized: + 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 *SetMySearchStatusForbidden: + 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 *SetMySearchStatusPreconditionFailed: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(412) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentAttemptHeaders: @@ -3705,6 +4341,70 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes } } +func encodeUnhideOrganizationResponse(response UnhideOrganizationRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *UnhideOrganizationNoContent: + // 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(204) + + return nil + + case *UnhideOrganizationBadRequest: + 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 *UnhideOrganizationUnauthorized: + 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 *UnhideOrganizationForbidden: + 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 encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *OrganizationHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index f5f0910..d9f2b0d 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,16 +11,16 @@ import ( ) var ( - rn49AllowedHeaders = map[string]string{ + rn59AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn7AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn47AllowedHeaders = map[string]string{ + rn57AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn44AllowedHeaders = map[string]string{ + rn54AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn25AllowedHeaders = map[string]string{ @@ -29,7 +29,7 @@ var ( rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn52AllowedHeaders = map[string]string{ + rn65AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn20AllowedHeaders = map[string]string{ @@ -44,13 +44,23 @@ var ( rn17AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn53AllowedHeaders = map[string]string{ + rn66AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn31AllowedHeaders = map[string]string{ + rn46AllowedHeaders = map[string]string{ + "DELETE": "X-Csrf-Token", + "PUT": "X-Csrf-Token", + } + rn63AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn32AllowedHeaders = map[string]string{ + rn64AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", + } + rn34AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", + } + rn35AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } rn10AllowedHeaders = map[string]string{ @@ -65,22 +75,22 @@ var ( rn14AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn36AllowedHeaders = map[string]string{ + rn39AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn46AllowedHeaders = map[string]string{ + rn56AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn51AllowedHeaders = map[string]string{ + rn61AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn54AllowedHeaders = map[string]string{ + rn67AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn16AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn39AllowedHeaders = map[string]string{ + rn42AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } ) @@ -237,7 +247,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn49AllowedHeaders, + allowedHeaders: rn59AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -314,7 +324,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn47AllowedHeaders, + allowedHeaders: rn57AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -338,7 +348,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn44AllowedHeaders, + allowedHeaders: rn54AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -491,7 +501,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn52AllowedHeaders, + allowedHeaders: rn65AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -782,7 +792,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn53AllowedHeaders, + allowedHeaders: rn66AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -822,31 +832,304 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - case 'p': // Prefix: "profile" + case 'p': // Prefix: "pr" - if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" { + if l := len("pr"); len(elem) >= l && elem[0:l] == "pr" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r) - case "PUT": - s.handleSaveMyProfileRequest([0]string{}, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET,PUT", - allowedHeaders: rn31AllowedHeaders, - acceptPost: "", - acceptPatch: "", - }) + break + } + switch elem[0] { + case 'i': // Prefix: "ivacy" + + if l := len("ivacy"); len(elem) >= l && elem[0:l] == "ivacy" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleGetMyPrivacySettingsRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "access-history" + + if l := len("access-history"); len(elem) >= l && elem[0:l] == "access-history" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleListMyCardAccessHistoryRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'h': // Prefix: "hi" + + if l := len("hi"); len(elem) >= l && elem[0:l] == "hi" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'd': // Prefix: "dden-organizations" + + if l := len("dden-organizations"); len(elem) >= l && elem[0:l] == "dden-organizations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch r.Method { + case "GET": + s.handleListMyHiddenOrganizationsRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "org_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "DELETE": + s.handleUnhideOrganizationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + case "PUT": + s.handleHideOrganizationRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "DELETE,PUT", + allowedHeaders: rn46AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + case 's': // Prefix: "story" + + if l := len("story"); len(elem) >= l && elem[0:l] == "story" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleListMyPrivacyHistoryRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + case 'p': // Prefix: "p" + + if l := len("p"); len(elem) >= l && elem[0:l] == "p" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'r': // Prefix: "review" + + if l := len("review"); len(elem) >= l && elem[0:l] == "review" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyCardPreviewRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 'u': // Prefix: "ublication" + + if l := len("ublication"); len(elem) >= l && elem[0:l] == "ublication" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "PUT": + s.handleSetMyPublicationRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "PUT", + allowedHeaders: rn63AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + case 's': // Prefix: "search-status" + + if l := len("search-status"); len(elem) >= l && elem[0:l] == "search-status" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "PUT": + s.handleSetMySearchStatusRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "PUT", + allowedHeaders: rn64AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + } + + } + + case 'o': // Prefix: "ofile" + + if l := len("ofile"); len(elem) >= l && elem[0:l] == "ofile" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r) + case "PUT": + s.handleSaveMyProfileRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PUT", + allowedHeaders: rn34AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return } - return } case 'q': // Prefix: "questionnaire" @@ -867,7 +1150,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn32AllowedHeaders, + allowedHeaders: rn35AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1079,7 +1362,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn36AllowedHeaders, + allowedHeaders: rn39AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1159,7 +1442,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn46AllowedHeaders, + allowedHeaders: rn56AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1187,7 +1470,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn51AllowedHeaders, + allowedHeaders: rn61AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1217,7 +1500,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn54AllowedHeaders, + allowedHeaders: rn67AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1295,7 +1578,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn39AllowedHeaders, + allowedHeaders: rn42AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2110,38 +2393,314 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } - case 'p': // Prefix: "profile" + case 'p': // Prefix: "pr" - if l := len("profile"); len(elem) >= l && elem[0:l] == "profile" { + if l := len("pr"); len(elem) >= l && elem[0:l] == "pr" { elem = elem[l:] } else { break } if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetMyProfileOperation - r.summary = "Read the private profile of the current candidate." - r.operationID = "GetMyProfile" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/profile" - r.args = args - r.count = 0 - return r, true - case "PUT": - r.name = SaveMyProfileOperation - r.summary = "Replace the private profile of the current candidate." - r.operationID = "SaveMyProfile" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/profile" - r.args = args - r.count = 0 - return r, true - default: - return + break + } + switch elem[0] { + case 'i': // Prefix: "ivacy" + + if l := len("ivacy"); len(elem) >= l && elem[0:l] == "ivacy" { + elem = elem[l:] + } else { + break } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = GetMyPrivacySettingsOperation + r.summary = "Read the visibility settings of the current candidate." + r.operationID = "GetMyPrivacySettings" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'a': // Prefix: "access-history" + + if l := len("access-history"); len(elem) >= l && elem[0:l] == "access-history" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = ListMyCardAccessHistoryOperation + r.summary = "List the accesses of organizations to the card of the current candidate." + r.operationID = "ListMyCardAccessHistory" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/access-history" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'h': // Prefix: "hi" + + if l := len("hi"); len(elem) >= l && elem[0:l] == "hi" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'd': // Prefix: "dden-organizations" + + if l := len("dden-organizations"); len(elem) >= l && elem[0:l] == "dden-organizations" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + switch method { + case "GET": + r.name = ListMyHiddenOrganizationsOperation + r.summary = "List the organizations that the candidate hides the profile from." + r.operationID = "ListMyHiddenOrganizations" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/hidden-organizations" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + switch elem[0] { + case '/': // Prefix: "/" + + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + elem = elem[l:] + } else { + break + } + + // Param: "org_id" + // Leaf parameter, slashes are prohibited + idx := strings.IndexByte(elem, '/') + if idx >= 0 { + break + } + args[0] = elem + elem = "" + + if len(elem) == 0 { + // Leaf node. + switch method { + case "DELETE": + r.name = UnhideOrganizationOperation + r.summary = "Lift the hiding of the candidate profile from one organization." + r.operationID = "UnhideOrganization" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/hidden-organizations/{org_id}" + r.args = args + r.count = 1 + return r, true + case "PUT": + r.name = HideOrganizationOperation + r.summary = "Hide the candidate profile from one organization." + r.operationID = "HideOrganization" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/hidden-organizations/{org_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + + case 's': // Prefix: "story" + + if l := len("story"); len(elem) >= l && elem[0:l] == "story" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = ListMyPrivacyHistoryOperation + r.summary = "List the changes of the visibility settings of the current candidate." + r.operationID = "ListMyPrivacyHistory" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/history" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + case 'p': // Prefix: "p" + + if l := len("p"); len(elem) >= l && elem[0:l] == "p" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'r': // Prefix: "review" + + if l := len("review"); len(elem) >= l && elem[0:l] == "review" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyCardPreviewOperation + r.summary = "Preview the anonymous card that organizations would read." + r.operationID = "GetMyCardPreview" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/preview" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 'u': // Prefix: "ublication" + + if l := len("ublication"); len(elem) >= l && elem[0:l] == "ublication" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "PUT": + r.name = SetMyPublicationOperation + r.summary = "Publish or close the anonymous candidate card." + r.operationID = "SetMyPublication" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/publication" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + case 's': // Prefix: "search-status" + + if l := len("search-status"); len(elem) >= l && elem[0:l] == "search-status" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "PUT": + r.name = SetMySearchStatusOperation + r.summary = "Set or confirm the search status of the current candidate." + r.operationID = "SetMySearchStatus" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/privacy/search-status" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } + + } + + case 'o': // Prefix: "ofile" + + if l := len("ofile"); len(elem) >= l && elem[0:l] == "ofile" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyProfileOperation + r.summary = "Read the private profile of the current candidate." + r.operationID = "GetMyProfile" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/profile" + r.args = args + r.count = 0 + return r, true + case "PUT": + r.name = SaveMyProfileOperation + r.summary = "Replace the private profile of the current candidate." + r.operationID = "SaveMyProfile" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/profile" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + } case 'q': // Prefix: "questionnaire" diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 6a5170b..5ff774c 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -190,6 +190,95 @@ func (s *AccountScenario) UnmarshalText(data []byte) error { } } +// The anonymous candidate card as an organization reads it. Only values that the candidate confirmed +// reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a +// soft skill, the location) that looks like a contact (an email address, a phone number, a URL or +// domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It +// carries no name, contact, resume text, employer, salary figure, account or profile identifier, and +// no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches +// an organization only through the contact grant of an accepted invitation. Each property is null when +// its field is not published or the candidate has no value for it, so the card does not tell the two +// apart. The set of properties is closed, and an organization-visible card must never gain a property +// that identifies the candidate. The search ranking and the full card of an organization's search +// result are defined by the search contract (TASK-185), which reuses this content. +// Ref: #/components/schemas/AnonymousCardContent +type AnonymousCardContent struct { + // Categories confirmed by assessment results, or null. + Categories []CardCategory `json:"categories"` + // Technology tags of the candidate, or null. + Stack []StackTag `json:"stack"` + // Total months of work experience, summed by the server without the employers, periods, or + // descriptions, or null. + ExperienceMonths NilInt `json:"experience_months"` + // Soft skills of the candidate, or null. + SoftSkills []string `json:"soft_skills"` + // City or region as free text, never a street address, or null. Plain text; clients show it as text, + // never as HTML. + Location NilString `json:"location"` + // Whether the candidate is ready to relocate, or null. + Relocation NilBool `json:"relocation"` +} + +// GetCategories returns the value of Categories. +func (s *AnonymousCardContent) GetCategories() []CardCategory { + return s.Categories +} + +// GetStack returns the value of Stack. +func (s *AnonymousCardContent) GetStack() []StackTag { + return s.Stack +} + +// GetExperienceMonths returns the value of ExperienceMonths. +func (s *AnonymousCardContent) GetExperienceMonths() NilInt { + return s.ExperienceMonths +} + +// GetSoftSkills returns the value of SoftSkills. +func (s *AnonymousCardContent) GetSoftSkills() []string { + return s.SoftSkills +} + +// GetLocation returns the value of Location. +func (s *AnonymousCardContent) GetLocation() NilString { + return s.Location +} + +// GetRelocation returns the value of Relocation. +func (s *AnonymousCardContent) GetRelocation() NilBool { + return s.Relocation +} + +// SetCategories sets the value of Categories. +func (s *AnonymousCardContent) SetCategories(val []CardCategory) { + s.Categories = val +} + +// SetStack sets the value of Stack. +func (s *AnonymousCardContent) SetStack(val []StackTag) { + s.Stack = val +} + +// SetExperienceMonths sets the value of ExperienceMonths. +func (s *AnonymousCardContent) SetExperienceMonths(val NilInt) { + s.ExperienceMonths = val +} + +// SetSoftSkills sets the value of SoftSkills. +func (s *AnonymousCardContent) SetSoftSkills(val []string) { + s.SoftSkills = val +} + +// SetLocation sets the value of Location. +func (s *AnonymousCardContent) SetLocation(val NilString) { + s.Location = val +} + +// SetRelocation sets the value of Relocation. +func (s *AnonymousCardContent) SetRelocation(val NilBool) { + s.Relocation = val +} + // Candidate answer, selected by `format`, which must equal the format of the answered item. It carries // only the answer: no score, duration, correctness flag, or seed. The server records the times itself // and scores the answer with the key of the fixed item instance. Each format defines when two answers @@ -3292,6 +3381,364 @@ func (s *CandidateQuestionnaireUpdate) SetWorkContext(val WorkContext) { s.WorkContext = val } +// One access of an organization to the card or the contacts of the current candidate. `organization` +// is null for a view by an organization that has no invitation relation with the candidate, so the +// history shows that the card was viewed without naming a company that the candidate cannot otherwise +// see; whether the candidate should learn the name is an open product question. The record carries no +// query, ranking, or search filter of the organization. +// Ref: #/components/schemas/CardAccess +type CardAccess struct { + // Identifier of the access record. + ID uuid.UUID `json:"id"` + Kind CardAccessKind `json:"kind"` + OccurredAt Timestamp `json:"occurred_at"` + Organization NilPrivacyOrganization `json:"organization"` +} + +// GetID returns the value of ID. +func (s *CardAccess) GetID() uuid.UUID { + return s.ID +} + +// GetKind returns the value of Kind. +func (s *CardAccess) GetKind() CardAccessKind { + return s.Kind +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *CardAccess) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// GetOrganization returns the value of Organization. +func (s *CardAccess) GetOrganization() NilPrivacyOrganization { + return s.Organization +} + +// SetID sets the value of ID. +func (s *CardAccess) SetID(val uuid.UUID) { + s.ID = val +} + +// SetKind sets the value of Kind. +func (s *CardAccess) SetKind(val CardAccessKind) { + s.Kind = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *CardAccess) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +// SetOrganization sets the value of Organization. +func (s *CardAccess) SetOrganization(val NilPrivacyOrganization) { + s.Organization = val +} + +// How an organization reached the candidate. +// +// - card_viewed: an organization read the anonymous card in a search result. +// - contact_read: an organization read the contacts through the contact grant of an accepted +// invitation. +// +// Ref: #/components/schemas/CardAccessKind +type CardAccessKind string + +const ( + CardAccessKindCardViewed CardAccessKind = "card_viewed" + CardAccessKindContactRead CardAccessKind = "contact_read" +) + +// AllValues returns all CardAccessKind values. +func (CardAccessKind) AllValues() []CardAccessKind { + return []CardAccessKind{ + CardAccessKindCardViewed, + CardAccessKindContactRead, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CardAccessKind) MarshalText() ([]byte, error) { + switch s { + case CardAccessKindCardViewed: + return []byte(s), nil + case CardAccessKindContactRead: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CardAccessKind) UnmarshalText(data []byte) error { + switch CardAccessKind(data) { + case CardAccessKindCardViewed: + *s = CardAccessKindCardViewed + return nil + case CardAccessKindContactRead: + *s = CardAccessKindContactRead + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One page of the accesses to the card of the current candidate, newest first. +// Ref: #/components/schemas/CardAccessList +type CardAccessList struct { + // Accesses of the page. + Items []CardAccess `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *CardAccessList) GetItems() []CardAccess { + return s.Items +} + +// GetPage returns the value of Page. +func (s *CardAccessList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *CardAccessList) SetItems(val []CardAccess) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *CardAccessList) SetPage(val PageInfo) { + s.Page = val +} + +// CardAccessListHeaders wraps CardAccessList with response headers. +type CardAccessListHeaders struct { + CacheControl CacheControlNoStore + Response CardAccessList +} + +// GetCacheControl returns the value of CacheControl. +func (s *CardAccessListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CardAccessListHeaders) GetResponse() CardAccessList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CardAccessListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CardAccessListHeaders) SetResponse(val CardAccessList) { + s.Response = val +} + +func (*CardAccessListHeaders) listMyCardAccessHistoryRes() {} + +// A category confirmed by assessment results, as the card shows it. +// Ref: #/components/schemas/CardCategory +type CardCategory struct { + Specialization SpecializationCode `json:"specialization"` + Grade GradeCode `json:"grade"` +} + +// GetSpecialization returns the value of Specialization. +func (s *CardCategory) GetSpecialization() SpecializationCode { + return s.Specialization +} + +// GetGrade returns the value of Grade. +func (s *CardCategory) GetGrade() GradeCode { + return s.Grade +} + +// SetSpecialization sets the value of Specialization. +func (s *CardCategory) SetSpecialization(val SpecializationCode) { + s.Specialization = val +} + +// SetGrade sets the value of Grade. +func (s *CardCategory) SetGrade(val GradeCode) { + s.Grade = val +} + +// A group of values of the anonymous candidate card that the candidate chooses to publish. The set is +// closed and has no value for the full name, a contact, or the lowest salary: the card never carries +// them, so no choice and no later contract change in this list can publish them by accident. Contacts +// leave only through the contact grant of an accepted invitation (C4), and the lowest salary never +// leaves. +// +// - categories: the categories confirmed by assessment results (specialization and confirmed grade). +// A self-assessed grade is not a category and is never published. +// - stack: the technology tags of the profile. +// - experience: the total months of work experience, without employers, periods, or descriptions. +// - soft_skills: the soft skills of the profile. +// - location: the city or region of the profile. +// - relocation: whether the candidate is ready to relocate. +// +// Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status +// `extracted`) and an unknown value never do, whatever the field set says. +// +// Adding a value is a contract change that lets a candidate publish more, and it is also a migration +// (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and +// event tables list the codes). A client treats an unknown value as a reason to ask for an update, and +// the server never adds a new value to a published set on its own. +// Ref: #/components/schemas/CardField +type CardField string + +const ( + CardFieldCategories CardField = "categories" + CardFieldStack CardField = "stack" + CardFieldExperience CardField = "experience" + CardFieldSoftSkills CardField = "soft_skills" + CardFieldLocation CardField = "location" + CardFieldRelocation CardField = "relocation" +) + +// AllValues returns all CardField values. +func (CardField) AllValues() []CardField { + return []CardField{ + CardFieldCategories, + CardFieldStack, + CardFieldExperience, + CardFieldSoftSkills, + CardFieldLocation, + CardFieldRelocation, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s CardField) MarshalText() ([]byte, error) { + switch s { + case CardFieldCategories: + return []byte(s), nil + case CardFieldStack: + return []byte(s), nil + case CardFieldExperience: + return []byte(s), nil + case CardFieldSoftSkills: + return []byte(s), nil + case CardFieldLocation: + return []byte(s), nil + case CardFieldRelocation: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *CardField) UnmarshalText(data []byte) error { + switch CardField(data) { + case CardFieldCategories: + *s = CardFieldCategories + return nil + case CardFieldStack: + *s = CardFieldStack + return nil + case CardFieldExperience: + *s = CardFieldExperience + return nil + case CardFieldSoftSkills: + *s = CardFieldSoftSkills + return nil + case CardFieldLocation: + *s = CardFieldLocation + return nil + case CardFieldRelocation: + *s = CardFieldRelocation + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type CardFieldSet []CardField + +// What an organization that the candidate does not hide the profile from would read now, computed from +// the current profile, the current publication, and the consent ledger. It is a read for the +// candidate: it creates no view and no history record, and it never reaches an organization. `card` is +// null while the profile is closed. +// Ref: #/components/schemas/CardPreview +type CardPreview struct { + State PublicationState `json:"state"` + Fields CardFieldSet `json:"fields"` + Card NilAnonymousCardContent `json:"card"` + GeneratedAt Timestamp `json:"generated_at"` +} + +// GetState returns the value of State. +func (s *CardPreview) GetState() PublicationState { + return s.State +} + +// GetFields returns the value of Fields. +func (s *CardPreview) GetFields() CardFieldSet { + return s.Fields +} + +// GetCard returns the value of Card. +func (s *CardPreview) GetCard() NilAnonymousCardContent { + return s.Card +} + +// GetGeneratedAt returns the value of GeneratedAt. +func (s *CardPreview) GetGeneratedAt() Timestamp { + return s.GeneratedAt +} + +// SetState sets the value of State. +func (s *CardPreview) SetState(val PublicationState) { + s.State = val +} + +// SetFields sets the value of Fields. +func (s *CardPreview) SetFields(val CardFieldSet) { + s.Fields = val +} + +// SetCard sets the value of Card. +func (s *CardPreview) SetCard(val NilAnonymousCardContent) { + s.Card = val +} + +// SetGeneratedAt sets the value of GeneratedAt. +func (s *CardPreview) SetGeneratedAt(val Timestamp) { + s.GeneratedAt = val +} + +// CardPreviewHeaders wraps CardPreview with response headers. +type CardPreviewHeaders struct { + CacheControl CacheControlNoStore + Response CardPreview +} + +// GetCacheControl returns the value of CacheControl. +func (s *CardPreviewHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *CardPreviewHeaders) GetResponse() CardPreview { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *CardPreviewHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *CardPreviewHeaders) SetResponse(val CardPreview) { + s.Response = val +} + +func (*CardPreviewHeaders) getMyCardPreviewRes() {} + // Professional direction with its specializations. Each specialization belongs to exactly one // direction. // Ref: #/components/schemas/CatalogDirection @@ -5486,6 +5933,14 @@ type GetMyAssessmentResultUnauthorized Problem func (*GetMyAssessmentResultUnauthorized) getMyAssessmentResultRes() {} +type GetMyCardPreviewForbidden Problem + +func (*GetMyCardPreviewForbidden) getMyCardPreviewRes() {} + +type GetMyCardPreviewUnauthorized Problem + +func (*GetMyCardPreviewUnauthorized) getMyCardPreviewRes() {} + type GetMyInvitationBadRequest Problem func (*GetMyInvitationBadRequest) getMyInvitationRes() {} @@ -5502,6 +5957,14 @@ type GetMyInvitationUnauthorized Problem func (*GetMyInvitationUnauthorized) getMyInvitationRes() {} +type GetMyPrivacySettingsForbidden Problem + +func (*GetMyPrivacySettingsForbidden) getMyPrivacySettingsRes() {} + +type GetMyPrivacySettingsUnauthorized Problem + +func (*GetMyPrivacySettingsUnauthorized) getMyPrivacySettingsRes() {} + type GetMyProfileForbidden Problem func (*GetMyProfileForbidden) getMyProfileRes() {} @@ -5703,6 +6166,140 @@ func (s *HealthResponseStatus) UnmarshalText(data []byte) error { } } +// One organization that the candidate hides the profile from. The record belongs to the candidate: no +// organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not +// published. +// Ref: #/components/schemas/HiddenOrganization +type HiddenOrganization struct { + Organization PrivacyOrganization `json:"organization"` + HiddenAt Timestamp `json:"hidden_at"` +} + +// GetOrganization returns the value of Organization. +func (s *HiddenOrganization) GetOrganization() PrivacyOrganization { + return s.Organization +} + +// GetHiddenAt returns the value of HiddenAt. +func (s *HiddenOrganization) GetHiddenAt() Timestamp { + return s.HiddenAt +} + +// SetOrganization sets the value of Organization. +func (s *HiddenOrganization) SetOrganization(val PrivacyOrganization) { + s.Organization = val +} + +// SetHiddenAt sets the value of HiddenAt. +func (s *HiddenOrganization) SetHiddenAt(val Timestamp) { + s.HiddenAt = val +} + +// HiddenOrganizationHeaders wraps HiddenOrganization with response headers. +type HiddenOrganizationHeaders struct { + CacheControl CacheControlNoStore + Response HiddenOrganization +} + +// GetCacheControl returns the value of CacheControl. +func (s *HiddenOrganizationHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *HiddenOrganizationHeaders) GetResponse() HiddenOrganization { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *HiddenOrganizationHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *HiddenOrganizationHeaders) SetResponse(val HiddenOrganization) { + s.Response = val +} + +func (*HiddenOrganizationHeaders) hideOrganizationRes() {} + +// One page of the organizations that the candidate hides the profile from, newest first with the +// organization identifier as the tie-breaker. +// Ref: #/components/schemas/HiddenOrganizationList +type HiddenOrganizationList struct { + // Hidden organizations of the page. + Items []HiddenOrganization `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *HiddenOrganizationList) GetItems() []HiddenOrganization { + return s.Items +} + +// GetPage returns the value of Page. +func (s *HiddenOrganizationList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *HiddenOrganizationList) SetItems(val []HiddenOrganization) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *HiddenOrganizationList) SetPage(val PageInfo) { + s.Page = val +} + +// HiddenOrganizationListHeaders wraps HiddenOrganizationList with response headers. +type HiddenOrganizationListHeaders struct { + CacheControl CacheControlNoStore + Response HiddenOrganizationList +} + +// GetCacheControl returns the value of CacheControl. +func (s *HiddenOrganizationListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *HiddenOrganizationListHeaders) GetResponse() HiddenOrganizationList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *HiddenOrganizationListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *HiddenOrganizationListHeaders) SetResponse(val HiddenOrganizationList) { + s.Response = val +} + +func (*HiddenOrganizationListHeaders) listMyHiddenOrganizationsRes() {} + +type HideOrganizationBadRequest Problem + +func (*HideOrganizationBadRequest) hideOrganizationRes() {} + +type HideOrganizationConflict Problem + +func (*HideOrganizationConflict) hideOrganizationRes() {} + +type HideOrganizationForbidden Problem + +func (*HideOrganizationForbidden) hideOrganizationRes() {} + +type HideOrganizationNotFound Problem + +func (*HideOrganizationNotFound) hideOrganizationRes() {} + +type HideOrganizationUnauthorized Problem + +func (*HideOrganizationUnauthorized) hideOrganizationRes() {} + // Neutral acknowledgement. Its content is identical whether or not the address belongs to an account // or is already verified, so the response does not enumerate accounts. The client tells the user to // check the mailbox. @@ -7261,6 +7858,18 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +type ListMyCardAccessHistoryBadRequest Problem + +func (*ListMyCardAccessHistoryBadRequest) listMyCardAccessHistoryRes() {} + +type ListMyCardAccessHistoryForbidden Problem + +func (*ListMyCardAccessHistoryForbidden) listMyCardAccessHistoryRes() {} + +type ListMyCardAccessHistoryUnauthorized Problem + +func (*ListMyCardAccessHistoryUnauthorized) listMyCardAccessHistoryRes() {} + type ListMyConsentsBadRequest Problem func (*ListMyConsentsBadRequest) listMyConsentsRes() {} @@ -7269,6 +7878,18 @@ type ListMyConsentsUnauthorized Problem func (*ListMyConsentsUnauthorized) listMyConsentsRes() {} +type ListMyHiddenOrganizationsBadRequest Problem + +func (*ListMyHiddenOrganizationsBadRequest) listMyHiddenOrganizationsRes() {} + +type ListMyHiddenOrganizationsForbidden Problem + +func (*ListMyHiddenOrganizationsForbidden) listMyHiddenOrganizationsRes() {} + +type ListMyHiddenOrganizationsUnauthorized Problem + +func (*ListMyHiddenOrganizationsUnauthorized) listMyHiddenOrganizationsRes() {} + type ListMyInvitationsBadRequest Problem func (*ListMyInvitationsBadRequest) listMyInvitationsRes() {} @@ -7293,6 +7914,18 @@ type ListMyOrganizationsUnauthorized Problem func (*ListMyOrganizationsUnauthorized) listMyOrganizationsRes() {} +type ListMyPrivacyHistoryBadRequest Problem + +func (*ListMyPrivacyHistoryBadRequest) listMyPrivacyHistoryRes() {} + +type ListMyPrivacyHistoryForbidden Problem + +func (*ListMyPrivacyHistoryForbidden) listMyPrivacyHistoryRes() {} + +type ListMyPrivacyHistoryUnauthorized Problem + +func (*ListMyPrivacyHistoryUnauthorized) listMyPrivacyHistoryRes() {} + type ListMySupportCasesBadRequest Problem func (*ListMySupportCasesBadRequest) listMySupportCasesRes() {} @@ -9771,6 +10404,51 @@ func (s *NeedWorkFormatsInput) SetStatus(val NeedItemStatus) { type NewPassword string +// NewNilAnonymousCardContent returns new NilAnonymousCardContent with value set to v. +func NewNilAnonymousCardContent(v AnonymousCardContent) NilAnonymousCardContent { + return NilAnonymousCardContent{ + Value: v, + } +} + +// NilAnonymousCardContent is nullable AnonymousCardContent. +type NilAnonymousCardContent struct { + Value AnonymousCardContent + Null bool +} + +// SetTo sets value to v. +func (o *NilAnonymousCardContent) SetTo(v AnonymousCardContent) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAnonymousCardContent) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAnonymousCardContent) SetToNull() { + o.Null = true + var v AnonymousCardContent + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAnonymousCardContent) Get() (v AnonymousCardContent, 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 NilAnonymousCardContent) Or(d AnonymousCardContent) AnonymousCardContent { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilAssessmentItem returns new NilAssessmentItem with value set to v. func NewNilAssessmentItem(v AssessmentItem) NilAssessmentItem { return NilAssessmentItem{ @@ -10716,6 +11394,51 @@ func (o NilGradeCode) Or(d GradeCode) GradeCode { return d } +// NewNilInt returns new NilInt with value set to v. +func NewNilInt(v int) NilInt { + return NilInt{ + Value: v, + } +} + +// NilInt is nullable int. +type NilInt struct { + Value int + Null bool +} + +// SetTo sets value to v. +func (o *NilInt) SetTo(v int) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilInt) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilInt) SetToNull() { + o.Null = true + var v int + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilInt) Get() (v int, 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 NilInt) Or(d int) int { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilInt32 returns new NilInt32 with value set to v. func NewNilInt32(v int32) NilInt32 { return NilInt32{ @@ -11571,6 +12294,51 @@ func (o NilPracticeVerdict) Or(d PracticeVerdict) PracticeVerdict { return d } +// NewNilPrivacyOrganization returns new NilPrivacyOrganization with value set to v. +func NewNilPrivacyOrganization(v PrivacyOrganization) NilPrivacyOrganization { + return NilPrivacyOrganization{ + Value: v, + } +} + +// NilPrivacyOrganization is nullable PrivacyOrganization. +type NilPrivacyOrganization struct { + Value PrivacyOrganization + Null bool +} + +// SetTo sets value to v. +func (o *NilPrivacyOrganization) SetTo(v PrivacyOrganization) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilPrivacyOrganization) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilPrivacyOrganization) SetToNull() { + o.Null = true + var v PrivacyOrganization + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilPrivacyOrganization) Get() (v PrivacyOrganization, 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 NilPrivacyOrganization) Or(d PrivacyOrganization) PrivacyOrganization { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilProfileClaimQuote returns new NilProfileClaimQuote with value set to v. func NewNilProfileClaimQuote(v ProfileClaimQuote) NilProfileClaimQuote { return NilProfileClaimQuote{ @@ -12201,6 +12969,51 @@ func (o NilProfileYearMonth) Or(d ProfileYearMonth) ProfileYearMonth { return d } +// NewNilPublicationClosedReason returns new NilPublicationClosedReason with value set to v. +func NewNilPublicationClosedReason(v PublicationClosedReason) NilPublicationClosedReason { + return NilPublicationClosedReason{ + Value: v, + } +} + +// NilPublicationClosedReason is nullable PublicationClosedReason. +type NilPublicationClosedReason struct { + Value PublicationClosedReason + Null bool +} + +// SetTo sets value to v. +func (o *NilPublicationClosedReason) SetTo(v PublicationClosedReason) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilPublicationClosedReason) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilPublicationClosedReason) SetToNull() { + o.Null = true + var v PublicationClosedReason + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilPublicationClosedReason) Get() (v PublicationClosedReason, 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 NilPublicationClosedReason) Or(d PublicationClosedReason) PublicationClosedReason { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilSalaryRange returns new NilSalaryRange with value set to v. func NewNilSalaryRange(v SalaryRange) NilSalaryRange { return NilSalaryRange{ @@ -16434,6 +17247,333 @@ func (s *PracticeVerdict) SetGroups(val []PracticeGroupResult) { s.Groups = val } +// One recorded change of the visibility settings of the current candidate, as evidence of what was +// published, hidden, or announced and when. The history is append-only and returns only the caller's +// own records. A publication event carries the published fields and the C2 record behind them; an +// organization event names the organization; the other properties are null. +// Ref: #/components/schemas/PrivacyEvent +type PrivacyEvent struct { + // Identifier of the event. + ID uuid.UUID `json:"id"` + Kind PrivacyEventKind `json:"kind"` + OccurredAt Timestamp `json:"occurred_at"` + // Published fields after the change for `publication_opened` and `publication_changed`, an empty set + // for `publication_closed`, and null for every other kind. + Fields CardFieldSet `json:"fields"` + // C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null. + ConsentID NilUUID `json:"consent_id"` + // Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved + // when the history is read (the event stores only the identifier), or null. + Organization NilPrivacyOrganization `json:"organization"` +} + +// GetID returns the value of ID. +func (s *PrivacyEvent) GetID() uuid.UUID { + return s.ID +} + +// GetKind returns the value of Kind. +func (s *PrivacyEvent) GetKind() PrivacyEventKind { + return s.Kind +} + +// GetOccurredAt returns the value of OccurredAt. +func (s *PrivacyEvent) GetOccurredAt() Timestamp { + return s.OccurredAt +} + +// GetFields returns the value of Fields. +func (s *PrivacyEvent) GetFields() CardFieldSet { + return s.Fields +} + +// GetConsentID returns the value of ConsentID. +func (s *PrivacyEvent) GetConsentID() NilUUID { + return s.ConsentID +} + +// GetOrganization returns the value of Organization. +func (s *PrivacyEvent) GetOrganization() NilPrivacyOrganization { + return s.Organization +} + +// SetID sets the value of ID. +func (s *PrivacyEvent) SetID(val uuid.UUID) { + s.ID = val +} + +// SetKind sets the value of Kind. +func (s *PrivacyEvent) SetKind(val PrivacyEventKind) { + s.Kind = val +} + +// SetOccurredAt sets the value of OccurredAt. +func (s *PrivacyEvent) SetOccurredAt(val Timestamp) { + s.OccurredAt = val +} + +// SetFields sets the value of Fields. +func (s *PrivacyEvent) SetFields(val CardFieldSet) { + s.Fields = val +} + +// SetConsentID sets the value of ConsentID. +func (s *PrivacyEvent) SetConsentID(val NilUUID) { + s.ConsentID = val +} + +// SetOrganization sets the value of Organization. +func (s *PrivacyEvent) SetOrganization(val NilPrivacyOrganization) { + s.Organization = val +} + +// Kind of a change of the visibility settings that the history records. +// +// - publication_opened: the candidate published a closed profile. +// - publication_changed: the candidate changed the published fields of a published profile, or +// published it again under a new C2 record. +// - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by +// the ledger and is read from the consent history, not recorded here. +// - search_status_confirmed: the candidate set or confirmed `looking`. +// - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. +// - organization_hidden: the candidate hid the profile from an organization. +// - organization_unhidden: the candidate lifted the hiding for an organization. +// +// Ref: #/components/schemas/PrivacyEventKind +type PrivacyEventKind string + +const ( + PrivacyEventKindPublicationOpened PrivacyEventKind = "publication_opened" + PrivacyEventKindPublicationChanged PrivacyEventKind = "publication_changed" + PrivacyEventKindPublicationClosed PrivacyEventKind = "publication_closed" + PrivacyEventKindSearchStatusConfirmed PrivacyEventKind = "search_status_confirmed" + PrivacyEventKindSearchStatusCleared PrivacyEventKind = "search_status_cleared" + PrivacyEventKindOrganizationHidden PrivacyEventKind = "organization_hidden" + PrivacyEventKindOrganizationUnhidden PrivacyEventKind = "organization_unhidden" +) + +// AllValues returns all PrivacyEventKind values. +func (PrivacyEventKind) AllValues() []PrivacyEventKind { + return []PrivacyEventKind{ + PrivacyEventKindPublicationOpened, + PrivacyEventKindPublicationChanged, + PrivacyEventKindPublicationClosed, + PrivacyEventKindSearchStatusConfirmed, + PrivacyEventKindSearchStatusCleared, + PrivacyEventKindOrganizationHidden, + PrivacyEventKindOrganizationUnhidden, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PrivacyEventKind) MarshalText() ([]byte, error) { + switch s { + case PrivacyEventKindPublicationOpened: + return []byte(s), nil + case PrivacyEventKindPublicationChanged: + return []byte(s), nil + case PrivacyEventKindPublicationClosed: + return []byte(s), nil + case PrivacyEventKindSearchStatusConfirmed: + return []byte(s), nil + case PrivacyEventKindSearchStatusCleared: + return []byte(s), nil + case PrivacyEventKindOrganizationHidden: + return []byte(s), nil + case PrivacyEventKindOrganizationUnhidden: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PrivacyEventKind) UnmarshalText(data []byte) error { + switch PrivacyEventKind(data) { + case PrivacyEventKindPublicationOpened: + *s = PrivacyEventKindPublicationOpened + return nil + case PrivacyEventKindPublicationChanged: + *s = PrivacyEventKindPublicationChanged + return nil + case PrivacyEventKindPublicationClosed: + *s = PrivacyEventKindPublicationClosed + return nil + case PrivacyEventKindSearchStatusConfirmed: + *s = PrivacyEventKindSearchStatusConfirmed + return nil + case PrivacyEventKindSearchStatusCleared: + *s = PrivacyEventKindSearchStatusCleared + return nil + case PrivacyEventKindOrganizationHidden: + *s = PrivacyEventKindOrganizationHidden + return nil + case PrivacyEventKindOrganizationUnhidden: + *s = PrivacyEventKindOrganizationUnhidden + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// One page of the settings history of the current candidate, newest first. +// Ref: #/components/schemas/PrivacyEventList +type PrivacyEventList struct { + // Events of the page. + Items []PrivacyEvent `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *PrivacyEventList) GetItems() []PrivacyEvent { + return s.Items +} + +// GetPage returns the value of Page. +func (s *PrivacyEventList) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *PrivacyEventList) SetItems(val []PrivacyEvent) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *PrivacyEventList) SetPage(val PageInfo) { + s.Page = val +} + +// PrivacyEventListHeaders wraps PrivacyEventList with response headers. +type PrivacyEventListHeaders struct { + CacheControl CacheControlNoStore + Response PrivacyEventList +} + +// GetCacheControl returns the value of CacheControl. +func (s *PrivacyEventListHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *PrivacyEventListHeaders) GetResponse() PrivacyEventList { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *PrivacyEventListHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *PrivacyEventListHeaders) SetResponse(val PrivacyEventList) { + s.Response = val +} + +func (*PrivacyEventListHeaders) listMyPrivacyHistoryRes() {} + +// Organization as the candidate who hid it reads it. The name is the current name of the organization. +// The candidate must already have been able to see the organization to hide it, so the reference tells +// them nothing that they could not read before. +// Ref: #/components/schemas/PrivacyOrganization +type PrivacyOrganization struct { + // Identifier of the organization. + ID uuid.UUID `json:"id"` + // Current name of the organization. Plain text; clients show it as text, never as HTML. + Name string `json:"name"` +} + +// GetID returns the value of ID. +func (s *PrivacyOrganization) GetID() uuid.UUID { + return s.ID +} + +// GetName returns the value of Name. +func (s *PrivacyOrganization) GetName() string { + return s.Name +} + +// SetID sets the value of ID. +func (s *PrivacyOrganization) SetID(val uuid.UUID) { + s.ID = val +} + +// SetName sets the value of Name. +func (s *PrivacyOrganization) SetName(val string) { + s.Name = val +} + +// The visibility settings of the current candidate in one read: the publication, the search status, +// and the number of hidden organizations. The three are independent: each has its own version and its +// own operation, and a change of one leaves the others as they were. A new account reads a closed +// profile, `not_looking`, and no hidden organization. +// Ref: #/components/schemas/PrivacySettings +type PrivacySettings struct { + Publication Publication `json:"publication"` + SearchStatus SearchStatus `json:"search_status"` + // Number of organizations that the candidate hides the profile from. The list is read with + // `ListMyHiddenOrganizations`. + HiddenOrganizationsTotal int `json:"hidden_organizations_total"` +} + +// GetPublication returns the value of Publication. +func (s *PrivacySettings) GetPublication() Publication { + return s.Publication +} + +// GetSearchStatus returns the value of SearchStatus. +func (s *PrivacySettings) GetSearchStatus() SearchStatus { + return s.SearchStatus +} + +// GetHiddenOrganizationsTotal returns the value of HiddenOrganizationsTotal. +func (s *PrivacySettings) GetHiddenOrganizationsTotal() int { + return s.HiddenOrganizationsTotal +} + +// SetPublication sets the value of Publication. +func (s *PrivacySettings) SetPublication(val Publication) { + s.Publication = val +} + +// SetSearchStatus sets the value of SearchStatus. +func (s *PrivacySettings) SetSearchStatus(val SearchStatus) { + s.SearchStatus = val +} + +// SetHiddenOrganizationsTotal sets the value of HiddenOrganizationsTotal. +func (s *PrivacySettings) SetHiddenOrganizationsTotal(val int) { + s.HiddenOrganizationsTotal = val +} + +// PrivacySettingsHeaders wraps PrivacySettings with response headers. +type PrivacySettingsHeaders struct { + CacheControl CacheControlNoStore + Response PrivacySettings +} + +// GetCacheControl returns the value of CacheControl. +func (s *PrivacySettingsHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *PrivacySettingsHeaders) GetResponse() PrivacySettings { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *PrivacySettingsHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *PrivacySettingsHeaders) SetResponse(val PrivacySettings) { + s.Response = val +} + +func (*PrivacySettingsHeaders) getMyPrivacySettingsRes() {} + // Problem details (RFC 9457) returned with the application/problem+json media type for every error // response. `code` is the stable, machine-readable reason; clients branch on it rather than on // `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack @@ -16456,7 +17596,10 @@ type Problem struct { // Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; // it is not a secret. TraceID OptString `json:"trace_id"` - // Field-level reasons for validation_failed. Other codes omit it. + // Field-level reasons. validation_failed always carries them; state_conflict may carry one as a + // disambiguator when one code covers several conflicts (for example consent_required and + // limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation + // response. Errors []ProblemFieldError `json:"errors"` } @@ -16753,7 +17896,9 @@ type ProblemFieldError struct { // parameter name, for example `/limit` or `/Idempotency-Key`. Pointer string `json:"pointer"` // Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or - // a value outside the schema). Clients must tolerate new values. + // a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a + // consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must + // tolerate new values. Code string `json:"code"` // Fixed English message that never echoes the submitted value. Message string `json:"message"` @@ -18311,6 +19456,266 @@ type ProfileVersion int64 type ProfileYearMonth string +// Publication setting of the candidate card. It is separate from the consent: the C2 consent in the +// ledger proves that the candidate accepted the publication text, and this setting records whether and +// which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, +// whatever the stored setting says, so a revocation closes the card at once. The state, the fields, +// and the times belong to the history that the C2 consent record does not carry. +// Ref: #/components/schemas/Publication +type Publication struct { + State PublicationState `json:"state"` + // Why the profile is closed, or null while it is published. + ClosedReason NilPublicationClosedReason `json:"closed_reason"` + // Card fields that organizations may read. Empty exactly when `state` is `closed`. + Fields CardFieldSet `json:"fields"` + // Identifier of the C2 record of the consent ledger that backs the current or the last publication, + // the `id` of a `ConsentRecord` of this account, or null when the profile was never published. + ConsentID NilUUID `json:"consent_id"` + // Moment of the latest change that published or republished the card, or null while the profile was + // never published. It stays after a closing, as the time of the last publication. + PublishedAt NilTimestamp `json:"published_at"` + Version PublicationVersion `json:"version"` +} + +// GetState returns the value of State. +func (s *Publication) GetState() PublicationState { + return s.State +} + +// GetClosedReason returns the value of ClosedReason. +func (s *Publication) GetClosedReason() NilPublicationClosedReason { + return s.ClosedReason +} + +// GetFields returns the value of Fields. +func (s *Publication) GetFields() CardFieldSet { + return s.Fields +} + +// GetConsentID returns the value of ConsentID. +func (s *Publication) GetConsentID() NilUUID { + return s.ConsentID +} + +// GetPublishedAt returns the value of PublishedAt. +func (s *Publication) GetPublishedAt() NilTimestamp { + return s.PublishedAt +} + +// GetVersion returns the value of Version. +func (s *Publication) GetVersion() PublicationVersion { + return s.Version +} + +// SetState sets the value of State. +func (s *Publication) SetState(val PublicationState) { + s.State = val +} + +// SetClosedReason sets the value of ClosedReason. +func (s *Publication) SetClosedReason(val NilPublicationClosedReason) { + s.ClosedReason = val +} + +// SetFields sets the value of Fields. +func (s *Publication) SetFields(val CardFieldSet) { + s.Fields = val +} + +// SetConsentID sets the value of ConsentID. +func (s *Publication) SetConsentID(val NilUUID) { + s.ConsentID = val +} + +// SetPublishedAt sets the value of PublishedAt. +func (s *Publication) SetPublishedAt(val NilTimestamp) { + s.PublishedAt = val +} + +// SetVersion sets the value of Version. +func (s *Publication) SetVersion(val PublicationVersion) { + s.Version = val +} + +// Why a closed profile is closed, shown only to the candidate. +// +// - never_published: the candidate has never published the profile. +// - closed_by_candidate: the candidate closed the publication. +// - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never +// reopens the publication; the candidate publishes again explicitly and the new publication refers +// to the new consent record. +// +// Ref: #/components/schemas/PublicationClosedReason +type PublicationClosedReason string + +const ( + PublicationClosedReasonNeverPublished PublicationClosedReason = "never_published" + PublicationClosedReasonClosedByCandidate PublicationClosedReason = "closed_by_candidate" + PublicationClosedReasonConsentRevoked PublicationClosedReason = "consent_revoked" +) + +// AllValues returns all PublicationClosedReason values. +func (PublicationClosedReason) AllValues() []PublicationClosedReason { + return []PublicationClosedReason{ + PublicationClosedReasonNeverPublished, + PublicationClosedReasonClosedByCandidate, + PublicationClosedReasonConsentRevoked, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PublicationClosedReason) MarshalText() ([]byte, error) { + switch s { + case PublicationClosedReasonNeverPublished: + return []byte(s), nil + case PublicationClosedReasonClosedByCandidate: + return []byte(s), nil + case PublicationClosedReasonConsentRevoked: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PublicationClosedReason) UnmarshalText(data []byte) error { + switch PublicationClosedReason(data) { + case PublicationClosedReasonNeverPublished: + *s = PublicationClosedReasonNeverPublished + return nil + case PublicationClosedReasonClosedByCandidate: + *s = PublicationClosedReasonClosedByCandidate + return nil + case PublicationClosedReasonConsentRevoked: + *s = PublicationClosedReasonConsentRevoked + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// PublicationHeaders wraps Publication with response headers. +type PublicationHeaders struct { + CacheControl CacheControlNoStore + Response Publication +} + +// GetCacheControl returns the value of CacheControl. +func (s *PublicationHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *PublicationHeaders) GetResponse() Publication { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *PublicationHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *PublicationHeaders) SetResponse(val Publication) { + s.Response = val +} + +func (*PublicationHeaders) setMyPublicationRes() {} + +// Whether the candidate card can be read by organizations at all. It is computed from the stored +// publication and the consent ledger: a profile is closed unless the candidate published it and the C2 +// consent that backs the publication is still unrevoked. +// +// - closed: no organization reads the card. This is the state of every new profile and of a profile +// whose publication was closed or whose C2 was revoked. +// - published: organizations may read exactly the fields in `fields`, except for the organizations +// the candidate hid. +// +// Ref: #/components/schemas/PublicationState +type PublicationState string + +const ( + PublicationStateClosed PublicationState = "closed" + PublicationStatePublished PublicationState = "published" +) + +// AllValues returns all PublicationState values. +func (PublicationState) AllValues() []PublicationState { + return []PublicationState{ + PublicationStateClosed, + PublicationStatePublished, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s PublicationState) MarshalText() ([]byte, error) { + switch s { + case PublicationStateClosed: + return []byte(s), nil + case PublicationStatePublished: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *PublicationState) UnmarshalText(data []byte) error { + switch PublicationState(data) { + case PublicationStateClosed: + *s = PublicationStateClosed + return nil + case PublicationStatePublished: + *s = PublicationStatePublished + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +// The complete new publication setting. `published` needs a non-empty set of fields and an active C2 +// consent of the account; `closed` needs an empty set and never fails for a missing consent. The body +// names no consent: the server binds the publication to the account's current unrevoked C2 record, and +// a client can neither supply nor forge one. +// Ref: #/components/schemas/PublicationUpdate +type PublicationUpdate struct { + ExpectedVersion PublicationVersion `json:"expected_version"` + State PublicationState `json:"state"` + Fields CardFieldSet `json:"fields"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *PublicationUpdate) GetExpectedVersion() PublicationVersion { + return s.ExpectedVersion +} + +// GetState returns the value of State. +func (s *PublicationUpdate) GetState() PublicationState { + return s.State +} + +// GetFields returns the value of Fields. +func (s *PublicationUpdate) GetFields() CardFieldSet { + return s.Fields +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *PublicationUpdate) SetExpectedVersion(val PublicationVersion) { + s.ExpectedVersion = val +} + +// SetState sets the value of State. +func (s *PublicationUpdate) SetState(val PublicationState) { + s.State = val +} + +// SetFields sets the value of Fields. +func (s *PublicationUpdate) SetFields(val CardFieldSet) { + s.Fields = val +} + +type PublicationVersion int64 + // One specialization chosen by the candidate with the candidate's self-assessment. // `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the // assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed @@ -18671,6 +20076,189 @@ type SaveMyQuestionnaireUnauthorized Problem func (*SaveMyQuestionnaireUnauthorized) saveMyQuestionnaireRes() {} +// Search status of the candidate as it holds now. The status `looking` stores the moment of its +// confirmation and lapses when the confirmation interval of the product policy passes without a new +// confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public +// state, and a lapse never changes the publication or the hidden organizations. It needs no stored +// change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms +// again explicitly. +// Ref: #/components/schemas/SearchStatus +type SearchStatus struct { + // The status that holds now: `looking` only while the confirmation has not lapsed. + Value SearchStatusValue `json:"value"` + // True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` + // is `not_looking`. False otherwise, including a status the candidate cleared. + Lapsed bool `json:"lapsed"` + // Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared + // it. + ConfirmedAt NilTimestamp `json:"confirmed_at"` + // Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` + // section of the product policy version in force then, or null when `confirmed_at` is null. A later + // policy change does not move it; it stays in the past for a lapsed status. + LapsesAt NilTimestamp `json:"lapses_at"` + Version SearchStatusVersion `json:"version"` +} + +// GetValue returns the value of Value. +func (s *SearchStatus) GetValue() SearchStatusValue { + return s.Value +} + +// GetLapsed returns the value of Lapsed. +func (s *SearchStatus) GetLapsed() bool { + return s.Lapsed +} + +// GetConfirmedAt returns the value of ConfirmedAt. +func (s *SearchStatus) GetConfirmedAt() NilTimestamp { + return s.ConfirmedAt +} + +// GetLapsesAt returns the value of LapsesAt. +func (s *SearchStatus) GetLapsesAt() NilTimestamp { + return s.LapsesAt +} + +// GetVersion returns the value of Version. +func (s *SearchStatus) GetVersion() SearchStatusVersion { + return s.Version +} + +// SetValue sets the value of Value. +func (s *SearchStatus) SetValue(val SearchStatusValue) { + s.Value = val +} + +// SetLapsed sets the value of Lapsed. +func (s *SearchStatus) SetLapsed(val bool) { + s.Lapsed = val +} + +// SetConfirmedAt sets the value of ConfirmedAt. +func (s *SearchStatus) SetConfirmedAt(val NilTimestamp) { + s.ConfirmedAt = val +} + +// SetLapsesAt sets the value of LapsesAt. +func (s *SearchStatus) SetLapsesAt(val NilTimestamp) { + s.LapsesAt = val +} + +// SetVersion sets the value of Version. +func (s *SearchStatus) SetVersion(val SearchStatusVersion) { + s.Version = val +} + +// SearchStatusHeaders wraps SearchStatus with response headers. +type SearchStatusHeaders struct { + CacheControl CacheControlNoStore + Response SearchStatus +} + +// GetCacheControl returns the value of CacheControl. +func (s *SearchStatusHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *SearchStatusHeaders) GetResponse() SearchStatus { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *SearchStatusHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *SearchStatusHeaders) SetResponse(val SearchStatus) { + s.Response = val +} + +func (*SearchStatusHeaders) setMySearchStatusRes() {} + +// The complete new search status. `looking` is also the confirmation of a status that still holds or +// has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy +// version; the server takes them from the effective product policy. +// Ref: #/components/schemas/SearchStatusUpdate +type SearchStatusUpdate struct { + ExpectedVersion SearchStatusVersion `json:"expected_version"` + Value SearchStatusValue `json:"value"` +} + +// GetExpectedVersion returns the value of ExpectedVersion. +func (s *SearchStatusUpdate) GetExpectedVersion() SearchStatusVersion { + return s.ExpectedVersion +} + +// GetValue returns the value of Value. +func (s *SearchStatusUpdate) GetValue() SearchStatusValue { + return s.Value +} + +// SetExpectedVersion sets the value of ExpectedVersion. +func (s *SearchStatusUpdate) SetExpectedVersion(val SearchStatusVersion) { + s.ExpectedVersion = val +} + +// SetValue sets the value of Value. +func (s *SearchStatusUpdate) SetValue(val SearchStatusValue) { + s.Value = val +} + +// Whether the candidate says they are searching for work. The status is a statement, never a consent: +// it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, +// the publication, or the hidden organizations. +// +// - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see +// `SearchStatus.lapsed`. +// - not_looking: the candidate is not announcing a search. It is the state of every new account and +// the state to which a lapsed status falls. +// +// Ref: #/components/schemas/SearchStatusValue +type SearchStatusValue string + +const ( + SearchStatusValueLooking SearchStatusValue = "looking" + SearchStatusValueNotLooking SearchStatusValue = "not_looking" +) + +// AllValues returns all SearchStatusValue values. +func (SearchStatusValue) AllValues() []SearchStatusValue { + return []SearchStatusValue{ + SearchStatusValueLooking, + SearchStatusValueNotLooking, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s SearchStatusValue) MarshalText() ([]byte, error) { + switch s { + case SearchStatusValueLooking: + return []byte(s), nil + case SearchStatusValueNotLooking: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *SearchStatusValue) UnmarshalText(data []byte) error { + switch SearchStatusValue(data) { + case SearchStatusValueLooking: + *s = SearchStatusValueLooking + return nil + case SearchStatusValueNotLooking: + *s = SearchStatusValueNotLooking + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type SearchStatusVersion int64 + type SendOrganizationInvitationBadRequest Problem func (*SendOrganizationInvitationBadRequest) sendOrganizationInvitationRes() {} @@ -18816,6 +20404,42 @@ func (s *SessionHeaders) SetResponse(val Session) { func (*SessionHeaders) loginRes() {} +type SetMyPublicationBadRequest Problem + +func (*SetMyPublicationBadRequest) setMyPublicationRes() {} + +type SetMyPublicationConflict Problem + +func (*SetMyPublicationConflict) setMyPublicationRes() {} + +type SetMyPublicationForbidden Problem + +func (*SetMyPublicationForbidden) setMyPublicationRes() {} + +type SetMyPublicationPreconditionFailed Problem + +func (*SetMyPublicationPreconditionFailed) setMyPublicationRes() {} + +type SetMyPublicationUnauthorized Problem + +func (*SetMyPublicationUnauthorized) setMyPublicationRes() {} + +type SetMySearchStatusBadRequest Problem + +func (*SetMySearchStatusBadRequest) setMySearchStatusRes() {} + +type SetMySearchStatusForbidden Problem + +func (*SetMySearchStatusForbidden) setMySearchStatusRes() {} + +type SetMySearchStatusPreconditionFailed Problem + +func (*SetMySearchStatusPreconditionFailed) setMySearchStatusRes() {} + +type SetMySearchStatusUnauthorized Problem + +func (*SetMySearchStatusUnauthorized) setMySearchStatusRes() {} + type SkillName string type SkillTaxonomyCode string @@ -21242,6 +22866,7 @@ func (*TooManyRequestsHeaders) createOrganizationInvitationRes() {} func (*TooManyRequestsHeaders) createOrganizationNeedRes() {} func (*TooManyRequestsHeaders) createOrganizationRes() {} func (*TooManyRequestsHeaders) declineMyInvitationRes() {} +func (*TooManyRequestsHeaders) hideOrganizationRes() {} func (*TooManyRequestsHeaders) loginRes() {} func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {} func (*TooManyRequestsHeaders) registerAccountRes() {} @@ -21254,6 +22879,35 @@ func (*TooManyRequestsHeaders) updateOrganizationRes() {} func (*TooManyRequestsHeaders) viewMyInvitationRes() {} func (*TooManyRequestsHeaders) withdrawOrganizationInvitationRes() {} +type UnhideOrganizationBadRequest Problem + +func (*UnhideOrganizationBadRequest) unhideOrganizationRes() {} + +type UnhideOrganizationForbidden Problem + +func (*UnhideOrganizationForbidden) unhideOrganizationRes() {} + +// UnhideOrganizationNoContent is response for UnhideOrganization operation. +type UnhideOrganizationNoContent struct { + CacheControl CacheControlNoStore +} + +// GetCacheControl returns the value of CacheControl. +func (s *UnhideOrganizationNoContent) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// SetCacheControl sets the value of CacheControl. +func (s *UnhideOrganizationNoContent) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +func (*UnhideOrganizationNoContent) unhideOrganizationRes() {} + +type UnhideOrganizationUnauthorized Problem + +func (*UnhideOrganizationUnauthorized) unhideOrganizationRes() {} + type UpdateOrganizationBadRequest Problem func (*UpdateOrganizationBadRequest) updateOrganizationRes() {} diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index e763b1b..8a010e6 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -70,7 +70,9 @@ var operationRolesSessionCookie = map[string][]string{ GetMyAssessmentAttemptOperation: []string{}, GetMyAssessmentAvailabilityOperation: []string{}, GetMyAssessmentResultOperation: []string{}, + GetMyCardPreviewOperation: []string{}, GetMyInvitationOperation: []string{}, + GetMyPrivacySettingsOperation: []string{}, GetMyProfileOperation: []string{}, GetMyQuestionnaireOperation: []string{}, GetMySupportCaseOperation: []string{}, @@ -78,9 +80,13 @@ var operationRolesSessionCookie = map[string][]string{ GetOrganizationInvitationOperation: []string{}, GetOrganizationInvitationContactsOperation: []string{}, GetOrganizationNeedOperation: []string{}, + HideOrganizationOperation: []string{}, + ListMyCardAccessHistoryOperation: []string{}, ListMyConsentsOperation: []string{}, + ListMyHiddenOrganizationsOperation: []string{}, ListMyInvitationsOperation: []string{}, ListMyOrganizationsOperation: []string{}, + ListMyPrivacyHistoryOperation: []string{}, ListMySupportCasesOperation: []string{}, ListOrganizationInvitationsOperation: []string{}, ListOrganizationNeedsOperation: []string{}, @@ -89,7 +95,10 @@ var operationRolesSessionCookie = map[string][]string{ SaveMyProfileOperation: []string{}, SaveMyQuestionnaireOperation: []string{}, SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, UpdateOrganizationInvitationOperation: []string{}, UpdateOrganizationNeedOperation: []string{}, @@ -129,12 +138,16 @@ var operationRolesSessionCsrf = map[string][]string{ CreateOrganizationNeedOperation: []string{}, DeclineMyInvitationOperation: []string{}, FinalizeMyAssessmentAttemptOperation: []string{}, + HideOrganizationOperation: []string{}, LogoutOperation: []string{}, RaiseOrganizationInvitationSalaryOperation: []string{}, SaveMyProfileOperation: []string{}, SaveMyQuestionnaireOperation: []string{}, SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, UpdateOrganizationOperation: []string{}, UpdateOrganizationInvitationOperation: []string{}, UpdateOrganizationNeedOperation: []string{}, diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index c551de0..5ed9a02 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -572,6 +572,29 @@ type Handler interface { // // GET /api/v1/me/assessment-attempts/{attempt_id}/result GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error) + // GetMyCardPreview implements GetMyCardPreview operation. + // + // Requires the session cookie of a candidate account. Returns the card exactly as an organization that + // the candidate does not hide the profile from would read it now, built from the current profile, the + // current publication, and the consent ledger. The response is `Cache-Control: no-store`. + // + // The preview is a private read for the candidate: it creates no view, leaves no access record, and is + // never shown to an organization. While the profile is closed `card` is null. `card` is + // `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no + // identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, + // or account or profile identifier, and each property is null when it is not published or has no + // value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with + // values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A + // free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, + // an @handle) is dropped from the card, so the preview shows exactly what an organization would read. + // The self-assessed grade is not a category and never appears; categories come only from assessment + // results. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. + // + // GET /api/v1/me/privacy/preview + GetMyCardPreview(ctx context.Context) (GetMyCardPreviewRes, error) // GetMyInvitation implements GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -603,6 +626,27 @@ type Handler interface { // // GET /api/v1/me/invitations/{invitation_id} GetMyInvitation(ctx context.Context, params GetMyInvitationParams) (GetMyInvitationRes, error) + // GetMyPrivacySettings implements GetMyPrivacySettings operation. + // + // Requires the session cookie of a candidate account. The candidate comes from the session, never from + // a request parameter. Returns the publication of the candidate card, the search status, and the + // number of hidden organizations in one read. The response is `Cache-Control: no-store`. + // + // A profile is closed by default. A candidate who never published reads `publication.state` `closed` + // with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the + // profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or + // an assessment changes these settings. The C2 consent, the search status, and the hidden + // organizations are three independent settings: the C2 record in the consent ledger proves that the + // candidate accepted the publication text, the publication records which fields are published, and the + // search status is a statement of the candidate that is not a consent. A change of one never changes + // another, and none of them ever makes the candidate more visible by itself: the search status lapses + // to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. + // + // GET /api/v1/me/privacy + GetMyPrivacySettings(ctx context.Context) (GetMyPrivacySettingsRes, error) // GetMyProfile implements GetMyProfile operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -795,6 +839,66 @@ type Handler interface { // // GET /api/v1/specializations GetSpecializationCatalog(ctx context.Context) (*SpecializationCatalog, error) + // HideOrganization implements HideOrganization operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. The request has no body: the path names the organization and the candidate + // comes from the session. The hiding is a record that belongs to the candidate and references the + // organization; it changes neither the C2 consent, nor the publication, nor the search status. + // + // The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization + // that is already hidden answers 200 with the existing record and its original `hidden_at`, changes + // nothing, and writes no history record. There is one record per candidate and organization. + // + // Anti-enumeration: an organization that does not exist and an organization that the candidate cannot + // see answer the same 404 not_found, with the same body and without a timing or an error code that + // tells them apart, so the operation is not a way to ask whether an identifier belongs to an + // organization. The candidate can see an organization that has sent them an invitation, and the + // organizations that a candidate lookup will list (planned; see the open questions of the contract). + // The response names the organization only after that check, with its current name. The identifiers + // are random, the general rate limit applies and can answer 429 with Retry-After before any check, and + // the record never reveals to an organization that a candidate hides it. + // + // A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the + // entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from + // other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the + // limit. + // + // Hiding an organization that holds an active contact grant of the candidate revokes that grant with + // the reason `visibility_closed` in the same transaction (planned together with the invitation + // operations). Lifting the hiding never reopens a grant. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the + // path (400), account scenario (403 forbidden for an employer), the organization and its visibility to + // the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like + // every visibility change, hiding needs a verified email (a usecase requirement). + // + // PUT /api/v1/me/privacy/hidden-organizations/{org_id} + HideOrganization(ctx context.Context, params HideOrganizationParams) (HideOrganizationRes, error) + // ListMyCardAccessHistory implements ListMyCardAccessHistory operation. + // + // Requires the session cookie of a candidate account. The candidate comes from the session, so the + // response holds only accesses to the caller's own card. Returns a page, newest first with the record + // identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + // + // An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the + // contacts through an active contact grant (`contact_read`). Reading the history is not an access and + // writes nothing. A view of the card by an organization that has no invitation relation with the + // candidate carries `organization` null, so the candidate sees that the card was viewed without + // learning a company that they cannot otherwise see; a contact read always names the organization, + // because the candidate accepted its invitation. The entries carry no search query, filter, or ranking + // of the organization, and no organization the candidate hides ever appears as a viewer, because a + // hidden organization cannot read the card. + // + // The storage of accesses is planned with the card and contact operations of the organization side + // (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 + // not_implemented after the session and request checks. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + // + // GET /api/v1/me/privacy/access-history + ListMyCardAccessHistory(ctx context.Context, params ListMyCardAccessHistoryParams) (ListMyCardAccessHistoryRes, error) // ListMyConsents implements ListMyConsents operation. // // Requires the session cookie of a candidate or an employer account. The subject comes from the @@ -824,6 +928,22 @@ type Handler interface { // // GET /api/v1/me/consents ListMyConsents(ctx context.Context, params ListMyConsentsParams) (ListMyConsentsRes, error) + // ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation. + // + // Requires the session cookie of a candidate account. The candidate comes from the session, so the + // response holds only the caller's own records and no request can name another account. Returns a page + // of the hidden organizations, newest first with the organization identifier as the tie-breaker, with + // cursor pagination. The response is `Cache-Control: no-store`. + // + // The records belong to the candidate. An organization never reads them, never learns that it is + // hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, + // no card, no contact read. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + // + // GET /api/v1/me/privacy/hidden-organizations + ListMyHiddenOrganizations(ctx context.Context, params ListMyHiddenOrganizationsParams) (ListMyHiddenOrganizationsRes, error) // ListMyInvitations implements ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -871,6 +991,24 @@ type Handler interface { // // GET /api/v1/me/organizations ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error) + // ListMyPrivacyHistory implements ListMyPrivacyHistory operation. + // + // Requires the session cookie of a candidate account. The candidate comes from the session, so the + // response holds only the caller's own records. Returns a page of the settings history, newest first + // with the event identifier as the tie-breaker, with cursor pagination. The response is + // `Cache-Control: no-store`. + // + // The history is append-only evidence of what the candidate published, hid, and announced, and when. A + // publication event keeps the published fields and the C2 record behind them, which is what the + // consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the + // field set). A revocation of C2 and a lapse of the search status are computed and are not events + // here; the consent history shows the revocation. The history never contains a profile value. + // + // A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account + // answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + // + // GET /api/v1/me/privacy/history + ListMyPrivacyHistory(ctx context.Context, params ListMyPrivacyHistoryParams) (ListMyPrivacyHistoryRes, error) // ListMySupportCases implements ListMySupportCases operation. // // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that @@ -1186,6 +1324,90 @@ type Handler interface { // // POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/send SendOrganizationInvitation(ctx context.Context, req *InvitationCommand, params SendOrganizationInvitationParams) (SendOrganizationInvitationRes, error) + // SetMyPublication implements SetMyPublication operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. The body is the complete new publication setting: `state` `published` with + // the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; + // the search status and the hidden organizations stay as they were. + // + // Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger + // (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of + // the account and binds the publication to that record, so a client sends no consent identifier and + // cannot forge one. Without one the server answers 409 state_conflict with the entry + // `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every + // other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, + // TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction + // that writes the publication, so a revocation that races with a publication either commits first (the + // publication is refused) or closes the card right after. A revocation of C2 closes the card at once, + // because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the + // candidate publishes again under the new record. The revocation path itself (TASK-064) closes the + // stored publication and revokes the contact grants in its own transaction. A closing sent over a + // stored publication whose C2 was revoked is a real change: it stores the closing, records + // `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility + // change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only + // accounts without such records). Publishing never adds a field that the body did not name, and a new + // `CardField` value is never published for a candidate who did not choose it. + // + // The field set contains only the groups of `CardField`. The full name, contacts, and the lowest + // salary have no value there, so no body can publish them. Only values that the candidate confirmed + // ever reach the card. Contacts reach an organization only through the contact grant (C4), and a + // profile that is published or closed changes none of the grants that exist; closing the publication, + // and hiding an organization that holds a grant, revoke the contact grants concerned with the reason + // `visibility_closed` in the same transaction as the change (planned together with the operations, see + // the invitation contract). + // + // Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, + // 0 for the first publication. If it is not the current version the server answers 412 + // version_conflict and changes nothing. The version travels in the body rather than in If-Match + // because the generated client cannot read the ETag header yet. A body that equals the stored setting + // changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a + // retry after a lost response succeeds without an Idempotency-Key. A version above the current one + // never existed and always answers 412. Every change is recorded in the settings history with its + // time, the fields, and the C2 record. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden for an employer), a version above the current one (412), rules that + // depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 + // for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown + // card field, and more fields than there are groups; a published state with no field, and a closed + // state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never + // repeat a submitted value. + // + // PUT /api/v1/me/privacy/publication + SetMyPublication(ctx context.Context, req *PublicationUpdate) (SetMyPublicationRes, error) + // SetMySearchStatus implements SetMySearchStatus operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. + // The status is a statement of the candidate and never a consent. It changes neither the C2 consent, + // nor the publication, nor the hidden organizations, and it does not close or open any contact grant; + // a candidate whose profile is closed who sets `looking` becomes visible to no one. + // + // `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from + // the `search_status` section of the effective product policy (30 days in the demo policy, + // `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time + // then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it + // replaces the confirmation time with now and advances the version, also after a lapse. The body + // carries no time, interval, or policy version. + // + // After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The + // lapse is computed and written nowhere, so it needs no job, it can never make the candidate more + // visible, and it never touches the publication or the hidden organizations. A reminder before the + // lapse is a planned notification, not a part of this operation. + // + // Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the + // status; a stale or non-existent version answers 412 version_conflict and changes nothing. + // `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. + // `looking` always changes the stored confirmation, so a retry of a confirmation whose response was + // lost with the old version answers 412 and the client reads the status again. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), + // account scenario (403 forbidden for an employer), a version above the current one (412), an + // unchanged `not_looking` (200), then a stale version (412). + // + // PUT /api/v1/me/privacy/search-status + SetMySearchStatus(ctx context.Context, req *SearchStatusUpdate) (SetMySearchStatusRes, error) // SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -1243,6 +1465,24 @@ type Handler interface { // // POST /api/v1/me/assessment-attempts/{attempt_id}/answers SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error) + // UnhideOrganization implements UnhideOrganization operation. + // + // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, + // and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. + // The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or + // does not exist, so the operation reveals nothing about the organization, and a repeat after a lost + // response succeeds. The record is deleted, the settings history keeps the event + // `organization_unhidden` only when a record was deleted. + // + // Lifting the hiding makes the candidate readable by that organization again only if the profile is + // published and the organization otherwise may read it. It changes neither the C2 consent, nor the + // publication, nor the search status, and it never reopens a contact grant that the hiding closed. + // + // Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the + // path (400), account scenario (403 forbidden for an employer), then the deletion (204). + // + // DELETE /api/v1/me/privacy/hidden-organizations/{org_id} + UnhideOrganization(ctx context.Context, params UnhideOrganizationParams) (UnhideOrganizationRes, error) // UpdateOrganization implements UpdateOrganization operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 26aa476..d12d841 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -628,6 +628,32 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge return r, ht.ErrNotImplemented } +// GetMyCardPreview implements GetMyCardPreview operation. +// +// Requires the session cookie of a candidate account. Returns the card exactly as an organization that +// the candidate does not hide the profile from would read it now, built from the current profile, the +// current publication, and the consent ledger. The response is `Cache-Control: no-store`. +// +// The preview is a private read for the candidate: it creates no view, leaves no access record, and is +// never shown to an organization. While the profile is closed `card` is null. `card` is +// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no +// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, +// or account or profile identifier, and each property is null when it is not published or has no +// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with +// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A +// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, +// an @handle) is dropped from the card, so the preview shows exactly what an organization would read. +// The self-assessed grade is not a category and never appears; categories come only from assessment +// results. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/privacy/preview +func (UnimplementedHandler) GetMyCardPreview(ctx context.Context) (r GetMyCardPreviewRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyInvitation implements GetMyInvitation operation. // // Requires the session cookie of a candidate account. The candidate comes from the session; the @@ -662,6 +688,30 @@ func (UnimplementedHandler) GetMyInvitation(ctx context.Context, params GetMyInv return r, ht.ErrNotImplemented } +// GetMyPrivacySettings implements GetMyPrivacySettings operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, never from +// a request parameter. Returns the publication of the candidate card, the search status, and the +// number of hidden organizations in one read. The response is `Cache-Control: no-store`. +// +// A profile is closed by default. A candidate who never published reads `publication.state` `closed` +// with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the +// profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or +// an assessment changes these settings. The C2 consent, the search status, and the hidden +// organizations are three independent settings: the C2 record in the consent ledger proves that the +// candidate accepted the publication text, the publication records which fields are published, and the +// search status is a statement of the candidate that is not a consent. A change of one never changes +// another, and none of them ever makes the candidate more visible by itself: the search status lapses +// to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. +// +// GET /api/v1/me/privacy +func (UnimplementedHandler) GetMyPrivacySettings(ctx context.Context) (r GetMyPrivacySettingsRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyProfile implements GetMyProfile operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -878,6 +928,72 @@ func (UnimplementedHandler) GetSpecializationCatalog(ctx context.Context) (r *Sp return r, ht.ErrNotImplemented } +// HideOrganization implements HideOrganization operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The request has no body: the path names the organization and the candidate +// comes from the session. The hiding is a record that belongs to the candidate and references the +// organization; it changes neither the C2 consent, nor the publication, nor the search status. +// +// The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization +// that is already hidden answers 200 with the existing record and its original `hidden_at`, changes +// nothing, and writes no history record. There is one record per candidate and organization. +// +// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot +// see answer the same 404 not_found, with the same body and without a timing or an error code that +// tells them apart, so the operation is not a way to ask whether an identifier belongs to an +// organization. The candidate can see an organization that has sent them an invitation, and the +// organizations that a candidate lookup will list (planned; see the open questions of the contract). +// The response names the organization only after that check, with its current name. The identifiers +// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and +// the record never reveals to an organization that a candidate hides it. +// +// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the +// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from +// other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the +// limit. +// +// Hiding an organization that holds an active contact grant of the candidate revokes that grant with +// the reason `visibility_closed` in the same transaction (planned together with the invitation +// operations). Lifting the hiding never reopens a grant. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the +// path (400), account scenario (403 forbidden for an employer), the organization and its visibility to +// the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like +// every visibility change, hiding needs a verified email (a usecase requirement). +// +// PUT /api/v1/me/privacy/hidden-organizations/{org_id} +func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrganizationParams) (r HideOrganizationRes, _ error) { + return r, ht.ErrNotImplemented +} + +// ListMyCardAccessHistory implements ListMyCardAccessHistory operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only accesses to the caller's own card. Returns a page, newest first with the record +// identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. +// +// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the +// contacts through an active contact grant (`contact_read`). Reading the history is not an access and +// writes nothing. A view of the card by an organization that has no invitation relation with the +// candidate carries `organization` null, so the candidate sees that the card was viewed without +// learning a company that they cannot otherwise see; a contact read always names the organization, +// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking +// of the organization, and no organization the candidate hides ever appears as a viewer, because a +// hidden organization cannot read the card. +// +// The storage of accesses is planned with the card and contact operations of the organization side +// (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 +// not_implemented after the session and request checks. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/access-history +func (UnimplementedHandler) ListMyCardAccessHistory(ctx context.Context, params ListMyCardAccessHistoryParams) (r ListMyCardAccessHistoryRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMyConsents implements ListMyConsents operation. // // Requires the session cookie of a candidate or an employer account. The subject comes from the @@ -910,6 +1026,25 @@ func (UnimplementedHandler) ListMyConsents(ctx context.Context, params ListMyCon return r, ht.ErrNotImplemented } +// ListMyHiddenOrganizations implements ListMyHiddenOrganizations operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only the caller's own records and no request can name another account. Returns a page +// of the hidden organizations, newest first with the organization identifier as the tie-breaker, with +// cursor pagination. The response is `Cache-Control: no-store`. +// +// The records belong to the candidate. An organization never reads them, never learns that it is +// hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, +// no card, no contact read. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/hidden-organizations +func (UnimplementedHandler) ListMyHiddenOrganizations(ctx context.Context, params ListMyHiddenOrganizationsParams) (r ListMyHiddenOrganizationsRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMyInvitations implements ListMyInvitations operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, never from @@ -963,6 +1098,27 @@ func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params List return r, ht.ErrNotImplemented } +// ListMyPrivacyHistory implements ListMyPrivacyHistory operation. +// +// Requires the session cookie of a candidate account. The candidate comes from the session, so the +// response holds only the caller's own records. Returns a page of the settings history, newest first +// with the event identifier as the tie-breaker, with cursor pagination. The response is +// `Cache-Control: no-store`. +// +// The history is append-only evidence of what the candidate published, hid, and announced, and when. A +// publication event keeps the published fields and the C2 record behind them, which is what the +// consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the +// field set). A revocation of C2 and a lapse of the search status are computed and are not events +// here; the consent history shows the revocation. The history never contains a profile value. +// +// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account +// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. +// +// GET /api/v1/me/privacy/history +func (UnimplementedHandler) ListMyPrivacyHistory(ctx context.Context, params ListMyPrivacyHistoryParams) (r ListMyPrivacyHistoryRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMySupportCases implements ListMySupportCases operation. // // Requires the session cookie of a candidate or an employer account. Returns a page of the cases that @@ -1311,6 +1467,96 @@ func (UnimplementedHandler) SendOrganizationInvitation(ctx context.Context, req return r, ht.ErrNotImplemented } +// SetMyPublication implements SetMyPublication operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new publication setting: `state` `published` with +// the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; +// the search status and the hidden organizations stay as they were. +// +// Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger +// (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of +// the account and binds the publication to that record, so a client sends no consent identifier and +// cannot forge one. Without one the server answers 409 state_conflict with the entry +// `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every +// other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, +// TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction +// that writes the publication, so a revocation that races with a publication either commits first (the +// publication is refused) or closes the card right after. A revocation of C2 closes the card at once, +// because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the +// candidate publishes again under the new record. The revocation path itself (TASK-064) closes the +// stored publication and revokes the contact grants in its own transaction. A closing sent over a +// stored publication whose C2 was revoked is a real change: it stores the closing, records +// `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility +// change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only +// accounts without such records). Publishing never adds a field that the body did not name, and a new +// `CardField` value is never published for a candidate who did not choose it. +// +// The field set contains only the groups of `CardField`. The full name, contacts, and the lowest +// salary have no value there, so no body can publish them. Only values that the candidate confirmed +// ever reach the card. Contacts reach an organization only through the contact grant (C4), and a +// profile that is published or closed changes none of the grants that exist; closing the publication, +// and hiding an organization that holds a grant, revoke the contact grants concerned with the reason +// `visibility_closed` in the same transaction as the change (planned together with the operations, see +// the invitation contract). +// +// Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, +// 0 for the first publication. If it is not the current version the server answers 412 +// version_conflict and changes nothing. The version travels in the body rather than in If-Match +// because the generated client cannot read the ETag header yet. A body that equals the stored setting +// changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a +// retry after a lost response succeeds without an Idempotency-Key. A version above the current one +// never existed and always answers 412. Every change is recorded in the settings history with its +// time, the fields, and the C2 record. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), a version above the current one (412), rules that +// depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 +// for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown +// card field, and more fields than there are groups; a published state with no field, and a closed +// state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never +// repeat a submitted value. +// +// PUT /api/v1/me/privacy/publication +func (UnimplementedHandler) SetMyPublication(ctx context.Context, req *PublicationUpdate) (r SetMyPublicationRes, _ error) { + return r, ht.ErrNotImplemented +} + +// SetMySearchStatus implements SetMySearchStatus operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. +// The status is a statement of the candidate and never a consent. It changes neither the C2 consent, +// nor the publication, nor the hidden organizations, and it does not close or open any contact grant; +// a candidate whose profile is closed who sets `looking` becomes visible to no one. +// +// `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from +// the `search_status` section of the effective product policy (30 days in the demo policy, +// `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time +// then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it +// replaces the confirmation time with now and advances the version, also after a lapse. The body +// carries no time, interval, or policy version. +// +// After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The +// lapse is computed and written nowhere, so it needs no job, it can never make the candidate more +// visible, and it never touches the publication or the hidden organizations. A reminder before the +// lapse is a planned notification, not a part of this operation. +// +// Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the +// status; a stale or non-existent version answers 412 version_conflict and changes nothing. +// `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. +// `looking` always changes the stored confirmation, so a retry of a confirmation whose response was +// lost with the old version answers 412 and the client reads the status again. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), +// account scenario (403 forbidden for an employer), a version above the current one (412), an +// unchanged `not_looking` (200), then a stale version (412). +// +// PUT /api/v1/me/privacy/search-status +func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchStatusUpdate) (r SetMySearchStatusRes, _ error) { + return r, ht.ErrNotImplemented +} + // SubmitMyAssessmentAnswer implements SubmitMyAssessmentAnswer operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -1371,6 +1617,27 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A return r, ht.ErrNotImplemented } +// UnhideOrganization implements UnhideOrganization operation. +// +// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, +// and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. +// The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or +// does not exist, so the operation reveals nothing about the organization, and a repeat after a lost +// response succeeds. The record is deleted, the settings history keeps the event +// `organization_unhidden` only when a record was deleted. +// +// Lifting the hiding makes the candidate readable by that organization again only if the profile is +// published and the organization otherwise may read it. It changes neither the C2 consent, nor the +// publication, nor the search status, and it never reopens a contact grant that the hiding closed. +// +// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the +// path (400), account scenario (403 forbidden for an employer), then the deletion (204). +// +// DELETE /api/v1/me/privacy/hidden-organizations/{org_id} +func (UnimplementedHandler) UnhideOrganization(ctx context.Context, params UnhideOrganizationParams) (r UnhideOrganizationRes, _ error) { + return r, ht.ErrNotImplemented +} + // UpdateOrganization implements UpdateOrganization operation. // // Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 06e4392..63a25fd 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -155,6 +155,196 @@ func (s AccountScenario) Validate() error { } } +func (s *AnonymousCardContent) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Categories == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 9, + MaxLengthSet: true, + }).ValidateLength(len(s.Categories)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Categories { + 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: "categories", + Error: err, + }) + } + if err := func() error { + if s.Stack == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 30, + MaxLengthSet: true, + }).ValidateLength(len(s.Stack)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Stack { + 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: "stack", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ExperienceMonths.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 1200, + 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 { + failures = append(failures, validate.FieldError{ + Name: "experience_months", + Error: err, + }) + } + if err := func() error { + if s.SoftSkills == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 10, + MaxLengthSet: true, + }).ValidateLength(len(s.SoftSkills)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.SoftSkills { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 50, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(elem)); err != nil { + return errors.Wrap(err, "string") + } + 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: "soft_skills", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Location.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 100, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^\\S(?:.*\\S)?$"], + 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 { + failures = append(failures, validate.FieldError{ + Name: "location", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s AssessmentAnswer) Validate() error { switch s.Type { case ChoiceAnswerAssessmentAnswer: @@ -3456,6 +3646,326 @@ func (s *CandidateQuestionnaireUpdate) Validate() error { return nil } +func (s *CardAccess) 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 value, ok := s.Organization.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: "organization", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s CardAccessKind) Validate() error { + switch s { + case "card_viewed": + return nil + case "contact_read": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *CardAccessList) 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 *CardAccessListHeaders) 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 *CardCategory) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Specialization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "specialization", + 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 len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s CardField) Validate() error { + switch s { + case "categories": + return nil + case "stack": + return nil + case "experience": + return nil + case "soft_skills": + return nil + case "location": + return nil + case "relocation": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s CardFieldSet) Validate() error { + alias := ([]CardField)(s) + if alias == nil { + return nil // null + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: true, + MaxLength: 6, + MaxLengthSet: true, + }).ValidateLength(len(alias)); err != nil { + return errors.Wrap(err, "array") + } + if err := validate.UniqueItems(alias); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range alias { + 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 +} + +func (s *CardPreview) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Fields.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Card.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: "card", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *CardPreviewHeaders) 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 *CatalogDirection) Validate() error { if s == nil { return validate.ErrNilPointer @@ -5806,6 +6316,22 @@ func (s *GetMyAssessmentResultUnauthorized) Validate() error { return nil } +func (s *GetMyCardPreviewForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyCardPreviewUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyInvitationBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -5838,6 +6364,22 @@ func (s *GetMyInvitationUnauthorized) Validate() error { return nil } +func (s *GetMyPrivacySettingsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyPrivacySettingsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyProfileForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -6069,6 +6611,196 @@ func (s HealthResponseStatus) Validate() error { } } +func (s *HiddenOrganization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Organization.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "organization", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *HiddenOrganizationHeaders) 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 *HiddenOrganizationList) 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 *HiddenOrganizationListHeaders) 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 *HideOrganizationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *HideOrganizationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *HideOrganizationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *HideOrganizationNotFound) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *HideOrganizationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *IdentityRequestAccepted) Validate() error { if s == nil { return validate.ErrNilPointer @@ -7159,6 +7891,30 @@ func (s ItemContent) Validate() error { } } +func (s *ListMyCardAccessHistoryBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyCardAccessHistoryForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyCardAccessHistoryUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMyConsentsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -7175,6 +7931,30 @@ func (s *ListMyConsentsUnauthorized) Validate() error { return nil } +func (s *ListMyHiddenOrganizationsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyHiddenOrganizationsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyHiddenOrganizationsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMyInvitationsBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -7223,6 +8003,30 @@ func (s *ListMyOrganizationsUnauthorized) Validate() error { return nil } +func (s *ListMyPrivacyHistoryBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyPrivacyHistoryForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyPrivacyHistoryUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMySupportCasesBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -12320,6 +13124,296 @@ func (s *PracticeVerdict) Validate() error { return nil } +func (s *PrivacyEvent) 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.Fields.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Organization.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: "organization", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PrivacyEventKind) Validate() error { + switch s { + case "publication_opened": + return nil + case "publication_changed": + return nil + case "publication_closed": + return nil + case "search_status_confirmed": + return nil + case "search_status_cleared": + return nil + case "organization_hidden": + return nil + case "organization_unhidden": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PrivacyEventList) 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 *PrivacyEventListHeaders) 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 *PrivacyOrganization) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 200, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Name)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "name", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *PrivacySettings) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Publication.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "publication", + Error: err, + }) + } + if err := func() error { + if err := s.SearchStatus.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "search_status", + Error: err, + }) + } + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: true, + Max: 1000, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(s.HiddenOrganizationsTotal)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "hidden_organizations_total", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *PrivacySettingsHeaders) 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 *Problem) Validate() error { if s == nil { return validate.ErrNilPointer @@ -14440,6 +15534,190 @@ func (s ProfileYearMonth) Validate() error { return nil } +func (s *Publication) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if value, ok := s.ClosedReason.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: "closed_reason", + Error: err, + }) + } + if err := func() error { + if err := s.Fields.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PublicationClosedReason) Validate() error { + switch s { + case "never_published": + return nil + case "closed_by_candidate": + return nil + case "consent_revoked": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PublicationHeaders) 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 PublicationState) Validate() error { + switch s { + case "closed": + return nil + case "published": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s *PublicationUpdate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.State.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "state", + Error: err, + }) + } + if err := func() error { + if err := s.Fields.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "fields", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s PublicationVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + func (s *QuestionnaireSpecialization) Validate() error { if s == nil { return validate.ErrNilPointer @@ -14917,6 +16195,137 @@ func (s *SaveMyQuestionnaireUnauthorized) Validate() error { return nil } +func (s *SearchStatus) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if err := func() error { + if err := s.Version.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *SearchStatusHeaders) 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 *SearchStatusUpdate) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.ExpectedVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "expected_version", + Error: err, + }) + } + if err := func() error { + if err := s.Value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "value", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s SearchStatusValue) Validate() error { + switch s { + case "looking": + return nil + case "not_looking": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s SearchStatusVersion) Validate() error { + alias := (int64)(s) + if err := (validate.Int{ + MinSet: true, + Min: 0, + MaxSet: false, + Max: 0, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + func (s *SendOrganizationInvitationBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -15064,6 +16473,78 @@ func (s *SessionHeaders) Validate() error { return nil } +func (s *SetMyPublicationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMyPublicationConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMyPublicationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMyPublicationPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMyPublicationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMySearchStatusBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMySearchStatusForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMySearchStatusPreconditionFailed) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *SetMySearchStatusUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s SkillName) Validate() error { alias := (string)(s) if err := (validate.String{ @@ -16926,6 +18407,53 @@ func (s *TooManyRequestsHeaders) Validate() error { return nil } +func (s *UnhideOrganizationBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UnhideOrganizationForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *UnhideOrganizationNoContent) 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 len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *UnhideOrganizationUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *UpdateOrganizationBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { diff --git a/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go new file mode 100644 index 0000000..a2cbd08 --- /dev/null +++ b/backend/internal/adapter/primary/http/candidate_privacy_contract_test.go @@ -0,0 +1,408 @@ +package httpadapter + +import ( + "context" + "log/slog" + "net/http" + "slices" + "strings" + "testing" + + "github.com/ogen-go/ogen" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + metrics "lincodex/backend/internal/adapter/secondary/prometheus" +) + +const ( + privacyBasePath = "/api/v1/me/privacy" + privacyPublicationPath = privacyBasePath + "/publication" + privacySearchStatusPath = privacyBasePath + "/search-status" + privacyHiddenPath = privacyBasePath + "/hidden-organizations" + privacyOrganizationID = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01" +) + +// Each visibility setting is its own family of schemas. The three never +// refer to one another, so a client cannot read or write one setting through +// the DTO of another, and the search status is not a consent. +var ( + publicationSchemas = []string{"Publication", "PublicationUpdate", "PublicationVersion", "PublicationState", "PublicationClosedReason", "CardField", "CardFieldSet"} + searchStatusSchemas = []string{"SearchStatus", "SearchStatusUpdate", "SearchStatusVersion", "SearchStatusValue"} + hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"} + privacyOnlySchemas = []string{"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList"} + // 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"} +) + +func isPrivacySchema(name string) bool { + return slices.Contains(publicationSchemas, name) || slices.Contains(searchStatusSchemas, name) || + slices.Contains(hiddenSchemas, name) || slices.Contains(privacyOnlySchemas, name) +} + +// parameterName names a parameter by its component when it is a reference. +func parameterName(parameter *ogen.Parameter) string { + if parameter.Ref != "" { + return parameter.Ref[strings.LastIndex(parameter.Ref, "/")+1:] + } + return parameter.Name +} + +func privacyOperations(t *testing.T, spec *ogen.Spec) []*ogen.Operation { + t.Helper() + operations := make([]*ogen.Operation, 0, 9) + for _, id := range []string{ + "GetMyPrivacySettings", "SetMyPublication", "GetMyCardPreview", "SetMySearchStatus", "ListMyHiddenOrganizations", + "HideOrganization", "UnhideOrganization", "ListMyPrivacyHistory", "ListMyCardAccessHistory", + } { + operations = append(operations, operationByID(t, spec, id)) + } + return operations +} + +// Every visibility operation follows the project conventions: the session +// only for reads, the session and the CSRF token for changes, the version in +// the body with 412, 409 for a state that does not allow the change, 404 +// without a distinction, and no new problem code. +func TestPrivacyOperationsFollowTheConventions(t *testing.T) { + spec := parsePublicContract(t) + unsafe := map[string]bool{"SetMyPublication": true, "SetMySearchStatus": true, "HideOrganization": true, "UnhideOrganization": true} + for _, operation := range privacyOperations(t, spec) { + if !slices.Contains(operation.Tags, "privacy") { + t.Errorf("%s is not in the privacy tag", operation.OperationID) + } + if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") != unsafe[operation.OperationID] { + t.Errorf("%s security = %v, want the session cookie, and the CSRF token exactly for a change", operation.OperationID, operation.Security) + } + for _, status := range []string{"401", "403"} { + if operation.Responses[status] == nil { + t.Errorf("%s does not declare %s", operation.OperationID, status) + } + } + for _, parameter := range operation.Parameters { + name := parameterName(parameter) + if strings.EqualFold(name, "IdempotencyKey") || strings.EqualFold(name, "IfMatch") || strings.EqualFold(name, "Idempotency-Key") || strings.EqualFold(name, "If-Match") { + t.Errorf("%s takes %s, but every setting is a replaced state with its version in the body", operation.OperationID, name) + } + } + 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.Responses["default"] == nil { + t.Errorf("%s does not declare the problem default", operation.OperationID) + } + } + for _, id := range []string{"SetMyPublication", "SetMySearchStatus"} { + operation := operationByID(t, spec, id) + if operation.Responses["412"] == nil || operation.Responses["400"] == nil { + t.Errorf("%s does not declare 400 and 412", id) + } + update := resolveSchema(t, spec, operation.RequestBody.Content["application/json"].Schema) + if !slices.Contains(update.Required, "expected_version") { + t.Errorf("%s does not require expected_version", id) + } + } + // Publishing needs the C2 consent, and a missing one is a state conflict. + if operationByID(t, spec, "SetMyPublication").Responses["409"] == nil { + t.Error("SetMyPublication does not declare 409 state_conflict for a missing C2 consent") + } + if operationByID(t, spec, "SetMySearchStatus").Responses["409"] != nil { + t.Error("SetMySearchStatus declares 409: the status never depends on a consent") + } + // Hiding uses the same 404 for an unknown organization and one the + // candidate cannot see; lifting the hiding reveals nothing and has no 404. + hide := operationByID(t, spec, "HideOrganization") + if hide.Responses["404"] == nil || hide.Responses["409"] == nil || hide.Responses["429"] == nil || hide.RequestBody != nil { + t.Error("HideOrganization must declare 404, 409, and 429 and take no body") + } + unhide := operationByID(t, spec, "UnhideOrganization") + if unhide.Responses["204"] == nil || unhide.Responses["404"] != nil { + t.Error("UnhideOrganization must answer 204 and declare no 404: it reveals nothing about the organization") + } + // Lists page with the shared cursor parameters. + for _, id := range []string{"ListMyHiddenOrganizations", "ListMyPrivacyHistory", "ListMyCardAccessHistory"} { + names := []string{} + for _, parameter := range operationByID(t, spec, id).Parameters { + names = append(names, parameterName(parameter)) + } + if !slices.Contains(names, "PageLimit") || !slices.Contains(names, "PageCursor") { + t.Errorf("%s parameters = %v, want the shared PageLimit and PageCursor", id, names) + } + } + + // No new problem code: every code of the privacy responses already exists. + codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"})) + for _, code := range []string{"state_conflict", "version_conflict", "not_found", "rate_limited", "validation_failed"} { + if !slices.Contains(codes, code) { + t.Errorf("ProblemCode has no %s", code) + } + } +} + +// The publication stores which fields are published and refers to the C2 +// consent of the ledger; it neither carries nor changes a consent. The search +// status is not a consent either. +func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) { + spec := parsePublicContract(t) + index := componentsIndex(t, spec) + + for _, pair := range []struct { + name string + want []string + }{ + // The body names no consent: the server binds the active C2 record. + {"PublicationUpdate", []string{"expected_version", "fields", "state"}}, + {"SearchStatusUpdate", []string{"expected_version", "value"}}, + {"Publication", []string{"closed_reason", "consent_id", "fields", "published_at", "state", "version"}}, + {"SearchStatus", []string{"confirmed_at", "lapsed", "lapses_at", "value", "version"}}, + {"HiddenOrganization", []string{"hidden_at", "organization"}}, + {"PrivacySettings", []string{"hidden_organizations_total", "publication", "search_status"}}, + } { + 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 fields", pair.name) + } + } + + // The families do not reach one another. PrivacySettings is the one place + // that reads the three together. + families := map[string][]string{"publication": publicationSchemas, "search status": searchStatusSchemas, "hidden organizations": hiddenSchemas} + for name, members := range families { + for _, member := range members { + for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[member])) { + for otherName, others := range families { + if otherName != name && slices.Contains(others, reached) { + t.Errorf("the %s schema %s reaches the %s schema %s", name, member, otherName, reached) + } + } + } + } + } + + // A consent, a profile, an account, or an invitation is reachable from + // none of the settings: the status is a statement, never a consent. + for _, name := range slices.Concat(publicationSchemas, searchStatusSchemas, hiddenSchemas, privacyOnlySchemas) { + for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) { + if strings.HasPrefix(reached, "Consent") || strings.HasPrefix(reached, "Profile") || strings.HasPrefix(reached, "CandidateProfile") || + strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Contact") || reached == "Session" || reached == "User" { + t.Errorf("%s reaches %s", name, reached) + } + } + } + // The search status operation reaches no publication or hidden schema. + statusOperation := reachableSchemas(index, mustJSONValue(t, spec.Paths[privacySearchStatusPath])) + for _, name := range slices.Concat(publicationSchemas, hiddenSchemas, privacyOnlySchemas) { + if statusOperation[name] { + t.Errorf("the search status path reaches %s", name) + } + } + + // The published field set cannot name a name, a contact, or the salary. + fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"})) + want := []string{"categories", "stack", "experience", "soft_skills", "location", "relocation"} + slices.Sort(fields) + slices.Sort(want) + if !slices.Equal(fields, want) { + t.Errorf("CardField = %v, want %v", fields, want) + } + if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != uint64(len(want)) { + t.Error("CardFieldSet must hold distinct items and at most one per field") + } + status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"})) + if !slices.Equal(status, []string{"looking", "not_looking"}) { + t.Errorf("SearchStatusValue = %v, want looking and not_looking", status) + } +} + +// The anonymous card never reaches a profile, a contact, or an identifier: +// whatever an organization reads of a candidate before an accepted invitation +// is limited to its own closed set of properties. +func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) { + spec := parsePublicContract(t) + index := componentsIndex(t, spec) + + card := spec.Components.Schemas["AnonymousCardContent"] + if card == nil { + t.Fatal("the contract has no AnonymousCardContent") + } + if got, want := propertyNames(card), []string{"categories", "experience_months", "location", "relocation", "soft_skills", "stack"}; !slices.Equal(got, want) { + t.Errorf("AnonymousCardContent properties = %v, want %v", got, want) + } + if card.AdditionalProperties.Bool == nil || *card.AdditionalProperties.Bool { + t.Error("AnonymousCardContent accepts unknown properties") + } + // Each property is a card field and nothing else; a null is a hidden or + // missing value, never a flag that tells which. + for _, forbidden := range []string{"email", "phone", "telegram", "contact", "name", "salary", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume"} { + for _, name := range propertyNames(card) { + if strings.Contains(name, forbidden) { + t.Errorf("AnonymousCardContent has the property %q, which looks like %q", name, forbidden) + } + } + } + + // What the card and the preview reach is a small closed list of leaves. + allowed := []string{"AnonymousCardContent", "CardCategory", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode", "GradeCode", "StackTag", "Timestamp", "CardPreview"} + for _, name := range []string{"AnonymousCardContent", "CardPreview"} { + for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) { + if !slices.Contains(allowed, reached) { + t.Errorf("%s reaches %s, which the anonymous card must not carry", name, reached) + } + } + } + + // The private profile, the contact formats, and the contact disclosure + // are not reachable from any privacy schema or operation. + for path, item := range spec.Paths { + if !strings.HasPrefix(path, privacyBasePath) { + continue + } + for reached := range reachableSchemas(index, mustJSONValue(t, item)) { + if isProfileSchema(reached) || strings.HasPrefix(reached, "Contact") || reached == "EmailAddress" || reached == "PhoneNumber" || + 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") && + reached != "Problem" && reached != "ProblemCode" { + t.Errorf("%s reaches %s, which is neither a privacy schema nor a shared leaf", path, reached) + } + } + } + + // The reverse: the private profile family does not reach the card or any + // visibility schema, and an organization path reaches no setting of a + // candidate. The card content stays the only privacy schema meant for + // organization-visible operations later (TASK-185). + for name, schema := range spec.Components.Schemas { + if isPrivacySchema(name) { + continue + } + for reached := range reachableSchemas(index, mustJSONValue(t, schema)) { + if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" { + t.Errorf("%s reaches the candidate-private schema %s", name, reached) + } + } + } + for path, item := range spec.Paths { + if !strings.HasPrefix(path, "/api/v1/organizations") { + continue + } + for reached := range reachableSchemas(index, mustJSONValue(t, item)) { + if isPrivacySchema(reached) { + t.Errorf("%s reaches the candidate-private schema %s", path, reached) + } + } + } + for _, dto := range []any{api.AnonymousCardContent{}, api.CardCategory{}, api.CardPreview{}} { + assertNoJSONFields(t, dto, []string{ + "full_name", "name", "email", "phone", "telegram", "contacts", "salary_minimum", "user_id", "account_id", "profile_id", "employer", "resume", + }) + } +} + +// The generated request DTOs carry only what the candidate may choose: no +// consent identifier, time, interval, or policy version. +func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) { + assertNoJSONFields(t, api.PublicationUpdate{}, []string{"consent_id", "consent", "published_at", "version", "user_id", "contacts", "full_name", "salary_minimum"}) + assertNoJSONFields(t, api.SearchStatusUpdate{}, []string{"confirmed_at", "lapses_at", "lapsed", "interval", "policy_version", "policy_version_id", "consent_id", "version"}) + assertNoJSONFields(t, api.SearchStatus{}, []string{"consent_id", "published", "fields", "hidden_organizations", "policy_version_id"}) + assertNoJSONFields(t, api.HiddenOrganization{}, []string{"user_id", "candidate_id", "candidate", "reason"}) +} + +func newPrivacyRouter(t *testing.T) http.Handler { + t.Helper() + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return router +} + +// The operations are in the contract before their business logic: a schema +// failure answers 400 before anything else, a valid request with an accepted +// session answers 501, and no body reaches the handler without validation. +func TestPrivacySchemaValidationPrecedesImplementation(t *testing.T) { + session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} + for _, test := range []struct { + name string + method string + path string + body string + statusCode int + location api.ProblemFieldLocation + pointer string + code string + }{ + {name: "a valid publication", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["categories","stack"]}`, statusCode: http.StatusNotImplemented}, + {name: "a valid closing", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":3,"state":"closed","fields":[]}`, statusCode: http.StatusNotImplemented}, + {name: "a missing version", method: http.MethodPut, path: privacyPublicationPath, body: `{"state":"closed","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required"}, + {name: "a negative version", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":-1,"state":"closed","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid"}, + {name: "a contact as a card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["phone"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields/0", code: "invalid"}, + {name: "the full name as a card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["full_name"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields/0", code: "invalid"}, + {name: "a repeated card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["stack","stack"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields", code: "invalid"}, + {name: "a state outside the enum", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"draft","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/state", code: "invalid"}, + {name: "a consent identifier from the client", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["stack"],"consent_id":"01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid"}, + {name: "a valid status", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"looking"}`, statusCode: http.StatusNotImplemented}, + {name: "a status outside the enum", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"open"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/value", code: "invalid"}, + {name: "a confirmation time from the client", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"looking","confirmed_at":"2026-10-06T09:00:00Z"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid"}, + {name: "hiding an organization", method: http.MethodPut, path: privacyHiddenPath + "/" + privacyOrganizationID, statusCode: http.StatusNotImplemented}, + {name: "hiding a malformed identifier", method: http.MethodPut, path: privacyHiddenPath + "/not-a-uuid", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid"}, + {name: "lifting a hiding", method: http.MethodDelete, path: privacyHiddenPath + "/" + privacyOrganizationID, statusCode: http.StatusNotImplemented}, + {name: "lifting a malformed identifier", method: http.MethodDelete, path: privacyHiddenPath + "/not-a-uuid", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid"}, + {name: "the settings", method: http.MethodGet, path: privacyBasePath, statusCode: http.StatusNotImplemented}, + {name: "the preview", method: http.MethodGet, path: privacyBasePath + "/preview", statusCode: http.StatusNotImplemented}, + {name: "the hidden list", method: http.MethodGet, path: privacyHiddenPath + "?limit=50", statusCode: http.StatusNotImplemented}, + {name: "a hidden list limit over 100", method: http.MethodGet, path: privacyHiddenPath + "?limit=101", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid"}, + {name: "the history", method: http.MethodGet, path: privacyBasePath + "/history", statusCode: http.StatusNotImplemented}, + {name: "a malformed history cursor", method: http.MethodGet, path: privacyBasePath + "/history?cursor=not%20a%20cursor", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid"}, + {name: "the access history", method: http.MethodGet, path: privacyBasePath + "/access-history", statusCode: http.StatusNotImplemented}, + } { + t.Run(test.name, func(t *testing.T) { + response := serveIdentityRequest(t, newPrivacyRouter(t), identityRequest{method: test.method, path: test.path, body: test.body, headers: session}) + if test.statusCode == http.StatusNotImplemented { + requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) + return + } + problemBody := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed) + want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code} + for _, field := range problemBody.Errors { + if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { + return + } + } + t.Fatalf("errors = %+v, want an entry %+v", problemBody.Errors, want) + }) + } +} + +// Nothing here is reachable without a session: the deny-all security of the +// scaffold answers 401 for every operation, with or without a cookie. +func TestPrivacyAccessBeforeImplementation(t *testing.T) { + session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} + for _, test := range []identityRequest{ + {method: http.MethodGet, path: privacyBasePath}, + {method: http.MethodGet, path: privacyBasePath + "/preview"}, + {method: http.MethodGet, path: privacyBasePath + "/history", headers: session}, + {method: http.MethodGet, path: privacyBasePath + "/access-history"}, + {method: http.MethodGet, path: privacyHiddenPath}, + {method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"closed","fields":[]}`, headers: session}, + {method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"not_looking"}`, headers: session}, + {method: http.MethodPut, path: privacyHiddenPath + "/" + privacyOrganizationID, headers: session}, + {method: http.MethodDelete, path: privacyHiddenPath + "/" + privacyOrganizationID, headers: session}, + } { + t.Run(test.method+" "+test.path, func(t *testing.T) { + router := newTestRouter(t, func(context.Context) error { return nil }) + requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated) + }) + } +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 8e6f625..f0e5aa0 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -42,6 +42,30 @@ type AssessmentFamily struct { RetiredBy pgtype.Text } +type CandidateEffectivePublication struct { + UserID pgtype.UUID + Fields []string + PublishedAt pgtype.Timestamptz + Version int64 +} + +type CandidateHiddenOrganization struct { + UserID pgtype.UUID + OrganizationID pgtype.UUID + HiddenAt pgtype.Timestamptz +} + +type CandidatePrivacyEvent struct { + ID pgtype.UUID + UserID pgtype.UUID + Kind string + OccurredAt pgtype.Timestamptz + Fields []string + ConsentRecordID pgtype.UUID + ConsentPurpose pgtype.Text + OrganizationID pgtype.UUID +} + type CandidateProfile struct { UserID pgtype.UUID Version int64 @@ -62,6 +86,30 @@ type CandidateProfileClaim struct { ConfirmedAt pgtype.Timestamptz } +type CandidatePublication struct { + UserID pgtype.UUID + State string + Fields []string + ConsentRecordID pgtype.UUID + ConsentPurpose pgtype.Text + PublishedAt pgtype.Timestamptz + ClosedAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +type CandidateSearchStatus struct { + UserID pgtype.UUID + Status string + ConfirmedAt pgtype.Timestamptz + LapsesAt pgtype.Timestamptz + PolicyVersionID pgtype.UUID + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + type ConsentRecord struct { ID pgtype.UUID SubjectID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go new file mode 100644 index 0000000..05d91be --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/privacy.sql.go @@ -0,0 +1,683 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: privacy.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const countCandidateHiddenOrganizations = `-- name: CountCandidateHiddenOrganizations :one +SELECT count(*) AS total +FROM candidate_hidden_organizations +WHERE user_id = $1 +` + +// Counts the hiding records of one candidate for the settings read. +func (q *Queries) CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error) { + row := q.db.QueryRow(ctx, countCandidateHiddenOrganizations, userID) + var total int64 + err := row.Scan(&total) + return total, err +} + +const deleteCandidateHiddenOrganization = `-- name: DeleteCandidateHiddenOrganization :one +DELETE FROM candidate_hidden_organizations +WHERE user_id = $1 AND organization_id = $2 +RETURNING organization_id +` + +type DeleteCandidateHiddenOrganizationParams struct { + UserID pgtype.UUID + OrganizationID pgtype.UUID +} + +// Lifts one hiding. No row returns when the organization was not hidden, so +// the caller writes the history event only for a real deletion and answers +// 204 either way. +func (q *Queries) DeleteCandidateHiddenOrganization(ctx context.Context, arg DeleteCandidateHiddenOrganizationParams) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, deleteCandidateHiddenOrganization, arg.UserID, arg.OrganizationID) + var organization_id pgtype.UUID + err := row.Scan(&organization_id) + return organization_id, err +} + +const getCandidateHiddenOrganization = `-- name: GetCandidateHiddenOrganization :one +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = $1 + AND candidate_hidden_organizations.organization_id = $2 +` + +type GetCandidateHiddenOrganizationParams struct { + UserID pgtype.UUID + OrganizationID pgtype.UUID +} + +type GetCandidateHiddenOrganizationRow struct { + OrganizationID pgtype.UUID + OrganizationName string + HiddenAt pgtype.Timestamptz +} + +// Reads one hiding of the candidate with the current name of the +// organization. +func (q *Queries) GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error) { + row := q.db.QueryRow(ctx, getCandidateHiddenOrganization, arg.UserID, arg.OrganizationID) + var i GetCandidateHiddenOrganizationRow + err := row.Scan(&i.OrganizationID, &i.OrganizationName, &i.HiddenAt) + return i, err +} + +const insertCandidateHiddenOrganization = `-- name: InsertCandidateHiddenOrganization :one +INSERT INTO candidate_hidden_organizations ( + user_id, + organization_id, + hidden_at +) VALUES ( + $1, + $2, + $3 +) +ON CONFLICT (user_id, organization_id) DO NOTHING +RETURNING user_id, organization_id, hidden_at +` + +type InsertCandidateHiddenOrganizationParams struct { + UserID pgtype.UUID + OrganizationID pgtype.UUID + At pgtype.Timestamptz +} + +// Hides one organization. No row returns when the pair already exists, and +// the caller reads the existing record with its original time. The foreign key +// refuses an unknown organization (SQLSTATE 23503); the caller answers it +// exactly like an organization the candidate cannot see. The trigger refuses +// the 1001st record (candidate_hidden_organizations_limit). The trigger runs +// before the conflict check, so the caller reads the existing record first +// and a repeat at the limit is never refused. +func (q *Queries) InsertCandidateHiddenOrganization(ctx context.Context, arg InsertCandidateHiddenOrganizationParams) (CandidateHiddenOrganization, error) { + row := q.db.QueryRow(ctx, insertCandidateHiddenOrganization, arg.UserID, arg.OrganizationID, arg.At) + var i CandidateHiddenOrganization + err := row.Scan(&i.UserID, &i.OrganizationID, &i.HiddenAt) + return i, err +} + +const insertCandidatePrivacyEvent = `-- name: InsertCandidatePrivacyEvent :exec +INSERT INTO candidate_privacy_events ( + id, + user_id, + kind, + occurred_at, + fields, + consent_record_id, + organization_id +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +` + +type InsertCandidatePrivacyEventParams struct { + ID pgtype.UUID + UserID pgtype.UUID + Kind string + OccurredAt pgtype.Timestamptz + Fields []string + ConsentRecordID pgtype.UUID + OrganizationID pgtype.UUID +} + +// Appends one event to the settings history. The row holds identifiers, card +// field codes, and times, never a name; the caller +// writes it in the transaction of the change it records. +func (q *Queries) InsertCandidatePrivacyEvent(ctx context.Context, arg InsertCandidatePrivacyEventParams) error { + _, err := q.db.Exec(ctx, insertCandidatePrivacyEvent, + arg.ID, + arg.UserID, + arg.Kind, + arg.OccurredAt, + arg.Fields, + arg.ConsentRecordID, + arg.OrganizationID, + ) + return err +} + +const insertCandidatePublication = `-- name: InsertCandidatePublication :one +INSERT INTO candidate_publications ( + user_id, + state, + fields, + consent_record_id, + published_at, + closed_at, + version, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + 1, + $7, + $7 +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version +` + +type InsertCandidatePublicationParams struct { + UserID pgtype.UUID + State string + Fields []string + ConsentRecordID pgtype.UUID + PublishedAt pgtype.Timestamptz + ClosedAt pgtype.Timestamptz + At pgtype.Timestamptz +} + +type InsertCandidatePublicationRow struct { + UserID pgtype.UUID + Version int64 +} + +// Stores the first publication at version 1. No row returns when the account +// already has a row, so a first publication that lost a race with another +// one is answered as a version conflict. The foreign key refuses a record +// that is not a C2 record of this account. +func (q *Queries) InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error) { + row := q.db.QueryRow(ctx, insertCandidatePublication, + arg.UserID, + arg.State, + arg.Fields, + arg.ConsentRecordID, + arg.PublishedAt, + arg.ClosedAt, + arg.At, + ) + var i InsertCandidatePublicationRow + err := row.Scan(&i.UserID, &i.Version) + return i, err +} + +const insertCandidateSearchStatus = `-- name: InsertCandidateSearchStatus :one +INSERT INTO candidate_search_statuses ( + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4, + $5, + 1, + $6, + $6 +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version +` + +type InsertCandidateSearchStatusParams struct { + UserID pgtype.UUID + Status string + ConfirmedAt pgtype.Timestamptz + LapsesAt pgtype.Timestamptz + PolicyVersionID pgtype.UUID + At pgtype.Timestamptz +} + +type InsertCandidateSearchStatusRow struct { + UserID pgtype.UUID + Version int64 +} + +// Stores the first status at version 1; no row returns when one exists. +func (q *Queries) InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error) { + row := q.db.QueryRow(ctx, insertCandidateSearchStatus, + arg.UserID, + arg.Status, + arg.ConfirmedAt, + arg.LapsesAt, + arg.PolicyVersionID, + arg.At, + ) + var i InsertCandidateSearchStatusRow + err := row.Scan(&i.UserID, &i.Version) + return i, err +} + +const listCandidateHiddenOrganizations = `-- name: ListCandidateHiddenOrganizations :many +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = $1 + AND ( + $2::timestamptz IS NULL + OR ( + candidate_hidden_organizations.hidden_at, + candidate_hidden_organizations.organization_id + ) < ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY + candidate_hidden_organizations.hidden_at DESC, + candidate_hidden_organizations.organization_id DESC +LIMIT $4 +` + +type ListCandidateHiddenOrganizationsParams struct { + UserID pgtype.UUID + AfterHiddenAt pgtype.Timestamptz + AfterOrganizationID pgtype.UUID + RowLimit int32 +} + +type ListCandidateHiddenOrganizationsRow struct { + OrganizationID pgtype.UUID + OrganizationName string + HiddenAt pgtype.Timestamptz +} + +// 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. +func (q *Queries) ListCandidateHiddenOrganizations(ctx context.Context, arg ListCandidateHiddenOrganizationsParams) ([]ListCandidateHiddenOrganizationsRow, error) { + rows, err := q.db.Query(ctx, listCandidateHiddenOrganizations, + arg.UserID, + arg.AfterHiddenAt, + arg.AfterOrganizationID, + arg.RowLimit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCandidateHiddenOrganizationsRow + for rows.Next() { + var i ListCandidateHiddenOrganizationsRow + if err := rows.Scan(&i.OrganizationID, &i.OrganizationName, &i.HiddenAt); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listCandidatePrivacyEvents = `-- name: ListCandidatePrivacyEvents :many +SELECT + candidate_privacy_events.id, + candidate_privacy_events.kind, + candidate_privacy_events.occurred_at, + candidate_privacy_events.fields, + candidate_privacy_events.consent_record_id, + candidate_privacy_events.organization_id, + organizations.name AS organization_name +FROM candidate_privacy_events +LEFT JOIN organizations + ON organizations.id = candidate_privacy_events.organization_id +WHERE + candidate_privacy_events.user_id = $1 + AND ( + $2::timestamptz IS NULL + OR (candidate_privacy_events.occurred_at, candidate_privacy_events.id) < ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY + candidate_privacy_events.occurred_at DESC, + candidate_privacy_events.id DESC +LIMIT $4 +` + +type ListCandidatePrivacyEventsParams struct { + UserID pgtype.UUID + AfterOccurredAt pgtype.Timestamptz + AfterID pgtype.UUID + RowLimit int32 +} + +type ListCandidatePrivacyEventsRow struct { + ID pgtype.UUID + Kind string + OccurredAt pgtype.Timestamptz + Fields []string + ConsentRecordID pgtype.UUID + OrganizationID pgtype.UUID + OrganizationName pgtype.Text +} + +// 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 +// (occurred_at, id) position of the last event of the previous page. +func (q *Queries) ListCandidatePrivacyEvents(ctx context.Context, arg ListCandidatePrivacyEventsParams) ([]ListCandidatePrivacyEventsRow, error) { + rows, err := q.db.Query(ctx, listCandidatePrivacyEvents, + arg.UserID, + arg.AfterOccurredAt, + arg.AfterID, + arg.RowLimit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCandidatePrivacyEventsRow + for rows.Next() { + var i ListCandidatePrivacyEventsRow + if err := rows.Scan( + &i.ID, + &i.Kind, + &i.OccurredAt, + &i.Fields, + &i.ConsentRecordID, + &i.OrganizationID, + &i.OrganizationName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockCurrentC2Record = `-- name: LockCurrentC2Record :one +SELECT id +FROM consent_records +WHERE + subject_id = $1 + AND purpose = 'c2' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +FOR SHARE +` + +// Takes the candidate's current unrevoked C2 record for a publication and +// keeps it locked until the transaction ends. The share lock conflicts with +// the revocation stamp (an UPDATE of the row), so a revocation either commits +// before this statement, which then returns no row and the publication is +// refused, or waits until the publication transaction commits and closes the +// card right after. The caller must run it in the transaction that writes the +// publication and must re-read the effective state (ReadCandidatePublication) +// in that transaction to build its response. +func (q *Queries) LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, lockCurrentC2Record, subjectID) + var id pgtype.UUID + err := row.Scan(&id) + return id, err +} + +const readCandidatePublication = `-- name: ReadCandidatePublication :one + +SELECT + candidate_publications.user_id, + candidate_publications.state, + candidate_publications.fields, + candidate_publications.consent_record_id, + candidate_publications.published_at, + candidate_publications.closed_at, + candidate_publications.version, + candidate_publications.created_at, + candidate_publications.updated_at, + consent_records.revoked_at AS consent_revoked_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE candidate_publications.user_id = $1 +` + +type ReadCandidatePublicationRow struct { + UserID pgtype.UUID + State string + Fields []string + ConsentRecordID pgtype.UUID + PublishedAt pgtype.Timestamptz + ClosedAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + ConsentRevokedAt pgtype.Timestamptz +} + +// Queries of the candidate visibility settings (TASK-088): the publication of +// the card, the search status, the hidden organizations, and the history of +// these settings. Every statement is scoped by the candidate's user_id, and +// no statement selects another account's row. No statement reads or writes a +// profile value, a name, or a contact. A candidate with no row is closed, not +// looking, and hides nobody; no statement creates a row except an explicit +// act of the candidate. +// Reads the publication with the revocation state of the C2 record behind it +// in one statement, so the stored setting and the ledger come from one +// snapshot. The effective state is computed from them: published only while +// consent_revoked_at is NULL. No row means the candidate never published. +func (q *Queries) ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error) { + row := q.db.QueryRow(ctx, readCandidatePublication, userID) + var i ReadCandidatePublicationRow + err := row.Scan( + &i.UserID, + &i.State, + &i.Fields, + &i.ConsentRecordID, + &i.PublishedAt, + &i.ClosedAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + &i.ConsentRevokedAt, + ) + return i, err +} + +const readCandidateSearchStatus = `-- name: ReadCandidateSearchStatus :one +SELECT + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +FROM candidate_search_statuses +WHERE user_id = $1 +` + +// No row means the status was never set, which reads as not looking. The +// lapse is computed by the caller from lapses_at and its clock and is never +// written. +func (q *Queries) ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error) { + row := q.db.QueryRow(ctx, readCandidateSearchStatus, userID) + var i CandidateSearchStatus + err := row.Scan( + &i.UserID, + &i.Status, + &i.ConfirmedAt, + &i.LapsesAt, + &i.PolicyVersionID, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const readPublicationVisibleToOrganization = `-- name: ReadPublicationVisibleToOrganization :one +SELECT + effective.user_id, + effective.fields, + effective.published_at +FROM candidate_effective_publications AS effective +WHERE + effective.user_id = $1 + AND NOT exists( + SELECT 1 FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = $2 + ) +` + +type ReadPublicationVisibleToOrganizationParams struct { + UserID pgtype.UUID + OrganizationID pgtype.UUID +} + +type ReadPublicationVisibleToOrganizationRow struct { + UserID pgtype.UUID + Fields []string + PublishedAt pgtype.Timestamptz +} + +// The organization-facing read of a candidate's publication: the effective +// view (published and backed by an unrevoked C2) and no hiding of the reading +// organization. No row means the organization reads nothing, whichever of +// the reasons applies, so it cannot tell a hidden candidate from an +// unpublished one. Every organization-facing read of a publication starts +// from this shape (TASK-185, TASK-089, TASK-090). +func (q *Queries) ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error) { + row := q.db.QueryRow(ctx, readPublicationVisibleToOrganization, arg.UserID, arg.OrganizationID) + var i ReadPublicationVisibleToOrganizationRow + err := row.Scan(&i.UserID, &i.Fields, &i.PublishedAt) + return i, err +} + +const updateCandidatePublication = `-- name: UpdateCandidatePublication :one +UPDATE candidate_publications +SET + state = $1, + fields = $2, + consent_record_id = $3, + published_at = $4, + closed_at = $5, + version = candidate_publications.version + 1, + updated_at = greatest(candidate_publications.updated_at, $6) +WHERE + candidate_publications.user_id = $7 + AND candidate_publications.version = $8 +RETURNING user_id, version +` + +type UpdateCandidatePublicationParams struct { + State string + Fields []string + ConsentRecordID pgtype.UUID + PublishedAt pgtype.Timestamptz + ClosedAt pgtype.Timestamptz + At pgtype.Timestamptz + UserID pgtype.UUID + ExpectedVersion int64 +} + +type UpdateCandidatePublicationRow struct { + UserID pgtype.UUID + Version int64 +} + +// Replaces the publication over the version the caller read and advances the +// version in the same statement. No row returns for a stale version, which +// the caller answers as a version conflict. The update time never moves back, +// as in the profile. +func (q *Queries) UpdateCandidatePublication(ctx context.Context, arg UpdateCandidatePublicationParams) (UpdateCandidatePublicationRow, error) { + row := q.db.QueryRow(ctx, updateCandidatePublication, + arg.State, + arg.Fields, + arg.ConsentRecordID, + arg.PublishedAt, + arg.ClosedAt, + arg.At, + arg.UserID, + arg.ExpectedVersion, + ) + var i UpdateCandidatePublicationRow + err := row.Scan(&i.UserID, &i.Version) + return i, err +} + +const updateCandidateSearchStatus = `-- name: UpdateCandidateSearchStatus :one +UPDATE candidate_search_statuses +SET + status = $1, + confirmed_at = $2, + lapses_at = $3, + policy_version_id = $4, + version = candidate_search_statuses.version + 1, + updated_at = greatest(candidate_search_statuses.updated_at, $5) +WHERE + candidate_search_statuses.user_id = $6 + AND candidate_search_statuses.version = $7 +RETURNING user_id, version +` + +type UpdateCandidateSearchStatusParams struct { + Status string + ConfirmedAt pgtype.Timestamptz + LapsesAt pgtype.Timestamptz + PolicyVersionID pgtype.UUID + At pgtype.Timestamptz + UserID pgtype.UUID + ExpectedVersion int64 +} + +type UpdateCandidateSearchStatusRow struct { + UserID pgtype.UUID + Version int64 +} + +// Replaces the status over the version the caller read. Looking also stores +// the new confirmation, lapse time, and policy version; not looking clears +// them. It never names the publication or the hidden organizations. +func (q *Queries) UpdateCandidateSearchStatus(ctx context.Context, arg UpdateCandidateSearchStatusParams) (UpdateCandidateSearchStatusRow, error) { + row := q.db.QueryRow(ctx, updateCandidateSearchStatus, + arg.Status, + arg.ConfirmedAt, + arg.LapsesAt, + arg.PolicyVersionID, + arg.At, + arg.UserID, + arg.ExpectedVersion, + ) + var i UpdateCandidateSearchStatusRow + err := row.Scan(&i.UserID, &i.Version) + return i, err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index b65af98..7361fdb 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -88,9 +88,15 @@ type Querier interface { // returned registration version in the same transaction, rolled back when it // matches no row. ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) + // Counts the hiding records of one candidate for the settings read. + CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error) // Counts the families of a category that have at least one published // version, however many versions each has. CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error) + // Lifts one hiding. No row returns when the organization was not hidden, so + // the caller writes the history event only for a real deletion and answers + // 204 either way. + DeleteCandidateHiddenOrganization(ctx context.Context, arg DeleteCandidateHiddenOrganizationParams) (pgtype.UUID, error) // Removes the claims that a save replaces. The adapter calls it after the // version advanced and before it inserts the new set, in one transaction. DeleteCandidateProfileClaims(ctx context.Context, userID pgtype.UUID) error @@ -139,6 +145,9 @@ type Querier interface { GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) + // Reads one hiding of the candidate with the current name of the + // organization. + GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error) GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) GetCurrentAssessmentCategoryOpening(ctx context.Context, category string) (AssessmentCategoryOpening, error) @@ -222,6 +231,18 @@ type Querier interface { // returns no row instead of an error, so a conflict does not abort the // surrounding transaction. InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error) + // Hides one organization. No row returns when the pair already exists, and + // the caller reads the existing record with its original time. The foreign key + // refuses an unknown organization (SQLSTATE 23503); the caller answers it + // exactly like an organization the candidate cannot see. The trigger refuses + // the 1001st record (candidate_hidden_organizations_limit). The trigger runs + // before the conflict check, so the caller reads the existing record first + // and a repeat at the limit is never refused. + InsertCandidateHiddenOrganization(ctx context.Context, arg InsertCandidateHiddenOrganizationParams) (CandidateHiddenOrganization, error) + // Appends one event to the settings history. The row holds identifiers, card + // field codes, and times, never a name; the caller + // writes it in the transaction of the change it records. + InsertCandidatePrivacyEvent(ctx context.Context, arg InsertCandidatePrivacyEventParams) error // Queries of the manual candidate profile (TASK-066). The profile is personal // data of the account that owns it: every statement is scoped by user_id, and // no statement selects another account's row. None of them names a file, the @@ -235,6 +256,13 @@ type Querier interface { // statement never takes a trust level from the caller, because every claim // has level 0. InsertCandidateProfileClaim(ctx context.Context, arg InsertCandidateProfileClaimParams) error + // Stores the first publication at version 1. No row returns when the account + // already has a row, so a first publication that lost a race with another + // one is answered as a version conflict. The foreign key refuses a record + // that is not a C2 record of this account. + InsertCandidatePublication(ctx context.Context, arg InsertCandidatePublicationParams) (InsertCandidatePublicationRow, error) + // Stores the first status at version 1; no row returns when one exists. + InsertCandidateSearchStatus(ctx context.Context, arg InsertCandidateSearchStatusParams) (InsertCandidateSearchStatusRow, error) // Records a grant of C1, C2, C3, or C5. An unrevoked record of the same // subject, purpose, and text version already exists when no row returns; // the insert then changes nothing and does not abort the transaction. @@ -297,6 +325,16 @@ type Querier interface { // given position; an empty key and version 0 start at the beginning. The // (family_key, version) unique index serves the scan. ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, 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) + // 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 + // (occurred_at, id) position of the last event of the previous page. + ListCandidatePrivacyEvents(ctx context.Context, arg ListCandidatePrivacyEventsParams) ([]ListCandidatePrivacyEventsRow, error) // One page of the subject's ledger, newest grant first, optionally limited // to one state. Every record query is scoped by the subject, so a caller // never reads or revokes another subject's consent. The state is computed, @@ -329,6 +367,15 @@ type Querier interface { // canceled, or reclaimed after the lease expired. While the lock is held, // other workers skip the row, so the handler never runs twice at once. LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error) + // Takes the candidate's current unrevoked C2 record for a publication and + // keeps it locked until the transaction ends. The share lock conflicts with + // the revocation stamp (an UPDATE of the row), so a revocation either commits + // before this statement, which then returns no row and the publication is + // refused, or waits until the publication transaction commits and closes the + // card right after. The caller must run it in the transaction that writes the + // publication and must re-read the effective state (ReadCandidatePublication) + // in that transaction to build its response. + LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error) // Locks the listed window rows until the transaction ends, in // (period_kind, period_start) order, the same order for every caller, and // returns their usage. Under READ COMMITTED a waiting caller reads the usage @@ -387,6 +434,29 @@ type Querier interface { // 0). Claims come in a stable order: single fields by kind, list items by // position. Never replace this with two statements. ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error) + // Queries of the candidate visibility settings (TASK-088): the publication of + // the card, the search status, the hidden organizations, and the history of + // these settings. Every statement is scoped by the candidate's user_id, and + // no statement selects another account's row. No statement reads or writes a + // profile value, a name, or a contact. A candidate with no row is closed, not + // looking, and hides nobody; no statement creates a row except an explicit + // act of the candidate. + // Reads the publication with the revocation state of the C2 record behind it + // in one statement, so the stored setting and the ledger come from one + // snapshot. The effective state is computed from them: published only while + // consent_revoked_at is NULL. No row means the candidate never published. + ReadCandidatePublication(ctx context.Context, userID pgtype.UUID) (ReadCandidatePublicationRow, error) + // No row means the status was never set, which reads as not looking. The + // lapse is computed by the caller from lapses_at and its clock and is never + // written. + ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error) + // The organization-facing read of a candidate's publication: the effective + // view (published and backed by an unrevoked C2) and no hiding of the reading + // organization. No row means the organization reads nothing, whichever of + // the reasons applies, so it cannot tell a hidden candidate from an + // unpublished one. Every organization-facing read of a publication starts + // from this shape (TASK-185, TASK-089, TASK-090). + ReadPublicationVisibleToOrganization(ctx context.Context, arg ReadPublicationVisibleToOrganizationParams) (ReadPublicationVisibleToOrganizationRow, error) // Advances a delivery past one attempt and appends the attempt in one // statement, so both happen or neither does, inside or outside a // transaction. The update applies only while the stored version still @@ -480,6 +550,15 @@ type Querier interface { // revoked, expired, or idle session is not revived; the update re-checks // those conditions against a concurrent change. TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error) + // Replaces the publication over the version the caller read and advances the + // version in the same statement. No row returns for a stale version, which + // the caller answers as a version conflict. The update time never moves back, + // as in the profile. + UpdateCandidatePublication(ctx context.Context, arg UpdateCandidatePublicationParams) (UpdateCandidatePublicationRow, error) + // Replaces the status over the version the caller read. Looking also stores + // the new confirmation, lapse time, and policy version; not looking clears + // them. It never names the publication or the hidden organizations. + UpdateCandidateSearchStatus(ctx context.Context, arg UpdateCandidateSearchStatusParams) (UpdateCandidateSearchStatusRow, error) // Stores a change of the delivery state that is not an attempt: a quota wait, // a cancellation, or a new provider account before the first attempt. It // applies only while the stored version still equals expected_version and diff --git a/backend/internal/domain/visibility.go b/backend/internal/domain/visibility.go new file mode 100644 index 0000000..a3df88d --- /dev/null +++ b/backend/internal/domain/visibility.go @@ -0,0 +1,837 @@ +package domain + +import ( + "errors" + "fmt" + "log/slog" + "regexp" + "slices" + "strings" + "time" + "unicode" + + "github.com/google/uuid" + "golang.org/x/text/unicode/norm" +) + +// This file holds the visibility settings of a candidate (PRD FR02 and FR12, +// TASK-088): the publication of the anonymous card, the search status, and the +// organizations the candidate hides the profile from. +// +// The rules that shape every type here: +// - A candidate is closed by default. A new account has version 0 of every +// setting, and no value in this file opens anything by itself. +// - The consent C2 stays in the consent ledger. A publication refers to the +// C2 record that backs it and is effective only while that record is +// unrevoked; the search status is a statement and never a consent, so no +// function of one setting reads or changes another. +// - Nothing becomes more public automatically: a lapse of the search status +// only narrows it, a revoked C2 closes the card, and a new C2 publishes +// nothing. + +var ( + // ErrInvalidVisibility reports a visibility setting, request, or stored + // row that breaks a rule. + ErrInvalidVisibility = errors.New("invalid visibility setting") + + // ErrVisibilityVersionConflict reports that the expected version of a + // setting is not the current one: another change advanced it, or the + // client named a version that does not exist. Nothing was changed; the + // client reads the settings again. + ErrVisibilityVersionConflict = errors.New("visibility setting changed concurrently") + + // ErrPublicationConsentRequired reports a publication without an active + // C2 consent of the account. The candidate gives C2 first. + ErrPublicationConsentRequired = errors.New("publication needs an active C2 consent") +) + +// VisibilityFieldError reports the request field that broke a visibility +// rule. It matches ErrInvalidVisibility with errors.Is, and an HTTP adapter +// reads Pointer with errors.As to answer 400 with the pointer of the field. +// Neither field quotes the submitted value. +type VisibilityFieldError struct { + // Pointer is the JSON Pointer of the field in the request body, such as + // "/fields". + Pointer string + // Reason says which rule the field broke. + Reason string +} + +func (err *VisibilityFieldError) Error() string { + return "visibility field " + err.Pointer + " " + err.Reason +} + +func (err *VisibilityFieldError) Unwrap() error { return ErrInvalidVisibility } + +func invalidVisibilityField(location, pointer, reason string) error { + return fmt.Errorf("%s - %w", location, &VisibilityFieldError{Pointer: pointer, Reason: reason}) +} + +// MaxHiddenOrganizations is the number of organizations one candidate can +// hide the profile from. The database trigger +// candidate_hidden_organizations_enforce_limit enforces the same bound, and +// the contract's hidden_organizations_total maximum equals it. +const MaxHiddenOrganizations = 1000 + +// CardField is a group of values of the anonymous candidate card that a +// candidate chooses to publish. The set is closed and has no member for the +// full name, a contact, or the lowest salary: the card never carries them, so +// no choice can publish them. +type CardField string + +const ( + CardFieldCategories CardField = "categories" + CardFieldStack CardField = "stack" + CardFieldExperience CardField = "experience" + CardFieldSoftSkills CardField = "soft_skills" + CardFieldLocation CardField = "location" + CardFieldRelocation CardField = "relocation" +) + +const ( + // cardFieldsPointer is the request pointer of the field set. + cardFieldsPointer = "/fields" + // firstStoredVersion is the version of the first saved row of a setting; + // the contract's version 0 is the absence of a row. + firstStoredVersion int64 = 1 +) + +var cardFields = []CardField{ + CardFieldCategories, CardFieldStack, CardFieldExperience, + CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation, +} + +// CardFields returns every card field the contract defines. +func CardFields() []CardField { return slices.Clone(cardFields) } + +// Valid reports whether the field is one of the contract's codes. +func (field CardField) Valid() bool { return slices.Contains(cardFields, field) } + +// CardFieldSet is a set of distinct card fields in the canonical order that +// the database stores: ascending order of the codes. The zero value is the +// empty set. Equal sets are equal arrays. +type CardFieldSet struct { + fields []CardField +} + +// NewCardFieldSet validates the fields and returns them in canonical order. A +// repeated or unknown field is invalid, because the contract requires unique +// items from the closed enum. +func NewCardFieldSet(fields []CardField) (CardFieldSet, error) { + const location = "domain.NewCardFieldSet" + if len(fields) > len(cardFields) { + return CardFieldSet{}, invalidVisibilityField(location, cardFieldsPointer, "has more items than card fields exist") + } + // Unknown values are reported at their position in the request. + for index, field := range fields { + if !field.Valid() { + return CardFieldSet{}, invalidVisibilityField(location, fmt.Sprintf("%s/%d", cardFieldsPointer, index), "is not a card field") + } + } + ordered := slices.Clone(fields) + slices.Sort(ordered) + if len(slices.Compact(slices.Clone(ordered))) != len(ordered) { + return CardFieldSet{}, invalidVisibilityField(location, cardFieldsPointer, "repeats a card field") + } + return CardFieldSet{fields: ordered}, nil +} + +// Fields returns a copy of the fields in canonical order. +func (set CardFieldSet) Fields() []CardField { return slices.Clone(set.fields) } + +// Codes returns the field codes in canonical order, the form that the storage +// column holds. It is never nil, so an empty set is stored as an empty array. +func (set CardFieldSet) Codes() []string { + codes := make([]string, 0, len(set.fields)) + for _, field := range set.fields { + codes = append(codes, string(field)) + } + return codes +} + +func (set CardFieldSet) IsEmpty() bool { return len(set.fields) == 0 } + +func (set CardFieldSet) Contains(field CardField) bool { return slices.Contains(set.fields, field) } + +func (set CardFieldSet) Equal(other CardFieldSet) bool { return slices.Equal(set.fields, other.fields) } + +// PublicationState says whether organizations can read the card at all. +type PublicationState string + +const ( + PublicationClosed PublicationState = "closed" + PublicationPublished PublicationState = "published" +) + +// PublicationClosedReason explains a closed profile to its candidate. +type PublicationClosedReason string + +const ( + ClosedNeverPublished PublicationClosedReason = "never_published" + ClosedByCandidate PublicationClosedReason = "closed_by_candidate" + ClosedConsentRevoked PublicationClosedReason = "consent_revoked" +) + +// StoredPublication is a candidate_publications row joined with the +// revocation state of its C2 record, as one read returns them. +type StoredPublication struct { + UserID uuid.UUID + State string + Fields []string + ConsentRecordID uuid.UUID + PublishedAt time.Time + ClosedAt time.Time + Version int64 + // ConsentRevoked is true when the referenced C2 record has been revoked. + ConsentRevoked bool +} + +// Publication is the publication setting of one candidate. The zero state of +// a candidate who never published is built by NewPublication: closed, version +// 0, no consent record. The stored state is not the effective state: the card +// is readable only while the stored setting is published and its C2 record is +// unrevoked. +type Publication struct { + userID uuid.UUID + state PublicationState + fields CardFieldSet + consentRecordID uuid.UUID + publishedAt time.Time + closedAt time.Time + version int64 + consentRevoked bool +} + +// NewPublication returns the setting of a candidate who never published: the +// profile is closed. A new account starts here, and nothing in the account, +// profile, or questionnaire flows leaves it. +func NewPublication(userID uuid.UUID) (Publication, error) { + if userID == uuid.Nil { + return Publication{}, fmt.Errorf("domain.NewPublication - %w: user ID is empty", ErrInvalidVisibility) + } + return Publication{userID: userID, state: PublicationClosed}, nil +} + +// RestorePublication rebuilds a setting from a stored row and rejects a row +// that breaks the invariants the database also enforces. +func RestorePublication(stored StoredPublication) (Publication, error) { + const location = "domain.RestorePublication" + if stored.UserID == uuid.Nil || stored.ConsentRecordID == uuid.Nil || stored.Version < firstStoredVersion || stored.PublishedAt.IsZero() { + return Publication{}, fmt.Errorf("%s - %w: identifiers, version, or time are missing", location, ErrInvalidVisibility) + } + state := PublicationState(stored.State) + fields, err := restoreCardFieldSet(location, stored.Fields) + if err != nil { + return Publication{}, err + } + switch { + case state == PublicationPublished && !fields.IsEmpty() && stored.ClosedAt.IsZero(): + case state == PublicationClosed && fields.IsEmpty() && !stored.ClosedAt.IsZero() && !stored.ClosedAt.Before(stored.PublishedAt): + default: + return Publication{}, fmt.Errorf("%s - %w: state, fields, and closing time disagree", location, ErrInvalidVisibility) + } + return Publication{ + userID: stored.UserID, state: state, fields: fields, consentRecordID: stored.ConsentRecordID, + publishedAt: stored.PublishedAt, closedAt: stored.ClosedAt, version: stored.Version, consentRevoked: stored.ConsentRevoked, + }, nil +} + +// restoreCardFieldSet decodes the stored codes and requires the canonical +// form, so a row changed outside the application is rejected. +func restoreCardFieldSet(location string, codes []string) (CardFieldSet, error) { + fields := make([]CardField, 0, len(codes)) + for _, code := range codes { + fields = append(fields, CardField(code)) + } + set, err := NewCardFieldSet(fields) + if err != nil { + return CardFieldSet{}, fmt.Errorf("%s - stored card fields: %w", location, err) + } + if !slices.Equal(set.Codes(), codes) && len(codes) > 0 { + return CardFieldSet{}, fmt.Errorf("%s - %w: stored card fields are not in canonical order", location, ErrInvalidVisibility) + } + return set, nil +} + +func (publication Publication) UserID() uuid.UUID { return publication.userID } + +// Version is 0 for a candidate who never published. +func (publication Publication) Version() int64 { return publication.version } + +// ConsentRecordID is the C2 record behind the latest publication, or the zero +// UUID when the candidate never published. +func (publication Publication) ConsentRecordID() uuid.UUID { return publication.consentRecordID } + +// PublishedAt is the time of the latest change that published the card, and +// the zero time when the candidate never published. +func (publication Publication) PublishedAt() time.Time { return publication.publishedAt } + +// State is the effective state: published only while the stored setting is +// published and the C2 record behind it is unrevoked. +func (publication Publication) State() PublicationState { + if publication.state == PublicationPublished && !publication.consentRevoked { + return PublicationPublished + } + return PublicationClosed +} + +// Fields are the fields organizations may read now; empty while closed. +func (publication Publication) Fields() CardFieldSet { + if publication.State() == PublicationClosed { + return CardFieldSet{} + } + return publication.fields +} + +// ClosedReason says why a closed profile is closed. It is empty while the +// profile is published. +func (publication Publication) ClosedReason() PublicationClosedReason { + switch { + case publication.State() == PublicationPublished: + return "" + case publication.version == 0: + return ClosedNeverPublished + case publication.state == PublicationPublished: + return ClosedConsentRevoked + default: + return ClosedByCandidate + } +} + +// PublicationRequest is the complete new publication setting a candidate +// sends. Build it with NewPublicationRequest. +type PublicationRequest struct { + state PublicationState + fields CardFieldSet +} + +// NewPublicationRequest validates the rules that depend on the body alone: a +// published state needs at least one field and a closed state none. +func NewPublicationRequest(state PublicationState, fields []CardField) (PublicationRequest, error) { + const location = "domain.NewPublicationRequest" + set, err := NewCardFieldSet(fields) + if err != nil { + return PublicationRequest{}, err + } + switch state { + case PublicationPublished: + if set.IsEmpty() { + return PublicationRequest{}, invalidVisibilityField(location, cardFieldsPointer, "needs at least one card field to publish") + } + case PublicationClosed: + if !set.IsEmpty() { + return PublicationRequest{}, invalidVisibilityField(location, cardFieldsPointer, "must be empty when the profile is closed") + } + default: + return PublicationRequest{}, invalidVisibilityField(location, "/state", "is not a publication state") + } + return PublicationRequest{state: state, fields: set}, nil +} + +// PublicationChange is the outcome of applying a request. +type PublicationChange struct { + // Publication is the setting after the request. It equals the current one + // when Changed is false. + Publication Publication + // Changed is false when the request left the effective setting as it was: + // nothing is stored, the version stays, and no event is recorded. + Changed bool + // Event is the kind of history record the change needs; empty when + // Changed is false. + Event PrivacyEventKind +} + +// Apply applies a request over the version the client read. activeConsent is +// the identifier of the account's current unrevoked C2 record, or the zero +// UUID when it has none. The order follows the contract: a version above the +// current one is a conflict, an unchanged effective setting is not a change, +// any other change over a stale version is a conflict, and a publication needs +// an active C2. +func (publication Publication) Apply(request PublicationRequest, expectedVersion int64, activeConsent uuid.UUID, at time.Time) (PublicationChange, error) { + const location = "domain.Publication.Apply" + if publication.userID == uuid.Nil || request.state == "" { + return PublicationChange{}, fmt.Errorf("%s - %w: setting or request is not initialized", location, ErrInvalidVisibility) + } + if expectedVersion > publication.version { + return PublicationChange{}, fmt.Errorf("%s - version %d does not exist: %w", location, expectedVersion, ErrVisibilityVersionConflict) + } + effective := publication.State() + if publication.repeats(request, effective) { + return PublicationChange{Publication: publication}, nil + } + if expectedVersion < publication.version { + return PublicationChange{}, fmt.Errorf("%s - expected version is not current: %w", location, ErrVisibilityVersionConflict) + } + + next := publication + next.version = publication.version + 1 + next.consentRevoked = false + if request.state == PublicationClosed { + next.close(at) + return PublicationChange{Publication: next, Changed: true, Event: PrivacyEventPublicationClosed}, nil + } + if activeConsent == uuid.Nil { + return PublicationChange{}, fmt.Errorf("%s - no active C2 record: %w", location, ErrPublicationConsentRequired) + } + next.state = PublicationPublished + next.fields = request.fields + next.consentRecordID = activeConsent + next.publishedAt = at + next.closedAt = time.Time{} + event := PrivacyEventPublicationChanged + if effective == PublicationClosed { + event = PrivacyEventPublicationOpened + } + return PublicationChange{Publication: next, Changed: true, Event: event}, nil +} + +// repeats reports a request that leaves the setting as it is. A closing over +// a stored publication whose C2 was revoked is a real change: the card is +// already closed in effect, but the stored setting still says published, so +// the request normalizes the row to closed and records the closing (and the +// usecase revokes the contact grants it closes). Only a stored closed setting, +// or a profile that never published, makes a closing a repeat. +func (publication Publication) repeats(request PublicationRequest, effective PublicationState) bool { + if request.state == PublicationClosed { + return publication.state == PublicationClosed + } + return effective == PublicationPublished && request.fields.Equal(publication.Fields()) +} + +// close stores the closing. The last published time stays as evidence, and a +// closing never moves back before it, whatever the instance clock says. +func (publication *Publication) close(at time.Time) { + publication.state = PublicationClosed + publication.fields = CardFieldSet{} + publication.closedAt = at + if publication.closedAt.Before(publication.publishedAt) { + publication.closedAt = publication.publishedAt + } +} + +// StoredFields returns the canonical codes of the stored set for the database +// column, whatever the effective state. +func (publication Publication) StoredFields() []string { return publication.fields.Codes() } + +// StoredState returns the stored state for the database column. +func (publication Publication) StoredState() PublicationState { return publication.state } + +// ClosedAt is the time the candidate closed the publication, and the zero +// time while it is published or was never published. +func (publication Publication) ClosedAt() time.Time { return publication.closedAt } + +// LogValue logs only the account identifier, the version, and the effective +// state. +func (publication Publication) LogValue() slog.Value { + return slog.GroupValue( + slog.String("user_id", publication.userID.String()), + slog.Int64("version", publication.version), + slog.String("state", string(publication.State())), + ) +} + +// SearchStatusValue is what a candidate says about searching for work. It is +// a statement, never a consent: it publishes nothing and hides nothing. +type SearchStatusValue string + +const ( + SearchStatusLooking SearchStatusValue = "looking" + SearchStatusNotLooking SearchStatusValue = "not_looking" +) + +// SearchStatusConfirmation is the policy a confirmation of looking is made +// under: the version of the product policy and its confirmation interval. +type SearchStatusConfirmation struct { + policyVersionID PolicyVersionID + interval CalendarDays +} + +// NewSearchStatusConfirmation takes the interval from the search_status +// section of one stored policy version. The interval comes from the versioned +// policy, never from a constant in the code, so the owner changes it by +// publishing a new policy version. +func NewSearchStatusConfirmation(policyVersionID PolicyVersionID, policy SearchStatusPolicy) (SearchStatusConfirmation, error) { + const location = "domain.NewSearchStatusConfirmation" + if policyVersionID.IsZero() { + return SearchStatusConfirmation{}, fmt.Errorf("%s - %w: policy version is empty", location, ErrInvalidVisibility) + } + if err := policy.Validate(); err != nil { + return SearchStatusConfirmation{}, fmt.Errorf("%s - %w: %w", location, ErrInvalidVisibility, err) + } + return SearchStatusConfirmation{policyVersionID: policyVersionID, interval: policy.SearchingConfirmationInterval}, nil +} + +// StoredSearchStatus is a candidate_search_statuses row. +type StoredSearchStatus struct { + UserID uuid.UUID + Status string + ConfirmedAt time.Time + LapsesAt time.Time + PolicyVersionID PolicyVersionID + Version int64 +} + +// SearchStatus is the search status of one candidate. A candidate who never +// set it is not looking at version 0. The stored status is what the candidate +// last said; the status that holds now is computed against the clock, so a +// lapse is never written and cannot make anyone more visible. +type SearchStatus struct { + userID uuid.UUID + stored SearchStatusValue + confirmedAt time.Time + lapsesAt time.Time + policyVersionID PolicyVersionID + version int64 +} + +// NewSearchStatus returns the status of a candidate who never set it. +func NewSearchStatus(userID uuid.UUID) (SearchStatus, error) { + if userID == uuid.Nil { + return SearchStatus{}, fmt.Errorf("domain.NewSearchStatus - %w: user ID is empty", ErrInvalidVisibility) + } + return SearchStatus{userID: userID, stored: SearchStatusNotLooking}, nil +} + +// RestoreSearchStatus rebuilds a status from a stored row and rejects a row +// that breaks the invariants the database also enforces. +func RestoreSearchStatus(stored StoredSearchStatus) (SearchStatus, error) { + const location = "domain.RestoreSearchStatus" + if stored.UserID == uuid.Nil || stored.Version < firstStoredVersion { + return SearchStatus{}, fmt.Errorf("%s - %w: identifier or version is invalid", location, ErrInvalidVisibility) + } + status := SearchStatusValue(stored.Status) + switch { + case status == SearchStatusLooking && !stored.ConfirmedAt.IsZero() && stored.LapsesAt.After(stored.ConfirmedAt) && !stored.PolicyVersionID.IsZero(): + case status == SearchStatusNotLooking && stored.ConfirmedAt.IsZero() && stored.LapsesAt.IsZero() && stored.PolicyVersionID.IsZero(): + default: + return SearchStatus{}, fmt.Errorf("%s - %w: status, confirmation, and policy version disagree", location, ErrInvalidVisibility) + } + return SearchStatus{ + userID: stored.UserID, stored: status, confirmedAt: stored.ConfirmedAt, lapsesAt: stored.LapsesAt, + policyVersionID: stored.PolicyVersionID, version: stored.Version, + }, nil +} + +func (status SearchStatus) UserID() uuid.UUID { return status.userID } + +// Version is 0 for a candidate who never set the status. +func (status SearchStatus) Version() int64 { return status.version } + +// StoredValue is the status the candidate last set. +func (status SearchStatus) StoredValue() SearchStatusValue { return status.stored } + +// ConfirmedAt is the latest confirmation of looking, or the zero time. +func (status SearchStatus) ConfirmedAt() time.Time { return status.confirmedAt } + +// LapsesAt is when the confirmed status lapses, or the zero time. It was fixed +// at the confirmation and no later policy change moves it. +func (status SearchStatus) LapsesAt() time.Time { return status.lapsesAt } + +// PolicyVersionID is the policy version the lapse time was computed under, or +// the zero value when the candidate is not looking. +func (status SearchStatus) PolicyVersionID() PolicyVersionID { return status.policyVersionID } + +// Effective is the status that holds at now: looking only while the +// confirmation has not lapsed. A lapse falls to the non-public status. +func (status SearchStatus) Effective(now time.Time) SearchStatusValue { + if status.stored == SearchStatusLooking && now.Before(status.lapsesAt) { + return SearchStatusLooking + } + return SearchStatusNotLooking +} + +// Lapsed reports a status the candidate set to looking and did not confirm in +// time. +func (status SearchStatus) Lapsed(now time.Time) bool { + return status.stored == SearchStatusLooking && !now.Before(status.lapsesAt) +} + +// SearchStatusChange is the outcome of applying a status request. +type SearchStatusChange struct { + Status SearchStatus + // Changed is false when the request left the stored status as it was. + Changed bool + // Event is the history record the change needs; empty when unchanged. + Event PrivacyEventKind +} + +// Apply sets or confirms the status over the version the client read. The +// confirmation is only used for looking and fixes the lapse time from the +// policy at the moment of the confirmation. The request never touches the +// publication or the hidden organizations: this type knows neither. +// +// Looking always changes the stored confirmation, so a stale version is a +// conflict even for a repeat. Not looking over a stored not looking is not a +// change. +func (status SearchStatus) Apply(value SearchStatusValue, expectedVersion int64, confirmation SearchStatusConfirmation, at time.Time) (SearchStatusChange, error) { + const location = "domain.SearchStatus.Apply" + if status.userID == uuid.Nil { + return SearchStatusChange{}, fmt.Errorf("%s - %w: status is not initialized", location, ErrInvalidVisibility) + } + if value != SearchStatusLooking && value != SearchStatusNotLooking { + return SearchStatusChange{}, invalidVisibilityField(location, "/value", "is not a search status") + } + if expectedVersion > status.version { + return SearchStatusChange{}, fmt.Errorf("%s - version %d does not exist: %w", location, expectedVersion, ErrVisibilityVersionConflict) + } + if value == SearchStatusNotLooking && status.stored == SearchStatusNotLooking { + return SearchStatusChange{Status: status}, nil + } + if expectedVersion < status.version { + return SearchStatusChange{}, fmt.Errorf("%s - expected version is not current: %w", location, ErrVisibilityVersionConflict) + } + + next := SearchStatus{userID: status.userID, stored: value, version: status.version + 1} + event := PrivacyEventSearchStatusCleared + if value == SearchStatusLooking { + if confirmation.policyVersionID.IsZero() || confirmation.interval <= 0 { + return SearchStatusChange{}, fmt.Errorf("%s - %w: confirmation policy is missing", location, ErrInvalidVisibility) + } + next.confirmedAt = at + next.lapsesAt = at.Add(confirmation.interval.Duration()) + next.policyVersionID = confirmation.policyVersionID + event = PrivacyEventSearchStatusConfirmed + } + return SearchStatusChange{Status: next, Changed: true, Event: event}, nil +} + +// LogValue logs only the account identifier, the version, and the stored +// value. +func (status SearchStatus) LogValue() slog.Value { + return slog.GroupValue( + slog.String("user_id", status.userID.String()), + slog.Int64("version", status.version), + slog.String("stored", string(status.stored)), + ) +} + +// HiddenOrganization is the record of a candidate hiding the profile from one +// organization. It belongs to the candidate: no organization reads it. +type HiddenOrganization struct { + userID uuid.UUID + organizationID uuid.UUID + hiddenAt time.Time +} + +// NewHiddenOrganization builds the record of a hiding. The pair is unique in +// the database, so hiding twice is the same record. +func NewHiddenOrganization(userID, organizationID uuid.UUID, at time.Time) (HiddenOrganization, error) { + if userID == uuid.Nil || organizationID == uuid.Nil || at.IsZero() { + return HiddenOrganization{}, fmt.Errorf("domain.NewHiddenOrganization - %w: identifiers or time are missing", ErrInvalidVisibility) + } + return HiddenOrganization{userID: userID, organizationID: organizationID, hiddenAt: at}, nil +} + +func (hidden HiddenOrganization) UserID() uuid.UUID { return hidden.userID } +func (hidden HiddenOrganization) OrganizationID() uuid.UUID { return hidden.organizationID } +func (hidden HiddenOrganization) HiddenAt() time.Time { return hidden.hiddenAt } + +// LogValue logs only the identifiers. +func (hidden HiddenOrganization) LogValue() slog.Value { + return slog.GroupValue( + slog.String("user_id", hidden.userID.String()), + slog.String("organization_id", hidden.organizationID.String()), + ) +} + +// PrivacyEventKind is a kind of change that the settings history records. +type PrivacyEventKind string + +const ( + PrivacyEventPublicationOpened PrivacyEventKind = "publication_opened" + PrivacyEventPublicationChanged PrivacyEventKind = "publication_changed" + PrivacyEventPublicationClosed PrivacyEventKind = "publication_closed" + PrivacyEventSearchStatusConfirmed PrivacyEventKind = "search_status_confirmed" + PrivacyEventSearchStatusCleared PrivacyEventKind = "search_status_cleared" + PrivacyEventOrganizationHidden PrivacyEventKind = "organization_hidden" + PrivacyEventOrganizationUnhidden PrivacyEventKind = "organization_unhidden" +) + +// Valid reports whether the kind is one the history stores. +func (kind PrivacyEventKind) Valid() bool { + switch kind { + case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged, PrivacyEventPublicationClosed, + PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared, + PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden: + return true + default: + return false + } +} + +// PrivacyEvent is one record of the settings history, in the shape the +// candidate_privacy_events table accepts. +type PrivacyEvent struct { + id uuid.UUID + userID uuid.UUID + kind PrivacyEventKind + occurredAt time.Time + fields CardFieldSet + consentRecordID uuid.UUID + organizationID uuid.UUID +} + +// NewPublicationEvent records a publication change. A publication carries the +// published fields and the C2 record behind them; a closing carries neither. +func NewPublicationEvent(change PublicationChange, at time.Time) (PrivacyEvent, error) { + const location = "domain.NewPublicationEvent" + if !change.Changed { + return PrivacyEvent{}, fmt.Errorf("%s - %w: the change is empty", location, ErrInvalidVisibility) + } + event := PrivacyEvent{userID: change.Publication.userID, kind: change.Event, occurredAt: at} + switch change.Event { + case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged: + event.fields = change.Publication.fields + event.consentRecordID = change.Publication.consentRecordID + case PrivacyEventPublicationClosed: + case PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared, PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden: + return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not a publication event", location, ErrInvalidVisibility, change.Event) + default: + return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not a publication event", location, ErrInvalidVisibility, change.Event) + } + return completeEvent(location, event) +} + +// NewSearchStatusEvent records a change of the search status. +func NewSearchStatusEvent(change SearchStatusChange, at time.Time) (PrivacyEvent, error) { + const location = "domain.NewSearchStatusEvent" + if !change.Changed || (change.Event != PrivacyEventSearchStatusConfirmed && change.Event != PrivacyEventSearchStatusCleared) { + return PrivacyEvent{}, fmt.Errorf("%s - %w: the change is not a status change", location, ErrInvalidVisibility) + } + return completeEvent(location, PrivacyEvent{userID: change.Status.userID, kind: change.Event, occurredAt: at}) +} + +// NewOrganizationEvent records a hiding or the lifting of one. Only the +// identifier is kept; the candidate's read resolves the current name. +func NewOrganizationEvent(kind PrivacyEventKind, userID, organizationID uuid.UUID, at time.Time) (PrivacyEvent, error) { + const location = "domain.NewOrganizationEvent" + if kind != PrivacyEventOrganizationHidden && kind != PrivacyEventOrganizationUnhidden { + return PrivacyEvent{}, fmt.Errorf("%s - %w: kind %q is not an organization event", location, ErrInvalidVisibility, kind) + } + if organizationID == uuid.Nil { + return PrivacyEvent{}, fmt.Errorf("%s - %w: organization is missing", location, ErrInvalidVisibility) + } + return completeEvent(location, PrivacyEvent{ + userID: userID, kind: kind, occurredAt: at, organizationID: organizationID, + }) +} + +func completeEvent(location string, event PrivacyEvent) (PrivacyEvent, error) { + if event.userID == uuid.Nil || event.occurredAt.IsZero() { + return PrivacyEvent{}, fmt.Errorf("%s - %w: account or time is missing", location, ErrInvalidVisibility) + } + id, err := uuid.NewV7() + if err != nil { + return PrivacyEvent{}, fmt.Errorf("%s - generate ID: %w", location, err) + } + event.id = id + return event, nil +} + +func (event PrivacyEvent) ID() uuid.UUID { return event.id } +func (event PrivacyEvent) UserID() uuid.UUID { return event.userID } +func (event PrivacyEvent) Kind() PrivacyEventKind { return event.kind } +func (event PrivacyEvent) OccurredAt() time.Time { return event.occurredAt } +func (event PrivacyEvent) Fields() CardFieldSet { return event.fields } +func (event PrivacyEvent) ConsentRecordID() uuid.UUID { return event.consentRecordID } +func (event PrivacyEvent) OrganizationID() uuid.UUID { return event.organizationID } + +// HasFieldSet reports whether the event stores a field set: every publication +// event does, an empty one for a closing, and no other kind does. +func (event PrivacyEvent) HasFieldSet() bool { + switch event.kind { + case PrivacyEventPublicationOpened, PrivacyEventPublicationChanged, PrivacyEventPublicationClosed: + return true + case PrivacyEventSearchStatusConfirmed, PrivacyEventSearchStatusCleared, PrivacyEventOrganizationHidden, PrivacyEventOrganizationUnhidden: + return false + default: + return false + } +} + +// LogValue logs only identifiers and the kind. +func (event PrivacyEvent) LogValue() slog.Value { + return slog.GroupValue( + slog.String("id", event.id.String()), + slog.String("kind", string(event.kind)), + ) +} + +// Rules for the content of an anonymous card (TASK-089 builds it; these are +// the hard requirements of this task): +// - Only confirmed profile values ever reach the card. A suggestion that +// the candidate did not confirm (status extracted) and an unknown value +// never do. +// - A free text value (a stack tag, a soft skill, a location) is dropped +// when it looks like a contact, because the card must never carry a +// contact outside the contact grant (C4). CardTextLooksLikeContact is the +// check the builder must apply to every free text before it enters the +// card; it errs on the side of dropping. +// - Quasi-identifiers (a rare combination of location, stack, and +// experience) and the generalization of rare features are an acceptance +// criterion of TASK-089, not decided here. + +const ( + // cardWordStart and cardWordEnd are Unicode word boundaries. Go's \b is + // ASCII-only, so it cannot see the edge of a Cyrillic or other non-ASCII + // label. + cardWordStart = `(?:^|[^\p{L}\p{N}_])` + cardWordEnd = `(?:$|[^\p{L}\p{N}_])` + // cardDomainEnd also treats a hyphen as part of the label, so pro.company + // does not match the ending pro. + cardDomainEnd = `(?:$|[^\p{L}\p{N}-])` + // cardContactTLDs are the domain endings that make a dotted token a + // domain. The list is deliberately wide and errs on the side of dropping: + // Socket.io is dropped with it. "net" is not in it so that ASP.NET stays a + // stack tag; a lowercase name.net is caught separately. + cardContactTLDs = `com|ru|org|io|me|dev|app|xyz|info|su|рф|ua|by|kz|co|ai|de|uk|tv|ly|gl|dog|site|online|tech|fm|cc|gg|link|page|store|shop|blog|cloud|top|pro|biz|us|eu|fr|nl|pl|cz|moscow|бел|укр|рус|онлайн|сайт` + // cardContactWords are words that introduce or disguise a contact, with + // or without an @: messengers, contact nouns, and the spelled-out parts of + // an address. They match as whole words only. + cardContactWords = `at|dot|собака|точка|telegram|tg|whatsapp|viber|skype|телеграм|телега|вотсап|ватсап|вайбер|скайп|email|mail|e-mail|phone|tel|почта|телефон|контакт|contact` + // minCardPhoneDigits is the number of digits in one group from which a + // text is treated as a phone number. Seven is the shortest local number. + minCardPhoneDigits = 7 +) + +var ( + cardContactEmail = regexp.MustCompile(`[^\s@]+@[^\s@]+`) + cardContactHandle = regexp.MustCompile(`@\s*[\p{L}\p{N}_]{3,}`) + cardContactURL = regexp.MustCompile(`(?:https?://|tg://|www\.|\bt\.me/)|[\p{L}\p{N}-]+\.(?:` + cardContactTLDs + `)` + cardDomainEnd) + cardContactNet = regexp.MustCompile(`[\p{Ll}\p{N}-]+\.net` + cardDomainEnd) + cardContactWord = regexp.MustCompile(cardWordStart + `(?:` + cardContactWords + `)` + cardWordEnd) + // cardPhoneGroup is a run of digits separated only by spaces, dashes, + // dots, and parentheses, so "Python 3.12, Django 4.2" are separate groups. + cardPhoneGroup = regexp.MustCompile(`[\p{Nd}+(][\p{Nd}\s().\-]*`) +) + +// CardTextLooksLikeContact reports whether a free text value of the profile +// looks like a contact: an email address, a phone number, a URL or domain +// (including an internationalized one), a Telegram link or an @handle (also +// spelled "@ name"), an obfuscated address ("a [at] b dot com"), or a +// messenger or contact word ("tg: name", "почта"). The text is normalized +// with NFKC first, so fullwidth and compatibility forms of @, +, and digits +// count, and every Unicode decimal digit counts toward a phone number. A card +// builder drops such a value instead of publishing it. The check errs on the +// side of dropping; it is the barrier for free text until TASK-089 replaces +// free text by a closed taxonomy, which closes the residual risk. +func CardTextLooksLikeContact(text string) bool { + normalized := norm.NFKC.String(text) + lowered := strings.ToLower(normalized) + if cardContactEmail.MatchString(lowered) || cardContactHandle.MatchString(lowered) || + cardContactURL.MatchString(lowered) || cardContactNet.MatchString(normalized) || cardContactWord.MatchString(lowered) { + return true + } + for _, group := range cardPhoneGroup.FindAllString(lowered, -1) { + digits := 0 + for _, character := range group { + if unicode.IsDigit(character) { + digits++ + } + } + if digits >= minCardPhoneDigits { + return true + } + } + return false +} diff --git a/backend/internal/domain/visibility_test.go b/backend/internal/domain/visibility_test.go new file mode 100644 index 0000000..31a6ffa --- /dev/null +++ b/backend/internal/domain/visibility_test.go @@ -0,0 +1,475 @@ +package domain + +import ( + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +var visibilityNow = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + +func mustCardFields(t *testing.T, fields ...CardField) CardFieldSet { + t.Helper() + set, err := NewCardFieldSet(fields) + if err != nil { + t.Fatalf("NewCardFieldSet(%v) error = %v", fields, err) + } + return set +} + +func mustPublicationRequest(t *testing.T, state PublicationState, fields ...CardField) PublicationRequest { + t.Helper() + request, err := NewPublicationRequest(state, fields) + if err != nil { + t.Fatalf("NewPublicationRequest(%s, %v) error = %v", state, fields, err) + } + return request +} + +func newClosedPublication(t *testing.T) Publication { + t.Helper() + publication, err := NewPublication(uuid.New()) + if err != nil { + t.Fatalf("NewPublication() error = %v", err) + } + return publication +} + +func publish(t *testing.T, publication Publication, expectedVersion int64, consent uuid.UUID, at time.Time, fields ...CardField) Publication { + t.Helper() + change, err := publication.Apply(mustPublicationRequest(t, PublicationPublished, fields...), expectedVersion, consent, at) + if err != nil || !change.Changed { + t.Fatalf("Apply(publish) = %+v, %v, want a change", change, err) + } + return change.Publication +} + +func TestNewCardFieldSetIsCanonicalAndClosed(t *testing.T) { + set := mustCardFields(t, CardFieldStack, CardFieldCategories) + if got := strings.Join(set.Codes(), ","); got != "categories,stack" { + t.Fatalf("Codes() = %q, want ascending order whatever the input order", got) + } + if empty := mustCardFields(t); !empty.IsEmpty() || empty.Codes() == nil { + t.Fatal("an empty set must be empty and encode as an empty, non-nil array") + } + for _, code := range []string{"full_name", "email", "phone", "telegram", "salary_minimum", "contacts", ""} { + if _, err := NewCardFieldSet([]CardField{CardField(code)}); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewCardFieldSet(%q) error = %v, want a refusal: the card never carries it", code, err) + } + } + if _, err := NewCardFieldSet([]CardField{CardFieldStack, CardFieldStack}); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewCardFieldSet(repeated) error = %v, want a refusal", err) + } + var fieldError *VisibilityFieldError + if _, err := NewCardFieldSet([]CardField{CardFieldStack, "contacts"}); !errors.As(err, &fieldError) || fieldError.Pointer != "/fields/1" || strings.Contains(err.Error(), "contacts") { + t.Errorf("an unknown field error = %v, want the pointer without the submitted value", err) + } + for _, field := range CardFields() { + if !field.Valid() { + t.Errorf("CardFields() lists %q, which is not valid", field) + } + } +} + +func TestNewPublicationRequestChecksTheBodyAlone(t *testing.T) { + for _, test := range []struct { + name string + state PublicationState + fields []CardField + ok bool + }{ + {"published with a field", PublicationPublished, []CardField{CardFieldStack}, true}, + {"closed with no field", PublicationClosed, nil, true}, + {"published with no field", PublicationPublished, nil, false}, + {"closed with a field", PublicationClosed, []CardField{CardFieldStack}, false}, + {"unknown state", "hidden", nil, false}, + } { + t.Run(test.name, func(t *testing.T) { + _, err := NewPublicationRequest(test.state, test.fields) + if (err == nil) != test.ok { + t.Fatalf("NewPublicationRequest() error = %v, want ok %v", err, test.ok) + } + if err != nil && !errors.Is(err, ErrInvalidVisibility) { + t.Fatalf("error = %v, want ErrInvalidVisibility", err) + } + }) + } +} + +func TestAProfileIsClosedByDefault(t *testing.T) { + publication := newClosedPublication(t) + if publication.State() != PublicationClosed || publication.ClosedReason() != ClosedNeverPublished || + publication.Version() != 0 || !publication.Fields().IsEmpty() || publication.ConsentRecordID() != uuid.Nil { + t.Fatalf("a new publication = %v %v v%d, want closed, never published, version 0, no consent", publication.State(), publication.ClosedReason(), publication.Version()) + } + // Closing a profile that never opened changes nothing and stores no row. + change, err := publication.Apply(mustPublicationRequest(t, PublicationClosed), 0, uuid.Nil, visibilityNow) + if err != nil || change.Changed || change.Publication.Version() != 0 { + t.Fatalf("Apply(close of a never published profile) = %+v, %v, want no change", change, err) + } +} + +func TestPublishingNeedsAnActiveC2AndNamesNoConsent(t *testing.T) { + publication := newClosedPublication(t) + request := mustPublicationRequest(t, PublicationPublished, CardFieldCategories) + if _, err := publication.Apply(request, 0, uuid.Nil, visibilityNow); !errors.Is(err, ErrPublicationConsentRequired) { + t.Fatalf("Apply(without C2) error = %v, want ErrPublicationConsentRequired", err) + } + consent := uuid.New() + change, err := publication.Apply(request, 0, consent, visibilityNow) + if err != nil || !change.Changed || change.Event != PrivacyEventPublicationOpened { + t.Fatalf("Apply(publish) = %+v, %v, want an opened publication", change, err) + } + published := change.Publication + if published.State() != PublicationPublished || published.ClosedReason() != "" || published.Version() != 1 || + published.ConsentRecordID() != consent || !published.PublishedAt().Equal(visibilityNow) || + !published.Fields().Equal(mustCardFields(t, CardFieldCategories)) { + t.Fatalf("published = %v v%d, want the new record bound to the C2 record", published.State(), published.Version()) + } + // The input did not change. + if publication.State() != PublicationClosed || publication.Version() != 0 { + t.Fatal("Apply changed its receiver") + } +} + +func TestPublicationOrderOfChecks(t *testing.T) { + consent := uuid.New() + published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack, CardFieldCategories) + same := mustPublicationRequest(t, PublicationPublished, CardFieldCategories, CardFieldStack) + other := mustPublicationRequest(t, PublicationPublished, CardFieldCategories) + + // A version above the current one never existed, even for an unchanged body. + if _, err := published.Apply(same, 5, consent, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) { + t.Fatalf("Apply(future version) error = %v, want a version conflict", err) + } + // An unchanged body is a success over a stale version, so a lost response can be retried. + published = publish(t, published, 1, consent, visibilityNow.Add(time.Hour), CardFieldCategories) + if change, err := published.Apply(other, 1, uuid.Nil, visibilityNow); err != nil || change.Changed || change.Publication.Version() != 2 { + t.Fatalf("Apply(unchanged, stale) = %+v, %v, want no change at version 2", change, err) + } + // Any other change over a stale version is a conflict, also a closing. + if _, err := published.Apply(same, 1, consent, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) { + t.Fatalf("Apply(change, stale) error = %v, want a version conflict", err) + } + // A stale version is a conflict before the missing consent is reported. + if _, err := published.Apply(same, 1, uuid.Nil, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) { + t.Fatalf("Apply(change, stale, no consent) error = %v, want the version conflict first", err) + } + change, err := published.Apply(mustPublicationRequest(t, PublicationClosed), 2, uuid.Nil, visibilityNow.Add(2*time.Hour)) + if err != nil || !change.Changed || change.Event != PrivacyEventPublicationClosed { + t.Fatalf("Apply(close) = %+v, %v, want a closing that needs no consent", change, err) + } + closed := change.Publication + if closed.State() != PublicationClosed || closed.ClosedReason() != ClosedByCandidate || !closed.Fields().IsEmpty() || closed.Version() != 3 || + !closed.PublishedAt().Equal(visibilityNow.Add(time.Hour)) || !closed.ClosedAt().Equal(visibilityNow.Add(2*time.Hour)) { + t.Fatalf("closed = %v %v v%d, want closed by the candidate with the last published time kept", closed.State(), closed.ClosedReason(), closed.Version()) + } +} + +func TestPublishedFieldsChangeWithTheirOwnEvent(t *testing.T) { + consent := uuid.New() + published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack) + change, err := published.Apply(mustPublicationRequest(t, PublicationPublished, CardFieldStack, CardFieldLocation), 1, consent, visibilityNow.Add(time.Minute)) + if err != nil || !change.Changed || change.Event != PrivacyEventPublicationChanged || change.Publication.Version() != 2 { + t.Fatalf("Apply(more fields) = %+v, %v, want a changed publication at version 2", change, err) + } + event, err := NewPublicationEvent(change, visibilityNow.Add(time.Minute)) + if err != nil || event.Kind() != PrivacyEventPublicationChanged || !event.HasFieldSet() || event.ConsentRecordID() != consent || + !event.Fields().Equal(mustCardFields(t, CardFieldLocation, CardFieldStack)) { + t.Fatalf("NewPublicationEvent() = %v, %v, want the fields and the C2 record behind them", event, err) + } +} + +// A revoked C2 closes the card without any write, and a later C2 grant never +// reopens it: only an explicit publication under the new record does. +func TestARevokedConsentClosesAndNeverReopensByItself(t *testing.T) { + consent := uuid.New() + published := publish(t, newClosedPublication(t), 0, consent, visibilityNow, CardFieldStack) + stored := StoredPublication{ + UserID: published.UserID(), State: string(PublicationPublished), Fields: published.StoredFields(), ConsentRecordID: consent, + PublishedAt: visibilityNow, Version: 1, ConsentRevoked: true, + } + revoked, err := RestorePublication(stored) + if err != nil { + t.Fatalf("RestorePublication() error = %v", err) + } + if revoked.State() != PublicationClosed || revoked.ClosedReason() != ClosedConsentRevoked || !revoked.Fields().IsEmpty() { + t.Fatalf("a revoked C2 left the card %v (%v) with fields %v, want closed", revoked.State(), revoked.ClosedReason(), revoked.Fields().Codes()) + } + // The same body is not "unchanged": the card is closed now, so it is a new publication. + newConsent := uuid.New() + change, err := revoked.Apply(mustPublicationRequest(t, PublicationPublished, CardFieldStack), 1, newConsent, visibilityNow.Add(time.Hour)) + if err != nil || !change.Changed || change.Event != PrivacyEventPublicationOpened || change.Publication.ConsentRecordID() != newConsent || + change.Publication.State() != PublicationPublished { + t.Fatalf("Apply(publish again) = %+v, %v, want an opened publication under the new record", change, err) + } + // Closing a card that the revocation closed in effect is a real change: + // the stored row is normalized to closed and the closing is recorded. + closing, err := revoked.Apply(mustPublicationRequest(t, PublicationClosed), 1, uuid.Nil, visibilityNow.Add(2*time.Hour)) + if err != nil || !closing.Changed || closing.Event != PrivacyEventPublicationClosed || closing.Publication.StoredState() != PublicationClosed || + closing.Publication.ClosedReason() != ClosedByCandidate || closing.Publication.Version() != 2 { + t.Fatalf("Apply(close over a revoked C2) = %+v, %v, want a recorded closing at version 2", closing, err) + } + // A second closing is the repeat of the stored closing. + if again, err := closing.Publication.Apply(mustPublicationRequest(t, PublicationClosed), 1, uuid.Nil, visibilityNow); err != nil || again.Changed { + t.Fatalf("Apply(close again) = %+v, %v, want no change", again, err) + } +} + +func TestRestorePublicationRejectsRowsThatBreakTheInvariants(t *testing.T) { + user, consent := uuid.New(), uuid.New() + valid := StoredPublication{UserID: user, State: "published", Fields: []string{"categories", "stack"}, ConsentRecordID: consent, PublishedAt: visibilityNow, Version: 1} + if _, err := RestorePublication(valid); err != nil { + t.Fatalf("RestorePublication(valid) error = %v", err) + } + for name, mutate := range map[string]func(*StoredPublication){ + "published without fields": func(s *StoredPublication) { s.Fields = nil }, + "closed with fields": func(s *StoredPublication) { s.State = "closed"; s.ClosedAt = visibilityNow }, + "closed without a close time": func(s *StoredPublication) { s.State = "closed"; s.Fields = nil }, + "published with a close time": func(s *StoredPublication) { s.ClosedAt = visibilityNow }, + "fields out of order": func(s *StoredPublication) { s.Fields = []string{"stack", "categories"} }, + "a contact as a field": func(s *StoredPublication) { s.Fields = []string{"phone"} }, + "unknown state": func(s *StoredPublication) { s.State = "draft" }, + "no consent record": func(s *StoredPublication) { s.ConsentRecordID = uuid.Nil }, + "version zero": func(s *StoredPublication) { s.Version = 0 }, + } { + t.Run(name, func(t *testing.T) { + stored := valid + mutate(&stored) + if _, err := RestorePublication(stored); !errors.Is(err, ErrInvalidVisibility) { + t.Fatalf("RestorePublication() error = %v, want ErrInvalidVisibility", err) + } + }) + } +} + +func demoSearchConfirmation(t *testing.T) SearchStatusConfirmation { + t.Helper() + id, err := NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + confirmation, err := NewSearchStatusConfirmation(id, DemoProductPolicyV1().SearchStatus) + if err != nil { + t.Fatalf("NewSearchStatusConfirmation() error = %v", err) + } + return confirmation +} + +func newSearchStatus(t *testing.T) SearchStatus { + t.Helper() + status, err := NewSearchStatus(uuid.New()) + if err != nil { + t.Fatalf("NewSearchStatus() error = %v", err) + } + return status +} + +func TestSearchStatusLapsesAfterThePolicyIntervalToTheNonPublicState(t *testing.T) { + confirmation := demoSearchConfirmation(t) + initial := newSearchStatus(t) + if initial.Effective(visibilityNow) != SearchStatusNotLooking || initial.Version() != 0 || initial.Lapsed(visibilityNow) { + t.Fatal("a new account must not be looking at version 0") + } + change, err := initial.Apply(SearchStatusLooking, 0, confirmation, visibilityNow) + if err != nil || !change.Changed || change.Event != PrivacyEventSearchStatusConfirmed { + t.Fatalf("Apply(looking) = %+v, %v, want a confirmation", change, err) + } + looking := change.Status + // The interval is the 30 days of the demo policy, read from the versioned document. + if want := visibilityNow.Add(30 * 24 * time.Hour); !looking.LapsesAt().Equal(want) || !looking.ConfirmedAt().Equal(visibilityNow) || + looking.PolicyVersionID() != confirmation.policyVersionID || looking.Version() != 1 { + t.Fatalf("looking = confirmed %v lapses %v v%d, want 30 days under the policy version", looking.ConfirmedAt(), looking.LapsesAt(), looking.Version()) + } + last := looking.LapsesAt().Add(-time.Nanosecond) + if looking.Effective(last) != SearchStatusLooking || looking.Lapsed(last) { + t.Fatal("the status must hold until the lapse time") + } + for _, at := range []time.Time{looking.LapsesAt(), looking.LapsesAt().Add(365 * 24 * time.Hour)} { + if looking.Effective(at) != SearchStatusNotLooking || !looking.Lapsed(at) { + t.Fatalf("at %v the status = %v lapsed %v, want not_looking and lapsed: a lapse only narrows", at, looking.Effective(at), looking.Lapsed(at)) + } + } + // A lapse is not a stored change: the stored status is still what the candidate said. + if looking.StoredValue() != SearchStatusLooking { + t.Fatal("the lapse rewrote the stored status") + } + // The candidate confirms again after the lapse with the current version. + later := looking.LapsesAt().Add(time.Hour) + again, err := looking.Apply(SearchStatusLooking, 1, confirmation, later) + if err != nil || !again.Changed || again.Status.Version() != 2 || again.Status.Effective(later) != SearchStatusLooking || !again.Status.ConfirmedAt().Equal(later) { + t.Fatalf("Apply(confirm after the lapse) = %+v, %v, want a new confirmation at version 2", again, err) + } +} + +func TestSearchStatusVersionRules(t *testing.T) { + confirmation := demoSearchConfirmation(t) + initial := newSearchStatus(t) + // Not looking over a status that was never set stores nothing. + if change, err := initial.Apply(SearchStatusNotLooking, 0, SearchStatusConfirmation{}, visibilityNow); err != nil || change.Changed { + t.Fatalf("Apply(not_looking, never set) = %+v, %v, want no change", change, err) + } + if _, err := initial.Apply(SearchStatusLooking, 4, confirmation, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) { + t.Fatalf("Apply(future version) error = %v, want a version conflict", err) + } + if _, err := initial.Apply("searching", 0, confirmation, visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Fatalf("Apply(unknown value) error = %v, want ErrInvalidVisibility", err) + } + if _, err := initial.Apply(SearchStatusLooking, 0, SearchStatusConfirmation{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Fatalf("Apply(looking without a policy) error = %v, want ErrInvalidVisibility", err) + } + looking := mustApplySearch(t, initial, SearchStatusLooking, 0, confirmation, visibilityNow) + // Looking again over a stale version is a conflict: a repeat of a confirmation changes the stored time. + if _, err := looking.Apply(SearchStatusLooking, 0, confirmation, visibilityNow); !errors.Is(err, ErrVisibilityVersionConflict) { + t.Fatalf("Apply(looking, stale) error = %v, want a version conflict", err) + } + cleared := mustApplySearch(t, looking, SearchStatusNotLooking, 1, SearchStatusConfirmation{}, visibilityNow.Add(time.Hour)) + if cleared.StoredValue() != SearchStatusNotLooking || !cleared.ConfirmedAt().IsZero() || !cleared.LapsesAt().IsZero() || !cleared.PolicyVersionID().IsZero() || cleared.Lapsed(visibilityNow.Add(100*24*time.Hour)) { + t.Fatal("not_looking must carry no confirmation, and a cleared status is never lapsed") + } + // Clearing twice is not a change, even with a stale version. + if change, err := cleared.Apply(SearchStatusNotLooking, 1, SearchStatusConfirmation{}, visibilityNow); err != nil || change.Changed { + t.Fatalf("Apply(not_looking, stale, unchanged) = %+v, %v, want no change", change, err) + } +} + +func mustApplySearch(t *testing.T, status SearchStatus, value SearchStatusValue, expected int64, confirmation SearchStatusConfirmation, at time.Time) SearchStatus { + t.Helper() + change, err := status.Apply(value, expected, confirmation, at) + if err != nil || !change.Changed { + t.Fatalf("Apply(%s) = %+v, %v, want a change", value, change, err) + } + return change.Status +} + +func TestSearchStatusConfirmationComesFromAValidVersionedPolicy(t *testing.T) { + id, err := NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + if _, err := NewSearchStatusConfirmation(PolicyVersionID{}, SearchStatusPolicy{SearchingConfirmationInterval: 30}); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("a confirmation without a policy version error = %v, want ErrInvalidVisibility", err) + } + for _, days := range []CalendarDays{0, -1, maxSearchingConfirmationInterval + 1} { + if _, err := NewSearchStatusConfirmation(id, SearchStatusPolicy{SearchingConfirmationInterval: days}); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("a confirmation of %d days error = %v, want a refusal", days, err) + } + } + // An owner-published interval is used as is. + confirmation, err := NewSearchStatusConfirmation(id, SearchStatusPolicy{SearchingConfirmationInterval: 14}) + if err != nil { + t.Fatalf("NewSearchStatusConfirmation(14) error = %v", err) + } + looking := mustApplySearch(t, newSearchStatus(t), SearchStatusLooking, 0, confirmation, visibilityNow) + if want := visibilityNow.Add(14 * 24 * time.Hour); !looking.LapsesAt().Equal(want) { + t.Fatalf("lapses at %v, want %v", looking.LapsesAt(), want) + } +} + +func TestRestoreSearchStatusRejectsRowsThatBreakTheInvariants(t *testing.T) { + policy, err := NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + user := uuid.New() + valid := StoredSearchStatus{UserID: user, Status: "looking", ConfirmedAt: visibilityNow, LapsesAt: visibilityNow.Add(time.Hour), PolicyVersionID: policy, Version: 1} + if _, err := RestoreSearchStatus(valid); err != nil { + t.Fatalf("RestoreSearchStatus(valid) error = %v", err) + } + if _, err := RestoreSearchStatus(StoredSearchStatus{UserID: user, Status: "not_looking", Version: 2}); err != nil { + t.Fatalf("RestoreSearchStatus(not_looking) error = %v", err) + } + for name, mutate := range map[string]func(*StoredSearchStatus){ + "looking without a confirmation": func(s *StoredSearchStatus) { s.ConfirmedAt = time.Time{} }, + "lapse not after the confirm": func(s *StoredSearchStatus) { s.LapsesAt = s.ConfirmedAt }, + "looking without a policy": func(s *StoredSearchStatus) { s.PolicyVersionID = PolicyVersionID{} }, + "not looking with a confirmation": func(s *StoredSearchStatus) { s.Status = "not_looking" }, + "unknown status": func(s *StoredSearchStatus) { s.Status = "open" }, + "version zero": func(s *StoredSearchStatus) { s.Version = 0 }, + } { + t.Run(name, func(t *testing.T) { + stored := valid + mutate(&stored) + if _, err := RestoreSearchStatus(stored); !errors.Is(err, ErrInvalidVisibility) { + t.Fatalf("RestoreSearchStatus() error = %v, want ErrInvalidVisibility", err) + } + }) + } +} + +func TestHiddenOrganizationAndEventsNeedTheirIdentifiers(t *testing.T) { + user, organization := uuid.New(), uuid.New() + hidden, err := NewHiddenOrganization(user, organization, visibilityNow) + if err != nil || hidden.UserID() != user || hidden.OrganizationID() != organization || !hidden.HiddenAt().Equal(visibilityNow) { + t.Fatalf("NewHiddenOrganization() = %v, %v, want the record", hidden, err) + } + for _, args := range [][2]uuid.UUID{{uuid.Nil, organization}, {user, uuid.Nil}} { + if _, err := NewHiddenOrganization(args[0], args[1], visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewHiddenOrganization(%v) error = %v, want a refusal", args, err) + } + } + if _, err := NewHiddenOrganization(user, organization, time.Time{}); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewHiddenOrganization(no time) error = %v, want a refusal", err) + } + event, err := NewOrganizationEvent(PrivacyEventOrganizationHidden, user, organization, visibilityNow) + if err != nil || event.ID() == uuid.Nil || event.HasFieldSet() || event.OrganizationID() != organization { + t.Fatalf("NewOrganizationEvent() = %v, %v, want an event without a field set", event, err) + } + if _, err := NewOrganizationEvent(PrivacyEventPublicationClosed, user, organization, visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewOrganizationEvent(publication kind) error = %v, want a refusal", err) + } + if _, err := NewPublicationEvent(PublicationChange{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewPublicationEvent(no change) error = %v, want a refusal", err) + } + if _, err := NewSearchStatusEvent(SearchStatusChange{}, visibilityNow); !errors.Is(err, ErrInvalidVisibility) { + t.Errorf("NewSearchStatusEvent(no change) error = %v, want a refusal", err) + } +} + +func TestVisibilityTypesLogOnlyIdentifiers(t *testing.T) { + publication := publish(t, newClosedPublication(t), 0, uuid.New(), visibilityNow, CardFieldStack, CardFieldLocation) + event, err := NewOrganizationEvent(PrivacyEventOrganizationHidden, uuid.New(), uuid.New(), visibilityNow) + if err != nil { + t.Fatalf("NewOrganizationEvent() error = %v", err) + } + var out strings.Builder + logger := slog.New(slog.NewTextHandler(&out, nil)) + logger.Info("settings", "publication", publication, "event", event) + for _, secret := range []string{"location", "stack"} { + if strings.Contains(out.String(), secret) { + t.Errorf("log output %q contains %q", out.String(), secret) + } + } +} + +func TestCardTextLooksLikeContact(t *testing.T) { + for _, text := range []string{ + "anna@example.com", "write to anna@mail.ru", "@anna_dev", "tg: @anna_dev", "t.me/anna", "https://github.com/anna", + "www.example.org", "anna.dev", "+7 (900) 000-00-00", "89000000000", "8 900 000 00 00", "example.com", + // Internationalized domains and wider endings. + "вася.com", "site.рф", "вася.рф", "anna.ua", "anna.by", "anna.kz", "anna.co", "anna.ai", "anna.de", "anna.tv", "anna.site", + "anna.online", "anna.tech", "bit.ly/x", "telegram.dog/anna", "tg://resolve?domain=anna", "wa.me/79000000000", "asp.net", + // Other digit scripts and compatibility forms. + "٧٩٠٠٠٠٠٠٠٠٠", "89000000000", "+7 900 000 00 00", "anna@example.com", "@anna_dev", + // Obfuscation. + "anna [at] example dot com", "vasya at gmail", "vasya собака gmail точка com", "@ vasya", "anna (dot) dev", + // Messenger and contact words without an @. + "tg: vasya_ivanov", "telegram vasya_ivanov", "whatsapp 1", "viber", "skype: vasya", "почта", "телефон", "email me", + } { + if !CardTextLooksLikeContact(text) { + t.Errorf("CardTextLooksLikeContact(%q) = false, want true", text) + } + } + for _, text := range []string{ + "PostgreSQL", "Node.js", "Vue.js", "Next.js", "Python 3.12", "ASP.NET", "C++", "C#", "Kubernetes", "Казань", "Mentoring", + "Go 1.22", "Java 17", "Санкт-Петербург", "Python 3.12, Django 4.2, PostgreSQL 16", "pro.company", "Team leadership", + } { + if CardTextLooksLikeContact(text) { + t.Errorf("CardTextLooksLikeContact(%q) = true, want false", text) + } + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 214f0b3..51d29b0 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -702,7 +702,7 @@ Decisions: - Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented. - Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. - Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)). -- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are evidence of the publication history of TASK-088, which must keep them with their times. Adding a field scope to C2 rows later is an additive migration and contract change. +- C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are kept with their times and the C2 record behind each in the history of TASK-088 (`candidate_publications` and `candidate_privacy_events`, see [Candidate visibility](#candidate-visibility)). Adding a field scope to C2 rows later is an additive migration and contract change. - C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. - Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent. - Scoping. Every read and revocation takes the subject, and the contract operation takes it from the session, so the read model returns only the caller's own records. Errors of the adapter keep the SQLSTATE and constraint name only, and `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant`, and `ConsentRevocation` show no subject, organization, name, or fields in `fmt` and `slog` output. @@ -802,6 +802,44 @@ Decisions: - Consistent read. `ReadCandidateProfile` reads the profile row and every claim in one statement (a LEFT JOIN), that is, from one snapshot; two separate queries could return version N with the claims of N+1 when a save commits between them. The adapter must use only this query and never replace it with two; a write reads the profile in the same transaction as the replacement, and the version condition protects against a lost edit. - Privacy. The values are personal data of the candidate: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent`, and `CandidateProfile` hide themselves in `fmt` and `slog` output, `CandidateProfile` logs only the account identifier and the version, domain errors name the field and the rule but never the value, and metric labels are never taken from the profile. No query selects the profile of another account: every statement is scoped by `user_id`. The adapter must never log or wrap `pgconn.PgError.Detail` (it contains the failing row with names and phones) and reports only the SQLSTATE and the constraint name, as the organizations adapter does. +### Candidate visibility + +Implemented as storage, domain, and the source contract (TASK-088): the migration `backend/db/migrations/00015_create_candidate_privacy.sql` (number 00014 belongs to the idempotency records of the registration task), the queries in `backend/db/queries/privacy.sql`, the domain types in `backend/internal/domain/visibility.go`, the schemas in `api/core/components/schemas/privacy_schemas.yml`, and nine operations of the tag `privacy` in `api/core/routes/candidate_privacy*.yml` under `/api/v1/me/privacy` ([api/README.en.md](../../api/README.en.md#candidate-visibility)). There is no port, adapter, or handler yet: the operations answer 401 `unauthenticated` while there are no sessions and 501 `not_implemented` after validation. The port and the adapter come with the handlers and must join `UnitOfWork`; the queries and the domain conversion of rows (`RestorePublication`, `RestoreSearchStatus`) are ready and covered by an integration test. + +Four independent pieces of state, each with its own table and its own version. No statement of one table writes another, and the consent C2 is neither copied nor replaced: + +- `candidate_publications`: one row per candidate, created by the first explicit publication, so a new profile has no row and is closed. Columns: `state` (`published` or `closed`), `fields` (a canonical array of card field codes, empty exactly when closed), `consent_record_id`, `published_at`, `closed_at`, `version`, and times. The card field codes are a closed set (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); the full name, a contact, and the lowest salary have no code, and the function `candidate_card_fields_are_canonical` with a CHECK refuses anything else, so no row can publish them. +- `candidate_search_statuses`: one row per candidate who ever set the status. `status` is `looking` or `not_looking`; `looking` stores `confirmed_at`, `lapses_at`, and `policy_version_id`, and `not_looking` stores none of them (a CHECK ties the three together). The only foreign key is `users`, and a trigger checks `policy_version_id` against `policy_versions` (SQLSTATE 23503, constraint name `candidate_search_statuses_policy_fkey`), because a real foreign key would make PostgreSQL refuse TRUNCATE of the immutable policy table before its own trigger could answer: the table has no consent column and no reference to the ledger, and a test reads the catalog to prove it. +- `candidate_hidden_organizations`: the primary key `(user_id, organization_id)` makes a hiding unique per candidate and organization; `organization_id` references `organizations` with `ON DELETE RESTRICT`. A BEFORE INSERT trigger (`candidate_hidden_organizations_enforce_limit`) bounds one candidate to 1000 records, serializing the inserts of one candidate through a no-key-update lock on the account row, and fails with SQLSTATE 23514 and the constraint name `candidate_hidden_organizations_limit`. The index on `(organization_id, user_id)` serves the organization side, which has to exclude hidden candidates without learning who hid it. +- `candidate_privacy_events`: the append-only history (a trigger refuses every UPDATE with `candidate_privacy_events_immutable`, and refuses DELETE only while the account is verified, with `candidate_privacy_events_retained`; TRUNCATE stays allowed for test isolation). It holds the kind, the time, the published field set and the C2 record of a publication event, and only the organization identifier for a hiding event (the candidate's read joins the current name, so the table holds no text about an organization); a CHECK fixes the shape of every kind. It never holds a profile value or a name. A trigger refuses DELETE while the account is confirmed (`candidate_privacy_events_retained`, the same condition as `consent_records_refuse_delete`, to be extended by the retention rule and the account deletion procedure), a trigger on `users` refuses deleting a confirmed account that has history with the same constraint name (the cascade runs after the account row is gone, so the row trigger alone cannot see it), and the account reference cascades, so the unverified account cleanup removes the rows of an account it deletes. The hide and unhide records are sensitive: they say which employer a candidate avoids. + +Decisions: + +- A profile is closed by default. Nothing in the account, the profile, the questionnaire, or an assessment creates a row, and the integration test saves a profile and checks that all four tables stay empty. The domain reads a missing row as version 0, closed with the reason `never_published`, not looking, and hiding nobody. +- C2 stays in the consent ledger; the publication references it. Duplicating the consent state would let two tables disagree about whether a candidate agreed. `candidate_publications` therefore holds only what the ledger deliberately does not carry (which fields and when) and a reference to the C2 record behind them. The composite foreign key `(consent_record_id, user_id, consent_purpose)` over the unique index `consent_records_id_subject_purpose_key` (added by this migration; the record id is already unique, so it restricts nothing) accepts only a C2 record of the same account, and a record that a publication refers to cannot be deleted. The effective state is computed: `ReadCandidatePublication` joins the revocation stamp of the record in one statement, and the card is `published` only while the stored state is `published` and the record is unrevoked. A revocation of C2 closes the card at once without any write here, and a later C2 grant opens nothing: the publication stays bound to the revoked record, so the candidate publishes again explicitly and the new publication binds to the new record. The body of the publish operation carries no consent identifier; the usecase binds the account's current unrevoked C2 record in the same transaction as the write, and it MUST take it with the port method that issues `LockCurrentC2Record` (`SELECT ... FOR SHARE`), not with `ConsentLedger().Current`, otherwise the race with a revocation returns, and without one answers 409 `state_conflict`. +- The search status is not a consent. It has its own table, its own version, and no reference to the ledger, and `domain.SearchStatus` knows neither the publication nor the hidden organizations, so applying a status cannot change them. The integration test sets, confirms, and clears the status in a fixture and compares the raw rows of the consent ledger, the publication, and the hidden organizations before and after: they are equal. +- The lapse of `looking` comes from the versioned policy and only narrows. The 30 days are `search_status.searching_confirmation_interval_days` of the effective `product` policy version (demo version 1: 30), so the owner changes them by publishing a new policy version, not by a constant or configuration. A confirmation fixes `lapses_at` and stores `policy_version_id`, so a later policy change moves no stored time and every row names the policy it was made under, as the policy section requires. The lapse itself is computed (`SearchStatus.Effective(now)` is `looking` only while `now` is before `lapses_at`) and never written: no process, job, or clock skew can turn an expired status into anything more public, the stored row keeps what the candidate said, and the read model shows `value` `not_looking` with `lapsed` true. The candidate confirms again with `looking`, which replaces `confirmed_at`. A reminder before the lapse is a planned notification, not part of this task. +- Versions. Each setting has its own `version` (0 is the absence of a row), checked in the statement like the profile: `UpdateCandidatePublication` and `UpdateCandidateSearchStatus` change a row only when the stored version equals the one the caller read, and no row returns for a stale one (412 `version_conflict`). The domain order is the contract's: a version above the current one is a conflict, an unchanged effective setting is a success even over a stale version, any other change over a stale version is a conflict, and a publication needs an active C2. Because the settings are independent, a change of one never makes another stale. +- Hidden organizations belong to the candidate and are safe against enumeration. The record is the candidate's: no organization-visible query selects it, and an organization cannot tell a hidden candidate from an unpublished one. Hiding by identifier must not become a way to ask whether an organization exists. The foreign key refuses an unknown organization (SQLSTATE 23503), and the usecase must answer that exactly like an organization the candidate cannot see: the same 404 `not_found` with the same body, without a different timing or code. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup lists (planned, an open question), so a hiding reveals nothing the candidate could not already read. Lifting a hiding is a DELETE that answers 204 for any well-formed identifier, so it reveals nothing at all, and its history event is written only when a row was deleted. The identifiers are random UUIDv7 values, and the general rate limit covers the probing that remains. +- Contact grants. Closing the publication, and hiding an organization that holds an active contact grant, revoke the grant with the reason `visibility_closed` in the same transaction as the change (the invitation contract fixes the reason). That belongs to the usecases that do not exist yet; this task stores the settings and defines the contract. The search status never closes a grant. +- History instead of a field scope. The C2 record proves the consent to the publication text, and `candidate_privacy_events` keeps what the consent ledger note asked for: the published field set and its changes with their times and the C2 record behind each. A revocation of C2 and a lapse are computed, not events. Whether C2 needs its own field scope as a consent under article 10.1 of 152-FZ is still a legal question (see the consent ledger). +- Privacy. The tables hold identifiers, card field codes, and times; no profile value, name, contact, or file (a test lists the columns). `Publication`, `SearchStatus`, `HiddenOrganization`, and `PrivacyEvent` log only identifiers, versions, and kinds. No query selects another account's row: every statement is scoped by `user_id`. The adapter must report only the SQLSTATE and the constraint name, as the others do. + +- One structural barrier for organization-facing reads. The view `candidate_effective_publications` is published AND backed by an unrevoked C2 record. Every read on behalf of an organization (the search, the card, the contact read: TASK-185, TASK-089, TASK-090) must select from this view and add `NOT EXISTS` over `candidate_hidden_organizations` for the reading organization, as `ReadPublicationVisibleToOrganization` does; no row means "nothing to read" whichever reason applies, so an organization cannot tell a hidden candidate from an unpublished one. Reading `candidate_publications` directly is reserved for the candidate's own settings queries, and `backend/db/privacy_queries_test.go` fails when any other query in `db/queries` names the table. +- Closing over a revoked C2. A closing sent over a stored `published` row whose C2 was revoked is a real change: the row is normalized to `closed`, `publication_closed` is recorded, and the contact grants are revoked with `visibility_closed` like for any closing. Only a stored `closed` row makes a closing a repeat. The C2 revocation path (TASK-064) must itself close the stored publication and revoke the contact grants of the account in its own transaction; the computed state closes the card at once, but it does not revoke grants. +- Publish and revoke race. The publish transaction takes the current C2 with `LockCurrentC2Record` (`SELECT ... FOR SHARE`) and writes the publication under that lock, then re-reads the effective state with `ReadCandidatePublication` in the same transaction to build its response. The revocation stamp is an UPDATE of the same row, so it either commits first (the lock returns no row and the publication is refused with 409) or waits until the publication commits and closes the card right after; an integration test holds the lock and proves both orders. +- Verified email. Publishing, hiding, and the history exist only for accounts with a verified email (a usecase requirement). The unverified account cleanup (`DeleteUnverifiedUsersRegisteredBefore`) deletes its consent records explicitly and would meet the restricting reference of a publication to its C2 record, so that no unconfirmed account holds a publication is a usecase requirement, not a physical impossibility: the cleanup also works over an unverified account that does hold a C2, a publication, and history, and over a C2 revoked and granted again (an integration scenario verifies it, and it depends on the order in which the data-modifying statements of the cleanup apply). Hiding records and history cascade. +- Two kinds of 409 `state_conflict` are told apart by `errors[]`: `{in: body, pointer: /state, code: consent_required}` for a publication without an active C2, and `{in: path, pointer: /org_id, code: limit_reached}` for the 1001st hidden organization. The hiding limit is enforced by the trigger under a lock on the account row; when an insertion fails with SQLSTATE 23514 and `candidate_hidden_organizations_limit`, the adapter must re-read the pair before answering 409, because a concurrent PUT of the same pair at 999 records can have created it, and the idempotent answer is 200; an integration test fires eight concurrent insertions at 999 records and expects exactly one success. +- A new card field is a contract change and a migration. The codes are listed in the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables, as well as in the `CardField` enum, `domain.CardField`, and the card builder. + +Content of the card (hard requirements for TASK-089, which builds it): + +- Only values that the candidate confirmed ever reach the card; an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. +- A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped, never published. `domain.CardTextLooksLikeContact` is the check the builder must apply to every free text; it errs on the side of dropping. +- Quasi-identifiers (a rare combination of location, stack, and experience) and the generalization of rare features are an acceptance criterion of TASK-089, not decided here (see the open question in the API README). + +The anonymous card for organizations is not built here: `AnonymousCardContent` is the closed set of properties that a published card can hold (confirmed categories, stack, total months of experience, soft skills, location, relocation), with no name, contact, employer, salary, or identifier, and a contract test walks the references of the card and the preview and fails on any profile, contact, consent, or organization schema. The card of an organization's search result (TASK-185) must reuse it. `GetMyCardPreview` and `ListMyCardAccessHistory` are contract-only: the preview needs the profile, the confirmed categories, and the publication read together, and the access records are written by the search and contact-read tasks, so the table for them comes with those tasks. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 47cce93..baf6d29 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -370,6 +370,22 @@ Unit tests (`make -C backend test`) check the profile rules without a database: `TestCandidateProfileMigrationRollsBack` rolls migration 00013 back on an isolated database and checks that both tables disappear while `users` stays. +## Candidate visibility tests + +Unit tests (`make -C backend test`) check the visibility rules without a database: + +- `internal/domain/visibility_test.go`: the card field set is canonical, closed, and refuses the full name, any contact, and the salary; a publication request needs a field to publish and none to close; a new profile is closed and never published; publishing needs an active C2 and names no consent; the order of checks (a future version, an unchanged state over a stale version, a stale change, a missing consent); a revoked C2 closes the card and a new C2 does not reopen it; the search status lapses after the interval of the policy to the non-public status without a write, is confirmed again explicitly, and takes the interval from the policy version; stored rows that break an invariant are rejected; the types log only identifiers. +- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: by the contract bundle, the operations follow the conventions (the CSRF scheme exactly for changes, the version in the body, no Idempotency-Key or If-Match, the same 404 for hiding, 204 without a 404 for lifting); the publication and the search status carry no consent and reach no schema of each other; **the anonymous card and the preview reach no profile, contact, consent, invitation, or organization schema and have no property that names or identifies a person**, and no organization path reaches a setting; through the generated server the schema rejects a contact as a card field, a consent identifier, and a client-sent time before the implementation, a valid request answers 501, and a denied session answers 401. +- `frontend/src/shared/api/privacy-contract.test.ts`: the generated Zod schemas read a new candidate as closed and not looking at version 0, reject a card field that is a name, a contact, or the salary, strip a consent, a time, and an interval from the parsed requests, keep the card closed to contacts, and the generated organization, invitation, need, profile, and consent files hold no setting keys. + +`TestCandidatePrivacyStorage` in `backend/integration_test/candidate_privacy_test.go` uses `bootstrap(t, postgresService)`; `candidatePrivacyTables` belong to `usersDependentTables`: + +- A new profile has no published state: after saving a profile all four tables are empty and the reads return no row. A hidden organization is unique per candidate and belongs to the candidate; an unknown organization is refused by the reference; lifting deletes once; the 1001st record is refused by the trigger. +- Publication: the foreign key accepts only a C2 record of the same account; a revocation in the ledger closes the card without a write; a new C2 grant publishes nothing; a stale update returns no row; the constraints refuse a contact as a field, a wrong order, and a wrong state shape. +- Search status: in a fixture the status is set, confirmed, and cleared, and the raw rows of the consent ledger, the publication, and the hidden organizations stay equal; looking stores the confirmation under the policy version with the interval of the policy; a lapse changes no row; the constraints refuse looking without its confirmation; the table has no consent column and references only users. +- Closing over a revoked C2 normalizes the stored row and records the closing; an organization reads a publication only through the effective view and not when it hides the reading organization (the same no-row answer as for an unpublished profile); a revocation racing with a publication, held under `LockCurrentC2Record`, waits for it and closes the card after it, or finds nothing to lock; eight concurrent hidings at 999 records let exactly one through; the unverified account cleanup removes the hiding records and history of an unverified account and spares a confirmed one. `backend/db/privacy_queries_test.go` fails when a query other than the three settings queries names `candidate_publications`, and `TestCardTextLooksLikeContact` pins the drop of free text that looks like a contact. +- History: append-only (UPDATE refused, DELETE refused while the account is confirmed), identifiers only, the shape of each kind is checked, pages continue by position, and the published fields and the C2 record are kept with their time. No privacy table has a column for a profile value, a name, a contact, or a file. + ## Assessment bank tests `backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go`, and `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) check without a database: invalid family content is refused (review rules, unknown algorithm, parameter bounds, answer format mismatch, rubric shape, Unicode format characters); statement templates accept only text and `{{.name}}` placeholders, and a nested `define` bomb, a `printf` width bomb, a `range` over a number, and a recursive `block` are refused within a second without being run; a template without the placeholders its answer depends on is refused; the rendered statement size is bounded; a changed stored document fails the hash check; each publication refusal names its reason; one seed gives one variant while the rubric stays the same across seeds; golden tests pin the exact statement and reference answer of a fixed seed for each of the four algorithms and the scheme 1 content hash of a fixed input; a row is verified with the hash scheme it was stored with (a test registers a second scheme, and a hash of one scheme under the name of the other, or an unknown scheme, is refused); a template whose statement reaches the size bound for one probe seed only is refused at import, because the highest parameter values are rendered for eight seeds; the line and paragraph separators are refused like format characters; the four solvers match hand-computed cases; the coverage required for an opening is `max_scored_items` plus `seed_items` of the policy; and the demo bundle parses as an AI draft with a pending review and no reviewer. With in-memory fakes of the repository and the unit of work, the usecase tests prove that a concurrent identical import reports the version as unchanged and a concurrent import with other content is refused, that the sentinels of database races become refusals with the matching reason, that publishing retires the older published version after taking the category lock and is refused when a newer one is published, that opening requires the policy version in force, that availability is refused when the published count falls below the opening's requirement or when the opening's policy version is no longer in force, and that an older approved draft is refused while a newer version exists as a draft, a published, or a retired one. `internal/adapter/secondary/postgres/assessment_bank_test.go` checks that the bank constraints map to their sentinels without the failing row, that a list page outside its limit fails before any statement, and that the category lock is refused outside a transaction. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 0ac98ef..a5f0503 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -702,7 +702,7 @@ contact_grant относится к паре кандидат-компания - Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы. - Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. - Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)). -- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения - доказательства истории публикации из TASK-088, которая обязана хранить их со временем. Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. +- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории TASK-088 (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. - C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. - Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие. - Ограничение субъектом. Каждое чтение и отзыв принимают субъекта, а операция контракта берет его из сессии, поэтому модель чтения возвращает только собственные записи вызывающего. Ошибки адаптера сохраняют только SQLSTATE и имя ограничения, а `domain.ConsentRecord`, `ConsentGrant`, `ContactConsentGrant` и `ConsentRevocation` не показывают в выводе `fmt` и `slog` субъекта, организацию, название или поля. @@ -802,6 +802,44 @@ contact_grant относится к паре кандидат-компания - Согласованное чтение. `ReadCandidateProfile` читает строку профиля и все заявления одним оператором (LEFT JOIN), то есть из одного снимка; два отдельных запроса могли бы вернуть версию N с заявлениями N+1 при сохранении между ними. Адаптер обязан использовать только этот запрос и не заменять его двумя; запись читает профиль в той же транзакции, что и замена, а защиту от потерянной правки дает условие версии. - Приватность. Значения - ПДн кандидата: `ProfileClaim`, `ProfileExperience`, `ProfileSalaryMinimum`, `CandidateProfileContent` и `CandidateProfile` скрывают себя в выводе `fmt` и `slog`, `CandidateProfile` логирует только идентификатор аккаунта и версию, ошибки домена называют поле и правило, но не значение, а метки метрик никогда не берутся из профиля. Ни один запрос не выбирает профиль чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер никогда не логирует и не оборачивает `pgconn.PgError.Detail` (там строка с именами и телефонами) и сообщает только SQLSTATE и имя ограничения, как адаптер организаций. +### Видимость кандидата + +Реализовано как хранилище, домен и исходный контракт (TASK-088): миграция `backend/db/migrations/00015_create_candidate_privacy.sql` (номер 00014 занят записями идемпотентности задачи регистрации), запросы в `backend/db/queries/privacy.sql`, доменные типы в `backend/internal/domain/visibility.go`, схемы в `api/core/components/schemas/privacy_schemas.yml` и девять операций тега `privacy` в `api/core/routes/candidate_privacy*.yml` под `/api/v1/me/privacy` ([api/README.md](../../api/README.md#видимость-кандидата)). Порта, адаптера и обработчика еще нет: пока нет сессий, операции отвечают 401 `unauthenticated`, а после валидации - 501 `not_implemented`. Порт и адаптер появятся вместе с обработчиками и должны войти в `UnitOfWork`; запросы и доменное восстановление строк (`RestorePublication`, `RestoreSearchStatus`) готовы и покрыты интеграционным тестом. + +Четыре независимых состояния, у каждого своя таблица и своя версия. Ни один оператор одной таблицы не пишет другую, а согласие C2 не копируется и не заменяется: + +- `candidate_publications`: одна строка на кандидата, создается первой явной публикацией, поэтому у нового профиля строки нет и он закрыт. Столбцы: `state` (`published` или `closed`), `fields` (канонический массив кодов полей карточки, пустой ровно при `closed`), `consent_record_id`, `published_at`, `closed_at`, `version` и времена. Коды полей карточки - закрытый набор (`categories`, `stack`, `experience`, `soft_skills`, `location`, `relocation`); у полного имени, контакта и минимальной зарплаты кода нет, а функция `candidate_card_fields_are_canonical` с CHECK отклоняет все остальное, поэтому ни одна строка не может их опубликовать. +- `candidate_search_statuses`: одна строка на кандидата, который хоть раз задавал статус. `status` - `looking` или `not_looking`; `looking` хранит `confirmed_at`, `lapses_at` и `policy_version_id`, а `not_looking` не хранит ничего из этого (CHECK связывает три значения). Внешний ключ только на `users`, а `policy_version_id` проверяет триггер по `policy_versions` (SQLSTATE 23503, имя ограничения `candidate_search_statuses_policy_fkey`), потому что настоящий внешний ключ заставил бы PostgreSQL отказать в TRUNCATE неизменяемой таблицы политик раньше ее собственного триггера: у таблицы нет столбца согласия и ссылки на журнал, тест читает каталог и это доказывает. +- `candidate_hidden_organizations`: первичный ключ `(user_id, organization_id)` делает скрытие уникальным для пары кандидат-организация; `organization_id` ссылается на `organizations` с `ON DELETE RESTRICT`. Триггер BEFORE INSERT (`candidate_hidden_organizations_enforce_limit`) ограничивает кандидата 1000 записями, сериализуя вставки одного кандидата блокировкой no-key-update строки аккаунта, и падает с SQLSTATE 23514 и именем ограничения `candidate_hidden_organizations_limit`. Индекс по `(organization_id, user_id)` обслуживает сторону организации, которая должна исключать скрывших кандидатов, не узнавая, кто ее скрыл. +- `candidate_privacy_events`: журнал только для добавления (триггер запрещает любой UPDATE с `candidate_privacy_events_immutable` и запрещает DELETE, только пока аккаунт подтвержден, с `candidate_privacy_events_retained`; TRUNCATE для изоляции тестов разрешен). В нем вид события, время, набор опубликованных полей и запись C2 для события публикации, а для скрытия - только идентификатор организации (чтение кандидата присоединяет текущее название, поэтому в таблице нет текста об организации); CHECK задает форму каждого вида. Значений профиля и имен там нет. Триггер запрещает DELETE, пока аккаунт подтвержден (`candidate_privacy_events_retained`, то же условие, что у `consent_records_refuse_delete`; его расширят правило хранения и процедура удаления аккаунта), триггер на `users` запрещает удалять подтвержденный аккаунт с историей под тем же именем ограничения (каскад выполняется, когда строки аккаунта уже нет, и строковый триггер один этого не видит), а ссылка на аккаунт каскадная, поэтому очистка неподтвержденных аккаунтов удаляет строки удаляемого аккаунта. Записи о скрытии и снятии скрытия чувствительны: они говорят, каких работодателей кандидат избегает. + +Решения: + +- Профиль закрыт по умолчанию. Ничто в аккаунте, профиле, анкете или оценке не создает строку, а интеграционный тест сохраняет профиль и проверяет, что все четыре таблицы остаются пустыми. Домен читает отсутствие строки как версию 0, закрытый профиль с причиной `never_published`, статус "не ищет" и отсутствие скрытых организаций. +- C2 остается в журнале согласий, публикация на него ссылается. Дублирование состояния согласия позволило бы двум таблицам расходиться в том, согласился ли кандидат. Поэтому `candidate_publications` хранит только то, чего журнал намеренно не несет (какие поля и когда), и ссылку на запись C2, на которой публикация держится. Составной внешний ключ `(consent_record_id, user_id, consent_purpose)` по уникальному индексу `consent_records_id_subject_purpose_key` (добавлен этой миграцией; идентификатор записи и так уникален, поэтому индекс ничего не ограничивает) принимает только запись C2 того же аккаунта, а запись, на которую ссылается публикация, удалить нельзя. Действующее состояние вычисляется: `ReadCandidatePublication` присоединяет отметку отзыва записи в одном операторе, и карточка `published` только пока сохраненное состояние `published`, а запись не отозвана. Отзыв C2 закрывает карточку сразу, без записи в эту таблицу, а новая выдача C2 ничего не открывает: публикация остается привязанной к отозванной записи, кандидат публикует заново явно, и новая публикация привязывается к новой записи. В теле операции публикации нет идентификатора согласия; юзкейс привязывает текущую неотозванную запись C2 аккаунта в той же транзакции, что и запись, и ОБЯЗАН брать ее методом порта, который выполняет `LockCurrentC2Record` (`SELECT ... FOR SHARE`), а не `ConsentLedger().Current`, иначе гонка с отзывом возвращается, а без нее отвечает 409 `state_conflict`. +- Статус поиска - не согласие. У него своя таблица, своя версия и нет ссылки на журнал, а `domain.SearchStatus` не знает ни публикации, ни скрытых организаций, поэтому применение статуса не может их изменить. Интеграционный тест в фикстуре задает, подтверждает и снимает статус и сравнивает сырые строки журнала согласий, публикации и скрытых организаций до и после: они равны. +- Истечение `looking` берется из версионированной политики и только сужает видимость. 30 дней - это `search_status.searching_confirmation_interval_days` действующей версии политики `product` (демо-версия 1: 30), поэтому владелец меняет срок публикацией новой версии политики, а не константой или конфигурацией. Подтверждение фиксирует `lapses_at` и сохраняет `policy_version_id`, поэтому последующее изменение политики не сдвигает сохраненные времена, а каждая строка называет политику, по которой создана, как требует раздел политик. Само истечение вычисляется (`SearchStatus.Effective(now)` дает `looking`, только пока `now` раньше `lapses_at`) и нигде не записывается: ни процесс, ни задача, ни расхождение часов не превратит истекший статус во что-то более публичное, сохраненная строка хранит слова кандидата, а ответ показывает `value` `not_looking` и `lapsed` true. Кандидат подтверждает снова значением `looking`, которое заменяет `confirmed_at`. Напоминание до истечения - запланированное уведомление, не часть этой задачи. +- Версии. У каждой настройки своя `version` (0 - отсутствие строки), она проверяется в самом операторе, как у профиля: `UpdateCandidatePublication` и `UpdateCandidateSearchStatus` меняют строку только если сохраненная версия равна прочитанной вызывающим, а для устаревшей строка не возвращается (412 `version_conflict`). Порядок в домене совпадает с контрактом: версия выше текущей - конфликт, неизмененная действующая настройка - успех даже при устаревшей версии, любое другое изменение по устаревшей версии - конфликт, а публикации нужна действующая C2. Поскольку настройки независимы, изменение одной никогда не делает устаревшей другую. +- Скрытые организации принадлежат кандидату и защищены от перебора. Запись принадлежит кандидату: ни один запрос стороны организации ее не выбирает, а организация не отличает скрывшего кандидата от неопубликованного. Скрытие по идентификатору не должно стать способом спросить, существует ли организация. Внешний ключ отклоняет неизвестную организацию (SQLSTATE 23503), а юзкейс обязан ответить на это так же, как на организацию, которую кандидат не видит: тот же 404 `not_found` с тем же телом, без другого времени ответа или кода. Кандидат видит организацию, приславшую ему приглашение, и организации, которые покажет поиск организаций для кандидата (запланирован, открытый вопрос), поэтому скрытие не раскрывает того, что кандидат не мог прочитать раньше. Снятие скрытия - DELETE, который отвечает 204 на любой корректный идентификатор и потому ничего не раскрывает; событие истории пишется, только если строка была удалена. Идентификаторы - случайные UUIDv7, а оставшийся перебор покрывает общий лимит запросов. +- Контактные разрешения. Закрытие публикации и скрытие организации, у которой есть активное контактное разрешение, отзывают его с причиной `visibility_closed` в той же транзакции, что и изменение (причину задает контракт приглашений). Это относится к юзкейсам, которых еще нет; эта задача хранит настройки и задает контракт. Статус поиска разрешение никогда не закрывает. +- История вместо области полей. Запись C2 доказывает согласие с текстом публикации, а `candidate_privacy_events` хранит то, о чем просила заметка журнала согласий: набор опубликованных полей и его изменения с временами и записью C2 за каждым. Отзыв C2 и истечение статуса вычисляются и не являются событиями. Нужна ли C2 собственная область полей как согласию по статье 10.1 152-ФЗ - по-прежнему юридический вопрос (см. журнал согласий). +- Приватность. Таблицы хранят идентификаторы, коды полей карточки и времена; значений профиля, имен, контактов и файлов нет (тест перечисляет столбцы). `Publication`, `SearchStatus`, `HiddenOrganization` и `PrivacyEvent` пишут в журналы только идентификаторы, версии и виды. Ни один запрос не выбирает строку чужого аккаунта: каждый оператор ограничен `user_id`. Адаптер должен сообщать только SQLSTATE и имя ограничения, как остальные. + +- Один структурный барьер для чтений со стороны организации. Представление `candidate_effective_publications` - опубликовано И держится на неотозванной записи C2. Каждое чтение от имени организации (поиск, карточка, чтение контактов: TASK-185, TASK-089, TASK-090) обязано выбирать из этого представления и добавлять `NOT EXISTS` по `candidate_hidden_organizations` для читающей организации, как это делает `ReadPublicationVisibleToOrganization`; отсутствие строки значит "читать нечего" по любой причине, поэтому организация не отличает скрывшего кандидата от неопубликованного. Прямое чтение `candidate_publications` оставлено только запросам настроек самого кандидата, а `backend/db/privacy_queries_test.go` падает, когда другой запрос в `db/queries` называет таблицу. +- Закрытие поверх отозванной C2. Закрытие поверх сохраненной строки `published`, чья C2 отозвана, - настоящее изменение: строка нормализуется в `closed`, пишется `publication_closed`, а контактные разрешения отзываются с `visibility_closed`, как при любом закрытии. Повтором закрытия считается только сохраненное состояние `closed`. Путь отзыва C2 (TASK-064) сам обязан закрыть сохраненную публикацию и отозвать контактные разрешения аккаунта в своей транзакции; вычисляемое состояние закрывает карточку сразу, но разрешения не отзывает. +- Гонка публикации и отзыва. Транзакция публикации берет текущую C2 через `LockCurrentC2Record` (`SELECT ... FOR SHARE`), пишет публикацию под этой блокировкой и затем перечитывает действующее состояние `ReadCandidatePublication` в той же транзакции, чтобы построить ответ. Отметка отзыва - UPDATE той же строки, поэтому он либо фиксируется раньше (блокировка не вернет строку, публикация отклонена с 409), либо ждет фиксации публикации и закрывает карточку сразу после; интеграционный тест удерживает блокировку и доказывает оба порядка. +- Подтвержденный email. Публикация, скрытие и история существуют только у аккаунтов с подтвержденным email (требование юзкейса). Очистка неподтвержденных аккаунтов (`DeleteUnverifiedUsersRegisteredBefore`) удаляет их записи согласий явно и столкнулась бы с ограничивающей ссылкой публикации на запись C2, поэтому отсутствие публикации у неподтвержденного аккаунта - требование юзкейса, а не физическая невозможность: очистка работает и для неподтвержденного аккаунта, у которого есть C2, публикация и история, и для C2, отозванной и выданной снова (это проверяет интеграционный сценарий, и он зависит от порядка применения изменяющих операторов очистки). Записи скрытия и история удаляются каскадом. +- Два вида 409 `state_conflict` различаются через `errors[]`: `{in: body, pointer: /state, code: consent_required}` для публикации без действующей C2 и `{in: path, pointer: /org_id, code: limit_reached}` для 1001-й скрытой организации. Предел скрытий обеспечивает триггер под блокировкой строки аккаунта; когда вставка падает с SQLSTATE 23514 и `candidate_hidden_organizations_limit`, адаптер обязан перечитать пару перед ответом 409, потому что параллельный PUT той же пары при 999 записях мог ее создать, а идемпотентный ответ - 200; интеграционный тест запускает восемь параллельных вставок при 999 записях и ожидает ровно один успех. +- Новое поле карточки - это изменение контракта и миграция. Коды перечислены в функции `candidate_card_fields_are_canonical` и в CHECK таблиц публикации и событий, а также в enum `CardField`, `domain.CardField` и построителе карточки. + +Содержимое карточки (жесткие требования к TASK-089, который ее строит): + +- В карточку попадают только значения, которые кандидат подтвердил; неподтвержденное предложение (статус `extracted`) и неизвестное значение не попадают никогда, что бы ни говорил набор полей. +- Свободный текст (тег стека, софт-скилл, место), похожий на контакт (адрес email, номер телефона, URL или домен, ссылка Telegram, @handle), отбрасывается и не публикуется. Проверка, которую построитель обязан применять к каждому свободному тексту, - `domain.CardTextLooksLikeContact`; она ошибается в сторону отбрасывания. +- Квазиидентификаторы (редкое сочетание места, стека и опыта) и обобщение редких признаков - критерий приемки TASK-089, здесь не решаются (см. открытый вопрос в README API). + +Анонимная карточка для организаций здесь не строится: `AnonymousCardContent` - закрытый набор свойств, которые может содержать опубликованная карточка (подтвержденные категории, стек, суммарный опыт в месяцах, софт-скиллы, место, переезд), без имени, контакта, работодателя, зарплаты и идентификатора, а контрактный тест обходит ссылки карточки и предпросмотра и падает на любой схеме профиля, контакта, согласия или организации. Карточку результата поиска организации (TASK-185) нужно строить на ней. `GetMyCardPreview` и `ListMyCardAccessHistory` только в контракте: предпросмотру нужно читать профиль, подтвержденные категории и публикацию вместе, а записи обращений пишут задачи поиска и чтения контактов, поэтому таблица для них придет с этими задачами. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index d0da2a1..6b46b7c 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -370,6 +370,22 @@ Unit-тесты (`make -C backend test`) проверяют правила жу `TestCandidateProfileMigrationRollsBack` откатывает миграцию 00013 на изолированной базе, проверяет, что обе таблицы исчезают, а `users` остается. +## Тесты видимости кандидата + +Модульные тесты (`make -C backend test`) проверяют правила видимости без базы: + +- `internal/domain/visibility_test.go`: набор полей карточки канонический, закрытый и отклоняет полное имя, любой контакт и зарплату; запрос публикации требует поле для публикации и не допускает его при закрытии; новый профиль закрыт и не публиковался; публикации нужна действующая C2, а согласие она не называет; порядок проверок (будущая версия, неизмененное состояние при устаревшей версии, устаревшее изменение, нет согласия); отозванная C2 закрывает карточку, а новая ее не открывает; статус поиска истекает через срок политики до непубличного статуса без записи, подтверждается заново явно и берет срок из версии политики; сохраненные строки, нарушающие инвариант, отклоняются; типы пишут в журнал только идентификаторы. +- `internal/adapter/primary/http/candidate_privacy_contract_test.go`: по бандлу контракта операции следуют соглашениям (схема CSRF ровно для изменений, версия в теле, нет Idempotency-Key и If-Match, одинаковый 404 для скрытия, 204 без 404 для снятия); публикация и статус поиска не несут согласия и не достигают схем друг друга; **анонимная карточка и предпросмотр не достигают схем профиля, контакта, согласия, приглашения или организации и не имеют свойства, называющего или идентифицирующего человека**, а путь организации не достигает настроек; через сгенерированный сервер схема отклоняет контакт как поле карточки, идентификатор согласия и время от клиента до реализации, валидный запрос отвечает 501, а отказанная сессия - 401. +- `frontend/src/shared/api/privacy-contract.test.ts`: сгенерированные схемы Zod читают нового кандидата как закрытого и не ищущего с версией 0, отклоняют поле карточки, которое является именем, контактом или зарплатой, убирают согласие, время и срок из разобранных запросов, не пускают контакты в карточку, а в сгенерированных файлах организации, приглашения, потребности, профиля и согласий нет ключей настроек. + +`TestCandidatePrivacyStorage` в `backend/integration_test/candidate_privacy_test.go` использует `bootstrap(t, postgresService)`; `candidatePrivacyTables` входят в `usersDependentTables`: + +- У нового профиля нет состояния публикации: после сохранения профиля все четыре таблицы пусты, а чтения не возвращают строки. Скрытая организация уникальна для кандидата и принадлежит ему; неизвестную организацию отклоняет ссылка; снятие удаляет один раз; 1001-ю запись отклоняет триггер. +- Публикация: внешний ключ принимает только запись C2 того же аккаунта; отзыв в журнале закрывает карточку без записи; новая выдача C2 ничего не публикует; устаревшее обновление не возвращает строку; ограничения отклоняют контакт как поле, неверный порядок и неверную форму состояния. +- Статус поиска: в фикстуре статус задается, подтверждается и снимается, а сырые строки журнала согласий, публикации и скрытых организаций остаются равными; `looking` хранит подтверждение под версией политики со сроком политики; истечение не меняет строк; ограничения отклоняют `looking` без подтверждения; в таблице нет столбца согласия, а внешний ключ ведет только на аккаунты. +- Закрытие поверх отозванной C2 нормализует сохраненную строку и записывает закрытие; организация читает публикацию только через действующее представление и не читает, если скрыта (тот же ответ без строки, что и для неопубликованного профиля); отзыв, гоняющийся с публикацией, удерживаемой под `LockCurrentC2Record`, ждет ее и закрывает карточку после, либо не находит что блокировать; восемь параллельных скрытий при 999 записях пропускают ровно одно; очистка неподтвержденных аккаунтов удаляет записи скрытия и историю неподтвержденного аккаунта и не трогает подтвержденный. `backend/db/privacy_queries_test.go` падает, когда запрос, кроме трех запросов настроек, называет `candidate_publications`, а `TestCardTextLooksLikeContact` фиксирует отбрасывание свободного текста, похожего на контакт. +- История: только добавление (UPDATE отклоняется, DELETE отклоняется, пока аккаунт подтвержден), только идентификаторы, форма каждого вида проверена, страницы продолжаются по позиции, опубликованные поля и запись C2 хранятся со временем. Ни в одной таблице видимости нет столбца для значения профиля, имени, контакта или файла. + ## Тесты банка заданий `backend/internal/domain/assessment_family_test.go`, `assessment_generator_test.go` и `backend/internal/usecase/assessment/` (`bundle_test.go`, `bank_test.go`) проверяют без базы: отклоняется некорректное содержимое семейства (правила рецензии, неизвестный алгоритм, границы параметров, несоответствие формата ответа, форма рубрики, символы формата Unicode); шаблоны условий принимают только текст и подстановки `{{.name}}`, а бомба из вложенных `define`, бомба ширины `printf`, `range` по числу и рекурсивный `block` отклоняются быстрее секунды и не запускаются; шаблон без подстановок, от которых зависит ответ, отклоняется; размер готового условия ограничен; измененный сохраненный документ не проходит проверку хеша; каждый отказ в публикации называет причину; один seed дает один вариант, а рубрика одинакова для всех seed; golden-тесты фиксируют точное условие и эталонный ответ для заданного seed у каждого из четырех алгоритмов и хеш содержимого схемы 1 для заданного входа; строка проверяется схемой хеша, с которой она сохранена (тест регистрирует вторую схему, а хеш одной схемы под именем другой и неизвестная схема отклоняются); шаблон, чье условие достигает границы размера только для одного пробного seed, отклоняется при импорте, потому что наибольшие значения параметров подставляются для восьми seed; разделители строки и абзаца отклоняются как символы формата; четыре решателя совпадают с посчитанными вручную случаями; покрытие для открытия равно `max_scored_items` плюс `seed_items` политики; демонстрационный пакет читается как черновик ИИ с рецензией `pending` и без рецензента. С in-memory подделками репозитория и единицы работы usecase-тесты доказывают: одновременный идентичный импорт сообщает версию как неизмененную, а одновременный импорт с другим содержимым отклоняется; sentinel-ошибки гонок базы становятся отказами с подходящей причиной; публикация после взятия блокировки категории выводит из обращения более старую опубликованную версию и отклоняется, если опубликована более новая; открытие требует действующую версию политики; доступность отклоняется, когда число опубликованных семейств падает ниже требования открытия или когда версия политики открытия больше не действует; более старый одобренный черновик отклоняется, пока существует более новая версия: черновик, опубликованная или выведенная из обращения. `internal/adapter/secondary/postgres/assessment_bank_test.go` проверяет, что ограничения банка преобразуются в свои sentinel-ошибки без строки с нарушением, что страница списка вне предела падает до любого запроса и что блокировка категории отклоняется вне транзакции. diff --git a/frontend/src/shared/api/endpoints/index.msw.ts b/frontend/src/shared/api/endpoints/index.msw.ts index 9d607b1..bcd1b3f 100644 --- a/frontend/src/shared/api/endpoints/index.msw.ts +++ b/frontend/src/shared/api/endpoints/index.msw.ts @@ -7,4 +7,5 @@ export { getIdentityMock } from './identity/identity.msw' export { getInvitationMock } from './invitation/invitation.msw' export { getNeedMock } from './need/need.msw' export { getOrganizationMock } from './organization/organization.msw' +export { getPrivacyMock } from './privacy/privacy.msw' export { getSupportMock } from './support/support.msw' diff --git a/frontend/src/shared/api/endpoints/index.ts b/frontend/src/shared/api/endpoints/index.ts index 6a547e5..a65245c 100644 --- a/frontend/src/shared/api/endpoints/index.ts +++ b/frontend/src/shared/api/endpoints/index.ts @@ -7,4 +7,5 @@ export * from './identity/identity'; export * from './invitation/invitation'; export * from './need/need'; export * from './organization/organization'; +export * from './privacy/privacy'; export * from './support/support'; diff --git a/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts b/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts new file mode 100644 index 0000000..e358891 --- /dev/null +++ b/frontend/src/shared/api/endpoints/privacy/privacy.msw.ts @@ -0,0 +1,175 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + faker +} from '@faker-js/faker'; + +import { + fakeFromPattern +} from '../../mock-pattern'; + +import { + HttpResponse, + http +} from 'msw'; +import type { + RequestHandlerOptions +} from 'msw'; + +import type { + AnonymousCardContent, + CardAccessList, + CardPreview, + HiddenOrganization, + HiddenOrganizationList, + PrivacyEventList, + PrivacyOrganization, + PrivacySettings, + Publication, + SearchStatus +} from '../../schemas'; + + +export const getGetMyPrivacySettingsResponseMock = (overrideResponse: Partial> = {}): PrivacySettings => ({publication: {state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, search_status: {value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0})}, hidden_organizations_total: faker.number.int({min: 0, max: 1000}), ...overrideResponse}) + +export const getSetMyPublicationResponseMock = (overrideResponse: Partial> = {}): Publication => ({state: faker.helpers.arrayElement(['closed','published'] as const), closed_reason: faker.helpers.arrayElement([faker.helpers.arrayElement(['never_published','closed_by_candidate','consent_revoked'] as const),null,]), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), published_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse}) + +export const getGetMyCardPreviewResponseAnonymousCardContentMock = (overrideResponse: Partial = {}): AnonymousCardContent => ({...{categories: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 9}) }, (_, i) => i + 1).map(() => ({specialization: faker.helpers.arrayElement(['backend','frontend','mobile','network_engineer','devops_sre','data_analyst','ds_ml','information_security','qa'] as const), grade: faker.helpers.arrayElement(['intern','junior','middle','senior'] as const)})), null]), stack: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 30}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), experience_months: faker.helpers.arrayElement([faker.number.int({min: 0, max: 1200}), null]), soft_skills: faker.helpers.arrayElement([Array.from({ length: faker.number.int({min: 1, max: 10}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 50}))), null]), location: faker.helpers.arrayElement([fakeFromPattern("^\\S(?:.*\\S)?$", {minLength: 1, maxLength: 100}), null]), relocation: faker.helpers.arrayElement([faker.datatype.boolean(), null])}, ...overrideResponse}); + +export const getGetMyCardPreviewResponseMock = (overrideResponse: Partial> = {}): CardPreview => ({state: faker.helpers.arrayElement(['closed','published'] as const), fields: faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const), card: faker.helpers.arrayElement([{...getGetMyCardPreviewResponseAnonymousCardContentMock()},null,]), generated_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + +export const getSetMySearchStatusResponseMock = (overrideResponse: Partial> = {}): SearchStatus => ({value: faker.helpers.arrayElement(['looking','not_looking'] as const), lapsed: faker.datatype.boolean(), confirmed_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), lapses_at: faker.helpers.arrayElement([faker.date.past().toISOString().slice(0, 19) + 'Z',null,]), version: faker.number.int({min: 0}), ...overrideResponse}) + +export const getListMyHiddenOrganizationsResponseMock = (overrideResponse: Partial> = {}): HiddenOrganizationList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, hidden_at: faker.date.past().toISOString().slice(0, 19) + 'Z'})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) + +export const getHideOrganizationResponseMock = (overrideResponse: Partial> = {}): HiddenOrganization => ({organization: {id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, hidden_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse}) + +export const getListMyPrivacyHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse}); + +export const getListMyPrivacyHistoryResponseMock = (overrideResponse: Partial> = {}): PrivacyEventList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['publication_opened','publication_changed','publication_closed','search_status_confirmed','search_status_cleared','organization_hidden','organization_unhidden'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', fields: faker.helpers.arrayElement([faker.helpers.arrayElements(['categories','stack','experience','soft_skills','location','relocation'] as const),null,]), consent_id: faker.helpers.arrayElement([faker.string.uuid(),null,]), organization: faker.helpers.arrayElement([{...getListMyPrivacyHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) + +export const getListMyCardAccessHistoryResponsePrivacyOrganizationMock = (overrideResponse: Partial = {}): PrivacyOrganization => ({...{id: faker.string.uuid(), name: faker.string.alpha({length: {min: 1, max: 200}})}, ...overrideResponse}); + +export const getListMyCardAccessHistoryResponseMock = (overrideResponse: Partial> = {}): CardAccessList => ({items: Array.from({ length: faker.number.int({min: 1, max: 100}) }, (_, i) => i + 1).map(() => ({id: faker.string.uuid(), kind: faker.helpers.arrayElement(['card_viewed','contact_read'] as const), occurred_at: faker.date.past().toISOString().slice(0, 19) + 'Z', organization: faker.helpers.arrayElement([{...getListMyCardAccessHistoryResponsePrivacyOrganizationMock()},null,])})), page: {has_more: faker.datatype.boolean(), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null])}, ...overrideResponse}) + + +export const getGetMyPrivacySettingsMockHandler = (overrideResponse?: PrivacySettings | ((info: Parameters[1]>[0]) => Promise | PrivacySettings), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/privacy', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyPrivacySettingsResponseMock(), + { status: 200 + }) + }, options) +} + +export const getSetMyPublicationMockHandler = (overrideResponse?: Publication | ((info: Parameters[1]>[0]) => Promise | Publication), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/privacy/publication', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getSetMyPublicationResponseMock(), + { status: 200 + }) + }, options) +} + +export const getGetMyCardPreviewMockHandler = (overrideResponse?: CardPreview | ((info: Parameters[1]>[0]) => Promise | CardPreview), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/privacy/preview', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getGetMyCardPreviewResponseMock(), + { status: 200 + }) + }, options) +} + +export const getSetMySearchStatusMockHandler = (overrideResponse?: SearchStatus | ((info: Parameters[1]>[0]) => Promise | SearchStatus), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/privacy/search-status', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getSetMySearchStatusResponseMock(), + { status: 200 + }) + }, options) +} + +export const getListMyHiddenOrganizationsMockHandler = (overrideResponse?: HiddenOrganizationList | ((info: Parameters[1]>[0]) => Promise | HiddenOrganizationList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/privacy/hidden-organizations', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getListMyHiddenOrganizationsResponseMock(), + { status: 200 + }) + }, options) +} + +export const getHideOrganizationMockHandler = (overrideResponse?: HiddenOrganization | ((info: Parameters[1]>[0]) => Promise | HiddenOrganization), options?: RequestHandlerOptions) => { + return http.put('*/api/v1/me/privacy/hidden-organizations/:orgId', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getHideOrganizationResponseMock(), + { status: 200 + }) + }, options) +} + +export const getUnhideOrganizationMockHandler = (overrideResponse?: void | ((info: Parameters[1]>[0]) => Promise | void), options?: RequestHandlerOptions) => { + return http.delete('*/api/v1/me/privacy/hidden-organizations/:orgId', async (info: Parameters[1]>[0]) => { + if (typeof overrideResponse === 'function') {await overrideResponse(info); } + + return new HttpResponse(null, + { status: 204 + }) + }, options) +} + +export const getListMyPrivacyHistoryMockHandler = (overrideResponse?: PrivacyEventList | ((info: Parameters[1]>[0]) => Promise | PrivacyEventList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/privacy/history', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getListMyPrivacyHistoryResponseMock(), + { status: 200 + }) + }, options) +} + +export const getListMyCardAccessHistoryMockHandler = (overrideResponse?: CardAccessList | ((info: Parameters[1]>[0]) => Promise | CardAccessList), options?: RequestHandlerOptions) => { + return http.get('*/api/v1/me/privacy/access-history', async (info: Parameters[1]>[0]) => { + + + return HttpResponse.json(overrideResponse !== undefined + ? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse) + : getListMyCardAccessHistoryResponseMock(), + { status: 200 + }) + }, options) +} +export const getPrivacyMock = () => [ + getGetMyPrivacySettingsMockHandler(), + getSetMyPublicationMockHandler(), + getGetMyCardPreviewMockHandler(), + getSetMySearchStatusMockHandler(), + getListMyHiddenOrganizationsMockHandler(), + getHideOrganizationMockHandler(), + getUnhideOrganizationMockHandler(), + getListMyPrivacyHistoryMockHandler(), + getListMyCardAccessHistoryMockHandler() +] diff --git a/frontend/src/shared/api/endpoints/privacy/privacy.ts b/frontend/src/shared/api/endpoints/privacy/privacy.ts new file mode 100644 index 0000000..220980e --- /dev/null +++ b/frontend/src/shared/api/endpoints/privacy/privacy.ts @@ -0,0 +1,967 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + CardAccessList, + CardPreview, + HiddenOrganization, + HiddenOrganizationList, + ListMyCardAccessHistoryParams, + ListMyHiddenOrganizationsParams, + ListMyPrivacyHistoryParams, + PrivacyEventList, + PrivacySettings, + Problem, + Publication, + PublicationUpdate, + SearchStatus, + SearchStatusUpdate +} from '../../schemas'; + +import { apiRequest } from '../../client'; +import type { ErrorType } from '../../client'; + + +type SecondParameter unknown> = Parameters[1]; + + + +const withQueryKey = (query: T, queryKey: K): T & { queryKey: K } => { + const result = { queryKey } as T & { queryKey: K }; + for (const key of Object.keys(query)) { + // The explicit queryKey always wins, matching the previous + // `{ ...query, queryKey }` spread where it was set last. + if (key === 'queryKey') continue; + Object.defineProperty(result, key, { + enumerable: true, + configurable: true, + get: () => (query as Record)[key], + }); + } + return result; +}; + +export const getGetMyPrivacySettingsUrl = () => { + + + + + return `/api/v1/me/privacy` +} + +/** + * Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns the publication of the candidate card, the search status, and the number of hidden organizations in one read. The response is `Cache-Control: no-store`. + * + * A profile is closed by default. A candidate who never published reads `publication.state` `closed` with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or an assessment changes these settings. The C2 consent, the search status, and the hidden organizations are three independent settings: the C2 record in the consent ledger proves that the candidate accepted the publication text, the publication records which fields are published, and the search status is a statement of the candidate that is not a consent. A change of one never changes another, and none of them ever makes the candidate more visible by itself: the search status lapses to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + * @summary Read the visibility settings of the current candidate. + */ +export const getMyPrivacySettings = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyPrivacySettingsUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyPrivacySettingsQueryKey = () => { + return [ + `/api/v1/me/privacy` + ] as const; + } + + +export const getGetMyPrivacySettingsQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyPrivacySettingsQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyPrivacySettings({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyPrivacySettingsQueryResult = NonNullable>> +export type GetMyPrivacySettingsQueryError = ErrorType + + +export function useGetMyPrivacySettings>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyPrivacySettings>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyPrivacySettings>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Read the visibility settings of the current candidate. + */ + +export function useGetMyPrivacySettings>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyPrivacySettingsQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getSetMyPublicationUrl = () => { + + + + + return `/api/v1/me/privacy/publication` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. + * + * Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings, TASK-063) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself (TASK-064) closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + * + * The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). + * + * Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first publication. If it is not the current version the server answers 412 version_conflict and changes nothing. The version travels in the body rather than in If-Match because the generated client cannot read the ETag header yet. A body that equals the stored setting changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a retry after a lost response succeeds without an Idempotency-Key. A version above the current one never existed and always answers 412. Every change is recorded in the settings history with its time, the fields, and the C2 record. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), rules that depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown card field, and more fields than there are groups; a published state with no field, and a closed state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never repeat a submitted value. + * @summary Publish or close the anonymous candidate card. + */ +export const setMyPublication = async (publicationUpdate: PublicationUpdate, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getSetMyPublicationUrl(), + { + ...options, + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(publicationUpdate) + } +);} + + + + + +export const getSetMyPublicationMutationKey = () => ['setMyPublication'] as const; + +export const getSetMyPublicationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SetMyPublicationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SetMyPublicationMutationVariables, TContext> => { + +const mutationKey = getSetMyPublicationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, SetMyPublicationMutationVariables> = (props) => { + const {data} = props ?? {}; + + return setMyPublication(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SetMyPublicationMutationResult = NonNullable>> + export type SetMyPublicationMutationBody = PublicationUpdate + export type SetMyPublicationMutationError = ErrorType + export type SetMyPublicationMutationVariables = {data: PublicationUpdate} + + /** + * @summary Publish or close the anonymous candidate card. + */ +export const useSetMyPublication = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SetMyPublicationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SetMyPublicationMutationVariables, + TContext + > => { + return useMutation(getSetMyPublicationMutationOptions(options), queryClient); + } + export const getGetMyCardPreviewUrl = () => { + + + + + return `/api/v1/me/privacy/preview` +} + +/** + * Requires the session cookie of a candidate account. Returns the card exactly as an organization that the candidate does not hide the profile from would read it now, built from the current profile, the current publication, and the consent ledger. The response is `Cache-Control: no-store`. + * + * The preview is a private read for the candidate: it creates no view, leaves no access record, and is never shown to an organization. While the profile is closed `card` is null. `card` is `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure, or account or profile identifier, and each property is null when it is not published or has no value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link, an @handle) is dropped from the card, so the preview shows exactly what an organization would read. The self-assessed grade is not a category and never appears; categories come only from assessment results. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + * @summary Preview the anonymous card that organizations would read. + */ +export const getMyCardPreview = async ( options?: Parameters[1]): Promise => { + + return apiRequest(getGetMyCardPreviewUrl(), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getGetMyCardPreviewQueryKey = () => { + return [ + `/api/v1/me/privacy/preview` + ] as const; + } + + +export const getGetMyCardPreviewQueryOptions = >, TError = ErrorType>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetMyCardPreviewQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => getMyCardPreview({ signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetMyCardPreviewQueryResult = NonNullable>> +export type GetMyCardPreviewQueryError = ErrorType + + +export function useGetMyCardPreview>, TError = ErrorType>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetMyCardPreview>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetMyCardPreview>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Preview the anonymous card that organizations would read. + */ + +export function useGetMyCardPreview>, TError = ErrorType>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetMyCardPreviewQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getSetMySearchStatusUrl = () => { + + + + + return `/api/v1/me/privacy/search-status` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. The status is a statement of the candidate and never a consent. It changes neither the C2 consent, nor the publication, nor the hidden organizations, and it does not close or open any contact grant; a candidate whose profile is closed who sets `looking` becomes visible to no one. + * + * `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from the `search_status` section of the effective product policy (30 days in the demo policy, `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it replaces the confirmation time with now and advances the version, also after a lapse. The body carries no time, interval, or policy version. + * + * After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The lapse is computed and written nowhere, so it needs no job, it can never make the candidate more visible, and it never touches the publication or the hidden organizations. A reminder before the lapse is a planned notification, not a part of this operation. + * + * Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the status; a stale or non-existent version answers 412 version_conflict and changes nothing. `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. `looking` always changes the stored confirmation, so a retry of a confirmation whose response was lost with the old version answers 412 and the client reads the status again. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), an unchanged `not_looking` (200), then a stale version (412). + * @summary Set or confirm the search status of the current candidate. + */ +export const setMySearchStatus = async (searchStatusUpdate: SearchStatusUpdate, options?: Parameters[1]): Promise => { + + const getHeaders = (h?: NonNullable): Record => { + if (!h) return {}; + if (h instanceof Headers) return Object.fromEntries(h.entries()); + if (Symbol.iterator in h) { + return Object.fromEntries( + Array.from(h as Iterable>, (entry) => Array.from(entry) as [string, string]), + ); + } + const headers: Record = {}; + for (const [name, value] of Object.entries(h)) { + if (value !== undefined) headers[name] = value; + } + return headers; + }; +return apiRequest(getSetMySearchStatusUrl(), + { + ...options, + method: 'PUT', + headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) }, + body: JSON.stringify(searchStatusUpdate) + } +);} + + + + + +export const getSetMySearchStatusMutationKey = () => ['setMySearchStatus'] as const; + +export const getSetMySearchStatusMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SetMySearchStatusMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,SetMySearchStatusMutationVariables, TContext> => { + +const mutationKey = getSetMySearchStatusMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, SetMySearchStatusMutationVariables> = (props) => { + const {data} = props ?? {}; + + return setMySearchStatus(data,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type SetMySearchStatusMutationResult = NonNullable>> + export type SetMySearchStatusMutationBody = SearchStatusUpdate + export type SetMySearchStatusMutationError = ErrorType + export type SetMySearchStatusMutationVariables = {data: SearchStatusUpdate} + + /** + * @summary Set or confirm the search status of the current candidate. + */ +export const useSetMySearchStatus = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,SetMySearchStatusMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + SetMySearchStatusMutationVariables, + TContext + > => { + return useMutation(getSetMySearchStatusMutationOptions(options), queryClient); + } + export const getListMyHiddenOrganizationsUrl = (params?: ListMyHiddenOrganizationsParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/me/privacy/hidden-organizations?${stringifiedParams}` : `/api/v1/me/privacy/hidden-organizations` +} + +/** + * Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records and no request can name another account. Returns a page of the hidden organizations, newest first with the organization identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + * + * The records belong to the candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, no card, no contact read. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + * @summary List the organizations that the candidate hides the profile from. + */ +export const listMyHiddenOrganizations = async (params?: ListMyHiddenOrganizationsParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMyHiddenOrganizationsUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMyHiddenOrganizationsQueryKey = (params?: ListMyHiddenOrganizationsParams,) => { + return [ + `/api/v1/me/privacy/hidden-organizations`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMyHiddenOrganizationsQueryOptions = >, TError = ErrorType>(params?: ListMyHiddenOrganizationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMyHiddenOrganizationsQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMyHiddenOrganizations(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMyHiddenOrganizationsQueryResult = NonNullable>> +export type ListMyHiddenOrganizationsQueryError = ErrorType + + +export function useListMyHiddenOrganizations>, TError = ErrorType>( + params: undefined | ListMyHiddenOrganizationsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMyHiddenOrganizations>, TError = ErrorType>( + params?: ListMyHiddenOrganizationsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMyHiddenOrganizations>, TError = ErrorType>( + params?: ListMyHiddenOrganizationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the organizations that the candidate hides the profile from. + */ + +export function useListMyHiddenOrganizations>, TError = ErrorType>( + params?: ListMyHiddenOrganizationsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMyHiddenOrganizationsQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getHideOrganizationUrl = (orgId: string,) => { + + + + + return `/api/v1/me/privacy/hidden-organizations/${orgId}` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body: the path names the organization and the candidate comes from the session. The hiding is a record that belongs to the candidate and references the organization; it changes neither the C2 consent, nor the publication, nor the search status. + * + * The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. + * + * Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate can see an organization that has sent them an invitation, and the organizations that a candidate lookup will list (planned; see the open questions of the contract). The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it. + * + * A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. + * + * Hiding an organization that holds an active contact grant of the candidate revokes that grant with the reason `visibility_closed` in the same transaction (planned together with the invitation operations). Lifting the hiding never reopens a grant. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), the organization and its visibility to the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like every visibility change, hiding needs a verified email (a usecase requirement). + * @summary Hide the candidate profile from one organization. + */ +export const hideOrganization = async (orgId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getHideOrganizationUrl(orgId), + { + ...options, + method: 'PUT' + + + } +);} + + + + + +export const getHideOrganizationMutationKey = () => ['hideOrganization'] as const; + +export const getHideOrganizationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,HideOrganizationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,HideOrganizationMutationVariables, TContext> => { + +const mutationKey = getHideOrganizationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, HideOrganizationMutationVariables> = (props) => { + const {orgId} = props ?? {}; + + return hideOrganization(orgId,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type HideOrganizationMutationResult = NonNullable>> + + export type HideOrganizationMutationError = ErrorType + export type HideOrganizationMutationVariables = {orgId: string} + + /** + * @summary Hide the candidate profile from one organization. + */ +export const useHideOrganization = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,HideOrganizationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + HideOrganizationMutationVariables, + TContext + > => { + return useMutation(getHideOrganizationMutationOptions(options), queryClient); + } + export const getUnhideOrganizationUrl = (orgId: string,) => { + + + + + return `/api/v1/me/privacy/hidden-organizations/${orgId}` +} + +/** + * Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or does not exist, so the operation reveals nothing about the organization, and a repeat after a lost response succeeds. The record is deleted, the settings history keeps the event `organization_unhidden` only when a record was deleted. + * + * Lifting the hiding makes the candidate readable by that organization again only if the profile is published and the organization otherwise may read it. It changes neither the C2 consent, nor the publication, nor the search status, and it never reopens a contact grant that the hiding closed. + * + * Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), then the deletion (204). + * @summary Lift the hiding of the candidate profile from one organization. + */ +export const unhideOrganization = async (orgId: string, options?: Parameters[1]): Promise => { + + return apiRequest(getUnhideOrganizationUrl(orgId), + { + ...options, + method: 'DELETE' + + + } +);} + + + + + +export const getUnhideOrganizationMutationKey = () => ['unhideOrganization'] as const; + +export const getUnhideOrganizationMutationOptions = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,UnhideOrganizationMutationVariables, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,UnhideOrganizationMutationVariables, TContext> => { + +const mutationKey = getUnhideOrganizationMutationKey(); +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, UnhideOrganizationMutationVariables> = (props) => { + const {orgId} = props ?? {}; + + return unhideOrganization(orgId,requestOptions) + } + + + + + + + return { mutationFn, ...mutationOptions }} + + export type UnhideOrganizationMutationResult = NonNullable>> + + export type UnhideOrganizationMutationError = ErrorType + export type UnhideOrganizationMutationVariables = {orgId: string} + + /** + * @summary Lift the hiding of the candidate profile from one organization. + */ +export const useUnhideOrganization = , + TContext = unknown>(options?: { mutation?:UseMutationOptions>, TError,UnhideOrganizationMutationVariables, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + UnhideOrganizationMutationVariables, + TContext + > => { + return useMutation(getUnhideOrganizationMutationOptions(options), queryClient); + } + export const getListMyPrivacyHistoryUrl = (params?: ListMyPrivacyHistoryParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/me/privacy/history?${stringifiedParams}` : `/api/v1/me/privacy/history` +} + +/** + * Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records. Returns a page of the settings history, newest first with the event identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + * + * The history is append-only evidence of what the candidate published, hid, and announced, and when. A publication event keeps the published fields and the C2 record behind them, which is what the consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the field set). A revocation of C2 and a lapse of the search status are computed and are not events here; the consent history shows the revocation. The history never contains a profile value. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + * @summary List the changes of the visibility settings of the current candidate. + */ +export const listMyPrivacyHistory = async (params?: ListMyPrivacyHistoryParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMyPrivacyHistoryUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMyPrivacyHistoryQueryKey = (params?: ListMyPrivacyHistoryParams,) => { + return [ + `/api/v1/me/privacy/history`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMyPrivacyHistoryQueryOptions = >, TError = ErrorType>(params?: ListMyPrivacyHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMyPrivacyHistoryQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMyPrivacyHistory(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMyPrivacyHistoryQueryResult = NonNullable>> +export type ListMyPrivacyHistoryQueryError = ErrorType + + +export function useListMyPrivacyHistory>, TError = ErrorType>( + params: undefined | ListMyPrivacyHistoryParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMyPrivacyHistory>, TError = ErrorType>( + params?: ListMyPrivacyHistoryParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMyPrivacyHistory>, TError = ErrorType>( + params?: ListMyPrivacyHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the changes of the visibility settings of the current candidate. + */ + +export function useListMyPrivacyHistory>, TError = ErrorType>( + params?: ListMyPrivacyHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMyPrivacyHistoryQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + +export const getListMyCardAccessHistoryUrl = (params?: ListMyCardAccessHistoryParams,) => { + const normalizedParams = new URLSearchParams(); + + Object.entries(params || {}).forEach(([key, value]) => { + + if (value !== undefined) { + normalizedParams.append(key, value === null ? 'null' : String(value)) + } + }); + + const stringifiedParams = normalizedParams.toString(); + + return stringifiedParams.length > 0 ? `/api/v1/me/privacy/access-history?${stringifiedParams}` : `/api/v1/me/privacy/access-history` +} + +/** + * Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + * + * An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A view of the card by an organization that has no invitation relation with the candidate carries `organization` null, so the candidate sees that the card was viewed without learning a company that they cannot otherwise see; a contact read always names the organization, because the candidate accepted its invitation. The entries carry no search query, filter, or ranking of the organization, and no organization the candidate hides ever appears as a viewer, because a hidden organization cannot read the card. + * + * The storage of accesses is planned with the card and contact operations of the organization side (TASK-185 and the contact read of the invitation contract); until then the operation answers 501 not_implemented after the session and request checks. + * + * A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + * @summary List the accesses of organizations to the card of the current candidate. + */ +export const listMyCardAccessHistory = async (params?: ListMyCardAccessHistoryParams, options?: Parameters[1]): Promise => { + + return apiRequest(getListMyCardAccessHistoryUrl(params), + { + ...options, + method: 'GET' + + + } +);} + + + + + +export const getListMyCardAccessHistoryQueryKey = (params?: ListMyCardAccessHistoryParams,) => { + return [ + `/api/v1/me/privacy/access-history`, ...(params ? [params] : []) + ] as const; + } + + +export const getListMyCardAccessHistoryQueryOptions = >, TError = ErrorType>(params?: ListMyCardAccessHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMyCardAccessHistoryQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMyCardAccessHistory(params, { signal, ...requestOptions }); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMyCardAccessHistoryQueryResult = NonNullable>> +export type ListMyCardAccessHistoryQueryError = ErrorType + + +export function useListMyCardAccessHistory>, TError = ErrorType>( + params: undefined | ListMyCardAccessHistoryParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMyCardAccessHistory>, TError = ErrorType>( + params?: ListMyCardAccessHistoryParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMyCardAccessHistory>, TError = ErrorType>( + params?: ListMyCardAccessHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List the accesses of organizations to the card of the current candidate. + */ + +export function useListMyCardAccessHistory>, TError = ErrorType>( + params?: ListMyCardAccessHistoryParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMyCardAccessHistoryQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + return withQueryKey(query, queryOptions.queryKey); +} + + + + + + diff --git a/frontend/src/shared/api/privacy-contract.test.ts b/frontend/src/shared/api/privacy-contract.test.ts new file mode 100644 index 0000000..6920243 --- /dev/null +++ b/frontend/src/shared/api/privacy-contract.test.ts @@ -0,0 +1,323 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, expectTypeOf, it } from "vitest"; +import { setMyPublication, setMySearchStatus } from "./endpoints/privacy/privacy"; +import { + AnonymousCardContent, + CardField, + CardPreview, + HiddenOrganization, + PrivacySettings, + Publication, + PublicationUpdate, + SearchStatus, + SearchStatusUpdate, +} from "./schemas"; + +// These tests pin the generated visibility contract (TASK-088) that the +// privacy settings screen consumes. They fail when regeneration lets a +// request name a consent or a time, lets a card field name a name, a contact, +// or the salary, lets the anonymous card gain a contact, mixes the search +// status with a consent, or leaks a setting into an organization DTO. + +const consentId = "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60"; + +const closedPublication = { + state: "closed", + closed_reason: "never_published", + fields: [], + consent_id: null, + published_at: null, + version: 0, +} as const; + +const publishedPublication = { + state: "published", + closed_reason: null, + fields: ["categories", "stack"], + consent_id: consentId, + published_at: "2026-10-06T09:10:00Z", + version: 1, +} as const; + +const notLooking = { + value: "not_looking", + lapsed: false, + confirmed_at: null, + lapses_at: null, + version: 0, +} as const; + +const lookingStatus = { + value: "looking", + lapsed: false, + confirmed_at: "2026-10-06T09:12:00Z", + lapses_at: "2026-11-05T09:12:00Z", + version: 1, +} as const; + +describe("generated PrivacySettings", () => { + it("reads a new candidate as closed, not looking, and hiding nobody, all at version 0", () => { + const parsed = PrivacySettings.parse({ + publication: closedPublication, + search_status: notLooking, + hidden_organizations_total: 0, + }); + + expect(parsed.publication).toMatchObject({ state: "closed", fields: [], version: 0 }); + expect(parsed.publication.consent_id).toBeNull(); + expect(parsed.search_status.value).toBe("not_looking"); + }); + + it("reads a published profile with its fields, its C2 record, and a confirmed status", () => { + const settings = { + publication: publishedPublication, + search_status: lookingStatus, + hidden_organizations_total: 1, + }; + + expect(PrivacySettings.parse(settings)).toEqual(settings); + }); + + it.each([ + ["a state outside closed and published", { ...publishedPublication, state: "draft" }], + ["a closing reason outside the enum", { ...closedPublication, closed_reason: "expired" }], + ["a consent identifier that is not a UUID", { ...publishedPublication, consent_id: "c2" }], + ["a negative version", { ...publishedPublication, version: -1 }], + ])("rejects a publication with %s", (_case, publication) => { + expect(Publication.safeParse(publication).success).toBe(false); + }); +}); + +describe("generated PublicationUpdate", () => { + const update = { expected_version: 0, state: "published", fields: ["categories", "stack"] }; + + it("accepts a publication and a closing", () => { + expect(PublicationUpdate.parse(update)).toEqual(update); + expect(PublicationUpdate.parse({ expected_version: 1, state: "closed", fields: [] })).toEqual({ + expected_version: 1, + state: "closed", + fields: [], + }); + }); + + it.each(["full_name", "email", "phone", "telegram", "contacts", "salary_minimum", "user_id"])( + "has no card field %s, so no request can publish it", + (field) => { + expect(CardField.safeParse(field).success).toBe(false); + expect(PublicationUpdate.safeParse({ ...update, fields: [field] }).success).toBe(false); + }, + ); + + it.each([ + ["a missing version", { state: "closed", fields: [] }], + ["a negative version", { ...update, expected_version: -1 }], + ["a fractional version", { ...update, expected_version: 1.5 }], + ["a missing field set", { expected_version: 0, state: "closed" }], + ["more fields than there are groups", { ...update, fields: [...CardField.options, "stack"] }], + ["an unknown state", { ...update, state: "hidden" }], + ])("rejects a body with %s", (_case, body) => { + expect(PublicationUpdate.safeParse(body).success).toBe(false); + }); + + it("never carries a consent, a time, or a version of the result in the parsed body", () => { + const parsed = PublicationUpdate.parse({ + ...update, + consent_id: consentId, + published_at: "2026-10-06T09:10:00Z", + version: 5, + }); + + // Generated Zod strips unknown keys; the server rejects them with 400. + expect(Object.keys(parsed).sort()).toEqual(["expected_version", "fields", "state"]); + expectTypeOf().toEqualTypeOf<{ + expected_version: number; + state: "closed" | "published"; + fields: Array< + "categories" | "stack" | "experience" | "soft_skills" | "location" | "relocation" + >; + }>(); + }); + + it("takes the update as the only argument of the generated call", () => { + expectTypeOf(setMyPublication).parameter(0).toEqualTypeOf(); + }); +}); + +describe("generated SearchStatus", () => { + it("is not a consent: it names no consent, publication, or organization", () => { + expect(Object.keys(SearchStatus.shape).sort()).toEqual([ + "confirmed_at", + "lapsed", + "lapses_at", + "value", + "version", + ]); + expect(Object.keys(SearchStatusUpdate.shape).sort()).toEqual(["expected_version", "value"]); + }); + + it("stores the confirmation of looking and a lapse that falls to the non-public status", () => { + expect(SearchStatus.parse(lookingStatus)).toEqual(lookingStatus); + // A lapsed status holds as not_looking and still shows when it was confirmed. + const lapsed = { ...lookingStatus, value: "not_looking", lapsed: true }; + + expect(SearchStatus.parse(lapsed)).toEqual(lapsed); + }); + + it.each([ + ["a value outside looking and not_looking", { expected_version: 0, value: "open" }], + ["a missing version", { value: "looking" }], + ["a negative version", { expected_version: -1, value: "looking" }], + ])("rejects an update with %s", (_case, body) => { + expect(SearchStatusUpdate.safeParse(body).success).toBe(false); + }); + + it("never carries a time, an interval, or a policy version in the parsed update", () => { + const parsed = SearchStatusUpdate.parse({ + expected_version: 0, + value: "looking", + confirmed_at: "2026-10-06T09:12:00Z", + lapses_at: "2030-01-01T00:00:00Z", + interval_days: 3650, + policy_version_id: consentId, + }); + + expect(Object.keys(parsed).sort()).toEqual(["expected_version", "value"]); + expectTypeOf(setMySearchStatus).parameter(0).toEqualTypeOf(); + }); +}); + +describe("generated HiddenOrganization", () => { + it("belongs to the candidate and names the organization and the time", () => { + const hidden = { + organization: { id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01", name: "ООО Пример Платежи" }, + hidden_at: "2026-10-06T09:20:00Z", + }; + + expect(HiddenOrganization.parse(hidden)).toEqual(hidden); + expect( + HiddenOrganization.safeParse({ ...hidden, organization: { ...hidden.organization, id: "x" } }) + .success, + ).toBe(false); + }); +}); + +describe("generated AnonymousCardContent", () => { + const card = { + categories: [{ specialization: "backend", grade: "middle" }], + stack: ["PostgreSQL", "Kafka"], + experience_months: null, + soft_skills: null, + location: null, + relocation: null, + }; + + it("holds only the closed set of card properties and reads an unpublished one as null", () => { + expect(AnonymousCardContent.parse(card)).toEqual(card); + expect(Object.keys(AnonymousCardContent.shape).sort()).toEqual([ + "categories", + "experience_months", + "location", + "relocation", + "soft_skills", + "stack", + ]); + }); + + it("never keeps a name, a contact, a salary, or an identifier of the candidate", () => { + const parsed = AnonymousCardContent.parse({ + ...card, + full_name: "Anna Sokolova", + email: "anna@example.com", + phone: "+79000000000", + telegram: "@anna", + salary_minimum: 180000, + user_id: consentId, + }); + + expect(Object.keys(parsed).sort()).toEqual(Object.keys(card).sort()); + }); + + it("is the card of a preview that is null while the profile is closed", () => { + const closed = { + state: "closed", + fields: [], + card: null, + generated_at: "2026-10-06T09:30:00Z", + }; + + expect(CardPreview.parse(closed)).toEqual(closed); + expect(CardPreview.parse({ ...closed, state: "published", fields: ["stack"], card })).toMatchObject({ + card: { stack: ["PostgreSQL", "Kafka"] }, + }); + }); +}); + +// A setting of a candidate is private. The check reads the generated files: +// the privacy schemas carry no profile, contact, or consent field, and the +// organization, invitation, need, and profile sides carry no setting. +describe("privacy schemas", () => { + const apiDirectory = resolve(dirname(fileURLToPath(import.meta.url))); + const sourcesIn = (directory: string) => + readdirSync(join(apiDirectory, directory), { recursive: true, encoding: "utf8" }) + .filter((name) => name.endsWith(".ts")) + .map((name) => ({ + name: join(directory, name), + source: readFileSync(join(apiDirectory, directory, name), "utf8"), + })); + + const privacySide = [...sourcesIn(join("schemas", "privacy"))]; + const otherSide = ["organization", "invitation", "need", "candidate", "consent"].flatMap((tag) => [ + ...sourcesIn(join("schemas", tag)), + ...sourcesIn(join("endpoints", tag)), + ]); + + // Generated object keys that only the visibility settings have, matched as + // quoted keys because endpoint comments quote contract prose. + const privacyOnly = [ + '"hidden_organizations_total":', + '"lapses_at":', + '"closed_reason":', + '"experience_months":', + '"hidden_at":', + ]; + // Generated object keys that the private profile, a contact disclosure, or + // a consent record has and no visibility schema may. + const forbiddenOnPrivacySide = [ + '"full_name":', + '"email":', + '"phone":', + '"telegram":', + '"salary_minimum":', + '"confirmed_categories":', + '"text_version":', + '"invitation_id":', + '"fields": zod.array(zod.enum([\'email\'', + ]; + + it("finds the generated files of both sides", () => { + expect(privacySide.length).toBeGreaterThan(20); + expect(otherSide.length).toBeGreaterThan(50); + }); + + it("is not reachable from an organization, invitation, need, profile, or consent schema or endpoint", () => { + const leaks = otherSide.flatMap((file) => + privacyOnly + .filter((marker) => file.source.includes(marker)) + .map((marker) => `${file.name}: ${marker}`), + ); + + expect(leaks).toEqual([]); + }); + + it("carries no name, contact, salary, profile claim, or consent field", () => { + const leaks = privacySide.flatMap((file) => + forbiddenOnPrivacySide + .filter((marker) => file.source.includes(marker)) + .map((marker) => `${file.name}: ${marker}`), + ); + + expect(leaks).toEqual([]); + }); +}); diff --git a/frontend/src/shared/api/schemas/candidate/index.ts b/frontend/src/shared/api/schemas/candidate/index.ts index df9ebb9..4ba3511 100644 --- a/frontend/src/shared/api/schemas/candidate/index.ts +++ b/frontend/src/shared/api/schemas/candidate/index.ts @@ -54,5 +54,4 @@ export * from './questionnaireSpecialization.zod'; export * from './questionnaireVersion.zod'; export * from './saveMyProfileBody.zod'; export * from './saveMyQuestionnaireBody.zod'; -export * from './stackTag.zod'; export * from './workContext.zod'; diff --git a/frontend/src/shared/api/schemas/index.ts b/frontend/src/shared/api/schemas/index.ts index 8e5091b..f9c4a3d 100644 --- a/frontend/src/shared/api/schemas/index.ts +++ b/frontend/src/shared/api/schemas/index.ts @@ -29,6 +29,7 @@ export * from './salaryRange.zod'; export * from './salaryTaxBasis.zod'; export * from './skillName.zod'; export * from './specializationCode.zod'; +export * from './stackTag.zod'; export * from './taskLanguage.zod'; export * from './timestamp.zod'; export * from './workFormat.zod'; @@ -41,4 +42,5 @@ export * from './identity'; export * from './invitation'; export * from './need'; export * from './organization'; +export * from './privacy'; export * from './support'; diff --git a/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts new file mode 100644 index 0000000..36ddf1c --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/anonymousCardContent.zod.ts @@ -0,0 +1,44 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const anonymousCardContentCategoriesMax = 9; + +export const anonymousCardContentStackItemMax = 50; + + +export const anonymousCardContentStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const anonymousCardContentStackMax = 30; + +export const anonymousCardContentExperienceMonthsMin = 0; +export const anonymousCardContentExperienceMonthsMax = 1200; + +export const anonymousCardContentSoftSkillsItemMax = 50; + + +export const anonymousCardContentSoftSkillsItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const anonymousCardContentSoftSkillsMax = 10; + +export const anonymousCardContentLocationMax = 100; + + +export const anonymousCardContentLocationRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const AnonymousCardContent = zod.object({ + "categories": zod.array(zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') +}).describe('A category confirmed by assessment results, as the card shows it.')).max(anonymousCardContentCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), + "stack": zod.array(zod.string().min(1).max(anonymousCardContentStackItemMax).regex(anonymousCardContentStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(anonymousCardContentStackMax).nullable().describe('Technology tags of the candidate, or null.'), + "experience_months": zod.int().min(anonymousCardContentExperienceMonthsMin).max(anonymousCardContentExperienceMonthsMax).nullable().describe('Total months of work experience, summed by the server without the employers, periods, or descriptions, or null.'), + "soft_skills": zod.array(zod.string().min(1).max(anonymousCardContentSoftSkillsItemMax).regex(anonymousCardContentSoftSkillsItemRegExp).describe('Plain text; clients show it as text, never as HTML.')).max(anonymousCardContentSoftSkillsMax).nullable().describe('Soft skills of the candidate, or null.'), + "location": zod.string().min(1).max(anonymousCardContentLocationMax).regex(anonymousCardContentLocationRegExp).nullable().describe('City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.'), + "relocation": zod.boolean().nullable().describe('Whether the candidate is ready to relocate, or null.') +}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract (TASK-185), which reuses this content.') + +export type AnonymousCardContent = zod.input; +export type AnonymousCardContentOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardAccess.zod.ts b/frontend/src/shared/api/schemas/privacy/cardAccess.zod.ts new file mode 100644 index 0000000..4076fc9 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardAccess.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const cardAccessOrganizationOneNameMax = 200; + + +export const CardAccess = zod.object({ + "id": zod.uuid().describe('Identifier of the access record.'), + "kind": zod.enum(['card_viewed', 'contact_read']).describe('How an organization reached the candidate.\n\n- card_viewed: an organization read the anonymous card in a search result.\n- contact_read: an organization read the contacts through the contact grant of an accepted invitation.'), + "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(cardAccessOrganizationOneNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'),zod.null()]) +}).describe('One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization.') + +export type CardAccess = zod.input; +export type CardAccessOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardAccessKind.zod.ts b/frontend/src/shared/api/schemas/privacy/cardAccessKind.zod.ts new file mode 100644 index 0000000..f341132 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardAccessKind.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CardAccessKind = zod.enum(['card_viewed', 'contact_read']).describe('How an organization reached the candidate.\n\n- card_viewed: an organization read the anonymous card in a search result.\n- contact_read: an organization read the contacts through the contact grant of an accepted invitation.') + +export type CardAccessKind = zod.input; +export type CardAccessKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardAccessList.zod.ts b/frontend/src/shared/api/schemas/privacy/cardAccessList.zod.ts new file mode 100644 index 0000000..b6c5ec0 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardAccessList.zod.ts @@ -0,0 +1,35 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const cardAccessListItemsItemOrganizationOneNameMax = 200; + +export const cardAccessListItemsMax = 100; + +export const cardAccessListPageNextCursorMax = 512; + + +export const cardAccessListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const CardAccessList = zod.object({ + "items": zod.array(zod.object({ + "id": zod.uuid().describe('Identifier of the access record.'), + "kind": zod.enum(['card_viewed', 'contact_read']).describe('How an organization reached the candidate.\n\n- card_viewed: an organization read the anonymous card in a search result.\n- contact_read: an organization read the contacts through the contact grant of an accepted invitation.'), + "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(cardAccessListItemsItemOrganizationOneNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'),zod.null()]) +}).describe('One access of an organization to the card or the contacts of the current candidate. `organization` is null for a view by an organization that has no invitation relation with the candidate, so the history shows that the card was viewed without naming a company that the candidate cannot otherwise see; whether the candidate should learn the name is an open product question. The record carries no query, ranking, or search filter of the organization.')).max(cardAccessListItemsMax).describe('Accesses of the page.'), + "page": zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(cardAccessListPageNextCursorMax).regex(cardAccessListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.') +}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.') +}).describe('One page of the accesses to the card of the current candidate, newest first.') + +export type CardAccessList = zod.input; +export type CardAccessListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts b/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts new file mode 100644 index 0000000..6aff793 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardCategory.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CardCategory = zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') +}).describe('A category confirmed by assessment results, as the card shows it.') + +export type CardCategory = zod.input; +export type CardCategoryOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardField.zod.ts b/frontend/src/shared/api/schemas/privacy/cardField.zod.ts new file mode 100644 index 0000000..7d07d40 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardField.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CardField = zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.') + +export type CardField = zod.input; +export type CardFieldOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardFieldSet.zod.ts b/frontend/src/shared/api/schemas/privacy/cardFieldSet.zod.ts new file mode 100644 index 0000000..8824a81 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardFieldSet.zod.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const CardFieldSetMin = 0; +export const CardFieldSetMax = 6; + + +export const CardFieldSet = zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(CardFieldSetMin).max(CardFieldSetMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.') + +export type CardFieldSet = zod.input; +export type CardFieldSetOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts new file mode 100644 index 0000000..08fc52c --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/cardPreview.zod.ts @@ -0,0 +1,52 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const cardPreviewFieldsMin = 0; +export const cardPreviewFieldsMax = 6; + +export const cardPreviewCardOneCategoriesMax = 9; + +export const cardPreviewCardOneStackItemMax = 50; + + +export const cardPreviewCardOneStackItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const cardPreviewCardOneStackMax = 30; + +export const cardPreviewCardOneExperienceMonthsMin = 0; +export const cardPreviewCardOneExperienceMonthsMax = 1200; + +export const cardPreviewCardOneSoftSkillsItemMax = 50; + + +export const cardPreviewCardOneSoftSkillsItemRegExp = new RegExp('^\\S(?:.*\\S)?$'); +export const cardPreviewCardOneSoftSkillsMax = 10; + +export const cardPreviewCardOneLocationMax = 100; + + +export const cardPreviewCardOneLocationRegExp = new RegExp('^\\S(?:.*\\S)?$'); + +export const CardPreview = zod.object({ + "state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'), + "fields": zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(cardPreviewFieldsMin).max(cardPreviewFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'), + "card": zod.union([zod.object({ + "categories": zod.array(zod.object({ + "specialization": zod.enum(['backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', 'data_analyst', 'ds_ml', 'information_security', 'qa']).describe('Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here.\n\n- backend: Backend (development).\n- frontend: Frontend (development).\n- mobile: Mobile (development).\n- network_engineer: Network Engineer (infrastructure).\n- devops_sre: DevOps/SRE (infrastructure).\n- data_analyst: Data Analyst (data).\n- ds_ml: DS/ML (data).\n- information_security: Information security (security).\n- qa: QA (quality).\n\nAdding a value is a contract change; renaming or removing one is a breaking change.'), + "grade": zod.enum(['intern', 'junior', 'middle', 'senior']).describe('Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.') +}).describe('A category confirmed by assessment results, as the card shows it.')).max(cardPreviewCardOneCategoriesMax).nullable().describe('Categories confirmed by assessment results, or null.'), + "stack": zod.array(zod.string().min(1).max(cardPreviewCardOneStackItemMax).regex(cardPreviewCardOneStackItemRegExp).describe('Free technology tag of the candidate\'s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.')).max(cardPreviewCardOneStackMax).nullable().describe('Technology tags of the candidate, or null.'), + "experience_months": zod.int().min(cardPreviewCardOneExperienceMonthsMin).max(cardPreviewCardOneExperienceMonthsMax).nullable().describe('Total months of work experience, summed by the server without the employers, periods, or descriptions, or null.'), + "soft_skills": zod.array(zod.string().min(1).max(cardPreviewCardOneSoftSkillsItemMax).regex(cardPreviewCardOneSoftSkillsItemRegExp).describe('Plain text; clients show it as text, never as HTML.')).max(cardPreviewCardOneSoftSkillsMax).nullable().describe('Soft skills of the candidate, or null.'), + "location": zod.string().min(1).max(cardPreviewCardOneLocationMax).regex(cardPreviewCardOneLocationRegExp).nullable().describe('City or region as free text, never a street address, or null. Plain text; clients show it as text, never as HTML.'), + "relocation": zod.boolean().nullable().describe('Whether the candidate is ready to relocate, or null.') +}).describe('The anonymous candidate card as an organization reads it. Only values that the candidate confirmed reach it; an unconfirmed suggestion and an unknown value never do. A free text value (a stack tag, a soft skill, the location) that looks like a contact (an email address, a phone number, a URL or domain, a Telegram link, an @handle) is dropped by the builder (TASK-089) and never published. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The search ranking and the full card of an organization\'s search result are defined by the search contract (TASK-185), which reuses this content.'),zod.null()]), + "generated_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('What an organization that the candidate does not hide the profile from would read now, computed from the current profile, the current publication, and the consent ledger. It is a read for the candidate: it creates no view and no history record, and it never reaches an organization. `card` is null while the profile is closed.') + +export type CardPreview = zod.input; +export type CardPreviewOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/hiddenOrganization.zod.ts b/frontend/src/shared/api/schemas/privacy/hiddenOrganization.zod.ts new file mode 100644 index 0000000..2d51525 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/hiddenOrganization.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const hiddenOrganizationOrganizationNameMax = 200; + + +export const HiddenOrganization = zod.object({ + "organization": zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(hiddenOrganizationOrganizationNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'), + "hidden_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.') + +export type HiddenOrganization = zod.input; +export type HiddenOrganizationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/hiddenOrganizationList.zod.ts b/frontend/src/shared/api/schemas/privacy/hiddenOrganizationList.zod.ts new file mode 100644 index 0000000..e4913b3 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/hiddenOrganizationList.zod.ts @@ -0,0 +1,33 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const hiddenOrganizationListItemsItemOrganizationNameMax = 200; + +export const hiddenOrganizationListItemsMax = 100; + +export const hiddenOrganizationListPageNextCursorMax = 512; + + +export const hiddenOrganizationListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const HiddenOrganizationList = zod.object({ + "items": zod.array(zod.object({ + "organization": zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(hiddenOrganizationListItemsItemOrganizationNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'), + "hidden_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.') +}).describe('One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.')).max(hiddenOrganizationListItemsMax).describe('Hidden organizations of the page.'), + "page": zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(hiddenOrganizationListPageNextCursorMax).regex(hiddenOrganizationListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.') +}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.') +}).describe('One page of the organizations that the candidate hides the profile from, newest first with the organization identifier as the tie-breaker.') + +export type HiddenOrganizationList = zod.input; +export type HiddenOrganizationListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/index.ts b/frontend/src/shared/api/schemas/privacy/index.ts new file mode 100644 index 0000000..5008045 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/index.ts @@ -0,0 +1,36 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ + +export * from './anonymousCardContent.zod'; +export * from './cardAccess.zod'; +export * from './cardAccessKind.zod'; +export * from './cardAccessList.zod'; +export * from './cardCategory.zod'; +export * from './cardField.zod'; +export * from './cardFieldSet.zod'; +export * from './cardPreview.zod'; +export * from './hiddenOrganization.zod'; +export * from './hiddenOrganizationList.zod'; +export * from './listMyCardAccessHistoryParams.zod'; +export * from './listMyHiddenOrganizationsParams.zod'; +export * from './listMyPrivacyHistoryParams.zod'; +export * from './privacyEvent.zod'; +export * from './privacyEventKind.zod'; +export * from './privacyEventList.zod'; +export * from './privacyOrganization.zod'; +export * from './privacySettings.zod'; +export * from './publication.zod'; +export * from './publicationClosedReason.zod'; +export * from './publicationState.zod'; +export * from './publicationUpdate.zod'; +export * from './publicationVersion.zod'; +export * from './searchStatus.zod'; +export * from './searchStatusUpdate.zod'; +export * from './searchStatusValue.zod'; +export * from './searchStatusVersion.zod'; +export * from './setMyPublicationBody.zod'; +export * from './setMySearchStatusBody.zod'; diff --git a/frontend/src/shared/api/schemas/privacy/listMyCardAccessHistoryParams.zod.ts b/frontend/src/shared/api/schemas/privacy/listMyCardAccessHistoryParams.zod.ts new file mode 100644 index 0000000..5249cc7 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/listMyCardAccessHistoryParams.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const listMyCardAccessHistoryParamsLimitDefault = 20; +export const listMyCardAccessHistoryParamsLimitMax = 100; + +export const listMyCardAccessHistoryParamsCursorMax = 512; + + +export const listMyCardAccessHistoryParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMyCardAccessHistoryParams = zod.object({ + "limit": zod.int().min(1).max(listMyCardAccessHistoryParamsLimitMax).default(listMyCardAccessHistoryParamsLimitDefault), + "cursor": zod.string().min(1).max(listMyCardAccessHistoryParamsCursorMax).regex(listMyCardAccessHistoryParamsCursorRegExp).exactOptional() +}) + +export type ListMyCardAccessHistoryParams = zod.input; +export type ListMyCardAccessHistoryParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/listMyHiddenOrganizationsParams.zod.ts b/frontend/src/shared/api/schemas/privacy/listMyHiddenOrganizationsParams.zod.ts new file mode 100644 index 0000000..43e765a --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/listMyHiddenOrganizationsParams.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const listMyHiddenOrganizationsParamsLimitDefault = 20; +export const listMyHiddenOrganizationsParamsLimitMax = 100; + +export const listMyHiddenOrganizationsParamsCursorMax = 512; + + +export const listMyHiddenOrganizationsParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMyHiddenOrganizationsParams = zod.object({ + "limit": zod.int().min(1).max(listMyHiddenOrganizationsParamsLimitMax).default(listMyHiddenOrganizationsParamsLimitDefault), + "cursor": zod.string().min(1).max(listMyHiddenOrganizationsParamsCursorMax).regex(listMyHiddenOrganizationsParamsCursorRegExp).exactOptional() +}) + +export type ListMyHiddenOrganizationsParams = zod.input; +export type ListMyHiddenOrganizationsParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/listMyPrivacyHistoryParams.zod.ts b/frontend/src/shared/api/schemas/privacy/listMyPrivacyHistoryParams.zod.ts new file mode 100644 index 0000000..41c751b --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/listMyPrivacyHistoryParams.zod.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const listMyPrivacyHistoryParamsLimitDefault = 20; +export const listMyPrivacyHistoryParamsLimitMax = 100; + +export const listMyPrivacyHistoryParamsCursorMax = 512; + + +export const listMyPrivacyHistoryParamsCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const ListMyPrivacyHistoryParams = zod.object({ + "limit": zod.int().min(1).max(listMyPrivacyHistoryParamsLimitMax).default(listMyPrivacyHistoryParamsLimitDefault), + "cursor": zod.string().min(1).max(listMyPrivacyHistoryParamsCursorMax).regex(listMyPrivacyHistoryParamsCursorRegExp).exactOptional() +}) + +export type ListMyPrivacyHistoryParams = zod.input; +export type ListMyPrivacyHistoryParamsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/privacyEvent.zod.ts b/frontend/src/shared/api/schemas/privacy/privacyEvent.zod.ts new file mode 100644 index 0000000..237971b --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/privacyEvent.zod.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const privacyEventFieldsOneMin = 0; +export const privacyEventFieldsOneMax = 6; + +export const privacyEventOrganizationOneNameMax = 200; + + +export const PrivacyEvent = zod.object({ + "id": zod.uuid().describe('Identifier of the event.'), + "kind": zod.enum(['publication_opened', 'publication_changed', 'publication_closed', 'search_status_confirmed', 'search_status_cleared', 'organization_hidden', 'organization_unhidden']).describe('Kind of a change of the visibility settings that the history records.\n\n- publication_opened: the candidate published a closed profile.\n- publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record.\n- publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here.\n- search_status_confirmed: the candidate set or confirmed `looking`.\n- search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed.\n- organization_hidden: the candidate hid the profile from an organization.\n- organization_unhidden: the candidate lifted the hiding for an organization.'), + "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "fields": zod.union([zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventFieldsOneMin).max(privacyEventFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'), + "consent_id": zod.union([zod.uuid(),zod.null()]).describe('C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(privacyEventOrganizationOneNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'),zod.null()]).describe('Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null.') +}).describe('One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller\'s own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null.') + +export type PrivacyEvent = zod.input; +export type PrivacyEventOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/privacyEventKind.zod.ts b/frontend/src/shared/api/schemas/privacy/privacyEventKind.zod.ts new file mode 100644 index 0000000..5039ffc --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/privacyEventKind.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PrivacyEventKind = zod.enum(['publication_opened', 'publication_changed', 'publication_closed', 'search_status_confirmed', 'search_status_cleared', 'organization_hidden', 'organization_unhidden']).describe('Kind of a change of the visibility settings that the history records.\n\n- publication_opened: the candidate published a closed profile.\n- publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record.\n- publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here.\n- search_status_confirmed: the candidate set or confirmed `looking`.\n- search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed.\n- organization_hidden: the candidate hid the profile from an organization.\n- organization_unhidden: the candidate lifted the hiding for an organization.') + +export type PrivacyEventKind = zod.input; +export type PrivacyEventKindOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/privacyEventList.zod.ts b/frontend/src/shared/api/schemas/privacy/privacyEventList.zod.ts new file mode 100644 index 0000000..d64e042 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/privacyEventList.zod.ts @@ -0,0 +1,40 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const privacyEventListItemsItemFieldsOneMin = 0; +export const privacyEventListItemsItemFieldsOneMax = 6; + +export const privacyEventListItemsItemOrganizationOneNameMax = 200; + +export const privacyEventListItemsMax = 100; + +export const privacyEventListPageNextCursorMax = 512; + + +export const privacyEventListPageNextCursorRegExp = new RegExp('^[A-Za-z0-9_-]+$'); + +export const PrivacyEventList = zod.object({ + "items": zod.array(zod.object({ + "id": zod.uuid().describe('Identifier of the event.'), + "kind": zod.enum(['publication_opened', 'publication_changed', 'publication_closed', 'search_status_confirmed', 'search_status_cleared', 'organization_hidden', 'organization_unhidden']).describe('Kind of a change of the visibility settings that the history records.\n\n- publication_opened: the candidate published a closed profile.\n- publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record.\n- publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here.\n- search_status_confirmed: the candidate set or confirmed `looking`.\n- search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed.\n- organization_hidden: the candidate hid the profile from an organization.\n- organization_unhidden: the candidate lifted the hiding for an organization.'), + "occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'), + "fields": zod.union([zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacyEventListItemsItemFieldsOneMin).max(privacyEventListItemsItemFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.'),zod.null()]).describe('Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind.'), + "consent_id": zod.union([zod.uuid(),zod.null()]).describe('C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null.'), + "organization": zod.union([zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(privacyEventListItemsItemOrganizationOneNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.'),zod.null()]).describe('Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null.') +}).describe('One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller\'s own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null.')).max(privacyEventListItemsMax).describe('Events of the page.'), + "page": zod.object({ + "has_more": zod.boolean().describe('Whether another page follows this one.'), + "next_cursor": zod.string().min(1).max(privacyEventListPageNextCursorMax).regex(privacyEventListPageNextCursorRegExp).nullable().describe('Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing.') +}).describe('Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`.') +}).describe('One page of the settings history of the current candidate, newest first.') + +export type PrivacyEventList = zod.input; +export type PrivacyEventListOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/privacyOrganization.zod.ts b/frontend/src/shared/api/schemas/privacy/privacyOrganization.zod.ts new file mode 100644 index 0000000..8388f5c --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/privacyOrganization.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const privacyOrganizationNameMax = 200; + + +export const PrivacyOrganization = zod.object({ + "id": zod.uuid().describe('Identifier of the organization.'), + "name": zod.string().min(1).max(privacyOrganizationNameMax).describe('Current name of the organization. Plain text; clients show it as text, never as HTML.') +}).describe('Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before.') + +export type PrivacyOrganization = zod.input; +export type PrivacyOrganizationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/privacySettings.zod.ts b/frontend/src/shared/api/schemas/privacy/privacySettings.zod.ts new file mode 100644 index 0000000..857674a --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/privacySettings.zod.ts @@ -0,0 +1,40 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const privacySettingsPublicationFieldsOneMin = 0; +export const privacySettingsPublicationFieldsOneMax = 6; + +export const privacySettingsPublicationVersionMin = 0; + +export const privacySettingsSearchStatusVersionMin = 0; + +export const privacySettingsHiddenOrganizationsTotalMin = 0; +export const privacySettingsHiddenOrganizationsTotalMax = 1000; + + +export const PrivacySettings = zod.object({ + "publication": zod.object({ + "state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'), + "closed_reason": zod.union([zod.enum(['never_published', 'closed_by_candidate', 'consent_revoked']).describe('Why a closed profile is closed, shown only to the candidate.\n\n- never_published: the candidate has never published the profile.\n- closed_by_candidate: the candidate closed the publication.\n- consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.'),zod.null()]).describe('Why the profile is closed, or null while it is published.'), + "fields": zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(privacySettingsPublicationFieldsOneMin).max(privacySettingsPublicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'), + "consent_id": zod.union([zod.uuid(),zod.null()]).describe('Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published.'), + "published_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication.'), + "version": zod.int().min(privacySettingsPublicationVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.') +}).describe('Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.'), + "search_status": zod.object({ + "value": zod.enum(['looking', 'not_looking']).describe('Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations.\n\n- looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`.\n- not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.').describe('The status that holds now: `looking` only while the confirmation has not lapsed.'), + "lapsed": zod.boolean().describe('True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared.'), + "confirmed_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it.'), + "lapses_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status.'), + "version": zod.int().min(privacySettingsSearchStatusVersionMin).describe('Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`.') +}).describe('Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.'), + "hidden_organizations_total": zod.int().min(privacySettingsHiddenOrganizationsTotalMin).max(privacySettingsHiddenOrganizationsTotalMax).describe('Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`.') +}).describe('The visibility settings of the current candidate in one read: the publication, the search status, and the number of hidden organizations. The three are independent: each has its own version and its own operation, and a change of one leaves the others as they were. A new account reads a closed profile, `not_looking`, and no hidden organization.') + +export type PrivacySettings = zod.input; +export type PrivacySettingsOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/publication.zod.ts b/frontend/src/shared/api/schemas/privacy/publication.zod.ts new file mode 100644 index 0000000..5dd0f3b --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/publication.zod.ts @@ -0,0 +1,25 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const publicationFieldsOneMin = 0; +export const publicationFieldsOneMax = 6; + +export const publicationVersionMin = 0; + + +export const Publication = zod.object({ + "state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'), + "closed_reason": zod.union([zod.enum(['never_published', 'closed_by_candidate', 'consent_revoked']).describe('Why a closed profile is closed, shown only to the candidate.\n\n- never_published: the candidate has never published the profile.\n- closed_by_candidate: the candidate closed the publication.\n- consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.'),zod.null()]).describe('Why the profile is closed, or null while it is published.'), + "fields": zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationFieldsOneMin).max(publicationFieldsOneMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.').describe('Card fields that organizations may read. Empty exactly when `state` is `closed`.'), + "consent_id": zod.union([zod.uuid(),zod.null()]).describe('Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published.'), + "published_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication.'), + "version": zod.int().min(publicationVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.') +}).describe('Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.') + +export type Publication = zod.input; +export type PublicationOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/publicationClosedReason.zod.ts b/frontend/src/shared/api/schemas/privacy/publicationClosedReason.zod.ts new file mode 100644 index 0000000..a2ea827 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/publicationClosedReason.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PublicationClosedReason = zod.enum(['never_published', 'closed_by_candidate', 'consent_revoked']).describe('Why a closed profile is closed, shown only to the candidate.\n\n- never_published: the candidate has never published the profile.\n- closed_by_candidate: the candidate closed the publication.\n- consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.') + +export type PublicationClosedReason = zod.input; +export type PublicationClosedReasonOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/publicationState.zod.ts b/frontend/src/shared/api/schemas/privacy/publicationState.zod.ts new file mode 100644 index 0000000..4de17bf --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/publicationState.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PublicationState = zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.') + +export type PublicationState = zod.input; +export type PublicationStateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/publicationUpdate.zod.ts b/frontend/src/shared/api/schemas/privacy/publicationUpdate.zod.ts new file mode 100644 index 0000000..17c13b4 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/publicationUpdate.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const publicationUpdateExpectedVersionMin = 0; + +export const publicationUpdateFieldsMin = 0; +export const publicationUpdateFieldsMax = 6; + + +export const PublicationUpdate = zod.object({ + "expected_version": zod.int().min(publicationUpdateExpectedVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.'), + "state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'), + "fields": zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(publicationUpdateFieldsMin).max(publicationUpdateFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.') +}).describe('The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account\'s current unrevoked C2 record, and a client can neither supply nor forge one.') + +export type PublicationUpdate = zod.input; +export type PublicationUpdateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/publicationVersion.zod.ts b/frontend/src/shared/api/schemas/privacy/publicationVersion.zod.ts new file mode 100644 index 0000000..e423f70 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/publicationVersion.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const PublicationVersionMin = 0; + + +export const PublicationVersion = zod.int().min(PublicationVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.') + +export type PublicationVersion = zod.input; +export type PublicationVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/searchStatus.zod.ts b/frontend/src/shared/api/schemas/privacy/searchStatus.zod.ts new file mode 100644 index 0000000..08f725f --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/searchStatus.zod.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const searchStatusVersionMin = 0; + + +export const SearchStatus = zod.object({ + "value": zod.enum(['looking', 'not_looking']).describe('Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations.\n\n- looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`.\n- not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.').describe('The status that holds now: `looking` only while the confirmation has not lapsed.'), + "lapsed": zod.boolean().describe('True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared.'), + "confirmed_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it.'), + "lapses_at": zod.union([zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.'),zod.null()]).describe('Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status.'), + "version": zod.int().min(searchStatusVersionMin).describe('Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`.') +}).describe('Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.') + +export type SearchStatus = zod.input; +export type SearchStatusOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/searchStatusUpdate.zod.ts b/frontend/src/shared/api/schemas/privacy/searchStatusUpdate.zod.ts new file mode 100644 index 0000000..c19e784 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/searchStatusUpdate.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const searchStatusUpdateExpectedVersionMin = 0; + + +export const SearchStatusUpdate = zod.object({ + "expected_version": zod.int().min(searchStatusUpdateExpectedVersionMin).describe('Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`.'), + "value": zod.enum(['looking', 'not_looking']).describe('Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations.\n\n- looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`.\n- not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.') +}).describe('The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.') + +export type SearchStatusUpdate = zod.input; +export type SearchStatusUpdateOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/searchStatusValue.zod.ts b/frontend/src/shared/api/schemas/privacy/searchStatusValue.zod.ts new file mode 100644 index 0000000..d4cd0bf --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/searchStatusValue.zod.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SearchStatusValue = zod.enum(['looking', 'not_looking']).describe('Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations.\n\n- looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`.\n- not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.') + +export type SearchStatusValue = zod.input; +export type SearchStatusValueOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/searchStatusVersion.zod.ts b/frontend/src/shared/api/schemas/privacy/searchStatusVersion.zod.ts new file mode 100644 index 0000000..9ba4723 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/searchStatusVersion.zod.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const SearchStatusVersionMin = 0; + + +export const SearchStatusVersion = zod.int().min(SearchStatusVersionMin).describe('Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`.') + +export type SearchStatusVersion = zod.input; +export type SearchStatusVersionOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/setMyPublicationBody.zod.ts b/frontend/src/shared/api/schemas/privacy/setMyPublicationBody.zod.ts new file mode 100644 index 0000000..94785fe --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/setMyPublicationBody.zod.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const setMyPublicationBodyExpectedVersionMin = 0; + +export const setMyPublicationBodyFieldsMin = 0; +export const setMyPublicationBodyFieldsMax = 6; + + +export const SetMyPublicationBody = zod.object({ + "expected_version": zod.int().min(setMyPublicationBodyExpectedVersionMin).describe('Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale.'), + "state": zod.enum(['closed', 'published']).describe('Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked.\n\n- closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked.\n- published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.'), + "fields": zod.array(zod.enum(['categories', 'stack', 'experience', 'soft_skills', 'location', 'relocation']).describe('A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves.\n\n- categories: the categories confirmed by assessment results (specialization and confirmed grade). A self-assessed grade is not a category and is never published.\n- stack: the technology tags of the profile.\n- experience: the total months of work experience, without employers, periods, or descriptions.\n- soft_skills: the soft skills of the profile.\n- location: the city or region of the profile.\n- relocation: whether the candidate is ready to relocate.\n\nOnly values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says.\n\nAdding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.')).min(setMyPublicationBodyFieldsMin).max(setMyPublicationBodyFieldsMax).describe('Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays.') +}).describe('The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account\'s current unrevoked C2 record, and a client can neither supply nor forge one.') + +export type SetMyPublicationBody = zod.input; +export type SetMyPublicationBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/privacy/setMySearchStatusBody.zod.ts b/frontend/src/shared/api/schemas/privacy/setMySearchStatusBody.zod.ts new file mode 100644 index 0000000..acca4b6 --- /dev/null +++ b/frontend/src/shared/api/schemas/privacy/setMySearchStatusBody.zod.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval 🍺 + * Do not edit manually. + * Lincodex API + * OpenAPI spec version: 0.1.0 + */ +import * as zod from 'zod'; + +export const setMySearchStatusBodyExpectedVersionMin = 0; + + +export const SetMySearchStatusBody = zod.object({ + "expected_version": zod.int().min(setMySearchStatusBodyExpectedVersionMin).describe('Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`.'), + "value": zod.enum(['looking', 'not_looking']).describe('Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations.\n\n- looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`.\n- not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.') +}).describe('The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.') + +export type SetMySearchStatusBody = zod.input; +export type SetMySearchStatusBodyOutput = zod.output; diff --git a/frontend/src/shared/api/schemas/problem.zod.ts b/frontend/src/shared/api/schemas/problem.zod.ts index e3e9995..8f1062e 100644 --- a/frontend/src/shared/api/schemas/problem.zod.ts +++ b/frontend/src/shared/api/schemas/problem.zod.ts @@ -45,9 +45,9 @@ export const Problem = zod.object({ "errors": zod.array(zod.object({ "in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'), "pointer": zod.string().max(problemErrorsItemPointerMax).regex(problemErrorsItemPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'), - "code": zod.string().min(1).max(problemErrorsItemCodeMax).regex(problemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'), + "code": zod.string().min(1).max(problemErrorsItemCodeMax).regex(problemErrorsItemCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values.'), "message": zod.string().min(1).max(problemErrorsItemMessageMax).describe('Fixed English message that never echoes the submitted value.') -}).describe('One reason why a request field or parameter is invalid.')).max(problemErrorsMax).exactOptional().describe('Field-level reasons for validation_failed. Other codes omit it.') +}).describe('One reason why a request field or parameter is invalid.')).max(problemErrorsMax).exactOptional().describe('Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response.') }).describe('Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.') export type Problem = zod.input; diff --git a/frontend/src/shared/api/schemas/problemFieldError.zod.ts b/frontend/src/shared/api/schemas/problemFieldError.zod.ts index a6afab6..def750c 100644 --- a/frontend/src/shared/api/schemas/problemFieldError.zod.ts +++ b/frontend/src/shared/api/schemas/problemFieldError.zod.ts @@ -20,7 +20,7 @@ export const problemFieldErrorMessageMax = 500; export const ProblemFieldError = zod.object({ "in": zod.enum(['body', 'query', 'path', 'header', 'cookie']).describe('Part of the request that contains the invalid field.'), "pointer": zod.string().max(problemFieldErrorPointerMax).regex(problemFieldErrorPointerRegExp).describe('JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.'), - "code": zod.string().min(1).max(problemFieldErrorCodeMax).regex(problemFieldErrorCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.'), + "code": zod.string().min(1).max(problemFieldErrorCodeMax).regex(problemFieldErrorCodeRegExp).describe('Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values.'), "message": zod.string().min(1).max(problemFieldErrorMessageMax).describe('Fixed English message that never echoes the submitted value.') }).describe('One reason why a request field or parameter is invalid.') diff --git a/frontend/src/shared/api/schemas/candidate/stackTag.zod.ts b/frontend/src/shared/api/schemas/stackTag.zod.ts similarity index 100% rename from frontend/src/shared/api/schemas/candidate/stackTag.zod.ts rename to frontend/src/shared/api/schemas/stackTag.zod.ts