Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

14.6 KB
Raw Blame
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
"""Feishu user-token state for watch tasks."""

from __future__ import annotations

import asyncio
import os
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, Optional

import httpx
from lark_oapi.core.cache import ICache

from openviking.parse.accessors.feishu_token import (
    resolve_feishu_tenant_token_cache,
)
from openviking_cli.utils.config.parser_config import FeishuConfig

FEISHU_AUTH_PROVIDER = "feishu"
FEISHU_ACCESS_TOKEN_ARG = "feishu_access_token"
FEISHU_REFRESH_TOKEN_ARG = "feishu_refresh_token"
FEISHU_APP_ID_ARG = "feishu_app_id"
FEISHU_APP_SECRET_ARG = "feishu_app_secret"
FEISHU_REFRESH_GRANT_TYPE = "refresh_token"
FEISHU_REFRESH_SKEW = timedelta(minutes=5)
FEISHU_OAUTH_TOKEN_URL = "https://accounts.feishu.cn/oauth/v3/token"
LARK_OAUTH_TOKEN_URL = "https://accounts.larksuite.com/oauth/v3/token"


@dataclass(frozen=True)
class FeishuAppCredentials:
    app_id: str
    app_secret: str
    domain: str
    request_timeout: float


@dataclass(frozen=True)
class FeishuRefreshedToken:
    access_token: str
    refresh_token: str
    expires_in: int


class FeishuTokenRefreshError(Exception):
    """Raised when a Feishu user token refresh fails."""

    def __init__(self, message: str, *, permanent: bool = False):
        super().__init__(message)
        self.permanent = permanent


class FeishuTenantTokenError(Exception):
    """Raised when an app credential cannot produce a tenant token."""


def load_feishu_app_credentials(
    *,
    config=None,
    app_id: Optional[str] = None,
    app_secret: Optional[str] = None,
) -> FeishuAppCredentials:
    """Load Feishu app credentials from OpenViking config or environment."""
    if config is None:
        raise ValueError("Feishu credentials require explicit account configuration")
    if app_id is None and app_secret is None:
        resolved_app_id = (config.app_id or os.getenv("FEISHU_APP_ID", "")).strip()
        resolved_app_secret = (config.app_secret or os.getenv("FEISHU_APP_SECRET", "")).strip()
    else:
        resolved_app_id = app_id.strip() if isinstance(app_id, str) else ""
        resolved_app_secret = app_secret.strip() if isinstance(app_secret, str) else ""
    if not resolved_app_id or not resolved_app_secret:
        raise ValueError(
            "Feishu credentials not configured. Set FEISHU_APP_ID and "
            "FEISHU_APP_SECRET environment variables, or configure in ov.conf."
        )
    return FeishuAppCredentials(
        app_id=resolved_app_id,
        app_secret=resolved_app_secret,
        domain=(config.domain or "https://open.feishu.cn").strip(),
        request_timeout=float(config.request_timeout or 30.0),
    )


def create_feishu_auth_state(
    access_token: str,
    refresh_token: str,
    app_credentials: Optional[FeishuAppCredentials] = None,
    *,
    persist_app_secret: bool = True,
) -> Dict[str, Any]:
    """Create the private watch auth state for Feishu user-token watch tasks."""
    state = {
        "provider": FEISHU_AUTH_PROVIDER,
        "access_token": access_token,
        "refresh_token": refresh_token,
        "expires_at": None,
    }
    if app_credentials is not None:
        state["app_id"] = app_credentials.app_id
        if persist_app_secret:
            state["app_secret"] = app_credentials.app_secret
    return state


def is_feishu_auth_state(auth_state: Optional[Dict[str, Any]]) -> bool:
    return isinstance(auth_state, dict) and auth_state.get("provider") == FEISHU_AUTH_PROVIDER


def feishu_config_from_auth_state(
    auth_state: Dict[str, Any], current: FeishuConfig
) -> FeishuConfig:
    """Bind a watch execution to the app identity stored at creation.

    Non-identity parsing options keep their current account values. Legacy
    states without a complete app identity retain current-account fallback.
    """
    update: Dict[str, Any] = {}
    for key in ("app_id", "app_secret"):
        value = auth_state.get(key)
        if value is not None:
            update[key] = value
    return replace(current, **update)


def feishu_auth_state_needs_refresh(
    auth_state: Dict[str, Any],
    *,
    now: Optional[datetime] = None,
) -> bool:
    expires_at = auth_state.get("expires_at")
    if not expires_at:
        return True

    parsed = _parse_expires_at(expires_at)
    if parsed is None:
        return True

    current = now or datetime.now(timezone.utc)
    if current.tzinfo is None:
        current = current.replace(tzinfo=timezone.utc)
    return parsed <= current + FEISHU_REFRESH_SKEW


def apply_feishu_refreshed_token(
    auth_state: Dict[str, Any],
    refreshed: FeishuRefreshedToken,
    *,
    now: Optional[datetime] = None,
) -> Dict[str, Any]:
    current = now or datetime.now(timezone.utc)
    if current.tzinfo is None:
        current = current.replace(tzinfo=timezone.utc)
    expires_at = current + timedelta(seconds=max(0, int(refreshed.expires_in)))
    return {
        **auth_state,
        "provider": FEISHU_AUTH_PROVIDER,
        "access_token": refreshed.access_token,
        "refresh_token": refreshed.refresh_token,
        "expires_at": expires_at.isoformat(),
    }


class FeishuOAuthClient:
    """Small wrapper around Feishu/Lark user and tenant token operations."""

    def __init__(
        self,
        credentials: FeishuAppCredentials,
        *,
        tenant_token_cache: ICache | None = None,
    ):
        self._credentials = credentials
        self._tenant_token_cache = resolve_feishu_tenant_token_cache(tenant_token_cache)
        self._client = None

    @classmethod
    def from_config(
        cls,
        config,
        *,
        tenant_token_cache: ICache | None = None,
    ) -> "FeishuOAuthClient":
        return cls(
            load_feishu_app_credentials(config=config),
            tenant_token_cache=tenant_token_cache,
        )

    @classmethod
    def from_auth_state(
        cls,
        auth_state: Dict[str, Any],
        *,
        config,
        tenant_token_cache: ICache | None = None,
    ) -> "FeishuOAuthClient":
        try:
            bound = feishu_config_from_auth_state(auth_state, config)
            credentials = load_feishu_app_credentials(config=bound)
        except ValueError as exc:
            raise FeishuTokenRefreshError(
                "Feishu app credentials in watch task are invalid.",
                permanent=True,
            ) from exc
        return cls(credentials, tenant_token_cache=tenant_token_cache)

    async def get_tenant_access_token(self) -> str:
        return await asyncio.to_thread(self._get_tenant_access_token_sync)

    def _get_tenant_access_token_sync(self) -> str:
        try:
            from lark_oapi.core.model import Config
            from lark_oapi.core.token import TokenManager
        except ImportError as exc:
            raise FeishuTenantTokenError(
                "lark-oapi is required to obtain a Feishu tenant token. "
                "Install it with: pip install lark-oapi>=1.0.0"
            ) from exc

        config = Config()
        config.app_id = self._credentials.app_id
        config.app_secret = self._credentials.app_secret
        config.domain = self._credentials.domain
        config.timeout = self._credentials.request_timeout
        try:
            with self._tenant_token_cache.sdk_scope(
                app_id=self._credentials.app_id,
                app_secret=self._credentials.app_secret,
                domain=self._credentials.domain,
            ):
                token = TokenManager.get_self_tenant_token(config)
        except Exception as exc:
            raise FeishuTenantTokenError("Failed to obtain Feishu tenant token.") from exc
        if not isinstance(token, str) or not token.strip():
            raise FeishuTenantTokenError("Feishu tenant token response is empty.")
        return token.strip()

    async def refresh_user_access_token(self, refresh_token: str) -> FeishuRefreshedToken:
        if not isinstance(refresh_token, str) or not refresh_token.strip():
            raise FeishuTokenRefreshError(
                "Feishu refresh token is missing for watch task.",
                permanent=True,
            )
        return await asyncio.to_thread(self._refresh_user_access_token_sync, refresh_token.strip())

    def _refresh_user_access_token_sync(self, refresh_token: str) -> FeishuRefreshedToken:
        if refresh_token.count(".") != 2:
            return self._refresh_legacy_user_access_token_sync(refresh_token)

        try:
            response = httpx.post(
                (
                    LARK_OAUTH_TOKEN_URL
                    if "larksuite.com" in self._credentials.domain.lower()
                    else FEISHU_OAUTH_TOKEN_URL
                ),
                data={
                    "grant_type": FEISHU_REFRESH_GRANT_TYPE,
                    "client_id": self._credentials.app_id,
                    "client_secret": self._credentials.app_secret,
                    "refresh_token": refresh_token,
                },
                timeout=self._credentials.request_timeout,
            )
            payload = response.json()
        except Exception as exc:
            raise FeishuTokenRefreshError(
                f"Failed to refresh Feishu user token: {exc}",
                permanent=False,
            ) from exc

        if not isinstance(payload, dict):
            raise FeishuTokenRefreshError(
                "Feishu user token refresh response is not an object.",
                permanent=False,
            )

        code = payload.get("code")
        if response.status_code >= 400 or payload.get("error") or code not in (None, 0):
            error = payload.get("error")
            msg = str(
                payload.get("error_description")
                or payload.get("msg")
                or payload.get("message")
                or error
                or f"HTTP {response.status_code}"
            )
            raise FeishuTokenRefreshError(
                f"Feishu user token refresh failed: code={code}, msg={msg}",
                permanent=_is_permanent_refresh_error(code, f"{error or ''} {msg}"),
            )

        access_token = payload.get("access_token")
        new_refresh_token = payload.get("refresh_token")
        expires_in = payload.get("expires_in")
        access_token = access_token.strip() if isinstance(access_token, str) else ""
        new_refresh_token = new_refresh_token.strip() if isinstance(new_refresh_token, str) else ""
        if not access_token or not new_refresh_token or not isinstance(expires_in, int):
            raise FeishuTokenRefreshError(
                "Feishu user token refresh response is missing access_token, "
                "refresh_token, or expires_in.",
                permanent=False,
            )

        return FeishuRefreshedToken(
            access_token=access_token,
            refresh_token=new_refresh_token,
            expires_in=expires_in,
        )

    def _refresh_legacy_user_access_token_sync(self, refresh_token: str) -> FeishuRefreshedToken:
        try:
            from lark_oapi.api.authen.v1 import (
                CreateRefreshAccessTokenRequest,
                CreateRefreshAccessTokenRequestBody,
            )
        except ImportError as exc:
            raise FeishuTokenRefreshError(
                "lark-oapi is required to refresh legacy Feishu user tokens. "
                "Install it with: pip install lark-oapi>=1.0.0",
                permanent=True,
            ) from exc

        request = (
            CreateRefreshAccessTokenRequest.builder()
            .request_body(
                CreateRefreshAccessTokenRequestBody.builder()
                .grant_type(FEISHU_REFRESH_GRANT_TYPE)
                .refresh_token(refresh_token)
                .build()
            )
            .build()
        )
        try:
            response = self._get_client().authen.v1.refresh_access_token.create(request)
        except FeishuTokenRefreshError:
            raise
        except Exception as exc:
            raise FeishuTokenRefreshError(
                f"Failed to refresh Feishu user token: {exc}",
                permanent=False,
            ) from exc

        if not response.success():
            code = getattr(response, "code", None)
            msg = getattr(response, "msg", "") or ""
            raise FeishuTokenRefreshError(
                f"Feishu user token refresh failed: code={code}, msg={msg}",
                permanent=_is_permanent_refresh_error(code, msg),
            )

        data = getattr(response, "data", None)
        access_token = (getattr(data, "access_token", None) or "").strip()
        new_refresh_token = (getattr(data, "refresh_token", None) or "").strip()
        expires_in = getattr(data, "expires_in", None)
        if not access_token or not new_refresh_token or not isinstance(expires_in, int):
            raise FeishuTokenRefreshError(
                "Feishu user token refresh response is missing access_token, "
                "refresh_token, or expires_in.",
                permanent=False,
            )

        return FeishuRefreshedToken(
            access_token=access_token,
            refresh_token=new_refresh_token,
            expires_in=expires_in,
        )

    def _get_client(self):
        if self._client is None:
            try:
                import lark_oapi as lark
            except ImportError as exc:
                raise FeishuTokenRefreshError(
                    "lark-oapi is required to refresh legacy Feishu user tokens. "
                    "Install it with: pip install lark-oapi>=1.0.0",
                    permanent=True,
                ) from exc

            self._client = (
                lark.Client.builder()
                .app_id(self._credentials.app_id)
                .app_secret(self._credentials.app_secret)
                .domain(self._credentials.domain)
                .timeout(self._credentials.request_timeout)
                .build()
            )
        return self._client


def _parse_expires_at(value: Any) -> Optional[datetime]:
    if not isinstance(value, str) or not value.strip():
        return None
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        return None
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    return parsed


def _is_permanent_refresh_error(code: Any, msg: str) -> bool:
    text = f"{code or ''} {msg or ''}".lower()
    permanent_terms = (
        "invalid",
        "expired",
        "revoked",
        "unauthorized",
        "not exist",
        "not found",
        "mismatch",
        "refresh token",
        "refresh_token",
    )
    return any(term in text for term in permanent_terms)