feat: 添加飞书用户模块和订阅功能支持

- 新增feishu_users模块用于处理飞书用户身份验证和权限管理
- 新增subscriptions模块用于处理订阅相关功能
- 新增personalization模块用于个性化服务
- 在alembic迁移配置中注册新的模型模块
- 在API路由器中添加feishu_users和subscriptions路由
- 实现事件调度服务的改进,包括错误处理和状态更新优化
- 添加飞书命令处理的权限检查机制
- 实现飞书应用票据事件处理
- 改进审计日志记录功能
```
This commit is contained in:
2026-07-27 08:02:17 +08:00
parent db751f03b4
commit d7db84571d
148 changed files with 17110 additions and 765 deletions

View File

@@ -0,0 +1,63 @@
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.core.utils.time import utc_now
from app.modules.feishu.models import FeishuAppTicket
APP_TICKET_EVENT_TYPE = "app_ticket"
APP_TICKET_PAYLOAD_KEY = "app_ticket"
class FeishuAppTicketService:
"""Persist the latest ticket received through a verified Feishu event."""
def __init__(self, db: Session):
self.db = db
def get_ticket(self, app_id: str) -> str | None:
app_id_value = str(app_id).strip()
if not app_id_value:
return None
return self.db.scalar(
select(FeishuAppTicket.app_ticket).where(
FeishuAppTicket.app_id == app_id_value
)
)
def store_verified(self, app_id: str, ticket: str) -> FeishuAppTicket:
app_id_value = str(app_id).strip()
ticket_value = str(ticket).strip()
if not app_id_value or not ticket_value:
raise ValueError("Verified Feishu app ticket fields are required")
now = utc_now()
record = self.db.execute(
select(FeishuAppTicket)
.where(FeishuAppTicket.app_id == app_id_value)
.with_for_update()
).scalar_one_or_none()
if record is None:
record = FeishuAppTicket(
app_id=app_id_value,
app_ticket=ticket_value,
received_at=now,
updated_at=now,
)
try:
with self.db.begin_nested():
self.db.add(record)
self.db.flush()
except IntegrityError:
record = self.db.execute(
select(FeishuAppTicket)
.where(FeishuAppTicket.app_id == app_id_value)
.with_for_update()
).scalar_one()
record.app_ticket = ticket_value
record.received_at = now
record.updated_at = now
self.db.commit()
self.db.refresh(record)
return record

View File

@@ -1,67 +1,185 @@
import json
import time
from threading import RLock
from typing import Any
import httpx
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from app.core.constants import BEARER_TOKEN_TEMPLATE, HttpHeader
from app.core.config import get_settings
from app.core.constants import BEARER_TOKEN_TEMPLATE, HttpHeader
from app.modules.feishu.constants import (
FEISHU_APP_TICKET_MISSING,
FEISHU_APP_TOKEN_PATH,
FEISHU_AUTH_MISSING,
FEISHU_DEFAULT_TOKEN_EXPIRE_SECONDS,
FEISHU_MESSAGE_PATH,
FEISHU_IMAGE_PATH,
FEISHU_MESSAGE_PATH,
FEISHU_RECEIVE_ID_MISSING,
FEISHU_STORE_TENANT_TOKEN_PATH,
FEISHU_SUCCESS_CODE,
FEISHU_TENANT_KEY_MISSING,
FEISHU_TENANT_TOKEN_PATH,
FEISHU_TOKEN_EXPIRE_SAFETY_SECONDS,
FeishuAppType,
FeishuMessageType,
FeishuPayloadKey,
FeishuReceiveIdType,
)
from app.modules.feishu.errors import FeishuAPIError
_RETRYABLE_PROVIDER_CODES = frozenset(
{
99991400,
99991401,
99991402,
99991403,
}
)
_RETRYABLE_PROVIDER_TERMS = (
"rate limit",
"too many request",
"temporar",
"timeout",
"busy",
"限流",
"频率",
"超时",
"繁忙",
)
class FeishuClient:
"""Small Feishu Open Platform client for tenant token and message APIs."""
"""Small Feishu Open Platform client with tenant-isolated token caches."""
def __init__(self) -> None:
def __init__(self, db: Session | None = None) -> None:
self.settings = get_settings()
self.db = db
self._tenant_access_token: str | None = None
self._token_expires_at: float = 0
self._app_access_tokens: dict[str, tuple[str, float]] = {}
self._store_tenant_access_tokens: dict[tuple[str, str], tuple[str, float]] = {}
self._token_lock = RLock()
def _is_configured(self) -> bool:
return bool(self.settings.feishu_app_id and self.settings.feishu_app_secret)
def _get_tenant_access_token(self) -> str:
def _get_tenant_access_token(self, tenant_key: str | None = None) -> str:
if not self._is_configured():
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=FEISHU_AUTH_MISSING,
)
if self._tenant_access_token and time.time() < self._token_expires_at:
return self._tenant_access_token
if self.settings.feishu_app_type == FeishuAppType.STORE:
return self._get_store_tenant_access_token(tenant_key)
return self._get_self_tenant_access_token()
url = f"{self.settings.feishu_base_url}{FEISHU_TENANT_TOKEN_PATH}"
payload = {
FeishuPayloadKey.APP_ID: self.settings.feishu_app_id,
FeishuPayloadKey.APP_SECRET: self.settings.feishu_app_secret,
}
with httpx.Client(timeout=20) as client:
response = client.post(url, json=payload)
response.raise_for_status()
data = response.json()
if data.get(FeishuPayloadKey.CODE) != FEISHU_SUCCESS_CODE:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail={FeishuPayloadKey.FEISHU_ERROR: data},
def _get_self_tenant_access_token(self) -> str:
with self._token_lock:
if (
self._tenant_access_token
and time.time() < self._token_expires_at
):
return self._tenant_access_token
data = self._post(
f"{self.settings.feishu_base_url}{FEISHU_TENANT_TOKEN_PATH}",
operation="Feishu self tenant token request",
json={
FeishuPayloadKey.APP_ID: self.settings.feishu_app_id,
FeishuPayloadKey.APP_SECRET: self.settings.feishu_app_secret,
},
)
self._tenant_access_token = data[FeishuPayloadKey.TENANT_ACCESS_TOKEN]
expire_seconds = int(
data.get(FeishuPayloadKey.EXPIRE, FEISHU_DEFAULT_TOKEN_EXPIRE_SECONDS)
)
self._token_expires_at = time.time() + expire_seconds - FEISHU_TOKEN_EXPIRE_SAFETY_SECONDS
return self._tenant_access_token
token = self._required_token(
data,
FeishuPayloadKey.TENANT_ACCESS_TOKEN,
"Feishu self tenant token response",
)
self._tenant_access_token = token
self._token_expires_at = self._expires_at(data)
return token
def _get_store_app_access_token(self) -> str:
app_id = str(self.settings.feishu_app_id)
with self._token_lock:
cached = self._get_cached(self._app_access_tokens, app_id)
if cached is not None:
return cached
app_ticket = self._get_app_ticket(app_id)
data = self._post(
f"{self.settings.feishu_base_url}{FEISHU_APP_TOKEN_PATH}",
operation="Feishu store app token request",
json={
FeishuPayloadKey.APP_ID: app_id,
FeishuPayloadKey.APP_SECRET: self.settings.feishu_app_secret,
FeishuPayloadKey.APP_TICKET: app_ticket,
},
)
token = self._required_token(
data,
FeishuPayloadKey.APP_ACCESS_TOKEN,
"Feishu store app token response",
)
self._app_access_tokens[app_id] = (token, self._expires_at(data))
return token
def _get_store_tenant_access_token(self, tenant_key: str | None) -> str:
normalized_tenant_key = str(tenant_key or "").strip()
if not normalized_tenant_key:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=FEISHU_TENANT_KEY_MISSING,
)
app_id = str(self.settings.feishu_app_id)
cache_key = (app_id, normalized_tenant_key)
with self._token_lock:
cached = self._get_cached(
self._store_tenant_access_tokens,
cache_key,
)
if cached is not None:
return cached
app_access_token = self._get_store_app_access_token()
data = self._post(
f"{self.settings.feishu_base_url}{FEISHU_STORE_TENANT_TOKEN_PATH}",
operation="Feishu store tenant token request",
json={
FeishuPayloadKey.APP_ACCESS_TOKEN: app_access_token,
FeishuPayloadKey.TENANT_KEY: normalized_tenant_key,
},
)
token = self._required_token(
data,
FeishuPayloadKey.TENANT_ACCESS_TOKEN,
"Feishu store tenant token response",
)
self._store_tenant_access_tokens[cache_key] = (
token,
self._expires_at(data),
)
return token
def _get_app_ticket(self, app_id: str) -> str:
ticket: Any = None
if self.db is not None:
from app.modules.feishu.app_tickets import FeishuAppTicketService
ticket = FeishuAppTicketService(self.db).get_ticket(app_id)
if ticket is not None and not isinstance(ticket, str):
ticket = getattr(ticket, "app_ticket", None) or getattr(
ticket,
"ticket",
None,
)
normalized = str(ticket or "").strip()
if not normalized:
normalized = str(self.settings.feishu_app_ticket or "").strip()
if not normalized:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=FEISHU_APP_TICKET_MISSING,
)
return normalized
def send_message(
self,
@@ -69,77 +187,207 @@ class FeishuClient:
receive_id_type: str,
msg_type: str,
content: dict[str, Any],
uuid: str | None = None,
tenant_key: str | None = None,
) -> dict[str, Any]:
token = self._get_tenant_access_token()
url = f"{self.settings.feishu_base_url}{FEISHU_MESSAGE_PATH}"
token = self._get_tenant_access_token(tenant_key)
headers = {HttpHeader.AUTHORIZATION: BEARER_TOKEN_TEMPLATE.format(token=token)}
params = {FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type}
payload = {
FeishuPayloadKey.RECEIVE_ID: receive_id,
FeishuPayloadKey.MESSAGE_TYPE: msg_type,
FeishuPayloadKey.CONTENT: json.dumps(content, ensure_ascii=False),
}
with httpx.Client(timeout=20) as client:
response = client.post(url, headers=headers, params=params, json=payload)
response.raise_for_status()
data = response.json()
return data
if uuid:
payload[FeishuPayloadKey.UUID] = uuid
return self._post(
f"{self.settings.feishu_base_url}{FEISHU_MESSAGE_PATH}",
operation="Feishu message request",
headers=headers,
params={FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type},
json=payload,
)
def send_text(
self,
text: str,
receive_id: str | None = None,
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
) -> dict:
chat_id = receive_id or self.settings.feishu_default_chat_id
if not chat_id:
uuid: str | None = None,
tenant_key: str | None = None,
) -> dict[str, Any]:
target_id = receive_id or self.settings.feishu_default_chat_id
if not target_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=FEISHU_RECEIVE_ID_MISSING,
)
resolved_tenant_key = tenant_key
if receive_id is None and not resolved_tenant_key:
resolved_tenant_key = self.settings.feishu_default_tenant_key
return self.send_message(
chat_id,
target_id,
receive_id_type,
FeishuMessageType.TEXT,
{FeishuPayloadKey.TEXT: text},
uuid,
resolved_tenant_key,
)
def upload_image(
self,
image: bytes,
filename: str = "lifecycle-report.png",
tenant_key: str | None = None,
) -> dict[str, Any]:
token = self._get_tenant_access_token()
url = f"{self.settings.feishu_base_url}{FEISHU_IMAGE_PATH}"
resolved_tenant_key = tenant_key or self.settings.feishu_default_tenant_key
token = self._get_tenant_access_token(resolved_tenant_key)
headers = {HttpHeader.AUTHORIZATION: BEARER_TOKEN_TEMPLATE.format(token=token)}
with httpx.Client(timeout=30) as client:
response = client.post(
url,
headers=headers,
data={FeishuPayloadKey.IMAGE_TYPE: FeishuPayloadKey.MESSAGE},
files={
FeishuPayloadKey.IMAGE: (filename, image, "image/png"),
},
)
response.raise_for_status()
data = response.json()
if data.get(FeishuPayloadKey.CODE) != FEISHU_SUCCESS_CODE:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail={FeishuPayloadKey.FEISHU_ERROR: data},
)
return data
return self._post(
f"{self.settings.feishu_base_url}{FEISHU_IMAGE_PATH}",
operation="Feishu image upload request",
timeout=30,
headers=headers,
data={FeishuPayloadKey.IMAGE_TYPE: FeishuPayloadKey.MESSAGE},
files={
FeishuPayloadKey.IMAGE: (filename, image, "image/png"),
},
)
def send_card(
self,
card: dict[str, Any],
receive_id: str | None = None,
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
) -> dict:
chat_id = receive_id or self.settings.feishu_default_chat_id
if not chat_id:
uuid: str | None = None,
tenant_key: str | None = None,
) -> dict[str, Any]:
target_id = receive_id or self.settings.feishu_default_chat_id
if not target_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=FEISHU_RECEIVE_ID_MISSING,
)
return self.send_message(chat_id, receive_id_type, FeishuMessageType.INTERACTIVE, card)
resolved_tenant_key = tenant_key
if receive_id is None and not resolved_tenant_key:
resolved_tenant_key = self.settings.feishu_default_tenant_key
return self.send_message(
target_id,
receive_id_type,
FeishuMessageType.INTERACTIVE,
card,
uuid,
resolved_tenant_key,
)
def _post(
self,
url: str,
*,
operation: str,
timeout: int = 20,
**kwargs: Any,
) -> dict[str, Any]:
try:
with httpx.Client(timeout=timeout) as client:
response = client.post(url, **kwargs)
except httpx.HTTPError:
raise FeishuAPIError(
f"{operation} failed",
retryable=True,
) from None
if not status.HTTP_200_OK <= response.status_code < status.HTTP_300_MULTIPLE_CHOICES:
raise FeishuAPIError(
f"{operation} returned an HTTP error",
retryable=_is_retryable_http_status(response.status_code),
http_status=response.status_code,
)
try:
data = response.json()
except ValueError:
raise FeishuAPIError(
f"{operation} response was not valid JSON",
retryable=True,
http_status=response.status_code,
) from None
if not isinstance(data, dict):
raise FeishuAPIError(
f"{operation} response was not a JSON object",
retryable=True,
http_status=response.status_code,
)
provider_code = data.get(FeishuPayloadKey.CODE)
if provider_code != FEISHU_SUCCESS_CODE:
raise FeishuAPIError(
f"{operation} returned a non-zero business code",
retryable=_is_retryable_business_error(data),
http_status=response.status_code,
provider_code=provider_code,
provider_response={
FeishuPayloadKey.CODE: provider_code,
},
)
return data
@staticmethod
def _required_token(
data: dict[str, Any],
key: FeishuPayloadKey,
operation: str,
) -> str:
token = data.get(key)
if not isinstance(token, str) or not token.strip():
raise FeishuAPIError(
f"{operation} did not include the required credential",
retryable=True,
provider_code=data.get(FeishuPayloadKey.CODE),
provider_response={
FeishuPayloadKey.CODE: data.get(FeishuPayloadKey.CODE),
},
)
return token
@staticmethod
def _expires_at(data: dict[str, Any]) -> float:
try:
expire_seconds = int(
data.get(
FeishuPayloadKey.EXPIRE,
FEISHU_DEFAULT_TOKEN_EXPIRE_SECONDS,
)
)
except (TypeError, ValueError):
expire_seconds = FEISHU_DEFAULT_TOKEN_EXPIRE_SECONDS
usable_seconds = max(
1,
expire_seconds - FEISHU_TOKEN_EXPIRE_SAFETY_SECONDS,
)
return time.time() + usable_seconds
@staticmethod
def _get_cached(
cache: dict[Any, tuple[str, float]],
key: Any,
) -> str | None:
entry = cache.get(key)
if entry is None:
return None
token, expires_at = entry
if time.time() < expires_at:
return token
cache.pop(key, None)
return None
def _is_retryable_http_status(status_code: int) -> bool:
return (
status_code == status.HTTP_429_TOO_MANY_REQUESTS
or status_code >= status.HTTP_500_INTERNAL_SERVER_ERROR
)
def _is_retryable_business_error(data: dict[str, Any]) -> bool:
code = data.get(FeishuPayloadKey.CODE)
if code in _RETRYABLE_PROVIDER_CODES:
return True
message = str(data.get("msg") or "").casefold()
return any(term in message for term in _RETRYABLE_PROVIDER_TERMS)

View File

@@ -3,6 +3,12 @@ from enum import StrEnum
class FeishuReceiveIdType(StrEnum):
CHAT_ID = "chat_id"
OPEN_ID = "open_id"
class FeishuAppType(StrEnum):
SELF = "self"
STORE = "store"
class FeishuMessageType(StrEnum):
@@ -16,24 +22,30 @@ class FeishuEventSource(StrEnum):
class FeishuPayloadKey(StrEnum):
APP_ACCESS_TOKEN = "app_access_token"
APP_ID = "app_id"
APP_SECRET = "app_secret"
APP_TICKET = "app_ticket"
CARD = "card"
CHALLENGE = "challenge"
CHAT_TYPE = "chat_type"
CODE = "code"
CONFIG = "config"
CONTENT = "content"
DIV = "div"
DATA = "data"
ELEMENTS = "elements"
ENCRYPT = "encrypt"
EXPIRE = "expire"
FEISHU_ERROR = "feishu_error"
HEADER = "header"
IMAGE = "image"
IMAGE_KEY = "image_key"
IMAGE_TYPE = "image_type"
ID = "id"
IMG = "img"
IMG_KEY = "img_key"
KEY = "key"
ALT = "alt"
EVENT = "event"
EVENT_ID = "event_id"
@@ -42,6 +54,8 @@ class FeishuPayloadKey(StrEnum):
MESSAGE = "message"
MESSAGE_ID = "message_id"
MESSAGE_TYPE = "msg_type"
MENTIONS = "mentions"
NAME = "name"
OPEN_ID = "open_id"
PLAIN_TEXT = "plain_text"
RECEIVE_ID = "receive_id"
@@ -50,17 +64,23 @@ class FeishuPayloadKey(StrEnum):
SENDER_ID = "sender_id"
TAG = "tag"
TENANT_ACCESS_TOKEN = "tenant_access_token"
TENANT_KEY = "tenant_key"
TEXT = "text"
TITLE = "title"
TOKEN = "token"
UNION_ID = "union_id"
USER_ID = "user_id"
UUID = "uuid"
WIDE_SCREEN_MODE = "wide_screen_mode"
class FeishuCommandKey(StrEnum):
TEXT = "text"
CHAT_ID = "chat_id"
CHAT_TYPE = "chat_type"
ACTOR = "actor"
MENTIONS = "mentions"
PRINCIPAL = "principal"
class FeishuResponseKey(StrEnum):
@@ -85,10 +105,32 @@ class FeishuCommandResultKey(StrEnum):
class FeishuCommandName(StrEnum):
PERMISSION_DENIED = "permission_denied"
HELP = "help"
USER_SET_ADMIN = "user_set_admin"
USER_SET_USER = "user_set_user"
USER_DISABLE = "user_disable"
USER_ENABLE = "user_enable"
PREFERENCE_SET = "preference_set"
PREFERENCE_LIST = "preference_list"
PREFERENCE_DELETE = "preference_delete"
CONVERSATION_RESET = "conversation_reset"
PERSONAL_DATA_SUMMARY = "personal_data_summary"
PERSONAL_DATA_ERASURE_REQUEST = "personal_data_erasure_request"
PERSONAL_DATA_ERASURE_CONFIRM = "personal_data_erasure_confirm"
SUBSCRIPTION_CREATE = "subscription_create"
SUBSCRIPTION_LIST = "subscription_list"
SUBSCRIPTION_PAUSE = "subscription_pause"
SUBSCRIPTION_RESUME = "subscription_resume"
SUBSCRIPTION_CANCEL = "subscription_cancel"
SUBSCRIPTION_TIMEZONE = "subscription_timezone"
SUBSCRIPTION_QUIET_HOURS = "subscription_quiet_hours"
RULE_CREATE = "rule_create"
RULE_LIST = "rule_list"
RULE_DISABLE = "rule_disable"
RULE_ENABLE = "rule_enable"
RULE_UPDATE = "rule_update"
RULE_DELETE = "rule_delete"
FINANCE_NEEDS = "finance_needs"
PROJECT_FINANCE = "project_finance"
MARKET_OVERVIEW = "market_overview"
@@ -123,11 +165,15 @@ class FeishuCardKey(StrEnum):
VALUE = "value"
FEISHU_APP_TOKEN_PATH = "/auth/v3/app_access_token"
FEISHU_STORE_TENANT_TOKEN_PATH = "/auth/v3/tenant_access_token"
FEISHU_TENANT_TOKEN_PATH = "/auth/v3/tenant_access_token/internal"
FEISHU_MESSAGE_PATH = "/im/v1/messages"
FEISHU_IMAGE_PATH = "/im/v1/images"
FEISHU_DEFAULT_OPEN_API_DOMAIN = "https://open.feishu.cn"
FEISHU_AUTH_MISSING = "Feishu app credentials are not configured"
FEISHU_APP_TICKET_MISSING = "Feishu store app ticket is not available"
FEISHU_TENANT_KEY_MISSING = "tenant_key is required for Feishu store apps"
FEISHU_VERIFICATION_TOKEN_REQUIRED = "FEISHU_VERIFICATION_TOKEN is required"
FEISHU_INVALID_TOKEN = "Invalid Feishu token"
FEISHU_RECEIVE_ID_MISSING = "receive_id or FEISHU_DEFAULT_CHAT_ID is required"

View File

@@ -0,0 +1,29 @@
from typing import Any
from fastapi import HTTPException, status
class FeishuAPIError(HTTPException):
"""Normalized outbound Feishu failure with retry classification."""
def __init__(
self,
detail: str,
*,
retryable: bool,
http_status: int | None = None,
provider_code: int | str | None = None,
provider_response: dict[str, Any] | None = None,
) -> None:
super().__init__(
status_code=(
status.HTTP_503_SERVICE_UNAVAILABLE
if retryable
else status.HTTP_502_BAD_GATEWAY
),
detail=detail,
)
self.retryable = retryable
self.http_status = http_status
self.provider_code = provider_code
self.provider_response = provider_response or {}

View File

@@ -0,0 +1,131 @@
import base64
import json
import time
from hashlib import sha256
from secrets import compare_digest
from typing import Any, Mapping
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7
from fastapi import HTTPException, status
from app.core.config import get_settings
from app.modules.feishu.constants import FeishuPayloadKey
_SIGNATURE_MAX_AGE_SECONDS = 300
_SIGNATURE_HEADER = "x-lark-signature"
_TIMESTAMP_HEADER = "x-lark-request-timestamp"
_NONCE_HEADER = "x-lark-request-nonce"
class FeishuWebhookVerifier:
"""Verify, decrypt, and normalize an HTTP webhook before business handling."""
def verify(
self,
raw_body: bytes,
headers: Mapping[str, str],
) -> dict[str, Any]:
settings = get_settings()
if settings.feishu_encrypt_key:
self._verify_signature(raw_body, headers, settings.feishu_encrypt_key)
payload = self._load_json(raw_body)
if FeishuPayloadKey.ENCRYPT in payload:
if not settings.feishu_encrypt_key:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="FEISHU_ENCRYPT_KEY is required for encrypted webhooks",
)
payload = self._decrypt(
str(payload[FeishuPayloadKey.ENCRYPT]),
settings.feishu_encrypt_key,
)
self._verify_token(payload, settings.feishu_verification_token)
return payload
@staticmethod
def _load_json(raw_body: bytes) -> dict[str, Any]:
try:
payload = json.loads(raw_body)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid Feishu webhook JSON",
) from exc
if not isinstance(payload, dict):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid Feishu webhook payload",
)
return payload
@staticmethod
def _verify_signature(
raw_body: bytes,
headers: Mapping[str, str],
encrypt_key: str,
) -> None:
normalized = {str(key).lower(): str(value) for key, value in headers.items()}
timestamp = normalized.get(_TIMESTAMP_HEADER)
nonce = normalized.get(_NONCE_HEADER)
signature = normalized.get(_SIGNATURE_HEADER)
if not timestamp or not nonce or not signature:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing Feishu webhook signature headers",
)
try:
request_time = int(timestamp)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Feishu webhook timestamp",
) from exc
if abs(int(time.time()) - request_time) > _SIGNATURE_MAX_AGE_SECONDS:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Expired Feishu webhook signature",
)
signed = (
timestamp.encode("utf-8")
+ nonce.encode("utf-8")
+ encrypt_key.encode("utf-8")
+ raw_body
)
expected = sha256(signed).hexdigest()
if not compare_digest(signature, expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Feishu webhook signature",
)
@staticmethod
def _decrypt(encrypted: str, encrypt_key: str) -> dict[str, Any]:
try:
key = sha256(encrypt_key.encode("utf-8")).digest()
encrypted_bytes = base64.b64decode(encrypted, validate=True)
decryptor = Cipher(algorithms.AES(key), modes.CBC(key[:16])).decryptor()
padded = decryptor.update(encrypted_bytes) + decryptor.finalize()
unpadder = PKCS7(algorithms.AES.block_size).unpadder()
cleartext = unpadder.update(padded) + unpadder.finalize()
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid encrypted Feishu webhook",
) from exc
return FeishuWebhookVerifier._load_json(cleartext)
@staticmethod
def _verify_token(payload: dict[str, Any], expected: str | None) -> None:
if not expected:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="FEISHU_VERIFICATION_TOKEN is required",
)
header = payload.get(FeishuPayloadKey.HEADER) or {}
token = payload.get(FeishuPayloadKey.TOKEN) or header.get(FeishuPayloadKey.TOKEN)
if not token or not compare_digest(str(token), expected):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Feishu token",
)

View File

@@ -31,10 +31,18 @@ def _sdk_event_to_payload(event: Any) -> dict[str, Any]:
def _handle_message_event(event: Any) -> None:
_handle_verified_sdk_event(event)
def _handle_app_ticket_event(event: Any) -> None:
_handle_verified_sdk_event(event)
def _handle_verified_sdk_event(event: Any) -> None:
payload = _sdk_event_to_payload(event)
db = SessionLocal()
try:
result = FeishuEventService(db).handle_event(
result = FeishuEventService(db)._handle_verified_event(
payload,
source=FeishuEventSource.LONG_CONNECTION,
auto_reply=True,
@@ -62,6 +70,7 @@ def run_long_connection() -> None:
settings.feishu_verification_token or "",
)
.register_p2_im_message_receive_v1(_handle_message_event)
.register_p1_customized_event("app_ticket", _handle_app_ticket_event)
.build()
)
client = lark.ws.Client(

View File

@@ -1,6 +1,6 @@
from datetime import datetime
from sqlalchemy import DateTime, Integer, String
from sqlalchemy import DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.core.database import Base
@@ -16,3 +16,17 @@ class FeishuEventReceipt(Base):
event_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
message_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
received_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now, index=True)
class FeishuAppTicket(Base):
__tablename__ = "feishu_app_tickets"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
app_id: Mapped[str] = mapped_column(String(128), unique=True, index=True)
app_ticket: Mapped[str] = mapped_column(Text)
received_at: Mapped[datetime] = mapped_column(DateTime, default=utc_now, index=True)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=utc_now,
onupdate=utc_now,
)

View File

@@ -1,12 +1,11 @@
from typing import Any
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.security import ApiPrincipal, require_api_key
from app.application.feishu import FeishuCommandService, FeishuEventService
from app.modules.feishu.constants import FeishuEventSource, FeishuPayloadKey, FeishuResponseKey
from app.modules.feishu.event_verification import FeishuWebhookVerifier
from app.modules.feishu.schemas import (
FeishuCardMessage,
FeishuCommandRequest,
@@ -20,10 +19,11 @@ router = APIRouter()
@router.post("/webhook")
def feishu_webhook(payload: dict[str, Any], db: Session = Depends(get_db)) -> dict:
async def feishu_webhook(request: Request, db: Session = Depends(get_db)) -> dict:
"""Handle Feishu webhook challenge and text command events."""
return FeishuEventService(db).handle_event(
payload = FeishuWebhookVerifier().verify(await request.body(), request.headers)
return FeishuEventService(db)._handle_verified_event(
payload,
source=FeishuEventSource.WEBHOOK,
auto_reply=True,
@@ -41,6 +41,7 @@ def send_text(
receive_id=payload.receive_id,
receive_id_type=payload.receive_id_type,
actor=principal.actor,
tenant_key=payload.tenant_key,
)
return {
FeishuResponseKey.OK: result.get(FeishuPayloadKey.CODE) == 0,
@@ -59,6 +60,7 @@ def send_card(
receive_id=payload.receive_id,
receive_id_type=payload.receive_id_type,
actor=principal.actor,
tenant_key=payload.tenant_key,
)
return {
FeishuResponseKey.OK: result.get(FeishuPayloadKey.CODE) == 0,
@@ -82,4 +84,5 @@ def preview_command(
chat_id=payload.chat_id,
actor=principal.actor,
auto_reply=payload.auto_reply,
tenant_key=payload.tenant_key,
)

View File

@@ -12,12 +12,14 @@ class FeishuTextMessage(BaseModel):
description="chat_id or open_id depending on type.",
)
receive_id_type: str = FeishuReceiveIdType.CHAT_ID
tenant_key: str | None = Field(default=None, max_length=128)
text: str
class FeishuCardMessage(BaseModel):
receive_id: str | None = None
receive_id_type: str = FeishuReceiveIdType.CHAT_ID
tenant_key: str | None = Field(default=None, max_length=128)
card: dict[str, Any]
@@ -38,6 +40,7 @@ class FeishuSendResult(BaseModel):
class FeishuCommandRequest(BaseModel):
text: str
chat_id: str | None = None
tenant_key: str | None = Field(default=None, max_length=128)
actor: str = ActorValue.API
auto_reply: bool = False

View File

@@ -1,3 +1,4 @@
from hashlib import sha256
from secrets import compare_digest
from typing import Any
@@ -22,10 +23,18 @@ from app.modules.feishu.constants import (
class FeishuService:
"""Send Feishu messages and record audit entries for outbound actions."""
def __init__(self, db: Session):
def __init__(self, db: Session, tenant_key: str | None = None):
self.db = db
self.audit = AuditService(db)
self.client = FeishuClient()
self.client = FeishuClient(db)
self.tenant_key = _optional_text(tenant_key) or _optional_text(
get_settings().feishu_default_tenant_key
)
def set_tenant_key(self, tenant_key: str | None) -> None:
"""Set the default tenant used by subsequent outbound operations."""
self.tenant_key = _optional_text(tenant_key)
def verify_event(self, payload: dict[str, Any]) -> None:
settings = get_settings()
@@ -49,21 +58,32 @@ class FeishuService:
receive_id: str | None = None,
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
actor: str = ActorValue.SYSTEM,
uuid: str | None = None,
tenant_key: str | None = None,
record_audit: bool = True,
) -> dict[str, Any]:
result = self.client.send_text(text, receive_id, receive_id_type)
self.audit.log(
AuditLogCreate(
actor=actor,
source=AuditSource.FEISHU,
action=AuditAction.FEISHU_SEND_TEXT,
request_payload={
FeishuPayloadKey.RECEIVE_ID: receive_id,
FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type,
FeishuPayloadKey.TEXT: text,
},
response_payload=result,
)
result = self.client.send_text(
text,
receive_id,
receive_id_type,
uuid,
tenant_key=self._resolve_tenant_key(tenant_key),
)
if record_audit:
self.audit.log(
AuditLogCreate(
actor=actor,
source=AuditSource.FEISHU,
action=AuditAction.FEISHU_SEND_TEXT,
request_payload={
"receive_target_hash": _target_fingerprint(receive_id),
FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type,
"content_length": len(text),
FeishuPayloadKey.UUID: uuid,
},
response_payload=result,
)
)
return result
def send_card(
@@ -72,17 +92,26 @@ class FeishuService:
receive_id: str | None = None,
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
actor: str = ActorValue.SYSTEM,
uuid: str | None = None,
tenant_key: str | None = None,
) -> dict[str, Any]:
result = self.client.send_card(card, receive_id, receive_id_type)
result = self.client.send_card(
card,
receive_id,
receive_id_type,
uuid,
tenant_key=self._resolve_tenant_key(tenant_key),
)
self.audit.log(
AuditLogCreate(
actor=actor,
source=AuditSource.FEISHU,
action=AuditAction.FEISHU_SEND_CARD,
request_payload={
FeishuPayloadKey.RECEIVE_ID: receive_id,
"receive_target_hash": _target_fingerprint(receive_id),
FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type,
FeishuPayloadKey.CARD: card,
"card_element_count": len(card.get(FeishuPayloadKey.ELEMENTS) or []),
FeishuPayloadKey.UUID: uuid,
},
response_payload=result,
)
@@ -93,8 +122,12 @@ class FeishuService:
self,
image: bytes,
actor: str = ActorValue.SYSTEM,
tenant_key: str | None = None,
) -> dict[str, Any]:
result = self.client.upload_image(image)
result = self.client.upload_image(
image,
tenant_key=self._resolve_tenant_key(tenant_key),
)
self.audit.log(
AuditLogCreate(
actor=actor,
@@ -106,6 +139,9 @@ class FeishuService:
)
return result
def _resolve_tenant_key(self, tenant_key: str | None) -> str | None:
return _optional_text(tenant_key) or self.tenant_key
@staticmethod
def build_basic_card(
title: str,
@@ -144,3 +180,14 @@ class FeishuService:
},
FeishuPayloadKey.ELEMENTS: elements,
}
def _target_fingerprint(receive_id: str | None) -> str | None:
if not receive_id:
return None
return sha256(receive_id.encode("utf-8")).hexdigest()[:16]
def _optional_text(value: str | None) -> str | None:
text = str(value or "").strip()
return text or None