High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
test: the Windows-arm source guard matches a string literal, so the idiomatic PlatformWindows spelling defeats it (PIN-139)
Luigi Agosti57e8a605bcac
diff --git a/internal/stealth/ua_test.go b/internal/stealth/ua_test.goindex 15cd732b..f488e0a6 100644--- a/internal/stealth/ua_test.go+++ b/internal/stealth/ua_test.go@@ -1,9 +1,16 @@package stealthimport (- "os"+ "fmt"+ "go/ast"+ "go/parser"+ "go/token""os/exec"+ "path/filepath"+ "reflect"goruntime "runtime"+ "slices"+ "sort""strings""testing")@@ -67,52 +74,389 @@ func TestWindowsPlatformVersionIsNotDerivedFromTheHostBecauseChromeSendsAnAPICont.Errorf("PlatformVersionFor(%q) = %q, want the frozen %q that matches what Chrome sends", "Windows", got, want)}- // The assertion above cannot see the edit this test exists to stop. A Windows+ // The assertions above cannot see the edit this test exists to stop. A Windows// arm gated on GOOS == "windows" — the shape a contributor "completing the// switch" would write — never executes on a macOS or Linux runner, so calling// hostPlatformVersion here returns empty either way and the guard would pass on// every machine this project actually tests on. The arms themselves are what// must be checked, and reading them is GOOS-independent.- raw, err := os.ReadFile("ua.go")+ //+ // Read as a syntax tree rather than as text. A text scan for "Windows" is+ // defeated by the tidier spelling the file itself argues for — the exported+ // PlatformWindows constant — and by any third spelling (a local alias, a helper+ // call). Resolving comparisons through the package's own constants makes the+ // check spelling-independent, and it is what lets the anti-degradation half+ // below tell a genuine loss of the host read from a contributor rewriting the+ // existing arms with those same constants, which a literal scan reports as a+ // missing arm — a failure message asserting something untrue.+ // Package-scoped, not file-scoped: the rule is that nothing in this package+ // reads a host fact for Windows, and a guard that reads only ua.go states a+ // rule wider than it checks — the same scope gap that let the text scan miss a+ // helper one call away.+ sources, fileSet := parsePackageSources(t)+ platformNames := packageStringConstants(t, sources)+ readers := hostReadingDeclarations(t, sources)+ arms, defaultReturnsEmpty := hostPlatformVersionArms(t, sources, fileSet, platformNames, readers)++ // Check 1 — which platforms the switch answers for, by resolved value. Any+ // third arm is the regression however its platform is named.+ got := make([]string, 0, len(arms))+ for _, arm := range arms {+ if arm.platform == "" {+ t.Errorf("the arm at %s compares uaDataPlatform against an expression this guard cannot resolve to a platform name.\n"++ "Spell it as a string literal or one of the Platform* constants: an arm whose platform cannot be read is an arm this guard cannot police.", arm.where)+ }+ got = append(got, fmt.Sprintf("%s/%s", arm.platform, arm.goos))+ }+ sort.Strings(got)+ want := []string{PlatformLinux + "/linux", PlatformMacOS + "/darwin"}+ if !reflect.DeepEqual(got, want) {+ t.Errorf("hostPlatformVersion answers for %v, want exactly %v.\n"++ "Chrome derives Sec-CH-UA-Platform-Version on Windows from the UniversalApiContract version, not the OS version, "++ "so any host-derived value there is one real Chrome never sends. Leave Windows on the frozen default. "++ "Each arm must also keep its GOOS pairing: without it the arm reads this host's version while claiming another platform.", got, want)+ }+ if !defaultReturnsEmpty {+ t.Errorf("hostPlatformVersion's default arm no longer returns the empty string.\n" ++ "A default that delegates is how a Windows host read hides from a check on the arms: the switch keeps two arms and " ++ "the read moves one call away. Every platform without an arm must fall through to the frozen default in PlatformVersionFor.")+ }++ // Check 2 — the host readers are exactly the two known ones. A new+ // host-reading helper is the other way a Windows read arrives, and it is+ // invisible to any check that only looks at hostPlatformVersion.+ gotReaders := make([]string, 0, len(readers))+ for name := range readers {+ gotReaders = append(gotReaders, name)+ }+ sort.Strings(gotReaders)+ wantReaders := []string{"hostKernelVersion", "hostProductVersion"}+ if !reflect.DeepEqual(gotReaders, wantReaders) {+ t.Errorf("the package's host-fact readers are %v, want exactly %v.\n"++ "A third reader means some platform learned to read this host; on Windows that advertises the OS version "++ "(something like 10.0.26100) as Sec-CH-UA-Platform-Version, which real Chrome never sends.", gotReaders, wantReaders)+ }++ // Check 3 — each reader is called exactly once, from the arm for its own+ // platform. This is what survives indirection: moving a read into a helper,+ // into an early return above the switch, or up into PlatformVersionFor all show+ // up as a call site that is not the one arm allowed to have it. It also keeps+ // the parent card's anti-degradation rule, which is about the two arms reading+ // the RIGHT value — the behavioural oracle cannot check that, because it+ // exercises the macOS arm only on a macOS machine and the suite runs on Linux.+ for _, expected := range []struct{ platform, reader, why string }{+ {PlatformMacOS, "hostProductVersion", "Chrome reports the macOS product version (sw_vers -productVersion) through UA-CH, not the Darwin kernel release"},+ {PlatformLinux, "hostKernelVersion", "Chrome derives the Linux platformVersion from the kernel release (uname -r), not from a distro product version"},+ } {+ sites := callSitesOf(sources, fileSet, expected.reader)+ if len(sites) != 1 {+ t.Errorf("%s is called from %d places (%s), want exactly 1 — the %s arm of hostPlatformVersion.\n"++ "A second call site is a host read for some other platform, wherever it is written.",+ expected.reader, len(sites), strings.Join(sites, ", "), expected.platform)+ continue+ }+ arm, ok := armFor(arms, expected.platform)+ if !ok {+ t.Errorf("hostPlatformVersion has no %s arm, so this test would be pinning an empty switch rather than the Windows exception", expected.platform)+ continue+ }+ if !slices.Contains(arm.reads, expected.reader) {+ t.Errorf("the %s arm reads %v, want %s.\n%s", expected.platform, arm.reads, expected.reader, expected.why)+ }+ }+}++// platformArm is one case of hostPlatformVersion's switch, with the platform and+// GOOS it compares against resolved to their values, so the constant and the+// literal spelling of the same arm are indistinguishable here.+type platformArm struct {+ platform string+ goos string+ reads []string+ where string+}++func armFor(arms []platformArm, platform string) (platformArm, bool) {+ for _, arm := range arms {+ if arm.platform == platform {+ return arm, true+ }+ }+ return platformArm{}, false+}++// hostFactImport is the package every host read here goes through today. It is+// named rather than derived so that swapping the dependency reds this test — the+// census below would otherwise quietly become empty.+const hostFactImport = "host"++// parsePackageSources parses every non-test file of this package, so a host read+// added in a sibling file is inside the census rather than outside it.+func parsePackageSources(t *testing.T) (map[string]*ast.File, *token.FileSet) {+ t.Helper()+ paths, err := filepath.Glob("*.go")if err != nil {t.Fatal(err)}- body := string(raw)[strings.Index(string(raw), "func hostPlatformVersion("):]- if end := strings.Index(body, "\nfunc "); end >= 0 {- body = body[:end]+ fileSet := token.NewFileSet()+ sources := map[string]*ast.File{}+ importsHostFacts := false+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.go") {+ continue+ }+ file, err := parser.ParseFile(fileSet, path, nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", path, err)+ }+ sources[path] = file+ for _, spec := range file.Imports {+ if strings.HasSuffix(strings.Trim(spec.Path.Value, `"`), "/"+hostFactImport) {+ importsHostFacts = true+ }+ }+ }+ if len(sources) < 2 {+ t.Fatalf("parsed %d package files; the census matched almost nothing and would pass vacuously", len(sources))}- if strings.Contains(body, `"Windows"`) {- t.Errorf("hostPlatformVersion gained a Windows arm:\n%s\n"+- "Chrome derives Sec-CH-UA-Platform-Version on Windows from the UniversalApiContract version, not the OS version, "+- "so any host-derived value there is one real Chrome never sends. Leave Windows on the frozen default.", body)- }- // Each arm must also read the RIGHT host value, and that has to be checked here- // rather than behaviourally, for the same reason the Windows arm does. The- // behavioural oracle switches on GOOS, so it exercises the macOS arm only on a- // macOS machine — and the Go suite runs on ubuntu alone, so swapping the darwin- // arm to the kernel release is green in CI and reds only on a developer's laptop.- // Measured: with hostKernelVersion() there, macOS reports 25.5.0 against a host- // product version of 26.5.1, while a Linux container runs the whole package green.- // Which value each platform reads is the substance of this feature: Chrome sends- // the product version on macOS and the kernel release on Linux, and the two are- // easy to swap because both are "the host version".- for _, arm := range []struct{ condition, reads, why string }{- {`"macOS" && goruntime.GOOS == "darwin"`, "hostProductVersion()", "Chrome reports the macOS product version (sw_vers -productVersion) through UA-CH, not the Darwin kernel release"},- {`"Linux" && goruntime.GOOS == "linux"`, "hostKernelVersion()", "Chrome derives the Linux platformVersion from the kernel release (uname -r), not from a distro product version"},- } {- i := strings.Index(body, arm.condition)- if i < 0 {- t.Errorf("hostPlatformVersion no longer reads the host for %s; this test would then be pinning an empty switch rather than the Windows exception", arm.condition)+ if !importsHostFacts {+ t.Fatalf("no file in this package imports a %q package; the host-reader census has nothing to key on and would pass vacuously", hostFactImport)+ }+ return sources, fileSet+}++func packageStringConstants(t *testing.T, sources map[string]*ast.File) map[string]string {+ t.Helper()+ values := map[string]string{}+ for _, decl := range allDeclarations(sources) {+ gen, ok := decl.(*ast.GenDecl)+ if !ok || gen.Tok != token.CONST {continue}- rest := body[i:]- if end := strings.Index(rest, "\n\tcase "); end >= 0 {- rest = rest[:end]+ for _, spec := range gen.Specs {+ value, ok := spec.(*ast.ValueSpec)+ if !ok {+ continue+ }+ for i, name := range value.Names {+ if i >= len(value.Values) {+ continue+ }+ if resolved, ok := stringValueOf(value.Values[i], values); ok {+ values[name.Name] = resolved+ }+ }}- if !strings.Contains(rest, arm.reads) {- t.Errorf("the %s arm no longer reads %s:\n%s\n%s", arm.condition, arm.reads, rest, arm.why)+ }+ if len(values) == 0 {+ t.Fatal("no string constants found in ua.go; the arms below could not be resolved through the platform vocabulary")+ }+ return values+}++// stringValueOf resolves a string literal, a reference to an already-known+// constant, or a + chain of either. The + chain matters: a contributor can spell a+// platform name as "Win" + "dows" and defeat any check that only reads literals.+func stringValueOf(expr ast.Expr, known map[string]string) (string, bool) {+ switch typed := expr.(type) {+ case *ast.BasicLit:+ if typed.Kind == token.STRING {+ return strings.Trim(typed.Value, `"`), true+ }+ case *ast.Ident:+ if value, ok := known[typed.Name]; ok {+ return value, true+ }+ case *ast.BinaryExpr:+ if typed.Op != token.ADD {+ return "", false+ }+ left, okLeft := stringValueOf(typed.X, known)+ right, okRight := stringValueOf(typed.Y, known)+ if okLeft && okRight {+ return left + right, true+ }+ }+ return "", false+}++// hostReadingDeclarations is the derived set of package declarations that read a+// host fact: any top-level function or var whose body reaches the host package.+// Derived rather than listed so a new reader appears here without anyone+// remembering to add it.+func hostReadingDeclarations(t *testing.T, sources map[string]*ast.File) map[string]bool {+ t.Helper()+ readers := map[string]bool{}+ readsHost := func(node ast.Node) bool {+ reads := false+ ast.Inspect(node, func(n ast.Node) bool {+ selector, ok := n.(*ast.SelectorExpr)+ if !ok {+ return true+ }+ if ident, ok := selector.X.(*ast.Ident); ok && ident.Name == hostFactImport {+ reads = true+ }+ return true+ })+ return reads+ }+ for _, decl := range allDeclarations(sources) {+ switch typed := decl.(type) {+ case *ast.FuncDecl:+ if typed.Body != nil && readsHost(typed.Body) {+ readers[typed.Name.Name] = true+ }+ case *ast.GenDecl:+ if typed.Tok != token.VAR {+ continue+ }+ for _, spec := range typed.Specs {+ value, ok := spec.(*ast.ValueSpec)+ if !ok {+ continue+ }+ for i, name := range value.Names {+ if i < len(value.Values) && readsHost(value.Values[i]) {+ readers[name.Name] = true+ }+ }+ }+ }+ }+ if len(readers) == 0 {+ t.Fatal("no declaration in this package reads the host package; this census has nothing to constrain and would pass vacuously")+ }+ return readers+}++// hostPlatformVersionArms resolves hostPlatformVersion's switch into arms. A+// missing function is reported as such: the previous text-slicing version indexed+// on the function's name and panicked with a slice-bounds error when a careful+// rename updated production and the direct call but left the scan's literal stale.+func hostPlatformVersionArms(t *testing.T, sources map[string]*ast.File, fileSet *token.FileSet, platformNames map[string]string, readers map[string]bool) ([]platformArm, bool) {+ t.Helper()+ var decl *ast.FuncDecl+ for _, candidate := range allDeclarations(sources) {+ if fn, ok := candidate.(*ast.FuncDecl); ok && fn.Name.Name == "hostPlatformVersion" {+ decl = fn+ }+ }+ if decl == nil {+ t.Fatal("this package declares no hostPlatformVersion; if it was renamed, update this guard to the new name — it is the one place the Windows exception is enforced")+ }++ isGOOS := func(expr ast.Expr) bool {+ selector, ok := expr.(*ast.SelectorExpr)+ return ok && selector.Sel.Name == "GOOS"+ }++ var arms []platformArm+ defaultReturnsEmpty := false+ for _, statement := range decl.Body.List {+ switchStatement, ok := statement.(*ast.SwitchStmt)+ if !ok {+ continue+ }+ for _, clause := range switchStatement.Body.List {+ caseClause, ok := clause.(*ast.CaseClause)+ if !ok {+ continue+ }+ if caseClause.List == nil {+ defaultReturnsEmpty = returnsEmptyString(caseClause.Body)+ continue+ }+ position := fileSet.Position(caseClause.Pos())+ arm := platformArm{where: fmt.Sprintf("%s:%d", filepath.Base(position.Filename), position.Line)}+ for _, condition := range caseClause.List {+ ast.Inspect(condition, func(n ast.Node) bool {+ binary, ok := n.(*ast.BinaryExpr)+ if !ok || binary.Op != token.EQL {+ return true+ }+ for _, pair := range [][2]ast.Expr{{binary.X, binary.Y}, {binary.Y, binary.X}} {+ value, resolved := stringValueOf(pair[1], platformNames)+ if !resolved {+ continue+ }+ if isGOOS(pair[0]) {+ arm.goos = value+ } else if ident, ok := pair[0].(*ast.Ident); ok && ident.Name == "uaDataPlatform" {+ arm.platform = value+ }+ }+ return true+ })+ }+ ast.Inspect(&ast.BlockStmt{List: caseClause.Body}, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ if ident, ok := call.Fun.(*ast.Ident); ok && readers[ident.Name] {+ arm.reads = append(arm.reads, ident.Name)+ }+ return true+ })+ arms = append(arms, arm)+ }+ }+ if len(arms) == 0 {+ t.Fatal("hostPlatformVersion has no switch arms to read; this guard would pass vacuously")+ }+ return arms, defaultReturnsEmpty+}++func returnsEmptyString(body []ast.Stmt) bool {+ if len(body) != 1 {+ return false+ }+ statement, ok := body[0].(*ast.ReturnStmt)+ if !ok || len(statement.Results) != 1 {+ return false+ }+ literal, ok := statement.Results[0].(*ast.BasicLit)+ return ok && literal.Kind == token.STRING && literal.Value == `""`+}++// allDeclarations flattens the package's declarations in a stable file order, so+// every census below reads the whole package rather than one file.+func allDeclarations(sources map[string]*ast.File) []ast.Decl {+ names := make([]string, 0, len(sources))+ for name := range sources {+ names = append(names, name)+ }+ sort.Strings(names)+ var decls []ast.Decl+ for _, name := range names {+ decls = append(decls, sources[name].Decls...)+ }+ return decls+}++// callSitesOf reports every call to name in the package as "file:enclosing:line",+// so a second call site is named where the reader can open it.+func callSitesOf(sources map[string]*ast.File, fileSet *token.FileSet, name string) []string {+ var sites []string+ for _, decl := range allDeclarations(sources) {+ enclosing := "package-level var"+ if fn, ok := decl.(*ast.FuncDecl); ok {+ enclosing = fn.Name.Name}+ ast.Inspect(decl, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ if ident, ok := call.Fun.(*ast.Ident); ok && ident.Name == name {+ position := fileSet.Position(call.Pos())+ sites = append(sites, fmt.Sprintf("%s:%s:%d", filepath.Base(position.Filename), enclosing, position.Line))+ }+ return true+ })}+ return sites}func TestPlatformVersionForForeignPlatformUsesDefault(t *testing.T) {