fix(security): harden outbound requests and file previews

This commit is contained in:
wizardchen
2026-07-02 18:17:51 +08:00
committed by lyingbug
parent 7099a7e181
commit 663d13eb58
16 changed files with 546 additions and 110 deletions
+45 -3
View File
@@ -1,16 +1,29 @@
package mattermost
import (
"context"
"encoding/json"
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func withMattermostSSRFWhitelist(t *testing.T, whitelist string) {
t.Helper()
t.Setenv("SSRF_WHITELIST", whitelist)
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestParseOutgoingBody_ThreadRoot(t *testing.T) {
tests := []struct {
name string
payload outgoingPayload
name string
payload outgoingPayload
postReplyToMain bool
wantThreadRoot string
wantThreadRoot string
}{
{
name: "threaded reply has RootID",
@@ -60,6 +73,35 @@ func TestParseOutgoingBody_ThreadRoot(t *testing.T) {
}
}
func TestNewClientRejectsPrivateSiteURL(t *testing.T) {
withMattermostSSRFWhitelist(t, "")
if _, err := NewClient("http://127.0.0.1:8065", "bot-token"); err == nil {
t.Fatal("expected private Mattermost site_url to be rejected")
}
}
func TestMattermostClientBlocksRedirectToInternalURL(t *testing.T) {
withMattermostSSRFWhitelist(t, "127.0.0.1")
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer origin.Close()
client, err := NewClient(origin.URL, "bot-token")
if err != nil {
t.Fatalf("NewClient: %v", err)
}
_, err = client.CreatePost(context.Background(), "channel", "", "hello")
if err == nil {
t.Fatal("expected redirect to link-local metadata endpoint to be blocked")
}
if !stderrors.Is(err, secutils.ErrSSRFRedirectBlocked) {
t.Fatalf("error = %v, want ErrSSRFRedirectBlocked", err)
}
}
func TestParseOutgoingBody_JSON(t *testing.T) {
body := `{"token":"tok","user_id":"u1","user_name":"alice","channel_id":"ch1","post_id":"p1","text":"hello","root_id":"r1"}`
+20 -3
View File
@@ -7,8 +7,11 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
// Client calls Mattermost REST API v4.
@@ -25,14 +28,28 @@ func NewClient(siteURL, botToken string) (*Client, error) {
if siteURL == "" {
return nil, fmt.Errorf("site_url is required")
}
parsed, err := url.Parse(siteURL)
if err != nil || parsed.Host == "" {
return nil, fmt.Errorf("invalid site_url: must be a valid http(s) URL")
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return nil, fmt.Errorf("invalid site_url: must use http or https")
}
if err := secutils.ValidateURLForSSRF(siteURL); err != nil {
return nil, fmt.Errorf(
"invalid site_url: %w (for private Mattermost deployments, add the hostname to SSRF_WHITELIST)",
err,
)
}
if strings.TrimSpace(botToken) == "" {
return nil, fmt.Errorf("bot_token is required")
}
return &Client{
baseURL: siteURL + "/api/v4",
httpClient: &http.Client{
Timeout: 60 * time.Second,
},
httpClient: secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
Timeout: 60 * time.Second,
MaxRedirects: 5,
}),
token: strings.TrimSpace(botToken),
}, nil
}
+32
View File
@@ -5,8 +5,16 @@ import (
"testing"
"github.com/Tencent/WeKnora/internal/im"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
func withQQBotSSRFWhitelist(t *testing.T, whitelist string) {
t.Helper()
t.Setenv("SSRF_WHITELIST", whitelist)
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestParseGatewayPayloadC2CMessage(t *testing.T) {
event := messageEvent{
ID: "msg-1",
@@ -76,3 +84,27 @@ func TestParseExpiresIn(t *testing.T) {
})
}
}
func TestNewClientRejectsPrivateAPIBaseURL(t *testing.T) {
withQQBotSSRFWhitelist(t, "")
if _, err := NewClient("app", "secret", "http://127.0.0.1:8080", ""); err == nil {
t.Fatal("expected private qqbot api_base_url to be rejected")
}
}
func TestNewClientRejectsInsecureGatewayURL(t *testing.T) {
withQQBotSSRFWhitelist(t, "127.0.0.1")
if _, err := NewClient("app", "secret", "http://127.0.0.1:8080", "ws://127.0.0.1/gateway"); err == nil {
t.Fatal("expected non-wss qqbot gateway_url to be rejected")
}
}
func TestNewClientAllowsWhitelistedPrivateDeployment(t *testing.T) {
withQQBotSSRFWhitelist(t, "127.0.0.1")
if _, err := NewClient("app", "secret", "http://127.0.0.1:8080", "wss://127.0.0.1/gateway"); err != nil {
t.Fatalf("expected whitelisted private qqbot endpoints to pass: %v", err)
}
}
+56 -3
View File
@@ -6,9 +6,12 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
type Client struct {
@@ -35,12 +38,23 @@ func NewClient(appID, clientSecret, apiBaseURL, gatewayURL string) (*Client, err
if apiBaseURL == "" {
apiBaseURL = defaultAPIBaseURL
}
apiBaseURL = strings.TrimRight(strings.TrimSpace(apiBaseURL), "/")
if err := validateHTTPAPIBaseURL(apiBaseURL); err != nil {
return nil, err
}
gatewayURL = strings.TrimSpace(gatewayURL)
if err := validateGatewayURL(gatewayURL); err != nil {
return nil, err
}
return &Client{
appID: appID,
clientSecret: clientSecret,
apiBaseURL: strings.TrimRight(apiBaseURL, "/"),
gatewayURL: strings.TrimSpace(gatewayURL),
httpClient: &http.Client{Timeout: 15 * time.Second},
apiBaseURL: apiBaseURL,
gatewayURL: gatewayURL,
httpClient: secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
Timeout: 15 * time.Second,
MaxRedirects: 5,
}),
}, nil
}
@@ -55,9 +69,48 @@ func (c *Client) GatewayURL(ctx context.Context) (string, error) {
if result.URL == "" {
return "", fmt.Errorf("empty qqbot gateway url")
}
if err := validateGatewayURL(result.URL); err != nil {
return "", fmt.Errorf("invalid qqbot gateway url: %w", err)
}
return result.URL, nil
}
func validateHTTPAPIBaseURL(raw string) error {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return fmt.Errorf("invalid qqbot api_base_url: must be a valid http(s) URL")
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("invalid qqbot api_base_url: must use http or https")
}
if err := secutils.ValidateURLForSSRF(raw); err != nil {
return fmt.Errorf("invalid qqbot api_base_url: %w (for private deployments, add the hostname to SSRF_WHITELIST)", err)
}
return nil
}
func validateGatewayURL(raw string) error {
if strings.TrimSpace(raw) == "" {
return nil
}
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return fmt.Errorf("gateway_url must be a valid wss URL")
}
if u.Scheme != "wss" {
return fmt.Errorf("gateway_url must use wss")
}
checkURL := *u
checkURL.Scheme = "https"
if err := secutils.ValidateURLForSSRF(checkURL.String()); err != nil {
return fmt.Errorf(
"gateway_url failed SSRF validation: %w (for private deployments, add the hostname to SSRF_WHITELIST)",
err,
)
}
return nil
}
func (c *Client) SendC2CMessage(ctx context.Context, openID, content, msgID string) error {
path := fmt.Sprintf("/v2/users/%s/messages", openID)
return c.sendText(ctx, path, content, msgID)