> For the complete documentation index, see [llms.txt](https://docs.pyck.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pyck.cloud/development/authentication.md).

# Authentication

Audience: Programmer

## 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

### 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

### Personal Access Token (PAT) Authentication

* Alternative authentication method using long-lived tokens
* PATs are introspected against ZITADEL's token introspection endpoint
* Results are cached to improve performance

## Authorization

### Roles and Permissions

The backend supports the following roles with increasing privilege levels:

* Reader (1000): Read-only access
* Writer (1001): Read and write access
* Admin (1002): Administrative access
* System (1003): System-level access

### Tenant Isolation

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

## Implementation Details

### Authentication Header

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

### 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](/graphql-api/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/`)
* Company registration GraphQL mutation
* 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, eliminating the need to hardcode environment-specific values.

### Endpoint

```
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. This approach ensures configuration values remain consistent across environments without requiring separate build artifacts.

**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
};
```

## 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

## Tenant Registration Email Behavior

When using the [`registerTenant`](/graphql-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](/graphql-api/mutations/registertenant.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pyck.cloud/development/authentication.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
