跳转至

auth

feishu.gateway.auth

ServiceAuthError

Bases: Exception

内部网关请求缺少有效服务密钥时抛出。

源代码位于: feishu/gateway/auth.py
Python
class ServiceAuthError(Exception):
    r"""内部网关请求缺少有效服务密钥时抛出。"""

ServiceCapabilityError

Bases: Exception

已认证服务没有调用当前路由的能力时抛出。

源代码位于: feishu/gateway/auth.py
Python
class ServiceCapabilityError(Exception):
    r"""已认证服务没有调用当前路由的能力时抛出。"""

require_service

Python
require_service(request: Request, service_keys: Mapping[str, str]) -> str

校验 Authorization: Bearer <key> 并返回对应的服务名。

源代码位于: feishu/gateway/auth.py
Python
def require_service(request: Request, service_keys: Mapping[str, str]) -> str:
    r"""校验 ``Authorization: Bearer <key>`` 并返回对应的服务名。"""
    header = request.headers.get("authorization", "")
    prefix = "Bearer "
    if not header.startswith(prefix):
        raise ServiceAuthError("missing bearer token")
    token = header[len(prefix) :].strip()
    if not token:
        raise ServiceAuthError("missing bearer token")

    matched_service: str | None = None
    for expected_key, service_name in service_keys.items():
        if hmac.compare_digest(token, expected_key):
            matched_service = service_name

    if matched_service is None:
        raise ServiceAuthError("invalid bearer token")
    request.state.service = matched_service
    return matched_service

require_service_capability

Python
require_service_capability(request: Request, service_keys: Mapping[str, str], service_capabilities: Mapping[str, Collection[str]]) -> str

Validate a bearer key and, when configured, its route capability.

Empty capability configuration preserves the legacy authenticated gateway behavior. Once an ACL is configured, every service must have an explicit route capability and unmatched requests are denied.

源代码位于: feishu/gateway/auth.py
Python
def require_service_capability(
    request: Request,
    service_keys: Mapping[str, str],
    service_capabilities: Mapping[str, Collection[str]],
) -> str:
    r"""Validate a bearer key and, when configured, its route capability.

    Empty capability configuration preserves the legacy authenticated gateway
    behavior. Once an ACL is configured, every service must have an explicit
    route capability and unmatched requests are denied.
    """
    service = require_service(request, service_keys)
    if not service_capabilities:
        return service

    capabilities = service_capabilities.get(service)
    if capabilities is None or not any(_matches_capability(request.url.path, item) for item in capabilities):
        raise ServiceCapabilityError("service lacks required route capability")
    return service