fix(security): close six open GHSA findings from security triage
Harden share-link listing, password rotation, OIDC callback binding, org invite search, knowledge batch mutations, and connector redirects.
This commit is contained in:
@@ -27,11 +27,6 @@ import (
|
|||||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type oidcAuthorizationState struct {
|
|
||||||
Nonce string `json:"nonce"`
|
|
||||||
RedirectURI string `json:"redirect_uri,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
jwtSecretOnce sync.Once
|
jwtSecretOnce sync.Once
|
||||||
jwtSecret string
|
jwtSecret string
|
||||||
@@ -367,7 +362,7 @@ func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI s
|
|||||||
return nil, fmt.Errorf("failed to generate state: %w", err)
|
return nil, fmt.Errorf("failed to generate state: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
state, err := encodeOIDCAuthorizationState(&oidcAuthorizationState{
|
state, err := secutils.SignOIDCState(&secutils.OIDCStatePayload{
|
||||||
Nonce: nonce,
|
Nonce: nonce,
|
||||||
RedirectURI: strings.TrimSpace(redirectURI),
|
RedirectURI: strings.TrimSpace(redirectURI),
|
||||||
})
|
})
|
||||||
@@ -394,6 +389,7 @@ func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI s
|
|||||||
ProviderDisplayName: cfg.ProviderDisplayName,
|
ProviderDisplayName: cfg.ProviderDisplayName,
|
||||||
AuthorizationURL: authURL,
|
AuthorizationURL: authURL,
|
||||||
State: state,
|
State: state,
|
||||||
|
Nonce: nonce,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -592,7 +588,13 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPass
|
|||||||
user.PasswordHash = string(hashedPassword)
|
user.PasswordHash = string(hashedPassword)
|
||||||
user.UpdatedAt = time.Now()
|
user.UpdatedAt = time.Now()
|
||||||
|
|
||||||
return s.userRepo.UpdateUser(ctx, user)
|
if err := s.userRepo.UpdateUser(ctx, user); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalidate every outstanding session so a stolen token cannot
|
||||||
|
// survive a password rotation.
|
||||||
|
return s.tokenRepo.RevokeTokensByUserID(ctx, userID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidatePassword validates user password
|
// ValidatePassword validates user password
|
||||||
@@ -1207,14 +1209,6 @@ func generateRandomString(length int) (string, error) {
|
|||||||
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeOIDCAuthorizationState(state *oidcAuthorizationState) (string, error) {
|
|
||||||
payload, err := json.Marshal(state)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return base64.RawURLEncoding.EncodeToString(payload), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeJWTClaims(token string) (map[string]interface{}, error) {
|
func decodeJWTClaims(token string) (map[string]interface{}, error) {
|
||||||
parts := strings.Split(token, ".")
|
parts := strings.Split(token, ".")
|
||||||
if len(parts) < 2 {
|
if len(parts) < 2 {
|
||||||
|
|||||||
+28
-11
@@ -20,6 +20,9 @@ import (
|
|||||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const oidcNonceCookieName = "weknora_oidc_nonce"
|
||||||
|
const oidcNonceCookieMaxAge = 600
|
||||||
|
|
||||||
// AuthHandler implements HTTP request handlers for user authentication
|
// AuthHandler implements HTTP request handlers for user authentication
|
||||||
// Provides functionality for user registration, login, logout, and token management
|
// Provides functionality for user registration, login, logout, and token management
|
||||||
// through the REST API endpoints
|
// through the REST API endpoints
|
||||||
@@ -249,6 +252,14 @@ func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bind the state nonce to this browser so an attacker cannot replay
|
||||||
|
// their own authorization code into a victim's callback.
|
||||||
|
if resp.Nonce != "" {
|
||||||
|
secure := c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
|
||||||
|
c.SetSameSite(http.SameSiteLaxMode)
|
||||||
|
c.SetCookie(oidcNonceCookieName, resp.Nonce, oidcNonceCookieMaxAge, "/", "", secure, true)
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, resp)
|
c.JSON(http.StatusOK, resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,12 +312,14 @@ func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
state := strings.TrimSpace(c.Query("state"))
|
state := strings.TrimSpace(c.Query("state"))
|
||||||
decodedState, err := decodeOIDCState(state)
|
decodedState, err := decodeOIDCState(state, c.Request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)
|
logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)
|
||||||
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))
|
c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// One-time use: clear the binding cookie as soon as it is checked.
|
||||||
|
c.SetCookie(oidcNonceCookieName, "", -1, "/", "", false, true)
|
||||||
|
|
||||||
code := strings.TrimSpace(c.Query("code"))
|
code := strings.TrimSpace(c.Query("code"))
|
||||||
if code == "" {
|
if code == "" {
|
||||||
@@ -344,23 +357,26 @@ func encodeOIDCCallbackPayload(resp *types.OIDCCallbackResponse) (string, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
type oidcStatePayload struct {
|
type oidcStatePayload struct {
|
||||||
Nonce string `json:"nonce"`
|
Nonce string
|
||||||
RedirectURI string `json:"redirect_uri,omitempty"`
|
RedirectURI string
|
||||||
}
|
}
|
||||||
|
|
||||||
func decodeOIDCState(raw string) (*oidcStatePayload, error) {
|
func decodeOIDCState(raw string, req *http.Request) (*oidcStatePayload, error) {
|
||||||
decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(raw))
|
payload, err := secutils.VerifyOIDCState(raw)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var payload oidcStatePayload
|
cookieNonce, err := req.Cookie(oidcNonceCookieName)
|
||||||
if err := json.Unmarshal(decoded, &payload); err != nil {
|
if err != nil || cookieNonce == nil || strings.TrimSpace(cookieNonce.Value) == "" {
|
||||||
return nil, err
|
return nil, errors.NewValidationError("oidc nonce cookie missing")
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(payload.RedirectURI) == "" {
|
if cookieNonce.Value != payload.Nonce {
|
||||||
return nil, errors.NewValidationError("state.redirect_uri is required")
|
return nil, errors.NewValidationError("oidc nonce mismatch")
|
||||||
}
|
}
|
||||||
return &payload, nil
|
return &oidcStatePayload{
|
||||||
|
Nonce: payload.Nonce,
|
||||||
|
RedirectURI: strings.TrimSpace(payload.RedirectURI),
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlQueryEscape(value string) string {
|
func urlQueryEscape(value string) string {
|
||||||
@@ -713,6 +729,7 @@ func (h *AuthHandler) SwitchTenant(c *gin.Context) {
|
|||||||
|
|
||||||
c.JSON(http.StatusOK, dto.NewAuthLoginResponse(resp))
|
c.JSON(http.StatusOK, dto.NewAuthLoginResponse(resp))
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Summary 自动初始化(Lite 桌面版)
|
// @Summary 自动初始化(Lite 桌面版)
|
||||||
// @Description Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
|
// @Description Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程
|
||||||
// @Tags 认证
|
// @Tags 认证
|
||||||
|
|||||||
@@ -16,8 +16,10 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||||
"github.com/Tencent/WeKnora/internal/application/repository"
|
"github.com/Tencent/WeKnora/internal/application/repository"
|
||||||
"github.com/Tencent/WeKnora/internal/application/service"
|
"github.com/Tencent/WeKnora/internal/application/service"
|
||||||
|
"github.com/Tencent/WeKnora/internal/config"
|
||||||
"github.com/Tencent/WeKnora/internal/errors"
|
"github.com/Tencent/WeKnora/internal/errors"
|
||||||
"github.com/Tencent/WeKnora/internal/logger"
|
"github.com/Tencent/WeKnora/internal/logger"
|
||||||
|
"github.com/Tencent/WeKnora/internal/middleware"
|
||||||
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
||||||
"github.com/Tencent/WeKnora/internal/types"
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||||
@@ -29,6 +31,7 @@ import (
|
|||||||
|
|
||||||
// KnowledgeHandler processes HTTP requests related to knowledge resources
|
// KnowledgeHandler processes HTTP requests related to knowledge resources
|
||||||
type KnowledgeHandler struct {
|
type KnowledgeHandler struct {
|
||||||
|
cfg *config.Config
|
||||||
kgService interfaces.KnowledgeService
|
kgService interfaces.KnowledgeService
|
||||||
kbService interfaces.KnowledgeBaseService
|
kbService interfaces.KnowledgeBaseService
|
||||||
kbShareService interfaces.KBShareService
|
kbShareService interfaces.KBShareService
|
||||||
@@ -39,6 +42,7 @@ type KnowledgeHandler struct {
|
|||||||
|
|
||||||
// NewKnowledgeHandler creates a new knowledge handler instance
|
// NewKnowledgeHandler creates a new knowledge handler instance
|
||||||
func NewKnowledgeHandler(
|
func NewKnowledgeHandler(
|
||||||
|
cfg *config.Config,
|
||||||
kgService interfaces.KnowledgeService,
|
kgService interfaces.KnowledgeService,
|
||||||
kbService interfaces.KnowledgeBaseService,
|
kbService interfaces.KnowledgeBaseService,
|
||||||
kbShareService interfaces.KBShareService,
|
kbShareService interfaces.KBShareService,
|
||||||
@@ -47,6 +51,7 @@ func NewKnowledgeHandler(
|
|||||||
spanRepo repository.KnowledgeSpanRepository,
|
spanRepo repository.KnowledgeSpanRepository,
|
||||||
) *KnowledgeHandler {
|
) *KnowledgeHandler {
|
||||||
return &KnowledgeHandler{
|
return &KnowledgeHandler{
|
||||||
|
cfg: cfg,
|
||||||
kgService: kgService,
|
kgService: kgService,
|
||||||
kbService: kbService,
|
kbService: kbService,
|
||||||
kbShareService: kbShareService,
|
kbShareService: kbShareService,
|
||||||
@@ -56,6 +61,32 @@ func NewKnowledgeHandler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// requireKBOwnershipOrAdmin enforces the same "KB creator OR Admin+" matrix
|
||||||
|
// used by OwnedKBOrAdmin for routes whose KB id comes from the request body.
|
||||||
|
func (h *KnowledgeHandler) requireKBOwnershipOrAdmin(c *gin.Context, kbID string) error {
|
||||||
|
creator, err := resolveKBCreatorByKBID(c, h.kbService, kbID)
|
||||||
|
evalErr := middleware.EvaluateOwnershipOrRole(
|
||||||
|
c.Request.Context(),
|
||||||
|
h.cfg,
|
||||||
|
types.TenantRoleAdmin,
|
||||||
|
creator,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
if evalErr == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if goerrors.Is(evalErr, middleware.ErrResourceNotFound) {
|
||||||
|
return errors.NewNotFoundError("knowledge base not found")
|
||||||
|
}
|
||||||
|
if goerrors.Is(evalErr, middleware.ErrOwnershipForbidden) {
|
||||||
|
return errors.NewForbiddenError("No permission to operate on this knowledge base")
|
||||||
|
}
|
||||||
|
logger.ErrorWithFields(c.Request.Context(), evalErr, map[string]interface{}{
|
||||||
|
"kb_id": secutils.SanitizeForLog(kbID),
|
||||||
|
})
|
||||||
|
return errors.NewInternalServerError("cannot verify knowledge base ownership")
|
||||||
|
}
|
||||||
|
|
||||||
// validateKnowledgeBaseAccess validates access permissions to a knowledge base
|
// validateKnowledgeBaseAccess validates access permissions to a knowledge base
|
||||||
// using the ":id" URL path parameter. It delegates to validateKnowledgeBaseAccessWithKBID.
|
// using the ":id" URL path parameter. It delegates to validateKnowledgeBaseAccessWithKBID.
|
||||||
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.KnowledgeBase, string, uint64, types.OrgMemberRole, error) {
|
||||||
@@ -1048,6 +1079,10 @@ func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) {
|
|||||||
c.Error(errors.NewForbiddenError("No permission to delete knowledge"))
|
c.Error(errors.NewForbiddenError("No permission to delete knowledge"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
||||||
|
|
||||||
// Single batch fetch to validate that every id exists and belongs to the
|
// Single batch fetch to validate that every id exists and belongs to the
|
||||||
@@ -2057,6 +2092,10 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
|
|||||||
c.Error(errors.NewForbiddenError("No permission to access source knowledge base"))
|
c.Error(errors.NewForbiddenError("No permission to access source knowledge base"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := h.requireKBOwnershipOrAdmin(c, req.SourceKBID); err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Validate target KB
|
// Validate target KB
|
||||||
targetKB, err := h.kbService.GetKnowledgeBaseByID(ctx, req.TargetKBID)
|
targetKB, err := h.kbService.GetKnowledgeBaseByID(ctx, req.TargetKBID)
|
||||||
@@ -2072,6 +2111,10 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) {
|
|||||||
c.Error(errors.NewForbiddenError("No permission to access target knowledge base"))
|
c.Error(errors.NewForbiddenError("No permission to access target knowledge base"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := h.requireKBOwnershipOrAdmin(c, req.TargetKBID); err != nil {
|
||||||
|
c.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Validate type match
|
// Validate type match
|
||||||
if sourceKB.Type != targetKB.Type {
|
if sourceKB.Type != targetKB.Type {
|
||||||
|
|||||||
@@ -1870,6 +1870,8 @@ func (h *OrganizationHandler) SearchTenantsForInvite(c *gin.Context) {
|
|||||||
// 1) Match users by query and group by TenantID. We over-fetch so the
|
// 1) Match users by query and group by TenantID. We over-fetch so the
|
||||||
// de-duplication after filtering "already a member" tenants still
|
// de-duplication after filtering "already a member" tenants still
|
||||||
// leaves us with enough candidates to fill `limit`.
|
// leaves us with enough candidates to fill `limit`.
|
||||||
|
// User PII (email/username) is intentionally omitted from results:
|
||||||
|
// org admins only need tenant identity to send an invite.
|
||||||
users, err := h.userService.SearchUsers(ctx, query, limit*3+20)
|
users, err := h.userService.SearchUsers(ctx, query, limit*3+20)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Errorf(ctx, "Failed to search users: %v", err)
|
logger.Errorf(ctx, "Failed to search users: %v", err)
|
||||||
@@ -1902,11 +1904,7 @@ func (h *OrganizationHandler) SearchTenantsForInvite(c *gin.Context) {
|
|||||||
seen[u.TenantID] = &entry{
|
seen[u.TenantID] = &entry{
|
||||||
idx: len(seen),
|
idx: len(seen),
|
||||||
candidate: types.TenantInviteCandidate{
|
candidate: types.TenantInviteCandidate{
|
||||||
TenantID: u.TenantID,
|
TenantID: u.TenantID,
|
||||||
RepresentativeUserID: u.ID,
|
|
||||||
RepresentativeUsername: u.Username,
|
|
||||||
RepresentativeEmail: u.Email,
|
|
||||||
RepresentativeAvatar: u.Avatar,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -247,6 +247,35 @@ func (h *WikiPageHandler) KBCreatorLookupFromKBPath(c *gin.Context) (string, err
|
|||||||
return kb.CreatorID, nil
|
return kb.CreatorID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resolveKBCreatorByKBID resolves a KB id to CreatorID, scoped to the
|
||||||
|
// caller's tenant. Used by cross-KB handlers whose body carries kb_id
|
||||||
|
// instead of a URL param (batch-delete, move, etc.).
|
||||||
|
func resolveKBCreatorByKBID(
|
||||||
|
c *gin.Context,
|
||||||
|
kbService interfaces.KnowledgeBaseService,
|
||||||
|
kbID string,
|
||||||
|
) (string, error) {
|
||||||
|
ctx := c.Request.Context()
|
||||||
|
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
return "", errors.New("tenant context missing")
|
||||||
|
}
|
||||||
|
kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) {
|
||||||
|
return "", middleware.ErrResourceNotFound
|
||||||
|
}
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if kb == nil {
|
||||||
|
return "", middleware.ErrResourceNotFound
|
||||||
|
}
|
||||||
|
if kb.TenantID != tenantID {
|
||||||
|
return "", middleware.ErrResourceNotFound
|
||||||
|
}
|
||||||
|
return kb.CreatorID, nil
|
||||||
|
}
|
||||||
|
|
||||||
// resolveKBCreatorByKnowledgeID is the shared body for the knowledge /
|
// resolveKBCreatorByKnowledgeID is the shared body for the knowledge /
|
||||||
// chunk lookups. The service-layer chain helper does the tenant-scoped
|
// chunk lookups. The service-layer chain helper does the tenant-scoped
|
||||||
// fetch (knowledge -> KB) and returns repository sentinel errors;
|
// fetch (knowledge -> KB) and returns repository sentinel errors;
|
||||||
|
|||||||
@@ -219,13 +219,18 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
usersByID := h.hydrateUsers(c, rows)
|
usersByID := h.hydrateUsers(c, rows)
|
||||||
|
showShareLinks := types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleOwner)
|
||||||
resp := make([]types.TenantInvitationResponse, 0, len(rows))
|
resp := make([]types.TenantInvitationResponse, 0, len(rows))
|
||||||
for _, inv := range rows {
|
for _, inv := range rows {
|
||||||
// Within the tenant view we don't bother hydrating tenant name
|
// Within the tenant view we don't bother hydrating tenant name
|
||||||
// (the caller already knows the tenant). Pass an empty map.
|
// (the caller already knows the tenant). Pass an empty map.
|
||||||
// Use ...WithLink so management UI can re-display invite_url
|
// Share-link URLs embed the registration token — only Owners may
|
||||||
// for pending share-link rows (re-copy without revoking).
|
// re-copy them; other roles see metadata without invite_url.
|
||||||
resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))
|
if showShareLinks {
|
||||||
|
resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))
|
||||||
|
} else {
|
||||||
|
resp = append(resp, projectInvitation(inv, usersByID, nil))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"success": true,
|
"success": true,
|
||||||
|
|||||||
@@ -248,6 +248,54 @@ func rbacEnforcementEnabled(cfg *config.Config) bool {
|
|||||||
return cfg != nil && cfg.Tenant.IsRBACEnforced()
|
return cfg != nil && cfg.Tenant.IsRBACEnforced()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ErrOwnershipForbidden is returned by EvaluateOwnershipOrRole when the
|
||||||
|
// caller is neither the resource creator nor meets the minimum role.
|
||||||
|
var ErrOwnershipForbidden = errors.New("rbac: ownership or role insufficient")
|
||||||
|
|
||||||
|
// EvaluateOwnershipOrRole applies the same decision matrix as
|
||||||
|
// RequireOwnershipOrRole for handlers that resolve creator_id out-of-band
|
||||||
|
// (e.g. KB id carried in a JSON body rather than a URL param).
|
||||||
|
//
|
||||||
|
// Returns nil when access is allowed. ErrResourceNotFound means the
|
||||||
|
// handler should issue its own 404. ErrOwnershipForbidden maps to 403.
|
||||||
|
// Any other error is a transient lookup failure (503).
|
||||||
|
func EvaluateOwnershipOrRole(
|
||||||
|
ctx context.Context,
|
||||||
|
cfg *config.Config,
|
||||||
|
min types.TenantRole,
|
||||||
|
creatorID string,
|
||||||
|
lookupErr error,
|
||||||
|
) error {
|
||||||
|
role := types.TenantRoleFromContext(ctx)
|
||||||
|
if role.HasPermission(min) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if IsCrossTenantSuperuser(ctx, cfg) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !rbacEnforcementEnabled(cfg) {
|
||||||
|
uid, _ := types.UserIDFromContext(ctx)
|
||||||
|
logger.Warnf(ctx,
|
||||||
|
"[rbac] ownership/role would be checked (enforcement off, lookup skipped): user=%s have=%s need=%s",
|
||||||
|
uid, role, min)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(lookupErr, ErrResourceNotFound) {
|
||||||
|
return ErrResourceNotFound
|
||||||
|
}
|
||||||
|
if lookupErr != nil {
|
||||||
|
return lookupErr
|
||||||
|
}
|
||||||
|
uid, _ := types.UserIDFromContext(ctx)
|
||||||
|
if creatorID != "" && creatorID == uid {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
logger.Warnf(ctx,
|
||||||
|
"[rbac] ownership/role insufficient: user=%s have=%s need=%s creator=%q",
|
||||||
|
uid, role, min, creatorID)
|
||||||
|
return ErrOwnershipForbidden
|
||||||
|
}
|
||||||
|
|
||||||
// isCrossTenantSuperuser was moved to access.go (renamed to
|
// isCrossTenantSuperuser was moved to access.go (renamed to
|
||||||
// IsCrossTenantSuperuser, exported, and made flag-aware) so the same
|
// IsCrossTenantSuperuser, exported, and made flag-aware) so the same
|
||||||
// helper backs the X-Tenant-ID gate in auth.go and the RequireRole /
|
// helper backs the X-Tenant-ID gate in auth.go and the RequireRole /
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import (
|
|||||||
// 1. Add a *T field below + JSON tag (snake_case, must match the front-end key).
|
// 1. Add a *T field below + JSON tag (snake_case, must match the front-end key).
|
||||||
// 2. Extend the merge logic in service.UserService.UpdateUserPreferences.
|
// 2. Extend the merge logic in service.UserService.UpdateUserPreferences.
|
||||||
// 3. Surface the new knob in the frontend settings store.
|
// 3. Surface the new knob in the frontend settings store.
|
||||||
|
//
|
||||||
// No DB DDL is required — preferences is a single jsonb column.
|
// No DB DDL is required — preferences is a single jsonb column.
|
||||||
type UserPreferences struct {
|
type UserPreferences struct {
|
||||||
// EnableMemory mirrors the "开启记忆功能" switch in General Settings.
|
// EnableMemory mirrors the "开启记忆功能" switch in General Settings.
|
||||||
@@ -143,6 +144,9 @@ type OIDCAuthURLResponse struct {
|
|||||||
ProviderDisplayName string `json:"provider_display_name,omitempty"`
|
ProviderDisplayName string `json:"provider_display_name,omitempty"`
|
||||||
AuthorizationURL string `json:"authorization_url,omitempty"`
|
AuthorizationURL string `json:"authorization_url,omitempty"`
|
||||||
State string `json:"state,omitempty"`
|
State string `json:"state,omitempty"`
|
||||||
|
// Nonce is bound to an HttpOnly cookie on /auth/oidc/url and verified
|
||||||
|
// on callback; omitted from JSON so clients cannot replay it alone.
|
||||||
|
Nonce string `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type OIDCConfigResponse struct {
|
type OIDCConfigResponse struct {
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const oidcStateMaxAge = 10 * time.Minute
|
||||||
|
|
||||||
|
// OIDCStatePayload is the signed OIDC authorization state carried in the
|
||||||
|
// redirect URL and validated on callback.
|
||||||
|
type OIDCStatePayload struct {
|
||||||
|
Nonce string `json:"nonce"`
|
||||||
|
RedirectURI string `json:"redirect_uri,omitempty"`
|
||||||
|
IssuedAt int64 `json:"iat"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
oidcStateSecretOnce sync.Once
|
||||||
|
oidcStateSecret string
|
||||||
|
)
|
||||||
|
|
||||||
|
func oidcStateSigningKey() string {
|
||||||
|
oidcStateSecretOnce.Do(func() {
|
||||||
|
if envSecret := strings.TrimSpace(os.Getenv("JWT_SECRET")); envSecret != "" {
|
||||||
|
oidcStateSecret = envSecret
|
||||||
|
return
|
||||||
|
}
|
||||||
|
randomBytes := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(randomBytes); err != nil {
|
||||||
|
panic(fmt.Sprintf("failed to generate OIDC state signing key: %v", err))
|
||||||
|
}
|
||||||
|
oidcStateSecret = base64.StdEncoding.EncodeToString(randomBytes)
|
||||||
|
})
|
||||||
|
return oidcStateSecret
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignOIDCState returns a tamper-evident state token: base64url(payload).base64url(hmac).
|
||||||
|
func SignOIDCState(payload *OIDCStatePayload) (string, error) {
|
||||||
|
if payload == nil {
|
||||||
|
return "", errors.New("oidc state payload is required")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(payload.Nonce) == "" {
|
||||||
|
return "", errors.New("oidc state nonce is required")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(payload.RedirectURI) == "" {
|
||||||
|
return "", errors.New("oidc state redirect_uri is required")
|
||||||
|
}
|
||||||
|
if payload.IssuedAt == 0 {
|
||||||
|
payload.IssuedAt = time.Now().Unix()
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("marshal oidc state: %w", err)
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, []byte(oidcStateSigningKey()))
|
||||||
|
mac.Write(raw)
|
||||||
|
sig := mac.Sum(nil)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyOIDCState validates the HMAC and freshness of a state token.
|
||||||
|
func VerifyOIDCState(raw string) (*OIDCStatePayload, error) {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
parts := strings.Split(raw, ".")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return nil, errors.New("invalid oidc state format")
|
||||||
|
}
|
||||||
|
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode oidc state payload: %w", err)
|
||||||
|
}
|
||||||
|
sigBytes, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode oidc state signature: %w", err)
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, []byte(oidcStateSigningKey()))
|
||||||
|
mac.Write(payloadBytes)
|
||||||
|
if !hmac.Equal(mac.Sum(nil), sigBytes) {
|
||||||
|
return nil, errors.New("oidc state signature mismatch")
|
||||||
|
}
|
||||||
|
var payload OIDCStatePayload
|
||||||
|
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
|
||||||
|
return nil, fmt.Errorf("unmarshal oidc state: %w", err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(payload.RedirectURI) == "" {
|
||||||
|
return nil, errors.New("state.redirect_uri is required")
|
||||||
|
}
|
||||||
|
if payload.IssuedAt == 0 {
|
||||||
|
return nil, errors.New("state.iat is required")
|
||||||
|
}
|
||||||
|
issuedAt := time.Unix(payload.IssuedAt, 0)
|
||||||
|
if time.Since(issuedAt) > oidcStateMaxAge || time.Until(issuedAt) > time.Minute {
|
||||||
|
return nil, errors.New("oidc state expired or invalid timestamp")
|
||||||
|
}
|
||||||
|
return &payload, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSignAndVerifyOIDCState(t *testing.T) {
|
||||||
|
t.Setenv("JWT_SECRET", "test-oidc-state-secret")
|
||||||
|
oidcStateSecretOnce = sync.Once{}
|
||||||
|
oidcStateSecret = ""
|
||||||
|
|
||||||
|
state, err := SignOIDCState(&OIDCStatePayload{
|
||||||
|
Nonce: "nonce-abc",
|
||||||
|
RedirectURI: "http://localhost:5173/login",
|
||||||
|
IssuedAt: time.Now().Unix(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SignOIDCState: %v", err)
|
||||||
|
}
|
||||||
|
got, err := VerifyOIDCState(state)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("VerifyOIDCState: %v", err)
|
||||||
|
}
|
||||||
|
if got.Nonce != "nonce-abc" || got.RedirectURI != "http://localhost:5173/login" {
|
||||||
|
t.Fatalf("unexpected payload: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyOIDCStateRejectsTamperedPayload(t *testing.T) {
|
||||||
|
t.Setenv("JWT_SECRET", "test-oidc-state-secret")
|
||||||
|
oidcStateSecretOnce = sync.Once{}
|
||||||
|
oidcStateSecret = ""
|
||||||
|
|
||||||
|
state, err := SignOIDCState(&OIDCStatePayload{
|
||||||
|
Nonce: "nonce-abc",
|
||||||
|
RedirectURI: "http://localhost:5173/login",
|
||||||
|
IssuedAt: time.Now().Unix(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SignOIDCState: %v", err)
|
||||||
|
}
|
||||||
|
parts := strings.Split(state, ".")
|
||||||
|
tampered := parts[0] + ".AAAA"
|
||||||
|
if _, err := VerifyOIDCState(tampered); err == nil {
|
||||||
|
t.Fatal("expected tampered state to be rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -754,6 +754,24 @@ func DefaultSSRFSafeHTTPClientConfig() SSRFSafeHTTPClientConfig {
|
|||||||
// ErrSSRFRedirectBlocked is returned when a redirect target is blocked due to SSRF protection
|
// ErrSSRFRedirectBlocked is returned when a redirect target is blocked due to SSRF protection
|
||||||
var ErrSSRFRedirectBlocked = fmt.Errorf("redirect blocked: target URL failed SSRF validation")
|
var ErrSSRFRedirectBlocked = fmt.Errorf("redirect blocked: target URL failed SSRF validation")
|
||||||
|
|
||||||
|
// sameHTTPOrigin reports whether two URLs share scheme and host (port-aware).
|
||||||
|
func sameHTTPOrigin(a, b *url.URL) bool {
|
||||||
|
if a == nil || b == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// stripRedirectSensitiveHeaders removes credentials that must not follow a
|
||||||
|
// cross-host redirect (Go only strips Authorization/Cookie by default).
|
||||||
|
func stripRedirectSensitiveHeaders(req *http.Request) {
|
||||||
|
req.Header.Del("Authorization")
|
||||||
|
req.Header.Del("Cookie")
|
||||||
|
req.Header.Del("X-Auth-Token")
|
||||||
|
req.Header.Del("X-Api-Key")
|
||||||
|
req.Header.Del("Api-Key")
|
||||||
|
}
|
||||||
|
|
||||||
// NewSSRFSafeHTTPClient creates an HTTP client that validates redirect targets against SSRF protections.
|
// NewSSRFSafeHTTPClient creates an HTTP client that validates redirect targets against SSRF protections.
|
||||||
// This prevents SSRF attacks via HTTP redirects where an attacker's server redirects to internal services.
|
// This prevents SSRF attacks via HTTP redirects where an attacker's server redirects to internal services.
|
||||||
func NewSSRFSafeHTTPClient(config SSRFSafeHTTPClientConfig) *http.Client {
|
func NewSSRFSafeHTTPClient(config SSRFSafeHTTPClientConfig) *http.Client {
|
||||||
@@ -773,6 +791,12 @@ func NewSSRFSafeHTTPClient(config SSRFSafeHTTPClientConfig) *http.Client {
|
|||||||
return fmt.Errorf("stopped after %d redirects", config.MaxRedirects)
|
return fmt.Errorf("stopped after %d redirects", config.MaxRedirects)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Strip credentials when the redirect crosses hosts so connector
|
||||||
|
// tokens (e.g. Yuque X-Auth-Token) cannot leak to a third party.
|
||||||
|
if len(via) > 0 && !sameHTTPOrigin(via[0].URL, req.URL) {
|
||||||
|
stripRedirectSensitiveHeaders(req)
|
||||||
|
}
|
||||||
|
|
||||||
// Validate the redirect target URL for SSRF (whitelist-aware).
|
// Validate the redirect target URL for SSRF (whitelist-aware).
|
||||||
// Even whitelisted hosts must use http/https to prevent scheme-based attacks.
|
// Even whitelisted hosts must use http/https to prevent scheme-based attacks.
|
||||||
redirectScheme := strings.ToLower(req.URL.Scheme)
|
redirectScheme := strings.ToLower(req.URL.Scheme)
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSSRFSafeClientStripsAuthTokenOnCrossHostRedirect(t *testing.T) {
|
||||||
|
t.Setenv("SSRF_WHITELIST", "127.0.0.1,::1,localhost")
|
||||||
|
ResetSSRFWhitelistForTest()
|
||||||
|
t.Cleanup(ResetSSRFWhitelistForTest)
|
||||||
|
|
||||||
|
var gotToken string
|
||||||
|
attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotToken = r.Header.Get("X-Auth-Token")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
defer attacker.Close()
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/start", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, attacker.URL, http.StatusFound)
|
||||||
|
})
|
||||||
|
origin := httptest.NewServer(mux)
|
||||||
|
defer origin.Close()
|
||||||
|
|
||||||
|
client := NewSSRFSafeHTTPClient(SSRFSafeHTTPClientConfig{
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
MaxRedirects: 5,
|
||||||
|
})
|
||||||
|
req, err := http.NewRequest(http.MethodGet, origin.URL+"/start", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewRequest: %v", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("X-Auth-Token", "super-secret-yuque-token")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Do: %v", err)
|
||||||
|
}
|
||||||
|
resp.Body.Close()
|
||||||
|
|
||||||
|
if gotToken != "" {
|
||||||
|
t.Fatalf("X-Auth-Token leaked on cross-host redirect: %q", gotToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user