Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(security): close six open GHSA findings from security triage
wizardchenf23c674bad90
diff --git a/internal/application/service/user.go b/internal/application/service/user.goindex f31fae55b..79126242a 100644--- a/internal/application/service/user.go+++ b/internal/application/service/user.go@@ -27,11 +27,6 @@ import (secutils "github.com/Tencent/WeKnora/internal/utils")-type oidcAuthorizationState struct {- Nonce string `json:"nonce"`- RedirectURI string `json:"redirect_uri,omitempty"`-}-var (jwtSecretOnce sync.OncejwtSecret string@@ -367,7 +362,7 @@ func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI sreturn nil, fmt.Errorf("failed to generate state: %w", err)}- state, err := encodeOIDCAuthorizationState(&oidcAuthorizationState{+ state, err := secutils.SignOIDCState(&secutils.OIDCStatePayload{Nonce: nonce,RedirectURI: strings.TrimSpace(redirectURI),})@@ -394,6 +389,7 @@ func (s *userService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI sProviderDisplayName: cfg.ProviderDisplayName,AuthorizationURL: authURL,State: state,+ Nonce: nonce,}, nil}@@ -592,7 +588,13 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassuser.PasswordHash = string(hashedPassword)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@@ -1207,14 +1209,6 @@ func generateRandomString(length int) (string, error) {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) {parts := strings.Split(token, ".")if len(parts) < 2 {diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex ec571bef9..daea6466e 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -20,6 +20,9 @@ import (secutils "github.com/Tencent/WeKnora/internal/utils")+const oidcNonceCookieName = "weknora_oidc_nonce"+const oidcNonceCookieMaxAge = 600+// AuthHandler implements HTTP request handlers for user authentication// Provides functionality for user registration, login, logout, and token management// through the REST API endpoints@@ -249,6 +252,14 @@ func (h *AuthHandler) GetOIDCAuthorizationURL(c *gin.Context) {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)}@@ -301,12 +312,14 @@ func (h *AuthHandler) OIDCRedirectCallback(c *gin.Context) {}state := strings.TrimSpace(c.Query("state"))- decodedState, err := decodeOIDCState(state)+ decodedState, err := decodeOIDCState(state, c.Request)if err != nil {logger.Errorf(ctx, "Failed to decode OIDC state: %v", err)c.Redirect(http.StatusFound, frontendRedirectURI+"#oidc_error="+urlQueryEscape("invalid_state"))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"))if code == "" {@@ -344,23 +357,26 @@ func encodeOIDCCallbackPayload(resp *types.OIDCCallbackResponse) (string, error)}type oidcStatePayload struct {- Nonce string `json:"nonce"`- RedirectURI string `json:"redirect_uri,omitempty"`+ Nonce string+ RedirectURI string}-func decodeOIDCState(raw string) (*oidcStatePayload, error) {- decoded, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(raw))+func decodeOIDCState(raw string, req *http.Request) (*oidcStatePayload, error) {+ payload, err := secutils.VerifyOIDCState(raw)if err != nil {return nil, err}- var payload oidcStatePayload- if err := json.Unmarshal(decoded, &payload); err != nil {- return nil, err+ cookieNonce, err := req.Cookie(oidcNonceCookieName)+ if err != nil || cookieNonce == nil || strings.TrimSpace(cookieNonce.Value) == "" {+ return nil, errors.NewValidationError("oidc nonce cookie missing")}- if strings.TrimSpace(payload.RedirectURI) == "" {- return nil, errors.NewValidationError("state.redirect_uri is required")+ if cookieNonce.Value != payload.Nonce {+ 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 {@@ -713,6 +729,7 @@ func (h *AuthHandler) SwitchTenant(c *gin.Context) {c.JSON(http.StatusOK, dto.NewAuthLoginResponse(resp))}+// @Summary 自动初始化(Lite 桌面版)// @Description Lite 版专用:首次启动时自动创建默认用户和租户并返回令牌,后续启动直接签发令牌,免除手动注册/登录流程// @Tags 认证diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex e3f364cd9..591918283 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -16,8 +16,10 @@ import ("github.com/Tencent/WeKnora/internal/agent/tools""github.com/Tencent/WeKnora/internal/application/repository""github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/middleware""github.com/Tencent/WeKnora/internal/tracing/langfuse""github.com/Tencent/WeKnora/internal/types""github.com/Tencent/WeKnora/internal/types/interfaces"@@ -29,6 +31,7 @@ import (// KnowledgeHandler processes HTTP requests related to knowledge resourcestype KnowledgeHandler struct {+ cfg *config.ConfigkgService interfaces.KnowledgeServicekbService interfaces.KnowledgeBaseServicekbShareService interfaces.KBShareService@@ -39,6 +42,7 @@ type KnowledgeHandler struct {// NewKnowledgeHandler creates a new knowledge handler instancefunc NewKnowledgeHandler(+ cfg *config.Config,kgService interfaces.KnowledgeService,kbService interfaces.KnowledgeBaseService,kbShareService interfaces.KBShareService,@@ -47,6 +51,7 @@ func NewKnowledgeHandler(spanRepo repository.KnowledgeSpanRepository,) *KnowledgeHandler {return &KnowledgeHandler{+ cfg: cfg,kgService: kgService,kbService: kbService,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// using the ":id" URL path parameter. It delegates to validateKnowledgeBaseAccessWithKBID.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"))return}+ if err := h.requireKBOwnershipOrAdmin(c, kbID); err != nil {+ c.Error(err)+ return+ }ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)// 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"))return}+ if err := h.requireKBOwnershipOrAdmin(c, req.SourceKBID); err != nil {+ c.Error(err)+ return+ }// Validate target KBtargetKB, 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"))return}+ if err := h.requireKBOwnershipOrAdmin(c, req.TargetKBID); err != nil {+ c.Error(err)+ return+ }// Validate type matchif sourceKB.Type != targetKB.Type {diff --git a/internal/handler/organization.go b/internal/handler/organization.goindex 3a1aad5fd..c83dcf80e 100644--- a/internal/handler/organization.go+++ b/internal/handler/organization.go@@ -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// de-duplication after filtering "already a member" tenants still// 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)if err != nil {logger.Errorf(ctx, "Failed to search users: %v", err)@@ -1902,11 +1904,7 @@ func (h *OrganizationHandler) SearchTenantsForInvite(c *gin.Context) {seen[u.TenantID] = &entry{idx: len(seen),candidate: types.TenantInviteCandidate{- TenantID: u.TenantID,- RepresentativeUserID: u.ID,- RepresentativeUsername: u.Username,- RepresentativeEmail: u.Email,- RepresentativeAvatar: u.Avatar,+ TenantID: u.TenantID,},}}diff --git a/internal/handler/rbac_lookups.go b/internal/handler/rbac_lookups.goindex e586dbde7..5d5cf27cf 100644--- a/internal/handler/rbac_lookups.go+++ b/internal/handler/rbac_lookups.go@@ -247,6 +247,35 @@ func (h *WikiPageHandler) KBCreatorLookupFromKBPath(c *gin.Context) (string, errreturn 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 /// chunk lookups. The service-layer chain helper does the tenant-scoped// fetch (knowledge -> KB) and returns repository sentinel errors;diff --git a/internal/handler/tenant_invitation.go b/internal/handler/tenant_invitation.goindex bbe030957..e704fb469 100644--- a/internal/handler/tenant_invitation.go+++ b/internal/handler/tenant_invitation.go@@ -219,13 +219,18 @@ func (h *TenantInvitationHandler) ListTenantInvitations(c *gin.Context) {}usersByID := h.hydrateUsers(c, rows)+ showShareLinks := types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleOwner)resp := make([]types.TenantInvitationResponse, 0, len(rows))for _, inv := range rows {// Within the tenant view we don't bother hydrating tenant name// (the caller already knows the tenant). Pass an empty map.- // Use ...WithLink so management UI can re-display invite_url- // for pending share-link rows (re-copy without revoking).- resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))+ // Share-link URLs embed the registration token — only Owners may+ // re-copy them; other roles see metadata without invite_url.+ if showShareLinks {+ resp = append(resp, h.projectInvitationWithLink(inv, usersByID, nil))+ } else {+ resp = append(resp, projectInvitation(inv, usersByID, nil))+ }}c.JSON(http.StatusOK, gin.H{"success": true,diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.goindex 3155c1fe4..fa6d0242a 100644--- a/internal/middleware/rbac.go+++ b/internal/middleware/rbac.go@@ -248,6 +248,54 @@ func rbacEnforcementEnabled(cfg *config.Config) bool {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, exported, and made flag-aware) so the same// helper backs the X-Tenant-ID gate in auth.go and the RequireRole /diff --git a/internal/types/user.go b/internal/types/user.goindex dd2906259..a8ff93175 100644--- a/internal/types/user.go+++ b/internal/types/user.go@@ -19,6 +19,7 @@ import (// 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.// 3. Surface the new knob in the frontend settings store.+//// No DB DDL is required — preferences is a single jsonb column.type UserPreferences struct {// EnableMemory mirrors the "开启记忆功能" switch in General Settings.@@ -143,6 +144,9 @@ type OIDCAuthURLResponse struct {ProviderDisplayName string `json:"provider_display_name,omitempty"`AuthorizationURL string `json:"authorization_url,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 {diff --git a/internal/utils/oidc_state.go b/internal/utils/oidc_state.gonew file mode 100644index 000000000..1436da01c--- /dev/null+++ b/internal/utils/oidc_state.go@@ -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+}diff --git a/internal/utils/oidc_state_test.go b/internal/utils/oidc_state_test.gonew file mode 100644index 000000000..46233e1b4--- /dev/null+++ b/internal/utils/oidc_state_test.go@@ -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")+ }+}diff --git a/internal/utils/security.go b/internal/utils/security.goindex 0857444c7..c8b636dce 100644--- a/internal/utils/security.go+++ b/internal/utils/security.go@@ -754,6 +754,24 @@ func DefaultSSRFSafeHTTPClientConfig() SSRFSafeHTTPClientConfig {// ErrSSRFRedirectBlocked is returned when a redirect target is blocked due to SSRF protectionvar 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.// This prevents SSRF attacks via HTTP redirects where an attacker's server redirects to internal services.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)}+ // 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).// Even whitelisted hosts must use http/https to prevent scheme-based attacks.redirectScheme := strings.ToLower(req.URL.Scheme)diff --git a/internal/utils/security_redirect_test.go b/internal/utils/security_redirect_test.gonew file mode 100644index 000000000..1ba7b87cb--- /dev/null+++ b/internal/utils/security_redirect_test.go@@ -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)+ }+}