# API-Referenz

Vollstaendige REST API Dokumentation mit allen Endpoints und Beispielen.

**Base-URL**: `https://your-backend:8443/api/v1`

## Authentifizierung

Zwei Auth-Methoden (CombinedAuth Middleware):
- **API-Key** (Header `X-API-Key`): Fuer Agents und automatisierte Zugriffe
- **JWT Bearer Token** (Header `Authorization: Bearer <token>`): Fuer Frontend-Benutzer

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/auth/login` | Login (username + password → JWT Token, 8h Ablauf) |
| GET | `/auth/me` | Eigene Benutzerdaten |

Default-Admin: `admin` / `YOUR_PASSWORD` (min. 6 Zeichen).

---

## Agent-Management

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/agent/register` | Agent registrieren (mit optionaler `agent_id`) |
| POST | `/agent/heartbeat` | Systemdaten senden |
| POST | `/agents` | Firewall pre-registrieren (`{name, customer_id?}`) |
| GET | `/agents` | Alle Agents auflisten |
| GET | `/agents/{id}` | Agent + Systemdaten abrufen |
| GET | `/agents/{id}/system` | Nur Systemdaten |
| DELETE | `/agents/{id}` | Agent loeschen |

### Agent-Status

Status wird automatisch aus `last_heartbeat` berechnet:

| Status | Bedingung |
|--------|-----------|
| `online` | Heartbeat < 2 Minuten |
| `stale` | Heartbeat < 5 Minuten |
| `offline` | Heartbeat > 5 Minuten |
| `unknown` | Kein Heartbeat vorhanden |

### Pre-Registration

`POST /agents` mit `{"name": "FW-NAME", "customer_id": 1}` — legt Agent mit `hostname="(ausstehend)"` an.
Bei Agent-Registration wird automatisch nach Name gematcht (`GetAgentByName`).

### Beispiele

```bash
# Alle Agents auflisten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents

# Einzelner Agent mit Systemdaten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887

# Nur Systemdaten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/system

# Agent loeschen
curl -sk -H "X-API-Key: YOUR_API_KEY" -X DELETE \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887

# Hub-Status (verbundene Agents, aktive Tunnel)
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/hub/status

# Remote-Command ausfuehren
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/exec \
  -d '{"command":"uptime","timeout":30}'
```

---

## Agent-Events

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/agents/events` | Alle Events (`?limit=N&type=X`) |
| GET | `/agents/{id}/events` | Events eines Agents (`?limit=N&type=X`) |

Event-Typen: `online`, `offline`, `stale`, `connected`, `disconnected`

```bash
# Alle Events (letzte 10)
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/events?limit=10"

# Nur Offline-Events eines Agents
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/events?type=offline"
```

---

## Kunden (Customers)

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/customers` | Alle Kunden auflisten |
| POST | `/customers` | Neuen Kunden anlegen (`{number, name}`) |
| GET | `/customers/{id}` | Einzelnen Kunden abrufen |
| PUT | `/customers/{id}` | Kunden aktualisieren |
| DELETE | `/customers/{id}` | Kunden loeschen |
| GET | `/customers/{id}/agents` | Agents eines Kunden |
| PUT | `/agents/{id}/customer` | Agent einem Kunden zuordnen |
| DELETE | `/agents/{id}/customer` | Kundenzuordnung entfernen |

---

## Benutzer (Users)

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/users` | Alle Benutzer auflisten |
| POST | `/users` | Neuen Benutzer anlegen |
| PUT | `/users/{id}/password` | Passwort aendern (min. 6 Zeichen) |
| DELETE | `/users/{id}` | Benutzer loeschen |

---

## Metriken (TimescaleDB)

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/agents/{id}/metrics` | Rohe Metriken (`?metric=X&from=&to=&limit=N`) |
| GET | `/agents/{id}/metrics/summary` | Aggregierte Metriken (`?metric=X&bucket=5+minutes&from=&to=`) |

Verfuegbare Metriken: `cpu_usage`, `memory_used_percent`, `memory_used_bytes`, `memory_total_bytes`,
`uptime_seconds`, `disk_used_percent`, `disk_used_bytes`, `interface_rx_bytes`,
`interface_tx_bytes`, `gateway_rtt_ms`, `gateway_loss_percent`

Retention: 90 Tage (Raw), Compression nach 7 Tagen.

### Beispiele

```bash
# CPU-Auslastung der letzten 24h
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/metrics?metric=cpu_usage"

# RAM-Nutzung mit Zeitraum
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/metrics?metric=memory_used_percent&from=2026-02-28T00:00:00Z&to=2026-02-28T23:59:59Z"

# 5-Minuten-Durchschnitte der CPU
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/metrics/summary?metric=cpu_usage&bucket=5+minutes"

# Stuendliche RAM-Zusammenfassung
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/metrics/summary?metric=memory_used_percent&bucket=1+hour"
```

---

## Config-Backup

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/agents/{id}/backup` | Backup jetzt ausloesen (via WebSocket) |
| GET | `/agents/{id}/backups` | Alle Backups auflisten (`?limit=N`) |
| GET | `/agents/{id}/backups/{id\|latest}` | Backup herunterladen (`?format=xml` fuer Raw-XML) |
| DELETE | `/agents/{id}/backups/{id}` | Einzelnes Backup loeschen |
| GET | `/agents/{id}/backups/diff?a={id}&b={id}` | Zeilenweises Diff zwischen zwei Backups |

Backups werden dedupliziert: gleicher SHA256-Hash = kein neuer Eintrag.

### Beispiele

```bash
# Backup ausloesen
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/backup

# Alle Backups auflisten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/backups

# Neuestes Backup als XML herunterladen
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/backups/latest?format=xml" \
  -o config-backup.xml

# Diff zwischen Backup 1 und 3
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  "https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/backups/diff?a=1&b=3"
```

---

## Tunnel-Management

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/agents/{id}/tunnel` | Tunnel oeffnen |
| GET | `/agents/{id}/tunnels` | Aktive Tunnel auflisten |
| DELETE | `/agents/{id}/tunnel/{tid}` | Tunnel schliessen |
| POST | `/agents/{id}/exec` | Remote-Command ausfuehren |

### Beispiele

```bash
# SSH-Tunnel zur OPNsense
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/tunnel \
  -d '{"target_host":"127.0.0.1","target_port":22}'
# Response: {"tunnel_id":"xxx","proxy_port":10000,...}
# Verbinden: ssh -p 10000 root@your-backend

# WebGUI-Tunnel (OPNsense auf Port 4444)
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/tunnel \
  -d '{"target_host":"127.0.0.1","target_port":4444}'
# Im Browser: https://your-backend:10001/

# Aktive Tunnel auflisten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/tunnels

# Tunnel schliessen
curl -sk -H "X-API-Key: YOUR_API_KEY" -X DELETE \
  https://your-backend:8443/api/v1/agents/e92e87a684b20db15d8d2344583c5887/tunnel/TUNNEL_ID
```

---

## Updates & Reboot

Siehe [FIRMWARE.md](FIRMWARE.md) fuer den vollstaendigen Update-Prozess.

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/agents/{id}/update-check` | Verfuegbare Updates pruefen |
| POST | `/agents/{id}/update` | Normales Update (Core + Packages) |
| POST | `/agents/{id}/major-update` | Major-Upgrade auf Zielversion |
| POST | `/agents/{id}/reboot` | Reboot ausfuehren |

---

## Firmware / Agent-Update

Siehe [FIRMWARE.md](FIRMWARE.md) fuer Details.

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/firmware` | Alle Firmware-Versionen |
| POST | `/firmware/upload?version=X&platform=Y` | Binary hochladen |
| GET | `/firmware/download?platform=Y` | Binary herunterladen |
| POST | `/agents/{id}/request-update` | Update-Flag setzen |
| DELETE | `/agents/{id}/request-update` | Update-Flag zuruecksetzen |
| POST | `/agents/request-update-all` | Alle Agents updaten |

---

## WireGuard-Peer Management

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| POST | `/agents/{id}/wireguard/peers` | Neuen Peer anlegen |
| GET | `/agents/{id}/wireguard/peers` | Alle Peers auflisten (`?server_name=X`) |
| DELETE | `/agents/{id}/wireguard/peers/{uuid}` | Peer loeschen |

### Peer anlegen — Parameter

| Parameter | Pflicht | Default | Beschreibung |
|-----------|---------|---------|-------------|
| `name` | Ja | — | Peer-Name (z.B. "VPN_MUELLER") |
| `allowed_ips` | Nein | `0.0.0.0/0` | AllowedIPs fuer Client-Config |
| `dns` | Nein | — | DNS-Server fuer Client-Config |
| `server_name` | Nein | `ALWAYSON_VPN` | Name der WG-Server-Instanz |
| `endpoint` | Nein | WAN-IP:Port | Oeffentlicher Endpoint (Auto-Detect) |

### Ablauf beim Anlegen

1. Keypair wird auf der Firewall generiert (`wg genkey`/`wg pubkey`)
2. Naechste freie IP aus dem Tunnel-Subnetz wird automatisch vergeben
3. Peer wird in `config.xml` eingetragen und dem Server zugewiesen
4. `configctl wireguard configure` laedt die Aenderung
5. Response enthaelt die komplette Client-Config (ready for import)

### Beispiele

```bash
# Peer anlegen
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/wireguard/peers \
  -d '{"name":"VPN_MUELLER","allowed_ips":"0.0.0.0/0","dns":"10.172.100.210"}'

# Peer mit eigenem Endpoint
curl -sk -H "X-API-Key: YOUR_API_KEY" -X POST \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/wireguard/peers \
  -d '{"name":"VPN_EXTERN","allowed_ips":"0.0.0.0/0","endpoint":"vpn.kunde.de:8080"}'

# Alle Peers auflisten
curl -sk -H "X-API-Key: YOUR_API_KEY" \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/wireguard/peers

# Peer loeschen
curl -sk -H "X-API-Key: YOUR_API_KEY" -X DELETE \
  https://your-backend:8443/api/v1/agents/6beb8dfd38ecf03eab6c0f21b4ac7bee/wireguard/peers/89c10e2d-148e-11f1-a7af-7c5a1c6c7b73
```

---

## WebSocket

| Methode | Endpoint | Beschreibung |
|---------|----------|-------------|
| GET | `/agent/ws?agent_id=X&api_key=X` | WebSocket-Verbindung (Agent) |
| GET | `/hub/status` | Hub-Status (connected agents, aktive Tunnel) |

### WebSocket Commands (Backend → Agent)

```json
// Remote-Befehl ausfuehren
{"type":"command","id":"cmd1","command":"exec","params":{"command":"uptime","timeout":30}}

// Update-Check
{"type":"command","id":"cmd2","command":"update_check"}

// Normales Update
{"type":"command","id":"cmd3","command":"update","params":{"reboot":false}}

// Major-Update
{"type":"command","id":"cmd4","command":"major_update","params":{"version":"26.1","reboot":true}}

// Reboot
{"type":"command","id":"cmd5","command":"reboot","params":{"delay":5}}

// Config-Backup
{"type":"command","id":"cmd8","command":"backup","params":{}}

// Tunnel-Session oeffnen
{"type":"command","id":"cmd6","command":"tunnel_connect","params":{"session_id":"xxx","tunnel_id":"xxx","target_host":"127.0.0.1","target_port":22}}

// Tunnel-Session schliessen
{"type":"command","id":"cmd7","command":"tunnel_disconnect","params":{"session_id":"xxx"}}
```

### Binary WebSocket Messages (Tunnel-Daten)

Format: `[session_id_length:1][session_id][tcp_payload]`

Tunnel-Daten werden als Binary WebSocket Messages uebertragen (kein Base64-Overhead).
