Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions cmd/agentmesh-one/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,12 @@ func main() {
if tun != nil {
go func() {
<-tun.Done()
// The connector shares the terminal's process group, so the
// signal that stops this process stops it too: an exit during
// shutdown is expected, not a lost tunnel.
if cmd.Context().Err() != nil {
return
}
if err := tun.Err(); err != nil {
logger.Errorf("Tunnel %s closed: %v; remote devices can no longer reach %s", tunnelProvider, err, tun.URL())
}
Expand Down
15 changes: 11 additions & 4 deletions internal/tunnel/cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ func (c *Cloudflare) Name() string { return "cloudflare" }

// Open implements Provider.
func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
if c.Token != "" && strings.TrimSpace(c.ExternalURL) == "" {
namedURL := strings.TrimRight(strings.TrimSpace(c.ExternalURL), "/")
if c.Token != "" && namedURL == "" {
return nil, fmt.Errorf("cloudflare named tunnel requires ExternalURL (--external-url)")
}
binary, err := c.resolveBinary(ctx)
Expand Down Expand Up @@ -135,7 +136,10 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
cancel()
return nil, fmt.Errorf("failed to start cloudflared: %w", err)
}
t := &process{cancel: cancel, done: make(chan struct{}), namedURL: strings.TrimRight(strings.TrimSpace(c.ExternalURL), "/")}
t := &process{cancel: cancel, done: make(chan struct{})}
if c.Token != "" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for fixing the quick-tunnel URL! How about refusing ExternalURL without a Token instead of ignoring it? The CLI already refuses that combination. The check at the top of Open already refuses the opposite case, Token without ExternalURL. Something like:

an early exit pla

if c.Token == "" && namedURL != "" {
	return nil, fmt.Errorf("cloudflare ExternalURL applies only to a named tunnel (Token)")
}

as an early exit placed right after the check in line 107

t.namedURL = namedURL
}
Comment on lines +140 to +142

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If c.ExternalURL consists only of slashes and spaces (e.g., "/"), the check at line 106 passes, but t.namedURL becomes empty after trimming trailing slashes. This causes the tunnel to fall back to quick tunnel mode in scan and eventually time out. We should validate that t.namedURL is not empty after trimming.

	if c.Token != "" {
		t.namedURL = strings.TrimRight(strings.TrimSpace(c.ExternalURL), "/")
		if t.namedURL == "" {
			return nil, fmt.Errorf("cloudflare named tunnel requires a valid ExternalURL")
		}
	}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, taken in 0d7885e, with one change: the check goes before cloudflared starts rather than after it, since returning at that point would leave the process running. ExternalURL is now trimmed once up front, and a named tunnel whose hostname trims to nothing is refused with the existing requires ExternalURL error. TestCloudflareNamedTunnelRefusesAnEmptyExternalURL covers "", spaces, "/" and " // "; the slash cases failed on the previous code.

urlCh := make(chan string, 1)
go t.scan(pr, urlCh)
go func() {
Expand Down Expand Up @@ -308,10 +312,13 @@ func (p *process) Close() error {
}

// finish records the exit and releases Done; an exit caused by Close is
// not an error.
// not an error, any other exit is, even with status 0.
func (p *process) finish(err error) {
p.mu.Lock()
if !p.closed && err != nil {
if !p.closed {
if err == nil {
err = errors.New("exit status 0")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using a more descriptive error message like "connector exited unexpectedly with status 0" instead of "exit status 0" makes it clearer in the logs that this was an abnormal termination, especially since status 0 normally indicates success.

Suggested change
err = errors.New("exit status 0")
err = errors.New("connector exited unexpectedly with status 0")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I'd keep exit status 0. It is the text exec.ExitError gives for any other status (exit status 3), so Err() reads the same whichever way the connector exits, and it never appears alone. The watcher logs Tunnel cloudflare closed: exit status 0; remote devices can no longer reach <url>, and Open returns cloudflared exited before publishing a URL: exit status 0, so the line already says that the exit was unexpected.

}
p.err = err
}
p.mu.Unlock()
Expand Down
65 changes: 65 additions & 0 deletions internal/tunnel/cloudflare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,39 @@ func TestCloudflareOpenReportsEarlyExit(t *testing.T) {
}
}

// A connector that stops on its own reports why even when its exit status
// is 0: only Close leaves Err nil, and the caller logs the outage only when
// Err is set.
func TestCloudflareReportsUnrequestedCleanExit(t *testing.T) {
bin := stubCloudflared(t, `echo "INF starting" >&2; exit 0`)
_, err := (&Cloudflare{Binary: bin, Timeout: 5 * time.Second}).Open(context.Background(), "http://127.0.0.1:1")
if err == nil || strings.Contains(err.Error(), "%!") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: Thanks for covering both the Open path and the after-Open path in one test! This check passes for any error that does not contain %!, a failed start for example. How about checking for the reason itself?

Suggested change
if err == nil || strings.Contains(err.Error(), "%!") {
if err == nil || !strings.Contains(err.Error(), "exit status 0") {

t.Errorf("Open error = %v, want an early-exit error with a reason", err)
}

gate := filepath.Join(t.TempDir(), "exit")
bin = stubCloudflared(t, `echo "INF | https://installed-quick-1234.trycloudflare.com |" >&2
while [ ! -e "`+gate+`" ]; do sleep 0.01; done
exit 0
`)
tun, err := (&Cloudflare{Binary: bin, Timeout: 5 * time.Second, LookupHost: resolved}).Open(context.Background(), "http://127.0.0.1:1")
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = tun.Close() })
if err := os.WriteFile(gate, nil, 0o600); err != nil {
t.Fatal(err)
}
select {
case <-tun.Done():
case <-time.After(10 * time.Second):
t.Fatal("Done not closed after the connector exited")
}
if tun.Err() == nil {
t.Fatal("Err = nil after the connector exited without Close, want an error")
}
}

func TestCloudflareOpenTimesOutWithoutURL(t *testing.T) {
bin := stubCloudflared(t, `trap 'exit 0' TERM; while :; do sleep 1; done`)
p := &Cloudflare{Binary: bin, Timeout: 200 * time.Millisecond}
Expand Down Expand Up @@ -434,3 +467,35 @@ func TestLookup(t *testing.T) {
t.Fatalf("Lookup unknown = %v", err)
}
}

// ExternalURL names the hostname of a named tunnel; without a Token the
// connector runs a quick tunnel, and the URL published is the one it was
// assigned, not ExternalURL.
func TestCloudflareQuickTunnelIgnoresExternalURL(t *testing.T) {
bin := stubCloudflared(t, `echo "INF | https://quick-ext-1234.trycloudflare.com |" >&2
echo "INF Registered tunnel connection connIndex=0 location=ams01 protocol=quic" >&2
trap 'exit 0' TERM
while :; do sleep 1; done
`)
p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second, LookupHost: resolved, ExternalURL: "https://mesh.example.com"}
tun, err := p.Open(context.Background(), "http://127.0.0.1:1")
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = tun.Close() })
if got, want := tun.URL(), "https://quick-ext-1234.trycloudflare.com"; got != want {
t.Fatalf("URL = %q, want the assigned quick-tunnel URL %q", got, want)
}
}

// A named tunnel needs a hostname: an ExternalURL that trims to nothing is
// refused before cloudflared is started.
func TestCloudflareNamedTunnelRefusesAnEmptyExternalURL(t *testing.T) {
for _, externalURL := range []string{"", " ", "/", " // "} {
p := &Cloudflare{Binary: filepath.Join(t.TempDir(), "never-started"), Token: "token", ExternalURL: externalURL}
_, err := p.Open(context.Background(), "http://127.0.0.1:1")
if err == nil || !strings.Contains(err.Error(), "requires ExternalURL") {
t.Errorf("Open with ExternalURL %q: err = %v, want the ExternalURL refusal", externalURL, err)
}
}
}
Loading