refactor(routing): 暴露 system_locked_domains + 服务端 follow-up 清理(FK/Validate/dedup/exclude单源/共用Store/Builtin保留)

This commit is contained in:
wangjia
2026-07-29 06:38:52 +08:00
parent 52912268d0
commit 3159dd75c1
11 changed files with 285 additions and 36 deletions
+9 -3
View File
@@ -270,9 +270,15 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
if len(extraExclude) > 0 {
// IP 直连真生效:并入 TUN 入站的 route_exclude_address(auto_route 层排除,
// 见 tunIn 构造处注释——单靠 route.rules 的 ip_cidr→direct 在 macOS
// strict_route 下不生效)。与既有 LAN 网段去重合并。
exclude := []string{"192.168.0.0/16", "10.0.0.0/8"}
seen := map[string]bool{"192.168.0.0/16": true, "10.0.0.0/8": true}
// strict_route 下不生效)。单源读 tunIn 现有种子(不重复硬编码 LAN 网段;
// 其为 192.168+10,与上面 route.rules 的 LAN 直连 4 段有意不同——不能改成
// LAN 全集,否则会漏排除/多排除),与 extraExclude 去重合并、写回。
base, _ := tunIn["route_exclude_address"].([]string)
exclude := append([]string{}, base...)
seen := make(map[string]bool, len(base))
for _, e := range base {
seen[e] = true
}
for _, e := range extraExclude {
if !seen[e] {
seen[e] = true
@@ -64,6 +64,19 @@ func openRoutingDB(t *testing.T) *sql.DB {
return db
}
// seedConnectUser inserts a minimal users row so routing_profiles inserts
// (which now declare FOREIGN KEY (user_id) REFERENCES users(id)) satisfy the
// constraint — this DB opens with _pragma=foreign_keys(1) (internal/db/db.go),
// so SQLite does enforce it, unlike a bare default SQLite connection.
func seedConnectUser(t *testing.T, db *sql.DB, id int64) {
t.Helper()
uuid := "u-connect"
if _, err := db.Exec(`INSERT INTO users (id,uuid,email,pw_hash,dp_uuid,status,created_at)
VALUES (?,?,?, 'x','dp-'||?, 'active', ?)`, id, uuid, uuid+"@x", uuid, time.Now().UTC()); err != nil {
t.Fatal(err)
}
}
// newOnlineHub returns a real *nodes.Hub (backed by miniredis) with nodeUUID
// registered online, so ConnectNode's a.hub.IsOnline(...) gate passes and
// Push(...) succeeds without a real Redis deployment.
@@ -98,6 +111,7 @@ func TestConnectNode_ReadsRoutingProfile(t *testing.T) {
const uid = int64(42)
db := openRoutingDB(t)
seedConnectUser(t, db, uid)
rst := routing.NewStore(db)
p := routing.Default()
p.Rules = []routing.Rule{
@@ -167,6 +181,7 @@ func TestConnectNode_RoutingStoreErr_FailsSafe(t *testing.T) {
const uid = int64(44)
db := openRoutingDB(t)
seedConnectUser(t, db, uid)
// 写入一条无法反序列化的 profile_json,模拟 Get 出错。
if _, err := db.Exec(`INSERT INTO routing_profiles (user_id, profile_json, updated_at) VALUES (?,?,?)`,
uid, "{not-json", time.Now().UTC()); err != nil {
+24 -2
View File
@@ -14,10 +14,28 @@ import (
// user hasn't customized one yet; POST validates and upserts.
type RoutingAPI struct {
store *routing.Store
// lockedDomains are the system-forced-tunnel private-service domains
// (PANGOLIN_PRIVATE_SPLIT_DOMAINS, same slice injected into NodeAPI) —
// read-only, surfaced to GET so clients can warn users that rules against
// these domains silently have no effect. Never written to the persisted
// Profile.
lockedDomains []string
}
// NewRoutingAPI creates a RoutingAPI backed by the given routing.Store.
func NewRoutingAPI(store *routing.Store) *RoutingAPI { return &RoutingAPI{store: store} }
// lockedDomains is the system-forced private-service domain list (may be nil).
func NewRoutingAPI(store *routing.Store, lockedDomains []string) *RoutingAPI {
return &RoutingAPI{store: store, lockedDomains: lockedDomains}
}
// profileResponse wraps routing.Profile for GET /v1/me/routing, adding the
// read-only system_locked_domains list. It deliberately lives here — not on
// routing.Profile itself — so the field can never leak into the writable
// Profile contract that SaveProfile decodes POST bodies into.
type profileResponse struct {
*routing.Profile
SystemLockedDomains []string `json:"system_locked_domains"`
}
// GetProfile handles GET /v1/me/routing.
func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
@@ -34,7 +52,11 @@ func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
if p == nil {
p = routing.Default()
}
writeJSON(w, http.StatusOK, p)
locked := a.lockedDomains
if locked == nil {
locked = []string{}
}
writeJSON(w, http.StatusOK, profileResponse{Profile: p, SystemLockedDomains: locked})
}
// SaveProfile handles POST /v1/me/routing. On validation failure it returns
+81 -2
View File
@@ -65,7 +65,7 @@ func doAuthReq(t *testing.T, method, target string, body *strings.Reader, uid in
func TestRoutingGetDefaultThenSave(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 7)
api := NewRoutingAPI(routing.NewStore(db))
api := NewRoutingAPI(routing.NewStore(db), nil)
// GET 无档案 → 200 + Default
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 7, api.GetProfile)
@@ -120,7 +120,7 @@ func TestRoutingGetDefaultThenSave(t *testing.T) {
func TestRoutingGetUnauthorized(t *testing.T) {
db := openRoutingTestDB(t)
api := NewRoutingAPI(routing.NewStore(db))
api := NewRoutingAPI(routing.NewStore(db), nil)
req := httptest.NewRequest(http.MethodGet, "/v1/me/routing", nil)
rr := httptest.NewRecorder()
api.GetProfile(rr, req)
@@ -128,3 +128,82 @@ func TestRoutingGetUnauthorized(t *testing.T) {
t.Fatalf("expected 401, got %d", rr.Code)
}
}
// TestRoutingGetExposesSystemLockedDomains: GET must surface the injected
// lockedDomains list under system_locked_domains, without it ever ending up
// as part of routing.Profile's own field set.
func TestRoutingGetExposesSystemLockedDomains(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 8)
api := NewRoutingAPI(routing.NewStore(db), []string{"nas.x.com"})
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 8, api.GetProfile)
if rr.Code != 200 {
t.Fatalf("GET code %d", rr.Code)
}
var resp struct {
SystemLockedDomains []string `json:"system_locked_domains"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(resp.SystemLockedDomains) != 1 || resp.SystemLockedDomains[0] != "nas.x.com" {
t.Fatalf("want system_locked_domains=[nas.x.com], got %v", resp.SystemLockedDomains)
}
}
// TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray: a nil lockedDomains
// slice (no PANGOLIN_PRIVATE_SPLIT_DOMAINS configured) must serialize as
// `[]`, not `null` — clients shouldn't need a nil-check.
func TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 9)
api := NewRoutingAPI(routing.NewStore(db), nil)
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 9, api.GetProfile)
if rr.Code != 200 {
t.Fatalf("GET code %d", rr.Code)
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(rr.Body.Bytes(), &raw); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if got := string(raw["system_locked_domains"]); got != "[]" {
t.Fatalf("want system_locked_domains=`[]`, got %s", got)
}
}
// TestRoutingSaveIgnoresSystemLockedDomains: a client POSTing a body that
// includes system_locked_domains must not have it persisted — SaveProfile
// decodes straight into routing.Profile, which has no such field, so the
// key is silently dropped. Verify against the raw stored row (not the GET
// response, which always injects it from a.lockedDomains regardless of what
// was ever saved).
func TestRoutingSaveIgnoresSystemLockedDomains(t *testing.T) {
db := openRoutingTestDB(t)
seedRoutingUser(t, db, 10)
store := routing.NewStore(db)
api := NewRoutingAPI(store, []string{"nas.x.com"})
body := `{"mode":"rule","builtin":{"china_direct":true,"lan_direct":true,"private_via_tunnel":true},` +
`"rules":[],"final":"proxy","system_locked_domains":["evil.attacker.com"]}`
rr := doAuthReq(t, http.MethodPost, "/v1/me/routing", strings.NewReader(body), 10, api.SaveProfile)
if rr.Code != 200 {
t.Fatalf("POST code %d body %s", rr.Code, rr.Body)
}
stored, err := store.Get(context.Background(), 10)
if err != nil {
t.Fatal(err)
}
if stored == nil {
t.Fatal("expected a persisted profile")
}
raw, err := json.Marshal(stored)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(raw), "system_locked_domains") || strings.Contains(string(raw), "evil.attacker.com") {
t.Fatalf("system_locked_domains must never be persisted, got stored profile JSON: %s", raw)
}
}