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
+2
View File
@@ -16,6 +16,8 @@ const (
UserContextKey ContextKey = "User"
// UserIDContextKey is the context key for user ID
UserIDContextKey ContextKey = "UserID"
// PrincipalContextKey is the context key for the terminal caller principal.
PrincipalContextKey ContextKey = "Principal"
// TenantRoleContextKey is the context key for the caller's TenantRole
// in the currently active tenant (loaded by the auth middleware from
// the tenant_members table). See TenantRoleFromContext.
+13 -1
View File
@@ -7,7 +7,7 @@ import (
)
// MCPOAuthRepository persists OAuth clients (per service) and tokens
// (per user + service) for the MCP OAuth2 authorization-code flow.
// (per principal + service) for the MCP OAuth2 authorization-code flow.
type MCPOAuthRepository interface {
// GetClient returns the registered OAuth client for a service, or
// (nil, nil) when none has been registered yet.
@@ -23,10 +23,22 @@ type MCPOAuthRepository interface {
// (nil, nil) when the user has not authorized yet.
GetToken(ctx context.Context, tenantID uint64, userID, serviceID string) (*types.MCPOAuthToken, error)
// GetTokenForPrincipal returns the stored token for (tenant, principal, service),
// or (nil, nil) when the principal has not authorized yet.
GetTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (*types.MCPOAuthToken, error)
// SaveToken creates or updates the per-user token for a service.
SaveToken(ctx context.Context, token *types.MCPOAuthToken) error
// SaveTokenForPrincipal creates or updates the per-principal token for a service.
SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error
// DeleteToken removes the per-user token for a service (revoke /
// re-authorize).
DeleteToken(ctx context.Context, tenantID uint64, userID, serviceID string) error
// DeleteTokenForPrincipal removes the per-principal token for a service.
DeleteTokenForPrincipal(ctx context.Context, tenantID uint64, principal types.Principal, serviceID string) error
}
+15 -13
View File
@@ -68,23 +68,25 @@ func (m *MCPOAuthClient) encryptSecret() {
}
}
// MCPOAuthToken stores a per-user OAuth token for an MCP service. The agent
// connects to the MCP server on behalf of the invoking user, so tokens are
// isolated by (tenant_id, user_id, service_id).
// MCPOAuthToken stores a per-principal OAuth token for an MCP service. The
// agent connects to the MCP server on behalf of the invoking principal, so
// tokens are isolated by (tenant_id, principal_type, principal_id, service_id).
//
// AccessToken and RefreshToken are encrypted at rest (AES-256-GCM) when
// SYSTEM_AES_KEY is configured.
type MCPOAuthToken struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc"`
UserID string `json:"user_id" gorm:"type:varchar(64);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
AccessToken string `json:"-" gorm:"type:text"`
RefreshToken string `json:"-" gorm:"type:text"`
TokenType string `json:"token_type" gorm:"type:varchar(32)"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc"`
UserID string `json:"user_id" gorm:"type:varchar(512);not null;index"`
PrincipalType string `json:"principal_type" gorm:"type:varchar(32);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
PrincipalID string `json:"principal_id" gorm:"type:varchar(512);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
AccessToken string `json:"-" gorm:"type:text"`
RefreshToken string `json:"-" gorm:"type:text"`
TokenType string `json:"token_type" gorm:"type:varchar(32)"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName pins the table name (see MCPOAuthClient.TableName); the default
+65
View File
@@ -0,0 +1,65 @@
package types
import (
"context"
"strings"
)
const (
PrincipalWebUser = "web_user"
PrincipalAPITenant = "api_tenant"
PrincipalAPIUser = "api_user"
PrincipalAPIExternalUser = "api_external_user"
PrincipalIMUser = "im_user"
PrincipalEmbedChannel = "embed_channel"
PrincipalEmbedSession = "embed_session"
)
// Principal represents the terminal caller for per-subject isolation features.
// It is intentionally separate from UserID: many principals, such as IM users
// or embed visitors, are not WeKnora accounts and must not imply RBAC rights.
type Principal struct {
Type string
ID string
}
func (p Principal) Normalize() Principal {
return Principal{
Type: strings.TrimSpace(p.Type),
ID: strings.TrimSpace(p.ID),
}
}
func (p Principal) Valid() bool {
p = p.Normalize()
return p.Type != "" && p.ID != ""
}
func (p Principal) StorageID() string {
p = p.Normalize()
if !p.Valid() {
return ""
}
return p.Type + ":" + p.ID
}
func WithPrincipal(ctx context.Context, principal Principal) context.Context {
principal = principal.Normalize()
if !principal.Valid() {
return ctx
}
return context.WithValue(ctx, PrincipalContextKey, principal)
}
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
if ctx == nil {
return Principal{}, false
}
if p, ok := ctx.Value(PrincipalContextKey).(Principal); ok && p.Valid() {
return p.Normalize(), true
}
if uid, ok := UserIDFromContext(ctx); ok && strings.TrimSpace(uid) != "" {
return Principal{Type: PrincipalWebUser, ID: uid}, true
}
return Principal{}, false
}
+34
View File
@@ -0,0 +1,34 @@
package types
import (
"context"
"testing"
)
func TestPrincipalFromContextFallsBackToWebUser(t *testing.T) {
ctx := context.WithValue(context.Background(), UserIDContextKey, "u1")
p, ok := PrincipalFromContext(ctx)
if !ok {
t.Fatal("expected principal")
}
if p.Type != PrincipalWebUser || p.ID != "u1" {
t.Fatalf("principal = %#v", p)
}
}
func TestWithPrincipalRejectsBlankValues(t *testing.T) {
ctx := WithPrincipal(context.Background(), Principal{Type: " ", ID: "x"})
if _, ok := PrincipalFromContext(ctx); ok {
t.Fatal("blank principal type should not be stored")
}
}
func TestPrincipalStorageID(t *testing.T) {
p := Principal{Type: PrincipalIMUser, ID: "wecom:ch1:u1"}
if got := p.StorageID(); got != "im_user:wecom:ch1:u1" {
t.Fatalf("StorageID() = %q", got)
}
}
+55
View File
@@ -116,6 +116,8 @@ type Tenant struct {
ChatHistoryConfig *ChatHistoryConfig `yaml:"chat_history_config" json:"chat_history_config" gorm:"type:jsonb"`
// Retrieval config: global search/retrieval parameters shared by knowledge search and message search
RetrievalConfig *RetrievalConfig `yaml:"retrieval_config" json:"retrieval_config" gorm:"type:jsonb"`
// API principal config: controls how X-API-Key requests map to terminal principals.
APIPrincipalConfig *APIPrincipalConfig `yaml:"api_principal_config" json:"-" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time
@@ -215,6 +217,59 @@ type WeKnoraCloudCredentials struct {
AppSecret string `json:"app_secret"`
}
type APIPrincipalMode string
const (
APIPrincipalModeTenant APIPrincipalMode = "tenant"
APIPrincipalModeDirect APIPrincipalMode = "direct_header"
APIPrincipalModeSignedToken APIPrincipalMode = "signed_token"
)
// APIPrincipalConfig controls how tenant API-key requests map to terminal
// principals. Direct header mode is low-assurance and should only be used for
// trusted server-to-server calls; signed-token mode verifies the user claim.
type APIPrincipalConfig struct {
Mode APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name,omitempty"`
SignedTokenHeaderName string `json:"signed_token_header_name,omitempty"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
func (c *APIPrincipalConfig) Value() (driver.Value, error) {
if c == nil {
return nil, nil
}
cp := *c
if cp.HMACSecret != "" {
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.EncryptAESGCM(cp.HMACSecret, key); err == nil {
cp.HMACSecret = encrypted
}
}
}
return json.Marshal(&cp)
}
func (c *APIPrincipalConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
if err := json.Unmarshal(b, c); err != nil {
return err
}
if plain, ok := utils.DecryptStoredSecretLenient(c.HMACSecret); ok {
c.HMACSecret = plain
} else {
log.Printf("[crypto] tenant api_principal_config.hmac_secret: decrypt failed (SYSTEM_AES_KEY missing/rotated?), treating as unconfigured")
c.HMACSecret = ""
}
return nil
}
// GetWeKnoraCloud returns the WeKnoraCloud credentials, or nil if not configured.
func (c *CredentialsConfig) GetWeKnoraCloud() *WeKnoraCloudCredentials {
if c == nil || c.WeKnoraCloud == nil {