106 lines
17 KiB
Markdown
106 lines
17 KiB
Markdown
# Go backend
|
|
|
|
[Русский](README.md) | English
|
|
|
|
The main service uses Go, chi, and Clean Architecture. It currently provides health checks, identity and server-side sessions, the consent ledger and settings, and PostgreSQL, Redis, and SeaweedFS adapters; the remaining hiring workflows are still to be implemented.
|
|
|
|
- `cmd/app/` is the entry point; `internal/bootstrap/` wires dependencies and manages startup.
|
|
- `internal/` contains domain types, use cases, ports, and primary/secondary adapters.
|
|
- `config/` holds application settings; `pkg/` is for shared helper packages.
|
|
- `db/` and `codegen/` hold SQL queries, migrations, and generator configuration.
|
|
- `integration_test/` checks real dependencies through Testcontainers.
|
|
|
|
From the repository root, `make -C backend check` runs the main checks and `make -C backend test-int` runs integration tests with Docker. Use `make -C backend help` for all commands.
|
|
|
|
## Server sessions
|
|
|
|
Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Contract operations without an implemented business handler answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login.
|
|
|
|
Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime.
|
|
|
|
Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
|
|
|
|
HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`.
|
|
|
|
## Consent ledger and settings
|
|
|
|
Only the current C1 text is public for registration. A verified user can read current C1/C2/C3/C5 texts before granting them in settings and can page through their own consent history. C1 can be granted by either account scenario; C2, C3, and C5 are candidate-only. Mutations require explicit acceptance, the exact Origin, and session-bound CSRF.
|
|
|
|
Revoking C2 makes the publication effectively closed and hides its fields through the ledger-backed read in the same transaction; the stored publication stays linked to the revoked record, so a later C2 grant cannot reopen it. Revoking C3 does not block account, profile, or manual-assessment requests through support. Revoking C5 immediately closes the gate for future imports and writes an outbox intent; there is no external FSP adapter yet. C4 revocation is limited to one organization and uses the stored contact scope. A C1 request revokes consent and creates a durable deletion-request record with an outbox intent; repeats return the same active record, and the account is not deleted synchronously.
|
|
|
|
`make -C backend test-int` runs the full HTTP flow with PostgreSQL and Redis. `TestConsentSettingsOverHTTP` covers texts, history, grants, revocation effects, and the C1 deletion request.
|
|
|
|
## Organizations
|
|
|
|
`POST /api/v1/organizations`, `GET /api/v1/organizations/{org_id}`, and `PATCH /api/v1/organizations/{org_id}` are implemented. A verified employer creates the organization and its active owner membership in one transaction, starting at `e0` with basis `confirmed_email`. Every read checks active owner membership. Only the active owner can edit; the version advances on change and the verification level is preserved.
|
|
|
|
The same `Idempotency-Key` and body replay the original `201` snapshot within 24 hours, even after profile edits. Migration `00019_create_organization_creation_results.sql` stores that snapshot separately from the live organization. The 24 hours define the logical replay window. Bounded opportunistic cleanup runs on successful creates; physical deletion can occur later, and removes the snapshot with its generic idempotency record. `GET /api/v1/me/organizations` paginates the current employer's active memberships. Invitation routes still enforce the common owner check before the 501 fallback; their business operations remain unimplemented.
|
|
|
|
`TestOrganizationCreationAndOwnerEditingOverHTTP` checks concurrent replay, rollback on owner insertion failure, cross-account denial, persisted reads after rebuilding the API, and reuse of an expired key against PostgreSQL.
|
|
|
|
`TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations` covers company isolation, candidate denial even with a manually inserted membership, denial for other roles, pagination, and owner revocation with the same cookie. A company in the active-membership directory does not grant owner authority; the server checks the role on every request.
|
|
|
|
## Organization needs
|
|
|
|
Organization needs have transaction-bound PostgreSQL storage through `UnitOfWork.Needs()`. Migration `00023_create_organization_needs.sql` adds a current-version pointer and immutable snapshots scoped by organization. Creation starts at version 1. A changed snapshot advances the version with compare-and-swap; a losing writer gets a version conflict. The HTTP contract uses 412 for that conflict.
|
|
|
|
The owner-scoped create, read, list, and update operations live in `internal/adapter/primary/http/v1/need.go`. Every operation checks the current verified employer account and locks its active owner membership in the transaction. List cursors carry both account and organization scope. Creates retain the original public response for the 24-hour idempotency window, even after a later edit.
|
|
|
|
Source text is parsed locally by deterministic rules into unconfirmed suggestions. Unknown or ambiguous values remain unknown. Confirming a stored suggestion preserves its origin; a manual replacement records a manual origin. Editing source text preserves confirmed values, and removing a suggestion prevents later extraction from silently restoring it. Readiness is derived from confirmed requirements. Category recommendations currently report `not_available` without confirmed skills and `pending` otherwise; the category recommendation calculator is not implemented yet.
|
|
|
|
`requirements_version` identifies the snapshot where confirmed requirements last changed. Editing only the title, source text, or unconfirmed suggestions leaves that reference unchanged. Domain no-ops preserve both versions. Snapshots preserve provenance, reject oversized content, and use UTC microsecond timestamps. Current and historical reads require the organization ID; immutable history rejects ordinary UPDATE and DELETE. Down migration removes both tables and their history, so it is destructive after data has been written.
|
|
|
|
`TestOrganizationNeedsStorage` exercises actual PostgreSQL isolation, history, concurrent updates, transaction rollback, immutable snapshots, and storage bounds. The caller must perform the existing active-owner check in the same business operation; storage scope alone does not grant company access.
|
|
|
|
Migration `00026_create_organization_need_creation_results.sql` adds create-response storage and 8 KiB of database representation headroom for JSONB whitespace. The compact domain snapshot limit remains 256 KiB. Its down migration refuses to discard live replay results or restore the previous database bound over larger stored snapshots. Check those conditions before rollback; it does not remove need history to make a downgrade succeed.
|
|
|
|
## Support cases
|
|
|
|
Verified accounts can create and list their own cases at `/api/v1/me/support-cases` and read a case by its ID. Ownership is independent of access to a disputed action. Object references contain only a type and ID; the server checks their scope and does not copy private object content. Employers can submit general support requests. Candidates can also request manual assessment without a prior attempt or C3 consent. Such a request waits for an expert and does not assign a grade or grant consent.
|
|
|
|
A manual request pins the current published rubric for its specialization and grade. The API shows the grading-policy version; private references retain the exact category opening and immutable family-version manifest. Later publications do not change an existing case's rubric. Without one unambiguous current rubric, the version remains `null` and the case waits for an expert.
|
|
|
|
Creation requires an explicit support section in the effective product policy. `DemoProductPolicyV2` includes it; normal startup still seeds only the immutable V1 policy. The demo targets are five business days for support, complaints, and manual assessment, and ten for appeals. The versioned calendar counts UTC weekdays without public holidays and does not pause while waiting for the user. These are operational targets, not legal deadlines.
|
|
|
|
The account-wide rolling request limit is checked under a database lock before idempotent replay. Valid retries consume that request budget and return the original creation response during the 24-hour window. A 429 response includes `Retry-After`. GET and list show the current status, public history, and current overdue flag. Migration `00025_create_support_cases.sql` stores immutable events and replay results; rollback removes these records and is destructive.
|
|
|
|
`TestSupportCasesOverHTTP` covers real sessions, owner isolation, typed-reference checks, replay, manual assessment without C3, and request limits. `TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock` checks concurrent requests and clock ordering. Expert processing and references to not-yet-implemented invitations or anti-cheat reviews remain unavailable.
|
|
|
|
## Candidate questionnaire
|
|
|
|
Verified candidates can read and replace their own questionnaire through `GET/PUT /api/v1/me/questionnaire`. The questionnaire has a separate version and stores self-assessment, work formats, optional experience totals, and one or two specializations. It cannot assign confirmed grades. An identical retry returns the saved record without advancing its version; a stale changed body returns 412, as specified by the API contract. Concurrent identical writes also return the same winning record.
|
|
|
|
Saving advances onboarding only from `candidate_questionnaire` to `candidate_assessment`, in the same transaction. Other saved steps stay unchanged. Consent settings do not yet complete the consent onboarding step.
|
|
|
|
The public specialization catalog derives readiness from the current published bank, current policy, and an immutable reviewed mapping tied to the exact category opening and published-family manifest. Legacy openings without a mapping remain unavailable. Policy changes or family retirement invalidate readiness until a new reviewed opening is made; previously saved answers remain readable. Operator names are self-declared review metadata, not an authenticated operator identity.
|
|
|
|
`TestCandidateQuestionnaireOverHTTP` covers persistence, account isolation, version races, rollback, conditional onboarding, and changing bank availability. Company quota storage and its calling contract are described in [Company quotas](../docs/en/COMPANY_QUOTAS.md).
|
|
|
|
## Assessment attempts
|
|
|
|
A candidate creates an attempt through `POST /api/v1/me/assessment-attempts`, reads it by ID, and resumes work through `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions`. Real assessment requires current C3 consent; the owner's attempt history remains readable after revocation. GET neither consumes sessions nor changes state. A command with a stale version returns 412.
|
|
|
|
Creation pins the policy, bank and algorithm versions, the published family manifest, and generated question instances. The API response excludes answer keys, seeds, and private rubrics. Root-attempt quota is candidate-wide; retry and promotion intervals apply per specialization. A corrective attempt retains its root and the original chain deadline. Training `demo_express` uses a separate explicitly published bank and consumes no real-assessment quota.
|
|
|
|
Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records.
|
|
|
|
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. Category assignment remains separate work; a basic threshold is not evidence of calibration.
|
|
|
|
## Assessment signals
|
|
|
|
The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt.
|
|
|
|
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Browser collection and interpretation of these signals are separate work.
|
|
|
|
## Anonymous profile projection
|
|
|
|
The organization-scoped projection uses purpose-separated HMAC aliases, a closed skill taxonomy, coarse experience bands, and explicitly selected publication fields. Confirmed categories and self-assessed grades remain separate. It excludes contacts, employer names, free text, exact salary, and account identifiers. Overlapping work periods count once.
|
|
|
|
The repository filters current C2 publication and hidden organizations before building the cohort. Complete visible feature combinations with fewer than five candidates are generalized or suppressed. This reduces identification risk; it does not guarantee anonymity. The private owner-preview alias uses a separate purpose. Category and salary compatibility inputs remain absent until their authoritative source supplies them; missing evidence is never inferred from a claimed grade.
|
|
|
|
Candidates read settings at `GET /api/v1/me/privacy`, preview at `GET /api/v1/me/privacy/preview`, change history at `GET /api/v1/me/privacy/history`, and card views at `GET /api/v1/me/privacy/access-history`. Hidden organizations are listed at `GET /api/v1/me/privacy/hidden-organizations` and changed through `PUT/DELETE /api/v1/me/privacy/hidden-organizations/{org_id}`. Publication and search status use `PUT /api/v1/me/privacy/publication` and `PUT /api/v1/me/privacy/search-status`. The data is scoped to the candidate in the current session, responses use `Cache-Control: no-store`, and writes require the session CSRF token and an exact allowed Origin. C2, publication, search status, and hidden organizations are independent: changing one does not enable another. Search status is a statement by the candidate, not consent.
|
|
|
|
An employer with a verified account and active membership reads a card through `GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}`. Each request rechecks membership, current C2, publication, organization hiding, and the minimum cohort; a successful view and quota use are recorded in one transaction. A closed, revoked, hidden, or suppressed card is indistinguishable from an unknown handle. Candidates can see successful card views in their access history. Contact reads and C4 grant management are not available yet; cards never contain contact details.
|
|
|
|
See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md).
|