Proxy Architecture

This document describes how workspace application proxying works in kube-workspaces. The proxy is a standalone service (proxy/) deployed independently from the API, with session-based authentication and namespace access control.

All proxy traffic flows through the main host via the cluster’s ingress controller (e.g. nginx or Traefik):

https://workspaces.example.com/proxy/{namespace}/{name}/...

The kw-session cookie (same domain) provides authentication automatically.


Overview

When a user opens a workspace application (e.g. code-server, filebrowser, a VNC desktop), the browser loads the app through the reverse proxy. The proxy validates the user’s session and checks they have access to the workspace’s namespace before forwarding the request.

URL Format

https://workspaces.example.com/proxy/{namespace}/{name}/{path}

Example:

https://workspaces.example.com/proxy/user1/my-codeserver/

The request flows through the ingress controller (/proxy path) to the proxy service. The proxy validates the kw-session cookie, checks namespace access, then forwards to the workspace pod.


Component Architecture

Proxy component architecture


Authentication & Authorization

The proxy enforces the same auth model as the API:

Auth Flow

  1. User navigates to /proxy/{namespace}/{name}/...
  2. Ingress forwards to proxy service
  3. Proxy auth middleware:
    • Reads kw-session cookie (or Authorization: Bearer header)
    • If no token → 401 Unauthorized
    • Validates HMAC-SHA256 signature using signing key from K8s Secret
    • If invalid/expired → 401 Unauthorized
    • Checks if email is in adminEmails → grants admin role override
    • If admin → pass through (skip namespace check)
    • Looks up User CR by email (not cached — instant revocation)
    • If user disabled → 403 Forbidden
    • Checks UserHasNamespaceAccess(user, namespace) → personal NS + spec.namespaceAccess[]
    • If no access → 403 Forbidden
    • Otherwise → forward to proxy handler

Auth Bypass Conditions

Condition Behavior
AuthConfig.spec.enabled = false All requests pass through (no auth)
AuthConfig CR not found Auth disabled (fail-open, backward compatible)
Admin role (via CR or adminEmails) Skip namespace access check
Health endpoints (/healthz, /readyz) Always pass through
Root endpoint (/) Always pass through

Caching Strategy

Resource Caching Purpose
AuthConfig + signing key 30-second TTL Matches API behavior; avoids per-request Secret reads
User CRs Not cached Looked up on every request for instant revocation
Image CRs 30-second TTL Reduces API calls when resolving proxyConfig
Workspace image 10-second TTL Short TTL since workspace image rarely changes

The proxy’s K8s client is configured with QPS: 50 and Burst: 100 to prevent client-side throttling under load. Without this, the default client rate limits (5 QPS) caused 3-4 second delays on proxied requests.

This ensures user disabling and namespace access revocation take effect immediately, while reducing unnecessary API server load for static configuration.

RBAC Permissions

The proxy ServiceAccount (kube-workspaces-proxy) has:

ClusterRole:

rules:
  - apiGroups: ["kubeworkspaces.io"]
    resources: ["images"]
    verbs: ["list"]
  - apiGroups: ["kubeworkspaces.io"]
    resources: ["workspaces"]
    verbs: ["get"]
  - apiGroups: ["kubeworkspaces.io"]
    resources: ["authconfigs"]
    verbs: ["get"]
  - apiGroups: ["kubeworkspaces.io"]
    resources: ["users"]
    verbs: ["get", "list"]

Role (namespaced to kube-workspaces-system):

rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get"]

The namespaced Role limits Secret access to only the deployment namespace (where the signing key Secret lives).


The Proxy Service (proxy/)

Source: proxy/cmd/proxy/main.go, proxy/internal/proxy/proxy.go, proxy/internal/auth/

The proxy is a standalone Go binary with minimal dependencies:

  • stdlib net/http + net/http/httputil for reverse proxying
  • k8s.io/client-go dynamic client for reading CRs and Secrets
  • Custom HMAC-SHA256 token validation (same format as the API)
  • No Goa framework, no database

Request Flow

Client request arrives
        ↓
CORS middleware (origin check)
        ↓
Auth middleware:
  /healthz, /readyz, /, /sw.js → skip auth
  Auth disabled → skip auth
  Validate token → 401 if invalid
  Check namespace access → 403 if denied
        ↓
Root handler routing:
  /healthz, /readyz → health check response
  /sw.js → no-op ServiceWorker
  /proxy/{ns}/{name}/... → proxy handler
  Referer-based recovery → rewrite + proxy handler
  / → service info JSON
  Other: 404
        ↓
Proxy handler:
  Parse namespace, name, rest from URL
  Look up Workspace CR → extract container image
  Look up Image CRs → find proxyConfig
  Build target: http://{name}.{namespace}.svc.cluster.local:80/{rest}
  Forward via httputil.ReverseProxy
        ↓
Response modifications:
  Location header rewriting
  HTML rewriting (code-server, base tag)
        ↓
Response returned to client

Target Resolution

The proxy constructs the backend URL using Kubernetes DNS:

http://{workspace-name}.{namespace}.svc.cluster.local:80/{rest}
  • Port 80 is used by default (workspace Services map port 80 to the container’s defaultPort)
  • If audioPort is configured and the request path matches /audio/, the proxy routes to that port instead (e.g., port 6902)
  • The scheme is http unless scheme: https is set (or the deprecated tlsInsecure: true); tlsSkipVerify controls certificate verification

WebSocket Support

WebSocket connections are handled transparently by httputil.ReverseProxy. The proxy preserves Connection and Upgrade headers when an upgrade is requested. The FlushInterval: -1 setting enables streaming for long-lived connections.

Because WebSocket connections can be long-lived, configure your ingress controller to allow extended timeouts. The exact mechanism depends on the controller:

  • nginx ingress: set proxy-read-timeout/proxy-send-timeout annotations:
    nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
    
  • Traefik: WebSocket upgrades bypass the HTTP router timeouts, so no extra configuration is required.
  • Other controllers: consult your controller’s docs for long-lived/WebSocket connection settings.

Request Header Modifications

The Director function applies these transformations:

Header Behavior
Host Set to original request Host
X-Forwarded-Host Set to original request Host
X-Forwarded-Proto Set to https/http based on upstream header
Connection Removed unless WebSocket upgrade
Accept-Encoding Removed (forces decompression for response rewriting)
Custom headers Injected from proxyConfig.customRequestHeaders

Response Modifications

Location Header Rewriting

All Location headers in responses are rewritten to stay under the proxy prefix:

  • Absolute URL → proxy prefix + path (e.g. http://pod.ns.svc/login → /proxy/{ns}/{name}/login)
  • Absolute path → proxy prefix + path (e.g. /login → /proxy/{ns}/{name}/login)
  • Relative path → resolved relative to current proxy path

HTML Response Rewriting

For text/html responses (when a proxyConfig exists), the proxy performs:

  1. <base> tag injection (when injectBaseTag: true): Inserts <base href="/proxy/{ns}/{name}/"> after <head>, causing the browser to resolve all relative and absolute URLs through the proxy path.

  2. code-server remoteAuthority rewrite: Replaces "remoteAuthority":"remote:443" with the actual browser hostname so VS Code’s WebSocket connects through the proxy.

  3. code-server serverBasePath rewrite: Replaces "serverBasePath":"." with the proxy prefix path.

  4. code-server rootEndpoint rewrite: Replaces "rootEndpoint":"." with the proxy prefix path.

The proxy handles gzip-encoded responses by decompressing before rewriting and re-compressing after.

Escaped Request Recovery

The proxy includes multiple layers of recovery for requests that escape the path prefix:

Layer 1: Referer-based recovery (proxy-side)

If a request arrives at a path that doesn’t match /proxy/{ns}/{name}/..., the proxy checks the Referer header:

referer := r.Header.Get("Referer")
if referer != "" {
    proxyPrefix := proxy.ExtractProxyPrefix(referer, pathPrefix)
    if proxyPrefix != "" {
        r.URL.Path = proxyPrefix + r.URL.Path
        // forward to proxy handler
    }
}

This catches requests from workspace apps that use absolute paths like /js/app.js.

For requests without a Referer header (e.g. WebSocket upgrades from KasmVNC), the proxy sets a kw-proxy-prefix cookie on HTML responses:

Set-Cookie: kw-proxy-prefix=/proxy/{ns}/{name}; Path=/; SameSite=Lax

When the frontend production server receives an escaped request (e.g. /websockify) without a Referer, it reads this cookie to reconstruct the correct proxy path and forwards the request to the proxy service.

Flow:

  1. Browser loads workspace at /proxy/ns/name/ → proxy sets kw-proxy-prefix=/proxy/ns/name
  2. KasmVNC client connects to /websockify (root-relative, no Referer)
  3. Request hits frontend server (catch-all ingress)
  4. Frontend reads kw-proxy-prefix cookie → rewrites to /proxy/ns/name/websockify
  5. Frontend forwards to proxy service → proxy strips prefix → forwards to pod

Path blocklist: The frontend does NOT apply cookie-based recovery to known frontend routes: /workspaces, /admin, /auth, /api, /login, /volumes, /profile, /_next, /favicon, /manifest, /sw.js, /images, /icons

No-Op Service Worker

The proxy serves a no-op ServiceWorker at /sw.js:

self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));

This is also served from frontend/public/sw.js for the case where the request hits the frontend instead.

Bot Filtering

The proxy validates namespace and name segments against Kubernetes naming rules before attempting lookups:

  • Must start/end with lowercase alphanumeric
  • Middle characters: lowercase alphanumeric or hyphens
  • Max 253 characters

This rejects scanner probes like .git/HEAD, .ssh/id_rsa, wp-admin, etc. without hitting the Kubernetes API.

Error Handling

If the proxy cannot connect to the workspace pod, it returns:

{"error": "Failed to connect to workspace: <reason>"}

with HTTP status 502 (Bad Gateway).

Health Checks

Endpoint Purpose
/healthz Liveness probe
/readyz Readiness probe

Both return {"status":"ok"} with HTTP 200. Health checks bypass auth.

Request Logging

The proxy includes logging middleware that records every non-health request:

2024/01/15 10:30:42 GET /proxy/user1/my-code/ → 200 (45ms)
2024/01/15 10:30:43 GET /proxy/user1/my-code/static/app.js → 200 (12ms)

Logged fields: method, path, status code, duration. Health check endpoints (/healthz, /readyz) are excluded to reduce noise.

Graceful Shutdown

The proxy handles SIGINT and SIGTERM with a 30-second graceful shutdown window, allowing in-flight requests (including WebSocket connections) to complete.


Ingress

The Ingress resource handles routing (kustomize/base/ingress.yaml). The manifests declare ingressClassName and a cert-manager.io/cluster-issuer annotation, so they work with any Ingress controller (nginx, Traefik, etc.) — just set ingressClassName to the controller installed in your cluster.

Primary Ingress (kube-workspaces)

Direct path-based routing without rewriting:

Path Backend Notes
/v1 API REST API endpoints
/auth API OIDC/local login, callback, session endpoints
/proxy Proxy Workspace reverse proxy (auth-enabled)
/ (catch-all) Frontend Next.js app

Annotation:

  • cert-manager.io/cluster-issuer: letsencrypt-production

WebSocket note: if using nginx ingress, add proxy-read-timeout/proxy-send-timeout annotations (see the WebSocket Support section). Traefik handles WebSocket upgrades without additional annotations.

Routing Summary

Browser URL Routed to Service receives
/proxy/ns/name/path Proxy (direct) /proxy/ns/name/path
/v1/workspaces API (direct) /v1/workspaces
/workspaces Frontend N/A
/admin Frontend N/A

Dedicated API Subdomain

A second host rule routes api.workspaces.example.com directly to the API with no path rewriting.


Next.js Frontend

Proxy file (frontend/src/proxy.ts)

Purpose: Catch requests that “escape” the proxy prefix.

Workspace apps served under /proxy/ns/name/... may use absolute paths like /static/app.js. The browser sends these to the frontend (catch-all ingress). The proxy file detects this via the Referer header and redirects back to the proxy.

How it works:

  1. A user views a workspace app at /proxy/ns/name/
  2. The app’s JavaScript requests /static/app.js (absolute path)
  3. The browser sends this to the frontend (catch-all ingress rule)
  4. Proxy file inspects the Referer header
  5. Extracts the proxy prefix: /proxy/ns/name
  6. Responds with 308 Permanent Redirect to /proxy/ns/name/static/app.js
  7. Browser follows redirect → ingress routes to proxy service

Exclusions (not redirected):

  • /_next/* — Next.js internals
  • Known kube-workspaces paths: /api/v1/, /api/admin/, /api/auth/, /workspaces, /volumes, /admin, etc.

Frontend Proxy URL Generation

frontend/src/lib/api.ts exports:

// All proxy traffic goes through the main host
export function getProxyUrl(namespace: string, name: string, path: string): string {
  const cleanPath = path.startsWith("/") ? path.slice(1) : path;
  return `/proxy/${namespace}/${name}/${cleanPath}`;
}

Example: getProxyUrl("user1", "my-code", "/") → /proxy/user1/my-code/

The kw-session cookie is sent automatically because the proxy is on the same domain.

Dev Server Proxy (frontend/server.mjs)

The custom dev server replicates production routing for local development:

Proxied paths: /api/*, /auth/*, /proxy/* → API (default http://localhost:8090)

Path rewriting: /api/... is stripped to /... before forwarding (mirrors the ingress-level rewrite used by controllers like nginx: rewrite-target: /$2).

Production Server (frontend/server-prod.mjs)

In production, the frontend uses a subprocess architecture to handle escaped proxy requests:

Architecture:

  1. server-prod.mjs listens on port 3000 (the container’s exposed port)
  2. It spawns node server.js (Next.js standalone output) on an internal port (3001)
  3. All requests pass through server-prod.mjs which acts as a transparent proxy

Escaped request recovery:

  • Checks Referer header for proxy prefix extraction
  • Falls back to kw-proxy-prefix cookie when no Referer is present
  • Applies path blocklist (FRONTEND_PATH_PREFIXES) to avoid hijacking app routes
  • Forwards recovered requests to the proxy service (PROXY_URL env var)

Why subprocess? The Next.js standalone server.js relies on webpack internals that aren’t available when importing it directly. The subprocess approach avoids this dependency issue while still allowing the proxy logic wrapper.

Handles /sw.js: Serves a no-op ServiceWorker directly (prevents noVNC registration errors).


ProxyConfig Options

The proxyConfig field on Image CRs controls per-image proxy behavior. These settings are defined in the ImageProxyConfig struct (controller/api/v1alpha1/image_types.go) and read by the proxy service at request time via the K8s API.

needsNoopSW

proxyConfig:
  needsNoopSW: true

Type: bool (default: false)

Effect: Enables serving a no-op ServiceWorker script at /sw.js. Many web applications (noVNC, code-server, KasmVNC) attempt to register a ServiceWorker at the root scope. The no-op SW satisfies the browser’s registration requirement without interfering with the application.

When to use: Enable for any app that registers a ServiceWorker.


rewriteHostAbsolutePaths

proxyConfig:
  rewriteHostAbsolutePaths: true

Type: bool (default: false)

Effect: Enables Referer-based request rewriting at the proxy level. When the proxy receives a request that doesn’t match a valid workspace path, it checks the Referer header and internally rewrites the request.

When to use: Enable for apps that use absolute paths for assets or API calls. Safe to enable by default.


injectBaseTag

proxyConfig:
  injectBaseTag: true

Type: bool (default: false)

Effect: Injects a <base href="/proxy/{namespace}/{name}/"> tag into all HTML responses. This tells the browser to resolve all relative URLs relative to the workspace’s proxy prefix.

When to use: Use for apps that load resources with relative paths but don’t support a configurable base URL. Prefer the app’s native base URL configuration (like FB_BASEURL for filebrowser) when available.

Caution: The <base> tag can break apps that rely on window.location.pathname for routing.


scheme

proxyConfig:
  scheme: https

Type: string, one of http or https (default: http)

Effect: Selects the URL scheme the proxy uses to reach the workspace pod.

When to use: Set https for images that serve TLS on their workspace port (e.g. KasmVNC desktops, linuxserver/kasm). Leave unset — or set http explicitly — for images serving plain HTTP.


tlsSkipVerify

proxyConfig:
  scheme: https
  tlsSkipVerify: true

Type: bool (default: false)

Effect: When connecting over HTTPS, skips verification of the workspace’s TLS certificate (InsecureSkipVerify: true). Has no effect when the scheme is http.

When to use: Required for images serving self-signed certificates, which is typical for KasmVNC-based desktops. Omit it when the workspace presents a certificate signed by a CA the proxy trusts.


tlsInsecure (deprecated)

proxyConfig:
  tlsInsecure: true   # equivalent to: scheme: https + tlsSkipVerify: true

Type: bool (default: false)

Status: Deprecated — use scheme and tlsSkipVerify instead.

This single flag conflated two independent decisions: which scheme to dial, and whether to verify the certificate. As a result “HTTPS with a valid CA” was impossible to express, and the name misleadingly suggested it disabled TLS rather than enabling it.

It is still honoured for backwards compatibility: when scheme is unset, tlsInsecure: true implies both scheme: https and tlsSkipVerify: true. An explicit scheme always takes precedence.


websocketPaths

proxyConfig:
  websocketPaths:
    - /websockify

Type: []string (default: nil)

Effect: Currently informational only. Documents which paths use WebSocket connections. The Go reverse proxy supports WebSocket upgrade transparently on ALL paths.


customRequestHeaders

proxyConfig:
  customRequestHeaders:
    X-Custom-Header: "value"

Type: map[string]string (default: nil)

Effect: Injects additional HTTP headers into every proxied request sent to the workspace pod.


preservePathPrefix

proxyConfig:
  preservePathPrefix: true

Type: bool (default: false)

Effect: When enabled, the proxy forwards the full request path including the proxy prefix (/proxy/{namespace}/{name}/...) to the workspace pod, instead of stripping it. This is required for applications that are configured with a base URL matching the proxy prefix.

How it works:

Without preservePathPrefix (default):

Browser → /proxy/ws/my-fb/api/login
Proxy strips prefix → forwards /api/login to pod
App handles /api/login directly

With preservePathPrefix: true:

Browser → /proxy/ws/my-fb/api/login
Proxy preserves prefix → forwards /proxy/ws/my-fb/api/login to pod
App strips its configured baseURL (/proxy/ws/my-fb) → handles /api/login

When to use: Required for apps that:

  1. Support a base URL/path prefix configuration (CLI flag, env var, config file)
  2. Use that configuration to both generate URLs AND route incoming requests via path prefix stripping
  3. Would otherwise have root-relative paths that escape the proxy

Location header handling: When preservePathPrefix is true, the proxy assumes the app generates Location headers with the full prefix already included, so it doesn’t double-prefix them.

Example with filebrowser: