# Deploy Kavach Enterprise

> Run kavach-daemon as a sidecar, or let the Kubernetes operator manage it from ProtectedService and HealingPolicy resources. Every daemon mode, with health and metrics endpoints.

Kavach Enterprise ships as one multi-arch (`linux/amd64`, `linux/arm64`) container image, `ghcr.io/kavachlabs/kavach-daemon`, which bundles the daemon and a pinned `kavach` CLI. It runs as user `65532`, with a read-only root filesystem and no capabilities. Getting access, choosing a tag and upgrading are covered in [Install and upgrade](https://www.thekavachlabs.com/docs/enterprise/install).

There are two ways to run it:

- **Sidecar**: add the daemon container to your service's pod yourself.
- **Operator**: declare a `ProtectedService` and the operator creates and guards the sidecar for you.

## Before you start

- Your service records with a Kavach [SDK](https://www.thekavachlabs.com/docs/sdks), with its recorder writing to a shared-memory directory (for example `/dev/shm/kavach`).
- You have two builds of the service available to the daemon: the running one (`old`) and a candidate (`new`), as [host commands](https://www.thekavachlabs.com/docs/concepts#host-command).
- A bucket for fixtures and the audit trail; see [Storage](https://www.thekavachlabs.com/docs/enterprise/storage). Check it with `kavach-daemon --diagnose-storage` first.

## Sidecar

The service and the daemon share an in-memory volume. An init container copies the service's binaries where the daemon can run them for replay.

```yaml
spec:
  volumes:
    - name: kavach-shm
      emptyDir: { medium: Memory, sizeLimit: 256Mi }
    - name: kavach-app-bins
      emptyDir: { sizeLimit: 256Mi }
  initContainers:
    - name: stage-app-binaries
      image: ghcr.io/acme/payments:v1.4.0
      command: [/bin/cp, /app/payments-old, /app/payments-new, /opt/kavach/app-bins/]
      volumeMounts: [{ name: kavach-app-bins, mountPath: /opt/kavach/app-bins }]
  containers:
    - name: app
      image: ghcr.io/acme/payments:v1.4.0
      env:
        - { name: KAVACH_SHM_DIR, value: /dev/shm/kavach }
      volumeMounts: [{ name: kavach-shm, mountPath: /dev/shm/kavach }]
    - name: kavach-daemon
      image: ghcr.io/kavachlabs/kavach-daemon:<version>   # pin X.Y.Z or a digest
      args:
        - --run-shadow
        - --service=payments
        - --bucket=s3://acme-kavach/shadow
        - --shm-dir=/dev/shm/kavach
        - --fixtures-dir=/dev/shm/kavach/fixtures
        - --work-dir=/var/lib/kavach/work
        - --vault-dir=/var/lib/kavach/vault
        - --old-cmd=/opt/kavach/app-bins/payments-old
        - --new-cmd=/opt/kavach/app-bins/payments-new
        - --metrics-addr=0.0.0.0:9464
      livenessProbe: { httpGet: { path: /healthz, port: 9464 } }
      readinessProbe: { httpGet: { path: /readyz, port: 9464 } }
      env:
        - name: KAVACH_HMAC_KEY_FILE
          value: /run/secrets/kavach/hmac_key_hex
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        readOnlyRootFilesystem: true
        allowPrivilegeEscalation: false
        capabilities: { drop: [ALL] }
```

Because the daemon is a separate container, it keeps the tail of the recording when the service container is killed (`OOMKilled`, `SIGKILL`), and the fixture still gets written.

## Operator

Install the custom resources and the operator as described in [Install and upgrade](https://www.thekavachlabs.com/docs/enterprise/install#install-the-operator). The operator runs with a `Role` limited to its namespace and a default-deny network policy.

All three resources are in API group `kavach.dev/v1alpha1`.

### `ProtectedService`

```yaml
apiVersion: kavach.dev/v1alpha1
kind: ProtectedService
metadata:
  name: payments
  namespace: payments
spec:
  service: payments
  bucket: s3://acme-kavach/payments
  region: us-east-1
  appImage: ghcr.io/acme/payments:v1.4.0
  oldCommand: /app/payments-old
  newCommand: /app/payments-new
  replicas: 2
  minAvailable: 1
  healingPolicyRef: payments-strict
  egressCidrs: ["10.0.0.0/8"]
```

Required: `service`, `bucket`, `appImage`, `oldCommand`. Set `daemonImage` to a pinned version; it defaults to `ghcr.io/kavachlabs/kavach-daemon:latest`. The sidecar runs as `serviceAccountName`, so attach the registry pull secret to that service account. The operator refuses a spec that runs as root, is privileged, allows privilege escalation or has a writable root filesystem, and reports why in `status.conditions`.

### `HealingPolicy`

```yaml
apiVersion: kavach.dev/v1alpha1
kind: HealingPolicy
metadata:
  name: payments-strict
spec:
  minReproducingVariants: 25
  maxHistoricalVaultFailures: 0
  requireLockedInvariants: true
  requireAntiLobotomy: true      # reject fixes that silently drop outputs
  maxBlastRadius: SingleHandler  # SingleHandler | MultiHandler | ServiceWide
  minConfidence: 0.9
  canaryWatchSeconds: 300
  replayWindowHours: 168         # pre-merge replay window: 7 days
  autopilotEnabled: false        # true: roll out proven fixes without a human merge
```

The defaults are shown. With `autopilotEnabled: false`, proven fixes become pull requests for a person to merge.

### `QuarantineDrain`

```yaml
apiVersion: kavach.dev/v1alpha1
kind: QuarantineDrain
metadata:
  name: wallet-42
spec:
  service: payments
  entityKey: wallet_42
  bucket: s3://acme-kavach/live
  oldCommand: /app/payments-v1
  newCommand: /app/payments-v2
  dryRun: true
```

Create it with `dryRun: true` to see what the drain would emit, then set it to `false`. `status` reports the epochs, how many held and buffered events were drained, and diagnostics.

## Daemon modes

`kavach-daemon` takes one mode per process.

| Mode | What it does |
| --- | --- |
| `--diagnose-storage URI` | Checks a bucket supports the conditional writes and range reads Kavach needs. Add `--read-only` to skip writes. |
| `--run-shadow` | Shadow healer: harvest, scrub, verify and upload fixtures; prove candidate fixes; open pull requests. |
| `--serve-armor` | Live gateway: gate step effects over a Unix socket (`--uds-path`) and/or HTTP (`--http-addr`). |
| `--drain-quarantine` | Drain one entity's held backlog through the new build. `--dry-run` previews it. |
| `--run-autopilot` | Policy-gated canary, rollback, drain and vault commit for one entity. Exits `0` when done, `3` when escalated or rolled back. |
| `--simulate-pr` | Replay recent production fixtures from the bucket against a pull request's build: a CI gate. |
| `--reconcile-operator` | Run the Kubernetes reconciler. `--dry-run` prints manifests; `--once` reconciles once. |
| `--verify-audit` | Verify the audit trail. Exits `0` when valid, `1` when tampered. |
| `--consume-ring FILE` | Turn one shared-memory capture ring into an incident archive. |
| `--sample-memory` | Report cgroup memory pressure. |

### Live gateway

```bash
KAVACH_ARMOR_AUTH_TOKEN_FILE=/run/secrets/armor_token \
kavach-daemon --serve-armor --service payments --bucket s3://acme-kavach/live \
  --uds-path /var/run/kavach/armor.sock \
  --http-addr 127.0.0.1:8080 --metrics-addr 0.0.0.0:9464 \
  --fixtures-dir /dev/shm/kavach/fixtures --work-dir /var/lib/kavach/armor
```

| HTTP endpoint | Auth | Purpose |
| --- | --- | --- |
| `POST /v1/step` | required | Submit a step's outcome and effects for gating. |
| `GET /v1/quarantine` | required | List quarantined entities. |
| `GET /healthz`, `GET /readyz` | none | Probes. |
| `GET /metrics` | none | Prometheus metrics. |

Bound resource use with `--max-tracked-cells`, `--normal-cell-idle-ttl-ms`, `--max-http-connections` and `--max-uds-connections`.

### Pre-merge simulation in CI

```bash
kavach-daemon --simulate-pr --service payments --bucket s3://acme-kavach/shadow \
  --old-cmd ./payments-main --new-cmd ./payments-pr --kavach-cli "$(command -v kavach)"
```

## Health and metrics

The shadow healer and the live gateway expose `/healthz`, `/readyz` and Prometheus `/metrics` on `--metrics-addr`. Startup fails closed: the daemon is not ready until its storage passes the contract probe. The probe reasons, every metric, suggested alerts and sizing are in [Operations](https://www.thekavachlabs.com/docs/enterprise/operations).

## Exit codes

| Code | Meaning |
| --- | --- |
| `0` | Success (valid audit trail, completed drain or rollout). |
| `1` | Audit trail tampered, or the operation failed. |
| `2` | Usage error, including a secret passed on the command line. |
| `3` | Autopilot escalated to a person or rolled back. |

Source: https://www.thekavachlabs.com/docs/enterprise/deployment
