The mailcowtemplate claim: which mechanism replaces the stripped attribute
Status: RULED and SHIPPED: mechanism (c), a declared per-user attribute. §8 SUPERSEDES §4 and §5: read it first. §4(c) rejected the mechanism that shipped, and it was answering a question the owner was not asking; §8.1 says why, §8.2 says what the ruling forces about the NAME, and §8.4 names a half nothing on this page had spotted.
CORRECTED 2026-08-04. Then read §7. §2, §3.3 and §3.4 of this page were written from upstream’s Keycloak guide without reading the pinned mailcow source, and each got something wrong: the template re-apply on an existing mailbox is gated by neither
import_usersnorlogin_provisioning, so “withimportUsersfalse, nothing consults a template” (§3.3) is false; auto-create is gated bylogin_provisioning, not Import Users (§2); and §3.4’s open question is now answered. §7 states the corrected semantics with file:line, retracts the claim thatdefault_templatesubstitutes for the Attribute Mapping feature, and records what shipped. §1, §4, §5 and §6 stand as written; the mechanism ranking and the recommendation of (a) are unaffected.Line citations into
apps/mailcow/sso.plug.yamlbelow are stale:2b151ca10inserted ~30 lines of comment and themappers/templateskeys ahead of thedata:block, and the change in §7 inserts more. Read them as names, not offsets;serverUrl(cited as:27) is at:41, andimportUsers/mailpasswordFlow(cited as:33/:32) are at:47/:46.
Baselines. shc origin/main d934af851, ce origin/main 9c805ce.
Live measurements were taken read-only against the bitspur leader
37.27.215.210, container master_default_keycloak-keycloak-1, Keycloak
26.6.1 (image tag 2f319aef), one image behind ce HEAD’s pin
ad8e8366 (26.7.0, builtin/keycloak/vars.yaml:76). Nothing measured
depends on that delta; where it could, §4(d) says so.
The recommendation in one line: mechanism (a) (the mailcow sso plug
renders an oidc-hardcoded-claim-mapper on the client it already mints)
because the legacy value was a constant for all 22 users, so a hardcoded
claim is not a simplification of the old behaviour, it is an exact
reproduction of it. But land it as part of wiring mailcow into corp, not
before: today there is no mailcow client in corp at all, and SHC’s mailcow
plug has never configured a Keycloak IdP on any estate (§3.2).
1. Archaeology: what the legacy realm had, and why the migration dropped it
Section titled “1. Archaeology: what the legacy realm had, and why the migration dropped it”Established from the legacy bitspur Keycloak dump
(/var/tmp/shc-kc/backup/postgres__bit_keycloak.dump) and the migration
manifest (/var/tmp/shc-kc/dry/doc/manifest.txt); restated here so this page
stands alone.
- OIDC client
mail.bitspur.com(a77c218e-7a09-4f42-ab51-7a76b6f72b8c), confidential, root/base/redirecthttps://mail.bitspur.com, the mailcow instance. - A protocol mapper on it,
mailcow_template(bacfec02-0c87-45e5-aa1b-ef21bbeb26d4), typeoidc-usermodel-attribute-mapper, configuser.attribute=mailcow_template,claim.name=mailcow_template,jsonType.label=String, and, decisively,userinfo.token.claim=true,id.token.claim=false,access.token.claim=false. The claim was emitted in the userinfo response only, never in an ID or access token. - A per-user attribute
mailcow_templateon ~22 users, and every single one held the identical value"default". No user ever had a second template. - The 2026-08-03 migration into
corpstripped it from every user, recorded asSTRIP-ATTR <user>: mailcow_template (corp has no unmanaged-attribute policy).
1.1 Why it existed there and cannot exist here
Section titled “1.1 Why it existed there and cannot exist here”The legacy server was Keycloak 22.0.5 (migration_model.version in the
dump), realm main. That tree carries zero kc.user.profile.config
rows; the legacy realm had no declarative user profile at all. On 22 an
arbitrary per-user attribute needed no declaration and no policy; it simply
persisted. The attribute was not configured to be allowed, it was allowed by
the absence of enforcement.
corp runs 26.6.1, where the declarative user profile is enforced. Measured
live, all three realms (master, default, corp) declare exactly five
attributes:
username email firstName lastName walletsand none of the three carries an unmanagedAttributePolicy key at all
(GET /admin/realms/<r>/users/profile, zero occurrences in each). Absent
means DISABLED. So the strip was not a migration choice that could have
gone the other way with a flag flip. It was the only outcome available
without first changing the realm’s attribute policy.
wallets is worth naming because it looks like precedent and is not SHC’s:
it comes from the mp1 wallet SPI bundled in the SHC Keycloak image, the
same bundle that registers the siww-rule-mapper protocol mapper seen live,
and the wallets / wallet-addresses / wallet-rules client scopes in
corp. Neither repo declares it: grep -rn wallets over ce is empty, and
RealmSetup.java (shc keycloak/spi/src/main/java/org/selfhostedcloud/keycloak/events/RealmSetup.java)
contains no user-profile write. SHC has no user-profile writer anywhere:
zero hits for users/profile or unmanagedAttributePolicy in either
tree. That fact sets the cost of mechanism (c).
2. What upstream mailcow actually does with the claim
Section titled “2. What upstream mailcow actually does with the claim”From mailcow’s own Keycloak guide
(docs.mailcow.email/manual-guides/mailcow-UI/u_e-mailcow_ui-keycloak/):
- “The user has an attribute
mailcow_templatewith the valuedefault, which can be retrieved from the User Info Endpoint.” mailcow reads it from/userinfo, matching the legacy mapper’s userinfo-only posture exactly. - The value selects a mailbox template (quota, ACLs) via mailcow’s own Attribute Mapping table.
- Auto-create is conditional: “If a user does not exist in mailcow and logs
in via the mailcow UI, the user will be automatically created, provided
that a matching attribute mapping is configured”, i.e. only under Import
Users. (Wrong: the gate is
login_provisioning(functions.inc.php:2968), a separate setting.import_usersgates only the sync cron (keycloak-sync.php:174). §7.5.) - For an existing mailbox: “Each time a user logs in via the mailcow UI, mailcow checks if the assigned template has changed.”
The consequence that decides this page: mailcow reads a claim in a
userinfo response. It has no way to know, and no reason to care, whether
that claim came from a user attribute, a hardcoded mapper, a script, or a
group. Any mechanism that puts mailcow_template: default into
/userinfo for the mailcow client is behaviourally identical to the legacy
setup. The key inference holds.
3. Necessity verdict: not established, and three independent reasons why
Section titled “3. Necessity verdict: not established, and three independent reasons why”This is not “probably fine”. Each of the following is sufficient on its own to make the claim inert today.
3.1 There is no mailcow client in corp
Section titled “3.1 There is no mailcow client in corp”Live, GET /admin/realms/corp/clients:
account account-console admin-cli affine broker hulyrealm-management security-admin-consoleshc-access shc-cli shc-forward-auth shc-pat shc-swaggerNo mail.*, no mailcow. corp holds 31 users and mailcow_template
appears on zero of them. Nothing in corp is wired to mailcow, so no
claim on any client reaches mailcow.
3.2 SHC’s mailcow plug has never configured a Keycloak IdP
Section titled “3.2 SHC’s mailcow plug has never configured a Keycloak IdP”apps/mailcow/sso.plug.yaml:27 sets
serverUrl: ""A literal empty string, not a vars reference. Nothing populates it:
the only injection on the sso plug render path is
injectDerivedKeycloakIssuer (ce modules/app/integration_render.go:1312),
which fills vars.keycloak.issuer and nothing else. serverUrl therefore
renders empty on every deployment, and the plug’s own job guard at
apps/mailcow/sso.plug.yaml:60-63 reads:
if [ -z "$${SERVER_URL}" ]; then echo "No Keycloak server URL configured, skipping" exit 0fiSo configure-keycloak-oidc soft-skips unconditionally. SHC-packaged
mailcow has never had Keycloak SSO active. This is a latent defect
independent of this decision, and it is a prerequisite for any mechanism
here: a template claim on a client that mailcow was never told to talk to
does nothing.
3.3 The one path that requires a template is off by default
Section titled “3.3 The one path that requires a template is off by default”WRONG. Corrected in §7.2. The last sentence below does not hold. The template re-apply on an existing mailbox reads
mapperson every login and is gated by neitherimport_usersnorlogin_provisioning. What is true is narrower and is stated in §7.5: nothing consults a template today because the whole configure job soft-skips (§3.2).
apps/mailcow/sso.plug.yaml:33 sets importUsers: "false" (and :32
mailpasswordFlow: "false"). Per §2 the template is strictly required for
auto-create / periodic sync; existing mailboxes only get a
template-changed re-check. With importUsers false, nothing consults a
template.
3.4 What is not established from this side
Section titled “3.4 What is not established from this side”ANSWERED in §7.3 for the absent-claim question: with a non-empty
mappersrow and no claim,array_searchreturns false, the re-apply is skipped and login proceeds. Theidentity_providerhalf below is still unread.
Upstream does not document what happens when the claim is absent for an
existing mailbox: whether the template re-check no-ops or errors. Nor could
the legacy mailcow’s own identity_provider row be read: the rescued backup
set holds only postgres__bit_keycloak.dump (no mailcow MariaDB dump), so
whether the legacy instance actually ran with Import Users on is
unknown. If it did not, the legacy attribute was already decorative on
its own estate.
4. The four candidate mechanisms, measured
Section titled “4. The four candidate mechanisms, measured”First, what the platform can express today.
A plug cannot declare protocol mappers, and does not need to. The
keycloak sso socket’s plug schema (ce builtin/keycloak/sso.socket.yaml:11-16)
is exactly four fields (realm!, clientId!, clientSecret,
redirectUris), and its create-oidc-client job (:100-217) builds the
client body at :161/:163 and reconciles at :205/:207 with no
protocolMappers key on any path. There is no mapper grammar.
But a consumer plug can run an arbitrary job with the provider’s admin
credentials, and one already creates a protocol mapper. ce
modules/app/plug_jobs.go:43-62 parses jobs.post_deployment[*] with
context / image / service / command / environment, and :195-220
supports context: service and context: container. shc
apps/netbird/sso.plug.yaml:67-124 is the precedent, verbatim in shape:
context: container,image: "{{ vars.images.curl }}"(:68-69); the job container inherits the deployed stack’s networks, including the__shc_int_*edge to the provider, so it reaches the admin API at the socket’shostname:port(:56-60);- it reads
integration.socket.data.adminUser/adminPasswordwith| default('')(:72-74) and soft-skips with printed instructions when the provider exposes no admin API;apps/external-oidcshares this socket stem; - it
POSTs to/admin/realms/$REALM/clients/$CID/protocol-mappers/models(:116-118), idempotent by mapper name (:112), tolerating201/409(:119).
There is also module-side precedent for the same REST call: ce
modules/auth/keycloak_admin.go:794-800 (shc-swagger), :861-867
(shc-cli), :931-937 (shc-pat) and modules/auth/forward_auth_client.go:176-182
each create an oidc-audience-mapper on an SHC-internal client.
Two shapes are not expressible and one is decorative:
- A plug-side
schema:block is ignored.apps/mailcow/sso.plug.yaml:14-23declares one; nothing reads it. Only the socket’sschema.plugis consumed: for required-field validation, forSecretPlugFields(modules/app/integration_render.go:1425), and for the vapp cleanup lint. The mailcow plug’sschema:documents intent and enforces nothing. - Plug
post_deploymentfailures are non-fatal but loud (cemodules/app/plug_jobs.go:19-22). A failed mapper job logs and the install proceeds. Acceptable here (a missing template claim degrades to no template, not no login), but it means a mapper job is not a gate.
Live capability check, GET /admin/serverinfo on the bitspur leader:
| Mapper | Registered? |
|---|---|
oidc-hardcoded-claim-mapper | yes |
oidc-usermodel-attribute-mapper | yes |
oidc-audience-mapper | yes |
siww-rule-mapper (mp1) | yes |
oidc-script-based-protocol-mapper | no |
| any group-attribute → claim mapper | no (only oidc-group-membership-mapper, names only) |
oidc-hardcoded-claim-mapper’s declared config properties, live:
claim.name (required), claim.value, jsonType.label
(String/long/int/boolean/JSON), id.token.claim (default true),
access.token.claim (default true), userinfo.token.claim (default true),
introspection.token.claim, access.tokenResponse.claim,
lightweight.claim.
That property set reproduces the legacy mapper’s emission posture exactly:
userinfo.token.claim=true with the other three false.
(a) The sso plug renders a hardcoded-claim mapper: RECOMMENDED
Section titled “(a) The sso plug renders a hardcoded-claim mapper: RECOMMENDED”Available today, zero platform change. ~30 lines in one file
(apps/mailcow/sso.plug.yaml), copied in shape from
apps/netbird/sso.plug.yaml:67-124, posting:
{"name":"mailcow_template","protocol":"openid-connect", "protocolMapper":"oidc-hardcoded-claim-mapper", "config":{"claim.name":"mailcow_template","claim.value":"default", "jsonType.label":"String","userinfo.token.claim":"true", "id.token.claim":"false","access.token.claim":"false", "introspection.token.claim":"false"}}Cost. One catalogue file; no ce change; no new grammar; no realm-wide
surface. Per-app by construction; a realm with no mailcow gets nothing.
Idempotent by name. Soft-skips against external-oidc. Bounded blast
radius: worst case the mapper is absent and mailcow sees no template.
Caveats. (1) §3.2’s serverUrl defect must be fixed in the same change
or the mapper is pointless. (2) Make the value a var
(vars.keycloak.mailcowTemplate | default('default')) so a second template
is a --var away; that is one line, not machinery, and it is the honest
hedge against the constant turning out not to be constant. (3) Non-fatal
failure semantics per above.
(b) Bake it into the keycloak builtin: REJECT
Section titled “(b) Bake it into the keycloak builtin: REJECT”A hardcoded claim has to live on a client or a client scope. Realm-wide
means either every client in every realm emits mailcow_template (absurd),
or the keycloak module gains knowledge of a mailcow client, app knowledge
pushed into the platform. The code it would touch is the realm provision
script that runs on every realm reconcile on every estate (the
buildShc*Fragment family in ce modules/auth/keycloak_admin.go), where the
blast radius of a bug is estate-wide SSO. All of that to serve one app that
is not installed. Reject.
(c) A per-user attribute set at user-creation time: REJECT
Section titled “(c) A per-user attribute set at user-creation time: REJECT”Establishing which of the two enablers is needed: either works mechanically, and both are net-new.
- Declare it in the user profile:
PUT /admin/realms/corp/users/profileadding amailcow_templateattribute. Keeps validation and admin-console behaviour tidy, affects only the declared attribute. - Set
unmanagedAttributePolicy:ENABLED/ADMIN_VIEW/ADMIN_EDITre-admits arbitrary undeclared attributes realm-wide. What that affects: any attribute becomes writable on all 31 corp users, unvalidated;ENABLEDadditionally exposes them in user-facing forms and the account console. It also removes the filter that produced this decision; the strip that surfaced the question would have silently succeeded instead of being recorded. And it does not by itself put anything in a token: aoidc-usermodel-attribute-mapperis still required on top.
So (c) is strictly (a) plus a policy or profile change plus a
provisioning step. And SHC has no user-profile writer at all (§1.1); it
would be net-new platform machinery, landing in a seam already occupied by
SHC’s own ShcUserProfileProviderFactory
(shc keycloak/spi/.../seats/ShcUserProfileProviderFactory.java:23-45,
:65-73, :134), which wins the default-provider election over Keycloak’s
declarative-user-profile and delegates to it by id; confirmed live, the
user-profile SPI reports both declarative-user-profile and seats
providers. Plus a user-creation-time attribute setter in modules/user.
All of that buys per-user variation that no user has ever used: 22 of 22
held "default". This is the textbook case the no-speculative-machinery
doctrine exists to refuse.
(d) Role- or group-driven: REJECT, and two of the three are not available
Section titled “(d) Role- or group-driven: REJECT, and two of the three are not available”- Hardcoded-claim mapper on a conditionally-assigned client scope.
Available: corp already carries the standard client-scope set plus the mp1
wallets/wallet-rulesscopes. But it is (a) with one extra object, and it only pays off when several clients need the same claim. Exactly one client ever will. - A group with a default attribute. Not available. Measured: the live
mapper registry offers only
oidc-group-membership-mapper, which emits group names; there is no group-attribute → claim mapper registered on this server, and Keycloak does not fold group attributes into the user attributes thatoidc-usermodel-attribute-mapperreads. Would need an SPI. (corp’s two groups/Adminand/Employeedo both carry"attributes":{}live, so there is nothing to read even if a mapper existed.) - A script mapper. Not available, and expensive to make available.
oidc-script-based-protocol-mapperis not registered;SCRIPTSis listed live underdisabledFeatureswith"type":"PREVIEW","enabled":false. Enabling it means a--features=scriptsonkc.sh build; shckeycloak/docker/Dockerfile:87runs it bare and neither the Dockerfile norbuiltin/keycloak/compose.yamlsetsKC_FEATURES; therefore a rebuild of the SHC Keycloak image and a move of the immutable digest pin at cebuiltin/keycloak/vars.yaml:76, whose own comment says a broken image there is an estate-wide SSO outage. To emit a constant. Reject hard. (This is the one item where the 26.6.1-vs-26.7.0 delta could theoretically differ; it does not; the Dockerfile at shc HEAD still passes no features flag, so the newer image has SCRIPTS off too.)
Scoreboard
Section titled “Scoreboard”| Mechanism | Available today? | Files touched | Realm-wide surface | Buys per-user variation? |
|---|---|---|---|---|
| (a) plug hardcoded-claim mapper | yes | 1 (shc catalogue) | none | no, correctly |
| (b) keycloak builtin | yes | ce modules/auth realm script | all realms, all estates | no |
| (c) per-user attribute | no | ce modules/user + new profile writer + realm policy | yes (if via policy) | yes, unused |
| (d) client scope | yes | 1, +1 object | none | no |
| (d) group attribute | no | needs an SPI | n/a | n/a |
| (d) script mapper | no | image rebuild + digest pin move | estate-wide risk | yes, unused |
5. Recommendation and what it takes
Section titled “5. Recommendation and what it takes”Rule (a), and sequence it behind mailcow actually being wired.
The reasoning is one sentence: because the value was a constant for all 22 users, a hardcoded claim is not a downgrade from the legacy behaviour but a faithful reproduction of it, and (a) is the only mechanism whose cost is confined to the app that needs it.
Implementation, in order:
- Fix
serverUrl(§3.2):apps/mailcow/sso.plug.yaml:27. Without it nothing downstream matters. Either derive it from the socket’spublicUrl+basePaththe wayapps/gitea/sso.plug.yamlbuilds its discovery URL, or make it avars.keycloak.*reference. This should land whatever the ruling on the claim is. - Add one
jobs.post_deploymententry toapps/mailcow/sso.plug.yaml, modelled onapps/netbird/sso.plug.yaml:67-124:context: container,image: "{{ vars.images.curl }}"; env fromintegration.socket.data.{hostname,port,basePath,adminUser,adminPassword}andintegration.plug.data.{realm,clientId}; soft-skip when the admin credentials are empty; look up the client id,GET protocol-mappers/models,POSTthe body in §4(a) when absent, accept201/409. - Value as a var:
claim.valuefromvars.keycloak.mailcowTemplate | default('default'). - Cover it in
apps/mailcow/tests/tests.bats.
Roughly 30 lines, one file, one repo. No ce change, no new grammar, no platform surface, nothing to migrate.
And the honest position on timing: do not land steps 2–4 before mailcow is connected to a realm. There is no mailcow client in corp (§3.1), SHC’s mailcow SSO has never been active anywhere (§3.2), and the one path that needs a template is off by default (§3.3). Building the mapper now is machinery for a consumer that does not exist. Step 1 is worth landing on its own merits.
How the sibling capability lane tips this
Section titled “How the sibling capability lane tips this”That lane establishes whether SHC will provision/import mailcow users from Keycloak at all. Each answer, and where it lands:
- Import Users stays off / mailcow is not re-wired to corp → the claim is not needed at all. Ship step 1, record this page, build nothing else. (a) remains the mechanism if it is ever needed.
- mailcow will run with Import Users or Periodic Full Sync against corp → land (a) exactly as specified; step 1 becomes a hard blocker, not a tidy-up.
- Different mailboxes need different quotas/ACLs (more than one template) → still (a), with the value carried per deployment by the var in step 3.
- Per-USER template variation is required → this is the only answer
that forces (c), and it requires the lane to name at least two specific
users needing different templates. No such user has ever existed on this
estate: 22 of 22 held
"default".
6. Observed in passing: not this lane’s decision
Section titled “6. Observed in passing: not this lane’s decision”Two live observations against the open “keycloak realm backfill is inert:
default realm ABSENT and master has no shc-access on BOTH estates”
finding. On bitspur, both halves now read otherwise:
- realm
defaultexists (0 users) and carriesshc-access,shc-cli,shc-pat,shc-forward-auth,shc-swagger; - realm
masterdoes carryshc-access, plusshc-cli,shc-forward-auth,shc-swagger,traefik,openobserve, and thecorp-realm/default-realm/master-realmclients.
That does not close the finding (it was recorded of both estates and promanager was not measured here), but the bitspur half of it appears stale. Not chased further.
Separately: the live estate runs keycloak image 2f319aef (26.6.1) while ce
HEAD pins ad8e8366 (26.7.0), consistent with the release not yet having
been rolled to the estates.
7. CORRECTION 2026-08-04: the Attribute Mapping semantics, read from source
Section titled “7. CORRECTION 2026-08-04: the Attribute Mapping semantics, read from source”§2–§3 above were built from upstream’s Keycloak guide. The guide describes
the feature but not its gates, and this page inferred the gates wrongly. Every
claim in this section is from mailcow-dockerized tag 2026-07a (the tag
apps/mailcow/compose.yaml:18-33 clones), cited file:line, and each was
reproduced by executing the decision expressions in php:8.2-cli.
7.1 mappers / templates are two PARALLEL arrays
Section titled “7.1 mappers / templates are two PARALLEL arrays”The INDEX of a claim value in mappers selects templates[index]. That is
why the lookup is an array_search returning an index, and it is the same
pattern on all three doors:
| Door | lookup | use of the index |
|---|---|---|
| UI login | functions.inc.php:2904 | :2932 |
| mailpassword (dovecot delegates IMAP/POP3/SMTP/SIEVE here) | functions.auth.inc.php:564 | :574 |
| periodic-sync cron | keycloak-sync.php:171 | :204 |
Upstream states the contract in the shipped API spec,
data/web/api/openapi.yaml:6023-6028: “Each element corresponds to the
respective index in the templates array.” Its example is
mappers: ["small_mbox","medium_mbox"] / templates: ["small","medium"]
(:6110-6111).
Empty arrays on each door. array_search($v, []) is always false, so:
UI login skips the re-apply at :2926 and proceeds to the active-checks at
:2947; login succeeds; mailpassword skips at :568 and returns
'user'; auth succeeds; the sync cron logs “No matching attribute
mapping” and continues (:175/:200). Empty is a valid OFF, not a
degraded ON.
The absent-row shape is the one that kills logins. With no mappers row,
$iam_settings['mappers'] is null and array_search raises
TypeError: Argument #2 ($haystack) must be of type array, null given, which
prerequisites.inc.php:146-163 swallows into “An unknown error occured”. That
was 2b151ca10’s bug and its fix is correct.
A LENGTH MISMATCH re-creates the absent-row shape, and mailcow reports
success. identity_provider('edit') array_filters each side and writes
the two rows only when the counts still match
(functions.inc.php:2646-2648); otherwise it writes neither and returns
normally. array_filter drops falsy elements, so a mapper value of "" or
"0" mismatches the counts by itself. Reproduced: (["a","b"], ["A"]) →
not written; (["0","b"], ["A","B"]) → not written.
7.2 The re-apply on an EXISTING mailbox is ungated
Section titled “7.2 The re-apply on an EXISTING mailbox is ungated”This is the claim §3.3 got wrong. On a match with a mailbox that already
exists, both login doors call mailbox('edit', 'mailbox_from_template')
(functions.inc.php:2929, functions.auth.inc.php:571), and neither call
sits behind login_provisioning or import_users. The provisioning gate is
after the existing-mailbox return: :2968 is past the return true at
:2964, and :582 is past the return 'user' at :578. Reproduced with
login_provisioning => false: a matching claim on an existing mailbox still
yields “RE-APPLY template”.
7.3 What the re-apply overwrites: feature and hazard, named
Section titled “7.3 What the re-apply overwrites: feature and hazard, named”functions.mailbox.inc.php:3708-3775 rewrites, from the template:
mailbox row (quota, name, active, force_pw_update, force_tfa,
sogo_access, imap_access/pop3_access/smtp_access/sieve_access/
eas_access/dav_access) at :3761, TLS policy :3763, quarantine
notification + category :3765/:3767, rate limit :3769, and the whole
user ACL :3771. So: yes, a match overwrites mailbox settings from the
template on every login. That is the capability at stake.
It is idempotent only while nobody touches the mailbox. :3724-3728
short-circuits when the mailbox’s stored attribute_hash still equals
sha1 of the template’s attributes. But an ordinary mailbox edit (the
mailcow UI, the mailbox API) passes no attribute_hash, so :3152 stores
'' and :3444 writes it. Hand-tuning a template-mapped mailbox therefore
clears the hash, and the user’s next login silently reverts the tuning.
Reproduced: hash intact → short-circuits true; hash cleared → false.
Which is it? Both, and the distinction is the operator’s intent, not a property of the code. Central management is the feature; silent reversion of per-mailbox tuning is the same mechanism seen from the other side. Its worst trait is the shape of the trigger: it fires only after a human deliberately tuned something, so it cannot be discovered by installing and watching.
With no match the re-apply is simply skipped and login proceeds, the prior lane’s claim, confirmed, and the answer to §3.4’s open question.
7.4 RETRACTION: default_template is not a substitute, and is not in the guide
Section titled “7.4 RETRACTION: default_template is not a substitute, and is not in the guide”Two things this page and sso.plug.yaml asserted are false.
It is CREATION-ONLY. Upstream says so twice in its own shipped artefacts:
openapi.yaml:6020-6022: “If no matching Attribute Mapping exists for a
User, the default template will be used for creating the mailbox, but not
for updating the mailbox”, and the UI tooltip string
data/web/lang/lang.en-gb.json:233-234, identically. The code agrees: it is
read at exactly three sites, functions.inc.php:2978,
functions.auth.inc.php:594 and keycloak-sync.php:176, and every one is
inside a branch that has already decided to CREATE. It can never reach
mailbox('edit', 'mailbox_from_template'). So it does not reach the same
outcome as a mapping, and “strictly better substitute” is retracted.
It is not documented in the Keycloak guide at all. Fetched
docs.mailcow.email/manual-guides/mailcow-UI/u_e-mailcow_ui-keycloak/
(102,109 bytes): default_template and “default template” appear zero
times, while “Attribute Mapping” appears 5 times and mailcow_template
twice. It is documented in the shipped OpenAPI spec and the UI tooltip
above, so it is a supported setting rather than an undocumented code path,
but an operator following mailcow’s own Keycloak instructions will never
meet it. Worth stating plainly because it was offered here as the
replacement for the documented mechanism.
sso.plug.yaml additionally claimed default_template “ALSO covers the
mailpassword door” where a protocol mapper would not. The premise is right
and the conclusion does not follow: the mailpassword door reads the template
from the Keycloak user record (functions.auth.inc.php:563,
$user_res['attributes']['mailcow_template'][0]), not from the /userinfo
claim, so a hardcoded protocol mapper indeed cannot feed it, but
default_template does not cover that door either, because its only use
there (:594) is behind the provisioning gate at :582. A protocol mapper
covers the UI door only. Nothing SHC can render today covers the mailpassword
door. That is a real limit on mechanism (a) and §4/§5 should be read with
it.
7.5 What is and is not reachable today
Section titled “7.5 What is and is not reachable today”loginProvisioning is false, importUsers is false, periodic_sync is never
sent (coerced to 0 at functions.inc.php:2572). On top of that (and this
dominates everything else), serverUrl is a literal empty string in the
plug’s data: block, and serverUrl appears nowhere in ce’s builtin/
or modules/app/ trees, so nothing populates it and no --var can: the
configure-keycloak-oidc job hits its own guard and exit 0s on every
deployment. Net:
| reachable today? | |
|---|---|
any identity_provider row written by SHC | no; the job soft-skips |
| template re-apply on an existing mailbox | no (needs a non-empty mappers), but needs only that, not provisioning |
default_template | no; needs loginProvisioning=true and a served IdP |
| the sync cron’s use of either | no; import_users and periodic_sync both 0 |
So SHC-packaged mailcow has never had Keycloak SSO active anywhere (§3.2
established this and it is confirmed here), and 2b151ca10’s “broke every
SSO login” describes a latent defect rather than an observed outage. The fix
still belongs in the tree: it is what makes the first working serverUrl not
break.
7.6 Can SHC render the claim source? A partial gap, not a blocker
Section titled “7.6 Can SHC render the claim source? A partial gap, not a blocker”Two separate answers, because a prior lane’s finding is right about the socket and does not generalise:
- The
ssosocket cannot. cebuiltin/keycloak/sso.socket.yaml’s plug schema is four fields (realm!,clientId!,clientSecret,redirectUris) andprotocolMapper/protocol-mappersappear nowhere in the file. There is no mapper grammar, and adding one is a ce change this lane must not make. - A consumer plug job can. §4 already established this and it still
holds:
apps/netbird/sso.plug.yamlposts a protocol mapper to the admin REST API from a plugpost_deploymentjob. So mechanism (a) is buildable entirely in shc; no ce feature is missing for it.
Not built here, for the reason §5 gives (a consumer that does not exist) plus 7.4’s new one: it would cover only the UI door.
7.7 What shipped
Section titled “7.7 What shipped”Posture (c), var-driven, defaulting to the posture the evidence supports: OFF.
apps/mailcow/vars.yamlgainsssoTemplateMap: "", declared inapps/mailcow/app.yaml(the vars/schema parity guard is what caught its absence). Set it toclaimValue=Templatepairs to opt in:--var ssoTemplateMap=default=Default.apps/mailcow/sso.plug.yamlbuilds mailcow’s two parallel arrays from that one var. Empty rendersmappers: []+templates: [], byte-identical to what2b151ca10shipped, so the default behaviour is unchanged and nothing about a release in flight is affected.- One var carries both arrays deliberately: pairs make the §7.1 length
mismatch inexpressible, rather than guarded. The job additionally
refuses, non-zero, a pair with no
=, an""/"0"side (whatarray_filterdrops), or a quote/backslash (what would makejson_api.php:70-77reject the whole body). - The job prints
Attribute Mapping OFF/ON: <mappers> -> <templates>, so which posture ran is legible in the job log.
OFF is the honest default because SHC has no source for the claim: no
mailcow client in corp (§3.1), the per-user attribute stripped (§1), no
mapper on the minted client (§7.6). Shipping mappers: ["default"] with no
claim source would produce exactly the failure mode to avoid (a config that
looks configured and silently does nothing) because array_search(null, ["default"]) is false. And per §7.3 the capability it buys is one an
operator should choose, not inherit.
Asserted at the rendered, executed job body in both suites; each renders
the real plug file through ce’s own pipeline, runs it under /bin/sh with curl
stubbed, and parses the JSON curl was handed:
apps/mailcow/tests/tests.bats: the pre-existingsso_assert_post_bodyharness, extended to take the expectedmappers/templatespair and to require the job to announce which posture ran. Its permanent negative control had gone vacuous: its mutation anchored on the literal"mappers": [], which stopped existing when the arrays became shell-built, so itsgrep -vmatched nothing and it was re-running the unmutated file. Re-anchored on the key.tests/unit/modules/app/mailcow_template_mapping_test.go: new, and the one that pins the shipped OFF posture, the ordering of the pair, the refusals, and theserverUrlsoft-skip.
15 mutations of the plug file were each confirmed to turn a named Go assertion
red, and 8 to turn the intended bats test red. Two of those mutations initially
survived and both were real assertion gaps, since fixed: a glob in the
template map was tested in an empty directory (pathname expansion only rewrites
a word that matches something, so the set -f guard was unprovable), and the
bats refusal check accepted “declined to post” as equivalent to “exited
non-zero”, which a warn-only job would satisfy while leaving SSO
unconfigured. The behaviour was additionally exercised under busybox ash
(the container’s shell, not the test host’s dash) for all seven postures.
7.8 Still owed, unchanged by this lane
Section titled “7.8 Still owed, unchanged by this lane”CLOSED 2026-08-04 by a later lane; see §9.
serverUrlis populated, the client secret is real, and mailcow’s Keycloak IdP now activates. §3.2 and §7.5 describe the state before that; read them as history.
serverUrl (§3.2, §7.5) is the standing defect: until it is populated, every
setting on this page is inert. It is deliberately not fixed here;
populating it activates mailcow’s Keycloak IdP on any deployment carrying an
sso edge, which is a behaviour change that does not belong in a change
landing beside a release cut.
TestMailcowSSOJobSoftSkipsWithoutServerURL pins the current state and is
written to fail loudly when it is fixed, so the fix cannot land silently.
8. SUPERSEDED 2026-08-04: the owner ruled mechanism (c), and §4(c) was answering a different question
Section titled “8. SUPERSEDED 2026-08-04: the owner ruled mechanism (c), and §4(c) was answering a different question”Read this before §4 and §5. The owner’s requirement is “I just want to be able to have admins activate mail or not”, with “only 1 specific default template”. Mechanism (c) (a per-user attribute, declared) shipped. Mechanism (a) is now recorded as incapable of the requirement, not merely second-best. Three corrections, each independently sufficient.
8.1 A hardcoded claim cannot express “this user, not that one”
Section titled “8.1 A hardcoded claim cannot express “this user, not that one””§4(a)‘s whole case is that the legacy value was a CONSTANT, so a hardcoded
mapper reproduces the legacy behaviour exactly. That is still true and still
beside the point: a hardcoded claim emits the same value for every user of
the client, so with mappers: ["default"] every user matches and every user
gets a mailbox. It can reproduce the legacy estate, where all 22 users were
meant to have mail. It cannot express an admin’s per-user decision at all.
§4(c) rejected (c) because it “buys per-user variation that no user has ever used”. The rejection is sound about template variation (one template is still the only template), and wrong about the axis the owner asked for. The variation being bought is set vs not set, which is the feature.
8.2 The mailpassword door reads the RAW attribute, so the name is forced
Section titled “8.2 The mailpassword door reads the RAW attribute, so the name is forced”§7.4 established that a protocol mapper covers the UI door only. Read from
source, the reason is stronger than “a different door”: functions.auth.inc.php
:515-528 GETs
{server_url}/admin/realms/{realm}/users?email=…&exact=true with a
service-account admin token and :563 indexes
$user_res['attributes']['mailcow_template'][0], the raw Keycloak user
record, by a hardcoded key.
Consequences, both new:
- A declared attribute serves BOTH doors; a hardcoded mapper serves one.
Declared attributes are in that
attributesmap by construction. - An app-neutral name is foreclosed. A mapper can rename any attribute into
any claim, so a neutral name works on the UI door, and nothing can rename
the key that door indexes. A neutral name therefore costs either a
permanently-dead mailpassword door or a dual-write of one value into two
attributes.
mailcow_templateis kept for that reason, and undeclaring it is deleting one entry fromshcDeclaredUserAttributes.
That door is still not reachable today: mailpasswordFlow is false, it also
needs a per-user mailcow_password hash (:539-553) and a service account on
the mailcow client that may read users, and SHC provisions neither. It is named
because it decides the NAME, not because it works.
8.3 unmanagedAttributePolicy was never the only enabler, and §1.1’s
Section titled “8.3 unmanagedAttributePolicy was never the only enabler, and §1.1’s”“SHC has no user-profile writer” is now false
§4(c) priced (c) as “(a) plus a policy or profile change plus a
provisioning step”, listing the realm-wide unmanagedAttributePolicy beside the
narrow profile declaration. Only the narrow one shipped: one PUT /admin/realms/{r}/users/profile adding one attribute. No arbitrary undeclared
attribute becomes writable, nothing appears on a user-facing form
(permissions is admin/admin), and the strip that produced this page would
still be recorded for any other attribute.
There is now a user-profile writer: ce modules/auth/keycloak_admin.go,
declaredUserAttributesFragment, appended to BuildProvisionRealmScript for
TENANT realms only. It is a read-modify-write (a PUT REPLACES the whole
configuration, so a canonical body would undeclare wallets and break the mp1
SPI estate-wide), and it WARNs rather than fails on every error path, because it
sits on the reconcile path §4(b) calls estate-wide-SSO territory.
ShcUserProfileProviderFactory sits in front of that write and every user
create. It delegates getConfiguration/setConfiguration straight through and
gates only unbound-user profiles, so declaring an attribute neither disarms the
seat cap nor is blocked by it, proven, with the attribute in the payload and in
the configuration, in keycloak/spi/src/test/java/.../seats/DeclaredUserAttributeTest.java.
Flipping the attribute on an existing user is an UPDATE, which is ungated, so it
works on a free-tier realm that is already at the three-account cap.
8.4 default_template is the “or not”, and Default breaks the feature
Section titled “8.4 default_template is the “or not”, and Default breaks the feature”The half neither §4 nor §7 named. default_template is read ONLY where no
mapper matched (functions.inc.php:2977-2989,
functions.auth.inc.php:593-603), i.e. for exactly the users an admin did not
activate:
default_template | a user with no mailcow_template |
|---|---|
| non-empty | a mailbox is created for them anyway |
| empty | refused, “No matching attribute mapping was found” |
So ssoDefaultTemplate silently decides whether the switch is opt-IN or
opt-OUT, and §7.7 shipped it as Default. It is now "". This was latent
(loginProvisioning is false, so the branch is unreachable), and it is fixed
BEFORE anyone flips provisioning on, which is the flip that makes the switch do
anything for a user who has no mailbox yet.
8.5 What shipped, and what is still owed
Section titled “8.5 What shipped, and what is still owed”- ce:
mailcow_templatedeclared in every tenant realm: optional, empty legal, one legal valuedefault,permissionsadmin/admin,annotations.inputType: select. Keycloak’sDeclarativeUserProfileProviderwraps every declared validator withIGNORE_EMPTY_VALUE=true(26.7.0DeclarativeUserProfileProvider.java:275→:463-465), which is why optional + anoptionsvalidator does not make mail-less users unsaveable. - shc:
ssoTemplateMapdefaults to the one pairdefault=Default;ssoDefaultTemplatedefaults to""; a newmailcow-template-claim-mapperplug job mints anoidc-usermodel-attribute-mapperon the client ce already mints, emitting the claim into/userinfoONLY, the legacy mapper’s posture exactly. §7.6’s finding stands: thessosocket still cannot mint a mapper, and a consumer plug job still can, so this needed no ce grammar. ssoLoginProvisioningstays false. Measured, not assumed: with it false a mail-less user is refused with “Auto-create users on login is deactivated” (functions.inc.php:2968-2975); with it true anddefault_templateempty they are refused with “No matching attribute mapping was found” plus aclear_session(). Both are a cleanlogin_failed; the second is more specific but not enough more graceful to justify changing who may create a mailbox by default. It is the flip that makes activation create a mailbox, so an estate that wants the feature needs--var ssoLoginProvisioning=true.- §7.8’s
serverUrldefect is now closed; see §9, which landed alongside this. It dominated everything on this page while it stood: untilserver_urlwas populated, every mailcow-side setting here was inert because the configure job soft-skipped before reaching its POST. The Keycloak side (the declared attribute) was live regardless; an admin could flip it on the next reconcile pass whether or not mailcow ever read it. It is now read.
9. RESOLVED 2026-08-04: serverUrl derives from the socket, and a second blocker was found beside it
Section titled “9. RESOLVED 2026-08-04: serverUrl derives from the socket, and a second blocker was found beside it”The design fork §5 left open is resolved in favour of the SOCKET, not a
vars.keycloak.* reference. Two facts decided it:
- A
vars.keycloak.serverUrlwould be a per-consumer restatement of a fact the provider already publishes.builtin/keycloak/sso.socket.yamladvertisespublicUrl,basePath,hostnameandport; a plug consuming that socket should read the provider’s own address. Restating it per app is how one app ends up pointed at a different Keycloak than the one its client was minted in. - It is the established convention, not an invention. Of the 32 sso-plugged
apps,
apps/gitea,apps/windmillandapps/nextcloudbuild their Keycloak base from exactlyintegration.socket.data.publicUrl+.basePath, with.hostname/.portas the overlay fallback. mailcow now uses the same four keys and the same trailing-slash handling.
No ce change is required. The socket already publishes every field needed,
and apps/external-oidc publishes the same four for provider substitution
(basePath: "" deliberately, since its issuer is already absolute). The
earlier framing (“the socket does not advertise a usable base URL”) was wrong
in a specific way worth recording: the socket does, but the plug data:
block cannot see it. Plug data renders against vars/stack/environment/tenant
plus the host callables and nothing else (ce
modules/app/integration_render.go:508-527), while a plug job’s env renders
against integration.socket.data.* (ce modules/app/plug_jobs.go:128-137).
That is why serverUrl left data: entirely instead of being given a source.
The shape server_url must take, from the pinned source. It is the BARE
base URL (scheme + host + relative path prefix), and never /realms/<realm>,
because the bundled provider appends that itself:
Stevenmaguire\OAuth2\Client\Provider\Keycloak::getBaseUrlWithRealm() returns
authServerUrl . '/realms/' . realm (Keycloak.php:190-192) and every endpoint
is built on it (:117-119 auth, :129-131 token, :141-143 userinfo, :182
logout); authServerUrl is server_url (functions.inc.php:2807).
mailcow’s own code agrees (:2683, :3097, :3120), and
functions.auth.inc.php:517 uses {server_url}/admin/realms/{realm}/users,
the ADMIN REST base, which is why the relative path prefix has to be carried
(KC_HTTP_RELATIVE_PATH moves /realms and /admin under it). The shipped
spec states it in one line: “server_url: The base URL of your Keycloak server”,
example https://auth.mailcow.tld (openapi.yaml:5999-6001, :5955).
The second blocker, not previously named: clientSecret: "". An empty client
secret does not weaken the config, it switches the provider OFF;
identity_provider('init') requires server_url AND realm AND client_id AND
client_secret AND redirect_url AND version to be truthy
(functions.inc.php:2797-2798), so $iam_provider stays null, index.php:47
leaves the login page with no SSO button, and functions.auth.inc.php:509 kills
the mailpassword door, while isset('') being true means mailcow accepts
the edit and answers success. It could never have been filled at runtime either:
ce’s mint-and-return channel folds the generated secret into
integrations.sso.socket.* for the compose render only
(modules/app/integration_render.go:892-914), never into ic.PlugData, which
is what the post_deployment job renders from. Fixed the way every other
sso-plugged app does it (keycloak.clientSecret: "ref+vault://keycloak_client_secret?autogen"), so ce sets that secret on
the client.
And the response guard §6 declined. It is now possible and it landed, in the
stronger form: the job refuses a "type":"danger"/"type":"error" payload at
HTTP 200 (json_api.php sets no failure status on this route,
:1847-1862), requires an explicit success marker, and then reads the stored
settings back through GET /api/v1/get/identity-provider (:1535, admin-only,
GET-only per :358) and compares ten load-bearing fields against what it sent.
The read-back is what catches the one failure the response cannot show: a
mappers/templates count mismatch is array_filter()ed into neither row
while the function still returns true (:2646-2648). Five coerced fields are
deliberately not compared (mailpassword_flow, import_users, periodic_sync,
sync_interval, ignore_ssl_error); their stored form is not what was sent,
so asserting them would fail on a correct config.
On the claim source: §8 landed the mechanism (a declared per-user attribute
plus mailcow-template-claim-mapper) in the same window as this change, from a
sibling lane. The two are complements and neither works alone: §8 gives mailcow a
claim to match on, and this gives mailcow an address to be configured at. Before
this change ssoTemplateMap’s parser, its four refusals and its OFF posture were
all dead code behind a job that never ran; §8’s default pair now reaches mailcow
because the job does.
Still owed: a live proof. Everything above is established from the pinned
mailcow source (2026-07a), reproduced in php:8.2-cli-alpine for the wire
format and in the pinned ghcr.io/mailcow/nginx:1.30.4-1 (busybox ash/sed/tr,
the shell the job actually runs in) for the read-back comparison. No SHC estate
runs mailcow with an sso edge, so no browser has completed a login through
this. Two adjacent gaps found while reading and deliberately left alone:
mailpasswordFlow (hardcoded "false") needs a Keycloak service account for
its client_credentials grant (functions.inc.php:3119-3123) and ce’s
create-oidc-client sets no serviceAccountsEnabled, so turning it on would
fail; and edit/identity-provider-test is unusable as a probe for the same
reason.