277 lines
9.1 KiB
Go
277 lines
9.1 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Tencent/WeKnora/internal/im"
|
|
)
|
|
|
|
func TestParseCallbackMessagePicture(t *testing.T) {
|
|
msg := &callbackMessage{
|
|
ConversationID: "cid-group",
|
|
ConversationType: dingtalkConvTypeGroup,
|
|
MsgID: "msg-picture-1",
|
|
Msgtype: "picture",
|
|
Content: []byte(`{"downloadCode":"download-code-1"}`),
|
|
SenderStaffId: "staff-1",
|
|
SenderNick: "Alice",
|
|
SessionWebhook: "https://example.invalid/session",
|
|
}
|
|
|
|
got := parseCallbackMessage(msg)
|
|
if got.MessageType != im.MessageTypeImage {
|
|
t.Fatalf("MessageType = %q, want image", got.MessageType)
|
|
}
|
|
if got.FileKey != "download-code-1" {
|
|
t.Fatalf("FileKey = %q, want download code", got.FileKey)
|
|
}
|
|
if got.FileName != "msg-picture-1.png" {
|
|
t.Fatalf("FileName = %q", got.FileName)
|
|
}
|
|
if got.Content != "" {
|
|
t.Fatalf("Content = %q, want empty", got.Content)
|
|
}
|
|
}
|
|
|
|
func TestAdapterDownloadFileUsesMessageFilesAPI(t *testing.T) {
|
|
var sawToken bool
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/v1.0/robot/messageFiles/download":
|
|
sawToken = r.Header.Get("x-acs-dingtalk-access-token") == "cached-access-token"
|
|
body, _ := io.ReadAll(r.Body)
|
|
if !strings.Contains(string(body), `"downloadCode":"download-code-1"`) || !strings.Contains(string(body), `"robotCode":"robot-code-1"`) {
|
|
t.Errorf("unexpected request body: %s", body)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"downloadUrl":"` + serverURLForRequest(r) + `/media/picture"}`))
|
|
case "/media/picture":
|
|
w.Header().Set("Content-Type", "image/png")
|
|
w.Header().Set("Content-Disposition", `attachment; filename="question.png"`)
|
|
_, _ = w.Write([]byte("PNGDATA"))
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
adapter := NewAdapter("robot-code-1", "secret", "")
|
|
adapter.token = "cached-access-token"
|
|
adapter.tokenExpAt = time.Now().Add(time.Hour)
|
|
adapter.messageFileDownloadURL = server.URL + "/v1.0/robot/messageFiles/download"
|
|
adapter.allowInsecureDownload = true
|
|
|
|
reader, fileName, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{
|
|
MessageType: im.MessageTypeImage,
|
|
MessageID: "msg-picture-1",
|
|
FileKey: "download-code-1",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("DownloadFile: %v", err)
|
|
}
|
|
defer reader.Close()
|
|
body, _ := io.ReadAll(reader)
|
|
if string(body) != "PNGDATA" {
|
|
t.Fatalf("body = %q", body)
|
|
}
|
|
if fileName != "question.png" {
|
|
t.Fatalf("fileName = %q", fileName)
|
|
}
|
|
if !sawToken {
|
|
t.Fatal("missing DingTalk access token header")
|
|
}
|
|
}
|
|
|
|
func serverURLForRequest(r *http.Request) string {
|
|
return "http://" + r.Host
|
|
}
|
|
|
|
func TestNormalizeDingTalkInitialDownloadURLUpgradesHTTPToHTTPS(t *testing.T) {
|
|
rawURL := "http://media.example.com/path/image.png?signature=abc%2F123&name=a+b.png"
|
|
got, err := normalizeDingTalkInitialDownloadURL(rawURL)
|
|
if err != nil {
|
|
t.Fatalf("normalizeDingTalkInitialDownloadURL: %v", err)
|
|
}
|
|
want := "https://media.example.com/path/image.png?signature=abc%2F123&name=a+b.png"
|
|
if got != want {
|
|
t.Fatalf("normalized URL = %q, want %q", got, want)
|
|
}
|
|
}
|
|
|
|
func TestValidateDingTalkDownloadURLRejectsUnsafeTargets(t *testing.T) {
|
|
for _, rawURL := range []string{
|
|
"http://example.com/image.png",
|
|
"https://user:pass@example.com/image.png",
|
|
"https://127.0.0.1/image.png",
|
|
"https://10.0.0.8/image.png",
|
|
} {
|
|
t.Run(rawURL, func(t *testing.T) {
|
|
if err := validateDingTalkDownloadURL(rawURL, false); err == nil {
|
|
t.Fatalf("unsafe URL accepted: %s", rawURL)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestParseCallbackMessagePictureWithoutDownloadCodeStaysImage(t *testing.T) {
|
|
for _, content := range [][]byte{[]byte(`{}`), []byte(`not-json`)} {
|
|
msg := parseCallbackMessage(&callbackMessage{MsgID: "bad-picture", Msgtype: "picture", Content: content})
|
|
if msg.MessageType != im.MessageTypeImage {
|
|
t.Fatalf("MessageType = %q, want image", msg.MessageType)
|
|
}
|
|
if msg.FileKey != "" {
|
|
t.Fatalf("FileKey = %q, want empty", msg.FileKey)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestAdapterDownloadFileDoesNotFollowCredentialedAPIRedirect(t *testing.T) {
|
|
var redirectedToken string
|
|
target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
|
redirectedToken = r.Header.Get("x-acs-dingtalk-access-token")
|
|
}))
|
|
defer target.Close()
|
|
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Location", target.URL)
|
|
w.WriteHeader(http.StatusTemporaryRedirect)
|
|
}))
|
|
defer api.Close()
|
|
|
|
adapter := NewAdapter("robot-code-1", "secret", "")
|
|
adapter.token = "cached-access-token"
|
|
adapter.tokenExpAt = time.Now().Add(time.Hour)
|
|
adapter.messageFileDownloadURL = api.URL
|
|
adapter.allowInsecureDownload = true
|
|
_, _, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{MessageType: im.MessageTypeImage, FileKey: "code"})
|
|
if err == nil {
|
|
t.Fatal("expected redirect rejection")
|
|
}
|
|
if redirectedToken != "" {
|
|
t.Fatal("access token leaked across redirect")
|
|
}
|
|
}
|
|
|
|
func TestAdapterDownloadFileAcceptsGenericMediaContentType(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/api" {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"downloadUrl":"` + serverURLForRequest(r) + `/media"}`))
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/octet-stream")
|
|
_, _ = w.Write([]byte("PNGDATA"))
|
|
}))
|
|
defer server.Close()
|
|
adapter := NewAdapter("robot", "secret", "")
|
|
adapter.token = "token"
|
|
adapter.tokenExpAt = time.Now().Add(time.Hour)
|
|
adapter.messageFileDownloadURL = server.URL + "/api"
|
|
adapter.allowInsecureDownload = true
|
|
body, _, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{MessageType: im.MessageTypeImage, FileKey: "code"})
|
|
if err != nil {
|
|
t.Fatalf("DownloadFile: %v", err)
|
|
}
|
|
body.Close()
|
|
}
|
|
|
|
func TestDingTalkAPIClientDisablesProxyAndRedirects(t *testing.T) {
|
|
a := &Adapter{}
|
|
client := a.newDingTalkAPIClient(httpClient)
|
|
transport, ok := client.Transport.(*http.Transport)
|
|
if !ok {
|
|
t.Fatalf("transport type = %T, want *http.Transport", client.Transport)
|
|
}
|
|
if transport.Proxy != nil {
|
|
t.Fatal("DingTalk API client must ignore environment proxies")
|
|
}
|
|
req := httptest.NewRequest(http.MethodPost, "https://api.dingtalk.com/redirect", nil)
|
|
if err := client.CheckRedirect(req, nil); !errors.Is(err, http.ErrUseLastResponse) {
|
|
t.Fatalf("redirect error = %v, want http.ErrUseLastResponse", err)
|
|
}
|
|
}
|
|
|
|
func TestDingTalkRedirectLimitFailsClosed(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodGet, "https://example.com/image.png", nil)
|
|
via := make([]*http.Request, 10)
|
|
if err := validateDingTalkRedirect(req, via, false); err == nil {
|
|
t.Fatal("validateDingTalkRedirect should reject more than 10 requests")
|
|
}
|
|
}
|
|
|
|
func TestDingTalkSafeDialUsesValidatedConcreteIP(t *testing.T) {
|
|
stop := errors.New("stop after address capture")
|
|
var dialed string
|
|
dial := newDingTalkSafeDialContext(
|
|
func(context.Context, string) ([]net.IPAddr, error) {
|
|
return []net.IPAddr{{IP: net.ParseIP("1.1.1.1")}}, nil
|
|
},
|
|
func(_ context.Context, _ string, addr string) (net.Conn, error) {
|
|
dialed = addr
|
|
return nil, stop
|
|
},
|
|
)
|
|
_, err := dial(context.Background(), "tcp", "cdn.example.test:443")
|
|
if !errors.Is(err, stop) {
|
|
t.Fatalf("dial error = %v, want sentinel", err)
|
|
}
|
|
if dialed != "1.1.1.1:443" {
|
|
t.Fatalf("dialed address = %q, want validated concrete IP", dialed)
|
|
}
|
|
}
|
|
|
|
func TestDingTalkSafeDialRejectsEveryRestrictedResolvedIP(t *testing.T) {
|
|
for _, rawIP := range []string{
|
|
"0.0.0.1",
|
|
"240.0.0.1",
|
|
"2001:0000::1",
|
|
"2002:7f00:0001::1",
|
|
} {
|
|
t.Run(rawIP, func(t *testing.T) {
|
|
dialCalled := false
|
|
dial := newDingTalkSafeDialContext(
|
|
func(context.Context, string) ([]net.IPAddr, error) {
|
|
return []net.IPAddr{{IP: net.ParseIP(rawIP)}}, nil
|
|
},
|
|
func(context.Context, string, string) (net.Conn, error) {
|
|
dialCalled = true
|
|
return nil, errors.New("must not dial")
|
|
},
|
|
)
|
|
if _, err := dial(context.Background(), "tcp", "cdn.example.test:443"); err == nil {
|
|
t.Fatal("restricted resolved IP was accepted")
|
|
}
|
|
if dialCalled {
|
|
t.Fatal("restricted resolved IP reached network dial")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAdapterDownloadFileRedactsSignedURLFromErrors(t *testing.T) {
|
|
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(`{"downloadUrl":"http://127.0.0.1:1/media?X-Amz-Signature=TOPSECRET"}`))
|
|
}))
|
|
defer api.Close()
|
|
adapter := NewAdapter("robot", "secret", "")
|
|
adapter.token = "token"
|
|
adapter.tokenExpAt = time.Now().Add(time.Hour)
|
|
adapter.messageFileDownloadURL = api.URL
|
|
adapter.allowInsecureDownload = true
|
|
_, _, err := adapter.DownloadFile(context.Background(), &im.IncomingMessage{MessageType: im.MessageTypeImage, FileKey: "code"})
|
|
if err == nil {
|
|
t.Fatal("expected download error")
|
|
}
|
|
if strings.Contains(err.Error(), "TOPSECRET") || strings.Contains(err.Error(), "X-Amz-Signature") {
|
|
t.Fatalf("signed URL leaked in error: %v", err)
|
|
}
|
|
}
|