# Authentication

Audience: Developer

How to authenticate against the Pyck API with ZITADEL tokens

## Overview

Pyck uses ZITADEL for authentication and authorization. This document explains how to implement authentication when integrating with the Pyck backend API.

## Authentication flow

1. Authentication is handled via JWT tokens or Personal Access Tokens (PATs)
2. The authentication middleware validates these tokens against ZITADEL
3. User information, including roles and tenant information, is extracted and added to the request context

## Authentication methods

The Pyck GraphQL API supports two primary authentication methods:

### JWT authentication

- Standard OpenID Connect flow using JWT tokens
- Tokens are validated against ZITADEL's JWKS endpoint
- Token validation includes signature verification and claims validation

JWT (JSON Web Token) authentication is the most common method and involves including a valid JWT token in the Authorization header of your requests. JWT tokens are typically obtained through the ZITADEL authentication flow. Once you have a token, include it in all your API requests.

### Personal access token (PAT) authentication

- PATs are introspected against ZITADEL's token introspection endpoint
- Results are cached to improve performance

For system integrations and automation, you can use a personal access token. PATs are long-lived tokens that are created in ZITADEL for a machine user. Pyck has no GraphQL mutation for creating them.

## Sending authenticated requests

### Authorization header

- All authenticated requests require: `Authorization: Bearer <token>`
- Where `<token>` is either a valid JWT or PAT

```text
Authorization: Bearer <your_jwt_token>
```

```text
Authorization: Bearer <your_personal_access_token>
```

### Example authentication flow

#### Obtain a JWT token

Authenticate with ZITADEL to obtain a JWT token. This typically involves redirecting the user to the ZITADEL login page and handling the callback with the token.

#### Make authenticated requests

Once you have a token, include it in your GraphQL requests:

```javascript
// Example with fetch API
const response = await fetch('https://eu.pyck.cloud/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  body: JSON.stringify({
    query: `
      query {
        me {
          UserID
          Username
          Email
        }
      }
    `
  })
});
```

#### Handle token expiration

JWT tokens expire after a certain period. When a token expires, you'll receive a 401 Unauthorized response. You should:

1. Detect the 401 response
2. Request a new token using the refresh token flow
3. Retry the original request with the new token

## Authorization

### Roles and permissions

The backend supports the following roles with increasing privilege levels:

- Reader (`reader`): Read-only access
- Writer (`writer`): Read and write access
- Admin (`admin`): Administrative access
- System (`system`): System-level access

The lowest value is `none` (no access), so the full set is `none`, `reader`, `writer`, `admin` and `system`. Access to individual services is gated by separate service roles, described in [Service Roles](https://docs.pyck.cloud/dev/developers/service-roles.md).

### Tenant isolation

- Users are associated with a tenant
- Tenant ID can be specified via HTTP headers during authentication
- Authentication ensures users can only access resources within their tenant

### Tenant liveness check

In addition to role-based authorization, Pyck enforces tenant liveness checks:

**Home Tenant Check:**

- After token validation, the system verifies that the user's home tenant (the tenant they belong to) is not disabled
- If the home tenant is disabled, the request is rejected with **401 Unauthorized** regardless of which tenants are specified in request headers
- Users from disabled tenants lose access immediately across the system

Tenants named in the `X-Pyck-Tenant-Id` header are checked too. See [Headers documentation](https://docs.pyck.cloud/dev/developers/headers.md#disabled-tenant-behavior) for the rules.

**Cache and Performance:**

- Tenant liveness verdicts are cached with a short TTL (typically 1 minute) to reduce latency
- Lifecycle events (tenant disable/restore) immediately evict cached entries
- Access control changes take effect on the next request after the event; if the event is lost, after at most `PYCK_LIVENESS_CACHE_TTL` (default 1m)

## Implementation details

### Error handling

#### HTTP error response format

All HTTP endpoints (including authentication, health checks, webhooks, and file handlers) return errors in a standardized JSON format:

```json
{
  "error": "Error message description"
}
```

This applies to all non-GraphQL HTTP endpoints. For GraphQL-specific error handling, see the [GraphQL Error Handling](https://docs.pyck.cloud/dev/developers/error-handling.md) documentation.

#### Authentication errors

- Authentication errors return HTTP 401 Unauthorized status codes
- All error responses follow the JSON format shown above
- Common errors include expired tokens, invalid signatures, or insufficient permissions

**Example authentication error response:**

```json
{
  "error": "Unauthorized"
}
```

### Unauthenticated endpoints

Certain endpoints don't require authentication:

- Health check endpoints (`/health`)
- Metrics endpoints (`/metrics`)
- Webhook endpoints (paths containing `/webhook/`)
- Tenant registration GraphQL mutation (registerTenant)

## Frontend configuration discovery

Pyck provides a `/static/settings.json` endpoint that frontends can use to discover OIDC runtime configuration dynamically, so frontends need not hardcode environment-specific values.

### Endpoint

```text
GET /static/settings.json
```

### Response format

```json
{
  "appUrl": "https://app.example.com",
  "authority": "https://auth.example.com",
  "authorityClientId": "123456789",
  "debug": false,
  "environment": "production",
  "graphqlClientUri": "https://app.example.com/graphql",
  "redirectUri": "https://app.example.com/auth/callback",
  "features": {},
  "version": "1.0.0",
  "otelUrl": "https://otel.example.com",
  "otelIngestKey": "key123"
}
```

### Usage

Frontend applications should fetch this endpoint at startup to configure their OIDC client and other runtime settings.

**Example:**

```javascript
const response = await fetch('/static/settings.json');
const settings = await response.json();

// Configure OIDC client
const authConfig = {
  authority: settings.authority,
  client_id: settings.authorityClientId,
  redirect_uri: settings.redirectUri
};
```

### Client discovery document

New clients should use `GET /.well-known/pyck-configuration` instead. It needs no `Authorization` header, and `/static/settings.json` stays as it is (camelCase keys) only for the current frontend. Every key in the discovery document is kebab-case.

```text
GET /.well-known/pyck-configuration
```

```json
{
  "version": 1,
  "meta": { "environment": "eu" },
  "endpoints": {
    "auth": { "url": "https://auth.example.com" },
    "app": { "url": "https://app.example.com" },
    "graphql": { "url": "https://app.example.com/graphql" },
    "otel": { "url": "https://otel.example.com", "key": "key123" }
  },
  "components": {
    "pyck-control": {
      "auth": {
        "client-id": "123456789",
        "redirect-uri": "https://app.example.com/auth/callback"
      },
      "extra": { "build": "1.0.0", "debug": false, "features": {} }
    },
    "pyck-cli": { "auth": { "client-id": "987654321" } }
  }
}
```

- `version`: the version of the whole document. It changes only when a field is removed or renamed, never when a field is added.
- `meta.environment`: the name of the environment, for example `dev`, `test`, `demo` or `eu`. Operators can set it with `PYCK_DISCOVERY_ENVIRONMENT`, see [Optional discovery environment name](https://docs.pyck.cloud/dev/operations/configuration.md#optional-discovery-environment-name).
- `endpoints`: each entry is an object with a `url`. `auth` (the OIDC issuer), `app` and `graphql` are always present. `worker-api`, `ui-store`, `feedback`, `barcodes` and `otel` appear only when configured, and `otel` can also carry a `key`.
- `components`: one entry per client, which can be `pyck-control`, `pyck-cli`, `pyck-mobile`, `pyck-bruno` and `pyck-mcp`. Each has `auth.client-id`, and a client without a client ID is left out. The exception is `pyck-control`: it is always present with `extra` (`build`, `debug` and `features`), and has `auth` only when a client ID is configured.

## Development guide

When developing against the Pyck API, you'll need to:

1. Obtain a valid token from ZITADEL
2. Include this token in the Authorization header of all API requests
3. Implement token refresh logic when tokens expire
4. Handle authentication errors appropriately in your client application

## Testing authentication

For testing purposes, you can:

1. Use the ZITADEL developer console to generate test tokens
2. Verify token validity using the introspection endpoint
3. Test different roles to ensure proper authorization behavior

You can test your authentication by querying the `me` endpoint, which returns information about the authenticated user:

```graphql
query {
  me {
    UserID
    Username
    Email
  }
}
```

If authentication is successful, you'll receive information about your user. If not, you'll receive an error message.

## Tenant registration email behavior

When using the [`registerTenant`](https://docs.pyck.cloud/dev/api/mutations/registertenant.md) mutation, the system allows re-use of the same admin email address across multiple tenant registrations. Each tenant receives a unique tenant-specific primary email (e.g., `user@tenant1.example.com`, `user@tenant2.example.com`), with the original email added as an alias.

**Important:** Cross-tenant authorization is not supported. A user created for one tenant cannot access another tenant's resources, even if they share the same email alias.

**Recommendation:** Use unique email addresses for each tenant registration to avoid confusion and ensure clear account separation.

For detailed information, see the [registerTenant mutation documentation](https://docs.pyck.cloud/dev/api/mutations/registertenant.md).
