Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions example.config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,19 @@ allow-fallback-on-unknown-dc = false
# required.
[domain-fronting]
# By default, mtg resolves the fronting hostname (from the secret) via DNS
# to establish a TCP connection. If DNS resolution of that hostname is blocked,
# you can specify an IP address to connect to directly. The hostname is still
# used for SNI in the TLS handshake.
# to establish a TCP connection. If that resolution is blocked, or loops
# back to this server (e.g. mtg sits behind an SNI router whose DNS points
# at itself), override the destination here.
#
# default value is not set (DNS resolution is used).
# Use `host` — accepts a hostname or a literal IP. Hostnames are resolved
# at dial time, so a dual-stack DNS record can reach the right backend
# address family for IPv4 or IPv6 clients. `ip` is kept for backward
# compatibility (literal IP only). Setting both is an error.
#
# The hostname from the secret is still used for SNI in the TLS handshake.
#
# default value is not set (the secret's hostname is used).
# host = "fronting-backend"
# ip = "10.10.10.11"

# FakeTLS uses domain fronting protection. So it needs to know a port to
Expand Down
4 changes: 2 additions & 2 deletions internal/cli/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,8 @@ func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, addresses []string) e

func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
host := d.conf.Secret.Host
if ip := d.conf.GetDomainFrontingIP(nil); ip != "" {
host = ip
if override := d.conf.GetDomainFrontingHost(); override != "" {
host = override
}

port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/run_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ func runProxy(conf *config.Config, version string) error { //nolint: funlen, cyc
Secret: conf.Secret,
Concurrency: conf.GetConcurrency(mtglib.DefaultConcurrency),
DomainFrontingPort: conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort),
DomainFrontingIP: conf.GetDomainFrontingIP(nil),
DomainFrontingIP: conf.GetDomainFrontingHost(),
DomainFrontingProxyProtocol: conf.GetDomainFrontingProxyProtocol(false),
PreferIP: conf.PreferIP.Get(mtglib.DefaultPreferIP),
AutoUpdate: conf.AutoUpdate.Get(false),
Expand Down
13 changes: 10 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"net"
"net/url"

"github.com/9seconds/mtg/v2/mtglib"
Expand Down Expand Up @@ -38,6 +37,7 @@ type Config struct {
PublicIPv4 TypeIP `json:"publicIpv4"`
PublicIPv6 TypeIP `json:"publicIpv6"`
DomainFronting struct {
Host TypeHost `json:"host"`
IP TypeIP `json:"ip"`
Port TypePort `json:"port"`
ProxyProtocol TypeBool `json:"proxyProtocol"`
Expand Down Expand Up @@ -117,11 +117,14 @@ func (c *Config) GetDomainFrontingPort(defaultValue uint) uint {
return c.DomainFrontingPort.Get(defaultValue)
}

func (c *Config) GetDomainFrontingIP(defaultValue net.IP) string {
func (c *Config) GetDomainFrontingHost() string {
if host := c.DomainFronting.Host.Get(""); host != "" {
return host
}
if ip := c.DomainFronting.IP.Get(nil); ip != nil {
return ip.String()
}
if ip := c.DomainFrontingIP.Get(defaultValue); ip != nil {
if ip := c.DomainFrontingIP.Get(nil); ip != nil {
return ip.String()
}
return ""
Expand All @@ -140,6 +143,10 @@ func (c *Config) Validate() error {
return fmt.Errorf("incorrect bind-to parameter %s", c.BindTo.String())
}

if c.DomainFronting.Host.Get("") != "" && c.DomainFronting.IP.Get(nil) != nil {
return fmt.Errorf("[domain-fronting] host and ip are mutually exclusive; pick one")
}

return nil
}

Expand Down
37 changes: 37 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,43 @@ func (suite *ConfigTestSuite) TestString() {
suite.NotEmpty(conf.String())
}

func (suite *ConfigTestSuite) TestDomainFrontingHostAndIPMutuallyExclusive() {
conf, err := config.Parse(suite.ReadConfig("minimal.toml"))
suite.NoError(err)

suite.NoError(conf.DomainFronting.Host.Set("fronting-backend"))
suite.NoError(conf.DomainFronting.IP.Set("10.0.0.10"))
suite.Error(conf.Validate())
}

func (suite *ConfigTestSuite) TestDomainFrontingHostFromTOML() {
conf, err := config.Parse(suite.ReadConfig("domain_fronting_host.toml"))
suite.NoError(err)
suite.NoError(conf.Validate())
suite.Equal("fronting-backend", conf.GetDomainFrontingHost())
}

func (suite *ConfigTestSuite) TestDomainFrontingHostAcceptsLiteralIP() {
conf, err := config.Parse(suite.ReadConfig("domain_fronting_host_ip.toml"))
suite.NoError(err)
suite.NoError(conf.Validate())
suite.Equal("10.0.0.1", conf.GetDomainFrontingHost())
}

func (suite *ConfigTestSuite) TestDomainFrontingIPFromTOML() {
conf, err := config.Parse(suite.ReadConfig("domain_fronting_ip.toml"))
suite.NoError(err)
suite.NoError(conf.Validate())
suite.Equal("10.0.0.10", conf.GetDomainFrontingHost())
}

func (suite *ConfigTestSuite) TestDomainFrontingNotSet() {
conf, err := config.Parse(suite.ReadConfig("minimal.toml"))
suite.NoError(err)
suite.NoError(conf.Validate())
suite.Equal("", conf.GetDomainFrontingHost())
}

func TestConfig(t *testing.T) {
t.Parallel()
suite.Run(t, &ConfigTestSuite{})
Expand Down
1 change: 1 addition & 0 deletions internal/config/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type tomlConfig struct {
PublicIPv4 string `toml:"public-ipv4" json:"publicIpv4,omitempty"`
PublicIPv6 string `toml:"public-ipv6" json:"publicIpv6,omitempty"`
DomainFronting struct {
Host string `toml:"host" json:"host,omitempty"`
IP string `toml:"ip" json:"ip,omitempty"`
Port uint `toml:"port" json:"port,omitempty"`
ProxyProtocol bool `toml:"proxy-protocol" json:"proxyProtocol,omitempty"`
Expand Down
5 changes: 5 additions & 0 deletions internal/config/testdata/domain_fronting_host.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
secret = "7oe1GqLy6TBc38CV3jx7q09nb29nbGUuY29t"
bind-to = "0.0.0.0:3128"

[domain-fronting]
host = "fronting-backend"
5 changes: 5 additions & 0 deletions internal/config/testdata/domain_fronting_host_ip.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
secret = "7oe1GqLy6TBc38CV3jx7q09nb29nbGUuY29t"
bind-to = "0.0.0.0:3128"

[domain-fronting]
host = "10.0.0.1"
5 changes: 5 additions & 0 deletions internal/config/testdata/domain_fronting_ip.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
secret = "7oe1GqLy6TBc38CV3jx7q09nb29nbGUuY29t"
bind-to = "0.0.0.0:3128"

[domain-fronting]
ip = "10.0.0.10"
61 changes: 61 additions & 0 deletions internal/config/type_host.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package config

import (
"fmt"
"net"
"strings"
)

// TypeHost is a non-empty string that is either a literal IP address
// (IPv4 or IPv6) or a hostname suitable for DNS resolution. It does not
// include a port — the port belongs in a separate field.
type TypeHost struct {
Value string
}

func (t *TypeHost) Set(value string) error {
if value == "" {
return fmt.Errorf("host cannot be empty")
}

if net.ParseIP(value) != nil {
t.Value = value

return nil
}

if strings.ContainsAny(value, " \t\n/?#") {
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if there is a possibility to validate that this domain is resolvable. We can set any double dutch here. IP is fine, but I do believe that we can do something about resolving hostname.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd push back on doing DNS at parse time. Three reasons:

  1. Codebase precedent. The closest existing field is mtglib.Secret.Host (the secret's SNI hostname), and Secret.Set() does no DNS validation — only non-empty. Same "any double dutch" risk, deliberate choice.

  2. The reachability check already lives in doctor. checkFrontingDomain() in internal/cli/doctor.go resolves and dials the fronting target end-to-end; with this PR it picks up host via GetDomainFrontingHost(). A bogus hostname surfaces the dialer's DNS error there. That's the right layer for semantic checks — explicit, opt-in, with proper diagnostics.

  3. Resolving at parse time defeats the point of accepting a hostname. The motivating case (mtg behind an SNI router on a docker network) specifically needs dial-time resolution: the alias may resolve in-container but not on the host, and the address family can flip between v4/v6 per client (Happy Eyeballs). If we resolve at parse, either we cache the IP and lose all that, or we discard and resolve again at dial — in which case the parse-time resolve is just a flaky boot dependency.

Operational: a transient DNS hiccup at startup would prevent the proxy from starting, and a one-shot resolve doesn't catch the host going stale later — so it adds fragility without much real safety.

If the concern is that doctor's message for an unresolvable host is too generic (it surfaces whatever DialContext returns), I can add an explicit LookupIPAddr step in checkFrontingDomain so the error reads "hostname X cannot be resolved" rather than being nested inside a dial error. Want me to wire that in?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, thanks. I see your point. But I must reply on that argument:

The motivating case (mtg behind an SNI router on a docker network) specifically needs dial-time resolution: the alias may resolve in-container but not on the host, and the address family can flip between v4/v6 per client (Happy Eyeballs)

We should not think about different modes, host and container one. There should be only one environment we have to think about: one that runs mtg. If it happens to be in a container, let it be it. If it happens to be a generic host one, let it be a host one. If something is resolved on the host, but not in a container, then this is not a concern of mtg.

But this is not a performative concern, just my opinion in this regard. Such rigid behavior helps making a resilient software

return fmt.Errorf("incorrect host %q", value)
}

// At this point value is not a parsed IP (IPv6 literals returned
// above), so any remaining colon indicates a host:port form, which
// belongs in a separate field.
if strings.Contains(value, ":") {
return fmt.Errorf("host must not contain a port: %q", value)
}

t.Value = value

return nil
}

func (t TypeHost) Get(defaultValue string) string {
if t.Value == "" {
return defaultValue
}

return t.Value
}

func (t *TypeHost) UnmarshalText(data []byte) error {
return t.Set(string(data))
}

func (t TypeHost) MarshalText() ([]byte, error) {
return []byte(t.Value), nil
}

func (t TypeHost) String() string {
return t.Value
}
77 changes: 77 additions & 0 deletions internal/config/type_host_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package config_test

import (
"encoding/json"
"testing"

"github.com/9seconds/mtg/v2/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)

type typeHostTestStruct struct {
Value config.TypeHost `json:"value"`
}

type TypeHostTestSuite struct {
suite.Suite
}

func (suite *TypeHostTestSuite) TestUnmarshalFail() {
testData := []string{
"",
"web:8443",
"http://example.com",
"example.com/path",
"two words",
}

for _, v := range testData {
data, err := json.Marshal(map[string]string{
"value": v,
})
suite.NoError(err)

suite.T().Run(v, func(t *testing.T) {
assert.Error(t, json.Unmarshal(data, &typeHostTestStruct{}))
})
}
}

func (suite *TypeHostTestSuite) TestUnmarshalOk() {
testData := []string{
"example.com",
"web",
"sub.example.com",
"127.0.0.1",
"2001:db8::1",
}

for _, v := range testData {
value := v

data, err := json.Marshal(map[string]string{
"value": value,
})
suite.NoError(err)

suite.T().Run(value, func(t *testing.T) {
testStruct := &typeHostTestStruct{}
assert.NoError(t, json.Unmarshal(data, testStruct))
assert.Equal(t, value, testStruct.Value.Get(""))
})
}
}

func (suite *TypeHostTestSuite) TestGet() {
value := config.TypeHost{}
suite.Equal("default", value.Get("default"))

suite.NoError(value.Set("example.com"))
suite.Equal("example.com", value.Get("default"))
}

func TestTypeHost(t *testing.T) {
t.Parallel()
suite.Run(t, &TypeHostTestSuite{})
}
11 changes: 6 additions & 5 deletions mtglib/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type Proxy struct {
idleTimeout time.Duration
handshakeTimeout time.Duration
domainFrontingPort int
domainFrontingIP string
domainFrontingHost string
domainFrontingProxyProtocol bool
workerPool *ants.PoolWithFunc
telegram *dc.Telegram
Expand All @@ -48,11 +48,12 @@ type Proxy struct {
}

// DomainFrontingAddress returns a host:port pair for a fronting domain.
// If DomainFrontingIP is set, it is used instead of resolving the hostname.
// If a fronting host (literal IP or hostname) is configured, it is used
// instead of resolving the secret's hostname.
func (p *Proxy) DomainFrontingAddress() string {
host := p.secret.Host
if p.domainFrontingIP != "" {
host = p.domainFrontingIP
if p.domainFrontingHost != "" {
host = p.domainFrontingHost
}

return net.JoinHostPort(host, strconv.Itoa(p.domainFrontingPort))
Expand Down Expand Up @@ -354,7 +355,7 @@ func NewProxy(opts ProxyOpts) (*Proxy, error) {
eventStream: opts.EventStream,
logger: logger,
domainFrontingPort: opts.getDomainFrontingPort(),
domainFrontingIP: opts.DomainFrontingIP,
domainFrontingHost: opts.DomainFrontingIP,
tolerateTimeSkewness: opts.getTolerateTimeSkewness(),
idleTimeout: opts.getIdleTimeout(),
handshakeTimeout: opts.getHandshakeTimeout(),
Expand Down
13 changes: 8 additions & 5 deletions mtglib/proxy_opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,14 @@ type ProxyOpts struct {
// This is an optional setting.
DomainFrontingPort uint

// DomainFrontingIP is an IP address to use when connecting to the fronting
// domain instead of resolving the hostname from the secret via DNS.
//
// This is useful when DNS resolution of the fronting host is blocked.
// The hostname from the secret is still used for SNI in the TLS handshake.
// DomainFrontingIP is the address to use when connecting to the fronting
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense to deprecate this option then. Otherwise we will have 2 ways how to set the same effective values

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the principle — two ways to set the same effective value is confusing. The codebase already has a clean pattern for this: checkDeprecatedConfig() in internal/cli/doctor.go plus the tplWDeprecatedConfig template (already deprecates the flat domain-fronting-ip/domain-fronting-port in favour of the [domain-fronting] block). I can mirror it for [domain-fronting].iphost:

  1. Add a deprecation entry to checkDeprecatedConfig (when = "2.4.0", one minor after the existing 2.3.0 removals).
  2. Update example.config.toml to mark # ip = "10.10.10.11" deprecated, matching the comment style of the other deprecated blocks.
  3. Add // Deprecated: use Host instead. on Config.DomainFronting.IP.

One thing I'd like to pin down before the commit: scope. Are you asking to deprecate the config option [domain-fronting].ip, or also the public Go field mtglib.ProxyOpts.DomainFrontingIP?

The Go field is the dial target consumed by anyone using mtg as a library. With this PR it already holds either a hostname or an IP, so deprecating the symbol would mean introducing a renamed DomainFrontingHost for the same value — a breaking API change. I'd lean toward only deprecating the config key and leaving the Go API alone (maybe with a clarifying note in the godoc), but it's your call.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, glad we agree here. Yes, I'm thinking about config option. We can add a comment for DomainFrontingIP that it is present but unnecessary, and just remove all its usage. I understand that in theory it is going to break backward compatibility but this is not a new pattern. I think we are fine here.

For example, this is how Go itself communicates such deprecations: https://pkg.go.dev/net just take a look at DualStack. It has been deprecated and flipped its original meaning. Technically, this was not backward compatible change.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two scope questions before the commit:

  1. DomainFrontingIP deprecation. "Remove all its usage" reads two ways: (a) soft — NewProxy copies IP → Host when Host is empty, existing library callers keep working; (b) strict no-op à la net.Dialer.DualStack — field marked Deprecated, value silently ignored. Your DualStack reference points at (b); I'll go that way unless you'd rather not silently break out-of-tree callers.

  2. CLI flag. --domain-fronting-ip in simple_run is the same situation at the CLI layer. Add --domain-fronting-host + deprecate the old flag in this PR, or leave the CLI surface for a follow-up?

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that good compromise would be to issue a warning in logs if any value is set. And ignore afterwards

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirming: warn + ignore for the config key, the DomainFrontingIP Go field, and the --domain-fronting-ip CLI flag.

One side effect worth flagging: a config with only ip set (no host) will warn and effectively disable domain-fronting until the user renames the key — same deliberate compatibility break as net.Dialer.DualStack. Will push the deprecation as the next commit on this branch.

// domain instead of resolving the hostname from the secret via DNS. It
// can be a literal IP or a hostname; hostnames are resolved at dial time
// via the native dialer (which honours dual-stack and Happy Eyeballs).
//
// This is useful when DNS resolution of the secret's hostname is blocked
// or loops back to this server. The hostname from the secret is still
// used for SNI in the TLS handshake.
//
// This is an optional setting.
DomainFrontingIP string
Expand Down
Loading