Skip to content
Authentication and Sessions

Authentication and Sessions

The gateway authenticates every user with OpenID Connect (OIDC) and keeps the result in an encrypted, host-only session cookie. With the optional client-certificate gate, every request also needs the person’s company client certificate. It serves three hostnames, all routed by the Host header in gateway/internal/server/router.go:

HostVariableServes
DashboardKORNERCODE_HOSTThe single-page application, the REST API under /api/v1/, and the OIDC endpoints under /auth/
DevDEV_HOSTThe reverse proxy to the user’s code-server (IDE), plus /auth/bridge
TestTEST_HOSTThe reverse proxy to the application listening on the workspace’s test port, plus /auth/bridge

Only the dashboard host talks to the identity provider (IdP). The dev and test hosts receive their sessions from the dashboard through short-lived bridge tickets (see Cross-host hand-off).

For how the gateway fits into the rest of the system, see Gateway architecture.


OIDC authorization code flow

The gateway uses the authorization code flow. The implicit flow and device grants are not used. Handlers live in gateway/internal/server/oidc_handlers.go; the OIDC client is gateway/internal/auth/oidc.go.

Browser                    Gateway (dashboard host)          IdP
   │                          │                               │
   │  GET /auth/login         │                               │
   │  ?redirect=<target>      │                               │
   │─────────────────────────►│                               │
   │                          │ generate random state + nonce │
   │                          │ validate target (loginTarget) │
   │                          │ save state, nonce, target     │
   │  302 IdP authorize       │                               │
   │  ?state=...&nonce=...    │                               │
   │◄─────────────────────────│                               │
   │                          │                               │
   │  GET authorize ─────────────────────────────────────────►│
   │         [user signs in]                                  │
   │◄─────────────────────────────────────────────────────────│
   │  302 /auth/callback?code=...&state=...                   │
   │                          │                               │
   │  GET /auth/callback      │                               │
   │─────────────────────────►│                               │
   │                          │ check state                   │
   │                          │ exchange code ───────────────►│
   │                          │◄──────────── id_token ────────│
   │                          │ verify ID token, check nonce  │
   │                          │ require sub, validate OwnerID │
   │                          │ save claims in session        │
   │  302 postLoginLocation   │                               │
   │  (Set-Cookie)            │                               │
   │◄─────────────────────────│                               │

State and nonce

/auth/login generates two independent 16-byte random values (hex encoded) and stores both in the session cookie before redirecting to the IdP:

  • state protects the callback against cross-site request forgery. /auth/callback rejects the request with 400 unless the state query parameter equals the stored value.
  • nonce binds the ID token to this authorization request. The gateway passes it in the authorization request and rejects an ID token whose nonce claim does not match the stored value.

If the gateway cannot generate random bytes or cannot write the session, /auth/login fails with 500 instead of starting the handshake.

ID token validation and claims

The gateway exchanges the authorization code at the IdP’s token endpoint and verifies the returned id_token with github.com/coreos/go-oidc (signature, issuer, audience equal to the client ID, and expiry). It requests the scopes openid, profile, email and groups.

ClaimField (gateway/internal/domain/claims.go)Usage
subClaims.SubIdentity. Required; the login fails if it is empty.
preferred_usernameClaims.PreferredUsernameDisplay name
Identity claim (OIDC_IDENTITY_CLAIM, default preferred_username)Claims.IdentityCompared with the client certificate’s CN at sign-in when the client-certificate gate is on; unused otherwise
emailClaims.EmailInformational only (audit metadata, admin views); never used for identity
email_verifiedClaims.EmailVerifiedInformational only
Groups claim (OIDC_GROUPS_CLAIM, default groups)Claims.GroupsTeam resolution and admin authorization
nonceClaims.NonceCompared with the stored nonce

The IdP must emit the groups claim in the ID token. Only its name is configurable (gateway.oidc.groupsClaim); it is a top-level claim holding a list of strings or a single string, and anything else counts as no groups. Group names are used as they come, so a provider that sends full paths (/kornercode-admins) needs ADMIN_GROUPS and Team.spec.groupClaim written the same way. The local development realm configures a groups client scope with a group-membership mapper (hack/local-dev/keycloak-setup.sh).

Single OIDC URL

The gateway reads one IdP setting, OIDC_URL (Helm key gateway.oidc.url). It is both the discovery base and the expected iss claim, so it must be one canonical URL that the browser and the gateway pod can both reach. Discovery runs in the background and is retried until it succeeds, so the gateway starts and stays Ready while the IdP is unreachable; until then the login answers with an “identity provider is unavailable” page.

When the browser and the pod see different networks, map the public hostname inside the pod instead of using a second URL. The local development environment does this with the chart’s gateway.hostAliases value, which hack/local-dev/bootstrap.sh sets to the in-cluster Keycloak Service IP (see hack/local-dev/values.yaml).

The OIDC redirect URI is derived from the dashboard host: https://<KORNERCODE_HOST>/auth/callback. Register exactly this URI with the IdP. KORNERCODE_HOST may include a port (for example dashboard.kornercode.local:8443 in local development); the port is kept in the redirect URI and stripped for host routing.


Login redirects

A login keeps the address the user was trying to reach, including host, port and path.

  1. An unauthenticated browser request on the dev or test host is redirected to https://<KORNERCODE_HOST>/auth/login?redirect=<original URL>. On the dashboard host, the gateway serves the login page, whose sign-in button calls /auth/login. API requests (paths under /api/v1/, or Accept: application/json) receive 401 with a JSON body instead of a redirect, and the single-page application sends the user to /auth/login.
  2. /auth/login validates the redirect value with loginTarget (gateway/internal/server/http_helpers.go) and stores the result in the session.
  3. After a successful callback, postLoginLocation turns the stored target into the final redirect.

loginTarget accepts only the following:

redirect valueStored target
Relative path (/path?query)The path and query, after sanitiseRedirect
Absolute http/https URL on the dashboard hostIts path and query only
Absolute http/https URL on the dev or test hostScheme, host, port, path and query
Anything else: other hosts, user info in the URL, other schemes, backslashes, protocol-relative URLs/

sanitiseRedirect also rejects literal and percent-encoded backslashes and drops URL fragments.

For a dev or test target, postLoginLocation mints a bridge ticket for that host and redirects to <scheme>://<host>[:port]/auth/bridge?ticket=...&redirect=<path>, because the session cookie set by the callback is valid only on the dashboard host. All other targets are returned as a local path.


Owner identity

The owner identity of a user is the lowercased OIDC sub claim (Claims.OwnerID() in gateway/internal/domain/claims.go). The callback validates it with domain.NewOwnerID (gateway/internal/domain/identity.go) and rejects the login if the value is empty, longer than 58 characters (validation.OwnerIDMaxLen), or does not match ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$. Keycloak’s UUID subjects satisfy this rule.

The owner identity is used as:

  • spec.owner on the Workspace the gateway creates for the user;
  • the code.kornercloud.dev/owner label on the Workspace and on the Pod, Service and home PVC the operator creates or adopts;
  • the value an administrator puts in the code.kornercloud.dev/home-for label to hand a restored volume to the user (see Migrating existing home directories);
  • the input to validation.HomePVCName (operator/api/v1alpha1/validation/ownerid.go), which produces the name home-<owner> of a newly created home. The home actually mounted is resolved by labels and recorded in the Workspace’s status.homePVCName, which the gateway reads.

The user’s preferred_username is stored on the Workspace as the code.kornercloud.dev/owner-name annotation for display only.

When the gateway resolves a user’s Workspace it lists by the owner label, refuses to route if more than one Workspace matches, and re-checks that spec.owner equals the caller’s owner identity (GetWorkspaceForUser in gateway/internal/k8s/workspace.go). The Workspace validating webhook rejects any change to spec.owner after creation.


Session management

Sessions are stored client-side in a cookie managed by gorilla/sessions. The store is built by NewSessionStore in gateway/internal/auth/session.go.

Keys

SESSION_SECRET is the root secret. The gateway refuses to start if it is shorter than 32 bytes. Generate it with openssl rand -hex 32.

Four 32-byte keys are derived from it with HKDF-SHA256, each with its own info label:

KeyHKDF info labelUsed for
Session HMAC keykornercode-session-hash-v1Authenticating the session cookie
Session encryption keykornercode-session-block-v1AES-256 encryption of the session cookie
Bridge HMAC keykornercode-bridge-hash-v1Authenticating bridge tickets
Bridge encryption keykornercode-bridge-block-v1AES-256 encryption of bridge tickets

Session cookies and bridge tickets are therefore encrypted and authenticated with disjoint keys. Rotating SESSION_SECRET invalidates all of them at once; see Session secret rotation.

Cookie properties

PropertyValue
Namekornercode-session
EncodingAES-256 encryption plus HMAC-SHA256 (gorilla/securecookie)
DomainSESSION_DOMAIN; empty by default, which makes the cookie host-only
Securetrue
HttpOnlytrue
SameSiteLax
Path/
Max-AgeSESSION_MAX_AGE_SECONDS, default 28800 (8 hours)

With the default empty SESSION_DOMAIN, the dashboard, dev and test hosts each hold their own cookie, and no other host under the same parent domain receives it. This keeps the session away from code served on sibling hosts. Setting SESSION_DOMAIN (Helm key gateway.security.sessionDomain) to a parent domain shares one cookie across all subdomains and removes that protection; it is not recommended.

Session values

KeyContent
claimsThe verified claims from the ID token, plus the login time (AuthTime)
issued_atUnix time of the last save; drives sliding expiry
oauth_stateOIDC state during the login flow
oidc_nonceOIDC nonce during the login flow
post_login_redirectValidated post-login target; removed when the callback saves the claims
workspace_targetOn a dev-host session only: the namespace/name of another user’s Workspace an admin opened

Lifetime and sliding expiry

AuthMiddleware calls RefreshIfStale on every authenticated request. When the session was last saved more than a quarter of Max-Age ago (2 hours with the default), the gateway re-issues the cookie with a fresh Max-Age. An active session is therefore extended while the user keeps making requests; an idle session ends after Max-Age. A login is valid for at most SESSION_MAX_LIFETIME_SECONDS (default 24 hours), renewals included: GetClaims rejects claims whose login time is older, and the user signs in again. Bridge tickets carry the login time, so sessions on the dev and test hosts end at the same time as the dashboard session.

The claims in the session are the ones captured at login. They are not refreshed from the IdP while the session lives; see Group propagation lag.

Cross-host hand-off (bridge tickets)

Because cookies are host-only, the dashboard hands a session to the dev or test host through a bridge ticket (gateway/internal/auth/bridge.go):

Browser                    Gateway (dashboard host)        Gateway (dev/test host)
   │ POST /api/v1/bridge/ticket?target=dev                       │
   │───────────────────────────►│                                │
   │ {"ticket": "...", "host": "dev.example.com"}                │
   │◄───────────────────────────│                                │
   │ GET /auth/bridge?ticket=...&redirect=/                      │
   │────────────────────────────────────────────────────────────►│
   │                            decrypt, check expiry and host    │
   │ 302 /  (Set-Cookie: host-only session)                      │
   │◄────────────────────────────────────────────────────────────│
  • POST /api/v1/bridge/ticket (gateway/internal/api/bridge.go) requires an authenticated dashboard session. target must be dev or test; the handler resolves it to the configured host, so a client cannot request a ticket for an arbitrary host.
  • A ticket carries the caller’s claims, the target host, an expiry 30 seconds after minting (constants.BridgeTicketTTL), and, for admins only, an optional target Workspace. It is encrypted and authenticated with the bridge keys.
  • /auth/bridge (bridgeWrap in gateway/internal/server/bridge_handlers.go) runs on the dev and test hosts before authentication. It rejects a ticket that fails decryption, has expired, or was minted for another host with a single 401. On success it writes a host-only session for that host (SaveBridgeSession) and redirects to the sanitized redirect path.
  • Tickets are not recorded server-side: a ticket can be redeemed more than once until it expires.

The single-page application performs this exchange when the user opens the IDE or the test application. The login flow performs the same exchange when the post-login target is on the dev or test host.

Logout

GET /auth/logout on the dashboard host:

  1. Clears the dashboard session cookie. If the cookie cannot be decoded (for example after a SESSION_SECRET rotation), the gateway returns 500 and increments gateway_session_store_errors_total{op="clear"} instead of reporting a successful logout.
  2. Also expires any legacy kornercode-session cookie scoped to the parent domain of KORNERCODE_HOST, so that browsers holding a cookie from a deployment that used a parent-domain SESSION_DOMAIN are logged out as well.
  3. Redirects to the IdP’s end_session_endpoint with client_id and post_logout_redirect_uri set to the dashboard root, which ends the IdP single sign-on session. If the IdP’s discovery document has no end_session_endpoint, the gateway logs a warning at startup and logout only clears the gateway cookie. A break-glass session, or a logout while discovery has not yet succeeded, redirects to / instead, without contacting the IdP.

Sessions on the dev and test hosts are separate host-only cookies. Logging out of the dashboard does not clear them; they remain valid until they expire or SESSION_SECRET is rotated. Obtaining a new bridge ticket requires a dashboard session, which requires a new login.


Client-certificate gate

With clientCertificates.enabled, every request on the dashboard, dev and test hosts needs the person’s company client certificate, and the session must belong to that certificate. It is off by default; off, none of this section applies, apart from the cross-site request check, which runs either way. Operating instructions are in the admin guide; the decision is ADR 0015.

Trust chain

  1. The browser presents the person’s certificate to the ingress, which requires one signed by the company CA. Every host asks for it.
  2. The ingress removes any certificate header the client sent and puts the full certificate in a request header (X-Forwarded-Tls-Client-Cert for Traefik).
  3. The ingress forwards the request to the gateway’s client-certificate listener (port 8444), which requires a client certificate from kornercode’s internal CA with the DNS SAN kornercode-ingress and the clientAuth usage. With the gate on, this listener is the only one that serves the three hosts: the plain listeners (8080, and 8443 with gateway TLS) answer /healthz and 404 for everything else, so an in-cluster caller cannot reach the router with a forged header.
  4. The gateway verifies the forwarded certificate on every request (newCertGate in gateway/internal/server/certgate.go, before routing), then checks it against the session.

The gateway refuses a request that also carries the certificate header of another dialect (certificate_header_ambiguous). It then decodes the leaf certificate and checks, in this order: the certificate is present and well formed, it is within its validity dates, its chain leads to the company CA (only the first certificate in the header is judged; later ones only help build the path), it has exactly one subject CN, and it is not revoked. The first failure decides the refusal reason (gateway/internal/clientcert/verifier.go):

ReasonMeaning
certificate_header_ambiguousAnother dialect’s certificate header is present
no_certificateNo certificate in the configured header
certificate_malformedThe header could not be decoded
certificate_expiredOutside its validity dates (expired or not yet valid)
certificate_untrustedNo chain to the company CA with the clientAuth usage, or a CA certificate
certificate_cn_ambiguousNo subject CN, or more than one
certificate_revokedListed in its CRL
revocation_unavailableNo CRL could be fetched (with onUnavailable: deny), or a CRL failed its integrity checks

Revocation uses the CRLs named in the certificate (http:// and https:// only). Integrity failures (bad CRL signature, unparseable CRL, issuer mismatch) always refuse. When no CRL can be fetched and no cached one is still valid, clientCertificates.revocation.onUnavailable decides: deny (the default) refuses, allow lets the request through and audits it as revocation: unchecked. The policy is the same for every user and every request, break-glass included, so with deny a revocation-list outage that outlasts the cached lists locks everyone out, administrators included.

The gateway reads only the header of the configured dialect (clientCertificates.headerDialect). If the ingress actually wrote another dialect’s header, it would neither set nor strip the configured one, and that header would be whatever the client sent. A request carrying a certificate header of any other dialect, even an empty one, is therefore refused. This catches a dialect mismatch as long as the ingress sets its own header on every request; the chart’s Traefik middleware strips all three dialects’ headers from client requests, so a visitor cannot trigger the refusal by sending one.

Sign-in and session binding

  • Sign-in. /auth/callback compares the ID token’s identity claim (gateway.oidc.identityClaim, default preferred_username) with the certificate’s CN, without regard to case and without trimming. A missing or empty claim is refused as identity_claim_missing, a different value as certificate_identity_mismatch; no session is saved. On a mismatch the gateway also ends the Keycloak session that signed the wrong person in: it sends the browser to the end-session endpoint with the ID token as id_token_hint (no confirmation page) and state=certificate_identity_mismatch, and the sign-in page it comes back to says what happened. Without this, a browser that kept the previous person’s Keycloak sign-in (a non-private window restarted with another certificate) would be signed in as that person on every attempt. If the provider publishes no end-session endpoint the refusal page is shown instead. On a match the session is bound to the CN.
  • Every later request, on all three hosts, must present a certificate whose CN is the one the session is bound to: regardless of case for an OIDC session, exactly for a break-glass session. The binding is to the CN, not to one certificate, so a renewed certificate keeps working.
  • A session bound to another CN is refused as certificate_session_mismatch, audited and cleared. A page load is sent back to the same address, which then shows the sign-in page: a browser that kept another person’s session cookie across a restart starts over without an error. An API call or a form post gets 403 with the reason, and the dashboard reloads the page instead of signing in again.
  • A session bound to no CN (opened before the gate was turned on) is cleared quietly: a page load is sent back to the same address, which then shows the sign-in page; an API call gets 401.
  • Bridge tickets carry the CN. /auth/bridge on the dev and test hosts refuses a ticket bound to another certificate as certificate_session_mismatch, so the dev and test sessions are verified exactly like the dashboard’s.

A refusal answers 403: API requests get {"error":"certificate refused","reason":"<reason>"}, browsers a “Certificate refused” page naming the reason.

Open requests

An open request (an IDE WebSocket, a dashboard log stream) ends when the certificate expires or the login reaches its maximum lifetime, whichever comes first. While it is open, the gateway verifies the certificate again every 30 seconds against the cached CRLs and closes the request when it is refused, for example after a revocation.

Break-glass login

Break-glass signs an administrator in with the client certificate alone, for when the identity provider is unavailable. It needs the gate and at least one entry in breakGlass.mapping.

  1. The sign-in page and the “identity provider is unavailable” page show a second button, “Administrator sign-in without Keycloak”. It posts to /auth/break-glass on the dashboard host. Presenting a certificate never opens a session by itself.
  2. The gate has already verified the certificate. The handler (breakGlassHandler in gateway/internal/server) looks up its CN in the mapping, exactly and case-sensitively. A CN that is not listed is refused as cn_not_allowed.
  3. The gateway issues a session for the mapping entry (sub, username, email, groups), bound to the CN and flagged as break-glass, and sends the browser where it was going. It never contacts the identity provider.

Every mapped person is an administrator, whatever their groups say. A break-glass session uses the normal session cookie, lasts at most 8 hours (breakGlass.sessionMaxLifetimeSeconds), and its later requests need the exact CN. Each request of a break-glass session, on every host, also needs the CN still in the mapping with the same sub, username, email and groups; otherwise the session is cleared like one bound to no certificate (logged, not audited), and a break-glass bridge ticket opens no session. The gateway reads the mapping at start-up and the chart restarts it when the mapping changes, so removing or editing an entry ends that administrator’s break-glass sessions at their next request after the restart. The break-glass flag is set only by this handler, never from an ID token. Break-glass sessions and bridge tickets are not accepted while the gate is off. Logging out of a break-glass session clears the cookie and returns to /, without a call to the identity provider. A banner on every dashboard page says the session is a break-glass one.

Start-up without the identity provider

The gateway starts and stays Ready without the identity provider; OIDC discovery is retried in the background. Until it succeeds, /auth/login and /auth/callback answer with an “identity provider is unavailable” page (with the break-glass button when break-glass is on), and existing sessions keep working.

What it protects against

  • A session cookie replayed from another machine, with no certificate or with someone else’s: every request needs a certificate whose CN the session is bound to.
  • Someone without a company-issued certificate: the ingress and the gateway both check the chain.
  • Revoked and expired certificates, and a lapsed CRL (by default), on every request, including requests that stay open.
  • A forged certificate header: the gateway serves the hosts only on a listener that requires the ingress’s client certificate, and the ingress removes any header the client sent.
  • A copied certificate without its private key: the TLS handshake at the ingress needs the key.
  • An ingress that writes a different header dialect than configured: the request is refused as certificate_header_ambiguous instead of trusting a client-supplied header.
  • For break-glass, a certificate that is valid but not listed: the mapping is an allow-list.

What it does not protect against

  • Malware on the user’s own machine. Malware running as the user can drive the user’s browser, or use a private key the operating system lets that user’s processes use, so it can act with the cookie and the certificate together. Hardware or non-exportable keys make the key harder to steal but do not stop its misuse on the infected machine.
  • A compromised ingress. The gateway trusts the certificate the ingress forwards. Whoever controls the ingress can present any certificate in the header and act as anyone whose session or mapping entry has that CN.
  • Anyone who can create cert-manager Certificates against the kornercode-internal-ca-issuer ClusterIssuer. They can mint a kornercode-ingress client certificate and impersonate the ingress to the gateway. Restrict who can create Certificates that use this issuer.
  • A stolen key and certificate. With the person’s password they work until the certificate is revoked; for break-glass, until it is revoked or its CN is removed from the mapping (which ends the existing break-glass sessions at their next request once the gateway has restarted with the new mapping).
  • A revocation gap with onUnavailable: allow. Requests are accepted and audited as revocation: unchecked.

Audit

Certificate refusals by the gate, at sign-in and at /auth/bridge are recorded with the action auth.certificate, the subject client-certificate, the actor certificate:<cn> (certificate:unknown when no CN could be read), outcome: failure and the metadata cn, serial, issuer, clientIP (the ingress), method: client-certificate, reason, the host and path refused and, when present, forwardedFor. A certificate_identity_mismatch refusal adds the token’s identity. A request let through without a revocation check (onUnavailable: allow) is recorded with outcome: success and revocation: unchecked.

Break-glass logins and cn_not_allowed refusals are recorded with the action auth.break_glass.login, the subject break-glass, method: break-glass, the same certificate metadata, and the actor break-glass:<cn> on a refusal or the mapped sub on success. Admin actions taken in a break-glass session carry breakGlass: "true". The AdminOpenedIDE Kubernetes Event does not mention break-glass; the audit log does.

Refusals for the same CN and reason, and unchecked requests for the same CN, are written once a minute (see ADR 0014). See Audit and observability.


Cross-site request check

Cookies and client certificates are ambient authority: the browser sends them with any request to the dashboard, whichever page made it, including a page on a user’s dev or test host, which is same-site, so SameSite cookies do not help. The dashboard host therefore checks every state-changing request before anything else runs, whether the gate is on or off (originGuard in gateway/internal/server/origin_guard.go):

  • Every method other than GET, HEAD and OPTIONS must carry exactly one Origin header equal to the dashboard origin (https://<KORNERCODE_HOST>, port included), and Sec-Fetch-Site must be absent or same-origin. A missing Origin is refused.
  • A refused request gets 403 with {"error":"cross-origin request refused","reason":"cross_origin"}. No session is read or written and no audit entry is written; the gateway logs a warning with the method, path and origin.

Browsers send Origin on these requests by themselves. Scripts that call the API with POST, PUT, PATCH or DELETE must send it too, for example curl -H 'Origin: https://dashboard.example.com' .... With the gate on, the certificate is judged first, so a cross-site request without a valid certificate is refused by the gate instead.


Auth middleware

AuthMiddleware (gateway/internal/server/middleware.go) wraps the dashboard API, the dev proxy and the test proxy:

func AuthMiddleware(sessions *auth.SessionStore, loginURL string, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        claims, ok := sessions.GetClaims(r)
        if !ok {
            rejectUnauthenticated(w, r, loginURL) // 401 JSON for API requests, 302 to /auth/login otherwise
            return
        }
        sessions.RefreshIfStale(w, r)
        ctx := domain.WithClaims(r.Context(), claims)
        if target, ok := sessions.GetWorkspaceTarget(r); ok {
            ctx = domain.WithWorkspaceTarget(ctx, target)
        }
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

With the client-certificate gate on, the gate runs before AuthMiddleware on every host and has already checked the certificate against the session. Downstream handlers and proxies read the claims with domain.ClaimsFromContext and do not re-read the cookie. Non-API paths on the dashboard host (the single-page application) are served only with a valid session; without one the gateway serves the login page. Static assets under /css/ and /js/ are served without a session because the login page needs them.

Before forwarding a request to a workspace, the dev and test proxies delete the Cookie and Authorization headers and replace any client-supplied X-Forwarded-* headers, so code running in the workspace never receives the gateway session. The dev proxy also rejects WebSocket upgrades whose Origin is not one of the three gateway hosts, or that carry Sec-Fetch-Site: cross-site.


Admin authorization

ADMIN_GROUPS (Helm key gateway.adminGroups) is a comma-separated list of IdP group names. admin.InitRBAC parses it at startup; an empty value means no user is an admin.

// gateway/internal/admin/rbac.go
func IsAdmin(claims *domain.Claims) bool {
    if claims == nil {
        return false
    }
    if claims.BreakGlass {
        return true // every break-glass mapping entry is an admin
    }
    for _, ag := range adminGroups {
        for _, ug := range claims.Groups {
            if ug == ag {
                return true
            }
        }
    }
    return false
}

AdminMiddleware gates every route under /api/v1/admin/ and returns 403 to non-admins. The admin API can:

  • list Workspaces in all namespaces, view their details, stream their logs, change their test port, and delete them;
  • create, update and delete WorkspaceProfiles, Teams and SecurityProfiles;
  • list managed NetworkPolicies, list and delete user PVCs, and read statistics and usage data;
  • query Prometheus through /api/v1/admin/metrics when PROMETHEUS_URL is set.

Team create and update requests are checked with validation.ValidateNamespace, validation.ValidateNamespaceLabels and validation.ValidateTeamMounts (operator/api/v1alpha1/validation), the same rules the Team admission webhook applies; see Network isolation.

Non-admin API routes are scoped to the caller: the gateway resolves the caller’s Team from the groups claim (the first Team, in name order, whose spec.groupClaim is in the claim) and only returns or modifies the caller’s own Workspaces in that Team’s namespace. Lists filter on the owner label; operations on a single Workspace also require spec.owner to equal the caller’s owner identity and answer 404 otherwise, so the existence of other users’ Workspaces is not disclosed.

Opening another user’s IDE

Admins can open another user’s IDE from the admin panel (“View IDE”):

  1. The single-page application calls POST /api/v1/bridge/ticket?target=dev&workspace=<namespace>/<name>. The workspace parameter is admin-only (403 otherwise), is accepted only with target=dev, and must name an existing Workspace (404 otherwise).
  2. Before minting the ticket, the gateway records an AdminOpenedIDE Kubernetes Event on that Workspace, which its owner sees in the workspace’s Events tab.
  3. /auth/bridge on the dev host stores the target in the dev-host session (workspace_target). Opening one’s own IDE later issues a ticket without a target, which clears it. A browser holds one session per host, so all IDE tabs on the dev host follow the most recent ticket.
  4. For every request on such a session, the dev proxy re-checks admin rights (workspaceFor in gateway/internal/proxy/devproxy.go) and returns 403 if the caller is no longer an admin, or 404 if the Workspace no longer exists.
  5. Requests from an admin view do not update the Workspace’s status.lastActivityTime, so they do not keep another user’s workspace alive.

The test host does not support targets; it always serves the caller’s own Workspace.


Group propagation lag

The gateway reads the groups claim from the ID token once, at login, and stores it in the session. Every later admin check (AdminMiddleware, the admin bridge ticket, the dev proxy’s re-check) and every Team lookup uses the groups stored in the session. The gateway does not poll the IdP, refresh tokens, or accept back-channel logout, and it does not check the ID token’s expiry after login.

As a result, a change of group membership in the IdP, including an admin demotion, takes effect for a user only when that user’s gateway session ends:

  • when the user logs out (dashboard session only; see Logout);
  • when the session expires after SESSION_MAX_AGE_SECONDS (default 8 hours) without activity;
  • at the latest SESSION_MAX_LIFETIME_SECONDS (default 24 hours) after the login, even for a user who stays active.

The IdP’s access token and ID token lifetimes do not shorten this window. To revoke access sooner:

GoalAction
Shorten the window for everyoneLower gateway.security.sessionMaxLifetimeSeconds and gateway.security.sessionMaxAgeSeconds
Remove admin rights from a whole groupRemove the group from ADMIN_GROUPS and restart the gateway; IsAdmin evaluates the current list on every request
End every session immediatelyRotate SESSION_SECRET; see Session secret rotation

Configuration reference

The gateway is configured under gateway: in the kornercode chart (config/helm). See Configuration for the full list of values.

VariableHelm keyRequiredDescription
OIDC_URLgateway.oidc.urlyesCanonical OIDC provider URL: discovery base and expected iss
OIDC_CLIENT_IDgateway.oidc.clientIDyesOIDC client ID (default kornercode-gateway)
OIDC_CLIENT_SECRETkey OIDC_CLIENT_SECRET in the Secret named by gateway.oidc.existingSecretyesOIDC client secret (default Secret kornercode-gateway-secrets)
SESSION_SECRETkey SESSION_SECRET in the same SecretyesRoot secret for session cookies and bridge tickets; at least 32 bytes
KORNERCODE_HOSTgateway.hosts.kornercodeyesDashboard host as browsers see it, optionally with a port; determines the redirect URI
DEV_HOSTgateway.hosts.devyesIDE host
TEST_HOSTgateway.hosts.testyesTest application host
SESSION_DOMAINgateway.security.sessionDomainnoCookie Domain; empty (default) for host-only cookies
SESSION_MAX_AGE_SECONDSgateway.security.sessionMaxAgeSecondsnoSession idle lifetime in seconds, used for the cookie Max-Age and checked by the gateway; default 28800
SESSION_MAX_LIFETIME_SECONDSgateway.security.sessionMaxLifetimeSecondsnoMaximum lifetime of a login in seconds, renewals included; default 86400
ADMIN_GROUPSgateway.adminGroupsnoComma-separated IdP groups whose members are admins; empty disables admin access
OIDC_IDENTITY_CLAIMgateway.oidc.identityClaimnoID token claim compared with the client certificate’s CN when the gate is on; default preferred_username
OIDC_GROUPS_CLAIMgateway.oidc.groupsClaimnoID token claim holding the user’s groups; default groups
—gateway.hostAliasesnoPod host aliases, for resolving OIDC_URL inside the pod when the networks differ

The client-certificate gate and break-glass variables (CLIENT_CERT_*, BREAK_GLASS_*) are listed in Configuration.