227 lines
7.3 KiB
Go
227 lines
7.3 KiB
Go
package dingtalk
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func tinyPNG(t *testing.T) []byte {
|
|
t.Helper()
|
|
img := image.NewRGBA(image.Rect(0, 0, 2, 3))
|
|
for y := 0; y < 3; y++ {
|
|
for x := 0; x < 2; x++ {
|
|
img.Set(x, y, color.RGBA{R: 255, A: 255})
|
|
}
|
|
}
|
|
var out bytes.Buffer
|
|
if err := png.Encode(&out, img); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out.Bytes()
|
|
}
|
|
|
|
func TestNewImageDownloaderMissingCredentials(t *testing.T) {
|
|
for _, tc := range []struct{ id, secret string }{{"", "s"}, {"id", ""}, {" ", "s"}, {"id", " "}} {
|
|
if got, err := NewImageDownloader(tc.id, tc.secret, nil); err == nil || got != nil {
|
|
t.Fatalf("NewImageDownloader(%q,%q)=%v,%v", tc.id, tc.secret, got, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDownloadEmptyCodeReturnsError(t *testing.T) {
|
|
d, err := NewImageDownloader("id", "secret", nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, code := range []string{"", " "} {
|
|
if _, err := d.Download(context.Background(), code); err == nil {
|
|
t.Fatalf("Download(%q) should fail", code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestImageDownloaderTwoHopAndTokenCache(t *testing.T) {
|
|
pngBytes := tinyPNG(t)
|
|
var tokenCalls, fileCalls int
|
|
var server *httptest.Server
|
|
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/token":
|
|
tokenCalls++
|
|
var body map[string]string
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
if body["appKey"] != "client-id" || body["appSecret"] != "client-secret" {
|
|
t.Errorf("oauth body=%v", body)
|
|
}
|
|
if body["clientId"] != "" || body["clientSecret"] != "" {
|
|
t.Errorf("legacy OAuth field names must not be sent: %v", body)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"accessToken": "access-token", "expireIn": 3600})
|
|
case "/file":
|
|
fileCalls++
|
|
if r.Header.Get("x-acs-dingtalk-access-token") != "access-token" {
|
|
t.Errorf("token header missing")
|
|
}
|
|
var body map[string]string
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
if body["downloadCode"] != "download-code" || body["robotCode"] != "client-id" {
|
|
t.Errorf("file body=%v", body)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"downloadUrl": server.URL + "/image?signature=secret"})
|
|
case "/image":
|
|
w.Header().Set("Content-Type", "text/plain") // deliberately untrusted
|
|
_, _ = w.Write(pngBytes)
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
|
|
d, err := newImageDownloaderForTest("client-id", "client-secret", server.Client(), server.URL+"/token", server.URL+"/file")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for i := 0; i < 2; i++ {
|
|
got, err := d.Download(context.Background(), "download-code")
|
|
if err != nil {
|
|
t.Fatalf("Download: %v", err)
|
|
}
|
|
if got.MIMEType != "image/png" || got.Width != 2 || got.Height != 3 || got.SizeBytes != int64(len(pngBytes)) || !strings.HasPrefix(got.DataURI, "data:image/png;base64,") {
|
|
t.Fatalf("image=%+v", got)
|
|
}
|
|
}
|
|
if tokenCalls != 1 || fileCalls != 2 {
|
|
t.Fatalf("tokenCalls=%d fileCalls=%d", tokenCalls, fileCalls)
|
|
}
|
|
}
|
|
|
|
func TestImageDownloaderRejectsRedirectWithoutLeakingToken(t *testing.T) {
|
|
var leaked string
|
|
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
leaked = r.Header.Get("x-acs-dingtalk-access-token")
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}))
|
|
defer target.Close()
|
|
var source *httptest.Server
|
|
source = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/token" {
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"accessToken": "top-secret-token", "expireIn": 3600})
|
|
return
|
|
}
|
|
http.Redirect(w, r, target.URL, http.StatusFound)
|
|
}))
|
|
defer source.Close()
|
|
d, err := newImageDownloaderForTest("id", "secret", source.Client(), source.URL+"/token", source.URL+"/file")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := d.Download(context.Background(), "code"); err == nil {
|
|
t.Fatal("API redirect should fail")
|
|
}
|
|
if leaked != "" {
|
|
t.Fatalf("token leaked across redirect: %q", leaked)
|
|
}
|
|
}
|
|
|
|
func TestImageDownloaderRejectsInvalidImageAndOversize(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
contentType string
|
|
body []byte
|
|
length int64
|
|
}{
|
|
{name: "html disguised", contentType: "image/png", body: []byte("<html>not image</html>")},
|
|
{name: "oversized content length", contentType: "image/png", body: []byte("x"), length: maxImageBytes + 1},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
var server *httptest.Server
|
|
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Path {
|
|
case "/token":
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"accessToken": "token", "expireIn": 3600})
|
|
case "/file":
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"downloadUrl": server.URL + "/image?q=signed-secret"})
|
|
case "/image":
|
|
w.Header().Set("Content-Type", tt.contentType)
|
|
if tt.length > 0 {
|
|
w.Header().Set("Content-Length", "8388609")
|
|
}
|
|
_, _ = w.Write(tt.body)
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
d, _ := newImageDownloaderForTest("id", "secret", server.Client(), server.URL+"/token", server.URL+"/file")
|
|
_, err := d.Download(context.Background(), "download-secret")
|
|
if err == nil {
|
|
t.Fatal("expected rejection")
|
|
}
|
|
for _, secret := range []string{"download-secret", "signed-secret", "token"} {
|
|
if strings.Contains(err.Error(), secret) {
|
|
t.Fatalf("error leaked %q: %v", secret, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestNormalizeInitialDownloadURL(t *testing.T) {
|
|
got, err := normalizeInitialDownloadURL("http://example.com/media/path?signature=secret")
|
|
if err != nil {
|
|
t.Fatalf("normalize: %v", err)
|
|
}
|
|
if got != "https://example.com/media/path?signature=secret" {
|
|
t.Fatalf("normalized=%q", got)
|
|
}
|
|
for _, raw := range []string{"ftp://example.com/a", "http://user:pass@example.com/a", "not-a-url"} {
|
|
if _, err := normalizeInitialDownloadURL(raw); err == nil {
|
|
t.Fatalf("%q should fail", raw)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSafeDownloadIPRejectsNonPublicRanges(t *testing.T) {
|
|
for _, raw := range []string{"127.0.0.1", "10.0.0.1", "192.168.1.1", "169.254.1.1", "100.64.0.1", "192.0.2.1", "198.18.0.1", "203.0.113.1", "::1", "fc00::1", "2001:db8::1"} {
|
|
if isSafeDownloadIP(net.ParseIP(raw)) {
|
|
t.Errorf("%s must be rejected", raw)
|
|
}
|
|
}
|
|
for _, raw := range []string{"8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"} {
|
|
if !isSafeDownloadIP(net.ParseIP(raw)) {
|
|
t.Errorf("%s should be public", raw)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReadImageRejectsPixelLimit(t *testing.T) {
|
|
// A PNG only needs a valid signature+IHDR for DecodeConfig. Patch a valid
|
|
// tiny PNG's dimensions and let CRC become invalid: DecodeConfig must reject
|
|
// it or the pixel policy must reject it, either outcome is fail closed.
|
|
data := tinyPNG(t)
|
|
if len(data) < 24 {
|
|
t.Fatal("short png fixture")
|
|
}
|
|
copy(data[16:20], []byte{0, 0, 0x27, 0x10}) // 10000
|
|
copy(data[20:24], []byte{0, 0, 0x13, 0x88}) // 5000 = 50M
|
|
if _, err := validateImageBytes(data); err == nil {
|
|
t.Fatal("50M-pixel image must fail")
|
|
}
|
|
}
|
|
|
|
func TestBoundedAPIResponse(t *testing.T) {
|
|
resp := &http.Response{Body: io.NopCloser(io.LimitReader(strings.NewReader(strings.Repeat("x", maxAPIResponseBytes+1)), maxAPIResponseBytes+1))}
|
|
if _, err := readBoundedAPIResponse(resp); err == nil {
|
|
t.Fatal("oversized API response must fail")
|
|
}
|
|
}
|