feat(credentials): add stage 3 authenticated OAuth and access-token issuance

Add explicit legacy/broker configuration. Broker mode requires a protected
keyring, product-approved permission profiles and enabled platform OAuth;
production requires PostgreSQL. Default legacy behavior stays unchanged.

Wire the broker to v2 signed device status, authorization start/status and
access-token issuance routes. Bind proofs to protocol, environment, app,
method/path and complete payload; verify nonce, certificate, owner and
binding generation. Add an additive generation migration and return the
current generation in binding receipts or authenticated bootstrap status.

Persist encrypted OAuth state and atomically claim callbacks. Verify the
actual consenting user, supersede older pending authorization intents and
recheck bindings/transactions before credential writes and issuance.
Preserve rotated credentials if unbind occurs mid-refresh, but deny issuance.
Return an explicit access-only response and record metadata-only audit.

Extract shared legacy device authentication so notifications do not depend
on the business proxy module. Broker mode omits legacy refresh/claim/start
and /work/api routes; authorization cards reference server-owned v2
transactions. Document signatures, configuration and migration boundaries.

Validation: 185 passed, 3 skipped (real PostgreSQL not configured), with
15 existing dependency deprecation warnings. New API coverage: 38 passed,
1 real PostgreSQL case skipped. AST, docs and staged diff checks pass.

No production deployment, key generation, client upgrade or real Work API
calls were performed. Compose/mount configuration, full unbind/connection
compensation and durable message-task lifecycle remain later stages.
This commit is contained in:
ex_tianzy
2026-11-04 10:52:16 +08:00
parent 02d433250f
commit 93bfbca83a
13 changed files with 1066 additions and 47 deletions
+21
View File
@@ -1,4 +1,6 @@
from pathlib import Path
import re
from urllib.parse import urlsplit
from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -39,9 +41,28 @@ class Settings(BaseSettings):
max_result: int = 16000
allow_insecure_local: bool = False
enrollment_signer_url: str = ""
credential_mode: str = "legacy"
credential_keyring_file: Path | None = None
credential_permission_profiles: dict[str, list[str]] = {}
@model_validator(mode="after")
def validate_runtime(self):
if self.credential_mode not in {"legacy", "broker"}:
raise ValueError("invalid credential mode")
for profile, scopes in self.credential_permission_profiles.items():
if (not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", profile) or not scopes or len(scopes) > 128
or any(not re.fullmatch(r"[A-Za-z0-9_:.-]{1,256}", scope) for scope in scopes)):
raise ValueError("invalid credential permission profile")
if self.credential_mode == "broker" and self.role == "connector":
if self.environment == "production" and not self.database_url:
raise ValueError("production broker mode requires PostgreSQL")
if (not self.credential_keyring_file or not self.credential_permission_profiles
or not self.feishu_enabled or not self.oauth_enabled):
raise ValueError("broker mode requires keyring, product permissions and enabled platform OAuth")
authorize = urlsplit(self.feishu_authorize_url)
if (authorize.scheme != "https" or not authorize.hostname or authorize.username or authorize.password
or authorize.query or authorize.fragment):
raise ValueError("broker mode requires a fixed HTTPS authorization endpoint")
if self.environment not in {"production", "test", "development"}:
raise ValueError("invalid environment")
if self.role == "connector" and min(len(self.admin_secret), len(self.internal_secret)) < 32:
+19 -7
View File
@@ -142,8 +142,16 @@ def create_app(settings=None, redis=None, platform=None):
store = Store(s.data_dir / "metadata.sqlite", s.database_url)
f = platform or Feishu(s)
broker = Broker(s, r, store)
oauth = OAuth(s, r, f)
oauth.store = store
if s.credential_mode == "broker":
from .credential_api import CredentialAPI
from .credential_broker import CredentialBroker
from .credential_store import CredentialStore, CredentialKeyring
credential_store = CredentialStore(store, CredentialKeyring.from_file(s.credential_keyring_file))
credential_broker = CredentialBroker(credential_store, r, f, environment=s.environment, app_id=s.feishu_app_id)
oauth = CredentialAPI(s, r, store, credential_broker)
else:
oauth = OAuth(s, r, f)
oauth.store = store
from .notifications import router as notification_router
background = set()
@@ -168,8 +176,9 @@ def create_app(settings=None, redis=None, platform=None):
async def sweep():
while True:
await asyncio.sleep(30)
async with oauth.lock:
oauth.prune()
if s.credential_mode == "legacy":
async with oauth.lock:
oauth.prune()
sweep_task = asyncio.create_task(sweep())
try:
yield
@@ -207,8 +216,9 @@ def create_app(settings=None, redis=None, platform=None):
from .enrollment import enrollment_router
app.include_router(enrollment_router(s, r, store, broker.signer, admin))
from .work_api import router as work_router
app.include_router(work_router(s, r, store, f))
if s.credential_mode == "legacy":
from .work_api import router as work_router
app.include_router(work_router(s, r, store, f))
@app.get("/health")
async def health():
@@ -329,7 +339,9 @@ def create_app(settings=None, redis=None, platform=None):
raise HTTPException(409, "owner/device already bound; request new code") from None
await r.incr("hn:web-generation:" + body.host_id)
store.audit(owner, "bind", body.host_id, "success")
return sign({"host_id": body.host_id, "owner": owner, "ts": int(time.time())}, broker.signer)
return sign({"host_id": body.host_id, "owner": owner,
"binding_generation": store.device(body.host_id)["binding_generation"],
"ts": int(time.time())}, broker.signer)
@app.post("/admin/test/binding-code")
async def test_code(body: Instruction, request: Request):
+317
View File
@@ -0,0 +1,317 @@
"""Opt-in broker-mode OAuth and device-authenticated access-token issuance."""
import hashlib
import hmac
import json
import re
import secrets
import time
from urllib.parse import urlencode
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from .common import no_cache, peer, rate_limit
from .credential_broker import (AuthorizationRequired, BrokerUnavailable, PermissionRequired, RefreshUnknown)
from .credential_store import CredentialError
from .crypto import canonical, verified, verify_device
class DeviceRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
host_id: str = Field(pattern=r"^[a-f0-9]{32}$")
binding_owner: str = Field(min_length=1, max_length=128)
binding_generation: int = Field(strict=True, ge=0)
request_id: str = Field(pattern=r"^[A-Za-z0-9_-]{8,100}$")
proof: dict = Field(repr=False)
class StatusRequest(DeviceRequest):
# Only status may bootstrap the generation, still proving the bound owner.
binding_generation: int | None = Field(default=None, strict=True, ge=0)
class PermissionRequest(DeviceRequest):
permission_profile: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$")
class TransactionRequest(DeviceRequest):
transaction_id: str = Field(pattern=r"^oauth2_[a-f0-9]{32}$")
class CredentialAPI:
def __init__(self, settings, redis, store, broker, clock=time.time):
self.s, self.r, self.store, self.broker, self.clock = settings, redis, store, broker, clock
self.db = store.db
with self.db:
self.db.execute("""CREATE TABLE IF NOT EXISTS work_authorizations_v2(
transaction_id TEXT PRIMARY KEY, environment TEXT NOT NULL, app_id TEXT NOT NULL,
owner TEXT NOT NULL, host_id TEXT NOT NULL, binding_generation BIGINT NOT NULL,
permission_profile TEXT NOT NULL, scopes_json TEXT NOT NULL,
request_id TEXT NOT NULL, request_hash TEXT NOT NULL, state_hash TEXT NOT NULL UNIQUE,
state_key_id TEXT NOT NULL, state_ciphertext TEXT NOT NULL,
created_at DOUBLE PRECISION NOT NULL, expires_at DOUBLE PRECISION NOT NULL,
status TEXT NOT NULL,
UNIQUE(environment,app_id,host_id,binding_generation,request_id))""")
self.router = APIRouter()
self.router.add_api_route("/work/v2/status", self.status, methods=["POST"])
self.router.add_api_route("/work/v2/authorizations", self.start, methods=["POST"])
self.router.add_api_route("/work/v2/authorizations/status", self.transaction_status, methods=["POST"])
self.router.add_api_route("/work/v2/credentials/access-token", self.access_token, methods=["POST"])
self.router.add_api_route("/oauth/cb", self.callback, methods=["GET"])
def require_binding(self, host, owner, generation=None):
device = self.store.device(host)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "device_unbound_or_revoked")
if (device["owner"] != owner
or (generation is not None and device["binding_generation"] != generation)):
raise HTTPException(403, "stale_binding")
return device
async def authenticate(self, body, request):
await rate_limit(self.r, "credential-ip:" + peer(request), 300)
device = self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
try:
key = verify_device(device["cert"], self.s.ca_cert.read_bytes(), body.host_id)
proof = verified(body.proof, key)
if (type(proof["version"]) is not int or proof["version"] != 2
or proof["environment"] != self.s.environment or proof["app_id"] != self.s.feishu_app_id
or proof["host_id"] != body.host_id or proof["purpose"] != "work-v2"
or proof["method"] != "POST" or proof["path"] != request.url.path
or type(proof["ts"]) not in (int, float)
or not abs(self.clock() - proof["ts"]) <= 90
or not isinstance(proof["nonce"], str)
or not re.fullmatch(r"[a-f0-9]{32}", proof["nonce"])
or proof["payload_hash"] != hashlib.sha256(canonical(body.model_dump(exclude={"proof"}))).hexdigest()):
raise ValueError()
except Exception:
raise HTTPException(403, "invalid_device_proof") from None
if not await self.r.set("hn:credential-proof:" + body.host_id + ":" + proof["nonce"],
"used", nx=True, ex=180):
raise HTTPException(409, "device_request_replayed")
await rate_limit(self.r, "credential-device:" + body.host_id, 120)
# Binding may have changed during Redis awaits.
return self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
def scopes(self, profile):
scopes = self.s.credential_permission_profiles.get(profile)
if not scopes:
raise HTTPException(403, "permission_profile_not_allowed")
return tuple(sorted(set(scopes)))
def _credential_status(self, owner):
value = self.broker.store.get(self.s.environment, self.s.feishu_app_id, owner)
if value is None:
return {"credential_status": "authorization_required", "granted_scopes": []}
if self.broker.store.refresh_status(self.s.environment, self.s.feishu_app_id, owner, value.version):
status = "refresh_unknown"
elif value.access_expires_at > self.clock() or value.refresh_expires_at > self.clock():
status = "available"
else:
status = "authorization_required"
return {"credential_status": status, "granted_scopes": list(value.scopes),
"credential_version": value.version, "access_expires_at": value.access_expires_at}
async def status(self, body: StatusRequest, request: Request):
device = await self.authenticate(body, request)
try:
result = self._credential_status(device["owner"])
except CredentialError:
raise HTTPException(503, "credential_temporarily_unavailable") from None
self.require_binding(body.host_id, device["owner"], device["binding_generation"])
return no_cache(JSONResponse({"credential_mode": "broker", "protocol_version": 2,
"binding_owner": device["owner"],
"binding_generation": device["binding_generation"],
"permission_profiles": sorted(self.s.credential_permission_profiles), **result}))
def _row(self, transaction_id):
row = self.db.execute("""SELECT * FROM work_authorizations_v2
WHERE transaction_id=? AND environment=? AND app_id=?""",
(transaction_id, self.s.environment, self.s.feishu_app_id)).fetchone()
if not row:
raise HTTPException(404, "authorization_not_found")
return dict(row)
def _live_row(self, transaction_id):
row = self._row(transaction_id)
if row["expires_at"] <= self.clock():
raise HTTPException(410, "authorization_expired")
self.require_binding(row["host_id"], row["owner"], row["binding_generation"])
if list(self.scopes(row["permission_profile"])) != json.loads(row["scopes_json"]):
raise HTTPException(409, "permission_profile_changed")
return row
@staticmethod
def _state_aad(row):
names = ("transaction_id", "environment", "app_id", "owner", "host_id", "binding_generation",
"permission_profile", "scopes_json", "request_hash", "expires_at", "state_hash", "state_key_id")
return canonical(["hainuo-oauth-state-v2", *[row[name] for name in names]])
def _state(self, row):
try:
state = self.broker.store.keyring.decrypt(row["state_key_id"], row["state_ciphertext"],
self._state_aad(row)).decode("ascii")
if not hmac.compare_digest(hashlib.sha256(state.encode()).hexdigest(), row["state_hash"]):
raise ValueError()
return state
except Exception:
raise HTTPException(503, "authorization_state_unavailable") from None
def _authorization_url(self, row):
params = {"app_id": self.s.feishu_app_id, "redirect_uri": self.s.public_url.rstrip("/") + "/oauth/cb",
"state": self._state(row), "scope": " ".join(json.loads(row["scopes_json"]))}
return self.s.feishu_authorize_url + "?" + urlencode(params)
def authorization_url_for_notification(self, owner, host, transaction_id):
row = self._live_row(transaction_id)
if row["owner"] != owner or row["host_id"] != host or row["status"] != "waiting":
raise HTTPException(403, "active_device_owned_authorization_required")
return self._authorization_url(row)
async def start(self, body: PermissionRequest, request: Request):
device = await self.authenticate(body, request)
scopes = self.scopes(body.permission_profile)
await rate_limit(self.r, "credential-authorize:" + device["owner"], 5)
self.require_binding(body.host_id, device["owner"], device["binding_generation"])
request_hash = hashlib.sha256(canonical(body.model_dump(exclude={"proof"}))).hexdigest()
row = self.db.execute("""SELECT * FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND host_id=? AND binding_generation=? AND request_id=?""",
(self.s.environment, self.s.feishu_app_id, body.host_id, body.binding_generation, body.request_id)).fetchone()
if row:
row = dict(row)
if row["request_hash"] != request_hash:
raise HTTPException(409, "request_id_reused")
else:
count = self.db.execute("""SELECT COUNT(*) AS total FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND status IN ('waiting','exchanging') AND expires_at>?""",
(self.s.environment, self.s.feishu_app_id, self.clock())).fetchone()["total"]
if count >= self.s.max_pending:
raise HTTPException(503, "authorization_capacity_reached")
state = "v2_" + secrets.token_urlsafe(32)
row = {"transaction_id": "oauth2_" + secrets.token_hex(16), "environment": self.s.environment,
"app_id": self.s.feishu_app_id, "owner": device["owner"], "host_id": body.host_id,
"binding_generation": device["binding_generation"], "permission_profile": body.permission_profile,
"scopes_json": json.dumps(scopes, separators=(",", ":")), "request_id": body.request_id,
"request_hash": request_hash, "state_hash": hashlib.sha256(state.encode()).hexdigest(),
"state_key_id": self.broker.store.keyring.active_key_id,
"created_at": float(self.clock()), "expires_at": float(self.clock() + 600), "status": "waiting"}
_, row["state_ciphertext"] = self.broker.store.keyring.encrypt(state.encode(), self._state_aad(row))
with self.db:
# Take a database row lock without changing the binding. This
# serializes distinct authorization starts across PG workers;
# Redis lease ownership is not a substitute for this transaction.
bound = self.db.execute("""UPDATE devices SET binding_generation=binding_generation
WHERE host_id=? AND owner=? AND binding_generation=? AND revoked=0""",
(body.host_id, device["owner"], device["binding_generation"])).rowcount
if bound != 1:
raise HTTPException(403, "stale_binding")
inserted = self.db.execute("""INSERT INTO work_authorizations_v2
(transaction_id,environment,app_id,owner,host_id,binding_generation,permission_profile,
scopes_json,request_id,request_hash,state_hash,state_key_id,state_ciphertext,created_at,expires_at,status)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING""",
tuple(row[key] for key in ("transaction_id", "environment", "app_id", "owner", "host_id",
"binding_generation", "permission_profile", "scopes_json", "request_id", "request_hash",
"state_hash", "state_key_id", "state_ciphertext", "created_at", "expires_at", "status"))).rowcount
if inserted == 1:
# One current authorization intent per application/user. An
# older narrow consent must not overwrite newer permissions.
self.db.execute("""UPDATE work_authorizations_v2 SET status='superseded'
WHERE environment=? AND app_id=? AND owner=? AND transaction_id<>?
AND status IN ('waiting','exchanging')""",
(self.s.environment, self.s.feishu_app_id, device["owner"], row["transaction_id"]))
actual = self.db.execute("""SELECT transaction_id,request_hash FROM work_authorizations_v2
WHERE environment=? AND app_id=? AND host_id=? AND binding_generation=? AND request_id=?""",
(self.s.environment, self.s.feishu_app_id, body.host_id, body.binding_generation, body.request_id)).fetchone()
if not actual or actual["request_hash"] != request_hash:
raise HTTPException(409, "request_id_reused")
row = self._live_row(actual["transaction_id"])
row = self._live_row(row["transaction_id"])
result = {"transaction_id": row["transaction_id"], "status": row["status"], "expires_at": row["expires_at"]}
if row["status"] == "waiting":
result["authorization_url"] = self._authorization_url(row)
return no_cache(JSONResponse(result, status_code=201))
async def transaction_status(self, body: TransactionRequest, request: Request):
await self.authenticate(body, request)
row = self._row(body.transaction_id)
if (row["owner"], row["host_id"], row["binding_generation"]) != (
body.binding_owner, body.host_id, body.binding_generation):
raise HTTPException(404, "authorization_not_found")
self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
status = ("expired" if row["expires_at"] <= self.clock() and row["status"] in {"waiting", "exchanging"}
else row["status"])
result = {"transaction_id": row["transaction_id"], "status": status}
if status == "authorized":
try:
result.update(self._credential_status(body.binding_owner))
except CredentialError:
raise HTTPException(503, "credential_temporarily_unavailable") from None
if not set(json.loads(row["scopes_json"])).issubset(result["granted_scopes"]):
result["status"] = "permission_update_required"
return no_cache(JSONResponse(result))
async def access_token(self, body: PermissionRequest, request: Request):
await self.authenticate(body, request)
required = self.scopes(body.permission_profile)
guard = lambda: self.require_binding(body.host_id, body.binding_owner, body.binding_generation)
try:
grant = await self.broker.get_access(body.binding_owner, required_scopes=required, guard=guard)
except HTTPException:
raise
except AuthorizationRequired:
raise HTTPException(401, "authorization_required") from None
except PermissionRequired:
raise HTTPException(403, "permission_update_required") from None
except RefreshUnknown:
raise HTTPException(409, "refresh_unknown") from None
except (BrokerUnavailable, CredentialError):
raise HTTPException(503, "credential_temporarily_unavailable") from None
guard()
self.store.audit(body.binding_owner, "credential_issue", body.host_id + ":" + body.request_id,
"completed_v" + str(grant.credential_version))
# Explicit whitelist: never asdict(UserCredential) or pass a platform response.
return no_cache(JSONResponse({"access_token": grant.access_token, "token_type": "Bearer",
"expires_at": grant.expires_at, "expires_in": max(0, int(grant.expires_at - self.clock())),
"server_time": self.clock(), "credential_version": grant.credential_version,
"granted_scopes": list(grant.scopes), "app_id": self.s.feishu_app_id}))
async def callback(self, request: Request, code: str = "", state: str = "", error: str = ""):
await rate_limit(self.r, "credential-callback:" + peer(request), 60)
if not re.fullmatch(r"v2_[A-Za-z0-9_-]{43}", state) or len(code) > 4096:
raise HTTPException(400, "invalid_authorization_callback")
row = self.db.execute("""SELECT transaction_id FROM work_authorizations_v2
WHERE state_hash=? AND environment=? AND app_id=?""",
(hashlib.sha256(state.encode()).hexdigest(), self.s.environment, self.s.feishu_app_id)).fetchone()
if not row:
raise HTTPException(400, "invalid_authorization_callback")
transaction = self._live_row(row["transaction_id"])
if not hmac.compare_digest(self._state(transaction), state) or transaction["status"] != "waiting":
raise HTTPException(400, "authorization_already_consumed")
if not code and not error:
raise HTTPException(400, "invalid_authorization_callback")
with self.db:
count = self.db.execute("""UPDATE work_authorizations_v2 SET status=?
WHERE transaction_id=? AND status='waiting' AND expires_at>?""",
("cancelled" if error else "exchanging", transaction["transaction_id"], self.clock())).rowcount
if count != 1:
raise HTTPException(400, "authorization_already_consumed")
if error:
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权已取消,请返回客户端。</p>", status_code=400))
def guard():
current = self._live_row(transaction["transaction_id"])
if current["status"] != "exchanging":
raise HTTPException(409, "authorization_not_active")
try:
await self.broker.authorize(transaction["owner"], code, guard=guard)
guard()
except Exception:
with self.db:
self.db.execute("UPDATE work_authorizations_v2 SET status='failed' WHERE transaction_id=? AND status='exchanging'",
(transaction["transaction_id"],))
raise HTTPException(502, "authorization_did_not_complete") from None
with self.db:
self.db.execute("UPDATE work_authorizations_v2 SET status='authorized' WHERE transaction_id=? AND status='exchanging'",
(transaction["transaction_id"],))
self.store.audit(transaction["owner"], "credential_authorized", transaction["transaction_id"], "completed")
return no_cache(HTMLResponse("<meta charset='utf-8'><p>授权完成,请返回客户端。</p>"))
+14 -2
View File
@@ -148,12 +148,14 @@ class CredentialBroker:
return AccessGrant(credential.access_token, credential.access_expires_at,
remaining, credential.version, credential.scopes)
async def authorize(self, owner, code):
async def authorize(self, owner, code, *, guard=None):
"""Only callable after the future OAuth transaction authenticates owner/state."""
identity = self._identity(owner)
if not isinstance(code, str) or not code or len(code) > 4096:
raise CredentialError("invalid authorization input")
async with self._lease(owner) as lease:
if guard:
guard()
current = self.store.get(*identity)
expected_version = current.version if current else 0
started = self.clock()
@@ -164,6 +166,8 @@ class CredentialBroker:
if not isinstance(info, dict) or info.get("open_id") != owner:
raise CredentialError("authorization identity mismatch")
await lease.check()
if guard:
guard()
version = self.store.save(*identity, expected_version=expected_version, **payload)
except CredentialConflict:
raise BrokerUnavailable("credential version changed") from None
@@ -176,11 +180,13 @@ class CredentialBroker:
credential = UserCredential(version=version, **{**payload, "scopes": tuple(payload["scopes"])})
return self._grant(credential, ())
async def get_access(self, owner, *, required_scopes=()):
async def get_access(self, owner, *, required_scopes=(), guard=None):
identity = self._identity(owner)
required = self._scopes(required_scopes)
# Lock even cache hits: authorization replacement and refresh share one owner.
async with self._lease(owner) as lease:
if guard:
guard()
current = self.store.get(*identity)
if current is None:
raise AuthorizationRequired("authorization required")
@@ -190,6 +196,8 @@ class CredentialBroker:
raise PermissionRequired("permission update required")
if current.access_expires_at - self.clock() > self.minimum_validity:
await lease.check()
if guard:
guard()
return self._grant(current, required)
if current.refresh_expires_at <= self.clock():
raise AuthorizationRequired("authorization required")
@@ -200,6 +208,8 @@ class CredentialBroker:
started = self.clock()
try:
await lease.check()
if guard:
guard()
result = await asyncio.wait_for(self.platform.credential_refresh(current.refresh_token),
self.platform_timeout)
payload = self._payload(result, started, previous=current)
@@ -223,4 +233,6 @@ class CredentialBroker:
self.store.finish_refresh(*identity, current.version, attempt, "completed")
from .credential_store import UserCredential
credential = UserCredential(version=version, **{**payload, "scopes": tuple(payload["scopes"])})
if guard:
guard()
return self._grant(credential, required)
+25
View File
@@ -0,0 +1,25 @@
"""Shared legacy device proof verification; v2 adds binding/version checks."""
import hashlib
import re
import time
from fastapi import HTTPException
from .crypto import canonical, verified, verify_device
async def device_owner(settings, redis, store, host, proof, purpose, payload):
device = store.device(host)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "active bound device required")
try:
key = verify_device(device["cert"], settings.ca_cert.read_bytes(), host)
data = verified(proof, key)
if (data["host_id"] != host or data["purpose"] != purpose or abs(time.time() - data["ts"]) > 90
or not re.fullmatch(r"[a-f0-9]{32}", data["nonce"])
or data["payload_hash"] != hashlib.sha256(canonical(payload)).hexdigest()):
raise ValueError()
except Exception:
raise HTTPException(403, "invalid device request proof") from None
if not await redis.set("hn:work-proof:" + host + ":" + data["nonce"], "1", nx=True, ex=180):
raise HTTPException(409, "device request replayed")
return device["owner"]
+18 -12
View File
@@ -12,7 +12,7 @@ from pydantic import BaseModel, ConfigDict, Field
from .common import no_cache, rate_limit
from .crypto import canonical
from .store import INTEGRITY_ERRORS
from .work_api import device_owner
from .device_auth import device_owner
class Notification(BaseModel):
@@ -56,17 +56,20 @@ def router(settings, redis, store, platform, oauth):
if body.kind == 'authorization':
if body.text or body.title or not body.oauth_state:
raise HTTPException(422, 'authorization requires only a pending OAuth state')
oauth.prune()
item = oauth.pending.get(body.oauth_state)
if (not settings.oauth_enabled or not item or item.status != 'waiting'
or item.owner != owner or item.host_id != body.host_id):
raise HTTPException(403, 'active device-owned authorization required')
params = {'app_id': settings.feishu_app_id,
'redirect_uri': settings.public_url.rstrip('/') + '/oauth/cb',
'state': body.oauth_state}
if settings.feishu_oauth_scopes:
params['scope'] = settings.feishu_oauth_scopes
url = settings.feishu_authorize_url + '?' + urlencode(params)
if hasattr(oauth, 'authorization_url_for_notification'):
url = oauth.authorization_url_for_notification(owner, body.host_id, body.oauth_state)
else:
oauth.prune()
item = oauth.pending.get(body.oauth_state)
if (not settings.oauth_enabled or not item or item.status != 'waiting'
or item.owner != owner or item.host_id != body.host_id):
raise HTTPException(403, 'active device-owned authorization required')
params = {'app_id': settings.feishu_app_id,
'redirect_uri': settings.public_url.rstrip('/') + '/oauth/cb',
'state': body.oauth_state}
if settings.feishu_oauth_scopes:
params['scope'] = settings.feishu_oauth_scopes
url = settings.feishu_authorize_url + '?' + urlencode(params)
if not url.startswith('https://'):
raise HTTPException(503, 'HTTPS authorization URL required')
content = {'config': {'wide_screen_mode': True},
@@ -99,6 +102,9 @@ def router(settings, redis, store, platform, oauth):
try:
# Complete credential acquisition before the last synchronous binding check.
token = await platform.tenant_token()
if body.kind == 'authorization' and hasattr(oauth, 'authorization_url_for_notification'):
# Recheck the transaction and generation after waiting on app credentials.
oauth.authorization_url_for_notification(owner, body.host_id, body.oauth_state)
device = store.device(body.host_id)
if not device or device['revoked'] or device['owner'] != owner:
status = 'binding_changed'
+1 -1
View File
@@ -65,7 +65,7 @@ class OAuth:
await rate_limit(self.redis, "oauth:start:" + peer(request), 20)
owner = ""
if body.host_id:
from .work_api import device_owner
from .device_auth import device_owner
owner = await device_owner(self.settings, self.redis, self.store, body.host_id,
body.proof, "work-oauth-v1", {})
async with self.lock:
+9 -3
View File
@@ -51,6 +51,12 @@ class Store:
self.db = sqlite3.connect(path, check_same_thread=False)
self.db.row_factory = sqlite3.Row
self.db.executescript("PRAGMA journal_mode=WAL;" + schema)
# Additive migration; retain all existing device identities and bindings.
with self.db:
if database_url:
self.db.execute("ALTER TABLE devices ADD COLUMN IF NOT EXISTS binding_generation BIGINT NOT NULL DEFAULT 0")
elif "binding_generation" not in {row["name"] for row in self.db.execute("PRAGMA table_info(devices)").fetchall()}:
self.db.execute("ALTER TABLE devices ADD COLUMN binding_generation BIGINT NOT NULL DEFAULT 0")
def device(self, host):
row = self.db.execute("SELECT * FROM devices WHERE host_id=?", (host,)).fetchone()
@@ -67,17 +73,17 @@ class Store:
def bind(self, host, owner):
with self.db:
# Conditional update also protects against two connectors racing for the same device.
count = self.db.execute("UPDATE devices SET owner=? WHERE host_id=? AND owner IS NULL AND revoked=0", (owner, host)).rowcount
count = self.db.execute("UPDATE devices SET owner=?,binding_generation=binding_generation+1 WHERE host_id=? AND owner IS NULL AND revoked=0", (owner, host)).rowcount
if count != 1:
raise ValueError("device unavailable or already bound")
def unbind(self, owner):
with self.db:
self.db.execute("UPDATE devices SET owner=NULL WHERE owner=?", (owner,))
self.db.execute("UPDATE devices SET owner=NULL,binding_generation=binding_generation+1 WHERE owner=?", (owner,))
def revoke(self, host):
with self.db:
self.db.execute("UPDATE devices SET revoked=1 WHERE host_id=?", (host,))
self.db.execute("UPDATE devices SET revoked=1,binding_generation=binding_generation+1 WHERE host_id=? AND revoked=0", (host,))
def begin_turn(self, turn, owner, host):
with self.db:
+2 -19
View File
@@ -10,7 +10,8 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from .common import no_cache, rate_limit
from .crypto import canonical, verified, verify_device
from .crypto import canonical
from .device_auth import device_owner
from .store import INTEGRITY_ERRORS
@@ -43,24 +44,6 @@ def business_allowed(method, path):
return any(re.fullmatch(p, path) for p in rules.get(method, []))
async def device_owner(settings, redis, store, host, proof, purpose, payload):
device = store.device(host)
if not device or device["revoked"] or not device["owner"]:
raise HTTPException(403, "active bound device required")
try:
key = verify_device(device["cert"], settings.ca_cert.read_bytes(), host)
data = verified(proof, key)
if (data["host_id"] != host or data["purpose"] != purpose or abs(time.time() - data["ts"]) > 90
or not re.fullmatch(r"[a-f0-9]{32}", data["nonce"])
or data["payload_hash"] != hashlib.sha256(canonical(payload)).hexdigest()):
raise ValueError()
except Exception:
raise HTTPException(403, "invalid device request proof") from None
if not await redis.set("hn:work-proof:" + host + ":" + data["nonce"], "1", nx=True, ex=180):
raise HTTPException(409, "device request replayed")
return device["owner"]
def router(settings, redis, store, platform):
routes = APIRouter()
store.db.execute("""CREATE TABLE IF NOT EXISTS business_operations(