# Admin API

> Manage your organization from your own code. Create an admin app, take a token with a private key or a secret, and call the API with the scopes you grant.

Source: https://docs.trustaige.com/admin-api

Replace these placeholders with your organization's own values:

- `<your-client-id>`: App client ID, for example `q3Jx8vN2mZ0bT5sLwK7yHc4dR1fGaE9uPiO6nVjXkMs`. On the app’s page in the hub, under Credentials.
- `<your-client-secret>`: Client secret, a secret. From the hub: on the app’s page under Credentials. Keep it on your server.

The Admin API is the hub, as an API. An **admin app** is a program that acts on
its own behalf, in its own organization, with exactly the scopes you grant it.
Nobody signs in to it, it holds no roles, and everything it does is recorded in
your audit log as that app.

1. Your program → Trustaige: POST /oauth2/token (client_credentials)
2. Trustaige → Your program: access token, up to an hour
3. Your program → Trustaige: GET /api/admin/… with the token

## Create an admin app

1. In the hub, open **Admin → Admin apps** and click **Create admin app**.
2. Under **What may it do?**, pick the scopes it needs. Each scope is one
   operation, and the app gets exactly these.
3. Under **How does it prove who it is?**, choose **Private key** (recommended:
   no secret exists, so none can leak) or **Client secret**.
4. For a private key, give Trustaige your public key: a **Hosted JWKS URL**
   (fetched and cached, so rotating keys needs nothing in the hub) or a
   **Pasted key set**. Click **Verify keys** to check Trustaige can read them.
   Leave **Assertion Signing Algorithm** at **Any supported**, or pin one.
5. Create the app. Its page shows its client ID under **Credentials**, and the
   client secret if it uses one.

To stop an app, disable it: the tokens it already holds stop working at once.
Removing a scope also takes effect on tokens already issued. Regenerating the
secret or replacing the keys stops the app taking new tokens with the old ones.

## Take a token with a private key

The app proves who it is with a short-lived JWT (a *client assertion*) signed by
its private key, sent in place of a secret
([RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523#section-2.2)). Your
private key never leaves your server, and Trustaige only ever holds the public
half.

### Make a key pair

Any ES256, RS256, PS256 or EdDSA (Ed25519) key works. With OpenSSL, an ES256
(P-256) key:

```bash title="Terminal"
openssl ecparam -name prime256v1 -genkey -noout \
  | openssl pkcs8 -topk8 -nocrypt -out admin-app.key
```

Then turn the public half into a key set. Give each key a `kid`; the assertion
names it, so you can publish a new key beside the old one when you rotate.

```js title="jwks.mjs"
import { createPublicKey } from 'node:crypto';
import { readFileSync } from 'node:fs';

const jwk = createPublicKey(readFileSync('admin-app.key')).export({ format: 'jwk' });
console.log(JSON.stringify({ keys: [{ ...jwk, kid: 'admin-app-1', use: 'sig', alg: 'ES256' }] }, null, 2));
```

```go title="jwks.go"
package main

import (
	"crypto/ecdsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"log"
	"os"
)

func main() {
	pemBytes, err := os.ReadFile("admin-app.key")
	if err != nil {
		log.Fatal(err)
	}
	block, _ := pem.Decode(pemBytes)
	parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		log.Fatal(err)
	}
	pub, err := parsed.(*ecdsa.PrivateKey).PublicKey.ECDH()
	if err != nil {
		log.Fatal(err)
	}
	point := pub.Bytes() // 0x04 || X || Y
	b64 := base64.RawURLEncoding.EncodeToString
	jwk := map[string]string{
		"kty": "EC", "crv": "P-256", "x": b64(point[1:33]), "y": b64(point[33:]),
		"kid": "admin-app-1", "use": "sig", "alg": "ES256",
	}
	out, _ := json.MarshalIndent(map[string]any{"keys": []any{jwk}}, "", "  ")
	os.Stdout.Write(append(out, '\n'))
}
```

```python title="jwks.py"
import json

from cryptography.hazmat.primitives.serialization import load_pem_private_key
from jwt.algorithms import ECAlgorithm

with open("admin-app.key", "rb") as f:
    key = load_pem_private_key(f.read(), password=None)

jwk = json.loads(ECAlgorithm.to_jwk(key.public_key()))
jwk.update(kid="admin-app-1", use="sig", alg="ES256")
print(json.dumps({"keys": [jwk]}, indent=2))
```

Host the output at an `https` URL you control and give the hub that URL, or
paste it into the hub. A hosted set can't redirect: Trustaige doesn't follow
redirects when it fetches one.

### Sign the assertion and ask for a token

| Claim or parameter | Value |
|---|---|
| `iss` and `sub` | Both the app's client ID, `<your-client-id>` |
| `aud` | `https://id.trustaige.com/oauth2/token` (the issuer, `https://id.trustaige.com`, is accepted too) |
| `exp` | Required, and no more than an hour away. A minute or two is plenty. |
| `iat` | Optional; if present, not in the future |
| `jti` | Required, and new every time: Trustaige refuses an assertion it has already seen |
| `kid` (header) | Required when your key set holds more than one signing key |
| `client_assertion_type` | `urn:ietf:params:oauth:client-assertion-type:jwt-bearer` |
| `client_id` | Optional: Trustaige reads it from the assertion's `iss` |

```js title="token.mjs"
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { SignJWT, importPKCS8 } from 'jose';

const TOKEN_URL = 'https://id.trustaige.com/oauth2/token';
const CLIENT_ID = '<your-client-id>';
const key = await importPKCS8(readFileSync('admin-app.key', 'utf8'), 'ES256');

const assertion = await new SignJWT({})
  .setProtectedHeader({ alg: 'ES256', kid: 'admin-app-1' })
  .setIssuer(CLIENT_ID)
  .setSubject(CLIENT_ID)
  .setAudience(TOKEN_URL)
  .setIssuedAt()
  .setExpirationTime('2m')
  .setJti(randomUUID())
  .sign(key);

const res = await fetch(TOKEN_URL, {
  method: 'POST',
  body: new URLSearchParams({
    grant_type: 'client_credentials',
    client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
    client_assertion: assertion,
    scope: 'users:read groups:manage',
  }),
});
if (!res.ok) throw new Error(`token request failed: ${res.status} ${await res.text()}`);
const { access_token, expires_in } = await res.json();
```

```go title="token.go"
package main

import (
	"crypto/rand"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

const (
	tokenURL = "https://id.trustaige.com/oauth2/token"
	clientID = "<your-client-id>"
)

func takeToken() (string, error) {
	pemBytes, err := os.ReadFile("admin-app.key")
	if err != nil {
		return "", fmt.Errorf("reading key: %w", err)
	}
	block, _ := pem.Decode(pemBytes)
	key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return "", fmt.Errorf("parsing key: %w", err)
	}

	now := time.Now()
	t := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.RegisteredClaims{
		Issuer:    clientID,
		Subject:   clientID,
		Audience:  jwt.ClaimStrings{tokenURL},
		IssuedAt:  jwt.NewNumericDate(now),
		ExpiresAt: jwt.NewNumericDate(now.Add(2 * time.Minute)),
		ID:        rand.Text(),
	})
	t.Header["kid"] = "admin-app-1"
	assertion, err := t.SignedString(key)
	if err != nil {
		return "", fmt.Errorf("signing assertion: %w", err)
	}

	resp, err := http.PostForm(tokenURL, url.Values{
		"grant_type":            {"client_credentials"},
		"client_assertion_type": {"urn:ietf:params:oauth:client-assertion-type:jwt-bearer"},
		"client_assertion":      {assertion},
		"scope":                 {"users:read groups:manage"},
	})
	if err != nil {
		return "", fmt.Errorf("requesting token: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("token request failed: %s", resp.Status)
	}
	var body struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return "", fmt.Errorf("decoding token response: %w", err)
	}
	return body.AccessToken, nil
}
```

```python title="token.py"
import time
import uuid

import jwt
import requests

TOKEN_URL = "https://id.trustaige.com/oauth2/token"
CLIENT_ID = "<your-client-id>"

with open("admin-app.key", "rb") as f:
    key = f.read()

now = int(time.time())
assertion = jwt.encode(
    {"iss": CLIENT_ID, "sub": CLIENT_ID, "aud": TOKEN_URL,
     "iat": now, "exp": now + 120, "jti": str(uuid.uuid4())},
    key, algorithm="ES256", headers={"kid": "admin-app-1"},
)

resp = requests.post(TOKEN_URL, data={
    "grant_type": "client_credentials",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": assertion,
    "scope": "users:read groups:manage",
}, timeout=10)
resp.raise_for_status()
access_token = resp.json()["access_token"]
```

```bash title="Terminal"
# ASSERTION is a freshly signed client assertion, from one of the other tabs.
curl https://id.trustaige.com/oauth2/token \
  -d grant_type=client_credentials \
  -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
  -d "client_assertion=$ASSERTION" \
  -d 'scope=users:read groups:manage'
```

## Take a token with a client secret

Send the client ID and secret as HTTP Basic authentication
(`client_secret_basic`), or as `client_id` and `client_secret` in the form body
(`client_secret_post`). Trustaige accepts either; if you send both, both must
be right.

```bash title="Terminal"
curl https://id.trustaige.com/oauth2/token \
  -u "<your-client-id>:<your-client-secret>" \
  -d grant_type=client_credentials \
  -d 'scope=users:read groups:manage'
```

```bash title="Terminal"
curl https://id.trustaige.com/oauth2/token \
  -d grant_type=client_credentials \
  -d client_id=<your-client-id> \
  -d client_secret=<your-client-secret> \
  -d 'scope=users:read groups:manage'
```

> **Important:** Keep the secret on your server, in your secret store: never in a browser, a
> mobile app or your repository. If it leaks, regenerate it on the app's page;
> the old one stops working at once.

## The token

```json title="200 OK"
{
  "access_token": "eyJhbGciOi…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "users:read groups:manage"
}
```

- **Name the scopes you want.** A request with no `scope` gets none of the
  admin operations: they're never granted by omission. Ask for any subset of
  what you granted the app; asking for one you didn't grant fails.
- **Tokens last up to an hour,** and there's no refresh token. When one
  expires, take another the same way.
- **Send it as a bearer token** with every call:

```bash title="Terminal"
curl https://id.trustaige.com/api/admin/members?limit=50 \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

Lists page with cursor tokens: the response carries `items`, `hasMore` and,
when there's more, `nextPageToken`, which you pass back as `next_page_token`.

## What an admin app can be granted

| Scope | Lets the app |
|---|---|
| `users:read` | Read people |
| `groups:manage` | Manage groups and their members |
| `apps:manage` | Manage apps and assignments |
| `audit:read`, `audit:export` | Read and export the audit log |
| `analytics:read` | Read analytics |
| `access_requests:read`, `access_requests:approve` | Read and approve access requests |
| `entitlements:view` | View entitlements |
| `webhooks:manage` | Manage webhooks |
| `ssf:manage` | Manage Shared Signals receivers and streams |

Other operations, such as managing roles, billing or the vault, are never
grantable to a program.

## When it doesn't work

**401 “Unauthorized request” from the token endpoint**

Trustaige couldn't authenticate the app. With a secret: the client ID or secret
is wrong, or the secret was regenerated. With a private key, check the
assertion: `iss` and `sub` are both the client ID; `aud` is the token endpoint
or the issuer; `exp` is set and no more than an hour away; `jti` is present
and hasn't been used before; it's signed with an algorithm the app accepts;
and the `kid` matches a key in the set you gave the hub (or the set holds only
one key). After rotating keys at a hosted URL, Trustaige picks up the new set
when it sees an unknown `kid`.

**“scope … is not available to this client”**

The app asked for a scope you haven't granted it. Grant it on the app's page,
or drop it from the request.

**“the application is disabled”**

The app is turned off in the hub. Turn it on again from its page.

**403 “application lacks the … scope”**

The token is valid but doesn't carry the operation this call needs. Grant the
scope on the app's page, then take a new token that asks for it.

**403 “the Admin API is not available on the starter plan”**

The Admin API starts on Foundation. The response's `code` is
`plan_feature_disabled` and `requiredPlan` names the plan it needs.

> **Note:** Guides for people, groups, apps, devices and policies, and a reference page
> for every endpoint (generated from the hub's OpenAPI description) are on the
> way.
