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
+55 -4
View File
@@ -56,9 +56,25 @@ func (r *mcpOAuthRepository) DeleteClient(ctx context.Context, tenantID uint64,
func (r *mcpOAuthRepository) GetToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) (*types.MCPOAuthToken, error) {
return r.GetTokenForPrincipal(ctx, tenantID, types.Principal{
Type: types.PrincipalWebUser,
ID: userID,
}, serviceID)
}
func (r *mcpOAuthRepository) GetTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (*types.MCPOAuthToken, error) {
principal = principal.Normalize()
if !principal.Valid() {
return nil, nil
}
var token types.MCPOAuthToken
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
tenantID, principal.Type, principal.ID, serviceID,
).
First(&token).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -70,12 +86,31 @@ func (r *mcpOAuthRepository) GetToken(
}
func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAuthToken) error {
if token.PrincipalType == "" || token.PrincipalID == "" {
token.PrincipalType = types.PrincipalWebUser
token.PrincipalID = token.UserID
}
return r.SaveTokenForPrincipal(ctx, token)
}
func (r *mcpOAuthRepository) SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error {
if token.PrincipalType == "" || token.PrincipalID == "" {
return nil
}
if token.UserID == "" {
token.UserID = (types.Principal{Type: token.PrincipalType, ID: token.PrincipalID}).StorageID()
}
token.UpdatedAt = time.Now()
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}, {Name: "service_id"}},
Columns: []clause.Column{
{Name: "tenant_id"},
{Name: "principal_type"},
{Name: "principal_id"},
{Name: "service_id"},
},
DoUpdates: clause.AssignmentColumns([]string{
"access_token", "refresh_token", "token_type", "expires_at", "updated_at",
"user_id", "access_token", "refresh_token", "token_type", "expires_at", "updated_at",
}),
}).
Create(token).Error
@@ -84,7 +119,23 @@ func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAut
func (r *mcpOAuthRepository) DeleteToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) error {
return r.DeleteTokenForPrincipal(ctx, tenantID, types.Principal{
Type: types.PrincipalWebUser,
ID: userID,
}, serviceID)
}
func (r *mcpOAuthRepository) DeleteTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) error {
principal = principal.Normalize()
if !principal.Valid() {
return nil
}
return r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
tenantID, principal.Type, principal.ID, serviceID,
).
Delete(&types.MCPOAuthToken{}).Error
}
@@ -0,0 +1,81 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newMCPOAuthTestRepo(t *testing.T) *mcpOAuthRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.MCPOAuthClient{}, &types.MCPOAuthToken{}))
return NewMCPOAuthRepository(db).(*mcpOAuthRepository)
}
func TestMCPOAuthRepositoryTokenForPrincipalIsolated(t *testing.T) {
repo := newMCPOAuthTestRepo(t)
ctx := context.Background()
expiresAt := time.Now().Add(time.Hour).UTC()
webPrincipal := types.Principal{Type: types.PrincipalWebUser, ID: "u1"}
apiPrincipal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:external-u1"}
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: webPrincipal.StorageID(),
PrincipalType: webPrincipal.Type,
PrincipalID: webPrincipal.ID,
ServiceID: "svc1",
AccessToken: "web-token",
RefreshToken: "web-refresh",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: apiPrincipal.StorageID(),
PrincipalType: apiPrincipal.Type,
PrincipalID: apiPrincipal.ID,
ServiceID: "svc1",
AccessToken: "api-token",
RefreshToken: "api-refresh",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
webToken, err := repo.GetTokenForPrincipal(ctx, 7, webPrincipal, "svc1")
require.NoError(t, err)
require.Equal(t, "web-token", webToken.AccessToken)
apiToken, err := repo.GetTokenForPrincipal(ctx, 7, apiPrincipal, "svc1")
require.NoError(t, err)
require.Equal(t, "api-token", apiToken.AccessToken)
}
func TestMCPOAuthRepositoryLegacyUserTokenUsesWebPrincipal(t *testing.T) {
repo := newMCPOAuthTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.SaveToken(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: "u1",
ServiceID: "svc1",
AccessToken: "legacy-token",
RefreshToken: "legacy-refresh",
TokenType: "Bearer",
ExpiresAt: time.Now().Add(time.Hour).UTC(),
}))
token, err := repo.GetTokenForPrincipal(ctx, 7, types.Principal{Type: types.PrincipalWebUser, ID: "u1"}, "svc1")
require.NoError(t, err)
require.Equal(t, "legacy-token", token.AccessToken)
}
+1 -1
View File
@@ -389,7 +389,7 @@ func (s *mcpServiceService) TestMCPService(
if service.AuthConfig.IsOAuth() {
config.OAuthRepo = s.oauthRepo
config.TenantID, _ = types.TenantIDFromContext(ctx)
config.UserID, _ = types.UserIDFromContext(ctx)
config.Principal, _ = types.PrincipalFromContext(ctx)
}
client, err := mcp.NewMCPClient(config)