# How Shadowbroker Handles Authentication and Authorization in Its Backend

> Discover how Shadowbroker secures its backend with secret keys, scoped tokens, local network checks, and OpenClaw HMAC signatures for robust authentication and authorization.

- Repository: [Shadowbroker/Shadowbroker](https://github.com/BigBodyCobain/Shadowbroker)
- Tags: how-to-guide
- Published: 2026-05-07

---

**Shadowbroker implements a layered security model in [`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py) that combines secret-based admin keys, scoped tokens, local-network trust checks, and OpenClaw HMAC signatures to authenticate requests and enforce transport-tier authorization policies.**

Shadowbroker, an open-source project maintained at `BigBodyCobain/Shadowbroker`, protects its FastAPI backend using a defense-in-depth approach to authentication and authorization. The system distinguishes between local administrative access, scoped API tokens, and cryptographically verified remote agents while enforcing network segmentation through transport-tier policies. Examining the source code reveals how dependency injection functions and cryptographic verification routines work together to secure API endpoints.

## Secret-Based Admin Authentication

The foundation of Shadowbroker’s security model rests on environment-configured secrets that validate administrative requests. The core logic resides in [`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py), where the system evaluates the `ADMIN_KEY` environment variable and optional scoped token mappings.

### Admin Key and Insecure Mode

Shadowbroker retrieves the master administrative secret using `str(get_settings().ADMIN_KEY or "").strip()` or falls back directly to `os.environ["ADMIN_KEY"]` ([`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py), lines 61-66). Requests must present this 64-character hex string in the `X-Admin-Key` header to gain privileged access.

For development environments, the framework supports an insecure admin bypass. When both `ALLOW_INSECURE_ADMIN` and `MESH_DEBUG_MODE` evaluate to true, the system permits administrative access without key validation (lines 68-74). This mode should never be enabled in production deployments.

### Scoped Token Map

Beyond the master key, Shadowbroker supports granular access control through `MESH_SCOPED_TOKENS`, an optional JSON map that pairs short tokens with permitted scopes. The system parses and normalizes this mapping at startup, allowing different API keys to access specific endpoint categories such as `"gate"`, `"dm"`, `"wormhole"`, `"mesh"`, or `"admin"` (lines 93-112).

## Determining Authorization Scopes per Request

Shadowbroker computes the required authorization scope dynamically for each incoming request. The `_required_scope_for_request` function inspects the request path and categorizes it into one of the predefined scopes: `"gate"`, `"dm"`, `"wormhole"`, `"mesh"`, or `"admin"` ([`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py), lines 115-125). This classification drives subsequent permission checks.

The `_check_scoped_auth` function validates the `X-Admin-Key` header against either the master admin key or the scoped token dictionary, enforcing the scope determined by the path classifier (lines 150-169). It also permits insecure admin access from localhost when no key is configured and debug mode is active. For explicit scope requirements, `_check_explicit_scoped_auth` performs similar validation while returning the authentication source—whether admin key, scoped token, or debug override (lines 172-190).

## FastAPI Dependency Injection for Route Protection

Shadowbroker exposes three primary dependency functions that routes import from [`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py) to enforce authentication requirements. These functions integrate directly with FastAPI’s `Depends` mechanism.

### require_admin

The `require_admin` dependency (lines 19-28) rejects any request lacking a valid admin key or appropriate scoped token. Apply this to sensitive endpoints that demand full administrative privileges.

### require_local_operator

The `require_local_operator` dependency (lines 65-74) restricts access to loopback interfaces (127.0.0.1), Docker bridge networks, or hosts presenting a valid admin key. This function is ideal for local tooling that should not exposed to external network interfaces.

### require_openclaw_or_local

The `require_openclaw_or_local` dependency (lines 84-106) implements a three-factor trust model. It accepts requests from:
- Trusted local hosts (loopback or Docker bridge)
- Valid admin key holders
- Remote agents presenting a cryptographically verified OpenClaw HMAC signature

This dependency enables secure remote agent communication without exposing admin credentials over the network.

## OpenClaw HMAC Authentication for Remote Agents

For remote agent verification, Shadowbroker implements the OpenClaw HMAC protocol in `_verify_openclaw_hmac`. This mechanism provides strong cryptographic assurance of request authenticity and integrity.

### Request Signing Headers

Remote agents must include three custom headers:
- `X-SB-Timestamp`: Unix timestamp
- `X-SB-Nonce`: Random hex string (minimum 16 characters)
- `X-SB-Signature`: HMAC-SHA256 of `METHOD|path|timestamp|nonce|sha256(body)` using the shared secret `OPENCLAW_HMAC_SECRET`

### Verification and Replay Protection

The verification routine performs multiple security checks ([`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py), lines 81-124):
1. Validates header presence and nonce length
2. Enforces timestamp freshness (±60 seconds, with tighter bounds during startup)
3. Checks the nonce against an expiring cache to prevent replay attacks
4. Hashes the request body and recomputes the expected HMAC
5. Stores the nonce temporarily if the signature matches

The bounded, auto-expiring nonce cache prevents replay attacks without requiring persistent disk storage (lines 81-91).

## Transport-Tier Enforcement and Authorization

Shadowbroker extends authorization beyond identity verification to network topology through transport-tier policies. Each API endpoint carries a classification (e.g., `private_strong`, `private_transitional`) that determines whether requests may traverse public networks or must remain within private lanes.

The `_resolve_route_transport_policy` function computes the effective policy for a route, while `_minimum_transport_tier` and `_private_plane_access_path` helpers enforce these constraints. While technically part of the authorization layer—gating data flow based on network path—the implementation resides in [`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py) to maintain cohesion with authentication logic.

## Security Hardening Measures

### Authorization Header Sanitization

When an OpenClaw HMAC-authenticated request carries an `Authorization` header resembling an LLM API key, Shadowbroker logs a critical error and rejects the request immediately ([`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py), lines 106-116). This prevents accidental credential leakage where remote agents might mistakenly forward sensitive third-party API keys.

### Nonce Cache Pruning

The replay protection system uses a bounded cache with automatic expiration to track consumed nonces. This design ensures the system can deny replay attempts without maintaining large persistent databases of historical request identifiers (lines 81-91).

## Implementation Examples

Protect an administrative endpoint using the `require_admin` dependency:

```python
from fastapi import APIRouter, Depends
from backend.auth import require_admin

router = APIRouter()

@router.get("/api/admin/status", dependencies=[Depends(require_admin)])
async def admin_status():
    return {"ok": True, "msg": "Admin access granted"}

```

Allow local tooling or verified remote OpenClaw agents:

```python
from backend.auth import require_openclaw_or_local
from fastapi import APIRouter, Depends

router = APIRouter()

@router.post("/api/ai/query", dependencies=[Depends(require_openclaw_or_local)])
async def ai_query(payload: dict):
    return {"result": "Processed securely"}

```

Manually verify scoped authentication within an endpoint:

```python
from backend.auth import _check_scoped_auth, _required_scope_for_request
from fastapi import Request, HTTPException

async def custom_endpoint(request: Request):
    scope = _required_scope_for_request(request)
    ok, detail = _check_scoped_auth(request, scope)
    if not ok:
        raise HTTPException(status_code=403, detail=detail)
    return {"secure": True}

```

## Key Source Files

| File | Role |
|------|------|
| [`backend/auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/auth.py) | Central authentication logic, scoped-token handling, OpenClaw HMAC verification, and transport-tier policy enforcement |
| [`backend/main.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/backend/main.py) | FastAPI application wiring that imports dependency functions from [`auth.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/auth.py) |
| [`routers/ai_intel.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/routers/ai_intel.py) | Demonstrates production usage of `require_openclaw_or_local` for AI-related routes |
| [`services/config.py`](https://github.com/BigBodyCobain/Shadowbroker/blob/main/services/config.py) | Provides `get_settings()` used throughout authentication to fetch environment and configuration values |

## Summary

- **Multi-layered authentication**: Shadowbroker combines admin keys, scoped tokens, local-network trusts, and HMAC signatures to verify caller identity.
- **Dynamic scope resolution**: The `_required_scope_for_request` function categorizes endpoints and enforces granular permissions through `_check_scoped_auth`.
- **FastAPI integration**: Dependencies `require_admin`, `require_local_operator`, and `require_openclaw_or_local` provide declarative route protection.
- **Cryptographic verification**: OpenClaw HMAC uses timestamp-bound, nonce-protected signatures with replay-resistant caching.
- **Transport-tier policies**: Network segmentation rules gate data flow independently of identity verification, enforcing private-lane requirements for sensitive operations.

## Frequently Asked Questions

### What is the difference between require_admin and require_local_operator?

**require_admin** demands a valid master admin key or scoped token regardless of network origin, while **require_local_operator** permits unauthenticated requests only from localhost (127.0.0.1) or Docker bridge networks unless a valid admin key is provided. Use the former for administrative dashboards and the latter for local maintenance tools.

### How does Shadowbroker prevent replay attacks in OpenClaw HMAC authentication?

The `_verify_openclaw_hmac` function stores each nonce in a bounded, auto-expiring cache after successful verification. Subsequent requests presenting the same nonce are rejected immediately, ensuring attackers cannot replay captured request signatures within the 60-second validity window.

### Can I use scoped tokens without setting the ADMIN_KEY?

Yes. The `MESH_SCOPED_TOKENS` configuration allows you to define short-lived tokens with specific scopes independent of the master `ADMIN_KEY`. However, if neither the master key nor scoped tokens are configured, the system will only permit access via insecure admin mode (if enabled) or local operator restrictions, which are unsuitable for production use.

### What happens if a request contains both OpenClaw HMAC headers and an Authorization header?

Shadowbroker treats this as a potential security violation. When OpenClaw authentication succeeds but the request also carries an `Authorization` header resembling an LLM API key, the system logs a critical error and rejects the request to prevent accidental credential leakage from remote agents.