> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kaireonai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Security

> Defense-in-depth security architecture in KaireonAI: encryption, tenant isolation, authentication, authorization, audit logging, and compliance.

KaireonAI is built with security at every layer. This page covers the full security posture — encryption, isolation, access control, input validation, audit logging, and compliance features that are built into the platform, not bolted on.

## Architecture Overview

Security is enforced at four boundaries:

1. **Network** — TLS in transit, SSRF prevention, rate limiting, circuit breakers
2. **Authentication** — Multiple auth methods (password, SSO, MFA, API keys) with secure credential storage
3. **Authorization** — Role-based access control with tenant isolation on every query
4. **Data** — Encryption at rest, PII masking, tamper-evident audit logging

Every API endpoint validates input with Zod schemas before processing. The formula engine uses a custom recursive-descent parser — dynamic code execution is never used.

## Encryption

### At Rest

All sensitive credentials (connector passwords, API tokens, OAuth secrets) are encrypted with **AES-256-GCM** before storage. Each credential record uses a unique initialization vector (IV) and authentication tag, preventing both decryption and tampering without the encryption key.

Platform API keys (prefixed `krn_`) are stored as one-way hashes — the original key cannot be recovered from the database.

### In Transit

All connections to KaireonAI use HTTPS/TLS. The hosted playground at `playground.kaireonai.com` enforces TLS. Self-hosted deployments should terminate TLS at the load balancer or reverse proxy.

## Tenant Isolation

Every API request is scoped to a single tenant. Cross-tenant data access is architecturally prevented.

* **Tenant resolution** — Each request resolves a `tenantId` from the JWT session or the API key binding. API key authentication ignores the `X-Tenant-Id` header to prevent spoofing.
* **Database enforcement** — A shared tenant-filter helper injects `tenantId` into every Prisma `where` clause. A scoped-tenant wrapper provides CRUD methods that automatically include the tenant filter.
* **PostgreSQL Row-Level Security** — Database-level RLS policies provide a second layer of isolation, ensuring that even raw SQL queries cannot access data outside the tenant boundary.
* **Fail closed** — If the tenant cannot be resolved or validated, the request is denied with `403 Forbidden`. If the database is unreachable during validation, the request is also denied.
* **Single-tenant mode** — Self-hosted deployments can set `SINGLE_TENANT_MODE=true` to bypass multi-tenant resolution.

<Note>
  There is no admin bypass that returns data across tenants. Every database query passes through tenant filtering.
</Note>

## Authentication

KaireonAI supports multiple authentication methods:

| Method           | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Password**     | Bcrypt-hashed passwords with configurable rounds. Passwords are never stored in plaintext.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **OIDC SSO**     | Enterprise single sign-on via OpenID Connect 2.0. Configure your IdP (Okta, Azure AD, OneLogin, etc.) in Settings. SAML 2.0 is on the roadmap.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| **TOTP/MFA**     | Time-based one-time passwords per RFC 6238 (compatible with any TOTP authenticator app). Endpoints at `/api/v1/auth/mfa` — `setup`, `enable`, `verify`, `disable` — are implemented with encrypted secret storage, one-way-hashed backup codes, timing-safe comparison, and rate-limited verification. Session-level enforcement is active: admin accounts with MFA enabled must complete a step-up verify within the last 15 minutes before any state-changing `/api/*` write, enforced in edge middleware via a server-issued HMAC `kaireon_stepup` cookie (see [MFA enforcement](/governance-security/mfa-enforcement)). WebAuthn / passkeys are also supported as a second factor. |
| **API Keys**     | Programmatic access with `krn_`-prefixed keys. Keys are hashed at creation — the plaintext is shown once and never stored.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| **Google OAuth** | Social login via Google OAuth 2.0 for development and smaller teams.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

### Account Lockout

Failed login attempts trigger progressive account lockout. The lockout counter uses **atomic database operations** to prevent race conditions where concurrent failed attempts could bypass the threshold. After the configured number of failures (default 5), the account is locked for a cooldown period.

### Internal Service Authentication

Internal service-to-service calls (e.g., worker to API) authenticate with a dedicated `INTERNAL_SERVICE_SECRET` environment variable. This secret is separate from `NEXTAUTH_SECRET` — the platform no longer falls back to the NextAuth secret for internal auth, preventing accidental secret reuse.

### Session Security

Authentication uses JWT-based sessions via NextAuth. Session tokens are HTTP-only cookies with `Secure` and same-site cookie flags in production. Tokens have configurable expiry.

## Authorization (RBAC)

Three built-in roles control access:

| Role       | Permissions                                                                                                       |
| ---------- | ----------------------------------------------------------------------------------------------------------------- |
| **Admin**  | Full access: create/edit/delete all entities, manage users, view audit logs, configure retention, approve changes |
| **Editor** | Create and edit offers, flows, pipelines, rules, and policies. Cannot manage users or view audit logs.            |
| **Viewer** | Read-only access to all platform data. Cannot create, edit, or delete any entity.                                 |

Role checks are enforced at the API route level. UI elements are hidden based on role, but the server-side check is the authoritative gate.

### SCIM Provisioning

Automated user lifecycle management via SCIM 2.0. Provision and deprovision users from your identity provider (Okta, Azure AD, etc.) without manual account creation.

## Input Validation

Every API endpoint validates request bodies, query parameters, and path parameters with **Zod schemas** before any business logic executes. Invalid requests are rejected with structured error messages.

### Safe Formula Engine

The formula engine (used for computed values in decision flows) is a custom **tokenizer + recursive-descent parser**. It supports arithmetic, comparison, ternary, and built-in functions (`min`, `max`, `round`, `abs`, `coalesce`, `concat`).

* No dynamic code execution of any kind (`eval`, `Function` constructor, etc. are never called)
* Syntax errors produce clear error messages, not runtime crashes

### SQL Injection Protection

Filter conditions in pipelines and decisioning gates use a **structured field + operator + value** model, not raw SQL string concatenation. The filter engine parses the field name, operator, and value as separate typed parameters, then constructs parameterized queries. This eliminates SQL injection by design — there is no regex-based sanitization step that could be bypassed.

### SSRF Prevention

URL validation on all outbound requests blocks access to internal network addresses (private IP ranges, localhost, metadata endpoints). This prevents server-side request forgery through connector configurations, webhook URLs, and **external scoring endpoints**. The validation covers IPv4 private ranges (10.x, 172.16-31.x, 192.168.x), IPv6 loopback and link-local, and cloud metadata endpoints (169.254.169.254).

### CSRF Protection

API-key-authenticated requests enforce `Content-Type: application/json` validation. Requests without the correct content type are rejected, preventing cross-site request forgery via form submissions or image tags that cannot set custom content types.

## PII Protection

### Masking Transforms

Data pipelines include two built-in transforms for protecting sensitive data:

* **Hash transform** — Replaces field values with a one-way SHA-256 hash for pseudonymization
* **Mask PII transform** — Pattern-based masking that preserves partial information (e.g., `***-**-6789` for SSN, `u***@example.com` for email)

Both transforms are available as pipeline nodes in the visual editor.

### Connector Credential Masking

Connector `authConfig` fields are **never returned in any API response**. All GET endpoints for connectors explicitly exclude credential fields from the database select clause. This applies to list, detail, and search responses — credentials are write-only.

### Encrypted Connector Credentials

Connector `authConfig` fields (passwords, tokens, secrets) are stored as AES-256-GCM encrypted JSON. The encryption key is derived from the `CONNECTOR_ENCRYPTION_KEY` environment variable.

### WhatsApp Credentials

WhatsApp channel credentials are encrypted with the same AES-256-GCM scheme as other connector credentials.

## Audit Logging

All entity mutations (create, update, delete) are recorded in an immutable audit log with a **SHA-256 cryptographic integrity chain**.

### Tamper Evidence

Each audit record's hash is computed over its contents plus the hash of the previous record, forming a blockchain-style chain. Tampering with any record breaks the chain from that point forward.

```
hash[n] = SHA-256(action + entityType + entityId + ... + hash[n-1])
```

The verification endpoint (`GET /api/v1/audit-logs/verify`) checks the entire chain and reports the first broken link if tampering is detected.

### Hash versions

Two hash formats coexist, distinguished by the value stored in each record's `integrityHash`:

* **Legacy** — a bare 64-character hex digest. Computed over the record's fields serialized in a fixed order.
* **v2** — prefixed `v2:` and computed over a **canonical serialization** with object keys sorted recursively. Because the `before` / `after` / `changes` snapshots live in PostgreSQL `jsonb` columns, which do not preserve key insertion order, canonical serialization ensures a record still verifies after a database round-trip that reorders keys.

The writer emits v2; the verifier recomputes each record with the format its stored hash indicates, so existing legacy records keep verifying and legacy→v2 chains link seamlessly (chain links store the hash string verbatim, prefix included).

### Resilience

The audit system uses a circuit breaker pattern. If the database is temporarily unavailable, events are buffered in memory (up to 500) and flushed when connectivity is restored. A per-tenant mutex prevents hash chain forks from concurrent writes.

If audit events are dropped (buffer full, persistent database failure), a **drop counter** is incremented and a critical-level log is emitted with the count of lost events. This ensures that audit data loss is never silent — your log aggregator will catch it even if the database cannot.

### Export

Audit logs can be exported in JSON, CSV, or SOC 2 format via `GET /api/v1/audit-export` for regulatory reporting and evidence collection.

## Rate Limiting & Circuit Breakers

### Rate Limiting

Sliding-window rate limiting is applied to the authentication surface — sign-in, registration, MFA (setup, enable, verify and disable), the WebAuthn ceremony routes, and SSO callbacks — as well as the decisioning endpoints and the health and readiness probes. Rate limiting the probes prevents denial-of-service attacks that target monitoring endpoints.

It is **not** applied uniformly across the management API: user administration, permission assignment, API-key minting, SCIM provisioning and key rotation currently have no limiter. Treat the management plane as protected by authentication and RBAC rather than by rate limiting.

Limits are configurable per route and return standard `429 Too Many Requests` responses with `Retry-After` headers when exceeded.

### Circuit Breakers

External service calls (connectors, webhooks, third-party APIs) are wrapped in circuit breakers that:

* Track failure rates over a configurable window
* Open the circuit after a threshold is exceeded, failing fast instead of waiting for timeouts
* Automatically retry after a cooldown period

## Webhook Security

Inbound webhooks are verified using **signature verification**. Each webhook delivery includes a signature header computed with a shared secret, preventing spoofed payloads.

## GDPR / CCPA Compliance

### DSAR (Data Subject Access Requests)

The `/api/v1/dsar` endpoint supports both **right-of-access** (data export) and **right-to-erasure** (data deletion) requests. DSAR processing is asynchronous via a job queue.

### Consent Management

Consent state is tracked per customer and respected in decision flows. Customers without active consent are excluded from decisioning.

### Data Retention

Configurable per-tenant retention policies control how long different data classes are kept:

| Data Class     | What It Covers                                    |
| -------------- | ------------------------------------------------- |
| `interactions` | Customer interaction history and response records |
| `decisions`    | Decision trace records                            |
| `metrics`      | Behavioral and pipeline execution metrics         |
| `audit`        | Audit log entries (supports legal hold)           |

Legal hold can be applied to any data class to prevent automatic purging regardless of the retention period.

## Responsible Disclosure

If you discover a security vulnerability in KaireonAI, please report it responsibly. See [SECURITY.md](https://github.com/kaireonai/platform/blob/main/SECURITY.md) on GitHub for our disclosure policy and contact information.

## Related

<CardGroup cols={3}>
  <Card title="Compliance & Privacy" icon="scale-balanced" href="/governance-security/compliance">
    Tenant isolation, audit logging, DSAR, PII masking, data retention
  </Card>

  <Card title="Authentication" icon="lock" href="/governance-security/authentication">
    User auth, API keys, SSO, and session management
  </Card>

  <Card title="Audit Logs API" icon="list-check" href="/api-reference/audit-logs">
    Full API reference for audit log endpoints
  </Card>
</CardGroup>
