> For the complete documentation index, see [llms.txt](https://docs.k9.io/key9-identity/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.k9.io/key9-identity/jsonair/2-install/2.8-admin-web-interface.md).

# 2.8 Admin Web Interface

How to configure and run the JSONAir admin web interface.

`jsonair-admin` is a lightweight browser-based administration tool for managing the `configurations` table. It provides a login-protected UI where administrators can search, create, edit, and delete configuration records without needing direct database access or the `jsonair-encrypt` command-line tool.

All configuration data written through the admin interface is automatically base64-encoded and encrypted using the same AES-256-GCM method that the JSONAir server uses, so agents retrieve configurations transparently with no changes on their side.

***

## How It Works

| Step | What Happens                                                                                                               |
| ---- | -------------------------------------------------------------------------------------------------------------------------- |
| 1    | Admin signs in through single sign-on (OpenID Connect), or with a username and password stored in environment variables    |
| 2    | A signed JWT session cookie is issued (4-hour lifetime, HTTP-only)                                                         |
| 3    | Admin searches the `configurations` table by type and/or name                                                              |
| 4    | Admin opens a record — the existing `config_data` is decrypted and base64-decoded for display                              |
| 5    | Admin edits the raw configuration text and saves                                                                           |
| 6    | On save, the admin interface base64-encodes the raw text, encrypts it with AES-256-GCM, and writes it back to the database |
| 7    | The JSONAir server decrypts and serves the updated configuration to agents on the next request                             |

The admin interface shares the `CONFIG_ENCRYPT_SECRET` with the JSONAir server — this is what allows it to read and write encrypted `config_data` values that the server can then decrypt.

> **Looking for an API instead of a web page?** Other services can create, update and delete configurations through the separate, write-only `jsonair-write` program. See [2.9 The Write API](https://github.com/k9io/jsonair/tree/main/docs/2.9-write-api.md).

***

## Building

### With Make

```bash
make jsonair-admin
```

The binary is placed at:

```
bin/jsonair-admin/jsonair-admin
```

### Directly with Go

```bash
go build -o bin/jsonair-admin/jsonair-admin ./cmd/jsonair-admin
```

The HTML templates, stylesheet, script and icon are embedded into the binary at compile time using Go's `embed` package. No external files are needed at runtime and the pages load nothing from the internet — the binary is fully self-contained. The interface follows the browser's light or dark mode setting.

***

## Environment Variables

### Required — Session

| Variable               | Description                                                                                                                                | Example                |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------- |
| `ADMIN_SESSION_SECRET` | Secret used to sign session JWTs, CSRF tokens and single sign-on state. Use a long, random string — keep this separate from other secrets. | `openssl rand -hex 32` |

### Admin Password Login

Required unless single sign-on is configured. With single sign-on, these are optional: set both to keep the password as an emergency fallback, or leave both unset to disable password sign-in entirely.

| Variable         | Description                          | Example                |
| ---------------- | ------------------------------------ | ---------------------- |
| `ADMIN_USERNAME` | Login username for the web interface | `admin`                |
| `ADMIN_PASSWORD` | Login password for the web interface | `openssl rand -hex 16` |

### Optional — Single Sign-On (OpenID Connect)

Setting `OIDC_ISSUER` turns on single sign-on. See [Single Sign-On](#single-sign-on-openid-connect) below.

| Variable               | Description                                                                                                                              | Default                |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| `OIDC_ISSUER`          | The identity provider's issuer URL. Its discovery document must be at `<issuer>/.well-known/openid-configuration`.                       | —                      |
| `OIDC_CLIENT_ID`       | Client ID registered for JSONAir Admin at the provider. Required with `OIDC_ISSUER`.                                                     | —                      |
| `OIDC_CLIENT_SECRET`   | Client secret. Leave unset only for a public client (PKCE is always used).                                                               | —                      |
| `OIDC_REDIRECT_URL`    | This interface's callback URL, exactly as registered at the provider: `https://<admin host>/auth/callback`. Required with `OIDC_ISSUER`. | —                      |
| `OIDC_PROVIDER_NAME`   | Name shown on the login button ("Sign in with …").                                                                                       | `SSO`                  |
| `OIDC_SCOPES`          | Space- or comma-separated scopes to request.                                                                                             | `openid email profile` |
| `OIDC_ALLOWED_EMAILS`  | Comma-separated email addresses allowed to sign in.                                                                                      | —                      |
| `OIDC_ALLOWED_DOMAINS` | Comma-separated email domains allowed to sign in (`example.com` allows `anyone@example.com`, not subdomains).                            | —                      |
| `OIDC_ALLOWED_GROUPS`  | Comma-separated group names allowed to sign in. Exact, case-sensitive match.                                                             | —                      |
| `OIDC_GROUPS_CLAIM`    | ID token claim that holds the user's groups.                                                                                             | `groups`               |
| `OIDC_ALLOW_ANY_USER`  | Set to `true` to allow everyone who can sign in to the provider.                                                                         | `false`                |

At least one of `OIDC_ALLOWED_EMAILS`, `OIDC_ALLOWED_DOMAINS` or `OIDC_ALLOWED_GROUPS` must be set (or `OIDC_ALLOW_ANY_USER=true`); otherwise `jsonair-admin` refuses to start, so a missing allowlist can never mean "everyone is an admin".

### Required — Encryption

| Variable                | Description                                                                                                                                                                                                                                                                                                        |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `CONFIG_ENCRYPT_SECRET` | **Must match the value used by the JSONAir server.** This is the same secret used to derive the AES-256-GCM key for `config_data`. If this value differs from the server's, the admin interface will not be able to decrypt existing records and the server will not be able to read records written by the admin. |

### Required — Database

| Variable         | Description             | Example            |
| ---------------- | ----------------------- | ------------------ |
| `MYSQL_USERNAME` | Database username       | `jsonair`          |
| `MYSQL_PASSWORD` | Database password       | `your-db-password` |
| `MYSQL_DATABASE` | Database name           | `jsonair`          |
| `MYSQL_HOST`     | Database hostname or IP | `127.0.0.1`        |
| `MYSQL_PORT`     | Database port           | `3306`             |

### Optional — Database TLS

| Variable                | Description                                                                        | Default |
| ----------------------- | ---------------------------------------------------------------------------------- | ------- |
| `MYSQL_TLS`             | Set to `true` to enable TLS for the database connection                            | `false` |
| `MYSQL_TLS_SKIP_VERIFY` | Set to `true` to disable certificate verification. Not recommended for production. | `false` |

### Optional — HTTP Server

| Variable      | Description                                                      | Default |
| ------------- | ---------------------------------------------------------------- | ------- |
| `HTTP_LISTEN` | Address and port to listen on                                    | `:8080` |
| `HTTP_TLS`    | Set to `true` to enable HTTPS                                    | `false` |
| `HTTP_CERT`   | Path to the TLS certificate file. Required when `HTTP_TLS=true`. | —       |
| `HTTP_KEY`    | Path to the TLS private key file. Required when `HTTP_TLS=true`. | —       |

When `HTTP_TLS=true`, the admin interface serves HTTPS directly. Alternatively, leave TLS disabled and terminate it at a reverse proxy (nginx, Caddy, etc.).

***

## Example `.env` File

```ini
# Session signing
ADMIN_SESSION_SECRET=replace-with-output-of-openssl-rand-hex-32

# Single sign-on (optional)
# OIDC_ISSUER=https://idp.example.com
# OIDC_CLIENT_ID=jsonair-admin
# OIDC_CLIENT_SECRET=replace-with-client-secret
# OIDC_REDIRECT_URL=https://admin.example.com/auth/callback
# OIDC_PROVIDER_NAME=Key9
# OIDC_ALLOWED_DOMAINS=example.com

# Password login (required unless OIDC is configured; optional fallback with it)
ADMIN_USERNAME=admin
ADMIN_PASSWORD=replace-with-a-strong-password

# Must match the JSONAir server value exactly
CONFIG_ENCRYPT_SECRET=same-value-as-your-jsonair-server

# Database (same database as the JSONAir server)
MYSQL_USERNAME=jsonair
MYSQL_PASSWORD=your-strong-db-password
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_DATABASE=jsonair

# HTTP
HTTP_LISTEN=:8080

# HTTPS (optional — remove if using a reverse proxy for TLS termination)
# HTTP_TLS=true
# HTTP_CERT=/etc/letsencrypt/live/admin.example.com/fullchain.pem
# HTTP_KEY=/etc/letsencrypt/live/admin.example.com/privkey.pem
```

> **Security:** Never commit a `.env` file containing real credentials to source control. Add `.env` to your `.gitignore`.

***

## Running the Admin Interface

### Directly

Place a `.env` file in the same directory as the binary and run:

```bash
cd /opt/jsonair-admin
./jsonair-admin
```

### As a systemd Service

Create `/etc/systemd/system/jsonair-admin.service`:

```ini
[Unit]
Description=JSONAir Admin Web Interface
After=network.target mysql.service
Wants=mysql.service

[Service]
Type=simple
User=jsonair-admin
WorkingDirectory=/opt/jsonair-admin
EnvironmentFile=/etc/jsonair/admin.env
ExecStart=/opt/jsonair-admin/jsonair-admin
Restart=on-failure
RestartSec=5
KillMode=mixed
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
```

Place your environment variables in `/etc/jsonair/admin.env`, then enable and start the service:

```bash
sudo systemctl daemon-reload
sudo systemctl enable jsonair-admin
sudo systemctl start jsonair-admin
sudo systemctl status jsonair-admin
```

### With HTTPS

Set the three TLS variables and the admin interface will serve HTTPS directly — no reverse proxy required.

```ini
HTTP_TLS=true
HTTP_CERT=/etc/letsencrypt/live/admin.example.com/fullchain.pem
HTTP_KEY=/etc/letsencrypt/live/admin.example.com/privkey.pem
HTTP_LISTEN=:8443
```

When TLS is enabled the server enforces TLS 1.2 as the minimum version, adds a `Strict-Transport-Security` header to every response, and marks the session cookie `Secure` so it is never transmitted over plain HTTP.

> **Tip:** Generate a self-signed certificate for internal use: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=jsonair-admin'`

### In a Container

Because all configuration is passed via environment variables and the binary is fully self-contained, the admin interface is straightforward to run in a container. A minimal `Dockerfile` looks like:

```dockerfile
FROM scratch
COPY jsonair-admin /jsonair-admin
ENTRYPOINT ["/jsonair-admin"]
```

Or using a minimal base image:

```dockerfile
FROM gcr.io/distroless/static-debian12
COPY jsonair-admin /jsonair-admin
ENTRYPOINT ["/jsonair-admin"]
```

Pass environment variables at runtime:

```bash
docker run -d \
  -p 8080:8080 \
  -e ADMIN_USERNAME=admin \
  -e ADMIN_PASSWORD=your-password \
  -e ADMIN_SESSION_SECRET=your-session-secret \
  -e CONFIG_ENCRYPT_SECRET=your-encrypt-secret \
  -e MYSQL_USERNAME=jsonair \
  -e MYSQL_PASSWORD=your-db-password \
  -e MYSQL_HOST=db.internal \
  -e MYSQL_PORT=3306 \
  -e MYSQL_DATABASE=jsonair \
  jsonair-admin
```

> **Note:** Cross-compile for Linux when building on macOS: `GOOS=linux GOARCH=amd64 go build -o jsonair-admin ./cmd/jsonair-admin`

***

## Single Sign-On (OpenID Connect)

`jsonair-admin` can sign people in through any OpenID Connect identity provider (Key9, Okta, Entra ID, Google Workspace, Keycloak, Authentik, …). Sign-in uses the authorization code flow with PKCE. The provider handles authentication, so its policies — passkeys, MFA, device checks — apply to the admin interface automatically. `jsonair-admin` stores nothing about users.

### Provider setup

1. Register a new OpenID Connect web application (confidential client) for JSONAir Admin.
2. Set its redirect / callback URI to `https://<admin host>/auth/callback`. This must match `OIDC_REDIRECT_URL` exactly.
3. Allow the scopes `openid`, `email` and `profile`. To allow access by group, also configure the provider to include the user's groups in the ID token, and set `OIDC_GROUPS_CLAIM` if the claim is not called `groups`.
4. Copy the issuer URL, client ID and client secret into the environment variables above.

Most providers only accept `https://` redirect URIs (except for `localhost`), so run the admin interface over HTTPS — directly or behind a TLS-terminating proxy — when using single sign-on.

### How sign-in works

1. The login page shows **Sign in with&#x20;*****name*** (`OIDC_PROVIDER_NAME`). Clicking it redirects to the provider.
2. After the user authenticates, the provider redirects back to `/auth/callback`.
3. `jsonair-admin` exchanges the code for tokens and verifies the ID token: signature (against the provider's published keys), issuer, audience (the client ID), expiry, and a single-use `state` and `nonce` that tie the response to this browser's sign-in attempt.
4. The user is checked against the allowlist. Email and domain rules match case-insensitively and are not satisfied by an address the provider marks `email_verified: false`.
5. On success, the normal 4-hour admin session starts. The top bar shows the user's email (or username, or subject ID if neither is provided).

Refused sign-ins are shown on the login page and logged to standard error with the user's identity.

Signing out ends the `jsonair-admin` session only; it does not sign you out of the identity provider. Removing someone from the allowlist or the provider stops new sign-ins, but an existing session stays valid until it expires (at most 4 hours) unless `ADMIN_SESSION_SECRET` is changed, which ends every session.

If the provider cannot be reached when `jsonair-admin` starts, a warning is logged and startup continues; sign-in retries the provider each time until it succeeds. If you kept the password login, it still works while the provider is down.

***

## Health Check

`jsonair-admin` exposes an unauthenticated health endpoint at `/health`. It pings the database and returns HTTP `200` when healthy or HTTP `503` when the database is unreachable.

```bash
curl http://localhost:8080/health
```

Healthy response:

```json
{"status": "ok"}
```

Unhealthy response (HTTP 503):

```json
{"status": "error", "message": "database unreachable"}
```

### Docker HEALTHCHECK

```dockerfile
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://localhost:8080/health || exit 1
```

Replace `8080` with the port set in `HTTP_LISTEN` if you change the default.

***

## Usage

### Logging In

Navigate to `http://your-host:8080` (or `https://` if `HTTP_TLS=true`) using the address set in `HTTP_LISTEN`. You will be redirected to the login page. Click **Sign in with&#x20;*****name*** to use single sign-on, or enter the `ADMIN_USERNAME` and `ADMIN_PASSWORD` values from your environment. The page shows only the methods that are configured.

Sessions expire 4 hours after you log in (activity does not extend them). The top bar shows how long your session has left, and a banner appears during the last 5 minutes. If your session expires while you are editing, the page will not submit (so your changes are not lost); sign in again in a new tab, then save. When an expired session sends you to the login page, it tells you why.

### Searching Configurations

After login you land on the **Configurations** list page. All records from the `configurations` table are shown in a table with columns for Type, Name, Key, Reload, Debug, and when the record was last updated.

The **Key** column shows the key's name from the `keys` table with a shortened UUID beneath it; hover to see the full UUID, or click the copy button to copy it. A configuration whose UUID has no matching key is shown as *No matching key*. **Updated** is shown as a relative time ("3 hours ago"); hover for the exact timestamp.

Use the **Type** and **Name** search fields at the top to filter the list. Filters are substring matches, so searching for `suri` in the Type field will match `suricata`. Both filters can be combined. Click **Clear filters** to reset.

### Creating a Configuration

Click **New configuration** to open the creation form. Fill in the following fields:

| Field                  | Description                                                                                                                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Key**                | The key this configuration belongs to. Select from the dropdown — it lists all records in the `keys` table. The agent must authenticate with this key to retrieve the configuration.        |
| **Type**               | The configuration type (e.g. `suricata`, `nginx`). Must match what the agent sends in its `JSONAIR_TYPE` variable.                                                                          |
| **Name**               | The configuration name (e.g. `suricata.yaml`). Must match what the agent sends in its `JSONAIR_NAME` variable.                                                                              |
| **Reload**             | Optional reload key or trigger value.                                                                                                                                                       |
| **Debug**              | Optional debug level (e.g. `INFO`, `DEBUG`).                                                                                                                                                |
| **Configuration Data** | Paste the raw configuration text here. Any format is accepted — YAML, JSON, TOML, plain text, binary, etc. The admin interface does not require or check a particular format when you save. |

Click **Create configuration** to save. The raw text is base64-encoded and encrypted before being written to the database.

A configuration is unique per **Key**, **Type** and **Name**. Creating a second one with the same three values is refused with a message that links to the existing record, which you can edit instead. If a save fails for any reason, the form keeps everything you entered.

### Editing a Configuration

Click **Edit** (or the configuration's name) in the list. The edit form shows the same fields as the creation form, pre-populated with the current values. The **Configuration data** editor displays the decrypted, decoded raw configuration text.

Make any changes and click **Save changes** (or press <kbd>Ctrl</kbd>/<kbd>⌘</kbd>+<kbd>S</kbd>). The updated text will be re-encoded and re-encrypted. The page marks unsaved changes and asks before you navigate away from them.

The configuration editor, on both the New and Edit pages:

* shows line numbers, plus the line and byte count;
* indents with <kbd>Tab</kbd> and outdents with <kbd>Shift</kbd>+<kbd>Tab</kbd> (press <kbd>Esc</kbd> first if you want <kbd>Tab</kbd> to move focus out of the editor);
* has **Verify as JSON / XML / YAML** buttons that check the syntax of the text and report whether it is valid. They are a convenience only — saving is never blocked by them.

> **Note:** Changing the **Key**, **Type** or **Name** of a configuration will break any agents currently polling for the old combination. The edit page shows a warning as soon as you change one of these fields. Update agents before changing them in production.

### Deleting a Configuration

Click the trash icon next to any record in the list, or **Delete configuration** at the bottom of the edit page. A confirmation dialog names the configuration and its key before the record is permanently removed. Deletion cannot be undone.

***

## Security Considerations

* **Keep the admin interface off the public internet.** Run it on an internal network, behind a VPN, or behind an authenticated reverse proxy. It provides direct read and write access to all configuration data in the database.
* The session cookie is **HTTP-only**, which keeps it out of reach of page scripts, and **`SameSite=Lax`**, so browsers do not send it on cross-site form posts or on requests embedded in other sites' pages. When `HTTP_TLS=true`, the cookie is also marked **Secure** so it is never transmitted over plain HTTP. Either enable TLS directly or place the admin interface behind a TLS-terminating reverse proxy (nginx, Caddy, etc.) when running over an untrusted network.
* **Cross-site request forgery (CSRF) protection.** Every change made while signed in (create, save, delete, verify, log out) must carry a CSRF token tied to the current session cookie. Signing in again issues a new session and so a new token; open pages pick up the new token automatically before saving, so signing in again in another tab never discards an edit. Requests a browser marks as coming from another site (`Sec-Fetch-Site: cross-site`) are refused outright, including the login form. Logging out is a POST, so other sites cannot sign you out.
* **Reverse proxies:** for browsers too old to send `Sec-Fetch-Site`, the cross-site check compares the `Origin` header with the `Host` header. If your proxy rewrites `Host`, pass the original through (for nginx, `proxy_set_header Host $host;`).
* **Response headers.** Every response carries a strict `Content-Security-Policy` that lets pages load scripts, styles, images and connections only from the admin interface itself, and forbids framing, plugins and form posts to other sites. The pages contain no inline scripts or styles. `Referrer-Policy: same-origin`, `X-Frame-Options: DENY` and `X-Content-Type-Options: nosniff` are also set.
* `ADMIN_SESSION_SECRET`, `ADMIN_PASSWORD`, `OIDC_CLIENT_SECRET` and `CONFIG_ENCRYPT_SECRET` should each be distinct values; generate your own with `openssl rand -hex 32`.
* With single sign-on, prefer leaving `ADMIN_USERNAME`/`ADMIN_PASSWORD` unset, so everyone signs in through the provider with its passkey/MFA policies. If you keep the password as an emergency fallback, treat it like any other break-glass credential.
* The admin interface does not drop OS privileges at startup (unlike the main server). Run it as a dedicated low-privilege user.
