fix: select random browser user agents for outbound HTTP

This commit is contained in:
ji ruo committed 2026-11-11 19:13:38 +08:00
1 parent 17c2fc5e08
commit 171db405dd
18 files changed
+205 -71

No files matched your search

+31 -17
View File
@@ -2,36 +2,50 @@
package httpidentity
import (
"crypto/rand"
"io"
"math/big"
"net/http"
"os"
"strings"
)
// UserAgent returns the configured value, or an empty string to omit the header.
// Use printable ASCII for consistent behavior across Go and the Python templates.
// Ignore malformed values rather than allowing header injection.
// Keep these valid browser UA samples in sync with the standalone Python
// templates. Select whole samples rather than inventing incompatible versions.
var userAgents = [...]string{
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0",
"Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
}
// UserAgent returns the configured printable ASCII value, or a random browser
// sample when unset, empty or malformed. Call once per logical request and reuse
// the selected value for redirects and retries.
func UserAgent() string {
value := strings.Trim(os.Getenv("ARTEX_HTTP_USER_AGENT"), " ")
for _, c := range value {
if c < 32 || c > 126 {
return ""
return randomUserAgent(rand.Reader)
}
}
return value
if value != "" {
return value
}
return randomUserAgent(rand.Reader)
}
// Apply must set even an empty value: deleting the header makes net/http send
// its own Go-http-client default instead of omitting User-Agent on the wire.
func randomUserAgent(source io.Reader) string {
index, err := rand.Int(source, big.NewInt(int64(len(userAgents))))
if err != nil {
return userAgents[0] // Keep a valid nonempty UA if system entropy fails.
}
return userAgents[index.Int64()]
}
// Apply selects an identity for this request; net/http preserves it on redirects.
func Apply(req *http.Request) {
req.Header.Set("User-Agent", UserAgent())
}
// ApplyRequired keeps a nonempty, generic library identity for services that
// require User-Agent (notably the GitHub API), without an ARTEX identifier.
func ApplyRequired(req *http.Request) {
value := UserAgent()
if value == "" {
value = "Go-http-client/1.1"
}
req.Header.Set("User-Agent", value)
}
+18 -4
View File
@@ -1,8 +1,10 @@
package httpidentity
import (
"bytes"
"net/http"
"net/http/httptest"
"slices"
"testing"
)
@@ -17,12 +19,12 @@ func TestApplyOnWire(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("ARTEX_HTTP_USER_AGENT", tc.value)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("User-Agent"); got != tc.want {
got := r.UserAgent()
if tc.want == "" && !slices.Contains(userAgents[:], got) {
t.Errorf("default User-Agent is not a browser sample: %q", got)
} else if tc.want != "" && got != tc.want {
t.Errorf("User-Agent = %q, want %q", got, tc.want)
}
if _, present := r.Header["User-Agent"]; tc.want == "" && present {
t.Error("empty User-Agent must be absent on the wire")
}
if r.Header.Get("X-Injected") != "" {
t.Error("header injection")
}
@@ -41,3 +43,15 @@ func TestApplyOnWire(t *testing.T) {
})
}
}
func TestRandomUserAgentSelection(t *testing.T) {
// Exercise every choice deterministically without a statistical/flaky test.
for index, want := range userAgents {
if got := randomUserAgent(bytes.NewReader([]byte{byte(index)})); got != want {
t.Errorf("choice %d = %q, want %q", index, got, want)
}
}
if got := randomUserAgent(bytes.NewReader(nil)); got != userAgents[0] {
t.Errorf("entropy failure fallback = %q", got)
}
}
+1 -1
View File
@@ -122,7 +122,6 @@ func staticAssetExt(rawURL string) string {
}
func webFetchRunner(cfg actool.WebFetchConfig) func(context.Context, json.RawMessage, *actool.ToolContext) (actool.Result, error) {
userAgent := httpidentity.UserAgent()
client := newFetchClient(cfg)
// direct is the no-proxy fallback used when a proxied fetch fails for a
// proxy-caused reason (closed tunnel / failed CONNECT / TLS or HTTP2 mismatch):
@@ -152,6 +151,7 @@ func webFetchRunner(cfg actool.WebFetchConfig) func(context.Context, json.RawMes
if err != nil {
return actool.Errorf("Error: " + err.Error()), nil
}
userAgent := httpidentity.UserAgent()
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
// One direct retry when the proxied attempt failed for a proxy-caused reason.
+32 -3
View File
@@ -12,6 +12,7 @@ import (
"path/filepath"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -37,13 +38,21 @@ func TestIdentityAcrossRoutes(t *testing.T) {
t.Run(route+"/"+ua, func(t *testing.T) {
t.Setenv("ARTEX_HTTP_USER_AGENT", ua)
var targetCalls, proxyCalls atomic.Int32
var mu sync.Mutex
var selected string
checkUA := func(r *http.Request) {
if got := r.Header.Get("User-Agent"); got != ua {
mu.Lock()
defer mu.Unlock()
got := r.UserAgent()
if ua == "" && !strings.HasPrefix(got, "Mozilla/5.0 ") {
t.Errorf("random UA missing: %q", got)
} else if ua != "" && got != ua {
t.Errorf("User-Agent = %q, want %q", got, ua)
}
if _, present := r.Header["User-Agent"]; ua == "" && present {
t.Error("empty User-Agent present on wire")
if selected != "" && selected != got {
t.Errorf("redirect/retry UA changed from %q to %q", selected, got)
}
selected = got
}
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
targetCalls.Add(1)
@@ -137,6 +146,26 @@ func TestTLSAndStaticAssetGuard(t *testing.T) {
}
}
func TestIdentitySelectedForEachCall(t *testing.T) {
t.Setenv("ARTEX_HTTP_USER_AGENT", "Before-Tool-Creation")
tool := New(actool.WebFetchConfig{})
seen := make(chan string, 2)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen <- r.UserAgent()
fmt.Fprint(w, "ok")
}))
defer server.Close()
for _, want := range []string{"First-Call", "Second-Call"} {
t.Setenv("ARTEX_HTTP_USER_AGENT", want)
if result := callFetch(t, tool, server.URL, false); result.IsError {
t.Fatal(result.Flatten())
}
if got := <-seen; got != want {
t.Fatalf("identity cached across calls: got %q, want %q", got, want)
}
}
}
func TestSDKMetadataPreserved(t *testing.T) {
base := actool.NewWebFetch(actool.WebFetchConfig{})
local := New(actool.WebFetchConfig{})