feat(frontend): add API integration playground

This commit is contained in:
wizardchen
2026-06-30 21:14:06 +08:00
committed by lyingbug
parent a24567a951
commit ee1014f87c
10 changed files with 1186 additions and 136 deletions
+38
View File
@@ -245,6 +245,7 @@ type APIPrincipalConfig struct {
SignedTokenHeaderName string `json:"signed_token_header_name"`
RequireDirectHeader bool `json:"require_direct_header"`
HasHMACSecret bool `json:"has_hmac_secret"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
type apiPrincipalConfigResponse struct {
@@ -261,6 +262,26 @@ type UpdateAPIPrincipalConfigRequest struct {
HMACSecret string `json:"hmac_secret,omitempty"`
}
// CreateAPIPrincipalTestTokenRequest signs a short-lived JWT for API integration testing.
type CreateAPIPrincipalTestTokenRequest struct {
ExternalUserID string `json:"external_user_id"`
ExpiresInSeconds int `json:"expires_in_seconds,omitempty"`
}
// APIPrincipalTestToken is a short-lived JWT signed with the tenant API principal HMAC secret.
type APIPrincipalTestToken struct {
Token string `json:"token"`
HeaderName string `json:"header_name"`
ExpiresInSeconds int `json:"expires_in_seconds"`
ExpiresAtUnix int64 `json:"expires_at_unix"`
ExternalUserID string `json:"external_user_id"`
}
type apiPrincipalTestTokenResponse struct {
Success bool `json:"success"`
Data APIPrincipalTestToken `json:"data"`
}
// GetAPIPrincipalConfig returns how X-API-Key requests map to principals for a tenant.
func (c *Client) GetAPIPrincipalConfig(ctx context.Context, tenantID uint64) (*APIPrincipalConfig, error) {
path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-config", tenantID)
@@ -292,3 +313,20 @@ func (c *Client) UpdateAPIPrincipalConfig(
}
return &response.Data, nil
}
// CreateAPIPrincipalTestToken signs a short-lived JWT with the tenant API principal HMAC secret.
func (c *Client) CreateAPIPrincipalTestToken(
ctx context.Context, tenantID uint64, req *CreateAPIPrincipalTestTokenRequest,
) (*APIPrincipalTestToken, error) {
path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-test-token", tenantID)
resp, err := c.doRequest(ctx, http.MethodPost, path, req, nil)
if err != nil {
return nil, err
}
var response apiPrincipalTestTokenResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
+29
View File
@@ -25,6 +25,7 @@ export interface APIPrincipalConfig {
signed_token_header_name: string
require_direct_header: boolean
has_hmac_secret: boolean
hmac_secret?: string
}
export interface UpdateAPIPrincipalConfigPayload {
@@ -35,6 +36,19 @@ export interface UpdateAPIPrincipalConfigPayload {
hmac_secret?: string
}
export interface CreateAPIPrincipalTestTokenPayload {
external_user_id: string
expires_in_seconds?: number
}
export interface APIPrincipalTestToken {
token: string
header_name: string
expires_in_seconds: number
expires_at_unix: number
external_user_id: string
}
// 搜索租户参数
export interface SearchTenantsParams {
keyword?: string
@@ -117,6 +131,21 @@ export async function updateAPIPrincipalConfig(
}
}
export async function createAPIPrincipalTestToken(
tenantId: number,
payload: CreateAPIPrincipalTestTokenPayload,
): Promise<{ success: boolean; data?: APIPrincipalTestToken; message?: string }> {
try {
const response = await post(`/api/v1/tenants/${tenantId}/api-principal-test-token`, payload)
return response as unknown as { success: boolean; data?: APIPrincipalTestToken; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.createApiPrincipalTestTokenFailed'),
}
}
}
/**
* 更新租户信息(目前暴露名称、描述两个字段的编辑入口)。
* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会
+44 -1
View File
@@ -3637,6 +3637,7 @@ export default {
resetApiKeyFailed: 'Failed to reset API Key',
getApiPrincipalConfigFailed: 'Failed to get API principal config',
updateApiPrincipalConfigFailed: 'Failed to update API principal config',
createApiPrincipalTestTokenFailed: 'Failed to create API test token',
updateFailed: 'Failed to update tenant information',
deleteFailed: 'Failed to delete tenant',
},
@@ -5774,11 +5775,15 @@ export default {
requireDirectHeaderDesc:
'When enabled, API Key requests without the user ID header are rejected; when disabled, all requests are treated as the whole tenant with no per-user distinction.',
tokenHeader: 'Token header',
tokenHeaderDesc: 'Clients send the backend-signed JWT; header name is configurable.',
tokenHeaderDesc: 'Clients send the backend-signed JWT in this fixed header.',
hmacSecret: 'HMAC secret',
hmacSecretDesc: 'Same secret stored in WeKnora; used only on your backend to sign JWTs—never send it as a request header.',
secretConfigured: 'Secret configured; enter a new value to rotate',
generateSecret: 'Generate secret',
hmacSecretResetConfirmTitle: 'Reset HMAC secret?',
hmacSecretResetConfirmBody: 'After reset, the old HMAC secret is revoked immediately. Every backend service signing JWTs with the old secret must switch to the new secret to keep signed-token calls working. This action cannot be undone.',
hmacSecretResetConfirmOk: 'Reset',
hmacSecretResetConfirmCancel: 'Cancel',
tokenSignExample: 'Backend JWT signing example (Go)',
signedRequestStep0:
'# 0. Sign JWT on your backend (HS256, aud=weknora, sub=user id, tenant_id={tenantId}, exp<=24h)',
@@ -5787,9 +5792,47 @@ export default {
requestExampleAgentChat: '# 2. Agent chat (SSE; replace <session_id> with the id from step 1)',
requestExampleJwtPlaceholder: '<JWT signed by your backend>',
requestExample: 'Request example',
playgroundTitle: 'API Playground',
playgroundDesc: 'Send real requests with the current API key and identity mode to verify session creation, agent chat, and SSE output.',
playgroundOpen: 'Open Playground',
playgroundDrawerDesc: 'Debug sessions, Agent Chat, and SSE output using the real API integration flow',
playgroundBadge: 'Real request',
playgroundSectionRequest: 'Request setup',
playgroundSectionPreview: 'Request preview',
playgroundSectionResult: 'Run result',
playgroundAgent: 'Test agent',
playgroundAgentPlaceholder: 'Select an agent to test',
playgroundBuiltin: 'Built-in',
playgroundAgentsLoadFailed: 'Failed to load agents',
playgroundExternalUser: 'External user ID',
playgroundExternalUserPlaceholder: 'user_123',
playgroundTenantModeHint: 'Tenant-only mode does not send an external user identity; all API sessions use the same tenant-level principal.',
playgroundDirectModeHint: 'This user ID is sent with the {headerName} header.',
playgroundSignedModeHint: 'Signed-token mode uses the JWT sub as the external user. The playground signs a short-lived test JWT for this user ID.',
playgroundQuestion: 'Test question',
playgroundQuestionPlaceholder: 'Enter a question to send to the agent',
playgroundRequestPreview: 'Request preview (secrets masked)',
playgroundRun: 'Run test',
playgroundStop: 'Stop',
playgroundNeedApiKey: 'This tenant has no API key.',
playgroundNeedAgent: 'Select a test agent.',
playgroundNeedQuestion: 'Enter a test question.',
playgroundNeedExternalUser: 'Enter an external user ID.',
playgroundMintTokenFailed: 'Failed to create a short-lived test JWT.',
playgroundMissingSessionId: 'Session creation succeeded, but the response did not include a session id.',
playgroundNoStream: 'The chat API did not return a readable SSE stream.',
playgroundGeneratedToken: 'Generated test token',
playgroundStepSession: 'Step 1: Create Session',
playgroundStepChat: 'Step 2: Agent Chat SSE',
playgroundFinalAnswer: 'Extracted answer',
playgroundEmptyResult: 'Run a test to show the session response, raw SSE output, and extracted answer here.',
playgroundSuccess: 'Test completed ({ms}ms)',
playgroundStopped: 'Test stopped',
playgroundFailed: 'API Playground test failed',
loadFailed: 'Failed to load API integration settings',
saveFailed: 'Failed to save API integration settings',
saveSuccess: 'API integration settings saved',
autoSaveNeedSecret: 'Signed-token mode needs an HMAC secret before auto-save can run.',
},
manageSectionTitle: 'Channel configuration',
manageSectionDesc: 'Select an agent to create or edit integration channels for that agent',
+44 -1
View File
@@ -2645,6 +2645,7 @@ export default {
resetApiKeyFailed: 'API 키 재설정 실패',
getApiPrincipalConfigFailed: 'API principal config 조회 실패',
updateApiPrincipalConfigFailed: 'API principal config 업데이트 실패',
createApiPrincipalTestTokenFailed: 'API 테스트 토큰 생성 실패',
updateFailed: '테넌트 정보 업데이트 실패',
},
initialization: {
@@ -5785,11 +5786,15 @@ export default {
requireDirectHeaderDesc:
"켜면 사용자 ID 헤더가 없는 API Key 요청을 거부하고, 끄면 테넌트 전체로 통일 처리하며 개별 사용자를 구분하지 않습니다.",
tokenHeader: "토큰 헤더",
tokenHeaderDesc: "클라이언트는 백엔드가 서명한 JWT를 전달합니다. 헤더 이름은 변경할 수 있습니다.",
tokenHeaderDesc: "클라이언트는 이 고정 헤더에 백엔드가 서명한 JWT를 전달합니다.",
hmacSecret: "HMAC secret",
hmacSecretDesc: "WeKnora에 저장된 것과 동일한 secret. 백엔드에서 JWT 서명에만 사용하며 요청 헤더로 보내지 않습니다.",
secretConfigured: "Secret configured; enter a new value to rotate",
generateSecret: "Secret 생성",
hmacSecretResetConfirmTitle: "HMAC secret을 재설정할까요?",
hmacSecretResetConfirmBody: "재설정하면 기존 HMAC secret은 즉시 무효화됩니다. 기존 secret으로 JWT를 서명하는 모든 백엔드 서비스는 새 secret으로 교체해야 서명 토큰 호출을 계속 사용할 수 있습니다. 이 작업은 되돌릴 수 없습니다.",
hmacSecretResetConfirmOk: "재설정",
hmacSecretResetConfirmCancel: "취소",
tokenSignExample: "백엔드 JWT 서명 예시 (Go)",
signedRequestStep0:
"# 0. 백엔드에서 JWT 서명 (HS256, aud=weknora, sub=사용자 ID, tenant_id={tenantId}, exp 최대 24시간)",
@@ -5798,9 +5803,47 @@ export default {
requestExampleAgentChat: "# 2. Agent 대화 (SSE; <session_id>를 1단계 id로 교체)",
requestExampleJwtPlaceholder: "<백엔드가 서명한 JWT>",
requestExample: "요청 예시",
playgroundTitle: "API Playground",
playgroundDesc: "현재 API Key와 사용자 ID 모드로 실제 요청을 보내 세션 생성, Agent 대화, SSE 출력을 확인합니다.",
playgroundOpen: "Playground 열기",
playgroundDrawerDesc: "실제 API 연동 흐름으로 Session, Agent Chat, SSE 출력을 디버그합니다",
playgroundBadge: "실제 요청",
playgroundSectionRequest: "요청 설정",
playgroundSectionPreview: "요청 미리보기",
playgroundSectionResult: "실행 결과",
playgroundAgent: "테스트 Agent",
playgroundAgentPlaceholder: "테스트할 Agent 선택",
playgroundBuiltin: "기본 제공",
playgroundAgentsLoadFailed: "Agent 목록을 불러오지 못했습니다",
playgroundExternalUser: "외부 사용자 ID",
playgroundExternalUserPlaceholder: "user_123",
playgroundTenantModeHint: "테넌트 전용 모드는 외부 사용자 ID를 보내지 않으며 모든 API 세션이 동일한 테넌트 주체에 속합니다.",
playgroundDirectModeHint: "{headerName} 헤더로 이 사용자 ID를 보냅니다.",
playgroundSignedModeHint: "서명 토큰 모드는 JWT sub를 외부 사용자로 사용합니다. Playground가 이 사용자 ID로 단기 테스트 JWT를 자동 서명합니다.",
playgroundQuestion: "테스트 질문",
playgroundQuestionPlaceholder: "Agent에게 보낼 질문을 입력하세요",
playgroundRequestPreview: "요청 미리보기(secret 마스킹됨)",
playgroundRun: "테스트 실행",
playgroundStop: "중지",
playgroundNeedApiKey: "현재 테넌트에 API Key가 없습니다.",
playgroundNeedAgent: "테스트 Agent를 선택하세요.",
playgroundNeedQuestion: "테스트 질문을 입력하세요.",
playgroundNeedExternalUser: "외부 사용자 ID를 입력하세요.",
playgroundMintTokenFailed: "단기 테스트 JWT 생성 실패.",
playgroundMissingSessionId: "세션 생성은 성공했지만 응답에 session id가 없습니다.",
playgroundNoStream: "대화 API가 읽을 수 있는 SSE 스트림을 반환하지 않았습니다.",
playgroundGeneratedToken: "이번에 생성된 테스트 토큰",
playgroundStepSession: "1단계: Session 생성",
playgroundStepChat: "2단계: Agent Chat SSE",
playgroundFinalAnswer: "추출된 답변",
playgroundEmptyResult: "테스트를 실행하면 Session 응답, 원시 SSE 출력, 추출된 답변이 여기에 표시됩니다.",
playgroundSuccess: "테스트 완료({ms}ms)",
playgroundStopped: "테스트가 중지되었습니다",
playgroundFailed: "API Playground 테스트 실패",
loadFailed: "API 통합 설정을 불러오지 못했습니다",
saveFailed: "API 통합 설정 저장 실패",
saveSuccess: "API 통합 설정이 저장되었습니다",
autoSaveNeedSecret: "서명 토큰 모드는 자동 저장 전에 HMAC secret이 필요합니다.",
},
manageSectionTitle: "채널 구성",
manageSectionDesc: "에이전트를 선택한 후 해당 에이전트의 통합 채널을 생성하거나 편집할 수 있습니다",
+44 -1
View File
@@ -2360,6 +2360,7 @@ export default {
resetApiKeyFailed: 'Не удалось сбросить API Key',
getApiPrincipalConfigFailed: 'Не удалось получить конфигурацию API principal',
updateApiPrincipalConfigFailed: 'Не удалось обновить конфигурацию API principal',
createApiPrincipalTestTokenFailed: 'Не удалось создать тестовый API Token',
updateFailed: 'Не удалось обновить информацию об арендаторе'
},
initialization: {
@@ -5607,11 +5608,15 @@ export default {
requireDirectHeaderDesc:
'Если включено, запросы без заголовка ID пользователя отклоняются; иначе все запросы обрабатываются как единый арендатор без различия конечных пользователей.',
tokenHeader: 'Заголовок token',
tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend; имя заголовка настраивается.',
tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend, в этом фиксированном заголовке.',
hmacSecret: 'HMAC secret',
hmacSecretDesc: 'Тот же secret, что в WeKnora; только для подписи JWT на backend — не отправляйте его в заголовке запроса.',
secretConfigured: 'Secret настроен; введите новое значение для ротации',
generateSecret: 'Сгенерировать secret',
hmacSecretResetConfirmTitle: 'Сбросить HMAC secret?',
hmacSecretResetConfirmBody: 'После сброса старый HMAC secret немедленно перестанет действовать. Все backend-сервисы, подписывающие JWT старым secret, должны перейти на новый secret, чтобы вызовы signed token продолжили работать. Это действие нельзя отменить.',
hmacSecretResetConfirmOk: 'Сбросить',
hmacSecretResetConfirmCancel: 'Отмена',
tokenSignExample: 'Пример подписи JWT на backend (Go)',
signedRequestStep0:
'# 0. Подпишите JWT на backend (HS256, aud=weknora, sub=ID пользователя, tenant_id={tenantId}, exp не более 24 ч)',
@@ -5620,9 +5625,47 @@ export default {
requestExampleAgentChat: '# 2. Agent-чат (SSE; замените <session_id> на id из шага 1)',
requestExampleJwtPlaceholder: '<JWT, подписанный backend>',
requestExample: 'Пример запроса',
playgroundTitle: 'API Playground',
playgroundDesc: 'Отправьте реальные запросы с текущим API key и режимом идентификации, чтобы проверить создание session, agent chat и SSE-ответ.',
playgroundOpen: 'Открыть Playground',
playgroundDrawerDesc: 'Отладка Session, Agent Chat и SSE-ответа через реальный API integration flow',
playgroundBadge: 'Реальный запрос',
playgroundSectionRequest: 'Настройка запроса',
playgroundSectionPreview: 'Preview запроса',
playgroundSectionResult: 'Результат запуска',
playgroundAgent: 'Тестовый агент',
playgroundAgentPlaceholder: 'Выберите агента для теста',
playgroundBuiltin: 'Встроенный',
playgroundAgentsLoadFailed: 'Не удалось загрузить агентов',
playgroundExternalUser: 'ID внешнего пользователя',
playgroundExternalUserPlaceholder: 'user_123',
playgroundTenantModeHint: 'Режим только арендатора не отправляет внешнего пользователя; все API sessions используют один tenant principal.',
playgroundDirectModeHint: 'Этот ID пользователя будет отправлен в заголовке {headerName}.',
playgroundSignedModeHint: 'В режиме signed token внешний пользователь берётся из JWT sub. Playground автоматически подпишет краткоживущий тестовый JWT для этого user ID.',
playgroundQuestion: 'Тестовый вопрос',
playgroundQuestionPlaceholder: 'Введите вопрос для отправки агенту',
playgroundRequestPreview: 'Preview запроса (секреты скрыты)',
playgroundRun: 'Запустить тест',
playgroundStop: 'Остановить',
playgroundNeedApiKey: 'У этого арендатора нет API key.',
playgroundNeedAgent: 'Выберите тестового агента.',
playgroundNeedQuestion: 'Введите тестовый вопрос.',
playgroundNeedExternalUser: 'Введите external user ID.',
playgroundMintTokenFailed: 'Не удалось создать краткоживущий тестовый JWT.',
playgroundMissingSessionId: 'Session создана, но в ответе нет session id.',
playgroundNoStream: 'Chat API не вернул читаемый SSE stream.',
playgroundGeneratedToken: 'Сгенерированный тестовый token',
playgroundStepSession: 'Шаг 1: создать Session',
playgroundStepChat: 'Шаг 2: Agent Chat SSE',
playgroundFinalAnswer: 'Извлечённый ответ',
playgroundEmptyResult: 'Запустите тест, чтобы увидеть здесь ответ Session, сырой SSE output и извлечённый ответ.',
playgroundSuccess: 'Тест завершён ({ms}ms)',
playgroundStopped: 'Тест остановлен',
playgroundFailed: 'Тест API Playground не удался',
loadFailed: 'Не удалось загрузить настройки API-интеграции',
saveFailed: 'Не удалось сохранить настройки API-интеграции',
saveSuccess: 'Настройки API-интеграции сохранены',
autoSaveNeedSecret: 'Для signed-token режима нужен HMAC secret перед автосохранением.',
},
manageSectionTitle: 'Настройка каналов',
manageSectionDesc: 'Выберите агента, чтобы создать или изменить каналы интеграции для него',
+44 -1
View File
@@ -2655,6 +2655,7 @@ export default {
resetApiKeyFailed: "重置 API Key 失败",
getApiPrincipalConfigFailed: "获取 API 用户身份配置失败",
updateApiPrincipalConfigFailed: "更新 API 用户身份配置失败",
createApiPrincipalTestTokenFailed: "生成 API 测试 Token 失败",
updateFailed: "更新空间信息失败",
deleteFailed: "删除空间失败",
},
@@ -5787,11 +5788,15 @@ export default {
requireDirectHeaderDesc:
"开启后,缺少用户 ID 请求头的 API Key 请求将被拒绝;关闭则按整个租户统一处理,不区分具体终端用户。",
tokenHeader: "Token 请求头",
tokenHeaderDesc: "客户端携带后端签发的 JWT,请求头名可自定义。",
tokenHeaderDesc: "客户端在该固定请求头中携带后端签发的 JWT。",
hmacSecret: "HMAC 密钥",
hmacSecretDesc: "与 WeKnora 保存的同一份密钥;仅用于后端签发 JWT,不要作为请求头发送。",
secretConfigured: "已配置密钥;输入新值可轮换",
generateSecret: "生成密钥",
hmacSecretResetConfirmTitle: "确认重置 HMAC 密钥?",
hmacSecretResetConfirmBody: "重置后,旧的 HMAC 密钥会立即失效,所有使用旧密钥签发 JWT 的后端服务必须更换为新密钥才可继续通过签名 Token 调用。此操作不可撤销。",
hmacSecretResetConfirmOk: "确认重置",
hmacSecretResetConfirmCancel: "取消",
tokenSignExample: "后端签发 JWT 示例(Go)",
signedRequestStep0:
"# 0. 在你的后端签发 JWT(HS256,aud=weknora,sub=用户 ID,tenant_id={tenantId},exp 不超过 24 小时)",
@@ -5800,9 +5805,47 @@ export default {
requestExampleAgentChat: "# 2. Agent 对话(SSE;将 <session_id> 替换为第 1 步返回的 id)",
requestExampleJwtPlaceholder: "<后端签发的 JWT>",
requestExample: "请求示例",
playgroundTitle: "API Playground",
playgroundDesc: "用当前 API Key 和身份模式发起真实请求,验证会话创建、智能体对话和 SSE 返回。",
playgroundOpen: "打开 Playground",
playgroundDrawerDesc: "按真实 API 集成方式调试 Session、Agent Chat 和 SSE 返回",
playgroundBadge: "真实请求",
playgroundSectionRequest: "请求配置",
playgroundSectionPreview: "请求预览",
playgroundSectionResult: "运行结果",
playgroundAgent: "测试智能体",
playgroundAgentPlaceholder: "选择要测试的智能体",
playgroundBuiltin: "内置",
playgroundAgentsLoadFailed: "智能体列表加载失败",
playgroundExternalUser: "外部用户 ID",
playgroundExternalUserPlaceholder: "user_123",
playgroundTenantModeHint: "仅租户模式不会发送外部用户身份,所有 API 会话归属同一个租户级主体。",
playgroundDirectModeHint: "将通过 {headerName} 请求头发送此用户 ID。",
playgroundSignedModeHint: "签名模式由 JWT 的 sub 代表外部用户;Playground 会用这里的用户 ID 自动签出短期测试 JWT。",
playgroundQuestion: "测试问题",
playgroundQuestionPlaceholder: "输入要发送给智能体的问题",
playgroundRequestPreview: "请求预览(已遮蔽密钥)",
playgroundRun: "运行测试",
playgroundStop: "停止",
playgroundNeedApiKey: "当前租户没有 API Key。",
playgroundNeedAgent: "请选择测试智能体。",
playgroundNeedQuestion: "请输入测试问题。",
playgroundNeedExternalUser: "请输入外部用户 ID。",
playgroundMintTokenFailed: "生成短期测试 JWT 失败。",
playgroundMissingSessionId: "创建会话成功,但响应中没有 session id。",
playgroundNoStream: "对话接口没有返回可读取的 SSE 流。",
playgroundGeneratedToken: "本次生成的测试 Token",
playgroundStepSession: "步骤 1:创建 Session",
playgroundStepChat: "步骤 2:Agent Chat SSE",
playgroundFinalAnswer: "提取出的回答",
playgroundEmptyResult: "运行后将在这里显示 Session 响应、SSE 原始输出和提取出的回答。",
playgroundSuccess: "测试完成({ms}ms)",
playgroundStopped: "测试已停止",
playgroundFailed: "API Playground 测试失败",
loadFailed: "加载 API 集成设置失败",
saveFailed: "保存 API 集成设置失败",
saveSuccess: "API 集成设置已保存",
autoSaveNeedSecret: "签名 Token 模式需要填写 HMAC 密钥后才能自动保存。",
},
manageSectionTitle: "渠道配置",
manageSectionDesc: "选择智能体后,可创建或编辑该智能体下的集成渠道",
File diff suppressed because it is too large Load Diff
+130 -20
View File
@@ -5,8 +5,10 @@ import (
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
@@ -110,11 +112,28 @@ type apiPrincipalConfigResponse struct {
SignedTokenHeaderName string `json:"signed_token_header_name"`
RequireDirectHeader bool `json:"require_direct_header"`
HasHMACSecret bool `json:"has_hmac_secret"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
type apiPrincipalTestTokenRequest struct {
ExternalUserID string `json:"external_user_id"`
ExpiresInSeconds int `json:"expires_in_seconds"`
}
type apiPrincipalTestTokenResponse struct {
Token string `json:"token"`
HeaderName string `json:"header_name"`
ExpiresInSeconds int `json:"expires_in_seconds"`
ExpiresAtUnix int64 `json:"expires_at_unix"`
ExternalUserID string `json:"external_user_id"`
}
const (
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
defaultAPIPrincipalTestTokenTTL = 15 * time.Minute
maxAPIPrincipalTestTokenTTL = time.Hour
maxAPIPrincipalExternalUserIDLen = 128
)
// defaultMaxOwnedTenantsPerUser is the cap applied when
@@ -539,20 +558,13 @@ func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalCo
if mode == "" {
mode = types.APIPrincipalModeTenant
}
directHeader := strings.TrimSpace(cfg.DirectHeaderName)
if directHeader == "" {
directHeader = defaultAPIPrincipalDirectHeader
}
tokenHeader := strings.TrimSpace(cfg.SignedTokenHeaderName)
if tokenHeader == "" {
tokenHeader = defaultAPIPrincipalTokenHeader
}
return apiPrincipalConfigResponse{
Mode: mode,
DirectHeaderName: directHeader,
SignedTokenHeaderName: tokenHeader,
DirectHeaderName: defaultAPIPrincipalDirectHeader,
SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,
RequireDirectHeader: cfg.RequireDirectHeader,
HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",
HMACSecret: strings.TrimSpace(cfg.HMACSecret),
}
}
@@ -645,17 +657,11 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
}
cfg := &types.APIPrincipalConfig{
Mode: req.Mode,
DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),
SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),
DirectHeaderName: defaultAPIPrincipalDirectHeader,
SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,
RequireDirectHeader: req.RequireDirectHeader,
HMACSecret: hmacSecret,
}
if cfg.DirectHeaderName == "" {
cfg.DirectHeaderName = defaultAPIPrincipalDirectHeader
}
if cfg.SignedTokenHeaderName == "" {
cfg.SignedTokenHeaderName = defaultAPIPrincipalTokenHeader
}
if cfg.Mode == types.APIPrincipalModeSignedToken && strings.TrimSpace(cfg.HMACSecret) == "" {
c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))
return
@@ -677,6 +683,110 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
})
}
// CreateAPIPrincipalTestToken godoc
// @Summary 生成 API Playground 测试 JWT
// @Description 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)
// @Tags 租户管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param request body handler.apiPrincipalTestTokenRequest true "测试 Token 参数"
// @Success 200 {object} map[string]interface{} "短期 JWT"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Router /tenants/{id}/api-principal-test-token [post]
func (h *TenantHandler) CreateAPIPrincipalTestToken(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
return
}
var req apiPrincipalTestTokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
externalUserID := strings.TrimSpace(req.ExternalUserID)
if err := validateAPIPrincipalExternalUserID(externalUserID); err != nil {
c.Error(errors.NewValidationError("external_user_id is invalid").WithDetails(err.Error()))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
}
return
}
cfg := tenant.APIPrincipalConfig
if cfg == nil || cfg.Mode != types.APIPrincipalModeSignedToken {
c.Error(errors.NewValidationError("signed_token mode is required"))
return
}
secret := strings.TrimSpace(cfg.HMACSecret)
if secret == "" {
c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))
return
}
ttl := defaultAPIPrincipalTestTokenTTL
if req.ExpiresInSeconds > 0 {
ttl = time.Duration(req.ExpiresInSeconds) * time.Second
}
if ttl <= 0 || ttl > maxAPIPrincipalTestTokenTTL {
c.Error(errors.NewValidationError("expires_in_seconds must be between 1 and 3600"))
return
}
now := time.Now()
expiresAt := now.Add(ttl)
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": externalUserID,
"tenant_id": strconv.FormatUint(id, 10),
"aud": "weknora",
"iat": now.Unix(),
"exp": expiresAt.Unix(),
}).SignedString([]byte(secret))
if err != nil {
c.Error(errors.NewInternalServerError("Failed to create API principal test token").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalTestTokenResponse{
Token: token,
HeaderName: defaultAPIPrincipalTokenHeader,
ExpiresInSeconds: int(ttl.Seconds()),
ExpiresAtUnix: expiresAt.Unix(),
ExternalUserID: externalUserID,
},
})
}
func validateAPIPrincipalExternalUserID(id string) error {
if id == "" {
return errors.NewValidationError("external_user_id is required")
}
if len(id) > maxAPIPrincipalExternalUserIDLen {
return errors.NewValidationError("external_user_id is too long")
}
for _, r := range id {
if r < 0x20 || r == 0x7f {
return errors.NewValidationError("external_user_id contains invalid characters")
}
}
return nil
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户
+2 -10
View File
@@ -324,11 +324,7 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.
}
switch cfg.Mode {
case types.APIPrincipalModeDirect:
name := strings.TrimSpace(cfg.DirectHeaderName)
if name == "" {
name = defaultExternalUserIDHeader
}
externalUserID := strings.TrimSpace(header.Get(name))
externalUserID := strings.TrimSpace(header.Get(defaultExternalUserIDHeader))
if externalUserID == "" {
if cfg.RequireDirectHeader {
return types.Principal{}, errMissingDirectHeader
@@ -343,11 +339,7 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.
ID: strconv.FormatUint(tenantID, 10) + ":" + externalUserID,
}, nil
case types.APIPrincipalModeSignedToken:
name := strings.TrimSpace(cfg.SignedTokenHeaderName)
if name == "" {
name = defaultExternalUserTokenHeader
}
externalUserID, err := verifyExternalUserJWT(header.Get(name), tenantID, cfg.HMACSecret)
externalUserID, err := verifyExternalUserJWT(header.Get(defaultExternalUserTokenHeader), tenantID, cfg.HMACSecret)
if err != nil || externalUserID == "" {
logger.Warnf(ctx, "invalid external user token for tenant=%d: %v", tenantID, err)
return types.Principal{}, fmt.Errorf("%w: %w", errInvalidExternalUserToken, err)
+2 -1
View File
@@ -107,7 +107,7 @@ func NewRouter(params RouterParams) *gin.Engine {
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-API-Key", "X-Request-ID", "X-Tenant-ID", "X-Embed-Session"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-API-Key", "X-Request-ID", "X-Tenant-ID", "X-Embed-Session", "X-External-User-ID", "X-External-User-Token"},
ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
@@ -573,6 +573,7 @@ func RegisterTenantRoutes(
tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)
tenantByID.GET("/api-principal-config", g.Owner(), handler.GetAPIPrincipalConfig)
tenantByID.PUT("/api-principal-config", g.Owner(), handler.UpdateAPIPrincipalConfig)
tenantByID.POST("/api-principal-test-token", g.Owner(), handler.CreateAPIPrincipalTestToken)
// Tenant member management (PR 3 of #1303). Listing is
// Viewer+ so any active member can see the roster; mutation