feat(proxy): 支持品赞分组代理与自动白名单
This commit is contained in:
@@ -0,0 +1,283 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestIPZanRequestURLSetsRequestedCount(t *testing.T) {
|
||||
raw := "https://service.ipzan.com/core-extract?num=1&minute=10&protocol=1&secret=x"
|
||||
got, err := NewIPZanProvider().RequestURL(raw, 6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got, "num=6") || strings.Contains(got, "num=1") {
|
||||
t.Fatalf("RequestURL() = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPZanParseTextMultiple(t *testing.T) {
|
||||
body := []byte("1.2.3.4:8001\r\n5.6.7.8:8002\r\n")
|
||||
got, err := NewIPZanProvider().Parse(
|
||||
"https://service.ipzan.com/core-extract?protocol=3",
|
||||
body,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("len=%d, want 2", len(got))
|
||||
}
|
||||
if got[0].URL != "socks5://1.2.3.4:8001" {
|
||||
t.Fatalf("URL=%q", got[0].URL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPZanParseJSONError(t *testing.T) {
|
||||
body := []byte(`{"code":-1,"data":null,"status":200,"message":"请先将1.2.3.4加入到白名单再进行提取"}`)
|
||||
_, err := NewIPZanProvider().Parse("https://service.ipzan.com/core-extract", body)
|
||||
if err == nil || !IsFatal(err) {
|
||||
t.Fatalf("expected fatal provider error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPZanParseJSONList(t *testing.T) {
|
||||
body := []byte(`{"code":0,"status":200,"data":{"list":[{"ip":"1.2.3.4","port":8001,"account":"user-a","password":"pass-a","expired":1893456000000},{"ip":"5.6.7.8","port":"8002"}]}}`)
|
||||
got, err := NewIPZanProvider().Parse(
|
||||
"https://service.ipzan.com/core-extract?protocol=1",
|
||||
body,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0].URL != "http://user-a:pass-a@1.2.3.4:8001" || got[1].URL != "http://5.6.7.8:8002" {
|
||||
t.Fatalf("unexpected endpoints: %#v", got)
|
||||
}
|
||||
if got[0].ExpiresAt != time.UnixMilli(1893456000000) {
|
||||
t.Fatalf("ExpiresAt=%v", got[0].ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericParseJSONListWithAuth(t *testing.T) {
|
||||
body := []byte(`{"code":0,"data":{"list":[{"ip":"1.2.3.4","port":9000,"username":"u","password":"p"}]}}`)
|
||||
got, err := NewGenericProvider().Parse("https://example.test/api", body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].URL != "http://u:p@1.2.3.4:9000" {
|
||||
t.Fatalf("unexpected endpoints: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericParseIPZanAccountPasswordSample(t *testing.T) {
|
||||
body := []byte(`{"data":{"list":[{"ip":"203.0.113.10","port":"15471","expired":1893456000000,"net":"电信","account":"test-account","password":"test-password"}]},"code":0,"message":"","status":200}`)
|
||||
got, err := NewGenericProvider().Parse("https://example.test/api?protocol=1", body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("len=%d, want 1", len(got))
|
||||
}
|
||||
if got[0].URL != "http://test-account:test-password@203.0.113.10:15471" {
|
||||
t.Fatalf("URL=%q", got[0].URL)
|
||||
}
|
||||
if got[0].Username != "test-account" || got[0].Password != "test-password" {
|
||||
t.Fatalf("credentials not parsed: %#v", got[0])
|
||||
}
|
||||
if got[0].ExpiresAt != time.UnixMilli(1893456000000) {
|
||||
t.Fatalf("ExpiresAt=%v", got[0].ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericProviderDoesNotTreatErrorIPAsProxy(t *testing.T) {
|
||||
body := []byte(`{"code":-1,"status":200,"message":"请先将1.2.3.4加入白名单"}`)
|
||||
_, err := NewGenericProvider().Parse("https://example.test/api", body)
|
||||
if err == nil || !IsFatal(err) {
|
||||
t.Fatalf("expected fatal provider error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenericProviderParsesLegacyJSONData(t *testing.T) {
|
||||
body := []byte(`{"status":100,"info":"成功","data":[{"ip":"1.2.3.4","port":"8001","prov":"浙江","city":"嘉兴"}]}`)
|
||||
got, err := NewGenericProvider().Parse("https://example.test/api", body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].URL != "http://1.2.3.4:8001" || got[0].Region != "浙江 嘉兴" {
|
||||
t.Fatalf("unexpected endpoints: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return fn(req)
|
||||
}
|
||||
|
||||
type autoWhitelistTestProvider struct {
|
||||
parseCalls int
|
||||
addedIP string
|
||||
}
|
||||
|
||||
func (p *autoWhitelistTestProvider) ID() string { return "test" }
|
||||
|
||||
func (p *autoWhitelistTestProvider) Match(*url.URL) bool { return true }
|
||||
|
||||
func (p *autoWhitelistTestProvider) RequestURL(apiURL string, count int) (string, error) {
|
||||
return apiURL, nil
|
||||
}
|
||||
|
||||
func (p *autoWhitelistTestProvider) Parse(string, []byte) ([]Endpoint, error) {
|
||||
p.parseCalls++
|
||||
if p.parseCalls == 1 {
|
||||
return nil, &ProviderError{
|
||||
Provider: "test",
|
||||
Message: "请先将1.2.3.4加入白名单再提取",
|
||||
Fatal: true,
|
||||
}
|
||||
}
|
||||
return []Endpoint{{URL: "http://1.2.3.4:9000", IP: "1.2.3.4"}}, nil
|
||||
}
|
||||
|
||||
func (p *autoWhitelistTestProvider) EnsureWhitelist(context.Context, *http.Client, WhitelistConfig) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *autoWhitelistTestProvider) AddWhitelist(_ context.Context, _ *http.Client, cfg WhitelistConfig) error {
|
||||
p.addedIP = cfg.IP
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestExtractWithWhitelistUsesProviderReportedIP(t *testing.T) {
|
||||
provider := &autoWhitelistTestProvider{}
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader("probe")),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
service := NewServiceWithProviders(client, provider)
|
||||
got, err := service.ExtractWithWhitelist(
|
||||
context.Background(),
|
||||
"https://example.test/extract",
|
||||
1,
|
||||
WhitelistConfig{AutoWhitelist: true},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if provider.addedIP != "1.2.3.4" {
|
||||
t.Fatalf("addedIP=%q", provider.addedIP)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("len=%d, want 1", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceSelectsIPZanProvider(t *testing.T) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if got := req.URL.Query().Get("num"); got != "3" {
|
||||
t.Fatalf("num=%q, want 3", got)
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader("1.2.3.4:8001\r\n5.6.7.8:8002\r\n9.9.9.9:8003")),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}
|
||||
service := NewServiceWithProviders(client, NewIPZanProvider(), NewGenericProvider())
|
||||
got, err := service.Extract(
|
||||
context.Background(),
|
||||
"https://service.ipzan.com/core-extract?num=1&protocol=1&secret=x",
|
||||
3,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("len=%d, want 3", len(got))
|
||||
}
|
||||
if got[0].Provider != "ipzan" {
|
||||
t.Fatalf("provider=%q, want ipzan", got[0].Provider)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPZanEnsureWhitelistSignsAndAdds(t *testing.T) {
|
||||
const (
|
||||
loginPassword = "login-pass"
|
||||
secret = "extract-secret"
|
||||
signKey = "0123456789abcdef"
|
||||
publicIP = "1.2.3.4"
|
||||
)
|
||||
fixedNow := time.Unix(1700000000, 0)
|
||||
var addCalled bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/whiteList-verify":
|
||||
if r.URL.Query().Get("no") != "plan-no" || r.URL.Query().Get("ip") != publicIP {
|
||||
t.Fatalf("unexpected verify query: %s", r.URL.RawQuery)
|
||||
}
|
||||
io.WriteString(w, `{"code":0,"data":false,"status":200,"message":""}`)
|
||||
case "/whiteList-add":
|
||||
addCalled = true
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Form.Get("replace") != "1" {
|
||||
t.Fatalf("replace=%q", r.Form.Get("replace"))
|
||||
}
|
||||
encrypted, err := hex.DecodeString(r.Form.Get("sign"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block, err := aes.NewCipher([]byte(signKey))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decrypted := make([]byte, len(encrypted))
|
||||
for offset := 0; offset < len(encrypted); offset += block.BlockSize() {
|
||||
block.Decrypt(decrypted[offset:offset+block.BlockSize()], encrypted[offset:offset+block.BlockSize()])
|
||||
}
|
||||
padding := int(decrypted[len(decrypted)-1])
|
||||
plain := string(decrypted[:len(decrypted)-padding])
|
||||
if want := loginPassword + ":" + secret + ":1700000000"; plain != want {
|
||||
t.Fatalf("sign plain=%q, want %q", plain, want)
|
||||
}
|
||||
io.WriteString(w, `{"code":0,"data":true,"status":200,"message":""}`)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
provider := &IPZanProvider{
|
||||
baseURL: server.URL,
|
||||
now: func() time.Time { return fixedNow },
|
||||
}
|
||||
err := provider.EnsureWhitelist(
|
||||
context.Background(),
|
||||
server.Client(),
|
||||
WhitelistConfig{
|
||||
APIURL: "https://service.ipzan.com/core-extract?no=plan-no&secret=" + secret,
|
||||
IP: publicIP,
|
||||
LoginPassword: loginPassword,
|
||||
SignKey: signKey,
|
||||
ReplaceOldest: true,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !addCalled {
|
||||
t.Fatal("whiteList-add was not called")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user