feat(mtproto): per-client ad-tags, management-API auth, and record secret sync

Catch the panel up to the mtg-multi README (v1.14.0):

- Each client can now carry its own 32-hex advertising tag overriding the
  inbound-level one. The tag lives on the client (settings JSON is the
  source of truth, clients.ad_tag is the UI projection), is rendered into
  the fork's [secret-ad-tags] section for active secrets only (mtg rejects
  a config whose override names an unknown secret), is pushed per entry
  through PUT /secrets, and is part of the reload fingerprint so a tag
  edit hot-applies without dropping connections.
- The loopback management API can replace the whole secret set, so every
  mtg process now gets a random per-process api-token; the manager sends
  it as a bearer token on PUT /secrets and GET /stats and reuses it across
  config rewrites, because mtg reads the token only at startup.
- Malformed tags are rejected at every save path and additionally dropped
  in InstanceFromInbound: one bad tag would otherwise fail the whole
  generated config and take every client of the inbound down with it.
- SyncInbound never copied a re-keyed mtproto secret into the canonical
  clients table, so the clients page and subscription links kept serving
  the old secret, which mtg then rejects. It is now guarded-copied like
  the other credentials.
This commit is contained in:
MHSanaei
2026-07-07 12:00:43 +02:00
parent 659f0f404c
commit 43500a5470
33 changed files with 361 additions and 54 deletions
+93 -25
View File
@@ -3,6 +3,8 @@ package mtproto
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"net"
@@ -20,10 +22,13 @@ import (
// SecretEntry is one named FakeTLS secret served by an mtg-multi process. Name is
// the client email, used both as the [secrets] key and as the per-user key in the
// /stats API so traffic can be attributed back to the client.
// /stats API so traffic can be attributed back to the client. AdTag is the
// client's own advertising-tag override, emitted into the [secret-ad-tags]
// section; empty falls back to the instance-level tag.
type SecretEntry struct {
Name string
Secret string
AdTag string
}
// Instance is the desired runtime configuration of one mtproto inbound. A single
@@ -98,13 +103,13 @@ func (inst Instance) structuralFingerprint() string {
// secretsFingerprint identifies the reloadable secret config regardless of
// client order, so a reordered clients array in the stored settings does not
// read as a change. It moves whenever a client is added, removed, disabled, or
// re-keyed, or the advertising tag changes — all of which mtg applies through
// /reload without dropping connections.
// read as a change. It moves whenever a client is added, removed, disabled,
// re-keyed, or re-tagged, or the global advertising tag changes — all of which
// mtg applies in place without dropping connections.
func (inst Instance) secretsFingerprint() string {
pairs := make([]string, 0, len(inst.Secrets))
for _, e := range inst.Secrets {
pairs = append(pairs, e.Name+"="+e.Secret)
pairs = append(pairs, e.Name+"="+e.Secret+";tag="+e.AdTag)
}
slices.Sort(pairs)
return "adtag=" + inst.AdTag + "|" + strings.Join(pairs, "|")
@@ -130,6 +135,7 @@ type managed struct {
structuralFP string
secretsFP string
apiPort int
apiToken string
last map[string]clientCounters
}
@@ -183,6 +189,7 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
Clients []struct {
Email string `json:"email"`
Secret string `json:"secret"`
AdTag string `json:"adTag"`
Enable bool `json:"enable"`
} `json:"clients"`
}
@@ -194,7 +201,7 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
if !c.Enable || c.Secret == "" || c.Email == "" {
continue
}
secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret})
secrets = append(secrets, SecretEntry{Name: c.Email, Secret: c.Secret, AdTag: usableAdTag(c.AdTag)})
}
if len(secrets) == 0 {
return Instance{}, false
@@ -214,12 +221,24 @@ func InstanceFromInbound(ib *model.Inbound) (Instance, bool) {
ThrottleMaxConnections: parsed.ThrottleMaxConnections,
RouteThroughXray: parsed.RouteThroughXray,
XrayRoutePort: parsed.RouteXrayPort,
AdTag: strings.TrimSpace(parsed.AdTag),
AdTag: usableAdTag(parsed.AdTag),
PublicIPv4: strings.TrimSpace(parsed.PublicIPv4),
PublicIPv6: strings.TrimSpace(parsed.PublicIPv6),
}, true
}
// usableAdTag returns a stored advertising tag only when it is well-formed.
// The save paths validate tags, but settings can arrive from raw API payloads
// or older data, and one malformed tag in a generated config makes mtg reject
// the whole file — taking every client of the inbound down with it.
func usableAdTag(tag string) string {
tag = strings.TrimSpace(tag)
if !model.ValidMtprotoAdTag(tag) {
return ""
}
return tag
}
// Ensure starts the mtg process for an instance, or restarts it when its
// configuration changed. A no-op when the desired process is already running.
func (m *Manager) Ensure(inst Instance) error {
@@ -277,10 +296,10 @@ func (m *Manager) ensureLocked(inst Instance) error {
cur.tag = inst.Tag
return nil
case ensureReload:
if err := writeConfig(configPathForID(inst.Id), inst, cur.apiPort); err != nil {
if err := writeConfig(configPathForID(inst.Id), inst, cur.apiPort, cur.apiToken); err != nil {
return err
}
if applySecrets(cur.apiPort, inst) {
if applySecrets(cur.apiPort, cur.apiToken, inst) {
cur.tag = inst.Tag
cur.secretsFP = secFP
logger.Infof("mtproto: applied secret update to inbound %d in place", inst.Id)
@@ -297,8 +316,12 @@ func (m *Manager) ensureLocked(inst Instance) error {
if err != nil {
return err
}
apiToken, err := newAPIToken()
if err != nil {
return err
}
cfgPath := configPathForID(inst.Id)
if err := writeConfig(cfgPath, inst, apiPort); err != nil {
if err := writeConfig(cfgPath, inst, apiPort, apiToken); err != nil {
return err
}
proc := newProcess(cfgPath, fmt.Sprintf("inbound %d", inst.Id))
@@ -311,6 +334,7 @@ func (m *Manager) ensureLocked(inst Instance) error {
structuralFP: structFP,
secretsFP: secFP,
apiPort: apiPort,
apiToken: apiToken,
last: map[string]clientCounters{},
}
logger.Infof("mtproto: started mtg for inbound %d on %s", inst.Id, inst.bindTo())
@@ -370,10 +394,11 @@ func (m *Manager) StopAll() {
// with at least one live connection.
func (m *Manager) CollectTraffic() ([]Traffic, []string) {
type snap struct {
id int
apiPort int
tag string
last map[string]clientCounters
id int
apiPort int
apiToken string
tag string
last map[string]clientCounters
}
m.mu.Lock()
snaps := make([]snap, 0, len(m.procs))
@@ -385,14 +410,14 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) {
for k, v := range cur.last {
lastCopy[k] = v
}
snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, tag: cur.tag, last: lastCopy})
snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy})
}
m.mu.Unlock()
var out []Traffic
var online []string
for _, s := range snaps {
users, ok := scrapeStats(s.apiPort)
users, ok := scrapeStats(s.apiPort, s.apiToken)
if !ok {
continue
}
@@ -445,9 +470,11 @@ func FreeLocalPort() (int, error) {
// renderConfig builds the mtg-multi TOML for an instance. Top-level keys must
// precede any [section] header in TOML, and [secrets] must be the final section
// so trailing keys are not swallowed by another table. The layout is therefore:
// top-level scalars (incl. api-bind-to), then [domain-fronting], [network] and
// [throttle], and finally [secrets] with one named secret per active client.
func renderConfig(inst Instance, apiPort int) string {
// top-level scalars (incl. api-bind-to and api-token), then [domain-fronting],
// [network] and [throttle], then [secret-ad-tags] for clients overriding the
// global advertising tag, and finally [secrets] with one named secret per
// active client.
func renderConfig(inst Instance, apiPort int, apiToken string) string {
var b strings.Builder
fmt.Fprintf(&b, "bind-to = %q\n", inst.bindTo())
if inst.Debug {
@@ -460,6 +487,9 @@ func renderConfig(inst Instance, apiPort int) string {
fmt.Fprintf(&b, "prefer-ip = %q\n", inst.PreferIP)
}
fmt.Fprintf(&b, "api-bind-to = \"127.0.0.1:%d\"\n", apiPort)
if apiToken != "" {
fmt.Fprintf(&b, "api-token = %q\n", apiToken)
}
if inst.AdTag != "" {
fmt.Fprintf(&b, "ad-tag = %q\n", inst.AdTag)
}
@@ -490,6 +520,20 @@ func renderConfig(inst Instance, apiPort int) string {
if inst.ThrottleMaxConnections > 0 {
fmt.Fprintf(&b, "\n[throttle]\nmax-connections = %d\n", inst.ThrottleMaxConnections)
}
// Only clients present in [secrets] may appear here: mtg rejects a config
// whose [secret-ad-tags] names an unknown secret, so a disabled client's
// override must vanish together with its secret.
tagged := false
for _, e := range inst.Secrets {
if e.AdTag == "" {
continue
}
if !tagged {
b.WriteString("\n[secret-ad-tags]\n")
tagged = true
}
fmt.Fprintf(&b, "%q = %q\n", e.Name, e.AdTag)
}
b.WriteString("\n[secrets]\n")
for _, e := range inst.Secrets {
fmt.Fprintf(&b, "%q = %q\n", e.Name, e.Secret)
@@ -497,11 +541,11 @@ func renderConfig(inst Instance, apiPort int) string {
return b.String()
}
func writeConfig(path string, inst Instance, apiPort int) error {
func writeConfig(path string, inst Instance, apiPort int, apiToken string) error {
if err := os.MkdirAll(configDir(), 0o750); err != nil {
return err
}
return os.WriteFile(path, []byte(renderConfig(inst, apiPort)), 0o640)
return os.WriteFile(path, []byte(renderConfig(inst, apiPort, apiToken)), 0o640)
}
// statsUser is one entry of the mtg-multi /stats users map. bytes_in is traffic
@@ -515,6 +559,7 @@ type statsUser struct {
type secretPutEntry struct {
Secret string `json:"secret"`
AdTag string `json:"ad_tag,omitempty"`
}
type secretsPutBody struct {
@@ -525,19 +570,40 @@ type secretsPutBody struct {
func secretsPayload(inst Instance) secretsPutBody {
secrets := make(map[string]secretPutEntry, len(inst.Secrets))
for _, e := range inst.Secrets {
secrets[e.Name] = secretPutEntry{Secret: e.Secret}
secrets[e.Name] = secretPutEntry{Secret: e.Secret, AdTag: e.AdTag}
}
return secretsPutBody{Secrets: secrets, AdTag: inst.AdTag}
}
// applySecrets pushes the desired secret set and advertising tag to a running
// newAPIToken mints the bearer token one mtg process and its manager share for
// the lifetime of that process. The management API can replace the whole
// secret set, so even though it only listens on loopback it must not be open
// to every local process. The token lives in the generated config (mtg reads
// it at startup only — a rewritten token would not apply until a restart,
// which is why the reload path reuses the stored one) and in the manager's
// memory, nowhere else.
func newAPIToken() (string, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
func authorize(req *http.Request, token string) {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}
// applySecrets pushes the desired secret set and advertising tags to a running
// mtg-multi through its management API (PUT /secrets on the same loopback port
// that serves /stats), so a client add, removal, re-key, or ad-tag change is
// applied in place. mtg keeps every connection whose secret is unchanged and
// closes only the removed or re-keyed ones. It returns true only on a 200: an
// older binary without the endpoint (404), a refused connection, or any other
// status yields false, so the caller falls back to a full restart.
func applySecrets(port int, inst Instance) bool {
func applySecrets(port int, token string, inst Instance) bool {
body, err := json.Marshal(secretsPayload(inst))
if err != nil {
return false
@@ -548,6 +614,7 @@ func applySecrets(port int, inst Instance) bool {
return false
}
req.Header.Set("Content-Type", "application/json")
authorize(req, token)
resp, err := client.Do(req)
if err != nil {
return false
@@ -559,12 +626,13 @@ func applySecrets(port int, inst Instance) bool {
// scrapeStats reads the mtg-multi /stats JSON API and returns the per-user
// cumulative counters. Best-effort: an unreachable endpoint or unparseable body
// yields ok=false.
func scrapeStats(port int) (map[string]statsUser, bool) {
func scrapeStats(port int, token string) (map[string]statsUser, bool) {
client := http.Client{Timeout: 3 * time.Second}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil)
if err != nil {
return nil, false
}
authorize(req, token)
resp, err := client.Do(req)
if err != nil {
return nil, false
+6 -2
View File
@@ -30,6 +30,10 @@ func TestScrapeStats(t *testing.T) {
http.NotFound(w, r)
return
}
if r.Header.Get("Authorization") != "Bearer sesame" {
w.WriteHeader(http.StatusUnauthorized)
return
}
_, _ = io.WriteString(w, `{"started_at":"2026-01-01T00:00:00Z","total_connections":2,`+
`"users":{`+
`"alice":{"connections":2,"bytes_in":100,"bytes_out":200,"last_seen":"2026-01-01T00:01:00Z"},`+
@@ -37,7 +41,7 @@ func TestScrapeStats(t *testing.T) {
}))
defer srv.Close()
users, ok := scrapeStats(serverPort(t, srv))
users, ok := scrapeStats(serverPort(t, srv), "sesame")
if !ok {
t.Fatal("scrapeStats should succeed against a valid /stats endpoint")
}
@@ -59,7 +63,7 @@ func TestScrapeStatsUnreachable(t *testing.T) {
port := serverPort(t, srv)
srv.Close()
if _, ok := scrapeStats(port); ok {
if _, ok := scrapeStats(port, ""); ok {
t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable")
}
}
+20 -5
View File
@@ -116,26 +116,34 @@ func TestApplySecrets(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var gotMethod, gotPath string
var gotMethod, gotPath, gotAuth string
var gotBody secretsPutBody
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
gotMethod, gotPath, gotAuth = r.Method, r.URL.Path, r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&gotBody)
w.WriteHeader(tc.status)
}))
defer srv.Close()
inst := mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})
inst := mtgInst(1,
SecretEntry{Name: "alice", Secret: "ee01"},
SecretEntry{Name: "bob", Secret: "ee02", AdTag: "fedcba9876543210fedcba9876543210"})
inst.AdTag = "0123456789abcdef0123456789abcdef"
if got := applySecrets(serverPort(t, srv), inst); got != tc.want {
if got := applySecrets(serverPort(t, srv), "sesame", inst); got != tc.want {
t.Fatalf("applySecrets = %v, want %v", got, tc.want)
}
if gotMethod != http.MethodPut || gotPath != "/secrets" {
t.Fatalf("expected PUT /secrets, got %s %s", gotMethod, gotPath)
}
if gotAuth != "Bearer sesame" {
t.Fatalf("expected the bearer token on the request, got %q", gotAuth)
}
if gotBody.Secrets["alice"].Secret != "ee01" || gotBody.AdTag != "0123456789abcdef0123456789abcdef" {
t.Fatalf("payload must carry the secret and ad-tag: %+v", gotBody)
}
if gotBody.Secrets["alice"].AdTag != "" || gotBody.Secrets["bob"].AdTag != "fedcba9876543210fedcba9876543210" {
t.Fatalf("payload must carry per-client ad-tag overrides only where set: %+v", gotBody)
}
})
}
@@ -143,7 +151,7 @@ func TestApplySecrets(t *testing.T) {
srv := httptest.NewServer(http.NotFoundHandler())
port := serverPort(t, srv)
srv.Close()
if applySecrets(port, mtgInst(1, SecretEntry{Name: "a", Secret: "ee"})) {
if applySecrets(port, "", mtgInst(1, SecretEntry{Name: "a", Secret: "ee"})) {
t.Fatal("a refused connection must yield false")
}
})
@@ -159,6 +167,10 @@ func TestEnsureHotReloadKeepsProcess(t *testing.T) {
}
waitSpawnCount(t, pidFile, 1)
orig := mgr.procs[1].proc
origToken := mgr.procs[1].apiToken
if origToken == "" {
t.Fatal("a started process must get an api token")
}
reloaded := make(chan struct{}, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -201,6 +213,9 @@ func TestEnsureHotReloadKeepsProcess(t *testing.T) {
if !strings.Contains(string(cfg), fmt.Sprintf("api-bind-to = \"127.0.0.1:%d\"", serverPort(t, srv))) {
t.Fatalf("reload must reuse the same api port:\n%s", cfg)
}
if !strings.Contains(string(cfg), fmt.Sprintf("api-token = %q", origToken)) {
t.Fatalf("reload must reuse the token the running process was started with:\n%s", cfg)
}
mgr.StopAll()
}
+44 -10
View File
@@ -20,8 +20,9 @@ func TestInstanceFromInbound(t *testing.T) {
`"domainFronting":{"ip":"127.0.0.1","port":9443,"proxyProtocol":true},` +
`"throttleMaxConnections":5000,` +
`"routeThroughXray":true,"routeXrayPort":50000,` +
`"adTag":" 0123456789abcdef0123456789abcdef ",` +
`"clients":[` +
`{"email":"alice","secret":"` + aliceSecret + `","enable":true},` +
`{"email":"alice","secret":"` + aliceSecret + `","adTag":"fedcba9876543210fedcba9876543210","enable":true},` +
`{"email":"bob","secret":"","enable":true},` +
`{"email":"carol","secret":"eeaa","enable":false}]}`,
}
@@ -38,6 +39,12 @@ func TestInstanceFromInbound(t *testing.T) {
if inst.Secrets[0].Secret != aliceSecret {
t.Fatalf("a valid secret must be preserved, got %q", inst.Secrets[0].Secret)
}
if inst.Secrets[0].AdTag != "fedcba9876543210fedcba9876543210" {
t.Fatalf("the client ad-tag override must be parsed, got %q", inst.Secrets[0].AdTag)
}
if inst.AdTag != "0123456789abcdef0123456789abcdef" {
t.Fatalf("the inbound ad-tag must be trimmed and kept, got %q", inst.AdTag)
}
if inst.Port != 8443 || inst.Id != 3 {
t.Fatalf("bad instance %+v", inst)
}
@@ -62,6 +69,17 @@ func TestInstanceFromInbound(t *testing.T) {
if _, ok := InstanceFromInbound(noSecrets); ok {
t.Fatal("an inbound with no active secret should not produce an instance")
}
badTags := &model.Inbound{Protocol: model.MTProto, Settings: `{"adTag":"nope",` +
`"clients":[{"email":"x","secret":"ee00","adTag":"deadbeef","enable":true}]}`}
badInst, ok := InstanceFromInbound(badTags)
if !ok {
t.Fatal("expected a usable instance despite malformed ad tags")
}
if badInst.AdTag != "" || badInst.Secrets[0].AdTag != "" {
t.Fatalf("malformed ad tags must be dropped so the generated config stays valid, got global=%q client=%q",
badInst.AdTag, badInst.Secrets[0].AdTag)
}
}
func TestRenderConfig(t *testing.T) {
@@ -70,8 +88,8 @@ func TestRenderConfig(t *testing.T) {
bare := renderConfig(Instance{
Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}},
Listen: "0.0.0.0", Port: 8443,
}, 5000)
for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]"} {
}, 5000, "")
for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[secret-ad-tags]", "api-token"} {
if strings.Contains(bare, unwanted) {
t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare)
}
@@ -87,21 +105,26 @@ func TestRenderConfig(t *testing.T) {
}
// A fully configured instance emits every option, the fronting section (as
// host, not the fork-deprecated ip), the throttle block, and [secrets] last.
// host, not the fork-deprecated ip), the throttle block, the per-client
// ad-tag overrides, and [secrets] last.
full := renderConfig(Instance{
Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}},
Listen: "0.0.0.0", Port: 443,
Secrets: []SecretEntry{
{Name: "alice", Secret: "ee11"},
{Name: "bob", Secret: "ee22", AdTag: "fedcba9876543210fedcba9876543210"},
},
Listen: "0.0.0.0", Port: 443,
Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6",
FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true,
ThrottleMaxConnections: 5000,
AdTag: "0123456789abcdef0123456789abcdef",
PublicIPv4: "1.2.3.4",
PublicIPv6: "2001:db8::1",
}, 6000)
}, 6000, "sesame")
for _, want := range []string{
"debug = true\n",
"proxy-protocol-listener = true\n",
`prefer-ip = "only-ipv6"`,
`api-token = "sesame"`,
`ad-tag = "0123456789abcdef0123456789abcdef"`,
`public-ipv4 = "1.2.3.4"`,
`public-ipv6 = "2001:db8::1"`,
@@ -111,6 +134,8 @@ func TestRenderConfig(t *testing.T) {
"proxy-protocol = true\n",
"[throttle]",
"max-connections = 5000",
"[secret-ad-tags]",
`"bob" = "fedcba9876543210fedcba9876543210"`,
} {
if !strings.Contains(full, want) {
t.Fatalf("full config missing %q:\n%s", want, full)
@@ -119,6 +144,9 @@ func TestRenderConfig(t *testing.T) {
if strings.Contains(full, `ip = "127.0.0.1"`) {
t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full)
}
if strings.Contains(full, `"alice" = "0123456789abcdef0123456789abcdef"`) || strings.Contains(full, `"alice" = ""`) {
t.Fatalf("a client without an override must not appear in [secret-ad-tags]:\n%s", full)
}
// TOML requires top-level keys before any [section] header, and [secrets]
// must be the final section so trailing keys are not swallowed by a table.
if strings.Index(full, "prefer-ip") > strings.Index(full, "[domain-fronting]") {
@@ -130,6 +158,9 @@ func TestRenderConfig(t *testing.T) {
if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") {
t.Fatalf("[throttle] must precede [secrets]:\n%s", full)
}
if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[secret-ad-tags]") {
t.Fatalf("[secret-ad-tags] must precede [secrets]:\n%s", full)
}
}
func TestRenderConfigXrayEgress(t *testing.T) {
@@ -139,7 +170,7 @@ func TestRenderConfigXrayEgress(t *testing.T) {
Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}},
Listen: "0.0.0.0", Port: 443,
RouteThroughXray: true, XrayRoutePort: 50000,
}, 7000)
}, 7000, "")
if !strings.Contains(routed, "[network]") ||
!strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) {
t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed)
@@ -153,7 +184,7 @@ func TestRenderConfigXrayEgress(t *testing.T) {
{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443},
{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
} {
if got := renderConfig(inst, 7000); strings.Contains(got, "[network]") {
if got := renderConfig(inst, 7000, ""); strings.Contains(got, "[network]") {
t.Fatalf("unrouted config must omit [network]:\n%s", got)
}
}
@@ -195,6 +226,9 @@ func TestFingerprintSplit(t *testing.T) {
"remove": func(i *Instance) { i.Secrets = nil },
"rename": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a2", Secret: "ee"}} },
"adTag": func(i *Instance) { i.AdTag = "0123456789abcdef0123456789abcdef" },
"clientAdTag": func(i *Instance) {
i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", AdTag: "0123456789abcdef0123456789abcdef"}}
},
} {
t.Run("secrets/"+name, func(t *testing.T) {
changed := base
@@ -212,7 +246,7 @@ func TestFingerprintSplit(t *testing.T) {
t.Run("orderInsensitive", func(t *testing.T) {
forward := Instance{Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}, {Name: "bob", Secret: "ee22"}}}
reversed := Instance{Secrets: []SecretEntry{{Name: "bob", Secret: "ee22"}, {Name: "alice", Secret: "ee11"}}}
if got, want := forward.secretsFingerprint(), "adtag=|alice=ee11|bob=ee22"; got != want {
if got, want := forward.secretsFingerprint(), "adtag=|alice=ee11;tag=|bob=ee22;tag="; got != want {
t.Fatalf("secrets fingerprint must join sorted pairs: got %q, want %q", got, want)
}
if forward.secretsFingerprint() != reversed.secretsFingerprint() {