Private infrastructure names, a real hostname, a commented-out internal mirror block, an internal product name, and a reviewer's name in a comment do not belong in a public repository; drop them and replace what needs a stand-in with neutral placeholders. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
19 KiB
OIDC for the Grafana instance (Phase 1)
Cozystack ships one Grafana codebase deployed twice: as
monitoring-system in the platform's cozy-monitoring namespace and as
monitoring in every tenant namespace. Both instances opt in to OIDC
authentication through the same flat selector on the Monitoring CR.
This document covers the operator-facing surface: what the modes mean,
what the chart provisions, and how a user signs in.
The architectural rationale lives in
cozystack/community#24
— in particular why per-tenant Keycloak realms are deliberately
deferred to Phase 2. This Grafana integration follows the same shape
as the tenant kube-apiserver's Phase 1
(cozystack/cozystack#3044),
adapted for a server-side (confidential) OAuth client instead of a
public kubectl one: authentication is wired up by the chart, but
authorization is an operator-supplied users: map reconciled into
the target (Grafana orgs here, ClusterRoleBindings in #3044) by a
chart-owned Job. The chart does not own any directory objects.
Selector
apiVersion: apps.cozystack.io/v1alpha1
kind: Monitoring
metadata:
name: monitoring
namespace: tenant-acme
spec:
oidc:
mode: System # System | CustomConfig | None (default)
users:
- email: alice@acme.example
role: Admin
- email: bob@acme.example
role: Viewer
Three modes:
- None — the only user-facing path is the
grafana-admin-passwordSecret, exposed to the tenant throughpackages/system/monitoring-rd. This is the default; existing instances render byte-identical to before. - System — the Grafana instance trusts the platform
cozyKeycloak realm via a per-instance confidential client. Users are the ones a platform admin already provisioned incozy; the tenant does not manage a directory of its own. - CustomConfig — Grafana trusts a tenant-supplied OIDC issuer
directly.
cozyis not in the path. Use for BYO IdPs (Okta, Auth0, a customer's own Keycloak).
The grafana-admin-password Secret stays a documented break-glass
path in every mode; disable_login_form is not flipped by this
selector. Hardening that further (e.g. locking the form off in
System mode) is a follow-up.
System mode
What the chart provisions, in the release namespace of the Monitoring CR:
-
KeycloakClient named
<namespace>-<release>in thecozyrealm —public: false,directAccess: false. Thesecretfield points at a chart-owned Kubernetes Secret via the EDP-Keycloak$<secret>:<key>syntax so the operator provisions the same confidential secret to Keycloak that Grafana reads at runtime.redirectUrisis locked tohttps://grafana.<host>/login/generic_oauth. -
KeycloakClientScope named
<namespace>-<release>-audiencecarrying anoidc-audience-mapperthat pinsid_token.audto the per-instance clientId. This is the per-instance isolation primitive: a token minted for one Monitoring release is rejected by another's Grafana. -
A Secret
<release>-oidc-clientcarrying a random 32-charclient-secret. Generated on first install (lookup+ random fallback, same pattern aspackages/system/dashboard), preserved across upgrades. -
The Grafana CR's
spec.config.auth.generic_oauthsection wired to the platform realm issuer (cozyby default,authentication.oidc.realmName) + the per-instance audience scope. Two independent gates ride on top of the raw OAuth wiring:Tenant-membership gate — unconditional in System mode. The chart requests the
groupsOIDC scope (already provisioned platform-wide bypackages/system/keycloak-configureas a realm-default KeycloakClientScope with anoidc-group-membership-mapper) and setsallowed_groups = <namespace>-view <namespace>-use <namespace>-admin <namespace>-super-admin groups_attribute_path = groupsgroups_attribute_pathis REQUIRED alongsideallowed_groupson Grafana v11.x+: without it Grafana leaves the extracteduser.Groupsslice empty regardless of what the userinfo endpoint returns, and the gate rejects every login with "user not a member of one of the required groups" — even when the token carries the correct claim (verified end-to-end on a test cluster with Grafana v11.6.15). The JMESPath expressiongroupsreads the top-levelgroupsarray from userinfo, matching the shape Keycloak'soidc-group-membership-mapperemits.The four groups match the KeycloakRealmGroups the tenant chart provisions in the
cozyrealm — seepackages/apps/tenant/templates/keycloakgroups.yaml. Grafana rejects any login whose token does not carry at least one of these groups. This is the isolation primitive that stops tenant-alice from signing into tenant-bob's Grafana even though both authenticate against the same flatcozyrealm. The audience mapper in point 2 protects against replay of a minted token across releases; this gate protects against issuance of a usable token to a caller outside the release's tenant.Users-map contract — active only when
spec.oidc.usersis non-empty. Three additional keys are merged on top:skip_org_role_sync = true— a login never overwrites the users-Job's role assignments;oauth_allow_insecure_email_lookup = true— the OIDC identity binds to the pre-provisioned local account by email;allow_sign_up = false— a cozy-realm identity whose email is NOT inspec.oidc.usersis rejected at login (even if they are a tenant member and pass the group gate) instead of being admitted asauto_assign_org_roleViewer and waiting for the next helm-upgrade prune pass to clean them up.
When
spec.oidc.usersis empty (or unset) the three users-map keys are NOT forced. The tenant-membership gate still applies, so only tenant members can log in — they land at Grafana'sauto_assign_org_roledefault (Viewer). This is the intended hands-off contract: the chart owns nothing app-side, but the Keycloak-layer gate still isolates the release. Cross-tenant users are rejected outright; in-tenant users get a self-service Viewer with no org-role management by the chart. -
A
GF_AUTH_GENERIC_OAUTH_CLIENT_SECRETenv on the Grafana Deployment sourced from the Secret in step 3. -
A post-install/post-upgrade users-Job — see the "Users and RBAC" section — that reconciles
spec.oidc.usersinto Grafana's Main Org.
No KeycloakRealmGroups and no role_attribute_path. Directory
objects (users, groups, group memberships) stay owned by whoever
operates the cozy realm; the Monitoring release only requests
authentication wiring, it does not act as a user directory.
Server-level GrafanaAdmin promotion (allow_assign_grafana_admin)
is out of scope for Phase 1. All Grafana instances — platform and
tenant — cap at org-level Admin.
CustomConfig mode
The tenant supplies the entire [auth.generic_oauth] payload. Two
paths:
spec:
oidc:
mode: CustomConfig
customConfig:
config:
client_id: my-grafana
client_secret: xxxxxxxx
auth_url: https://idp.acme.example/protocol/openid-connect/auth
token_url: https://idp.acme.example/protocol/openid-connect/token
api_url: https://idp.acme.example/protocol/openid-connect/userinfo
scopes: openid email profile
…or via an existing Secret in the tenant namespace whose auth.ini
key holds a ready-made [auth.generic_oauth] fragment:
spec:
oidc:
mode: CustomConfig
customConfig:
secretRef:
name: acme-byo-grafana-auth
When spec.oidc.users is non-empty the chart merges three settings
on top of the operator's inline map so the users-Job contract holds
in CustomConfig mode too:
skip_org_role_sync = true— a login never overwrites the Job's org-role assignments;oauth_allow_insecure_email_lookup = true— the OIDC identity binds to the pre-provisioned local account by email;allow_sign_up = false— an OIDC identity whose email is not in the users-map is rejected at login instead of being admitted with the defaultauto_assign_org_role.
All three keys are chart-forced (merge semantics, chart wins) —
setting them in the operator's map is a no-op, and
role_attribute_path would just be dead config since the Job
manages roles.
When spec.oidc.users is empty (or unset) the chart forces none of
the three keys — a BYO-IdP operator who does not use the users-map
gets their inline auth.generic_oauth applied verbatim. This
matters because oauth_allow_insecure_email_lookup against a BYO
issuer that does not verify emails is a needless account-linking
surface, and allow_sign_up = false with no pre-provisioned
accounts would lock everyone out. If you want the isolation
posture without the users-map, set the keys explicitly in your
inline map.
secretRef.name mode disables the users-map. The chart mounts the
operator's auth.ini fragment verbatim via GF_PATHS_CUSTOM_INI and
cannot inject either of the two chart-forced settings. Setting
spec.oidc.users alongside customConfig.secretRef.name fails the
render with an explicit message — the alternatives are: (a) use
customConfig.config (inline) and let the chart merge, or (b) leave
spec.oidc.users empty and include both skip_org_role_sync = true
and oauth_allow_insecure_email_lookup = true in your ini fragment
plus manage the OIDC → Grafana user mapping yourself.
Setting both config and secretRef.name (or neither) fails the
render. In CustomConfig mode no Keycloak objects are provisioned in
cozy and no chart-owned client-secret Secret is created — the
operator manages their own credentials end-to-end.
Users and RBAC
Grafana's built-in identity model exposes three org-level roles:
Admin / Editor / Viewer. The chart drives them from an
operator-supplied map on the CR:
spec:
oidc:
users:
- email: alice@acme.example
role: Admin
- email: bob@acme.example
role: Editor
- email: carol@acme.example
role: Viewer
A chart-owned Job runs on every helm install / helm upgrade and
reconciles that list into Main Org. membership via Grafana's admin
API:
- Each listed email gets a pre-provisioned local Grafana account
with a random password. The account is a shell; the operator
never uses that password. When they sign in with the OIDC flow
Grafana looks up the pre-provisioned account by email
(
oauth_allow_insecure_email_lookup = true) and attaches the OIDC identity to it. - Each listed email is added to Main Org. with the requested role.
Re-runs of the Job converge role changes (
Editor→Admin, demotions, etc.) viaPATCH /api/orgs/{orgId}/users/{userId}. - Every Main-Org member whose email is neither in the list nor the
break-glass
grafana-admin-passwordlogin is removed. Removing an entry fromusers:and re-reconciling revokes access.
The Job renders only when both mode != None and
spec.oidc.users is non-empty. Three empty-users states all resolve
to the same hands-off contract — the chart owns nothing in Grafana
orgs:
mode: None— OIDC is off, no chart-managed org membership at all. This matters on upgrade: existing tenants who ran the pre-PR Monitoring chart may have added users to Grafana manually through the UI; if the Job ran inmode: Noneits prune pass would silently delete those accounts on the next Flux reconcile.customConfig.secretRef— the users-map is forbidden by the render-time assert; the operator's mountedauth.inifragment is authoritative.mode: System | CustomConfig-inlinewithusers:unset — the operator opted into OIDC but not into the chart-managed users-map; they manage org membership themselves.
Setting users: [...] on the CR means the chart owns Main-Org
membership — anything added by hand (Grafana UI, admin API, other
tooling) gets pruned on the next reconcile. The reverse edge is
worth calling out: taking users: back to [] (or unsetting it)
does NOT prune the last entry — the chart stops managing membership
and any accounts the Job provisioned are left in place. Operators
who want to clean up OIDC-provisioned accounts after switching
System | CustomConfig → None (or after emptying users:) do it
themselves through the Grafana UI or admin API. The
activeDeadlineSeconds and ttlSecondsAfterFinished notes below
only apply when the Job actually renders.
While the users-map is active, users NOT listed in spec.oidc.users
who try to log in through OIDC are rejected at the door
(allow_sign_up = false) — no account is minted, no default
Viewer role is assigned. skip_org_role_sync = true in the
Grafana config additionally makes sure the Job's assignments
outlive the next login for users who ARE listed.
For System mode, the operator provisions the corresponding
Keycloak user in cozy in whatever way they already do (Keycloak
UI, a KeycloakRealmUser CR, an identity broker) and adds them to
one of the tenant's <namespace>-{view,use,admin,super-admin}
groups — Grafana's allowed_groups rejects the login otherwise.
The Monitoring release does not create Keycloak users and does not
provision KeycloakRealmGroups — group directory ownership stays
with the tenant chart (packages/apps/tenant); group membership is
curated by whoever operates the cozy realm.
How a user logs in
The user opens https://grafana.<host> in a browser and picks the
"Sign in with Keycloak" button under the login form. Grafana runs the
Authorization Code + PKCE flow against the cozy realm, receives a
token whose aud claim matches this Monitoring instance's clientId,
and — if the user's email is in spec.oidc.users — binds the OIDC
identity to the pre-provisioned local account with the role the Job
already set.
If the user's email is not in spec.oidc.users (and the users-map
is active — mode != None and the list is non-empty) the login is
refused by Grafana at the OAuth callback — allow_sign_up = false
does not mint an account for them. Add them to spec.oidc.users
and re-apply the CR; the Job will run on the next helm-upgrade,
pre-provision their local account, and the next login attempt will
succeed. When the users-map is inactive Grafana's default
allow_sign_up = true applies and any authenticated cozy-realm
identity lands with auto_assign_org_role (Viewer).
The break-glass admin_user / admin_password field on the form
stays wired to the grafana-admin-password Secret and continues to
work — useful when Keycloak is down or misconfigured.
Failure modes
mode: Systemwithout the platform-level OIDC feature — chart render hard-fails:spec.oidc.mode: System requires the platform-level OIDC feature. Flipauthentication.oidc.enabled: truein the platform values, or switch toCustomConfig. On the platform side that flag also swings thecozystack.monitoring-applicationPackageSource from variantdefault(baseline dependsOn only) to variantoidc(additionally waits forcozystack.keycloak-operatorso thev1.edp.epam.comCRDs consumed by the Keycloak-side of System mode are registered before the monitoring chart reconciles).mode: Systemwithout the Keycloak operator CRDs registered — chart render hard-fails:spec.oidc.mode: System requires the Keycloak operator CRDs (v1.edp.epam.com/v1). Symmetric acrosstemplates/grafana/oidc-keycloak.yamlandtemplates/grafana/grafana.yamlso Grafana never comes up with anauth.generic_oauthblock pointing at a client that never gets provisioned. For the platformmonitoring-systemrelease theoidcvariant'sdependsOn: cozystack.keycloak-operatorprevents the race; for tenant releases (MonitoringCR withmode: System) verify the keycloak-operator package is deployed before creating the CR.CustomConfigwith an unreachable issuer or wrong claim mappings — Grafana rejects the callback and the login screen shows an error; theadmin_user/admin_passwordSecret keeps working as break-glass.- User successfully logs in but sees no dashboards. Their email
is missing from
spec.oidc.users— no org role was assigned. Add the entry and re-apply the CR; the users-Job runs on the next helm-upgrade and grants access. - users-Job fails. The Job caps at
activeDeadlineSeconds: 900andbackoffLimit: 6. Common causes: Grafana never becomes ready (checkkubectl -n <ns> get pods -l app=grafana), or thegrafana-admin-passwordSecret is missing itsuser/passwordkeys.ttlSecondsAfterFinished: 3600keeps the failed hook Job (and its Pod's logs) around for one hour after the terminal Failed condition — check its logs withkubectl -n <ns> logs job/<release>-oidc-usersinside that window. After 1h the Kubernetes TTL controller garbage-collects the Job and the Pod together, so grab the logs quickly; if you missed the window, re-trigger the hook withhelm upgradeon the release and reproduce. emailVerifiedon Keycloak users is a prescriptive requirement, not a chart-enforced one. The chart does not emit anyclaimValidationRules— the layered guarantees you rely on instead are:- Provision users with
emailVerified: true(viaKeycloakRealmUseror the Keycloak UI's email-verify flow) so no unverified identity ever holds a given email. - The
cozyrealm keeps Keycloak's defaultduplicateEmails: false, so a second account cannot claim an already-registered address to impersonate an existing operator. - Grafana's own login flow rejects tokens the apiserver rejects,
so on the wire the same guarantee still holds through the JWT
signature and audience checks.
Adding a CEL
claimValidationRulesentry is a reasonable follow-up hardening; it is out of scope for Phase 1.
- Provision users with
CustomConfigwith both or neither payload set — chart render hard-fails:set exactly one of 'config' (inline) or 'secretRef.name' — they are mutually exclusive, orCustomConfig requires either spec.oidc.customConfig.config … or …secretRef.name.
What is NOT in Phase 1
- Per-tenant Keycloak realms. Phase 2 candidate; tracked in cozystack/community#24.
- Full-logout through Keycloak's end-session endpoint.
auth.generic_oauthnative to Grafana does the OAuth part; wiring--backend-logout-urland the corresponding Keycloak client attribute is a subsequent hardening. disable_login_form: trueundermode: System. Kept off so theadmin_user/admin_passwordSecret remains a documented break-glass path; hardening it is a follow-up.- Server-level
GrafanaAdminpromotion. All Grafana instances cap at org-levelAdmin. Not exposed on the CR. - CEL
claimValidationRulesenforcingemail_verified. See the failure-modes note above. - Multi-issuer / BYO alongside
cozy.mode: Systemandmode: CustomConfigare mutually exclusive on a single Monitoring release — no composition. Follow the tenant kube-apiserver PR's structured-config path if you need this later.