mirror of
https://github.com/BigBodyCobain/Shadowbroker.git
synced 2026-12-05 17:13:45 +01:00
Let the operator's own UI join Infonet without an admin-key login
Joining Infonet from the UI failed with "operator authentication required" unless the user had first unlocked admin with the admin key. That is the first thing a new user does, so it hit everyone. The frontend proxy now presents an HMAC of the admin key in X-SB-Operator-Client, only when the page was reached by a name people use for their own node (localhost, an IP, a LAN or single-label name, a Tailscale name, or a configured host), and strips any copy of that header a browser sends. The backend's new require_operator_client accepts that token from an allowed origin, and otherwise falls back to the admin-key check. Only /api/wormhole/join uses it; admin controls still need the key, and a caller reaching the backend directly still gets 403. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c73298aa2
commit
68667e07a7
4 files changed
+195
-1
No files matched your search
@@ -420,6 +420,48 @@ def is_local_operator_request(request: Request) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The operator's own client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
OPERATOR_CLIENT_HEADER = "X-SB-Operator-Client"
|
||||
_OPERATOR_CLIENT_CONTEXT = b"shadowbroker-operator-client-v1"
|
||||
|
||||
|
||||
def operator_client_token(admin_key: str | None = None) -> str:
|
||||
"""The credential the web UI's server-side proxy presents for the
|
||||
operator's own browser.
|
||||
|
||||
It is an HMAC of the admin key, so the proxy can vouch for its own UI
|
||||
without handing the admin key to a browser that has not logged in, and
|
||||
the token cannot be turned back into the key. It never grants admin
|
||||
controls: only routes guarded by ``require_operator_client`` accept it.
|
||||
Empty when no admin key is configured."""
|
||||
key = str(admin_key if admin_key is not None else _current_admin_key() or "").strip()
|
||||
if not key:
|
||||
return ""
|
||||
return hmac.new(key.encode("utf-8"), _OPERATOR_CLIENT_CONTEXT, _hashlib_mod.sha256).hexdigest()
|
||||
|
||||
|
||||
def _presents_operator_client_token(request: Request) -> bool:
|
||||
expected = operator_client_token()
|
||||
presented = str(request.headers.get(OPERATOR_CLIENT_HEADER, "") or "").strip()
|
||||
if not expected or not presented:
|
||||
return False
|
||||
return hmac.compare_digest(presented.encode(), expected.encode())
|
||||
|
||||
|
||||
def require_operator_client(request: Request):
|
||||
"""The operator's own client: the admin key, or the token the web UI's
|
||||
proxy presents (``operator_client_token``). Guards participation routes
|
||||
the UI uses without an admin-key login, such as joining Infonet. A caller
|
||||
that reaches the backend directly (LAN, or the onion service, which maps
|
||||
to the backend port) has no token and still needs the admin key."""
|
||||
if operator_origin_allowed(request) and _presents_operator_client_token(request):
|
||||
return
|
||||
require_local_operator(request)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OpenClaw HMAC authentication
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -13,6 +13,7 @@ from auth import (
|
||||
_strong_claims_policy_snapshot,
|
||||
require_admin,
|
||||
require_local_operator,
|
||||
require_operator_client,
|
||||
)
|
||||
from limiter import limiter
|
||||
|
||||
@@ -622,7 +623,7 @@ async def api_get_wormhole_status(request: Request):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/wormhole/join", dependencies=[Depends(require_local_operator)])
|
||||
@router.post("/api/wormhole/join", dependencies=[Depends(require_operator_client)])
|
||||
@limiter.limit("10/minute")
|
||||
async def api_wormhole_join(request: Request):
|
||||
from services.config import get_settings
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""The operator's own UI can join Infonet without an admin-key login.
|
||||
|
||||
The frontend proxy presents an HMAC of the admin key in X-SB-Operator-Client.
|
||||
The backend accepts that token only where require_operator_client is used,
|
||||
and a missing or wrong token still falls back to the admin-key check.
|
||||
"""
|
||||
|
||||
import hmac
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import auth
|
||||
|
||||
ADMIN_KEY = "test-admin-key-for-operator-client"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setattr(auth, "_current_admin_key", lambda: ADMIN_KEY)
|
||||
app = FastAPI()
|
||||
|
||||
@app.post("/join", dependencies=[Depends(auth.require_operator_client)])
|
||||
def join():
|
||||
return {"ok": True}
|
||||
|
||||
@app.post("/admin-only", dependencies=[Depends(auth.require_local_operator)])
|
||||
def admin_only():
|
||||
return {"ok": True}
|
||||
|
||||
return TestClient(app, client=("203.0.113.9", 50000))
|
||||
|
||||
|
||||
def _expected_token() -> str:
|
||||
return hmac.new(ADMIN_KEY.encode(), b"shadowbroker-operator-client-v1", hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def test_token_matches_the_proxy_formula():
|
||||
assert auth.operator_client_token(ADMIN_KEY) == _expected_token()
|
||||
|
||||
|
||||
def test_no_token_and_no_key_is_refused(client):
|
||||
assert client.post("/join").status_code == 403
|
||||
|
||||
|
||||
def test_wrong_token_is_refused(client):
|
||||
resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: "0" * 64})
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_proxy_token_is_accepted(client):
|
||||
resp = client.post("/join", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()})
|
||||
assert resp.status_code == 200
|
||||
|
||||
|
||||
def test_admin_key_still_works(client):
|
||||
assert client.post("/join", headers={"X-Admin-Key": ADMIN_KEY}).status_code == 200
|
||||
|
||||
|
||||
def test_token_is_refused_from_a_foreign_origin(client):
|
||||
resp = client.post(
|
||||
"/join",
|
||||
headers={
|
||||
auth.OPERATOR_CLIENT_HEADER: _expected_token(),
|
||||
"Origin": "https://evil.example",
|
||||
"Sec-Fetch-Site": "cross-site",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_token_does_not_unlock_admin_routes(client):
|
||||
resp = client.post("/admin-only", headers={auth.OPERATOR_CLIENT_HEADER: _expected_token()})
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_no_token_without_an_admin_key(monkeypatch):
|
||||
monkeypatch.setattr(auth, "_current_admin_key", lambda: "")
|
||||
assert auth.operator_client_token() == ""
|
||||
|
||||
|
||||
def test_join_route_uses_the_operator_client_check():
|
||||
from routers import wormhole
|
||||
|
||||
route = next(r for r in wormhole.router.routes if getattr(r, "path", "") == "/api/wormhole/join")
|
||||
calls = {d.call for d in route.dependant.dependencies}
|
||||
assert auth.require_operator_client in calls
|
||||
@@ -10,6 +10,8 @@
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createHmac } from 'crypto';
|
||||
import { isIP } from 'net';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { resolveAdminSessionToken, verifyPresentedAdminKey } from '@/lib/server/adminSessionStore';
|
||||
@@ -23,6 +25,7 @@ const STRIP_REQUEST = new Set([
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'x-admin-key',
|
||||
'x-sb-operator-client',
|
||||
'te',
|
||||
'trailers',
|
||||
'transfer-encoding',
|
||||
@@ -95,6 +98,63 @@ function isSensitiveProxyPath(pathSegments: string[]): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Token that tells the backend a request came through this proxy from the
|
||||
* operator's own UI (mirrors backend/auth.py operator_client_token). It is an
|
||||
* HMAC of the admin key, so the proxy can vouch for its own UI without giving
|
||||
* the admin key to a browser that has not logged in. The backend accepts it
|
||||
* only on routes the operator's UI needs before login (joining Infonet),
|
||||
* never for admin controls. A caller that reaches the backend directly is
|
||||
* still a stranger.
|
||||
*/
|
||||
let operatorClientCache: { key: string; token: string } | null = null;
|
||||
function operatorClientToken(): string {
|
||||
const key = String(process.env.ADMIN_KEY || '').trim();
|
||||
if (!key) return '';
|
||||
if (operatorClientCache?.key !== key) {
|
||||
operatorClientCache = {
|
||||
key,
|
||||
token: createHmac('sha256', key).update('shadowbroker-operator-client-v1').digest('hex'),
|
||||
};
|
||||
}
|
||||
return operatorClientCache.token;
|
||||
}
|
||||
|
||||
const LOCAL_HOST_SUFFIXES = ['.localhost', '.local', '.lan', '.internal', '.home.arpa', '.ts.net'];
|
||||
|
||||
/**
|
||||
* A web page on someone else's domain can point that domain at this machine
|
||||
* (DNS rebinding) and pass a same-origin check. Names like that are public
|
||||
* DNS names; the names people use to reach their own node are IPs,
|
||||
* localhost, single-label or LAN names, a Tailscale name, or a reverse-proxy
|
||||
* name they configured. Only those get the operator-client token.
|
||||
*/
|
||||
function hostIsOperatorReachable(req: NextRequest): boolean {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(req.nextUrl.origin || 'http://' + (req.headers.get('host') || '')).hostname.toLowerCase();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
host = host.replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
||||
if (!host) return false;
|
||||
if (host === 'localhost' || isIP(host)) return true;
|
||||
if (!host.includes('.') || LOCAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) return true;
|
||||
const configured = [
|
||||
...(process.env.SHADOWBROKER_ALLOWED_ORIGINS || '').split(','),
|
||||
...(process.env.SHADOWBROKER_TRUSTED_FRONTEND_HOSTS || '').split(','),
|
||||
];
|
||||
return configured.some((value) => {
|
||||
const entry = value.trim().toLowerCase();
|
||||
if (!entry) return false;
|
||||
try {
|
||||
return (entry.includes('://') ? new URL(entry).hostname : entry) === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function proxy(req: NextRequest, pathSegments: string[]): Promise<NextResponse> {
|
||||
try {
|
||||
if (!isAllowedBrowserRequest(req)) {
|
||||
@@ -217,6 +277,8 @@ async function proxy(req: NextRequest, pathSegments: string[]): Promise<NextResp
|
||||
if (authenticatedKey && (isSensitiveProxyPath(pathSegments) || isSensitiveMeshPath)) {
|
||||
forwardHeaders.set('X-Admin-Key', authenticatedKey);
|
||||
}
|
||||
const clientToken = hostIsOperatorReachable(req) ? operatorClientToken() : '';
|
||||
if (clientToken) forwardHeaders.set('X-SB-Operator-Client', clientToken);
|
||||
|
||||
const isBodyless = req.method === 'GET' || req.method === 'HEAD';
|
||||
let upstream: Response | null = null;
|
||||
|
||||
Reference in new issue
Block a user