feat: scope API MCP OAuth by principal

This commit is contained in:
wizardchen
2026-06-30 09:21:49 +08:00
committed by lyingbug
parent 77e4f93e3e
commit cb99736d72
39 changed files with 1566 additions and 108 deletions
+6
View File
@@ -553,6 +553,12 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error {
c.JSON(http.StatusForbidden, gin.H{"error": "session signature invalid"})
return apperrors.NewForbiddenError("session signature invalid")
}
principal := types.Principal{
Type: types.PrincipalEmbedSession,
ID: fmt.Sprintf("%d:%s:%s", ch.TenantID, ch.ID, sessionID),
}
c.Set(types.PrincipalContextKey.String(), principal)
c.Request = c.Request.WithContext(types.WithPrincipal(c.Request.Context(), principal))
return nil
}
+23 -17
View File
@@ -36,6 +36,12 @@ func NewMCPOAuthHandler(
return &MCPOAuthHandler{oauth: oauth, mcpManager: mcpManager, svc: svc, gate: gate}
}
func mcpOAuthPrincipalFromContext(ctx *gin.Context) (types.Principal, string) {
principal, _ := types.PrincipalFromContext(ctx.Request.Context())
principal = principal.Normalize()
return principal, principal.StorageID()
}
type mcpOAuthAuthorizeRequest struct {
// RedirectURI is the absolute backend callback URL registered with the
// authorization server (e.g. https://host/api/v1/mcp-services/oauth/callback).
@@ -63,8 +69,8 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -93,7 +99,7 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) {
return
}
authURL, err := h.oauth.StartAuthorization(ctx, service, tenantID, userID, req.RedirectURI, req.FrontendRedirect)
authURL, err := h.oauth.StartAuthorization(ctx, service, tenantID, principal, req.RedirectURI, req.FrontendRedirect)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"service_id": secutils.SanitizeForLog(serviceID),
@@ -163,13 +169,13 @@ func (h *MCPOAuthHandler) Status(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, userID, serviceID)
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, principal, serviceID)
if err != nil {
c.Error(errors.NewInternalServerError("failed to query authorization status: " + err.Error()))
return
@@ -192,13 +198,13 @@ func (h *MCPOAuthHandler) Revoke(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
if err := h.oauth.Revoke(ctx, tenantID, userID, serviceID); err != nil {
if err := h.oauth.Revoke(ctx, tenantID, principal, serviceID); err != nil {
c.Error(errors.NewInternalServerError("failed to revoke authorization: " + err.Error()))
return
}
@@ -238,8 +244,8 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
ctx := c.Request.Context()
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || strings.TrimSpace(userID) == "" {
principal, gateUserID := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() || gateUserID == "" {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -266,7 +272,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
switch decision {
case "cancel", "reject", "skip":
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{
Approved: false,
Reason: "user canceled",
}); err != nil {
@@ -298,7 +304,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
// Only resume once the user genuinely holds a token; otherwise the retry
// would just fail again with another authorization-required error.
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, userID, serviceID)
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, principal, serviceID)
if err != nil {
c.Error(errors.NewInternalServerError("failed to verify authorization: " + err.Error()))
return
@@ -308,7 +314,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
return
}
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{Approved: true}); err != nil {
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{Approved: true}); err != nil {
switch {
case stderrors.Is(err, approval.ErrPendingNotFound):
c.Error(errors.NewNotFoundError("pending authorization not found or already completed"))
@@ -346,8 +352,8 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) {
ctx := c.Request.Context()
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || strings.TrimSpace(userID) == "" {
_, gateUserID := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || strings.TrimSpace(gateUserID) == "" {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -356,7 +362,7 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) {
return
}
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{
Approved: false,
Reason: "user canceled",
}); err != nil {
+6 -6
View File
@@ -645,16 +645,16 @@ func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {
c.Error(errors.NewBadRequestError("decision must be approve or reject"))
return
}
userID, _ := c.Get(types.UserIDContextKey.String())
userIDStr, _ := userID.(string)
// Reject calls without an authenticated user up front. The gate's
// per-user authorization is fail-close, but surfacing 401 here gives
principal, _ := types.PrincipalFromContext(ctx)
gateUserID := principal.StorageID()
// Reject calls without an authenticated principal up front. The gate's
// per-principal authorization is fail-close, but surfacing 401 here gives
// a clearer signal that auth middleware did not populate the context.
if strings.TrimSpace(userIDStr) == "" {
if strings.TrimSpace(gateUserID) == "" {
c.Error(errors.NewUnauthorizedError("authenticated user required to resolve tool approval"))
return
}
if err := h.toolApprovalGate.Resolve(tenantID, userIDStr, pendingID, dec); err != nil {
if err := h.toolApprovalGate.Resolve(tenantID, gateUserID, pendingID, dec); err != nil {
switch {
case stderrors.Is(err, approval.ErrPendingNotFound):
c.Error(errors.NewNotFoundError("pending approval not found or already completed"))
+140
View File
@@ -96,6 +96,25 @@ type updateTenantRequest struct {
Description *string `json:"description" binding:"omitempty,max=512"`
}
type apiPrincipalConfigRequest struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
HMACSecret *string `json:"hmac_secret"`
}
type apiPrincipalConfigResponse struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
HasHMACSecret bool `json:"has_hmac_secret"`
}
const (
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
)
// defaultMaxOwnedTenantsPerUser is the cap applied when
// config.Tenant.MaxOwnedPerUser is left at zero. Picked to comfortably
// cover legitimate "personal + a couple of side-projects" use while
@@ -510,6 +529,127 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
})
}
func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalConfigResponse {
if cfg == nil {
cfg = &types.APIPrincipalConfig{}
}
mode := cfg.Mode
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,
HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",
}
}
// GetAPIPrincipalConfig returns the tenant API-key principal mapping config.
func (h *TenantHandler) GetAPIPrincipalConfig(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
}
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
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalConfigForResponse(tenant.APIPrincipalConfig),
})
}
// UpdateAPIPrincipalConfig updates how tenant API-key requests resolve principals.
func (h *TenantHandler) UpdateAPIPrincipalConfig(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 apiPrincipalConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
if req.Mode == "" {
req.Mode = types.APIPrincipalModeTenant
}
switch req.Mode {
case types.APIPrincipalModeTenant, types.APIPrincipalModeDirect, types.APIPrincipalModeSignedToken:
default:
c.Error(errors.NewValidationError("mode must be tenant, direct_header, or signed_token"))
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
}
existingSecret := ""
if tenant.APIPrincipalConfig != nil {
existingSecret = tenant.APIPrincipalConfig.HMACSecret
}
hmacSecret := existingSecret
if req.HMACSecret != nil {
hmacSecret = strings.TrimSpace(*req.HMACSecret)
}
cfg := &types.APIPrincipalConfig{
Mode: req.Mode,
DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),
SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),
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
}
tenant.APIPrincipalConfig = cfg
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to update API principal config").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalConfigForResponse(updatedTenant.APIPrincipalConfig),
})
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户