Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

26.3 KB
Raw Blame
package config

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func TestValidateBrowserProxy_TableDriven(t *testing.T) {
	tests := []struct {
		name    string
		proxy   BrowserProxyConfig
		wantErr bool
		wantSub string
	}{
		{name: "empty disables proxy", proxy: BrowserProxyConfig{}},
		{name: "good http",
			proxy: BrowserProxyConfig{Server: "http://proxy.example.com:8080"}},
		{name: "good https",
			proxy: BrowserProxyConfig{Server: "https://proxy.example.com:8443"}},
		{name: "good socks5",
			proxy: BrowserProxyConfig{Server: "socks5://10.0.0.1:1080"}},
		{name: "good socks4",
			proxy: BrowserProxyConfig{Server: "socks4://10.0.0.1:1080"}},
		{name: "good with bypass list",
			proxy: BrowserProxyConfig{
				Server:     "http://proxy.example.com:8080",
				BypassList: []string{"*.local", "127.0.0.1"},
			}},
		{name: "good with credentials",
			proxy: BrowserProxyConfig{
				Server:   "http://proxy.example.com:8080",
				Username: "alice",
				Password: "s3cr3t",
			}},
		{name: "bad scheme",
			proxy:   BrowserProxyConfig{Server: "ftp://proxy.example.com:21"},
			wantErr: true, wantSub: "scheme"},
		{name: "missing scheme",
			proxy:   BrowserProxyConfig{Server: "proxy.example.com:8080"},
			wantErr: true, wantSub: "scheme"},
		{name: "missing host",
			proxy:   BrowserProxyConfig{Server: "http://:8080"},
			wantErr: true, wantSub: "host"},
		{name: "missing port",
			proxy:   BrowserProxyConfig{Server: "http://proxy.example.com"},
			wantErr: true, wantSub: "host:port"},
		{name: "port out of range",
			proxy:   BrowserProxyConfig{Server: "http://proxy.example.com:99999"},
			wantErr: true, wantSub: "port"},
		{name: "embedded credentials rejected",
			proxy:   BrowserProxyConfig{Server: "http://user:[email protected]:8080"},
			wantErr: true, wantSub: "embedded credentials"},
		{name: "username without password",
			proxy: BrowserProxyConfig{
				Server:   "http://proxy.example.com:8080",
				Username: "alice",
			},
			wantErr: true, wantSub: "password is required"},
		{name: "password without username",
			proxy: BrowserProxyConfig{
				Server:   "http://proxy.example.com:8080",
				Password: "secret",
			},
			wantErr: true, wantSub: "username is required"},
		{name: "bypass with whitespace",
			proxy: BrowserProxyConfig{
				Server:     "http://proxy.example.com:8080",
				BypassList: []string{"foo bar"},
			},
			wantErr: true, wantSub: "whitespace"},
		{name: "bypass with semicolon",
			proxy: BrowserProxyConfig{
				Server:     "http://proxy.example.com:8080",
				BypassList: []string{"a;b"},
			},
			wantErr: true, wantSub: "';'"},
		{name: "empty bypass entry",
			proxy: BrowserProxyConfig{
				Server:     "http://proxy.example.com:8080",
				BypassList: []string{""},
			},
			wantErr: true, wantSub: "must not be empty"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			errs := ValidateBrowserProxy("browser.proxy", tt.proxy)
			if tt.wantErr {
				if len(errs) == 0 {
					t.Fatalf("expected validation error, got none")
				}
				if tt.wantSub != "" {
					joined := ""
					for _, e := range errs {
						joined += e.Error() + "\n"
					}
					if !strings.Contains(joined, tt.wantSub) {
						t.Errorf("expected error to contain %q, got: %s", tt.wantSub, joined)
					}
				}
				return
			}
			if len(errs) > 0 {
				t.Fatalf("unexpected validation errors: %v", errs)
			}
		})
	}
}

func TestValidateBrowserProxy_GeoBlock(t *testing.T) {
	t.Run("good geo accepted", func(t *testing.T) {
		errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo: &BrowserProxyGeoConfig{
				Timezone:   "Europe/London",
				Locale:     "en-GB",
				WebRTCIP:   "203.0.113.7",
				CountryISO: "GB",
			},
		})
		if len(errs) != 0 {
			t.Fatalf("expected no errors, got %v", errs)
		}
	})
	t.Run("bad timezone rejected", func(t *testing.T) {
		errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo:    &BrowserProxyGeoConfig{Timezone: "Not/AZone"},
		})
		if len(errs) == 0 {
			t.Fatal("expected validation error for bad timezone")
		}
	})
	t.Run("bad locale rejected", func(t *testing.T) {
		errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo:    &BrowserProxyGeoConfig{Locale: "EN-gb"},
		})
		if len(errs) == 0 {
			t.Fatal("expected validation error for bad locale")
		}
	})
	t.Run("bad webrtc IP rejected", func(t *testing.T) {
		errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo:    &BrowserProxyGeoConfig{WebRTCIP: "not-an-ip"},
		})
		if len(errs) == 0 {
			t.Fatal("expected validation error for bad webrtc IP")
		}
	})
	t.Run("empty geo block accepted", func(t *testing.T) {
		errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo:    &BrowserProxyGeoConfig{},
		})
		if len(errs) != 0 {
			t.Fatalf("empty geo should not fail validation, got %v", errs)
		}
	})
}

func TestMigrateLegacyBrowserConfig_GeoCarriesIntoSynthesizedTarget(t *testing.T) {
	bc := &BrowserConfig{
		Provider: BrowserChrome,
		Proxy: BrowserProxyConfig{
			Server: "http://proxy.example.com:8080",
			Geo: &BrowserProxyGeoConfig{
				Timezone: "Europe/London",
				Locale:   "en-GB",
			},
		},
	}
	synthesized, conflict := migrateLegacyBrowserConfig(bc, "")
	if !synthesized || conflict {
		t.Fatalf("expected synthesized=true conflict=false, got %v/%v", synthesized, conflict)
	}
	target, ok := bc.Targets[DefaultBrowserTargetName]
	if !ok {
		t.Fatal("default target not synthesized")
	}
	if target.Proxy.Geo == nil {
		t.Fatal("geo block missing from synthesized target")
	}
	if target.Proxy.Geo.Timezone != "Europe/London" || target.Proxy.Geo.Locale != "en-GB" {
		t.Errorf("geo not migrated correctly: %+v", target.Proxy.Geo)
	}
}

func TestBrowserProxyRedacted(t *testing.T) {
	t.Run("masks non-empty password", func(t *testing.T) {
		p := BrowserProxyConfig{
			Server:     "http://proxy.example.com:8080",
			BypassList: []string{"*.local"},
			Username:   "alice",
			Password:   "s3cr3t",
		}
		r := p.Redacted()
		if r.Password != "***" {
			t.Errorf("expected redacted password '***', got %q", r.Password)
		}
		if p.Password != "s3cr3t" {
			t.Errorf("original password mutated: %q", p.Password)
		}
		if r.Server != p.Server || r.Username != p.Username {
			t.Errorf("non-secret fields mutated: %+v", r)
		}
		if len(r.BypassList) != 1 || r.BypassList[0] != "*.local" {
			t.Errorf("bypass list lost: %+v", r.BypassList)
		}
		r.BypassList[0] = "mutated"
		if p.BypassList[0] != "*.local" {
			t.Errorf("redaction did not deep-copy bypass list")
		}
	})

	t.Run("empty password stays empty", func(t *testing.T) {
		p := BrowserProxyConfig{Server: "http://proxy.example.com:8080"}
		r := p.Redacted()
		if r.Password != "" {
			t.Errorf("expected empty password, got %q", r.Password)
		}
	})
}

func TestBrowserProxyFlags(t *testing.T) {
	t.Run("disabled proxy emits no flags", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{})
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(flags) != 0 {
			t.Fatalf("expected no flags, got %v", flags)
		}
	})

	t.Run("server only", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{Server: "http://proxy.example.com:8080"})
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(flags) != 1 {
			t.Fatalf("expected 1 flag, got %v", flags)
		}
		want := "--proxy-server=http://proxy.example.com:8080"
		if flags[0] != want {
			t.Errorf("want %q, got %q", want, flags[0])
		}
	})

	t.Run("with bypass list", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{
			Server:     "socks5://10.0.0.1:1080",
			BypassList: []string{"*.local", "127.0.0.1"},
		})
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(flags) != 2 {
			t.Fatalf("expected 2 flags, got %v", flags)
		}
		if flags[0] != "--proxy-server=socks5://10.0.0.1:1080" {
			t.Errorf("unexpected flag[0]: %q", flags[0])
		}
		if flags[1] != "--proxy-bypass-list=*.local;127.0.0.1" {
			t.Errorf("unexpected flag[1]: %q", flags[1])
		}
	})

	t.Run("ipv6 host stays bracketed", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{Server: "http://[2001:db8::1]:8080"})
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if len(flags) != 1 {
			t.Fatalf("expected 1 flag, got %v", flags)
		}
		if flags[0] != "--proxy-server=http://[2001:db8::1]:8080" {
			t.Errorf("unexpected IPv6 proxy flag: %q", flags[0])
		}
	})

	t.Run("credentials never leak into flag", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{
			Server:   "http://proxy.example.com:8080",
			Username: "alice",
			Password: "s3cr3t",
		})
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		for _, f := range flags {
			if strings.Contains(f, "alice") || strings.Contains(f, "s3cr3t") {
				t.Errorf("credential leaked into Chrome flag: %q", f)
			}
		}
	})

	// M2 regression: a malformed server must fail closed — launching without
	// the configured proxy would egress traffic from the real IP.
	t.Run("malformed server fails closed", func(t *testing.T) {
		flags, err := BrowserProxyFlags(BrowserProxyConfig{Server: "not a proxy url"})
		if err == nil {
			t.Fatalf("expected error for malformed server, got flags %v", flags)
		}
		if !strings.Contains(err.Error(), "refusing to launch") {
			t.Fatalf("error should name the fail-closed consequence: %v", err)
		}
		if len(flags) != 0 {
			t.Fatalf("no flags expected on error, got %v", flags)
		}
	})
}

func TestMigrateLegacyBrowserConfig_ProxyCarriesIntoSynthesizedTarget(t *testing.T) {
	bc := &BrowserConfig{
		Provider: BrowserChrome,
		Proxy: BrowserProxyConfig{
			Server:   "http://proxy.example.com:8080",
			Username: "alice",
			Password: "s3cr3t",
		},
	}
	synthesized, conflict := migrateLegacyBrowserConfig(bc, "")
	if !synthesized || conflict {
		t.Fatalf("expected synthesized=true conflict=false, got synthesized=%v conflict=%v", synthesized, conflict)
	}
	target, ok := bc.Targets[DefaultBrowserTargetName]
	if !ok {
		t.Fatalf("default target was not synthesized")
	}
	if target.Proxy.Server != "http://proxy.example.com:8080" {
		t.Errorf("proxy server not migrated, got %q", target.Proxy.Server)
	}
	if target.Proxy.Password != "s3cr3t" {
		t.Errorf("proxy password not migrated, got %q", target.Proxy.Password)
	}
}

func TestApplyTargetOverride_TargetProxyReplacesGlobal(t *testing.T) {
	cfg := &RuntimeConfig{
		DefaultBrowser: BrowserChrome,
		Proxy: BrowserProxyConfig{
			Server:     "http://global.example.com:8080",
			Username:   "global-user",
			Password:   "global-pass",
			BypassList: []string{"*.global.test"},
		},
		Targets: BrowserTargetsConfig{
			"with-proxy": {
				Provider: BrowserChrome,
				Proxy: BrowserProxyConfig{
					Server:     "socks5://target.example.com:1080",
					BypassList: []string{"*.target.test"},
				},
			},
			"inherits": {
				Provider: BrowserChrome,
			},
		},
	}

	t.Run("target proxy replaces global entirely", func(t *testing.T) {
		out := ApplyTargetOverride(cfg, "with-proxy")
		if out.Proxy.Server != "socks5://target.example.com:1080" {
			t.Errorf("server not overridden, got %q", out.Proxy.Server)
		}
		if out.Proxy.Username != "" || out.Proxy.Password != "" {
			t.Errorf("global credentials leaked into target proxy: %+v", out.Proxy)
		}
		if len(out.Proxy.BypassList) != 1 || out.Proxy.BypassList[0] != "*.target.test" {
			t.Errorf("target bypass list not used: %+v", out.Proxy.BypassList)
		}
		if cfg.Proxy.Server != "http://global.example.com:8080" {
			t.Errorf("input cfg.Proxy mutated: %+v", cfg.Proxy)
		}
	})

	t.Run("target without proxy inherits global", func(t *testing.T) {
		out := ApplyTargetOverride(cfg, "inherits")
		if out.Proxy.Server != "http://global.example.com:8080" {
			t.Errorf("expected to inherit global, got %q", out.Proxy.Server)
		}
		if out.Proxy.Username != "global-user" {
			t.Errorf("expected to inherit global credentials")
		}
	})
}

func TestApplyFileConfigToRuntime_ProxyGeoCopied(t *testing.T) {
	cfg := &RuntimeConfig{}
	fc := &FileConfig{
		Browser: BrowserConfig{
			Proxy: BrowserProxyConfig{
				Server: "http://proxy.example.com:8080",
				Geo: &BrowserProxyGeoConfig{
					Timezone:   "Europe/London",
					Locale:     "en-GB",
					WebRTCIP:   "203.0.113.7",
					CountryISO: "GB",
				},
			},
		},
	}

	ApplyFileConfigToRuntime(cfg, fc)

	if cfg.Proxy.Geo == nil {
		t.Fatal("proxy geo was not copied to runtime config")
	}
	if *cfg.Proxy.Geo != *fc.Browser.Proxy.Geo {
		t.Fatalf("runtime proxy geo = %+v, want %+v", *cfg.Proxy.Geo, *fc.Browser.Proxy.Geo)
	}
	fc.Browser.Proxy.Geo.Timezone = "America/New_York"
	if cfg.Proxy.Geo.Timezone != "Europe/London" {
		t.Fatalf("runtime proxy geo aliases file config: %+v", cfg.Proxy.Geo)
	}
}

func TestFileConfig_ProxyRoundTrip(t *testing.T) {
	t.Run("proxy omitted when empty", func(t *testing.T) {
		fc := FileConfig{
			Browser: BrowserConfig{Provider: BrowserChrome},
		}
		raw, err := json.Marshal(fc)
		if err != nil {
			t.Fatalf("marshal: %v", err)
		}
		if strings.Contains(string(raw), `"proxy"`) {
			t.Errorf("empty proxy should be omitted, got: %s", string(raw))
		}
	})

	t.Run("geo omitted when nil", func(t *testing.T) {
		fc := FileConfig{
			Browser: BrowserConfig{
				Provider: BrowserChrome,
				Proxy: BrowserProxyConfig{
					Server: "http://proxy.example.com:8080",
				},
			},
		}
		raw, err := json.Marshal(fc)
		if err != nil {
			t.Fatalf("marshal: %v", err)
		}
		if strings.Contains(string(raw), `"geo"`) {
			t.Errorf("nil geo should be omitted, got: %s", string(raw))
		}
	})

	t.Run("geo round-trips when configured", func(t *testing.T) {
		fc := FileConfig{
			Browser: BrowserConfig{
				Provider: BrowserChrome,
				Proxy: BrowserProxyConfig{
					Server: "http://proxy.example.com:8080",
					Geo: &BrowserProxyGeoConfig{
						Timezone:   "Europe/London",
						Locale:     "en-GB",
						WebRTCIP:   "203.0.113.7",
						CountryISO: "GB",
					},
				},
			},
		}
		raw, err := json.Marshal(fc)
		if err != nil {
			t.Fatalf("marshal: %v", err)
		}
		var rt FileConfig
		if err := json.Unmarshal(raw, &rt); err != nil {
			t.Fatalf("unmarshal: %v", err)
		}
		if rt.Browser.Proxy.Geo == nil {
			t.Fatal("geo lost in round-trip")
		}
		if *rt.Browser.Proxy.Geo != *fc.Browser.Proxy.Geo {
			t.Errorf("geo did not round-trip: got %+v want %+v", *rt.Browser.Proxy.Geo, *fc.Browser.Proxy.Geo)
		}
	})

	t.Run("proxy emitted when configured", func(t *testing.T) {
		fc := FileConfig{
			Browser: BrowserConfig{
				Provider: BrowserChrome,
				Proxy: BrowserProxyConfig{
					Server:   "http://proxy.example.com:8080",
					Username: "alice",
					Password: "s3cr3t",
				},
			},
		}
		raw, err := json.Marshal(fc)
		if err != nil {
			t.Fatalf("marshal: %v", err)
		}
		// On-disk format intentionally stores raw password; redaction happens at log/HTTP boundaries.
		if !strings.Contains(string(raw), `"password":"s3cr3t"`) {
			t.Errorf("on-disk config should contain raw password, got: %s", string(raw))
		}

		var rt FileConfig
		if err := json.Unmarshal(raw, &rt); err != nil {
			t.Fatalf("unmarshal: %v", err)
		}
		if rt.Browser.Proxy.Server != fc.Browser.Proxy.Server ||
			rt.Browser.Proxy.Username != fc.Browser.Proxy.Username ||
			rt.Browser.Proxy.Password != fc.Browser.Proxy.Password {
			t.Errorf("proxy did not round-trip: got %+v want %+v", rt.Browser.Proxy, fc.Browser.Proxy)
		}
	})
}

// L7(a): an '@' in the URL path is not embedded userinfo.
func TestParseProxyServer_PathWithAtSignAccepted(t *testing.T) {
	scheme, host, port, err := ParseProxyServer("http://proxy.example:8080/p@th")
	if err != nil {
		t.Fatalf("path containing '@' should parse: %v", err)
	}
	if scheme != "http" || host != "proxy.example" || port != 8080 {
		t.Fatalf("parsed %s://%s:%d, want http://proxy.example:8080", scheme, host, port)
	}
	if _, _, _, err := ParseProxyServer("http://user:[email protected]:8080"); err == nil {
		t.Fatal("embedded credentials must still be rejected")
	}
}

// A proxy block holding anything at all must survive a save. It did not: the whole
// block was dropped whenever server was unset, so `config set browser.proxy.username`
// reported success and wrote nothing — the command's own output cannot be the oracle
// for this, which is why these read the marshalled file back.
func TestProxyFieldsSurviveASaveWithoutAServer(t *testing.T) {
	for _, tc := range []struct {
		name  string
		proxy BrowserProxyConfig
		want  string
	}{
		{name: "username", proxy: BrowserProxyConfig{Username: "bob"}, want: "bob"},
		{name: "password", proxy: BrowserProxyConfig{Password: "hunter2"}, want: "hunter2"},
		{name: "bypassList", proxy: BrowserProxyConfig{BypassList: []string{"*.internal"}}, want: "*.internal"},
		{name: "geo.timezone", proxy: BrowserProxyConfig{Geo: &BrowserProxyGeoConfig{Timezone: "Europe/Rome"}}, want: "Europe/Rome"},
		{name: "geo.locale", proxy: BrowserProxyConfig{Geo: &BrowserProxyGeoConfig{Locale: "it-IT"}}, want: "it-IT"},
		{name: "geo.webrtcIP", proxy: BrowserProxyConfig{Geo: &BrowserProxyGeoConfig{WebRTCIP: "1.2.3.4"}}, want: "1.2.3.4"},
		{name: "geo.countryISO", proxy: BrowserProxyConfig{Geo: &BrowserProxyGeoConfig{CountryISO: "IT"}}, want: "IT"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			fc := &FileConfig{}
			fc.Browser.Proxy = tc.proxy

			raw, err := json.Marshal(fc)
			if err != nil {
				t.Fatal(err)
			}
			if !strings.Contains(string(raw), tc.want) {
				t.Errorf("browser.proxy.%s was accepted and then dropped by the save; the marshalled config is %s", tc.name, raw)
			}
		})
	}
}

// The fail-OPEN half: clearing the server on a populated proxy must be persisted, or the
// operator believes traffic no longer egresses through the proxy while it still does.
//
// Driven through SaveFileConfig against a file that already exists, because that is the
// only path where the defect lives: the save patches the file key by key from the
// marshalled config, so an omitempty-dropped server reads as a key the struct does not
// model and the OLD value is preserved. A test that only marshals the struct passes
// while the shipped command still leaves the proxy on.
func TestClearingTheServerOnAPopulatedProxyIsPersisted(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "config.json")
	if err := os.WriteFile(path, []byte(`{"browser":{"proxy":{"server":"http://p.example:8080","username":"bob","password":"hunter2","bypassList":["*.internal"]}}}`), 0600); err != nil {
		t.Fatal(err)
	}

	fc := &FileConfig{}
	fc.Browser.Proxy = BrowserProxyConfig{
		Server:     "",
		Username:   "bob",
		Password:   "hunter2",
		BypassList: []string{"*.internal"},
	}
	if err := SaveFileConfig(fc, path); err != nil {
		t.Fatal(err)
	}

	raw, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	var onDisk struct {
		Browser struct {
			Proxy struct {
				Server   *string `json:"server"`
				Username string  `json:"username"`
			} `json:"proxy"`
		} `json:"browser"`
	}
	if err := json.Unmarshal(raw, &onDisk); err != nil {
		t.Fatal(err)
	}
	if onDisk.Browser.Proxy.Server == nil {
		t.Fatalf("the cleared server is absent from the file, so the save could not tell it apart from an unmodelled key and left the old one: %s", raw)
	}
	if *onDisk.Browser.Proxy.Server != "" {
		t.Errorf("browser.proxy.server = %q after being cleared, want empty — a proxy that cannot be turned off is fail-open: %s", *onDisk.Browser.Proxy.Server, raw)
	}
	if onDisk.Browser.Proxy.Username != "bob" {
		t.Errorf("clearing the server discarded the credentials (username = %q); they are meant to survive for the next server", onDisk.Browser.Proxy.Username)
	}
}

// The render that makes the above possible, and its negative: a block with nothing in
// it must not grow a server key.
func TestOnlyANonEmptyProxyRendersAClearedServer(t *testing.T) {
	withCredentials, err := json.Marshal(BrowserProxyConfig{Username: "bob"})
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(withCredentials), `"server":""`) {
		t.Errorf("a serverless block renders as %s, without the server key the save needs to clear it", withCredentials)
	}

	empty, err := json.Marshal(BrowserProxyConfig{})
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(string(empty), "server") {
		t.Errorf("an empty proxy block renders as %s, growing a key nobody set", empty)
	}
}

// The negative control this fix must not break: a genuinely empty proxy block stays
// absent from the file rather than being written as an empty object.
func TestAnEmptyProxyBlockIsStillOmitted(t *testing.T) {
	fc := &FileConfig{}
	fc.Browser.Proxy = BrowserProxyConfig{}

	raw, err := json.Marshal(fc)
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(string(raw), `"proxy"`) {
		t.Errorf("an empty proxy block was written to the file: %s", raw)
	}
}

// AC2: an incomplete proxy is REPORTED, not dropped and not refused. The report has to
// arrive as an advisory rather than a validation error: validation errors gate
// `config set` behind a confirm that answers no off a TTY, so gating this one would
// refuse the very write that completes the block.
func TestAServerlessProxyBlockIsReportedAsAnAdvisory(t *testing.T) {
	fc := &FileConfig{}
	fc.Browser.Proxy = BrowserProxyConfig{Username: "bob", Password: "hunter2"}

	advisories := FileConfigAdvisories(fc)

	found := ""
	for _, advisory := range advisories {
		if strings.Contains(advisory, "browser.proxy") {
			found = advisory
		}
	}
	if found == "" {
		t.Fatalf("a proxy with credentials and no server is reported nowhere; advisories = %v", advisories)
	}
	if !strings.Contains(found, "browser.proxy.server") {
		t.Errorf("the advisory %q does not name browser.proxy.server as the prerequisite, so the reader is not told which key to set", found)
	}

	for _, err := range ValidateFileConfig(fc) {
		if strings.Contains(err.Error(), "browser.proxy.server") {
			t.Errorf("the missing server is ALSO a gating validation error (%v); off a TTY that refuses the write that would complete the block", err)
		}
	}
}

// AC3: the end state is what matters — setting the server afterwards clears the report
// and the proxy works with the credentials that were set first.
func TestSettingTheServerAfterwardsCompletesThePreviouslySetProxy(t *testing.T) {
	fc := &FileConfig{}
	fc.Browser.Proxy = BrowserProxyConfig{Username: "bob", Password: "hunter2"}
	fc.Browser.Proxy.Server = "http://proxy.example:8080"

	for _, advisory := range FileConfigAdvisories(fc) {
		if strings.Contains(advisory, "browser.proxy") {
			t.Errorf("the incomplete-proxy advisory survives a server being set: %q", advisory)
		}
	}

	flags, err := BrowserProxyFlags(fc.Browser.Proxy)
	if err != nil {
		t.Fatalf("BrowserProxyFlags after completing the block: %v", err)
	}
	if len(flags) == 0 || !strings.Contains(flags[0], "http://proxy.example:8080") {
		t.Errorf("flags = %v, want the configured proxy — preserving the credentials is pointless if the completed block does not launch", flags)
	}
}

// An incomplete block must not launch or authenticate: the values are kept, not applied.
func TestAServerlessProxyNeitherLaunchesNorAuthenticates(t *testing.T) {
	p := BrowserProxyConfig{Username: "bob", Password: "hunter2", BypassList: []string{"*.internal"}}

	flags, err := BrowserProxyFlags(p)
	if err != nil {
		t.Fatalf("a serverless proxy must be a no-op at launch, not an error: %v", err)
	}
	if len(flags) != 0 {
		t.Errorf("flags = %v, want none: there is no server to route through", flags)
	}
}

// AC5: the rest of proxy validation now runs for a serverless block. The empty bypass
// pattern was silently skipped, because one predicate answered both "no proxy is
// configured" and "this block is empty".
func TestProxyValidationRunsForAServerlessBlock(t *testing.T) {
	for _, tc := range []struct {
		name  string
		proxy BrowserProxyConfig
		want  string
	}{
		{name: "empty bypass pattern", proxy: BrowserProxyConfig{BypassList: []string{""}}, want: "bypass pattern must not be empty"},
		{name: "bypass pattern with a separator", proxy: BrowserProxyConfig{BypassList: []string{"a;b"}}, want: "must not contain whitespace"},
		{name: "username without password", proxy: BrowserProxyConfig{Username: "bob"}, want: "password is required"},
		{name: "password without username", proxy: BrowserProxyConfig{Password: "hunter2"}, want: "username is required"},
		{name: "invalid geo", proxy: BrowserProxyConfig{Geo: &BrowserProxyGeoConfig{CountryISO: "ITALY"}}, want: "geo"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			errs := ValidateBrowserProxy("browser.proxy", tc.proxy)

			joined := ""
			for _, err := range errs {
				joined += err.Error() + "\n"
			}
			if !strings.Contains(joined, tc.want) {
				t.Errorf("a serverless block skipped its own validation: errors = %q, want one containing %q", joined, tc.want)
			}
			for _, err := range errs {
				if strings.Contains(err.Error(), "proxy server is empty") {
					t.Errorf("the absent server is reported as a malformed one (%v); that is the advisory's job, and as an error it would gate the completing write", err)
				}
			}
		})
	}
}

// The negative control for the validator's entry gate: nothing set means nothing to
// validate, which is today's behaviour and must not change.
func TestAnEmptyProxyBlockIsStillValidatedAsAbsent(t *testing.T) {
	if errs := ValidateBrowserProxy("browser.proxy", BrowserProxyConfig{}); len(errs) != 0 {
		t.Errorf("an empty proxy block produced %v, want no diagnostics at all", errs)
	}
	fc := &FileConfig{}
	for _, advisory := range FileConfigAdvisories(fc) {
		if strings.Contains(advisory, "proxy") {
			t.Errorf("an empty proxy block was reported as incomplete: %q", advisory)
		}
	}
}

func TestACredentialsOnlyTargetProxyDoesNotReplaceAWorkingParentProxy(t *testing.T) {
	cfg := &RuntimeConfig{
		DefaultBrowser: BrowserChrome,
		Proxy:          BrowserProxyConfig{Server: "http://parent.example:8080"},
		Targets: BrowserTargetsConfig{
			"creds": {
				Provider: BrowserChrome,
				Proxy:    BrowserProxyConfig{Username: "bob", Password: "secret"},
			},
		},
	}

	resolved, err := ResolveExplicitBrowserTarget(cfg, "creds")
	if err != nil {
		t.Fatal(err)
	}
	if got := resolved.Config.Proxy.Server; got != "http://parent.example:8080" {
		t.Fatalf("resolved proxy server = %q; a target proxy carrying only credentials replaced the working parent proxy, so the target's traffic would egress directly", got)
	}

	flags, err := BrowserProxyFlags(resolved.Config.Proxy)
	if err != nil {
		t.Fatal(err)
	}
	if len(flags) == 0 {
		t.Fatal("resolved target produced no proxy launch flags; traffic would egress directly, un-proxied")
	}
}