Fix VPN internet connectivity and simplify client setup

Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
This commit is contained in:
shen
2026-10-12 06:51:25 -07:00
parent 2f185f914d
commit c7cc2aa865
41 changed files with 2841 additions and 247 deletions
+39
View File
@@ -0,0 +1,39 @@
package bridge
import (
"context"
"errors"
"fmt"
"net"
"os"
"strings"
"syscall"
)
// Return fixed diagnostic categories, never upstream messages containing node
// credentials, subscription URLs, or the generated configuration.
func startupFailure(stage string, cause error) error {
code := "engine_failure"
var dnsError *net.DNSError
var networkError net.Error
message := strings.ToLower(cause.Error())
switch {
case errors.Is(cause, syscall.EADDRINUSE):
code = "listen_port_in_use"
case errors.Is(cause, os.ErrPermission):
code = "permission_denied"
case errors.Is(cause, context.DeadlineExceeded) || errors.As(cause, &networkError) && networkError.Timeout():
code = "network_timeout"
case errors.As(cause, &dnsError):
code = "dns_resolution_failed"
case strings.Contains(message, "certificate") || strings.Contains(message, "x509"):
code = "tls_certificate_failed"
case strings.Contains(message, "rule-set") || strings.Contains(message, "rule set"):
code = "rule_set_failed"
case strings.Contains(message, "connection refused"):
code = "connection_refused"
case strings.Contains(message, "unsupported") || strings.Contains(message, "unknown") || strings.Contains(message, "invalid"):
code = "invalid_engine_options"
}
return fmt.Errorf("proxy startup failed [stage=%s, code=%s]", stage, code)
}
@@ -0,0 +1,23 @@
package bridge
import (
"errors"
"strings"
"testing"
)
func TestStartupDiagnosticsDoNotExposeUpstreamCredentials(t *testing.T) {
for _, message := range []string{
"unknown option password=test-secret https://example.test/sub?token=test-token",
"rule-set download https://user:test-secret@example.test/sub?token=test-token",
"unclassified failure with test-secret and test-token",
} {
result := startupFailure("initialize_engine", errors.New(message)).Error()
if strings.Contains(result, "test-secret") || strings.Contains(result, "test-token") || strings.Contains(result, "example.test") {
t.Fatalf("diagnostic exposed upstream contents: %s", result)
}
if !strings.Contains(result, "stage=initialize_engine") {
t.Fatal("diagnostic omitted failing stage")
}
}
}
+15 -6
View File
@@ -60,11 +60,13 @@ func registryContext(ctx context.Context) context.Context {
}
type Snapshot struct {
State string `json:"state"`
Version string `json:"version"`
State string `json:"state"`
Version string `json:"version"`
RuntimeEvents []RuntimeEvent `json:"runtime_events,omitempty"`
}
type Engine struct {
runtimeLogs runtimeLogs
selfTestTrace bool
startupCause error // Private diagnostic for package tests; never returned over ABI.
// Protector must be installed before starting a host TUN.
@@ -89,7 +91,7 @@ func (e *Engine) Snapshot() Snapshot {
if state == "Running" && e.ctx.Err() != nil {
state = "Failed"
}
return Snapshot{State: state, Version: "1.14.3"}
return Snapshot{State: state, Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()}
}
func (e *Engine) Start(parent context.Context, config Config) error {
@@ -135,7 +137,7 @@ func (e *Engine) Start(parent context.Context, config Config) error {
if err != nil {
cancel()
e.state = "Failed"
return errors.New("invalid managed engine configuration")
return startupFailure("decode_configuration", err)
}
if config.FakeIP || len(config.RuleSets) > 0 {
if e.cacheDir == "" {
@@ -148,19 +150,26 @@ func (e *Engine) Start(parent context.Context, config Config) error {
}
options.Experimental = &option.ExperimentalOptions{CacheFile: &option.CacheFileOptions{Enabled: true, Path: filepath.Join(e.cacheDir, "fakeip.db"), StoreFakeIP: config.FakeIP}}
}
e.runtimeLogs.configure(config.Proxy)
// Collect bounded, credential-redacted warning/error events in memory.
// Raw upstream logs must never go to stderr or a user's log file.
if !e.selfTestTrace {
options.Log = &option.LogOptions{Level: "warn", Output: os.DevNull}
}
instance, err := box.New(box.Options{Options: options, Context: ctx})
if err != nil {
e.startupCause = err
cancel()
e.state = "Failed"
return errors.New("cannot initialize proxy engine")
return startupFailure("initialize_engine", err)
}
instance.LogFactory().AttachPlatformWriter(&e.runtimeLogs)
if err = instance.Start(); err != nil {
e.startupCause = err
_ = instance.Close()
cancel()
e.state = "Failed"
return errors.New("cannot start proxy engine")
return startupFailure("start_engine", err)
}
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
return nil
+4 -1
View File
@@ -8,6 +8,7 @@ import (
"io"
"net"
"net/netip"
"strings"
"testing"
"time"
)
@@ -88,8 +89,10 @@ func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
if engine.Snapshot().State != "Stopped" {
t.Fatal("initial state")
}
if engine.Start(context.Background(), c) == nil {
if err := engine.Start(context.Background(), c); err == nil {
t.Fatal("started on occupied port")
} else if !strings.Contains(err.Error(), "listen_port_in_use") {
t.Fatalf("missing safe occupied-port diagnostic: %v", err)
}
if engine.Snapshot().State != "Failed" {
t.Fatal("failed start state")
+6 -1
View File
@@ -24,7 +24,12 @@ type hostPlatform struct {
monitor *hostMonitor
}
func (p *hostPlatform) Initialize(adapter.NetworkManager) error { return nil }
func (p *hostPlatform) Initialize(manager adapter.NetworkManager) error {
// The host monitor already knows the physical default, but sing-box keeps
// its own selectable-interface list. Populate it before outbound startup.
// Android cannot fill this list via the restricted kernel network monitor.
return manager.UpdateInterfaces()
}
func (p *hostPlatform) UsePlatformAutoDetectInterfaceControl() bool { return true }
func (p *hostPlatform) AutoDetectInterfaceControl(fd int) error {
if p.protect == nil {
+103
View File
@@ -0,0 +1,103 @@
package bridge
import (
"context"
"io"
"net"
"sync/atomic"
"testing"
"time"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/route"
"github.com/sagernet/sing/common/control"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/service"
)
// Exercise sing-box's real interface selection, which otherwise fails with
// "no available network interface" even though the host reports a default.
func TestHostPlatformInitialPhysicalNetwork(t *testing.T) {
interfaces, err := net.Interfaces()
if err != nil {
t.Fatal(err)
}
var physical net.Interface
for _, candidate := range interfaces {
if candidate.Flags&net.FlagUp != 0 && candidate.Flags&net.FlagLoopback == 0 {
physical = candidate
break
}
}
if physical.Index == 0 {
t.Skip("No active physical interface")
}
var protected atomic.Int32
p := &hostPlatform{
monitor: &hostMonitor{physical: &control.Interface{Name: physical.Name, Index: physical.Index, MTU: physical.MTU, Flags: physical.Flags}},
protect: func(fd int) error {
if fd < 0 {
t.Fatal("Invalid protected fd")
}
protected.Add(1)
return nil
},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
ctx = service.ContextWith[adapter.PlatformInterface](ctx, p)
manager, err := route.NewNetworkManager(ctx, log.NewNOPFactory().Logger(), option.RouteOptions{AutoDetectInterface: true}, option.DNSOptions{})
if err != nil {
t.Fatal(err)
}
if err = p.Initialize(manager); err != nil {
t.Fatal(err)
}
ctx = service.ContextWith[adapter.NetworkManager](ctx, manager)
d, err := dialer.NewDefault(ctx, option.DialerOptions{})
if err != nil {
t.Fatal(err)
}
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
go func() {
for {
c, err := listener.Accept()
if err != nil {
return
}
go func() { defer c.Close(); _, _ = io.Copy(c, c) }()
}
}()
conn, err := d.DialContext(ctx, "tcp", M.ParseSocksaddr(listener.Addr().String()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(3 * time.Second))
if _, err = conn.Write([]byte("protected TCP")); err != nil {
t.Fatal(err)
}
data := make([]byte, len("protected TCP"))
if _, err = io.ReadFull(conn, data); err != nil {
t.Fatal(err)
}
if string(data) != "protected TCP" || protected.Load() == 0 {
t.Fatal("TCP bypassed socket protection or echo failed")
}
before := protected.Load()
udp, err := d.ListenPacket(ctx, M.ParseSocksaddr("127.0.0.1:12345"))
if err != nil {
t.Fatal(err)
}
defer udp.Close()
if protected.Load() <= before {
t.Fatal("UDP bypassed socket protection")
}
}
+75
View File
@@ -0,0 +1,75 @@
package bridge
import (
"regexp"
"sort"
"strings"
"sync"
"github.com/sagernet/sing-box/log"
)
type RuntimeEvent struct {
Sequence uint64 `json:"sequence"`
Message string `json:"message"`
}
type runtimeLogs struct {
mu sync.Mutex
sequence uint64
events []RuntimeEvent
secrets []string
}
var logURLAuth = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://)[^\s/]+@`)
var logURLQuery = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*://[^\s?]+)\?[^\s]+`)
var logANSI = regexp.MustCompile("\x1b\\[[0-9;]*m")
func (r *runtimeLogs) configure(node map[string]any) {
r.mu.Lock()
defer r.mu.Unlock()
var remember func(map[string]any)
remember = func(values map[string]any) {
for key, value := range values {
if nested, ok := value.(map[string]any); ok {
remember(nested)
}
switch key {
case "password", "username", "uuid", "private_key", "token":
if text, ok := value.(string); ok && text != "" {
r.secrets = append(r.secrets, text)
}
}
}
}
remember(node)
sort.Slice(r.secrets, func(i, j int) bool { return len(r.secrets[i]) > len(r.secrets[j]) })
}
func (r *runtimeLogs) WriteMessage(level log.Level, message string) {
if level > log.LevelWarn {
return
}
r.mu.Lock()
defer r.mu.Unlock()
for _, value := range r.secrets {
message = strings.ReplaceAll(message, value, "[redacted]")
}
message = logURLAuth.ReplaceAllString(message, "${1}[redacted]@")
message = logURLQuery.ReplaceAllString(message, "${1}?[redacted]")
message = logANSI.ReplaceAllString(message, "")
if len(message) > 2048 {
message = string([]rune(message)[:min(512, len([]rune(message)))]) + "…"
}
r.sequence++
r.events = append(r.events, RuntimeEvent{Sequence: r.sequence, Message: message})
if len(r.events) > 32 {
r.events = append([]RuntimeEvent(nil), r.events[len(r.events)-32:]...)
}
}
func (r *runtimeLogs) snapshot() []RuntimeEvent {
r.mu.Lock()
defer r.mu.Unlock()
return append([]RuntimeEvent(nil), r.events...)
}
@@ -0,0 +1,36 @@
package bridge
import (
"github.com/sagernet/sing-box/log"
"strings"
"testing"
)
func TestRuntimeLogsBoundedAndRedacted(t *testing.T) {
var logs runtimeLogs
logs.configure(map[string]any{"uuid": "secret-uuid", "password": "secret-password"})
logs.WriteMessage(log.LevelInfo, "ignored")
for i := 0; i < 40; i++ {
logs.WriteMessage(log.LevelError, "failure secret-uuid secret-password https://u:p@example.test/?token=secret-token")
}
events := logs.snapshot()
if len(events) != 32 || events[0].Sequence != 9 {
t.Fatal("unbounded or incorrect log sequence")
}
for _, e := range events {
for _, secret := range []string{"secret-uuid", "secret-password", "secret-token", "u:p"} {
if strings.Contains(e.Message, secret) {
t.Fatal("runtime log exposed credential")
}
}
}
}
func TestRuntimeLogsRedactOverlappingCredentialValues(t *testing.T) {
var logs runtimeLogs
logs.configure(map[string]any{"username": "secret", "password": "secret-credential"})
logs.WriteMessage(log.LevelError, "authentication failed for secret-credential")
if strings.Contains(logs.snapshot()[0].Message, "credential") {
t.Fatal("short credential prevented full password redaction")
}
}