GlobalExceptionHandler не имел @ExceptionHandler для
MethodArgumentNotValidException — провал bean-валидации @Valid
@RequestBody (@NotBlank businessKey, @NotNull data и т.п.) падал в
generic Exception catch → HTTP 500 internal_error с пустым traceId.
admin-ui на создании/редактировании записи получал бесполезный
«Internal server error» без полей вместо 400 с пофайловой разбивкой.
Добавлен handler → 400 validation_failed с FieldError-списком.
Покрыто GlobalExceptionHandlerTest.
ClassCastException on every GET /api/v1/dictionaries/{name}/snapshots:
java.lang.ClassCastException: class java.time.Instant cannot be cast
to class java.sql.Timestamp
Root cause: pgJDBC 42.7+ возвращает timestamptz из native query как
java.time.Instant, а старый код жёстко кастил в java.sql.Timestamp.
42.6 возвращал Timestamp — отсюда и тесты с Timestamp проходили,
а runtime ломался.
Fix: helper `toBucketOffsetDateTime(Object raw, OffsetDateTime now)`
ловит все 3 возможных типа от драйвера:
- java.sql.Timestamp (pgJDBC 42.6 и ранее)
- java.time.Instant (pgJDBC 42.7+ — current behavior)
- java.time.OffsetDateTime (если jdbc.timestamp.return-type=offset-date-time)
При любом другом типе бросаем IllegalStateException — fail-loud вместо
silent CCE на каждом запросе.
Tests:
+ snapshots_acceptsInstantFromPg42_7Driver — regression на конкретный
bug (Instant from current driver)
+ snapshots_acceptsOffsetDateTime — defensive coverage
+ snapshots_rejectsUnexpectedTimestampType — fail-loud branch
Existing tests (с Timestamp) сохранены для backward-compat.
QA report BUG-005: "/search" возвращал 0 результатов на любые запросы
(«антенна», «GS_MOSCOW», «super» — всё пусто).
Root cause: SearchController convertedil scope enum в lowercase перед
WHERE filter:
data_scope = ANY(CAST(? AS TEXT[])) -- value: 'public'
Но DB stores UPPERCASE per migrations 0008/0009 CHECK constraint:
CHECK (data_scope IN ('PUBLIC', 'INTERNAL', 'RESTRICTED'))
Filter 'public' никогда не матчил 'PUBLIC' → empty result для всех queries.
Багу 5+ месяцев — comment в коде утверждал что DB lowercase, что было
неправдой даже в момент написания.
Fix: убрать .toLowerCase() — pass enum names как есть. Verified:
curl /api/v1/antenna/records?as_scope=PUBLIC возвращает GS_MOSCOW_A1
но curl /api/v1/search?q=GS_MOSCOW возвращал 0. После fix должен матчить.
Reported 2026-05-14: editing schema on an approvalRequired dictionary
applied inline without going through the schema-draft maker-checker
workflow. Two endpoints both lacked the gate that DictionaryRecordService
already had for record CRUD:
1. PUT /api/v1/admin/dictionaries/{name}
(frontend SchemaDrivenForm "edit schema" save button hits this).
DictionaryDefinitionService.updateSchema overwrote schemaJson directly.
Bonus backdoor: same request could simultaneously flip
approvalRequired:true→false and rewrite the schema in one transaction
— review-bypass via toggle.
2. PATCH /api/v1/admin/dictionaries/{name}/schema (inline non-breaking
patch — description / title / minimum / maximum / enum-add). Frontend
doesn't currently call this, but backend exposed it without a gate.
Both now reject with `422 approval_required` carrying the schema-drafts
URL in the message. Frontend's existing serverErrorMessage in
DictionaryEditorDialog already surfaces backend `message` to the user,
so no UI changes needed for correctness. UX polish (hide "Save" /
show "Create draft" CTA when approvalRequired=true) is a follow-up.
The PUT gate is narrow on purpose: schemaChanged OR approvalRequired
toggle-off. Pure metadata edits (display name, description, locales,
projection flag) on an approvalRequired dict still go through inline
— those don't affect record validation, no review needed.
Implements the Phase 2 hook from the previous commit. With this in
place, UserDisplayService.find chains:
hot cache → DB (user_display_cache) → Keycloak Admin API
so any realm user resolves on first display, even if they never made
an authenticated request to ordinis. The resolved entry is persisted
via UserDisplayService.upsert with source=KEYCLOAK_ON_DEMAND, so the
next render of the same sub hits the DB tier (~ms) instead of going
back to Keycloak.
Implementation notes:
- Spring RestClient (modern blocking HTTP, replaces RestTemplate).
- client_credentials grant against
{issuer}/realms/{realm}/protocol/openid-connect/token. Token cached
in-memory minus a 30s safety margin from `expires_in`.
- 401 on user lookup wipes the cached token and surfaces a
RuntimeException, so the next resolve refetches.
- 404 on user lookup → Optional.empty (definitive miss, sub not in
realm). UserDisplayService logs and the caller falls back to short
UUID. Negative cache TTL not implemented — added complexity not
justified for the current realm size (~50 users).
- Bean activated only when ordinis.keycloak.admin.enabled=true AND
the env vars are set. Default disabled — UserDisplayService treats
KeycloakUserResolver as @Autowired(required = false), so a
deployment without Keycloak admin creds keeps the previous behavior
(DB cache only) instead of crashing on startup.
Application config:
- ORDINIS_KEYCLOAK_ADMIN_ENABLED (false by default)
- ORDINIS_KEYCLOAK_ADMIN_URL e.g. https://auth.nstart.space
- ORDINIS_KEYCLOAK_ADMIN_REALM defaults to nstart
- ORDINIS_KEYCLOAK_ADMIN_CLIENT_ID via vault (see docs-internal/keycloak-admin-setup.md)
- ORDINIS_KEYCLOAK_ADMIN_CLIENT_SECRET via vault
Setup runbook (docs-internal/keycloak-admin-setup.md) covers:
- creating the Keycloak service-account client + assigning view-users
- writing the secret into both vault instances (different per env)
- wiring vault.hashicorp.com agent-inject annotations into the chart
- verification steps + common failure modes
Phase 3 (scheduled bulk sync) is documented at the end of the runbook
but deferred — depends on observed cache miss rate after this lands.
Closes "ток мой UUID отображается" pain reported on staging today: any
reviewer / maker / publisher / actor whose JWT sub never landed in the
JVM cache shows up as a short UUID in audit / reviews / changelog /
events / history / record drawer / webhook detail / record version
history. Restart the pod and even captured users disappear.
Three-tier resolve, replacing the in-memory-only cache that was the
"Альтернатива (на будущее)" TODO in the original UserDisplayService:
1. JVM ConcurrentHashMap hot cache (~µs, capped at 10k).
2. user_display_cache Postgres table (~ms, persistent across restart).
New migration 0023 — sub PK + preferred_username + name + email +
source enum + synced_at + updated_at, plus an index on synced_at
for the scheduled bulk sync that lands later.
3. Keycloak Admin API on-demand (Phase 2) — dispatched to optional
KeycloakUserResolver bean. When the bean isn't wired (no Keycloak
admin creds yet), the third tier is a no-op and UserCell falls
back to short UUID exactly like before.
Source enum on every row — JWT_CAPTURE / KEYCLOAK_SYNC /
KEYCLOAK_ON_DEMAND — so the eventual scheduled sync can prefer JWT-
captured rows (richest claims as the user actually saw them) and the
on-demand fallback can be distinguished from bulk sync in audits.
JwtUserCaptureFilter and UserDisplayController are unchanged — they
already used UserDisplayService.put / find with the same signatures.
The behavior change is invisible at the API layer: same /admin/users/
{sub}/display endpoint, same 404 user_not_cached on miss; persistence
just survives pod restart now.
mergeFrom on UserDisplayCacheEntry deliberately keeps the existing
non-blank field when an update brings null — Keycloak sync may have a
richer email than JWT capture; don't blank it out.
Phase 2 will land a KeycloakAdminUserResolver impl + vault secret
plumbing on this same branch. Phase 3 (scheduled bulk sync via
@Scheduled) is a separate sprint — it needs the Keycloak admin client
already in place.
Класс имеет два constructor'а (main + test). Без явной @Autowired
аннотации Spring может выбрать no-arg ctor → props=null →
rolesClaimPath() fallback на realm_access.roles несмотря на
env var ORDINIS_AUTH_ROLES_CLAIM=resource_access.ordinis.roles.
Симптом: 403 forbidden_role с message 'Требуется realm role:
ordinis:schema:reviewer' для user с ordinis:admin в
resource_access.ordinis.roles (super-role override не работал
потому что currentRoles() возвращал пустой set из неправильного
claim path).
Fix: @Autowired на main ctor — Spring выбирает его, props
инжектится, rolesClaim читается из env var правильно.
User report: token has roles в resource_access.ordinis.roles (client-scoped),
backend WorkflowRoles читал hardcoded realm_access.roles → forbidden_role
для всех reviewer actions.
Backend:
- WorkflowRoles: depends OrdinisAuthProperties → reads via rolesClaim path
(же что ScopeContext). Default realm_access.roles, на staging/prod env
var ORDINIS_AUTH_ROLES_CLAIM=resource_access.ordinis.roles (уже wired
в helm helper).
- Nested claim path resolver — mirror ScopeContext.readClaimByPath
- New super-role ADMIN ('ordinis:admin') — holder автоматически проходит
любой workflow check без явного назначения отдельных ролей. Convenience
для small teams.
Frontend (usePermissions.ts):
- tokenRoles() читает оба claim path (realm_access.roles +
resource_access.ordinis.roles) и объединяет — UI gate работает
независимо от backend config
- hasRole() recognizes 'ordinis:admin' как super-role override
- ROLE_ADMIN exported
Docs:
- docs/operator/rbac.md: добавлен ordinis:admin row, JWT claim path note,
Admin profile updated (super-role vs composite explanation)
GlobalExceptionHandler catch-all Exception → 500 ловил NoResourceFoundException
и NoHandlerFoundException. Симптомы на prod:
- /swagger-ui/index.html при disabled springdoc возвращал 500 (UI всё равно
не рендерился, но spring логировал 'Unhandled exception' на каждый запрос —
спамил alerting и затруднял поиск настоящих ошибок).
- GET /api/v1/typo от integrator'ов давал 500 вместо 404, осложняло
debugging без traceId-correlation.
- Любой stale frontend bundle с переименованным endpoint мог триггерить
false-positive incident alerts.
Fix: explicit @ExceptionHandler для обоих exception типов → 404 not_found.
Логирование DEBUG (не WARN/ERROR) — это ожидаемый 404, не аномалия.
Test: SmokeE2ETest.unknownPath_returns404WithNotFoundCode покрывает оба пути
(/api/v1/* и /swagger-ui/*) → 404 + body.code='not_found'.
SmokeE2ETest.contextLoadsAndCreatesRecord фильтрует audit_log по
action='CREATE' и ожидает row с businessKey. Мой backend #1 commit
сделал definitionCreated() писать action='CREATE' — конфликт с
record-level CREATE rows: filter подбирал dict-level row первой
(no businessKey → null assertion fail).
Fix: definitionCreated/definitionUpdated теперь пишут action
'DEFINITION_CREATE' / 'DEFINITION_UPDATE'. event_type остаётся
DEFINITION_CREATED/UPDATED (changelog query filter по event_type
IN список, не задеть).
Backend #2 из pending-endpoints brief. Frontend TimeTravelModal использует
этот endpoint для slider marks — каждая точка = bucket где минимум одна
запись validFrom попадает.
GET /api/v1/dictionaries/{name}/snapshots?from=...&to=...&granularity=day
Implementation:
- DictionaryRecordRepository.findSnapshotBuckets — native SQL date_trunc
GROUP BY bucket, ORDER BY bucket DESC. scope filter через text[] из CSV.
- SnapshotsService — gates dict existence/scope, validates granularity
(hour/day/week) + window, formats RU label (1 апр / сейчас), reverses
список чтобы oldest first (UI читает слева-направо).
- DictionaryChangelogController новый endpoint /snapshots.
Errors:
- 404 dictionary_not_found
- 400 invalid_granularity (not in {hour,day,week})
- 400 invalid_window (from >= to)
Frontend impact: TimeTravelModal slider marks переходит с recordTimestamps
derived data на реальный API. ~1h frontend swap.