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.
После !178 (record drawer + RecordHistoryDrawer + webhook detail) ещё
осталось 6 точек где раньше рендерился UUID. Все они в "истории
словаря" и tab "События":
1. ChangelogDiffModal:57 — header "автор: <name>" в diff modal.
Было: `{data.publishedBy.name}` (тип ChangelogPublisher.name —
docstring буквально говорит "Backend пока эхает sub").
Стало: <UserCell uuid={data.publishedBy.sub} />.
2. TimeTravelModal:686 — список изменений, имя автора рядом с датой.
3. TimeTravelModal:898 — RIGHT panel "История этой версии", dt/dd
pair с автором.
4. TimeTravelModal ComparePanel:414 — "· {author}" suffix,
author там DictionaryDetail.updatedBy (тоже UUID).
5. dictionaries.$name.tsx:2263 (events tab, EventsTabContent row) —
`{r.userId ?? 'anonymous'}` raw. Сменил на UserCell для не-null
userId, anonymous-fallback оставил без UserCell (нечего lookup'ать).
6. dictionaries.$name.tsx:2399 (history tab, HistoryTabContent entry)
— `{entry.publishedBy.name}` raw.
Всё через тот же useUserDisplay hook что и в !177 — backend
endpoint /admin/users/{sub}/display + JwtUserCaptureFilter cache.
Если sub нет в cache, UserCell fallback'ит на shortened UUID
(текущее поведение из !177).
ChangelogPublisher type comment в src/api/client.ts уже намекал что
.name это placeholder — useUserDisplay теперь реально резолвит.
MR !177 added /admin/users/{sub}/display + UserCell + useUserDisplay,
but only some renderers were migrated. Three places still rendered
raw UUID strings:
1. reviews.tsx:466 — record draft drawer ("Согласование draft" header)
showed `{draft.makerId}` raw. Tables on the same page already use
<UserCell uuid={d.makerId} />. Verified via prod staging:
soloviev.da approved a record draft today and the drawer header
showed the maker as "77ec2cc8-98e3-4d70-8037-94038fcbde67" instead
of the username.
2. RecordHistoryDrawer.tsx:110 — version history `updatedBy` raw.
3. webhooks.$id.tsx:235 — webhook subscription `createdBy` raw.
All three switched to <UserCell uuid={...} />, matching the existing
pattern. Added the import where missing. Wrapped each in
inline-flex so the UserCell sits next to the label cleanly.
No backend / API changes — same /admin/users/{sub}/display endpoint
populated by JwtUserCaptureFilter (MR !177).
Два бага в /webhooks (user report):
1. **500 при выборе scope в форме**
POST /admin/webhooks/subscriptions с scopeFilter:["PUBLIC"] возвращал 500.
Root cause: WebhookSubscription.scopeFilter был List<DataScope> с
@JdbcTypeCode(SqlTypes.ARRAY). Hibernate сериализовал enum в TEXT[] как
ordinal (е.g. {0} для PUBLIC), а DB CHECK constraint
chk_webhook_scope_filter ожидает строковые имена. Insert падал
DataIntegrityViolationException → 500.
Fix: field теперь List<String> (raw enum names). Getter/setter
конвертируют в/из DataScope — API surface (DTO, service signatures,
WebhookDispatcher) не меняется.
2. **Нет toggle active/inactive в UI**
useUpdateWebhook hook был, но не использовался в UI. Status показывался
только read-only badge'ом. Невозможно деактивировать webhook через UI.
Fix: добавлен toggle button рядом с Status badge на /webhooks/:id.
Sends PUT с inverted active flag (backend treats PUT как full replace,
поэтому пересобираем full payload).
i18n: 'webhooks.action.activate' / 'deactivate' default labels (RU).
Phase 1d enhancement: 'Согласования' пункт сайдбара скрыт если у user'а
нет approver/reviewer ролей. Раньше показывался любому authenticated —
оператор без reviewer прав видел queue, кликал и получал пустую
страницу (или 403 если бы пробовал approve).
Visibility rules:
- 'Мои черновики' — auth (maker может быть любой)
- 'Согласования' — auth + (ordinis:schema:reviewer OR ordinis:record:reviewer
OR ordinis:admin super-role) — иначе hidden
- 'Outbox' / 'Webhooks' / 'Аудит' — auth (admin-y но backend не gated
отдельной ролью)
Новый NavItem.reviewerOnly flag — фильтр в visibleSections учитывает
оба flag'а (authRequired + reviewerOnly).
Применено и к desktop Sidebar и к MobileSidebar (DRY refactor — отдельный
task).
Класс имеет два 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 правильно.
Revert MR !157 (removal). Shared runner pool снова показал queue
contention в часы пик. nstart-tagged выделенный pool обратно — лучше
predictable wait times для CI.
resource_group docker-builds-v2 (для parallel docker builds) остаётся
без изменений — orthogonal к runner tag selection.
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)
Phase 1d enforcement в DraftService.approve()/.reject() требует
realm role 'ordinis:record:reviewer'. Test fixtures используют
JwtTestSupport.signJwt() — добавляем role в JWT для reviewer'ов.
Changes в ApprovalWorkflowE2ETest:
- Новый helper reviewerTokenFor(subject) — internal scope + record:reviewer
- 4 reviewer call sites (bob/dave/julia/leo) → reviewerTokenFor()
- eve-solo (selfApproveBlocked test) тоже → reviewerTokenFor() чтобы
достичь self-approve check, иначе forbidden_role срабатывает раньше
Maker callsites (alice/carol/frank/ivan/kate) остаются на tokenFor()
без reviewer role — backend гейтит только approve/reject методы.
Fix для 4 failures в pipeline 6898:
- happyFlow_submitApprove_recordLiveAndOutboxEvent
- rejectFlow_keepsDraft_noLiveRecord
- selfApproveBlocked_409
- rejectWithoutComment_400