Skip to content

AuthAPI and TellyID deployment

Project: playtelly-iac
Services: services/access/AuthApi · services/access/Tellyid
Stack: Go (Fiber) · Zitadel · APISIX


1. Architecture Overview

Browser (Shaka Player)
        │
        │  GET /api/auth/me  (every 15 min)
        ▼
   APISIX Gateway
   ┌────────────┐        ┌──────────────────┐
   │  AuthApi   │◄──────►│  Zitadel (IdP)   │
   │ (Go/Fiber) │        │  PAT token auth  │
   └────────────┘        └──────────────────┘
        │  redirect (if unauthenticated)
        ▼
   TellyID  (login UI)
   └─► /auth?redirect_uri=...

Cookie domain: .castis.io — shared across authapi.castis.io and tellyid.castis.io.

Session lifetime: 1 hour (3600 s). Extended automatically on every /api/auth/me call while the user is actively watching.


2. Repository Structure

playtelly-iac/
└── services/
    └── access/
        ├── AuthApi/
        │   ├── base/
        │   │   ├── apisix/
        │   │   │   ├── private/
        │   │   │   │   └── apisixroute.yaml       # internal / admin routes
        │   │   │   └── public/
        │   │   │       ├── 01-certificate.yaml
        │   │   │       ├── 02-apisixtls.yaml
        │   │   │       ├── 03-apisixroute.yaml
        │   │   │       └── 04-apisixupstream.yaml
        │   │   ├── deployment.yml
        │   │   ├── secret.yml
        │   │   └── service.yml
        │   └── overlays/
        └── Tellyid/
            ├── base/
            │   ├── apisix/
            │   │   ├── private/
            │   │   │   └── apisixroute.yaml
            │   │   └── public/
            │   │       ├── 01-certificate.yaml
            │   │       ├── 02-apisixtls.yaml
            │   │       ├── 03-apisixroute.yaml
            │   │       └── 04-apisixupstream.yaml
            │   ├── deployment.yml
            │   └── service.yml

3. AuthApi Service — Deployment

3.1 deployment.yml

Define the AuthApi container, set the image from your internal registry, and reference the secret (below) as envFrom so environment variables are injected at runtime. Expose the Go Fiber port (typically 8080).

3.2 secret.yml

Stores the credentials the AuthApi needs at runtime. Required keys:

Key Description
ZITADEL_DOMAIN Full URL of your Zitadel instance (e.g. https://zitadel.castis.io)
ZITADEL_PAT Personal Access Token used to call Zitadel's /v2/sessions API
COOKIE_DOMAIN Should be .castis.io to share cookies across subdomains

Security: Never commit plain-text PAT values. Use Sealed Secrets or an external secrets manager in production.

3.3 service.yml

Exposes the AuthApi pod internally on port 80, forwarding to the container's Fiber port. This is what APISIX's upstream targets.


4. TellyID Service — Deployment

TellyID is the login UI. It handles the OIDC callback from Zitadel and sets the three session cookies (zitadel_session_id, zitadel_session_token, zitadel_user_id) on the .castis.io domain before redirecting back to the redirect_uri.

4.1 deployment.yml

Same structure as AuthApi. Define the container image and expose the TellyID app port (typically 3000).

4.2 service.yml

Exposes TellyID internally on port 80, targeting the container port. No secret.yml is required unless TellyID needs its own Zitadel credentials separate from AuthApi.


5. APISIX Routing Configuration

Each service has four APISIX manifests under base/apisix/public/. The filename prefix (01–04) defines the required apply order since later resources reference earlier ones.

File responsibilities

File Purpose
01-certificate.yaml Declares the TLS certificate for the service hostname
02-apisixtls.yaml Binds the certificate to the APISIX TLS store
03-apisixroute.yaml Defines HTTP routes: hostname, path matching, upstream reference, and plugins
04-apisixupstream.yaml Defines the backend upstream pointing to the Kubernetes service

Always apply in order. The route (03) references the TLS store (02), which references the certificate (01). Applying out of order causes APISIX to reject the route.

CORS requirement for AuthApi

The AuthApi route must have CORS configured with allow_credentials: true and the Shaka player origin explicitly listed. Without this, the browser will block the credentials: 'include' fetch from the frontend.

Private routes

The base/apisix/private/apisixroute.yaml in each service defines internal cluster routes (no TLS termination). These are used for service-to-service communication and should not be exposed externally.


6. Session Keep-Alive: Token Refresh Logic

6.1 Purpose

By default Zitadel sessions expire after 60 minutes of inactivity. Without intervention, a user watching a long video will be silently logged out. The extendZitadelSession function prevents this by resetting both the Zitadel session timer and the browser cookies on every /api/auth/me call.

6.2 How extendZitadelSession works

The function accepts the Fiber context and the three session values read from the incoming cookies (sessionID, sessionToken, userID). It does two things in sequence:

Step 1 — Extend the Zitadel session timer

Sends a PATCH /v2/sessions/{sessionID} request to Zitadel with lifetime: 3600s using the ZITADEL_PAT from config as a Bearer token. If this call fails due to a network error, it logs the failure but continues to step 2 regardless.

Step 2 — Reset browser cookies (always runs)

Regardless of whether the Zitadel PATCH succeeded, it calls c.Cookie(...) three times to rewrite all three session cookies with MaxAge: 3600. This means the browser session stays alive even during transient Zitadel connectivity issues.

func extendZitadelSession(c *fiber.Ctx, sessionID, sessionToken, userID string) {
    pat := config.Get("ZITADEL_PAT", "")
    tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
    client := &http.Client{Transport: tr}

    body, _ := json.Marshal(map[string]interface{}{
        "lifetime": "3600s",
    })

    req, _ := http.NewRequest("PATCH",
        fmt.Sprintf("%s/v2/sessions/%s", config.ZitadelDomain, sessionID),
        bytes.NewBuffer(body),
    )
    req.Header.Set("Authorization", "Bearer "+pat)
    req.Header.Set("Content-Type", "application/json")

    resp, err := client.Do(req)
    if err != nil {
        log.Printf("extendZitadelSession: session %s — ZITADEL extend failed (network error), browser cookies reset only", sessionID)
    } else {
        defer resp.Body.Close()
        log.Printf("extendZitadelSession: session %s — ZITADEL timer + browser cookies both reset to 1hr", sessionID)
    }

    // Always reset cookies regardless of Zitadel extend success/failure
    cookieDomain := ".castis.io"
    c.Cookie(&fiber.Cookie{
        Name: "zitadel_session_id", Value: sessionID,
        Domain: cookieDomain, HTTPOnly: true, Secure: true,
        SameSite: "Lax", MaxAge: 3600, Path: "/",
    })
    c.Cookie(&fiber.Cookie{
        Name: "zitadel_session_token", Value: sessionToken,
        Domain: cookieDomain, HTTPOnly: true, Secure: true,
        SameSite: "Lax", MaxAge: 3600, Path: "/",
    })
    c.Cookie(&fiber.Cookie{
        Name: "zitadel_user_id", Value: userID,
        Domain: cookieDomain, HTTPOnly: true, Secure: true,
        SameSite: "Lax", MaxAge: 3600, Path: "/",
    })
}

6.3 Calling from HandleGetMe

extendZitadelSession is called synchronously inside HandleGetMe, after the session is validated but before the response is returned. This is intentional — cookies must be written to the response before it is sent, so this cannot be deferred to a goroutine.

The call sequence inside HandleGetMe looks like:

1. Read cookies from request
2. Validate session against Zitadel
3. Call extendZitadelSession(c, sessionId, sessionToken, userId)   ← synchronous
4. Fetch user info from Zitadel /v2/users/{userId}
5. Return session JSON to client

Note on goroutines: Do not move extendZitadelSession into a goroutine. Fiber recycles the *fiber.Ctx after the handler returns, so any c.Cookie(...) call inside a goroutine would write to an already-recycled context and silently fail.

6.4 Behaviour matrix

Scenario Zitadel PATCH Browser cookies
User watching, network healthy Reset to 60 min Reset to 60 min
User watching, Zitadel unreachable Fails, logged Reset to 60 min
User idle > 60 min (no /me poll) Expires naturally Expires naturally

7. Shaka Frontend Integration

7.1 Overview

The Shaka player frontend must:

  1. Check the auth session on page load via /api/auth/me.
  2. Redirect unauthenticated users to TellyID with a redirect_uri so they return to the correct page after login.
  3. Poll the session every 15 minutes to keep the session alive during long viewing sessions. Each poll triggers extendZitadelSession server-side, resetting the 1-hour window.
  4. Load the video only once, guarded against double-initialisation from concurrent onload and setInterval calls.

7.2 Complete implementation

let videoLoaded = false;  // guard: prevents loadCustomVideo() running more than once

async function checkSession() {
  try {
    const res = await fetch('https://authapi.castis.io/api/auth/me', {
      credentials: 'include'  // required: sends session cookies cross-origin
    });

    if (!res.ok) {
      const redirectUrl = encodeURIComponent(window.location.origin + "/");
      window.location.href = `https://tellyid.castis.io/auth?redirect_uri=${redirectUrl}`;
      return;
    }

    const session = await res.json();
    log(`Session OK — user: ${session.user?.email || 'unknown'}`, 'ok');

    if (!videoLoaded) {
      videoLoaded = true;
      loadCustomVideo();  // only runs once per page load
    }

  } catch (e) {
    log('Session check failed: ' + e.message, 'err');
    const redirectUrl = encodeURIComponent(window.location.origin + "/");
    window.location.href = `https://tellyid.castis.io/auth?redirect_uri=${redirectUrl}`;
  }
}

window.onload = () => {
  checkSession();
};

// Poll every 15 min — each call extends the server-side session by 1 hour.
setInterval(checkSession, 15 * 60 * 1000);

7.3 Key changes explained

Change Reason
videoLoaded flag Prevents duplicate video initialisation when checkSession fires from both window.onload and setInterval
redirect_uri uses window.location.origin + "/" Works correctly across staging and production without hardcoding the hostname
Interval reduced to 15 min Keeps well within the 1-hour session window; each poll resets both the Zitadel timer and the browser cookie expiry
credentials: 'include' Required for cross-origin cookie transmission to authapi.castis.io

8. End-to-End Auth Flow

1. User opens Shaka player page
        │
2. window.onload → checkSession()
        │
3. GET https://authapi.castis.io/api/auth/me  (credentials: include)
        │
   ┌────┴──────────────────────────────────┐
   │ Cookie valid?                          │
   │                                        │
   │  YES ──► extendZitadelSession()        │  ← resets Zitadel + browser cookies
   │          return session JSON           │
   │          videoLoaded = true            │
   │          loadCustomVideo()             │
   │                                        │
   │  NO  ──► redirect to TellyID login ───►│
   └───────────────────────────────────────┘
        │
4. https://tellyid.castis.io/auth?redirect_uri=https%3A%2F%2Fshaka.castis.io%2F
        │
5. User authenticates via Zitadel OIDC
        │
6. TellyID sets cookies on .castis.io:
     zitadel_session_id
     zitadel_session_token
     zitadel_user_id
        │
7. TellyID redirects back to redirect_uri
        │
8. Page reloads → step 1 repeats → video loads
        │
9. Every 15 min: setInterval fires checkSession()
        └──► server calls extendZitadelSession()
             Zitadel timer + cookie MaxAge both reset to 3600s

9. Troubleshooting

Session expires despite active viewing

  • Check AuthApi logs for ZITADEL timer + browser cookies both reset to 1hr. If absent, extendZitadelSession is not being reached.
  • Confirm the frontend setInterval is set to 15 * 60 * 1000 and not the old 24-hour value.
  • Confirm the APISIX CORS configuration for AuthApi includes allow_credentials: true and the correct Shaka origin.

Redirect loop (login → shaka → login)

  • The redirect_uri value must be whitelisted in the Zitadel application settings under allowed redirect URIs.
  • Verify all three session cookies are present in the browser after login. If they are missing, check that TellyID is setting Domain: .castis.io and Secure: true on the cookies.

videoLoaded still true after returning from login

  • videoLoaded is page-scoped. A full page reload (which occurs on redirect) resets it to false automatically — no manual reset is needed.

TLS certificate not loading

  • Apply 01-certificate.yaml and 02-apisixtls.yaml before 03-apisixroute.yaml. APISIX requires the TLS store to exist before a route can reference it.

Last updated: 2026-05-29