Skip to content
SHC Docs

2026-08-06: RBAC role matrix, explicit deny, and the permission-filtered menu

  • Status: Accepted (owner-ruled semantics), NOT YET IMPLEMENTED. This document is the specification two builders code against: one in ce, one in shc.
  • Supersedes: nothing. It is the first written ruling on the role vocabulary.
  • Scope: the role grammar (ce modules/user), the authorisation gate (ce modules/auth), the user-facing app list (ce modules/user), and the Traefik menu injector (shc traefik/plugin).
  • Date: 2026-08-06. Measured against shc origin/main @ 4b61191dd (go.mod pin ce v0.0.24-0.20260806173530-8fe9cbaa5756) and the ce working checkout @ e8f077b. Every file:line below is from those trees.

Section 7, THE CONTRACT, is the only section a builder must obey literally. Sections 1–6 are the reasoning that produced it and the rulings it depends on.


Every claim in this section was read out of the code on 2026-08-06 and carries a file:line. Nothing here is inferred.

All SHC roles are Keycloak client roles on the shc-access client (ce modules/auth/types.go:44), bootstrapped per realm.

RoleWhere it is createdRealms
tenant:managekeycloak_admin.go:749 (BuildProvisionRealmScript), keycloak_admin.go:1084 (BuildEnsureAccessClientScript)every realm
tenant:readsameevery realm
audit:readsameevery realm
events:readsameevery realm
platform:manageextraRoleBranch (keycloak_admin.go:673-675, spliced at :763), system realm only; BuildEnsureAccessClientScript adds it for mastermaster / system realm only
stack:<name>lazily at install; subsystems/impl/stack_reconcile_keycloak.go:82 calls the keycloak admin client’s CreateAccessRole, name from auth.StackRoleName (keycloak_admin.go:55, "stack:" + name)the deployment’s tenant realm

There is no tenant:use role and no bare tenant role in the bootstrap set. This matters for the migration (§6): granting tenant:use today fails, because AssignRole pre-checks that the role exists (ce daemon/user_keycloak_adapter.go:139-160).

ce modules/user/service.go:16 (ParseRole) splits on :. The last segment is the verb iff it parses as a verb name and at least one non-verb segment remains. Verb tiers (modules/user/types.go:49):

VerbUse = 1 < VerbRead = 2 < VerbOperate = 3 < VerbManage = 4

HasPermission (service.go:91) is a flat union with an exact scope match plus one cross-class exception:

for _, r := range roles {
if len(r.Scope) == 1 && r.Scope[0] == "platform" && r.Verb >= VerbManage { return true }
if scopeMatches(r.Scope, required) && r.Verb >= verb { return true }
}

scopeMatches (service.go:64) requires equal length and equal segments. There is no prefix subsumption, no narrowing, no precedence, and no deny anywhere in the tree (grepped: the token deny appears only in error strings and in tenant_denied audit reasons).

  • applyMasterRealmPrivilege (ce modules/auth/service.go:425) appends platform:manage to any identity whose token resolves in the master realm. No grant is involved; the realm is the privilege.
  • On platform:manage, ValidateBearer prepends Permission{Resource:"*", Scopes:["*"]} (service.go:397 and the JWKS fast-path twin at service.go:556).
  • NewLocalUser (types.go:283), the UDS-socket caller, carries platform:manage plus the same wildcard permission, and Authorise returns nil for it before any check (service.go:989).

1.4 What actually consumes a stack:<name> role

Section titled “1.4 What actually consumes a stack:<name> role”

Exactly two call sites:

  • ce modules/auth/router.go:326: the forward-auth probe: u.HasPermission(stackRoleName(mapping.StackName), "use"); failure is 403 {"reason":"missing_role"}.
  • ce modules/logs/router.go:699, inside requireStackReadPermission (declared at :686, called at :167 and :195), which accepts tenant:read or stack:<name>:read.

That is the whole list.

1.5 The honest state of the write verbs: worse than the brief claimed

Section titled “1.5 The honest state of the write verbs: worse than the brief claimed”

The task brief stated that “modifying a deployment needs tenant:manage”. That is not what the code does. Measured:

Route fileGate actually mounted
modules/app/router.go:103-133: shc.stack.install, .update, .uninstall, .scale, .protect, .unprotect, .lease_renew, .lease_clear, shc.system.plan, shc.system.complete, shc.system.keycloak_reset_admin_password, DELETE /api/resource/Stack/{name}none: global Authenticate only, plus a per-handler requireTenantAccess (router.go:823) that checks tenant membership and nothing else
modules/stack/router.go:90-98: shc.stack.start, .stop, .restart, .exec, shc.container.restart, .dry_run, .config, .inspect, .logsnone
modules/backup/router.go:104-172: backup.create, .restore, .recover, .restore_from_file, .export, .import, .schedule.setnone (only .mount / .umount / .mounts / .detect_snapshot / shc.volume.mount* / shc.pod.mount carry platform:manage)
modules/shell/router.go:51-60: container execnone
modules/logs/router.go:53-56stack:read
modules/repo/router.go:161tenant:manage
modules/{cluster,dns,storage,config,task,node,tenant}/router.go, audit purge, auth service-clientplatform:manage

Therefore: any authenticated identity in tenant realm T can today install, update, uninstall, scale, exec into, back up and restore every stack in T. Gap (1) in the brief, “no per-stack MANAGE role”, is real, but its consequence is not “manage is too broad”, it is “manage is not required at all”.

1.6 A live contradiction between the gate and the app list

Section titled “1.6 A live contradiction between the gate and the app list”

ce modules/user/service.go:490 computes tenantBlanket := HasPermission(parsed, "tenant", needed) and, when true, lists every deployment in the tenant as accessible. The forward-auth gate (§1.4) never consults a tenant role. So an identity holding a tenant-tier role is told by GET /api/user/apps that it can use every app, and is then 403’d by the gate on every one of them. §3 rules this away.

1.7 A resource-resolution hazard the new gates must not inherit

Section titled “1.7 A resource-resolution hazard the new gates must not inherit”

resolveResource (ce modules/auth/service.go:958) builds the permission resource from reqctx.Stack, which WithRequestScope (modules/auth/observability_middleware.go:38) stamps from the client-supplied X-SHC-Stack header. Unlike the tenant stamp (line 44-48) it is not validated against the caller. A middleware-level per-stack gate keyed off that header would authorise against a stack the caller names rather than the stack the handler acts on. modules/logs already avoids this by checking in the handler against the resolved stack name (logs/router.go:699). §7.1.4 makes that the rule.


Scope × verb, exactly as ruled by the owner. All roles remain client roles on shc-access in the identity’s own realm.

RoleTierRealmMeaning
platform:managen/amaster onlyPlatform root. Everything, everywhere, undeniable (§4 R-a).
tenant:managemanageanyFull admin of this realm’s estate: every stack at manage, plus user/role administration, repo administration, tenant-scoped config.
tenant:operateoperateanyEvery stack in the realm at operate. (new role name; the tier already exists in the grammar)
tenant:readreadanyEvery stack in the realm at read.
tenant:useuseanyMembership. Every stack in the realm at use. (new role, see §6)
stack:<n>:managemanageanyFull control of ONE deployment. (new)
stack:<n>:operateoperateanyLifecycle of ONE deployment. (new)
stack:<n>:readreadanyRead-only of ONE deployment. Already honoured by modules/logs.
stack:<n>:useuseanyBrowser access to ONE deployment through the SSO gate.
stack:<n>useanyLegacy spelling of stack:<n>:use. Identical after parsing; see §5.
tenant:denyn/aanyExplicit deny of the whole realm for this identity. (new)
stack:<n>:denyn/aanyExplicit deny of ONE deployment for this identity. (new)
audit:read, events:readreadanyUnchanged module-level reads; orthogonal to this matrix.

Three rulings embedded above, each justified:

R-1: the tenant tier is a blanket at the same verb tier. tenant:V grants V on every stack in the realm. This resolves §1.6 by making the gate agree with the app list rather than the other way round, and it is what makes deny load-bearing: broad grant at the tenant tier, per-stack carve-outs by deny. Without it, tenant:use would be a role that grants literally nothing and the migration in §6 would be a no-op.

R-2: deny is NOT a verb tier. It is a distinct trailing marker segment. A builder MUST NOT add "deny" to ParseVerb (ce modules/user/types.go:77). If deny became a verb it would be ordered against VerbUse..VerbManage by the r.Verb >= verb comparison at service.go:100, and a deny role would start granting every tier at or below its rank. Deny is total at its scope and carries no tier: “deny manage but keep use” is expressed by not granting manage.

R-3: the deny spelling for a tenant is tenant:deny, not tenant:<t>:deny. A realm is a tenant, roles never cross realms (FetchPolicies resolves in the token’s own realm; ce modules/auth/types.go:452-461), and mergeRoles only ever sees the issuing realm’s roles. A role in realm A naming tenant B would be unenforceable by construction and would create a second, lying source of truth for tenancy. Cross-realm deny is therefore not expressible; see §4 R-c.

Amended 2026-10-29 (FZ-8104, Clay’s review rv_5fcce69a07559b6c). A realm still is its tenant, and an unqualified role still means only the tenant of the realm’s name. What changes is that a role may now name another tenant explicitly, spelled <T>/<role> on the realm’s shc-access client (public/tenant:manage, public/stack:wiki:deny), and it counts in tenant T only while the platform-admin-only config key auth.trusted_realms maps the realm to T (corp=master:read,public). That mapping is the single source of truth for which tenants a realm reaches, so the “lying second source” objection above no longer applies: a qualified role naming an unmapped tenant is inert, and doctor keycloak.trusted-realms reports it. The rule:

  • roles for tenant T = (T == R ? R’s unqualified roles : nothing) + R’s T/... roles with the prefix stripped, only while R→T is mapped; the deny sweep and the allow union then run unchanged on that set, so T/tenant:deny is the realm-wide deny for T;
  • an entry’s verb cap (master:read) lowers every allow it carries to that tier; denies are never capped;
  • a qualified role never confers platform: master/platform:manage is dropped, and platform root stays per person in auth.platform_admins;
  • the mapping is read only from config, never from a token claim;
  • a node that predates the grammar parses public/tenant:manage as the scope public/tenant, which matches nothing, so a mixed-version roll grants nothing extra;
  • the forward-auth gate (§5, apps) is unchanged: an app signs in through its own tenant’s realm, and a caller of another realm is refused cross_tenant.

A request that names a mapped tenant in X-SHC-Tenant acts as that tenant for the request: its roles are the stripped set, Keycloak policy permissions (realm-local) are dropped, and audit records keep the realm the token came from.

The “today” column is measured (§1.5). The “ruled” column is what the ce builder must wire. Rows marked NEW GATE are routes that have no permission gate today and gain one.

Operation (route)Gate todayRuled gate
Browser SSO to the app host (GET /api/auth/forward-auth)stack:<n>:usestack:<n>:use (unchanged), plus the tenant blanket per R-1
Appear in the launcher menunot filtered at alleffective verb ≥ use
shc.stack.status, GET /api/resource/Stack/{name}, shc.stack.services, shc.stack.config, shc.stack.inspect, shc.stack.dry_run, shc.stack.protect_show, shc.stack.lease_shownonestack:<n>:read NEW GATE
shc.logs.get, shc.stack.logs.stream, shc.stack.logsstack:readstack:<n>:read (unchanged in effect)
shc.stack.start, .stop, .restart, shc.container.restart, shc.job.run, shc.job.cancel, shc.backup.create{,_async}, shc.backup.verify, shc.schedule.enable, .disablenonestack:<n>:operate NEW GATE
shc.stack.install, .update, .uninstall, .scale, DELETE /api/resource/Stack/{name}, .protect, .unprotect, .lease_renew, .lease_clearnonestack:<n>:manage NEW GATE
shc.stack.exec, shc.container.exec, /internal/containers/{id}/exec*nonestack:<n>:manage NEW GATE: a shell in the container is root on the app
shc.backup.restore*, .recover*, .export, .import, .group, .ungroup, .restore_group, .schedule.set, .schedule.unset, .syncnonestack:<n>:manage NEW GATE: restore overwrites data, export removes it from the estate
shc config set at stack/deployment scopeplatform:managestack:<n>:manage NEW GATE (widening a too-narrow gate)
user/role administration (/api/user/{create,delete,grant,revoke,list,reset-password})tenant:manage via ResolveTargetTenant (modules/user/service.go:294)unchanged
repo administrationtenant:manageunchanged
shc.system.plan, .complete, .keycloak_reset_admin_password, cluster / dns / storage / node / tenant / task / backup-mount / auth service-clientplatform:manage (mostly) or noneplatform:manage, and the three shc.system.* routes gain the gate they lack NEW GATE

The one-sentence answer to “what does stack:<n>:manage allow that stack:<n>:use does not”: install, update, uninstall, scale, protect, lease, exec, restore, export and stack-scoped config, for that one deployment. use allows only walking through the SSO door of that one deployment and seeing it in the menu. Today the honest answer is “nothing, because none of those routes are gated at all”; this lane is what makes the sentence true.

Wiring the NEW GATE rows tightens routes that are open today to any tenant member. On the live estate the corp realm has no role mappings at all (§6), so the day these gates land, every non-master caller loses those routes until §6’s migration runs. The migration is therefore a prerequisite, not a follow-up. Land order: evaluator → /api/user/effective-apps → menu → migration → then the NEW GATE rows.


One function, in ce modules/user (the module that owns the grammar; auth imports user, never the reverse). Both the gate and the app list call it, so there is exactly one walk.

# ---------------------------------------------------------------------------
# EffectiveVerb(identity, tenant, stack) -> NONE | USE | READ | OPERATE | MANAGE
# ---------------------------------------------------------------------------
EffectiveVerb(id, tenant, stack):
# (0) transport bypass: the UDS local root. Undeniable.
if id.isLocal: # auth.NewLocalUser
return MANAGE
roles = ParseRoles(id.rawRoles) # user.ParseRoles, unchanged
# (1) platform root. Undeniable. Checked BEFORE any deny. See R-a, R-b.
if IsPlatformAdmin(roles): # user.IsPlatformAdmin
return MANAGE
# (2) realm binding. A non-platform identity only ever reasons about
# its own realm; roles never cross realms.
if tenant != "" and tenant != id.realm:
return NONE
# (3) DENY SWEEP. Any matching deny at ANY scope wins, full stop.
# Runs BEFORE the allow union, and returns immediately.
# There is no "more specific wins" and no tier on a deny.
for r in roles:
if r.isDeny and r.denyScope == ["tenant"]: return NONE
if r.isDeny and r.denyScope == ["stack", stack]: return NONE
# (4) ALLOW UNION. The maximum verb over every matching allow.
v = NONE
for r in roles:
if r.isDeny: continue
if r.scope == ["tenant"]: v = max(v, r.verb) # blanket, R-1
if r.scope == ["stack", stack]: v = max(v, r.verb)
return v
Authorised(id, tenant, stack, required):
return EffectiveVerb(id, tenant, stack) >= required
# Parsing a deny marker. NOTE: deny is NOT a verb (R-2).
ParseDeny(raw):
parts = split(raw, ":")
if last(parts) != "deny": return (nil, false)
scope = parts[:-1]
if scope is empty: return (nil, false) # bare "deny" is not a role
if any segment empty: return (nil, false)
return (scope, true)

Properties the builder must preserve, each of which a test must pin:

  1. Deny is not tiered. stack:x:deny denies use and manage alike.
  2. Deny does not need a matching allow. A deny on a stack the identity was never granted is a legal, inert-but-harmless grant.
  3. Broad deny beats narrow allow. tenant:deny + stack:x:manage → NONE. This is the AWS-IAM shape and the explicit inverse of “most specific wins”.
  4. The union is a max, not a first-match. stack:x:read + tenant:operate → operate on x.
  5. The walk is total and side-effect free. No IO, no keycloak call, no cache.

R-a: deny does NOT apply to platform:manage. Platform root is undeniable.

The evaluator returns MANAGE at step (1), before the deny sweep. Reasons:

  • platform:manage is only reachable from the master realm, and every master identity gets it synthesised with no grant behind it (applyMasterRealmPrivilege, service.go:425). A deny that bound it would have to be revoked through SHC’s own API, which the deny has just closed. The failure mode is an estate with no working administrative path, recoverable only by raw Keycloak admin access on the box.
  • A denied platform root cannot fix the deny, cannot uninstall the app, cannot reach /api/user/revoke (which itself needs tenant:manage in the target realm, and that route’s gate would also be denied).

Stated risk, accepted: deny is therefore useless as containment for a rogue or compromised platform admin. Containment for that threat is identity removal (disable the master-realm user, rotate the credential, rotate ForwardAuthClientSecretRef), not authorisation. An operator who wants a root that cannot see one app must use a tenant-realm identity with per-stack grants, not a master identity. This is the same residual risk applyMasterRealmPrivilege’s own doc comment already records (service.go:422-424); the deny feature does not widen it and must not be advertised as narrowing it.

R-b: deny does NOT apply to the master-realm auto-privilege either.

Same rule, same step (1), and it must be deliberate rather than emergent: a master identity carrying stack:x:deny still gets MANAGE. The builder MUST NOT “fix” this by moving the deny sweep above the platform check. The privilege is derived from the realm the token was verified against, not from a grant, so there is nothing for the deny to subtract; the identity would simply re-acquire platform:manage on its next token.

R-c: a deny in tenant realm T does not bind an identity that reaches T via platform:manage.

This follows from R-a, and additionally from mechanics: role resolution (mergeRoles, service.go:864; permissionsFor, service.go:683) reads roles from the token’s own realm. A platform admin’s token is issued by master, so a stack:x:deny sitting in realm corp is never loaded and never seen. The evaluator’s early return makes this explicit instead of accidental. Cross-realm deny is not expressible; an operator must not be told otherwise. The shc user grant path should refuse --tenant corp <anything>:deny against a master-realm user with a clear message rather than silently writing an inert role. (Builder: this refusal is a nice-to-have, not a gate; see §7.5.)

R-d: stack:x:manage + stack:x:deny on the same identity → deny wins.

Step (3) precedes step (4) and returns. No tie-break, no “the more specific grant wins”, no ordering dependence on how Keycloak happens to serialise the role list. A test must assert both role orderings produce NONE.

R-e: the wire MUST NOT distinguish deny from absence-of-allow.

Both produce a byte-identical refusal:

  • forward-auth: 403 {"allow":false,"reason":"missing_role","host":…,"required_role":"stack:<n>","user":…} (the existing shape (ce modules/auth/router.go:327-334), unchanged). There is no new reason value. required_role stays because it names the stack the caller just typed into the URL bar; it reveals nothing the caller did not already supply.
  • API routes: X403900NOPERM(required[0], resource) for both, unchanged.
  • /api/user/effective-apps (§7.1): a denied app is absent, exactly as a never-granted app is absent. It is never listed with a "denied" marker or a verb:"none". There is no badge for deny.

Rationale: a distinguishable deny is an oracle. An identity with no grants could enumerate the estate’s stack names by probing hosts and reading which refusals said “denied”; the presence of a deny proves the stack exists and that someone thought this identity worth excluding. Absence and denial must be indistinguishable to the party being refused.

The operator-facing side does distinguish, because it must be debuggable: the existing audit emission A403001PERMDNY (service.go:1028) gains one field, decision: "deny" | "no_allow", and the deny case additionally carries matched_role. That is an operator-only stream (audit:read / events:read) and never reaches the refused caller.


4. Decision: backwards compatibility for bare stack:<name>

Section titled “4. Decision: backwards compatibility for bare stack:<name>”

Ruling: stack:<n> ≡ stack:<n>:use. This is not a new mapping rule; it is what the existing parser already does.

Proof, traced through ce modules/user/service.go:16 and :91:

ParseRole("stack:openhands")
parts = ["stack", "openhands"] # no empty segments -> not rejected
len(parts) >= 2, so try the trailing segment as a verb:
ParseVerb("openhands") -> (VerbUse, ok=false) # types.go:77, not a verb name
ok == false, so the branch at service.go:33 is NOT taken:
verb stays VerbUse, scope stays ["stack", "openhands"]
=> Role{Scope: ["stack","openhands"], Verb: VerbUse}
ParseRole("stack:openhands:use")
parts = ["stack", "openhands", "use"]
ParseVerb("use") -> (VerbUse, ok=true) # types.go:82
=> Role{Scope: ["stack","openhands"], Verb: VerbUse} # IDENTICAL

Both parse to the same Role value. The forward-auth check (modules/auth/router.go:325-326) asks HasPermission(roles, "stack:openhands", "use"), which splits the required scope to ["stack","openhands"], matches scopeMatches exactly, and passes on VerbUse >= VerbUse.

Consequence for the live estate: the only real grant on it, shc user grant clayrisser stack:openhands, keeps working with no migration, no re-grant, and no dual-read shim, before and after this lane. The evaluator in §3 consumes the output of the same ParseRoles, so step (4) sees scope == ["stack","openhands"], verb == USE and returns USE, which satisfies the gate’s required = USE. A test must pin this exact string.

The same argument covers tenant:use ≡ bare tenant, should any realm carry the bare spelling.

4.1 The deny roles are inert on today’s binaries; pre-provisioning is safe

Section titled “4.1 The deny roles are inert on today’s binaries; pre-provisioning is safe”
ParseRole("stack:openhands:deny")
ParseVerb("deny") -> (VerbUse, ok=false) # "deny" is not in the verb switch
=> Role{Scope: ["stack","openhands","deny"], Verb: VerbUse}

That three-segment scope can never satisfy scopeMatches against the two-segment ["stack","openhands"] (service.go:64 compares lengths first), and StacksWithPermission (service.go:117) only collects len(r.Scope) == 2. Same for tenant:deny → ["tenant","deny"] vs required ["tenant"].

Therefore a deny role created and assigned in Keycloak before the evaluator ships grants nothing and denies nothing. Deny roles may be provisioned ahead of the code. This is the single most useful backcompat property in this document and it is why R-2 (deny must never become a Verb) is a hard rule: the day deny enters ParseVerb, every pre-provisioned stack:x:deny silently becomes an allow at whatever tier deny sorts to.

A stack literally named use, read, operate, manage or deny mints a role (StackRoleName, keycloak_admin.go:55) that the parser re-reads as a tenant-class role: ParseRole("stack:manage") → Scope ["stack"], Verb manage. It grants nothing today (no required scope is bare ["stack"]) but it is a trap-in-waiting. Builder MUST: reject those five names as deployment names at install time, with a coded error. Low effort, permanent.


5. Decision: the migration for the corp realm

Section titled “5. Decision: the migration for the corp realm”

Current state (from the brief, NOT verified by this document; see §9): the corp realm’s Admin group carries no role mappings, so every gated app 403s for browser users; the only real grant on the estate is shc user grant clayrisser stack:openhands.

Ruled target posture: tenant:manage for the Admin group, tenant:use for everyone else.

Under R-1, tenant:use grants browser access to every gated app in the corp realm. That is a deliberate widening and it is what the ruled posture asks for. If any corp app must not be reachable by all corp staff, the carve-out is an explicit stack:<n>:deny on the individuals excluded (§5.5), or skip tenant:use entirely and grant stack:<n>:use per person. Choose before step 3.

Also: do not add these humans to the master realm. Any master identity is platform root (§1.3) and undeniable (R-a).

Terminal window
# Environment. KC_BASE is the browser-facing keycloak base URL for this estate
# (path-mode estates include the /keycloak prefix, the same base the daemon's
# PublicURL() derives, ce modules/auth/service.go:280).
KC_BASE=https://<estate-host>/keycloak
KC_ADMIN=admin
KC_ADMIN_PASSWORD='<from the vault: ref+vault://keycloak_admin_password>'
REALM=corp
kcadm.sh config credentials --server "$KC_BASE" \
--realm master --user "$KC_ADMIN" --password "$KC_ADMIN_PASSWORD"
# 1. The shc-access client must exist in corp (it does if the tenant was minted
# through TenantService.create). Capture its internal id.
CID=$(kcadm.sh get clients -r "$REALM" -q clientId=shc-access \
--fields id --format csv --noquotes)
test -n "$CID" || { echo "shc-access missing in $REALM; run the realm provision first" >&2; exit 1; }
# 2. Inventory what is there now. Expect tenant:manage, tenant:read,
# audit:read, events:read, plus one stack:<name> per installed app.
kcadm.sh get "clients/$CID/roles" -r "$REALM" --fields name --format csv --noquotes

5.3 Create the roles that do not exist yet

Section titled “5.3 Create the roles that do not exist yet”

tenant:use is not in the bootstrap set (§1.1), and AssignRole rejects a grant of a role that does not exist. Create it first.

Terminal window
kcadm.sh create "clients/$CID/roles" -r "$REALM" -s name=tenant:use
# idempotent alternative: a 409 here means it already exists, which is fine:
# curl -s -o /dev/null -w '%{http_code}' -X POST \
# "$KC_BASE/admin/realms/$REALM/clients/$CID/roles" \
# -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
# -d '{"name":"tenant:use"}'
# Verify (must print tenant:use):
kcadm.sh get "clients/$CID/roles/tenant:use" -r "$REALM" --fields name

The permanent fix is to add tenant:use to the bootstrap loops so future realms carry it; see §7.5, ce task C6. Until that ships, this step is required per realm.

Terminal window
# --- Admins -> tenant:manage ------------------------------------------------
AGID=$(kcadm.sh get groups -r "$REALM" -q search=Admin \
--fields id,name --format csv --noquotes | awk -F, '$2=="Admin"{print $1}')
test -n "$AGID" || { echo "no Admin group in $REALM" >&2; exit 1; }
kcadm.sh add-roles -r "$REALM" --gid "$AGID" \
--cclientid shc-access --rolename tenant:manage
# --- Everyone else -> tenant:use -------------------------------------------
# Create a Members group if there is not one already.
kcadm.sh create groups -r "$REALM" -s name=Members || true
MGID=$(kcadm.sh get groups -r "$REALM" -q search=Members \
--fields id,name --format csv --noquotes | awk -F, '$2=="Members"{print $1}')
kcadm.sh add-roles -r "$REALM" --gid "$MGID" \
--cclientid shc-access --rolename tenant:use
# Make Members a DEFAULT group so newly-created users land in it.
# kcadm has no first-class verb for this; the REST call is authoritative:
# PUT /admin/realms/{realm}/default-groups/{groupId}
curl -sS -o /dev/null -w '%{http_code}\n' -X PUT \
"$KC_BASE/admin/realms/$REALM/default-groups/$MGID" \
-H "Authorization: Bearer $TOKEN" # expect 204
# Default groups apply to NEW users ONLY. Existing users must be joined:
for UID in $(kcadm.sh get users -r "$REALM" --fields id --format csv --noquotes); do
kcadm.sh update "users/$UID/groups/$MGID" -r "$REALM" -n
done

5.5 Carve-outs, if step 5.1 said you need them

Section titled “5.5 Carve-outs, if step 5.1 said you need them”
Terminal window
# Per-stack deny for one person (role must exist first, same as tenant:use):
kcadm.sh create "clients/$CID/roles" -r "$REALM" -s name=stack:payroll:deny
UID=$(kcadm.sh get users -r "$REALM" -q username=someone \
--fields id --format csv --noquotes)
kcadm.sh add-roles -r "$REALM" --uusername someone \
--cclientid shc-access --rolename stack:payroll:deny
# Elevating one person on one app (no deny needed):
shc user grant alice stack:openhands:manage --tenant corp

Prefer shc user grant where it applies: it routes through ResolveTargetTenant (authorisation), the role-grant product gate (ce modules/user/role_gate.go), and the audit stream. kcadm bypasses all three and is the break-glass path only.

Terminal window
# a) The mappings are there.
kcadm.sh get "groups/$AGID/role-mappings/clients/$CID" -r "$REALM" --fields name
kcadm.sh get "groups/$MGID/role-mappings/clients/$CID" -r "$REALM" --fields name
# b) A real user's token carries them. resource_access["shc-access"].roles is
# what mergeRoles reads (ce modules/auth/service.go:864).
# Log in as the user through the estate, then:
shc user apps # expect the apps the posture predicts
# c) The gate agrees with the list; this is the §1.6 contradiction closing.
curl -si "$SHC_URL/api/auth/forward-auth" \
-H "X-Forwarded-Host: <one gated app host>" \
-H "Authorization: Bearer $USER_TOKEN" | head -1 # expect HTTP/2 200
# d) clayrisser's legacy grant still works (the §4 proof, live).
curl -si "$SHC_URL/api/auth/forward-auth" \
-H "X-Forwarded-Host: <the openhands host>" \
-H "Authorization: Bearer $CLAYRISSER_TOKEN" | head -1 # expect 200

These commands have NOT been run. They are written from the code and from the Keycloak admin REST contract, not from a transcript. Dry-run 5.3 and 5.4 against a scratch realm before the corp realm.


  • The estate’s write routes stop being open to every tenant member (§2.1). This is the largest behavioural change in the lane and the reason §2.2 fixes the land order.
  • GET /api/user/apps and the forward-auth gate stop disagreeing (§1.6).
  • The menu becomes identity-scoped, which means an anonymous visitor to an ungated app sees no menu at all where today they see the whole tenant’s app list. That is a leak closing, not a regression, but it is visible.
  • Deny gives an operator a carve-out that does not exist today, and does not give them containment of platform root (R-a). The documentation must say so.
  • One evaluator serves the gate, the CLI, and the menu, so a future divergence is a compile error rather than a silent contradiction.

Everything below is binding on the two builders. Field names, paths, status codes and enum values are frozen; anything not stated is the builder’s choice.

New file ce modules/user/effective.go. Exported surface:

// Verb tiers unchanged (types.go). Added:
const VerbNone Verb = 0
// DenyRole is a parsed deny marker. Scope is the denied scope's segments.
type DenyRole struct{ Scope []string }
// ParseDeny parses one raw role string as a deny marker.
// Returns ok=false for anything that is not "<scope...>:deny".
func ParseDeny(raw string) (DenyRole, bool)
// EffectiveVerb implements §3 verbatim. tenant may be "" (skip the realm
// check). stack may be "" (then only tenant-tier allows are considered).
func EffectiveVerb(id Identity, tenant, stack string) Verb
// Identity is the evaluator's input. auth.User and user.User both adapt to it.
type Identity struct {
IsLocal bool
Realm string
RawRoles []string
}

user.HasPermission and user.StacksWithPermission keep their signatures and are reimplemented on top of EffectiveVerb so there is one walk. Their existing tests must still pass unchanged; that is the backcompat gate.

7.1.2 GET /api/user/effective-apps: the endpoint the menu consumes

Section titled “7.1.2 GET /api/user/effective-apps: the endpoint the menu consumes”

This is the single call. The menu never asks per app.

GET /api/user/effective-apps[?host=<hostname>][&tenant=<name>]
Auth: the global Authenticate middleware. Bearer in `Authorization`, or the
`shc_access_token` cookie (auth.CookieAccessToken), or UDS-local.
NOT a self-authenticating path; do NOT add it to
auth.selfAuthenticatingPaths.
Gate: none. RequirePermissions is NOT mounted. The endpoint is self-scoping:
it returns exactly what the caller can reach, and a caller entitled to
nothing gets an empty list with 200. It must never 403 (R-e).
?host= optional. When set, the response is restricted to the tenant that owns
that routed host, and the host's own entry is flagged `current: true`.
An unknown host yields 200 with an empty list (fail closed, no
enumeration).
?tenant= optional, platform admins only. A non-platform caller passing a tenant
other than its own gets X403931USRXTN; this is the ONE 403 the route
may emit, and it is about tenancy, never about a per-app decision.
Headers: Cache-Control: private, no-store
(identity-specific; must never land in a shared cache)

Response 200:

{
"version": 1,
"user": "clayrisser",
"tenant": "corp",
"platform_admin": false,
"apps": [
{
"tenant": "corp",
"environment": "prod",
"stack": "openhands",
"app": "openhands",
"status": "running",
"hosts": ["ai.example.com"],
"url": "https://ai.example.com/",
"verb": "use",
"source": "stack",
"current": true
}
],
"total_count": 1
}

Field rules, all frozen:

FieldRule
version1. Bump only on an incompatible reshape. Additive fields never bump it; consumers ignore unknown fields.
verbone of use, read, operate, manage. The effective verb after the deny sweep. Never none, never deny.
sourceone of platform, tenant, stack, which grant produced verb. Drives the hover text.
appsOnly apps whose effective verb is ≥ use. A denied app and a never-granted app are both simply absent (R-e).
urlhttps://<first host><path>; the client harmonises scheme/port (the plugin already does this; menu.go:385).
currentpresent and true only for the entry matching ?host=; omitted otherwise.
orderingdeterministic: tenant, environment, stack, first host. Same order BuildAppsMenu uses (ce modules/app/apps_menu.go:128).

GET /api/user/apps and /api/user/managed-apps are kept (the CLI’s shc user apps depends on them) and reimplemented over the same evaluator. managed-apps becomes “effective verb ≥ manage”.

ce modules/auth/router.go:325-335: replace the bare u.HasPermission(role, "use") with the evaluator:

if user.EffectiveVerb(id, mapping.TenantName, mapping.StackName) < user.VerbUse {
// response shape UNCHANGED; reason stays "missing_role" (R-e)
}

The 200 response additionally keeps X-SHC-Tenant / X-SHC-Stack (it already sets them, router.go:337-339) and gains one header:

X-SHC-Verb: use | read | operate | manage

so the gate can forward the caller’s verb for this host without a second call.

7.1.4 Per-stack gates: the resolution rule

Section titled “7.1.4 Per-stack gates: the resolution rule”

The NEW GATE rows in §2.1 MUST resolve the stack from the handler’s own target (route param, request body, or resolved deployment row) and MUST NOT use reqctx.Stack / the X-SHC-Stack header, which is client-supplied and unvalidated (§1.7). Follow the shape modules/logs already uses (requireStackReadPermission, logs/router.go:686). Provide one shared helper:

// auth.RequireStack checks the caller's effective verb on a named stack in a
// named tenant. Returns X403900NOPERM on refusal. Call it INSIDE the handler,
// after the target deployment is resolved.
func RequireStack(r *http.Request, tenant, stack string, verb user.Verb) error

auth.RequirePermissions middleware stays for the tenant- and platform-tier routes only.

7.1.5 The launcher script carries the verb

Section titled “7.1.5 The launcher script carries the verb”

ce modules/auth/launcher.go, launcherJS’s apps() reader (launcher.go:153) gains one field:

o={href:a.href, name:…, sub:…, here:…, verb:a.getAttribute('data-shc-verb')||''}

and build() sets a.title = o.name + (o.verb ? ': ' + o.verb : '') plus a small badge span when o.verb is manage or operate. Obey the file’s two encoding gotchas (launcher.go:68-81): no $ anywhere in the payload, no // comments, no newlines in the emitted value. TestLauncherScriptHasNoDollar pins the first.

Measured today: the gate runs first (shcinject.go:316), and on a 200 verdict it deletes gateStripHeaders (auth.go:174) and re-stamps only gateIdentityHeader = X-SHC-User (auth.go:388-390) onto the same *http.Request that finish later hands the injectors as rc.Request (shcinject.go:343, :439). So the injector can already read a gate-verified username. It cannot read the tenant, the stack, or the verb.

Changes:

  1. gateStripHeaders is unchanged (still deletes all four spoofable headers).
  2. On the 200 branch, the gate re-stamps four headers from the verdict response, not one: X-SHC-User, X-SHC-Tenant, X-SHC-Stack, X-SHC-Verb. All four come from the daemon’s response headers; none is client-supplied. Delete-then-set means they remain unspoofable.
  3. RequestContext gains an identity block, populated by the middleware from those same verdict values (not re-read from the request, so an ungated router cannot fake one):
type RequestContext struct {
Request *http.Request
Status Status
Identity *GateIdentity // nil when the router has no gate, or the gate
// did not admit via a verdict
}
type GateIdentity struct {
User string // X-SHC-User
Tenant string // X-SHC-Tenant
Stack string // X-SHC-Stack
Verb string // X-SHC-Verb (this host's verb)
}
  1. The credential is NOT copied into any header. The injector reads it the same way the gate does: Authorization, else the shc_access_token cookie off rc.Request, which is material the upstream app already receives, so this adds no exposure.

menuInjector gains a *menuClient and keeps menuSource.

Inject(rc, body):
1. body lacks launcherMarker -> return body (unchanged)
2. body already has menuMarker -> return body (unchanged)
3. no </body> -> return body (unchanged)
4. rc.Identity == nil -> return body NEW: no gate, no
identity, NO MENU. This is the
deliberate behaviour change in §6.
5. request host not present in apps.json -> return body (unchanged fail-
closed unknown-host rule; also a
free short-circuit that avoids a
daemon call for hosts we do not route)
6. entries = menuClient.Apps(credential, host)
- one GET to <shcURL>/api/user/effective-apps?host=<host>
- same http.Client as the gate (g.trust.client), same CA bundle
- 5s timeout (gateAuthzTimeout)
- cache keyed by (identity, host), TTL 30s (cacheTTL)
- ANY failure -> last good cached value for that key; if none, nil
7. entries empty -> return body (no menu)
8. render and splice before </body> (unchanged mechanics)

Rendering changes in renderMenu:

  • each <a> gains data-shc-verb="<verb>" and title="<label>: <verb>", which is what ce’s launcher JS reads (§7.1.5) and what satisfies the owner’s “reveal the effective verb on hover/long-press”.
  • the aria-current="page" marker now comes from the response’s current flag rather than a host string comparison.
  • everything else, the hidden <nav id="shc-apps-menu">, the wiring script, the escaping helpers, the maxMenuEntries cap, is unchanged.

★ Correction, 2026-08-08: what shipped, and what did not. §6’s consequence (“an anonymous visitor to an ungated app sees no menu at all”) was never implemented: the injected payload carried no credential check, and an anonymous request to an open corp route returned the whole tenant inventory on both estates. That gate now exists, and it is fail-closed on the daemon’s answer rather than on the presence of a cookie (see the CHANGELOG’s Security entry).

Two rendering claims above are also now false. aria-current still comes from the host comparison, not from the verdict’s per-deployment current flag (a deployment answering on two hosts would stamp two tiles, and the flag only exists on the filtered rung; see verdictApp in traefik/plugin/menu.go). And the hidden <nav> is gone: it relied on the hidden attribute alone, which any app rule setting display beats, and it rendered permanently open over Penpot’s login form. The payload is now one inline <script> that builds everything inside a shadow root. data-shc-verb and the title survive, on the anchors that script creates.

Fail-open posture, restated for this path: a daemon that is down means the last cached menu, then no menu. It never means the unfiltered tenant menu. Falling back to the file-derived list would show apps the caller may not open, which is precisely the property this lane exists to remove.

version stays 1. No field is added, renamed or removed. Reasons:

  1. The plugin ignores any file whose version is not 1 (menu.go:199). A bump dark-fails every already-deployed image: the menu vanishes estate-wide until every Traefik is rolled. There is no additive need that justifies that.
  2. Nothing per-identity can live in a file shared by every viewer of every host.
  3. The file keeps two real jobs: it is the host→tenant oracle and the fail-closed unknown-host gate (step 5 above), and it is the ingress projection the daemon already writes.

If a future need appears: add fields (the plugin ignores unknown ones, menu.go:96) and never bump the version.

7.3 Wire-level acceptance tests (both builders)

Section titled “7.3 Wire-level acceptance tests (both builders)”

ce:

  1. ParseRole("stack:openhands") and ParseRole("stack:openhands:use") produce the identical Role, the §4 backcompat pin.
  2. EffectiveVerb with stack:x:manage + stack:x:deny, in both role orders, returns VerbNone (R-d).
  3. tenant:deny + stack:x:manage returns VerbNone (broad deny beats narrow allow).
  4. A master-realm identity carrying stack:x:deny returns VerbManage (R-a/R-b).
  5. ParseVerb("deny") returns ok=false, the R-2 tripwire. If someone adds deny to the verb switch, this test is what fails.
  6. Two identities, one denied and one never granted, produce byte-identical forward-auth 403 bodies (R-e).
  7. /api/user/effective-apps for an identity with a deny omits the app entirely.
  8. /api/user/effective-apps returns 200 + empty list (never 403) for an authenticated identity with no grants.

shc:

  1. Injector with rc.Identity == nil renders nothing.
  2. Injector with an identity but a failing daemon renders the last cached menu, and nothing at all on a cold cache.
  3. Rendered anchors carry data-shc-verb and a title containing the verb.
  4. The gate stamps all four identity headers on a 200 verdict and none of them survives from the client on any other path (extend the existing delete-then-set test).

ce has no CI (memory: ce_never_gets_ci). Every ce change in this lane is verified by bumping the ce pin in an shc worktree and running shc’s auth and unit suites. That run is the gate. Do not push ce without it.

ce:

  • C1 modules/user/effective.go: ParseDeny, VerbNone, EffectiveVerb, Identity; reimplement HasPermission / StacksWithPermission over it.
  • C2 modules/auth/router.go: forward-auth uses the evaluator; add X-SHC-Verb to the 200.
  • C3 modules/user: GET /api/user/effective-apps; rebuild /apps and /managed-apps on the evaluator.
  • C4 modules/auth: RequireStack helper; wire the §2.1 NEW GATE rows in modules/{app,stack,backup,shell,job,schedule,config} after the migration lands.
  • C5 modules/auth/launcher.go: data-shc-verb + title/badge in launcherJS.
  • C6 modules/auth/keycloak_admin.go: add tenant:use (and, if adopted, tenant:operate) to both bootstrap role loops so new realms carry them.
  • C7 modules/auth/service.go:1028: decision + matched_role fields on A403001PERMDNY.
  • C8 reject use|read|operate|manage|deny as deployment names (§4.2).

shc:

  • S1 traefik/plugin/auth.go: stamp four verdict headers; expose GateIdentity.
  • S2 traefik/plugin/injector.go: RequestContext.Identity.
  • S3 traefik/plugin/menu.go: menuClient, the identity-gated inject flow, data-shc-verb rendering.
  • S4 tests 9–12.
  • S5 docs: the menu section of the app-development guide gains the “no identity, no menu” rule.

Verified by reading the code on 2026-08-06 (every file:line in §1, plus): the role bootstrap sets; applyMasterRealmPrivilege; the flat-union evaluator and the total absence of deny; the two consumers of stack:<name>; the fact that the app / stack / backup / shell write routes carry no permission gate; the ParseRole traces in §4 and §4.1; the X-SHC-Stack resolution hazard; the plugin’s gate-then-inject ordering and the shared *http.Request; the apps.json version-mismatch behaviour.

Assumed, taken from the task brief, NOT verified here: the live corp realm’s Admin group has no role mappings; shc user grant clayrisser stack:openhands is the only real grant on the estate. Both would need a live kcadm read against the estate to confirm. The §5 migration commands were written from the code and the Keycloak admin REST contract and have not been executed.