175 lines
5.2 KiB
Go
175 lines
5.2 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
// maxWebhookBodyBytes caps both the outgoing request body and the
|
|
// response body we are willing to read back from the session webhook.
|
|
maxWebhookBodyBytes = 1 << 20 // 1 MiB
|
|
defaultHTTPTimeout = 15 * time.Second
|
|
)
|
|
|
|
// WebhookSender posts replies to a DingTalk session webhook. It fails
|
|
// closed: only https URLs on port 443 without userinfo whose hostname is
|
|
// dingtalk.com or a subdomain are accepted, redirects are refused, and any
|
|
// non-2xx response is an error. This prevents answers from leaking to
|
|
// arbitrary public hosts (SSRF).
|
|
type WebhookSender struct {
|
|
client *http.Client
|
|
extraHosts map[string]bool // test-only additional allowed hostnames
|
|
validateURL func(string) error
|
|
}
|
|
|
|
// NewWebhookSender builds a sender. A nil client installs a hardened default
|
|
// (no redirects, sane timeout).
|
|
func NewWebhookSender(client *http.Client) (*WebhookSender, error) {
|
|
return newWebhookSender(client, nil)
|
|
}
|
|
|
|
func newWebhookSender(client *http.Client, extraHosts map[string]bool) (*WebhookSender, error) {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: defaultHTTPTimeout}
|
|
}
|
|
wrapped := *client
|
|
wrapped.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
return errors.New("dingtalk webhook redirects are not allowed")
|
|
}
|
|
sender := &WebhookSender{client: &wrapped, extraHosts: extraHosts}
|
|
sender.validateURL = func(raw string) error {
|
|
return sender.validate(raw)
|
|
}
|
|
return sender, nil
|
|
}
|
|
|
|
// newWebhookSenderForTest is used by tests to allow loopback TLS servers
|
|
// (any port) while exercising the exact same send/validation code path.
|
|
func newWebhookSenderForTest(client *http.Client, hosts ...string) (*WebhookSender, error) {
|
|
extra := make(map[string]bool, len(hosts))
|
|
for _, h := range hosts {
|
|
extra[strings.ToLower(h)] = true
|
|
}
|
|
sender, err := newWebhookSender(client, extra)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
base := sender.validateURL
|
|
sender.validateURL = func(raw string) error {
|
|
if err := base(raw); err == nil {
|
|
return nil
|
|
} else if !strings.Contains(err.Error(), "default port 443") {
|
|
return err
|
|
}
|
|
// Allow non-443 ports only for explicitly allow-listed test hosts.
|
|
u, parseErr := url.Parse(raw)
|
|
if parseErr != nil {
|
|
return parseErr
|
|
}
|
|
if u.Scheme != "https" || u.User != nil || !extra[strings.ToLower(u.Hostname())] {
|
|
return fmt.Errorf("dingtalk webhook URL must use default port 443, got %q", u.Port())
|
|
}
|
|
return nil
|
|
}
|
|
return sender, nil
|
|
}
|
|
|
|
// ValidateWebhookURL enforces the production webhook URL policy.
|
|
func ValidateWebhookURL(raw string) error {
|
|
return (&WebhookSender{}).validate(raw)
|
|
}
|
|
|
|
func (s *WebhookSender) validate(raw string) error {
|
|
if strings.TrimSpace(raw) == "" {
|
|
return errors.New("dingtalk webhook URL is empty")
|
|
}
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
return fmt.Errorf("dingtalk webhook URL parse: %w", err)
|
|
}
|
|
if u.Scheme != "https" {
|
|
return fmt.Errorf("dingtalk webhook URL must be https, got %q", u.Scheme)
|
|
}
|
|
if u.User != nil {
|
|
return errors.New("dingtalk webhook URL must not contain userinfo")
|
|
}
|
|
host := u.Hostname()
|
|
if host == "" {
|
|
return errors.New("dingtalk webhook URL must include a host")
|
|
}
|
|
port := u.Port()
|
|
if port != "" && port != "443" {
|
|
return fmt.Errorf("dingtalk webhook URL must use default port 443, got %q", port)
|
|
}
|
|
if !s.hostAllowed(host) {
|
|
return fmt.Errorf("dingtalk webhook host %q is not allowed", host)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *WebhookSender) hostAllowed(host string) bool {
|
|
host = strings.ToLower(host)
|
|
if ip := net.ParseIP(host); ip != nil {
|
|
return false
|
|
}
|
|
if host == "dingtalk.com" || strings.HasSuffix(host, ".dingtalk.com") {
|
|
return true
|
|
}
|
|
return s.extraHosts[host]
|
|
}
|
|
|
|
// SendMarkdown posts a markdown message to the session webhook.
|
|
func (s *WebhookSender) SendMarkdown(ctx context.Context, webhookURL, title, text string) error {
|
|
if err := s.validateURL(webhookURL); err != nil {
|
|
return err
|
|
}
|
|
if title == "" {
|
|
title = "DobotAI"
|
|
}
|
|
body, err := json.Marshal(map[string]any{
|
|
"msgtype": "markdown",
|
|
"markdown": map[string]string{
|
|
"title": title,
|
|
"text": text,
|
|
},
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("marshal dingtalk webhook payload: %w", err)
|
|
}
|
|
if len(body) > maxWebhookBodyBytes {
|
|
return errors.New("dingtalk webhook payload exceeds 1MiB")
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(body))
|
|
if err != nil {
|
|
return fmt.Errorf("build dingtalk webhook request: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := s.client.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("send dingtalk webhook: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxWebhookBodyBytes))
|
|
return fmt.Errorf("dingtalk webhook returned status %d", resp.StatusCode)
|
|
}
|
|
n, err := io.Copy(io.Discard, io.LimitReader(resp.Body, maxWebhookBodyBytes+1))
|
|
if err != nil {
|
|
return fmt.Errorf("read dingtalk webhook response: %w", err)
|
|
}
|
|
if n > maxWebhookBodyBytes {
|
|
return fmt.Errorf("dingtalk webhook response exceeds %d bytes", maxWebhookBodyBytes)
|
|
}
|
|
return nil
|
|
}
|