feat(cloud-auth): verify scoped bearer tokens

This commit is contained in:
2026-07-12 17:45:31 +08:00
parent 4cb116f527
commit b916b394c7
4 changed files with 186 additions and 27 deletions
@@ -27,7 +27,7 @@
## 4. Authentication And Authorization
- [ ] 4.1 Extend authenticated principals with scopes and implement constant-time configured bearer-token verification without logging credentials.
- [x] 4.1 Extend authenticated principals with scopes and implement constant-time configured bearer-token verification without logging credentials.
- [ ] 4.2 Add public scopes for task submission/read, pool read, plugin read, and plugin administration and enforce them on every `/v1` route.
- [ ] 4.3 Add host principals bound to one `host_id` and reject cross-host heartbeat, claim, renewal, or result operations.
- [ ] 4.4 Make missing production credentials a startup/readiness failure and permit anonymous mode only through the explicit non-production override.
+88
View File
@@ -0,0 +1,88 @@
from __future__ import annotations
from dataclasses import dataclass, field
from hashlib import sha256
from hmac import compare_digest
from typing import Protocol, runtime_checkable
@dataclass(frozen=True)
class Principal:
id: str = "anonymous"
scopes: frozenset[str] = field(default_factory=frozenset)
@runtime_checkable
class AuthProvider(Protocol):
def authenticate(self, request: object) -> Principal | None: ...
class NullAuthProvider:
"""Explicit insecure-development provider with unrestricted scope."""
def authenticate(self, request: object) -> Principal | None:
return Principal(scopes=frozenset({"*"}))
@dataclass(frozen=True)
class BearerCredential:
principal_id: str
token: str = field(repr=False)
scopes: frozenset[str] = field(default_factory=frozenset)
def __post_init__(self) -> None:
if not self.principal_id.strip():
raise ValueError("bearer credential principal_id must not be empty")
if not self.token:
raise ValueError("bearer credential token must not be empty")
@dataclass(frozen=True)
class _StoredBearerCredential:
principal: Principal
token_digest: bytes = field(repr=False)
class ConfiguredBearerAuthProvider:
"""Authenticate configured bearer tokens without exposing credential text."""
def __init__(self, credentials: list[BearerCredential]) -> None:
self._credentials = tuple(
_StoredBearerCredential(
principal=Principal(
id=credential.principal_id,
scopes=frozenset(credential.scopes),
),
token_digest=_token_digest(credential.token),
)
for credential in credentials
)
def authenticate(self, request: object) -> Principal | None:
token = _extract_bearer_token(request)
if token is None:
return None
candidate_digest = _token_digest(token)
matched_principal: Principal | None = None
for credential in self._credentials:
if compare_digest(candidate_digest, credential.token_digest):
matched_principal = credential.principal
return matched_principal
def _extract_bearer_token(request: object) -> str | None:
headers = getattr(request, "headers", None)
if headers is None:
return None
authorization = headers.get("authorization")
if not isinstance(authorization, str):
return None
scheme, separator, token = authorization.partition(" ")
if not separator or scheme.lower() != "bearer" or not token:
return None
return token
def _token_digest(token: str) -> bytes:
return sha256(token.encode("utf-8")).digest()
+4 -26
View File
@@ -10,9 +10,9 @@ authentication can be added later without changing route signatures.
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol, runtime_checkable
from typing import TYPE_CHECKING
from cloud.auth import AuthProvider, NullAuthProvider, Principal
from cloud.sdk.models import (
DeviceResponse,
ErrorResponse,
@@ -23,34 +23,12 @@ from cloud.sdk.models import (
TaskSubmissionRequest,
TaskSubmissionResponse,
)
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import JSONResponse
from fastapi import APIRouter, HTTPException, Request, status
if TYPE_CHECKING:
from cloud.plugins import PluginRegistry
from cloud.pool import DevicePool
from cloud.scheduler import TaskConstraints, TaskScheduler
@dataclass(frozen=True)
class Principal:
"""An authenticated principal. ``anonymous`` for the NullAuthProvider."""
id: str = "anonymous"
@runtime_checkable
class AuthProvider(Protocol):
"""Returns a Principal if the request is allowed, None to reject."""
def authenticate(self, request: object) -> Principal | None: ...
class NullAuthProvider:
"""Default auth provider: every caller is anonymous-and-allowed."""
def authenticate(self, request: object) -> Principal | None:
return Principal()
from cloud.scheduler import TaskScheduler
def create_cloud_router(
+93
View File
@@ -0,0 +1,93 @@
from __future__ import annotations
from dataclasses import dataclass
import cloud.auth as auth_module
from cloud.auth import (
BearerCredential,
ConfiguredBearerAuthProvider,
NullAuthProvider,
)
@dataclass
class _Request:
headers: dict[str, str]
def test_configured_bearer_auth_returns_identity_and_scopes() -> None:
provider = ConfiguredBearerAuthProvider(
[
BearerCredential(
principal_id="integrator-a",
token="secret-a",
scopes=frozenset({"tasks:submit", "tasks:read"}),
)
]
)
principal = provider.authenticate(
_Request(headers={"authorization": "Bearer secret-a"})
)
assert principal is not None
assert principal.id == "integrator-a"
assert principal.scopes == frozenset({"tasks:submit", "tasks:read"})
def test_missing_malformed_or_invalid_bearer_token_is_rejected() -> None:
provider = ConfiguredBearerAuthProvider(
[BearerCredential(principal_id="integrator", token="valid-token")]
)
assert provider.authenticate(_Request(headers={})) is None
assert (
provider.authenticate(_Request(headers={"authorization": "Basic value"}))
is None
)
assert (
provider.authenticate(_Request(headers={"authorization": "Bearer invalid"}))
is None
)
def test_bearer_verification_compares_every_configured_digest(monkeypatch) -> None:
comparisons: list[tuple[bytes, bytes]] = []
original_compare_digest = auth_module.compare_digest
def recording_compare_digest(left: bytes, right: bytes) -> bool:
comparisons.append((left, right))
return original_compare_digest(left, right)
monkeypatch.setattr(auth_module, "compare_digest", recording_compare_digest)
provider = ConfiguredBearerAuthProvider(
[
BearerCredential(principal_id="first", token="match"),
BearerCredential(principal_id="second", token="other"),
]
)
principal = provider.authenticate(
_Request(headers={"authorization": "Bearer match"})
)
assert principal is not None
assert principal.id == "first"
assert len(comparisons) == 2
assert all(len(left) == len(right) == 32 for left, right in comparisons)
def test_credential_representations_do_not_expose_token() -> None:
credential = BearerCredential(principal_id="integrator", token="top-secret")
provider = ConfiguredBearerAuthProvider([credential])
assert "top-secret" not in repr(credential)
assert "top-secret" not in repr(provider.__dict__)
def test_null_auth_provider_is_explicitly_unrestricted() -> None:
principal = NullAuthProvider().authenticate(_Request(headers={}))
assert principal is not None
assert principal.id == "anonymous"
assert principal.scopes == frozenset({"*"})