authentication.mdRaw

Authentication and Access Control

This guide explains how AISentinel authenticates users and systems, how to configure Single Sign-On (SSO), how to manage tenant-scoped API keys and service accounts, and how to audit and rotate credentials safely. It’s written for Portal users and tenant administrators — operator-only instructions (like deployment environment variables) are documented elsewhere.

Key concepts you'll find below:

  • Authentication methods: SSO (OIDC/SAML), NextAuth user flows, tenant API keys, and short-lived execution tokens.
  • API key lifecycle: create, scope, rotate, extend, and revoke.
  • SSO setup and validation flows supported by the Portal, and how to test configuration.
  • Execution tokens for short-lived approvals and how they differ from API keys.
  • Security best practices and common troubleshooting steps.

If you need operator-level details (KMS configuration, secrets manager integration), see Encryption & BYOK and Configuration Management.

Authentication methods overview

  • NextAuth (email magic links, email/password, developer sign-in) — the Portal default for human users.
  • Enterprise SSO (OIDC / SAML / OAuth providers) — recommended for production teams. The portal supports Okta, Azure AD, Google, Auth0 and generic OIDC/SAML providers.
  • Tenant API keys — scoped credentials for programs, agents, and CI/CD. These are tenant-scoped and appropriate for SDKs or automated processes.
  • Execution tokens — short-lived signed tokens minted to approve side-effecting operations (e.g., server-side evaluations). These tokens are intentionally short-lived and restricted by role.

All authentication events are audited and visible in tenant audit logs.

Single Sign-On (SSO) — setup & testing

Overview:

  • The Portal reads SSO configuration from tenant settings and exposes the sign-in button when SSO is enabled.
  • A tenant admin or owner configures SSO provider, client IDs, and optionally an issuer or OIDC discovery endpoint.
  • Client secrets are considered sensitive: use the Portal-provided provisioning flow which stores them in a secrets store (AWS Secrets Manager is supported when the environment is configured) or in tenant config protected by the server.

What you can do in the Portal (UI) vs API:

  • UI: You can set non-sensitive SSO metadata (for many providers that means client IDs and issuer fields), and the Portal offers a Test button to validate the configuration (the UI calls POST /tenants/{tenant}/sso-test).
  • Admin/API-only: Setting a client secret or performing an automated provisioning flow requires the Admin Owner API flow. Use POST /tenants/provision-sso when you need to persist secrets or run the automated OIDC discovery and validation.

Quick steps (high level):

  1. Create an application in your IdP (Okta/Azure/Google/Auth0). Configure a redirect URL for the Portal: https://<HOST>/api/auth/callback/sso or the portal’s callback path.
  2. Copy the provider Client ID and Client Secret.
  3. In the Portal, navigate to Tenant Configuration -> SSO and paste the Client ID (UI-friendly) and optional domain allowlist.
  4. Use the Admin API POST /tenants/provision-sso (or the Admin UI form) to store the sensitive client_secret. This call performs OIDC discovery and can optionally perform a real token exchange when confirm_test is true.
  5. Test the configuration with the portal (click “Test” which calls POST /tenants/{tenant}/sso-test) and then attempt a sign-in.

Endpoints used by the Portal:

  • GET /tenants/{tenant}/sso-metadata — used by the Portal to render the right SSO provider (buttons and textual hints).
  • POST /tenants/{tenant}/sso-test — quick configuration test.
  • POST /tenants/provision-sso — admin-only provisioning endpoint: it writes SSO client ID metadata and stores client secret in the tenant secrets store.

Troubleshooting:

  • Missing fields: If SSO Test reports “Incomplete … configuration”, verify both client_id and client_secret (for testing flows) are present in tenant config and that the issuer or discovery endpoint is correct.
  • Validation errors: Token exchanges may fail if the provider has additional security settings (callback restrictions, domain allowlists); consult your IdP logs.

API Keys & Service Accounts

API keys are the recommended mechanism for programs and automation. Keys are scoped to a tenant and can be created and managed via the Dashboard and API.

Typical uses:

  • SDK calls and long-running automation (SDKs for Python/JS/Go, etc.)
  • CI/CD jobs and agents that need tenant-scoped access
  • Service account roles that should have reduced privileges (scoped by rulepacks)
  • Scope an api key to one or more rulepacks for specific use cases

Key lifecycle and actions (Portal features map to the following API endpoints):

  • Create a key: POST /api/keys (UI creates keys for the current tenant; you can set name, expires_in_days or expires_at, allowed_rulepacks, and issue_renewal_token).
  • List keys: GET /api/keys — shows status (valid/expiring_soon/grace/expired) and allowed_rulepacks.
  • Revoke a key: DELETE /api/keys/{key_id} — immediate revocation of the credential.
  • Regenerate a key: POST /api/keys/{key_id} — issue a new secret; the previous key stops working.
  • Extend or refresh a key: POST /api/keys/{key_id}/extend — increase expiration or set a new expiry date; request a renewal_token for automation.
  • Rotate expiring keys: POST /api/keys/rotate-expiring — bulk rotation with optional per-key renewal_tokens issued.
  • Update rulepack scoping: POST /api/keys/{key_id}/rulepacks — limits a key to only work with a specific subset of rulepacks.

Important properties and behavior:

  • Expires & warnings: Keys include expires_at and will enter a warning/expiring_soon state before going into grace and then expired. You can extend keys from the UI or API.
  • Renewal tokens: When you request issue_renewal_token, the API returns a one-time renewal_token string (the server stores a hashed digest). Treat it like a sensitive secret and store it in a secure secret manager. Note: renewal tokens are an audit and automation artifact (useful when rotating keys) but they are not a replacement for tenant authentication — actual API calls to extend or rotate keys still require proper authentication.
  • System-generated keys: Some keys are system_generated (used for automatic signups or backend processes). These can have different default expiration durations than user-created keys.
  • Allowed rulepacks: Use allowed_rulepacks to restrict a key’s scope to a limited set of rulepacks. Attempting to run other rulepacks with a scoped key will result in authorization errors.

Developer examples (quick):

Create a key (cURL):

curl -X POST "https://your-aisentinel-host/api/keys" \
  -H "Authorization: Bearer <YOUR_FRONTEND_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"name": "automation-key", "expires_in_days": 30, "allowed_rulepacks":["default"], "issue_renewal_token": true}'

Extend an existing key using a TTL extension (the response can include a renewal_token):

curl -X POST "https://your-aisentinel-host/api/keys/<KEY_ID>/extend" \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"extend_by_days": 30, "issue_renewal_token": true}'

Rotate expiring keys in bulk (Admin/Owner flows):

curl -X POST "https://your-aisentinel-host/api/keys/rotate-expiring" \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"threshold_days": 7, "issue_renewal_token": true, "limit": 100}'

Create a key from a typical SDK (Python):

from aisentinel import Client

client = Client(api_key="TENANT_API_KEY")
new_key = client.keys.create(name="automation", expires_in_days=30, allowed_rulepacks=["default"])  # this call is proxied via the Portal API
print("Created key last4:", new_key.last4)

Create a key (JavaScript / Fetch):

const payload = { name: 'automation-key', expires_in_days: 30, allowed_rulepacks: ['default'], issue_renewal_token: true };
const res = await fetch('/api/keys', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
if (!res.ok) { throw new Error('Failed to create key'); }
const newKey = await res.json();
console.log('Created key last4:', newKey.last4, 'renewal token:', newKey.renewalToken ?? newKey.renewal_token);

Mint an execution token (JavaScript example talking to Portal admin API):

const payload = { tenant: 'demo-tenant', ttl: 300 };
const res = await fetch('/api/admin/tokens/mint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
const j = await res.json();
console.log('Execution token (short-lived):', j.token);

Use the Go SDK with a tenant API key (example uses the governor package):

package main

import (
  "context"
  "fmt"
  governor "github.com/aisentinel/aisentinel-go-sdk"
)

func main() {
  cfg := governor.Config{APIKey: "YOUR_TENANT_API_KEY"}
  g, err := governor.New(cfg)
  if err != nil {
    panic(err)
  }
  ctx := context.Background()
  // Example: evaluate a candidate using the governor client (refer to Go SDK examples in aisentinel-go-sdk/examples)
  res, err := g.Evaluate(ctx, governor.EvaluateRequest{ /* ... */ })
  if err != nil {
    panic(err)
  }
  fmt.Printf("Evaluate response: %+v\n", res)
}

SDK note: The SDK examples in frontend/docs/sdk/README.md show how to create a client with an API key. Use a rotating key provider for long-lived automation secrets.

Execution tokens — short-lived approval tokens

When an operation requires explicit approval (for example, a Python runtime execution or other side-effecting operations), the platform uses short-lived execution tokens.

  • Minting: Execution tokens are minted with POST /admin/tokens/mint (the UI has a Mint Token helper). The call requires that the API key making the request has mint_execution_tokens permission.
  • Purpose: These tokens are stateless HMAC-signed tokens (not API keys). They are intended to be used as a transient token on the specific operation call (e.g., attach the token to an evaluation request that requires side-effecting approval).
  • Best practice: Keep tokens short (a few minutes) and audit usage. Only admin or owner-created API keys may have permission to mint tokens, as assigned by roles.

Roles & Privileges — who can do what

  • OWNER / ADMIN: Full tenant access — can manage SSO, BYOK, and API keys for the tenant, and mint execution tokens for operations.
  • MEMBER: Regular tenant user — can create personal API keys (unless restricted by tenant policy) and manage their own keys; cannot mint execution tokens unless created by an owner.

Tenants can review role restrictions in the Dashboard under Team Management. Use the Roles & Privileges doc to match roles with operations.

BYOK / Encryption and Sensitive Data

  • BYOK (Bring Your Own Key) is supported for tenant data protection and is managed via the Encryption & BYOK guide which explains how to register a customer-owned key and rotate it.
  • For offline packages and special exports, tenant config may include OFFLINE_ENCRYPTION_KEY or use a tenant-managed key to encrypt exports.

Auditing & Monitoring

  • All credential operations (create, rotate, revoke, extend, mint execution tokens) generate audit events and are recorded via the tenant audit log.
  • Use the Dashboard’s Audit area and the API audit endpoints to review events for forensic and compliance purposes.

Best Practices (Checklist)

  • Prefer user SSO for human access; reduce the number of long-lived developer keys.
  • Use scoped keys with allowed_rulepacks to limit damage from token leakage.
  • Make keys short-lived and use issue_renewal_token when automation requires rotation.
  • Rotate keys on a schedule and use POST /api/keys/rotate-expiring for automation.
  • Rotate BYOK master keys per your security policy and use the BYOK rotation endpoints from that doc.

Troubleshooting

  • SSO Test issues: If the SSO Test reports missing or incomplete configuration, check that both Client ID and Client Secret are stored via POST /tenants/provision-sso (Admin) or via your tenant config, and that your IdP allows the Portal callback URL.
  • ‘API key limit reached’ on create: Check your tenant plan and usage; free tiers have a lower limit of keys — upgrade if you need more keys.
  • Rate limiting: The API enforces rate limits on key rotation/extension; retry after the suggested backoff period.
  • Key expired or in grace: Use POST /api/keys/{id}/extend to extend or rotate; or POST /api/keys/{id} to regenerate.