Compare commits

...

19 Commits

Author SHA1 Message Date
João "Pisco" Fernandes d8a066628b Release 2025.4.0 2025-04-01 20:23:54 +01:00
João "Pisco" Fernandes 553e77e061 chore: fix linter rules 2025-04-01 18:57:55 +01:00
Cyb3r Jak3 8f94f54ec7
feat: Adds a new command line for tunnel run for token file
Adds a new command line flag for `tunnel run` which allows a file to be
read for the token. I've left the token command line argument with
priority.
2025-04-01 18:23:22 +01:00
gofastasf 2827b2fe8f
fix: Use path and filepath operation appropriately
Using path package methods can cause errors on windows machines.

path methods are used for url operations and unix specific operation.

filepath methods are used for file system paths and its cross platform. 

Remove strings.HasSuffix and use filepath.Ext and path.Ext for file and
url extenstions respectively.
2025-04-01 17:59:43 +01:00
Rohan Mukherjee 6dc8ed710e
fix: expand home directory for credentials file
## Issue

The [documentation for creating a tunnel's configuration
file](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/create-local-tunnel/#4-create-a-configuration-file)
does not specify that the `credentials-file` field in `config.yml` needs
to be an absolute path.

A user (E.G. me 🤦) might add a path like `~/.cloudflared/<uuid>.json`
and wonder why the `cloudflared tunnel run` command is throwing a
credentials file not found error. Although one might consider it
intuitive, it's not a fair assumption as a lot of CLI tools allow file
paths with `~` for specifying files.

P.S. The tunnel ID in the following snippet is not a real tunnel ID, I
just generated it.
```
url: http://localhost:8000
tunnel: 958a1ef6-ff8c-4455-825a-5aed91242135
credentials-file: ~/.cloudflared/958a1ef6-ff8c-4455-825a-5aed91242135.json
```

Furthermore, the error has a confusing message for the user as the file
at the logged path actually exists, it is just that `os.Stat` failed
because it could not expand the `~`.

## Solution

This commit fixes the above issue by running a `homedir.Expand` on the
`credentials-file` path in the `credentialFinder` function.
2025-04-01 17:54:57 +01:00
Shereef Marzouk e0b1ac0d05
chore: Update tunnel configuration link in the readme 2025-04-01 17:53:29 +01:00
Bernhard M. Wiedemann e7c5eb54af
Use RELEASE_NOTES date instead of build date
Use `RELEASE_NOTES` date instead of build date
to make builds reproducible.
See https://reproducible-builds.org/ for why this is good
and https://reproducible-builds.org/specs/source-date-epoch/
for the definition of this variable.
This date call only works with GNU date and BSD date.

Alternatively,
https://reproducible-builds.org/docs/source-date-epoch/#makefile could
be implemented.

This patch was done while working on reproducible builds for openSUSE,
sponsored by the NLnet NGI0 fund.
2025-04-01 17:52:50 +01:00
teslaedison cfec602fa7
chore: remove repetitive words 2025-04-01 17:51:57 +01:00
Micah Yeager 6fceb94998
feat: emit explicit errors for the `service` command on unsupported OSes
Per the contribution guidelines, this seemed to me like a small enough
change to not warrant an issue before creating this pull request. Let me
know if you'd like me to create one anyway.

## Background

While working with `cloudflared` on FreeBSD recently, I noticed that
there's an inconsistency with the available CLI commands on that OS
versus others — namely that the `service` command doesn't exist at all
for operating systems other than Linux, macOS, and Windows.

Contrast `cloudflared --help` output on macOS versus FreeBSD (truncated
to focus on the `COMMANDS` section):

- Current help output on macOS:

  ```text
  COMMANDS:
     update     Update the agent if a new version exists
     version    Print the version
     proxy-dns  Run a DNS over HTTPS proxy server.
     tail       Stream logs from a remote cloudflared
     service    Manages the cloudflared launch agent
     help, h    Shows a list of commands or help for one command
     Access:
       access, forward  access <subcommand>
     Tunnel:
tunnel Use Cloudflare Tunnel to expose private services to the Internet
or to Cloudflare connected private users.
  ```
- Current help output on FreeBSD:
  ```text
  COMMANDS:
     update     Update the agent if a new version exists
     version    Print the version
     proxy-dns  Run a DNS over HTTPS proxy server.
     tail       Stream logs from a remote cloudflared
     help, h    Shows a list of commands or help for one command
     Access:
       access, forward  access <subcommand>
     Tunnel:
tunnel Use Cloudflare Tunnel to expose private services to the Internet
or to Cloudflare connected private users.
  ```

This omission has caused confusion for users (including me), especially
since the provided command in the Cloudflare Zero Trust dashboard
returns a seemingly-unrelated error message:

```console
$ sudo cloudflared service install ...
You did not specify any valid additional argument to the cloudflared tunnel command.

If you are trying to run a Quick Tunnel then you need to explicitly pass the --url flag.
Eg. cloudflared tunnel --url localhost:8080/.

Please note that Quick Tunnels are meant to be ephemeral and should only be used for testing purposes.
For production usage, we recommend creating Named Tunnels. (https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/)
```

## Contribution

This pull request adds a "stub" `service` command (including the usual
subcommands available on other OSes) to explicitly declare it as
unsupported on the operating system.

New help output on FreeBSD (and other operating systems where service
management is unsupported):

```text
COMMANDS:
   update     Update the agent if a new version exists
   version    Print the version
   proxy-dns  Run a DNS over HTTPS proxy server.
   tail       Stream logs from a remote cloudflared
   service    Manages the cloudflared system service (not supported on this operating system)
   help, h    Shows a list of commands or help for one command
   Access:
     access, forward  access <subcommand>
   Tunnel:
     tunnel  Use Cloudflare Tunnel to expose private services to the Internet or to   Cloudflare connected private users.
```

New outputs when running the service management subcommands:

```console
$ sudo cloudflared service install ...
service installation is not supported on this operating system
```

```console
$ sudo cloudflared service uninstall ...
service uninstallation is not supported on this operating system
```

This keeps the available commands consistent until proper service
management support can be added for these otherwise-supported operating
systems.
2025-04-01 17:48:20 +01:00
Roman cf817f7036
Fix messages to point to one.dash.cloudflare.com 2025-04-01 17:47:23 +01:00
VFLC c8724a290a
Fix broken links in `cmd/cloudflared/*.go` related to running tunnel as a service
This PR updates 3 broken links to document [run tunnel as a
service](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/configure-tunnels/local-management/as-a-service/).
2025-04-01 17:45:59 +01:00
João "Pisco" Fernandes e7586153be TUN-9101: Don't ignore errors on `cloudflared access ssh`
## Summary

This change ensures that errors resulting from the `cloudflared access ssh` call are no longer ignored. By returning the error from `carrier.StartClient` to the upstream, we ensure that these errors are properly logged on stdout, providing better visibility and debugging capabilities.

Relates to TUN-9101
2025-03-17 18:42:19 +00:00
Chung-Ting Huang 11777db304 TUN-9089: Pin go import to v0.30.0, v0.31.0 requires go 1.23
Closes TUN-9089
2025-03-06 12:05:24 +00:00
lneto 3f6b1f24d0 Release 2025.2.1 2025-02-26 16:44:32 +00:00
Luis Neto a4105e8708 TUN-9016: update base-debian to v12
## Summary

Fixes vulnerability ([CVE -2024-4741](https://github.com/advisories/GHSA-6vgq-8qjq-h578))

 Closes TUN-9016
2025-02-26 15:54:10 +00:00
Luis Neto 6496322bee TUN-9007: modify logic to resolve region when the tunnel token has an endpoint field
## Summary

Within the work of FEDRamp it is necessary to change the HA SD lookup to use as srv `fed-v2-origintunneld`

This work assumes that the tunnel token has an optional endpoint field which will be used to modify the behaviour of the HA SD lookup.

Finally, the presence of the endpoint will override region to _fed_ and fail if any value is passed for the flag region.

Closes TUN-9007
2025-02-25 19:03:41 +00:00
Luis Neto 906452a9c9 TUN-8960: Connect to FED API GW based on the OriginCert's endpoint
## Summary

Within the scope of the FEDRamp High RM, it is necessary to detect if an user should connect to a FEDRamp colo.

At first, it was considered to add the --fedramp as global flag however this could be a footgun for the user or even an hindrance, thus, the proposal is to save in the token (during login) if the user authenticated using the FEDRamp Dashboard. This solution makes it easier to the user as they will only be required to pass the flag in login and nothing else.

* Introduces the new field, endpoint, in OriginCert
* Refactors login to remove the private key and certificate which are no longer used
* Login will only store the Argo Tunnel Token
* Remove namedTunnelToken as it was only used to for serialization

Closes TUN-8960
2025-02-25 17:13:33 +00:00
Jingqi Huang d969fdec3e SDLC-3762: Remove backstage.io/source-location from catalog-info.yaml 2025-02-13 13:02:50 -08:00
João "Pisco" Fernandes 7336a1a4d6 TUN-8914: Create a flags module to group all cloudflared cli flags
## Summary

This commit refactors some of the flags of cloudflared to their own module, so that they can be used across the code without requiring to literal strings which are much more error prone.

 Closes TUN-8914
2025-02-06 03:30:27 -08:00
42 changed files with 617 additions and 440 deletions

View File

@ -22,7 +22,7 @@ RUN .teamcity/install-cloudflare-go.sh
RUN PATH="/tmp/go/bin:$PATH" make cloudflared RUN PATH="/tmp/go/bin:$PATH" make cloudflared
# use a distroless base image with glibc # use a distroless base image with glibc
FROM gcr.io/distroless/base-debian11:nonroot FROM gcr.io/distroless/base-debian12:nonroot
LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared" LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared"

View File

@ -17,7 +17,7 @@ RUN .teamcity/install-cloudflare-go.sh
RUN GOOS=linux GOARCH=amd64 PATH="/tmp/go/bin:$PATH" make cloudflared RUN GOOS=linux GOARCH=amd64 PATH="/tmp/go/bin:$PATH" make cloudflared
# use a distroless base image with glibc # use a distroless base image with glibc
FROM gcr.io/distroless/base-debian11:nonroot FROM gcr.io/distroless/base-debian12:nonroot
LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared" LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared"

View File

@ -17,7 +17,7 @@ RUN .teamcity/install-cloudflare-go.sh
RUN GOOS=linux GOARCH=arm64 PATH="/tmp/go/bin:$PATH" make cloudflared RUN GOOS=linux GOARCH=arm64 PATH="/tmp/go/bin:$PATH" make cloudflared
# use a distroless base image with glibc # use a distroless base image with glibc
FROM gcr.io/distroless/base-debian11:nonroot-arm64 FROM gcr.io/distroless/base-debian12:nonroot-arm64
LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared" LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared"

View File

@ -24,7 +24,7 @@ else
DEB_PACKAGE_NAME := $(BINARY_NAME) DEB_PACKAGE_NAME := $(BINARY_NAME)
endif endif
DATE := $(shell date -u '+%Y-%m-%d-%H%M UTC') DATE := $(shell date -u -r RELEASE_NOTES '+%Y-%m-%d-%H%M UTC')
VERSION_FLAGS := -X "main.Version=$(VERSION)" -X "main.BuildTime=$(DATE)" VERSION_FLAGS := -X "main.Version=$(VERSION)" -X "main.BuildTime=$(DATE)"
ifdef PACKAGE_MANAGER ifdef PACKAGE_MANAGER
VERSION_FLAGS := $(VERSION_FLAGS) -X "github.com/cloudflare/cloudflared/cmd/cloudflared/updater.BuiltForPackageManager=$(PACKAGE_MANAGER)" VERSION_FLAGS := $(VERSION_FLAGS) -X "github.com/cloudflare/cloudflared/cmd/cloudflared/updater.BuiltForPackageManager=$(PACKAGE_MANAGER)"

View File

@ -40,7 +40,7 @@ User documentation for Cloudflare Tunnel can be found at https://developers.clou
Once installed, you can authenticate `cloudflared` into your Cloudflare account and begin creating Tunnels to serve traffic to your origins. Once installed, you can authenticate `cloudflared` into your Cloudflare account and begin creating Tunnels to serve traffic to your origins.
* Create a Tunnel with [these instructions](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/create-tunnel) * Create a Tunnel with [these instructions](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/get-started/)
* Route traffic to that Tunnel: * Route traffic to that Tunnel:
* Via public [DNS records in Cloudflare](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/routing-to-tunnel/dns) * Via public [DNS records in Cloudflare](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/routing-to-tunnel/dns)
* Or via a public hostname guided by a [Cloudflare Load Balancer](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/routing-to-tunnel/lb) * Or via a public hostname guided by a [Cloudflare Load Balancer](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/routing-to-tunnel/lb)

View File

@ -1,3 +1,24 @@
2025.4.0
- 2025-04-02 Fix broken links in `cmd/cloudflared/*.go` related to running tunnel as a service
- 2025-04-02 chore: remove repetitive words
- 2025-04-01 Fix messages to point to one.dash.cloudflare.com
- 2025-04-01 feat: emit explicit errors for the `service` command on unsupported OSes
- 2025-04-01 Use RELEASE_NOTES date instead of build date
- 2025-04-01 chore: Update tunnel configuration link in the readme
- 2025-04-01 fix: expand home directory for credentials file
- 2025-04-01 fix: Use path and filepath operation appropriately
- 2025-04-01 feat: Adds a new command line for tunnel run for token file
- 2025-04-01 chore: fix linter rules
- 2025-03-17 TUN-9101: Don't ignore errors on `cloudflared access ssh`
- 2025-03-06 TUN-9089: Pin go import to v0.30.0, v0.31.0 requires go 1.23
2025.2.1
- 2025-02-26 TUN-9016: update base-debian to v12
- 2025-02-25 TUN-8960: Connect to FED API GW based on the OriginCert's endpoint
- 2025-02-25 TUN-9007: modify logic to resolve region when the tunnel token has an endpoint field
- 2025-02-13 SDLC-3762: Remove backstage.io/source-location from catalog-info.yaml
- 2025-02-06 TUN-8914: Create a flags module to group all cloudflared cli flags
2025.2.0 2025.2.0
- 2025-02-03 TUN-8914: Add a new configuration to locally override the max-active-flows - 2025-02-03 TUN-8914: Add a new configuration to locally override the max-active-flows
- 2025-02-03 Bump x/crypto to 0.31.0 - 2025-02-03 Bump x/crypto to 0.31.0

View File

@ -4,7 +4,6 @@ metadata:
name: cloudflared name: cloudflared
description: Client for Cloudflare Tunnels description: Client for Cloudflare Tunnels
annotations: annotations:
backstage.io/source-location: url:https://bitbucket.cfdata.org/projects/TUN/repos/cloudflared/browse
cloudflare.com/software-excellence-opt-in: "true" cloudflare.com/software-excellence-opt-in: "true"
cloudflare.com/jira-project-key: "TUN" cloudflare.com/jira-project-key: "TUN"
cloudflare.com/jira-project-component: "Cloudflare Tunnel" cloudflare.com/jira-project-component: "Cloudflare Tunnel"

View File

@ -16,7 +16,7 @@ bullseye: &bullseye
- golangci-lint - golangci-lint
pre-cache: &build_pre_cache pre-cache: &build_pre_cache
- export GOCACHE=/cfsetup_build/.cache/go-build - export GOCACHE=/cfsetup_build/.cache/go-build
- go install golang.org/x/tools/cmd/goimports@latest - go install golang.org/x/tools/cmd/goimports@v0.30.0
post-cache: post-cache:
# Linting # Linting
- make lint - make lint

View File

@ -104,7 +104,7 @@ func ssh(c *cli.Context) error {
case 3: case 3:
options.OriginURL = fmt.Sprintf("https://%s:%s", parts[2], parts[1]) options.OriginURL = fmt.Sprintf("https://%s:%s", parts[2], parts[1])
options.TLSClientConfig = &tls.Config{ options.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true, InsecureSkipVerify: true, // #nosec G402
ServerName: parts[0], ServerName: parts[0],
} }
log.Warn().Msgf("Using insecure SSL connection because SNI overridden to %s", parts[0]) log.Warn().Msgf("Using insecure SSL connection because SNI overridden to %s", parts[0])
@ -141,6 +141,5 @@ func ssh(c *cli.Context) error {
logger := log.With().Str("host", url.Host).Logger() logger := log.With().Str("host", url.Host).Logger()
s = stream.NewDebugStream(s, &logger, maxMessages) s = stream.NewDebugStream(s, &logger, maxMessages)
} }
carrier.StartClient(wsConn, s, options) return carrier.StartClient(wsConn, s, options)
return nil
} }

View File

@ -19,6 +19,7 @@ import (
"github.com/cloudflare/cloudflared/carrier" "github.com/cloudflare/cloudflared/carrier"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/logger" "github.com/cloudflare/cloudflared/logger"
"github.com/cloudflare/cloudflared/sshgen" "github.com/cloudflare/cloudflared/sshgen"
"github.com/cloudflare/cloudflared/token" "github.com/cloudflare/cloudflared/token"
@ -172,15 +173,15 @@ func Commands() []*cli.Command {
EnvVars: []string{"TUNNEL_SERVICE_TOKEN_SECRET"}, EnvVars: []string{"TUNNEL_SERVICE_TOKEN_SECRET"},
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: logger.LogFileFlag, Name: cfdflags.LogFile,
Usage: "Save application log to this file for reporting issues.", Usage: "Save application log to this file for reporting issues.",
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: logger.LogSSHDirectoryFlag, Name: cfdflags.LogDirectory,
Usage: "Save application log to this directory for reporting issues.", Usage: "Save application log to this directory for reporting issues.",
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: logger.LogSSHLevelFlag, Name: cfdflags.LogLevelSSH,
Aliases: []string{"loglevel"}, //added to match the tunnel side Aliases: []string{"loglevel"}, //added to match the tunnel side
Usage: "Application logging level {debug, info, warn, error, fatal}. ", Usage: "Application logging level {debug, info, warn, error, fatal}. ",
}, },
@ -342,7 +343,7 @@ func run(cmd string, args ...string) error {
return err return err
} }
go func() { go func() {
io.Copy(os.Stderr, stderr) _, _ = io.Copy(os.Stderr, stderr)
}() }()
stdout, err := c.StdoutPipe() stdout, err := c.StdoutPipe()
@ -350,7 +351,7 @@ func run(cmd string, args ...string) error {
return err return err
} }
go func() { go func() {
io.Copy(os.Stdout, stdout) _, _ = io.Copy(os.Stdout, stdout)
}() }()
return c.Run() return c.Run()
} }
@ -531,7 +532,7 @@ func isFileThere(candidate string) bool {
} }
// verifyTokenAtEdge checks for a token on disk, or generates a new one. // verifyTokenAtEdge checks for a token on disk, or generates a new one.
// Then makes a request to to the origin with the token to ensure it is valid. // Then makes a request to the origin with the token to ensure it is valid.
// Returns nil if token is valid. // Returns nil if token is valid.
func verifyTokenAtEdge(appUrl *url.URL, appInfo *token.AppInfo, c *cli.Context, log *zerolog.Logger) error { func verifyTokenAtEdge(appUrl *url.URL, appInfo *token.AppInfo, c *cli.Context, log *zerolog.Logger) error {
headers := parseRequestHeaders(c.StringSlice(sshHeaderFlag)) headers := parseRequestHeaders(c.StringSlice(sshHeaderFlag))

View File

@ -4,7 +4,7 @@ import (
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc" "github.com/urfave/cli/v2/altsrc"
"github.com/cloudflare/cloudflared/logger" cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
) )
var ( var (
@ -15,14 +15,14 @@ var (
func ConfigureLoggingFlags(shouldHide bool) []cli.Flag { func ConfigureLoggingFlags(shouldHide bool) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: logger.LogLevelFlag, Name: cfdflags.LogLevel,
Value: "info", Value: "info",
Usage: "Application logging level {debug, info, warn, error, fatal}. " + debugLevelWarning, Usage: "Application logging level {debug, info, warn, error, fatal}. " + debugLevelWarning,
EnvVars: []string{"TUNNEL_LOGLEVEL"}, EnvVars: []string{"TUNNEL_LOGLEVEL"},
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: logger.LogTransportLevelFlag, Name: cfdflags.TransportLogLevel,
Aliases: []string{"proto-loglevel"}, // This flag used to be called proto-loglevel Aliases: []string{"proto-loglevel"}, // This flag used to be called proto-loglevel
Value: "info", Value: "info",
Usage: "Transport logging level(previously called protocol logging level) {debug, info, warn, error, fatal}", Usage: "Transport logging level(previously called protocol logging level) {debug, info, warn, error, fatal}",
@ -30,19 +30,19 @@ func ConfigureLoggingFlags(shouldHide bool) []cli.Flag {
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: logger.LogFileFlag, Name: cfdflags.LogFile,
Usage: "Save application log to this file for reporting issues.", Usage: "Save application log to this file for reporting issues.",
EnvVars: []string{"TUNNEL_LOGFILE"}, EnvVars: []string{"TUNNEL_LOGFILE"},
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: logger.LogDirectoryFlag, Name: cfdflags.LogDirectory,
Usage: "Save application log to this directory for reporting issues.", Usage: "Save application log to this directory for reporting issues.",
EnvVars: []string{"TUNNEL_LOGDIRECTORY"}, EnvVars: []string{"TUNNEL_LOGDIRECTORY"},
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "trace-output", Name: cfdflags.TraceOutput,
Usage: "Name of trace output file, generated when cloudflared stops.", Usage: "Name of trace output file, generated when cloudflared stops.",
EnvVars: []string{"TUNNEL_TRACE_OUTPUT"}, EnvVars: []string{"TUNNEL_TRACE_OUTPUT"},
Hidden: shouldHide, Hidden: shouldHide,

View File

@ -0,0 +1,155 @@
package flags
const (
// HaConnections specifies how many connections to make to the edge
HaConnections = "ha-connections"
// SshPort is the port on localhost the cloudflared ssh server will run on
SshPort = "local-ssh-port"
// SshIdleTimeout defines the duration a SSH session can remain idle before being closed
SshIdleTimeout = "ssh-idle-timeout"
// SshMaxTimeout defines the max duration a SSH session can remain open for
SshMaxTimeout = "ssh-max-timeout"
// SshLogUploaderBucketName is the bucket name to use for the SSH log uploader
SshLogUploaderBucketName = "bucket-name"
// SshLogUploaderRegionName is the AWS region name to use for the SSH log uploader
SshLogUploaderRegionName = "region-name"
// SshLogUploaderSecretID is the Secret id of SSH log uploader
SshLogUploaderSecretID = "secret-id"
// SshLogUploaderAccessKeyID is the Access key id of SSH log uploader
SshLogUploaderAccessKeyID = "access-key-id"
// SshLogUploaderSessionTokenID is the Session token of SSH log uploader
SshLogUploaderSessionTokenID = "session-token"
// SshLogUploaderS3URL is the S3 URL of SSH log uploader (e.g. don't use AWS s3 and use google storage bucket instead)
SshLogUploaderS3URL = "s3-url-host"
// HostKeyPath is the path of the dir to save SSH host keys too
HostKeyPath = "host-key-path"
// RpcTimeout is how long to wait for a Capnp RPC request to the edge
RpcTimeout = "rpc-timeout"
// WriteStreamTimeout sets if we should have a timeout when writing data to a stream towards the destination (edge/origin).
WriteStreamTimeout = "write-stream-timeout"
// QuicDisablePathMTUDiscovery sets if QUIC should not perform PTMU discovery and use a smaller (safe) packet size.
// Packets will then be at most 1252 (IPv4) / 1232 (IPv6) bytes in size.
// Note that this may result in packet drops for UDP proxying, since we expect being able to send at least 1280 bytes of inner packets.
QuicDisablePathMTUDiscovery = "quic-disable-pmtu-discovery"
// QuicConnLevelFlowControlLimit controls the max flow control limit allocated for a QUIC connection. This controls how much data is the
// receiver willing to buffer. Once the limit is reached, the sender will send a DATA_BLOCKED frame to indicate it has more data to write,
// but it's blocked by flow control
QuicConnLevelFlowControlLimit = "quic-connection-level-flow-control-limit"
// QuicStreamLevelFlowControlLimit is similar to quicConnLevelFlowControlLimit but for each QUIC stream. When the sender is blocked,
// it will send a STREAM_DATA_BLOCKED frame
QuicStreamLevelFlowControlLimit = "quic-stream-level-flow-control-limit"
// Ui is to enable launching cloudflared in interactive UI mode
Ui = "ui"
// ConnectorLabel is the command line flag to give a meaningful label to a specific connector
ConnectorLabel = "label"
// MaxActiveFlows is the command line flag to set the maximum number of flows that cloudflared can be processing at the same time
MaxActiveFlows = "max-active-flows"
// Tag is the command line flag to set custom tags used to identify this tunnel via added HTTP request headers to the origin
Tag = "tag"
// Protocol is the command line flag to set the protocol to use to connect to the Cloudflare Edge
Protocol = "protocol"
// PostQuantum is the command line flag to force the connection to Cloudflare Edge to use Post Quantum cryptography
PostQuantum = "post-quantum"
// Features is the command line flag to opt into various features that are still being developed or tested
Features = "features"
// EdgeIpVersion is the command line flag to set the Cloudflare Edge IP address version to connect with
EdgeIpVersion = "edge-ip-version"
// EdgeBindAddress is the command line flag to bind to IP address for outgoing connections to Cloudflare Edge
EdgeBindAddress = "edge-bind-address"
// Force is the command line flag to specify if you wish to force an action
Force = "force"
// Edge is the command line flag to set the address of the Cloudflare tunnel server. Only works in Cloudflare's internal testing environment
Edge = "edge"
// Region is the command line flag to set the Cloudflare Edge region to connect to
Region = "region"
// IsAutoUpdated is the command line flag to signal the new process that cloudflared has been autoupdated
IsAutoUpdated = "is-autoupdated"
// LBPool is the command line flag to set the name of the load balancing pool to add this origin to
LBPool = "lb-pool"
// Retries is the command line flag to set the maximum number of retries for connection/protocol errors
Retries = "retries"
// MaxEdgeAddrRetries is the command line flag to set the maximum number of times to retry on edge addrs before falling back to a lower protocol
MaxEdgeAddrRetries = "max-edge-addr-retries"
// GracePeriod is the command line flag to set the maximum amount of time that cloudflared waits to shut down if it is still serving requests
GracePeriod = "grace-period"
// ICMPV4Src is the command line flag to set the source address and the interface name to send/receive ICMPv4 messages
ICMPV4Src = "icmpv4-src"
// ICMPV6Src is the command line flag to set the source address and the interface name to send/receive ICMPv6 messages
ICMPV6Src = "icmpv6-src"
// ProxyDns is the command line flag to run DNS server over HTTPS
ProxyDns = "proxy-dns"
// Name is the command line to set the name of the tunnel
Name = "name"
// AutoUpdateFreq is the command line for setting the frequency that cloudflared checks for updates
AutoUpdateFreq = "autoupdate-freq"
// NoAutoUpdate is the command line flag to disable cloudflared from checking for updates
NoAutoUpdate = "no-autoupdate"
// LogLevel is the command line flag for the cloudflared logging level
LogLevel = "loglevel"
// LogLevelSSH is the command line flag for the cloudflared ssh logging level
LogLevelSSH = "log-level"
// TransportLogLevel is the command line flag for the transport logging level
TransportLogLevel = "transport-loglevel"
// LogFile is the command line flag to define the file where application logs will be stored
LogFile = "logfile"
// LogDirectory is the command line flag to define the directory where application logs will be stored.
LogDirectory = "log-directory"
// TraceOutput is the command line flag to set the name of trace output file
TraceOutput = "trace-output"
// OriginCert is the command line flag to define the path for the origin certificate used by cloudflared
OriginCert = "origincert"
// Metrics is the command line flag to define the address of the metrics server
Metrics = "metrics"
// MetricsUpdateFreq is the command line flag to define how frequently tunnel metrics are updated
MetricsUpdateFreq = "metrics-update-freq"
// ApiURL is the command line flag used to define the base URL of the API
ApiURL = "api-url"
)

View File

@ -3,11 +3,38 @@
package main package main
import ( import (
"fmt"
"os" "os"
cli "github.com/urfave/cli/v2" cli "github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
) )
func runApp(app *cli.App, graceShutdownC chan struct{}) { func runApp(app *cli.App, graceShutdownC chan struct{}) {
app.Commands = append(app.Commands, &cli.Command{
Name: "service",
Usage: "Manages the cloudflared system service (not supported on this operating system)",
Subcommands: []*cli.Command{
{
Name: "install",
Usage: "Install cloudflared as a system service (not supported on this operating system)",
Action: cliutil.ConfiguredAction(installGenericService),
},
{
Name: "uninstall",
Usage: "Uninstall the cloudflared service (not supported on this operating system)",
Action: cliutil.ConfiguredAction(uninstallGenericService),
},
},
})
app.Run(os.Args) app.Run(os.Args)
} }
func installGenericService(c *cli.Context) error {
return fmt.Errorf("service installation is not supported on this operating system")
}
func uninstallGenericService(c *cli.Context) error {
return fmt.Errorf("service uninstallation is not supported on this operating system")
}

View File

@ -120,7 +120,7 @@ func installLaunchd(c *cli.Context) error {
log.Info().Msg("Installing cloudflared client as an user launch agent. " + log.Info().Msg("Installing cloudflared client as an user launch agent. " +
"Note that cloudflared client will only run when the user is logged in. " + "Note that cloudflared client will only run when the user is logged in. " +
"If you want to run cloudflared client at boot, install with root permission. " + "If you want to run cloudflared client at boot, install with root permission. " +
"For more information, visit https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/run-as-service") "For more information, visit https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/configure-tunnels/local-management/as-a-service/macos/")
} }
etPath, err := os.Executable() etPath, err := os.Executable()
if err != nil { if err != nil {

View File

@ -12,6 +12,7 @@ import (
"github.com/cloudflare/cloudflared/cmd/cloudflared/access" "github.com/cloudflare/cloudflared/cmd/cloudflared/access"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns" "github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns"
"github.com/cloudflare/cloudflared/cmd/cloudflared/tail" "github.com/cloudflare/cloudflared/cmd/cloudflared/tail"
"github.com/cloudflare/cloudflared/cmd/cloudflared/tunnel" "github.com/cloudflare/cloudflared/cmd/cloudflared/tunnel"
@ -105,7 +106,7 @@ func commands(version func(c *cli.Context)) []*cli.Command {
Usage: "specify if you wish to update to the latest beta version", Usage: "specify if you wish to update to the latest beta version",
}, },
&cli.BoolFlag{ &cli.BoolFlag{
Name: "force", Name: cfdflags.Force,
Usage: "specify if you wish to force an upgrade to the latest version regardless of the current version", Usage: "specify if you wish to force an upgrade to the latest version regardless of the current version",
Hidden: true, Hidden: true,
}, },

View File

@ -1,13 +1,13 @@
package main package main
import ( import (
"bufio"
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"os/exec" "os/exec"
"path" "path/filepath"
"text/template" "text/template"
homedir "github.com/mitchellh/go-homedir" homedir "github.com/mitchellh/go-homedir"
@ -44,7 +44,7 @@ func (st *ServiceTemplate) Generate(args *ServiceTemplateArgs) error {
return err return err
} }
if _, err = os.Stat(resolvedPath); err == nil { if _, err = os.Stat(resolvedPath); err == nil {
return fmt.Errorf(serviceAlreadyExistsWarn(resolvedPath)) return errors.New(serviceAlreadyExistsWarn(resolvedPath))
} }
var buffer bytes.Buffer var buffer bytes.Buffer
@ -57,7 +57,7 @@ func (st *ServiceTemplate) Generate(args *ServiceTemplateArgs) error {
fileMode = st.FileMode fileMode = st.FileMode
} }
plistFolder := path.Dir(resolvedPath) plistFolder := filepath.Dir(resolvedPath)
err = os.MkdirAll(plistFolder, 0o755) err = os.MkdirAll(plistFolder, 0o755)
if err != nil { if err != nil {
return fmt.Errorf("error creating %s: %v", plistFolder, err) return fmt.Errorf("error creating %s: %v", plistFolder, err)
@ -118,49 +118,6 @@ func ensureConfigDirExists(configDir string) error {
return err return err
} }
// openFile opens the file at path. If create is set and the file exists, returns nil, true, nil
func openFile(path string, create bool) (file *os.File, exists bool, err error) {
expandedPath, err := homedir.Expand(path)
if err != nil {
return nil, false, err
}
if create {
fileInfo, err := os.Stat(expandedPath)
if err == nil && fileInfo.Size() > 0 {
return nil, true, nil
}
file, err = os.OpenFile(expandedPath, os.O_RDWR|os.O_CREATE, 0600)
} else {
file, err = os.Open(expandedPath)
}
return file, false, err
}
func copyCredential(srcCredentialPath, destCredentialPath string) error {
destFile, exists, err := openFile(destCredentialPath, true)
if err != nil {
return err
} else if exists {
// credentials already exist, do nothing
return nil
}
defer destFile.Close()
srcFile, _, err := openFile(srcCredentialPath, false)
if err != nil {
return err
}
defer srcFile.Close()
// Copy certificate
_, err = io.Copy(destFile, srcFile)
if err != nil {
return fmt.Errorf("unable to copy %s to %s: %v", srcCredentialPath, destCredentialPath, err)
}
return nil
}
func copyFile(src, dest string) error { func copyFile(src, dest string) error {
srcFile, err := os.Open(src) srcFile, err := os.Open(src)
if err != nil { if err != nil {
@ -187,36 +144,3 @@ func copyFile(src, dest string) error {
ok = true ok = true
return nil return nil
} }
func copyConfig(srcConfigPath, destConfigPath string) error {
// Copy or create config
destFile, exists, err := openFile(destConfigPath, true)
if err != nil {
return fmt.Errorf("cannot open %s with error: %s", destConfigPath, err)
} else if exists {
// config already exists, do nothing
return nil
}
defer destFile.Close()
srcFile, _, err := openFile(srcConfigPath, false)
if err != nil {
fmt.Println("Your service needs a config file that at least specifies the hostname option.")
fmt.Println("Type in a hostname now, or leave it blank and create the config file later.")
fmt.Print("Hostname: ")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
if input == "" {
return err
}
fmt.Fprintf(destFile, "hostname: %s\n", input)
} else {
defer srcFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return fmt.Errorf("unable to copy %s to %s: %v", srcConfigPath, destConfigPath, err)
}
}
return nil
}

View File

@ -18,14 +18,12 @@ import (
"nhooyr.io/websocket" "nhooyr.io/websocket"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/credentials" "github.com/cloudflare/cloudflared/credentials"
"github.com/cloudflare/cloudflared/logger"
"github.com/cloudflare/cloudflared/management" "github.com/cloudflare/cloudflared/management"
) )
var ( var buildInfo *cliutil.BuildInfo
buildInfo *cliutil.BuildInfo
)
func Init(bi *cliutil.BuildInfo) { func Init(bi *cliutil.BuildInfo) {
buildInfo = bi buildInfo = bi
@ -56,7 +54,7 @@ func managementTokenCommand(c *cli.Context) error {
if err != nil { if err != nil {
return err return err
} }
var tokenResponse = struct { tokenResponse := struct {
Token string `json:"token"` Token string `json:"token"`
}{Token: token} }{Token: token}
@ -119,13 +117,13 @@ func buildTailCommand(subcommands []*cli.Command) *cli.Command {
Value: "", Value: "",
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: logger.LogLevelFlag, Name: cfdflags.LogLevel,
Value: "info", Value: "info",
Usage: "Application logging level {debug, info, warn, error, fatal}", Usage: "Application logging level {debug, info, warn, error, fatal}",
EnvVars: []string{"TUNNEL_LOGLEVEL"}, EnvVars: []string{"TUNNEL_LOGLEVEL"},
}, },
&cli.StringFlag{ &cli.StringFlag{
Name: credentials.OriginCertFlag, Name: cfdflags.OriginCert,
Usage: "Path to the certificate generated for your origin when you run cloudflared login.", Usage: "Path to the certificate generated for your origin when you run cloudflared login.",
EnvVars: []string{"TUNNEL_ORIGIN_CERT"}, EnvVars: []string{"TUNNEL_ORIGIN_CERT"},
Value: credentials.FindDefaultOriginCertPath(), Value: credentials.FindDefaultOriginCertPath(),
@ -169,7 +167,7 @@ func handleValidationError(resp *http.Response, log *zerolog.Logger) {
// logger will be created to emit only against the os.Stderr as to not obstruct with normal output from // logger will be created to emit only against the os.Stderr as to not obstruct with normal output from
// management requests // management requests
func createLogger(c *cli.Context) *zerolog.Logger { func createLogger(c *cli.Context) *zerolog.Logger {
level, levelErr := zerolog.ParseLevel(c.String(logger.LogLevelFlag)) level, levelErr := zerolog.ParseLevel(c.String(cfdflags.LogLevel))
if levelErr != nil { if levelErr != nil {
level = zerolog.InfoLevel level = zerolog.InfoLevel
} }
@ -183,9 +181,10 @@ func createLogger(c *cli.Context) *zerolog.Logger {
// parseFilters will attempt to parse provided filters to send to with the EventStartStreaming // parseFilters will attempt to parse provided filters to send to with the EventStartStreaming
func parseFilters(c *cli.Context) (*management.StreamingFilters, error) { func parseFilters(c *cli.Context) (*management.StreamingFilters, error) {
var level *management.LogLevel var level *management.LogLevel
var events []management.LogEventType
var sample float64 var sample float64
events := make([]management.LogEventType, 0)
argLevel := c.String("level") argLevel := c.String("level")
argEvents := c.StringSlice("event") argEvents := c.StringSlice("event")
argSample := c.Float64("sample") argSample := c.Float64("sample")
@ -225,12 +224,12 @@ func parseFilters(c *cli.Context) (*management.StreamingFilters, error) {
// getManagementToken will make a call to the Cloudflare API to acquire a management token for the requested tunnel. // getManagementToken will make a call to the Cloudflare API to acquire a management token for the requested tunnel.
func getManagementToken(c *cli.Context, log *zerolog.Logger) (string, error) { func getManagementToken(c *cli.Context, log *zerolog.Logger) (string, error) {
userCreds, err := credentials.Read(c.String(credentials.OriginCertFlag), log) userCreds, err := credentials.Read(c.String(cfdflags.OriginCert), log)
if err != nil { if err != nil {
return "", err return "", err
} }
client, err := userCreds.Client(c.String("api-url"), buildInfo.UserAgent(), log) client, err := userCreds.Client(c.String(cfdflags.ApiURL), buildInfo.UserAgent(), log)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -331,6 +330,7 @@ func Run(c *cli.Context) error {
header["cf-trace-id"] = []string{trace} header["cf-trace-id"] = []string{trace}
} }
ctx := c.Context ctx := c.Context
// nolint: bodyclose
conn, resp, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{ conn, resp, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{
HTTPHeader: header, HTTPHeader: header,
}) })

View File

@ -16,7 +16,7 @@ import (
"github.com/facebookgo/grace/gracenet" "github.com/facebookgo/grace/gracenet"
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/google/uuid" "github.com/google/uuid"
homedir "github.com/mitchellh/go-homedir" "github.com/mitchellh/go-homedir"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
@ -24,6 +24,7 @@ import (
"github.com/cloudflare/cloudflared/cfapi" "github.com/cloudflare/cloudflared/cfapi"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns" "github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns"
"github.com/cloudflare/cloudflared/cmd/cloudflared/updater" "github.com/cloudflare/cloudflared/cmd/cloudflared/updater"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
@ -47,61 +48,6 @@ import (
const ( const (
sentryDSN = "https://56a9c9fa5c364ab28f34b14f35ea0f1b:3e8827f6f9f740738eb11138f7bebb68@sentry.io/189878" sentryDSN = "https://56a9c9fa5c364ab28f34b14f35ea0f1b:3e8827f6f9f740738eb11138f7bebb68@sentry.io/189878"
// ha-Connections specifies how many connections to make to the edge
haConnectionsFlag = "ha-connections"
// sshPortFlag is the port on localhost the cloudflared ssh server will run on
sshPortFlag = "local-ssh-port"
// sshIdleTimeoutFlag defines the duration a SSH session can remain idle before being closed
sshIdleTimeoutFlag = "ssh-idle-timeout"
// sshMaxTimeoutFlag defines the max duration a SSH session can remain open for
sshMaxTimeoutFlag = "ssh-max-timeout"
// bucketNameFlag is the bucket name to use for the SSH log uploader
bucketNameFlag = "bucket-name"
// regionNameFlag is the AWS region name to use for the SSH log uploader
regionNameFlag = "region-name"
// secretIDFlag is the Secret id of SSH log uploader
secretIDFlag = "secret-id"
// accessKeyIDFlag is the Access key id of SSH log uploader
accessKeyIDFlag = "access-key-id"
// sessionTokenIDFlag is the Session token of SSH log uploader
sessionTokenIDFlag = "session-token"
// s3URLFlag is the S3 URL of SSH log uploader (e.g. don't use AWS s3 and use google storage bucket instead)
s3URLFlag = "s3-url-host"
// hostKeyPath is the path of the dir to save SSH host keys too
hostKeyPath = "host-key-path"
// rpcTimeout is how long to wait for a Capnp RPC request to the edge
rpcTimeout = "rpc-timeout"
// writeStreamTimeout sets if we should have a timeout when writing data to a stream towards the destination (edge/origin).
writeStreamTimeout = "write-stream-timeout"
// quicDisablePathMTUDiscovery sets if QUIC should not perform PTMU discovery and use a smaller (safe) packet size.
// Packets will then be at most 1252 (IPv4) / 1232 (IPv6) bytes in size.
// Note that this may result in packet drops for UDP proxying, since we expect being able to send at least 1280 bytes of inner packets.
quicDisablePathMTUDiscovery = "quic-disable-pmtu-discovery"
// quicConnLevelFlowControlLimit controls the max flow control limit allocated for a QUIC connection. This controls how much data is the
// receiver willing to buffer. Once the limit is reached, the sender will send a DATA_BLOCKED frame to indicate it has more data to write,
// but it's blocked by flow control
quicConnLevelFlowControlLimit = "quic-connection-level-flow-control-limit"
// quicStreamLevelFlowControlLimit is similar to quicConnLevelFlowControlLimit but for each QUIC stream. When the sender is blocked,
// it will send a STREAM_DATA_BLOCKED frame
quicStreamLevelFlowControlLimit = "quic-stream-level-flow-control-limit"
// uiFlag is to enable launching cloudflared in interactive UI mode
uiFlag = "ui"
LogFieldCommand = "command" LogFieldCommand = "command"
LogFieldExpandedPath = "expandedPath" LogFieldExpandedPath = "expandedPath"
LogFieldPIDPathname = "pidPathname" LogFieldPIDPathname = "pidPathname"
@ -116,7 +62,6 @@ Eg. cloudflared tunnel --url localhost:8080/.
Please note that Quick Tunnels are meant to be ephemeral and should only be used for testing purposes. Please note that Quick Tunnels are meant to be ephemeral and should only be used for testing purposes.
For production usage, we recommend creating Named Tunnels. (https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/) For production usage, we recommend creating Named Tunnels. (https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/tunnel-guide/)
` `
connectorLabelFlag = "label"
) )
var ( var (
@ -131,9 +76,9 @@ var (
// however this approach is not maintainble in the long-term. // however this approach is not maintainble in the long-term.
nonSecretFlagsList = []string{ nonSecretFlagsList = []string{
"config", "config",
"autoupdate-freq", cfdflags.AutoUpdateFreq,
"no-autoupdate", cfdflags.NoAutoUpdate,
"metrics", cfdflags.Metrics,
"pidfile", "pidfile",
"url", "url",
"hello-world", "hello-world",
@ -166,55 +111,55 @@ var (
"bastion", "bastion",
"proxy-address", "proxy-address",
"proxy-port", "proxy-port",
"loglevel", cfdflags.LogLevel,
"transport-loglevel", cfdflags.TransportLogLevel,
"logfile", cfdflags.LogFile,
"log-directory", cfdflags.LogDirectory,
"trace-output", cfdflags.TraceOutput,
"proxy-dns", cfdflags.ProxyDns,
"proxy-dns-port", "proxy-dns-port",
"proxy-dns-address", "proxy-dns-address",
"proxy-dns-upstream", "proxy-dns-upstream",
"proxy-dns-max-upstream-conns", "proxy-dns-max-upstream-conns",
"proxy-dns-bootstrap", "proxy-dns-bootstrap",
"is-autoupdated", cfdflags.IsAutoUpdated,
"edge", cfdflags.Edge,
"region", cfdflags.Region,
"edge-ip-version", cfdflags.EdgeIpVersion,
"edge-bind-address", cfdflags.EdgeBindAddress,
"cacert", "cacert",
"hostname", "hostname",
"id", "id",
"lb-pool", cfdflags.LBPool,
"api-url", cfdflags.ApiURL,
"metrics-update-freq", cfdflags.MetricsUpdateFreq,
"tag", cfdflags.Tag,
"heartbeat-interval", "heartbeat-interval",
"heartbeat-count", "heartbeat-count",
"max-edge-addr-retries", cfdflags.MaxEdgeAddrRetries,
"retries", cfdflags.Retries,
"ha-connections", "ha-connections",
"rpc-timeout", "rpc-timeout",
"write-stream-timeout", "write-stream-timeout",
"quic-disable-pmtu-discovery", "quic-disable-pmtu-discovery",
"quic-connection-level-flow-control-limit", "quic-connection-level-flow-control-limit",
"quic-stream-level-flow-control-limit", "quic-stream-level-flow-control-limit",
"label", cfdflags.ConnectorLabel,
"grace-period", cfdflags.GracePeriod,
"compression-quality", "compression-quality",
"use-reconnect-token", "use-reconnect-token",
"dial-edge-timeout", "dial-edge-timeout",
"stdin-control", "stdin-control",
"name", cfdflags.Name,
"ui", cfdflags.Ui,
"quick-service", "quick-service",
"max-fetch-size", "max-fetch-size",
"post-quantum", cfdflags.PostQuantum,
"management-diagnostics", "management-diagnostics",
"protocol", cfdflags.Protocol,
"overwrite-dns", "overwrite-dns",
"help", "help",
"max-active-flows", cfdflags.MaxActiveFlows,
} }
) )
@ -263,7 +208,7 @@ then protect with Cloudflare Access).
B) Locally reachable TCP/UDP-based private services to Cloudflare connected private users in the same account, e.g., B) Locally reachable TCP/UDP-based private services to Cloudflare connected private users in the same account, e.g.,
those enrolled to a Zero Trust WARP Client. those enrolled to a Zero Trust WARP Client.
You can manage your Tunnels via dash.teams.cloudflare.com. This approach will only require you to run a single command You can manage your Tunnels via one.dash.cloudflare.com. This approach will only require you to run a single command
later in each machine where you wish to run a Tunnel. later in each machine where you wish to run a Tunnel.
Alternatively, you can manage your Tunnels via the command line. Begin by obtaining a certificate to be able to do so: Alternatively, you can manage your Tunnels via the command line. Begin by obtaining a certificate to be able to do so:
@ -299,7 +244,7 @@ func TunnelCommand(c *cli.Context) error {
// --name required // --name required
// --url or --hello-world required // --url or --hello-world required
// --hostname optional // --hostname optional
if name := c.String("name"); name != "" { if name := c.String(cfdflags.Name); name != "" {
hostname, err := validation.ValidateHostname(c.String("hostname")) hostname, err := validation.ValidateHostname(c.String("hostname"))
if err != nil { if err != nil {
return errors.Wrap(err, "Invalid hostname provided") return errors.Wrap(err, "Invalid hostname provided")
@ -316,7 +261,7 @@ func TunnelCommand(c *cli.Context) error {
// A unauthenticated named tunnel hosted on <random>.<quick-tunnels-service>.com // A unauthenticated named tunnel hosted on <random>.<quick-tunnels-service>.com
// We don't support running proxy-dns and a quick tunnel at the same time as the same process // We don't support running proxy-dns and a quick tunnel at the same time as the same process
shouldRunQuickTunnel := c.IsSet("url") || c.IsSet(ingress.HelloWorldFlag) shouldRunQuickTunnel := c.IsSet("url") || c.IsSet(ingress.HelloWorldFlag)
if !c.IsSet("proxy-dns") && c.String("quick-service") != "" && shouldRunQuickTunnel { if !c.IsSet(cfdflags.ProxyDns) && c.String("quick-service") != "" && shouldRunQuickTunnel {
return RunQuickTunnel(sc) return RunQuickTunnel(sc)
} }
@ -330,7 +275,7 @@ func TunnelCommand(c *cli.Context) error {
return errDeprecatedClassicTunnel return errDeprecatedClassicTunnel
} }
if c.IsSet("proxy-dns") { if c.IsSet(cfdflags.ProxyDns) {
if shouldRunQuickTunnel { if shouldRunQuickTunnel {
return fmt.Errorf("running a quick tunnel with `proxy-dns` is not supported") return fmt.Errorf("running a quick tunnel with `proxy-dns` is not supported")
} }
@ -377,7 +322,7 @@ func runAdhocNamedTunnel(sc *subcommandContext, name, credentialsOutputPath stri
func routeFromFlag(c *cli.Context) (route cfapi.HostnameRoute, ok bool) { func routeFromFlag(c *cli.Context) (route cfapi.HostnameRoute, ok bool) {
if hostname := c.String("hostname"); hostname != "" { if hostname := c.String("hostname"); hostname != "" {
if lbPool := c.String("lb-pool"); lbPool != "" { if lbPool := c.String(cfdflags.LBPool); lbPool != "" {
return cfapi.NewLBRoute(hostname, lbPool), true return cfapi.NewLBRoute(hostname, lbPool), true
} }
return cfapi.NewDNSRoute(hostname, c.Bool(overwriteDNSFlagName)), true return cfapi.NewDNSRoute(hostname, c.Bool(overwriteDNSFlagName)), true
@ -407,7 +352,7 @@ func StartServer(
log.Info().Msg(config.ErrNoConfigFile.Error()) log.Info().Msg(config.ErrNoConfigFile.Error())
} }
if c.IsSet("trace-output") { if c.IsSet(cfdflags.TraceOutput) {
tmpTraceFile, err := os.CreateTemp("", "trace") tmpTraceFile, err := os.CreateTemp("", "trace")
if err != nil { if err != nil {
log.Err(err).Msg("Failed to create new temporary file to save trace output") log.Err(err).Msg("Failed to create new temporary file to save trace output")
@ -419,7 +364,7 @@ func StartServer(
if err := tmpTraceFile.Close(); err != nil { if err := tmpTraceFile.Close(); err != nil {
traceLog.Err(err).Msg("Failed to close temporary trace output file") traceLog.Err(err).Msg("Failed to close temporary trace output file")
} }
traceOutputFilepath := c.String("trace-output") traceOutputFilepath := c.String(cfdflags.TraceOutput)
if err := os.Rename(tmpTraceFile.Name(), traceOutputFilepath); err != nil { if err := os.Rename(tmpTraceFile.Name(), traceOutputFilepath); err != nil {
traceLog. traceLog.
Err(err). Err(err).
@ -449,7 +394,7 @@ func StartServer(
go waitForSignal(graceShutdownC, log) go waitForSignal(graceShutdownC, log)
if c.IsSet("proxy-dns") { if c.IsSet(cfdflags.ProxyDns) {
dnsReadySignal := make(chan struct{}) dnsReadySignal := make(chan struct{})
wg.Add(1) wg.Add(1)
go func() { go func() {
@ -471,7 +416,7 @@ func StartServer(
go func() { go func() {
defer wg.Done() defer wg.Done()
autoupdater := updater.NewAutoUpdater( autoupdater := updater.NewAutoUpdater(
c.Bool("no-autoupdate"), c.Duration("autoupdate-freq"), &listeners, log, c.Bool(cfdflags.NoAutoUpdate), c.Duration(cfdflags.AutoUpdateFreq), &listeners, log,
) )
errC <- autoupdater.Run(ctx) errC <- autoupdater.Run(ctx)
}() }()
@ -527,7 +472,7 @@ func StartServer(
c.Bool("management-diagnostics"), c.Bool("management-diagnostics"),
serviceIP, serviceIP,
clientID, clientID,
c.String(connectorLabelFlag), c.String(cfdflags.ConnectorLabel),
logger.ManagementLogger.Log, logger.ManagementLogger.Log,
logger.ManagementLogger, logger.ManagementLogger,
) )
@ -579,7 +524,7 @@ func StartServer(
errC <- metrics.ServeMetrics(metricsListener, ctx, metricsConfig, log) errC <- metrics.ServeMetrics(metricsListener, ctx, metricsConfig, log)
}() }()
reconnectCh := make(chan supervisor.ReconnectSignal, c.Int(haConnectionsFlag)) reconnectCh := make(chan supervisor.ReconnectSignal, c.Int(cfdflags.HaConnections))
if c.IsSet("stdin-control") { if c.IsSet("stdin-control") {
log.Info().Msg("Enabling control through stdin") log.Info().Msg("Enabling control through stdin")
go stdinControl(reconnectCh, log) go stdinControl(reconnectCh, log)
@ -699,31 +644,31 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
flags = append(flags, []cli.Flag{ flags = append(flags, []cli.Flag{
credentialsFileFlag, credentialsFileFlag,
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: "is-autoupdated", Name: cfdflags.IsAutoUpdated,
Usage: "Signal the new process that Cloudflare Tunnel connector has been autoupdated", Usage: "Signal the new process that Cloudflare Tunnel connector has been autoupdated",
Value: false, Value: false,
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringSliceFlag(&cli.StringSliceFlag{ altsrc.NewStringSliceFlag(&cli.StringSliceFlag{
Name: "edge", Name: cfdflags.Edge,
Usage: "Address of the Cloudflare tunnel server. Only works in Cloudflare's internal testing environment.", Usage: "Address of the Cloudflare tunnel server. Only works in Cloudflare's internal testing environment.",
EnvVars: []string{"TUNNEL_EDGE"}, EnvVars: []string{"TUNNEL_EDGE"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "region", Name: cfdflags.Region,
Usage: "Cloudflare Edge region to connect to. Omit or set to empty to connect to the global region.", Usage: "Cloudflare Edge region to connect to. Omit or set to empty to connect to the global region.",
EnvVars: []string{"TUNNEL_REGION"}, EnvVars: []string{"TUNNEL_REGION"},
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "edge-ip-version", Name: cfdflags.EdgeIpVersion,
Usage: "Cloudflare Edge IP address version to connect with. {4, 6, auto}", Usage: "Cloudflare Edge IP address version to connect with. {4, 6, auto}",
EnvVars: []string{"TUNNEL_EDGE_IP_VERSION"}, EnvVars: []string{"TUNNEL_EDGE_IP_VERSION"},
Value: "4", Value: "4",
Hidden: false, Hidden: false,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "edge-bind-address", Name: cfdflags.EdgeBindAddress,
Usage: "Bind to IP address for outgoing connections to Cloudflare Edge.", Usage: "Bind to IP address for outgoing connections to Cloudflare Edge.",
EnvVars: []string{"TUNNEL_EDGE_BIND_ADDRESS"}, EnvVars: []string{"TUNNEL_EDGE_BIND_ADDRESS"},
Hidden: false, Hidden: false,
@ -747,7 +692,7 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "lb-pool", Name: cfdflags.LBPool,
Usage: "The name of a (new/existing) load balancing pool to add this origin to.", Usage: "The name of a (new/existing) load balancing pool to add this origin to.",
EnvVars: []string{"TUNNEL_LB_POOL"}, EnvVars: []string{"TUNNEL_LB_POOL"},
Hidden: shouldHide, Hidden: shouldHide,
@ -771,21 +716,21 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "api-url", Name: cfdflags.ApiURL,
Usage: "Base URL for Cloudflare API v4", Usage: "Base URL for Cloudflare API v4",
EnvVars: []string{"TUNNEL_API_URL"}, EnvVars: []string{"TUNNEL_API_URL"},
Value: "https://api.cloudflare.com/client/v4", Value: "https://api.cloudflare.com/client/v4",
Hidden: true, Hidden: true,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: "metrics-update-freq", Name: cfdflags.MetricsUpdateFreq,
Usage: "Frequency to update tunnel metrics", Usage: "Frequency to update tunnel metrics",
Value: time.Second * 5, Value: time.Second * 5,
EnvVars: []string{"TUNNEL_METRICS_UPDATE_FREQ"}, EnvVars: []string{"TUNNEL_METRICS_UPDATE_FREQ"},
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringSliceFlag(&cli.StringSliceFlag{ altsrc.NewStringSliceFlag(&cli.StringSliceFlag{
Name: "tag", Name: cfdflags.Tag,
Usage: "Custom tags used to identify this tunnel via added HTTP request headers to the origin, in format `KEY=VALUE`. Multiple tags may be specified.", Usage: "Custom tags used to identify this tunnel via added HTTP request headers to the origin, in format `KEY=VALUE`. Multiple tags may be specified.",
EnvVars: []string{"TUNNEL_TAG"}, EnvVars: []string{"TUNNEL_TAG"},
Hidden: true, Hidden: true,
@ -804,64 +749,64 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
Hidden: true, Hidden: true,
}), }),
altsrc.NewIntFlag(&cli.IntFlag{ altsrc.NewIntFlag(&cli.IntFlag{
Name: "max-edge-addr-retries", Name: cfdflags.MaxEdgeAddrRetries,
Usage: "Maximum number of times to retry on edge addrs before falling back to a lower protocol", Usage: "Maximum number of times to retry on edge addrs before falling back to a lower protocol",
Value: 8, Value: 8,
Hidden: true, Hidden: true,
}), }),
// Note TUN-3758 , we use Int because UInt is not supported with altsrc // Note TUN-3758 , we use Int because UInt is not supported with altsrc
altsrc.NewIntFlag(&cli.IntFlag{ altsrc.NewIntFlag(&cli.IntFlag{
Name: "retries", Name: cfdflags.Retries,
Value: 5, Value: 5,
Usage: "Maximum number of retries for connection/protocol errors.", Usage: "Maximum number of retries for connection/protocol errors.",
EnvVars: []string{"TUNNEL_RETRIES"}, EnvVars: []string{"TUNNEL_RETRIES"},
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewIntFlag(&cli.IntFlag{ altsrc.NewIntFlag(&cli.IntFlag{
Name: haConnectionsFlag, Name: cfdflags.HaConnections,
Value: 4, Value: 4,
Hidden: true, Hidden: true,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: rpcTimeout, Name: cfdflags.RpcTimeout,
Value: 5 * time.Second, Value: 5 * time.Second,
Hidden: true, Hidden: true,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: writeStreamTimeout, Name: cfdflags.WriteStreamTimeout,
EnvVars: []string{"TUNNEL_STREAM_WRITE_TIMEOUT"}, EnvVars: []string{"TUNNEL_STREAM_WRITE_TIMEOUT"},
Usage: "Use this option to add a stream write timeout for connections when writing towards the origin or edge. Default is 0 which disables the write timeout.", Usage: "Use this option to add a stream write timeout for connections when writing towards the origin or edge. Default is 0 which disables the write timeout.",
Value: 0 * time.Second, Value: 0 * time.Second,
Hidden: true, Hidden: true,
}), }),
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: quicDisablePathMTUDiscovery, Name: cfdflags.QuicDisablePathMTUDiscovery,
EnvVars: []string{"TUNNEL_DISABLE_QUIC_PMTU"}, EnvVars: []string{"TUNNEL_DISABLE_QUIC_PMTU"},
Usage: "Use this option to disable PTMU discovery for QUIC connections. This will result in lower packet sizes. Not however, that this may cause instability for UDP proxying.", Usage: "Use this option to disable PTMU discovery for QUIC connections. This will result in lower packet sizes. Not however, that this may cause instability for UDP proxying.",
Value: false, Value: false,
Hidden: true, Hidden: true,
}), }),
altsrc.NewIntFlag(&cli.IntFlag{ altsrc.NewIntFlag(&cli.IntFlag{
Name: quicConnLevelFlowControlLimit, Name: cfdflags.QuicConnLevelFlowControlLimit,
EnvVars: []string{"TUNNEL_QUIC_CONN_LEVEL_FLOW_CONTROL_LIMIT"}, EnvVars: []string{"TUNNEL_QUIC_CONN_LEVEL_FLOW_CONTROL_LIMIT"},
Usage: "Use this option to change the connection-level flow control limit for QUIC transport.", Usage: "Use this option to change the connection-level flow control limit for QUIC transport.",
Value: 30 * (1 << 20), // 30 MB Value: 30 * (1 << 20), // 30 MB
Hidden: true, Hidden: true,
}), }),
altsrc.NewIntFlag(&cli.IntFlag{ altsrc.NewIntFlag(&cli.IntFlag{
Name: quicStreamLevelFlowControlLimit, Name: cfdflags.QuicStreamLevelFlowControlLimit,
EnvVars: []string{"TUNNEL_QUIC_STREAM_LEVEL_FLOW_CONTROL_LIMIT"}, EnvVars: []string{"TUNNEL_QUIC_STREAM_LEVEL_FLOW_CONTROL_LIMIT"},
Usage: "Use this option to change the connection-level flow control limit for QUIC transport.", Usage: "Use this option to change the connection-level flow control limit for QUIC transport.",
Value: 6 * (1 << 20), // 6 MB Value: 6 * (1 << 20), // 6 MB
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: connectorLabelFlag, Name: cfdflags.ConnectorLabel,
Usage: "Use this option to give a meaningful label to a specific connector. When a tunnel starts up, a connector id unique to the tunnel is generated. This is a uuid. To make it easier to identify a connector, we will use the hostname of the machine the tunnel is running on along with the connector ID. This option exists if one wants to have more control over what their individual connectors are called.", Usage: "Use this option to give a meaningful label to a specific connector. When a tunnel starts up, a connector id unique to the tunnel is generated. This is a uuid. To make it easier to identify a connector, we will use the hostname of the machine the tunnel is running on along with the connector ID. This option exists if one wants to have more control over what their individual connectors are called.",
Value: "", Value: "",
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: "grace-period", Name: cfdflags.GracePeriod,
Usage: "When cloudflared receives SIGINT/SIGTERM it will stop accepting new requests, wait for in-progress requests to terminate, then shutdown. Waiting for in-progress requests will timeout after this grace period, or when a second SIGTERM/SIGINT is received.", Usage: "When cloudflared receives SIGINT/SIGTERM it will stop accepting new requests, wait for in-progress requests to terminate, then shutdown. Waiting for in-progress requests will timeout after this grace period, or when a second SIGTERM/SIGINT is received.",
Value: time.Second * 30, Value: time.Second * 30,
EnvVars: []string{"TUNNEL_GRACE_PERIOD"}, EnvVars: []string{"TUNNEL_GRACE_PERIOD"},
@ -897,14 +842,14 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
Value: false, Value: false,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "name", Name: cfdflags.Name,
Aliases: []string{"n"}, Aliases: []string{"n"},
EnvVars: []string{"TUNNEL_NAME"}, EnvVars: []string{"TUNNEL_NAME"},
Usage: "Stable name to identify the tunnel. Using this flag will create, route and run a tunnel. For production usage, execute each command separately", Usage: "Stable name to identify the tunnel. Using this flag will create, route and run a tunnel. For production usage, execute each command separately",
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: uiFlag, Name: cfdflags.Ui,
Usage: "(depreciated) Launch tunnel UI. Tunnel logs are scrollable via 'j', 'k', or arrow keys.", Usage: "(depreciated) Launch tunnel UI. Tunnel logs are scrollable via 'j', 'k', or arrow keys.",
Value: false, Value: false,
Hidden: true, Hidden: true,
@ -922,7 +867,7 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
Hidden: true, Hidden: true,
}), }),
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: "post-quantum", Name: cfdflags.PostQuantum,
Usage: "When given creates an experimental post-quantum secure tunnel", Usage: "When given creates an experimental post-quantum secure tunnel",
Aliases: []string{"pq"}, Aliases: []string{"pq"},
EnvVars: []string{"TUNNEL_POST_QUANTUM"}, EnvVars: []string{"TUNNEL_POST_QUANTUM"},
@ -950,27 +895,27 @@ func configureCloudflaredFlags(shouldHide bool) []cli.Flag {
Hidden: shouldHide, Hidden: shouldHide,
}, },
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: credentials.OriginCertFlag, Name: cfdflags.OriginCert,
Usage: "Path to the certificate generated for your origin when you run cloudflared login.", Usage: "Path to the certificate generated for your origin when you run cloudflared login.",
EnvVars: []string{"TUNNEL_ORIGIN_CERT"}, EnvVars: []string{"TUNNEL_ORIGIN_CERT"},
Value: credentials.FindDefaultOriginCertPath(), Value: credentials.FindDefaultOriginCertPath(),
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: "autoupdate-freq", Name: cfdflags.AutoUpdateFreq,
Usage: fmt.Sprintf("Autoupdate frequency. Default is %v.", updater.DefaultCheckUpdateFreq), Usage: fmt.Sprintf("Autoupdate frequency. Default is %v.", updater.DefaultCheckUpdateFreq),
Value: updater.DefaultCheckUpdateFreq, Value: updater.DefaultCheckUpdateFreq,
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: "no-autoupdate", Name: cfdflags.NoAutoUpdate,
Usage: "Disable periodic check for updates, restarting the server with the new version.", Usage: "Disable periodic check for updates, restarting the server with the new version.",
EnvVars: []string{"NO_AUTOUPDATE"}, EnvVars: []string{"NO_AUTOUPDATE"},
Value: false, Value: false,
Hidden: shouldHide, Hidden: shouldHide,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: "metrics", Name: cfdflags.Metrics,
Value: metrics.GetMetricsDefaultAddress(metrics.Runtime), Value: metrics.GetMetricsDefaultAddress(metrics.Runtime),
Usage: fmt.Sprintf( Usage: fmt.Sprintf(
`Listen address for metrics reporting. If no address is passed cloudflared will try to bind to %v. `Listen address for metrics reporting. If no address is passed cloudflared will try to bind to %v.
@ -1134,62 +1079,62 @@ func legacyTunnelFlag(msg string) string {
func sshFlags(shouldHide bool) []cli.Flag { func sshFlags(shouldHide bool) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: sshPortFlag, Name: cfdflags.SshPort,
Usage: "Localhost port that cloudflared SSH server will run on", Usage: "Localhost port that cloudflared SSH server will run on",
Value: "2222", Value: "2222",
EnvVars: []string{"LOCAL_SSH_PORT"}, EnvVars: []string{"LOCAL_SSH_PORT"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: sshIdleTimeoutFlag, Name: cfdflags.SshIdleTimeout,
Usage: "Connection timeout after no activity", Usage: "Connection timeout after no activity",
EnvVars: []string{"SSH_IDLE_TIMEOUT"}, EnvVars: []string{"SSH_IDLE_TIMEOUT"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewDurationFlag(&cli.DurationFlag{ altsrc.NewDurationFlag(&cli.DurationFlag{
Name: sshMaxTimeoutFlag, Name: cfdflags.SshMaxTimeout,
Usage: "Absolute connection timeout", Usage: "Absolute connection timeout",
EnvVars: []string{"SSH_MAX_TIMEOUT"}, EnvVars: []string{"SSH_MAX_TIMEOUT"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: bucketNameFlag, Name: cfdflags.SshLogUploaderBucketName,
Usage: "Bucket name of where to upload SSH logs", Usage: "Bucket name of where to upload SSH logs",
EnvVars: []string{"BUCKET_ID"}, EnvVars: []string{"BUCKET_ID"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: regionNameFlag, Name: cfdflags.SshLogUploaderRegionName,
Usage: "Region name of where to upload SSH logs", Usage: "Region name of where to upload SSH logs",
EnvVars: []string{"REGION_ID"}, EnvVars: []string{"REGION_ID"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: secretIDFlag, Name: cfdflags.SshLogUploaderSecretID,
Usage: "Secret ID of where to upload SSH logs", Usage: "Secret ID of where to upload SSH logs",
EnvVars: []string{"SECRET_ID"}, EnvVars: []string{"SECRET_ID"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: accessKeyIDFlag, Name: cfdflags.SshLogUploaderAccessKeyID,
Usage: "Access Key ID of where to upload SSH logs", Usage: "Access Key ID of where to upload SSH logs",
EnvVars: []string{"ACCESS_CLIENT_ID"}, EnvVars: []string{"ACCESS_CLIENT_ID"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: sessionTokenIDFlag, Name: cfdflags.SshLogUploaderSessionTokenID,
Usage: "Session Token to use in the configuration of SSH logs uploading", Usage: "Session Token to use in the configuration of SSH logs uploading",
EnvVars: []string{"SESSION_TOKEN_ID"}, EnvVars: []string{"SESSION_TOKEN_ID"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewStringFlag(&cli.StringFlag{ altsrc.NewStringFlag(&cli.StringFlag{
Name: s3URLFlag, Name: cfdflags.SshLogUploaderS3URL,
Usage: "S3 url of where to upload SSH logs", Usage: "S3 url of where to upload SSH logs",
EnvVars: []string{"S3_URL"}, EnvVars: []string{"S3_URL"},
Hidden: true, Hidden: true,
}), }),
altsrc.NewPathFlag(&cli.PathFlag{ altsrc.NewPathFlag(&cli.PathFlag{
Name: hostKeyPath, Name: cfdflags.HostKeyPath,
Usage: "Absolute path of directory to save SSH host keys in", Usage: "Absolute path of directory to save SSH host keys in",
EnvVars: []string{"HOST_KEY_PATH"}, EnvVars: []string{"HOST_KEY_PATH"},
Hidden: true, Hidden: true,
@ -1229,7 +1174,7 @@ func sshFlags(shouldHide bool) []cli.Flag {
func configureProxyDNSFlags(shouldHide bool) []cli.Flag { func configureProxyDNSFlags(shouldHide bool) []cli.Flag {
return []cli.Flag{ return []cli.Flag{
altsrc.NewBoolFlag(&cli.BoolFlag{ altsrc.NewBoolFlag(&cli.BoolFlag{
Name: "proxy-dns", Name: cfdflags.ProxyDns,
Usage: "Run a DNS over HTTPS proxy server.", Usage: "Run a DNS over HTTPS proxy server.",
EnvVars: []string{"TUNNEL_DNS"}, EnvVars: []string{"TUNNEL_DNS"},
Hidden: shouldHide, Hidden: shouldHide,
@ -1327,7 +1272,7 @@ func nonSecretCliFlags(log *zerolog.Logger, cli *cli.Context, flagInclusionList
} }
switch flag { switch flag {
case logger.LogDirectoryFlag, logger.LogFileFlag: case cfdflags.LogDirectory, cfdflags.LogFile:
{ {
absolute, err := filepath.Abs(value) absolute, err := filepath.Abs(value)
if err != nil { if err != nil {

View File

@ -18,6 +18,7 @@ import (
"golang.org/x/term" "golang.org/x/term"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
"github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
"github.com/cloudflare/cloudflared/edgediscovery" "github.com/cloudflare/cloudflared/edgediscovery"
@ -33,12 +34,26 @@ import (
const ( const (
secretValue = "*****" secretValue = "*****"
icmpFunnelTimeout = time.Second * 10 icmpFunnelTimeout = time.Second * 10
fedRampRegion = "fed" // const string denoting the region used to connect to FEDRamp servers
) )
var ( var (
secretFlags = [2]*altsrc.StringFlag{credentialsContentsFlag, tunnelTokenFlag} secretFlags = [2]*altsrc.StringFlag{credentialsContentsFlag, tunnelTokenFlag}
configFlags = []string{"autoupdate-freq", "no-autoupdate", "retries", "protocol", "loglevel", "transport-loglevel", "origincert", "metrics", "metrics-update-freq", "edge-ip-version", "edge-bind-address", "max-active-flows"} configFlags = []string{
flags.AutoUpdateFreq,
flags.NoAutoUpdate,
flags.Retries,
flags.Protocol,
flags.LogLevel,
flags.TransportLogLevel,
flags.OriginCert,
flags.Metrics,
flags.MetricsUpdateFreq,
flags.EdgeIpVersion,
flags.EdgeBindAddress,
flags.MaxActiveFlows,
}
) )
func logClientOptions(c *cli.Context, log *zerolog.Logger) { func logClientOptions(c *cli.Context, log *zerolog.Logger) {
@ -96,8 +111,8 @@ func isSecretEnvVar(key string) bool {
} }
func dnsProxyStandAlone(c *cli.Context, namedTunnel *connection.TunnelProperties) bool { func dnsProxyStandAlone(c *cli.Context, namedTunnel *connection.TunnelProperties) bool {
return c.IsSet("proxy-dns") && return c.IsSet(flags.ProxyDns) &&
!(c.IsSet("name") || // adhoc-named tunnel !(c.IsSet(flags.Name) || // adhoc-named tunnel
c.IsSet(ingress.HelloWorldFlag) || // quick or named tunnel c.IsSet(ingress.HelloWorldFlag) || // quick or named tunnel
namedTunnel != nil) // named tunnel namedTunnel != nil) // named tunnel
} }
@ -115,14 +130,15 @@ func prepareTunnelConfig(
return nil, nil, errors.Wrap(err, "can't generate connector UUID") return nil, nil, errors.Wrap(err, "can't generate connector UUID")
} }
log.Info().Msgf("Generated Connector ID: %s", clientID) log.Info().Msgf("Generated Connector ID: %s", clientID)
tags, err := NewTagSliceFromCLI(c.StringSlice("tag")) tags, err := NewTagSliceFromCLI(c.StringSlice(flags.Tag))
if err != nil { if err != nil {
log.Err(err).Msg("Tag parse failure") log.Err(err).Msg("Tag parse failure")
return nil, nil, errors.Wrap(err, "Tag parse failure") return nil, nil, errors.Wrap(err, "Tag parse failure")
} }
tags = append(tags, pogs.Tag{Name: "ID", Value: clientID.String()}) tags = append(tags, pogs.Tag{Name: "ID", Value: clientID.String()})
transportProtocol := c.String("protocol") transportProtocol := c.String(flags.Protocol)
isPostQuantumEnforced := c.Bool(flags.PostQuantum)
featureSelector, err := features.NewFeatureSelector(ctx, namedTunnel.Credentials.AccountTag, c.StringSlice("features"), c.Bool("post-quantum"), log) featureSelector, err := features.NewFeatureSelector(ctx, namedTunnel.Credentials.AccountTag, c.StringSlice("features"), c.Bool("post-quantum"), log)
if err != nil { if err != nil {
@ -150,7 +166,7 @@ func prepareTunnelConfig(
return nil, nil, err return nil, nil, err
} }
protocolSelector, err := connection.NewProtocolSelector(transportProtocol, namedTunnel.Credentials.AccountTag, c.IsSet(TunnelTokenFlag), c.Bool("post-quantum"), edgediscovery.ProtocolPercentage, connection.ResolveTTL, log) protocolSelector, err := connection.NewProtocolSelector(transportProtocol, namedTunnel.Credentials.AccountTag, c.IsSet(TunnelTokenFlag), isPostQuantumEnforced, edgediscovery.ProtocolPercentage, connection.ResolveTTL, log)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -176,11 +192,11 @@ func prepareTunnelConfig(
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
edgeIPVersion, err := parseConfigIPVersion(c.String("edge-ip-version")) edgeIPVersion, err := parseConfigIPVersion(c.String(flags.EdgeIpVersion))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
edgeBindAddr, err := parseConfigBindAddress(c.String("edge-bind-address")) edgeBindAddr, err := parseConfigBindAddress(c.String(flags.EdgeBindAddress))
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -193,36 +209,50 @@ func prepareTunnelConfig(
log.Warn().Str("edgeIPVersion", edgeIPVersion.String()).Err(err).Msg("Overriding edge-ip-version") log.Warn().Str("edgeIPVersion", edgeIPVersion.String()).Err(err).Msg("Overriding edge-ip-version")
} }
region := c.String(flags.Region)
endpoint := namedTunnel.Credentials.Endpoint
var resolvedRegion string
// set resolvedRegion to either the region passed as argument
// or to the endpoint in the credentials.
// Region and endpoint are interchangeable
if region != "" && endpoint != "" {
return nil, nil, fmt.Errorf("region provided with a token that has an endpoint")
} else if region != "" {
resolvedRegion = region
} else if endpoint != "" {
resolvedRegion = endpoint
}
tunnelConfig := &supervisor.TunnelConfig{ tunnelConfig := &supervisor.TunnelConfig{
GracePeriod: gracePeriod, GracePeriod: gracePeriod,
ReplaceExisting: c.Bool("force"), ReplaceExisting: c.Bool(flags.Force),
OSArch: info.OSArch(), OSArch: info.OSArch(),
ClientID: clientID.String(), ClientID: clientID.String(),
EdgeAddrs: c.StringSlice("edge"), EdgeAddrs: c.StringSlice(flags.Edge),
Region: c.String("region"), Region: resolvedRegion,
EdgeIPVersion: edgeIPVersion, EdgeIPVersion: edgeIPVersion,
EdgeBindAddr: edgeBindAddr, EdgeBindAddr: edgeBindAddr,
HAConnections: c.Int(haConnectionsFlag), HAConnections: c.Int(flags.HaConnections),
IsAutoupdated: c.Bool("is-autoupdated"), IsAutoupdated: c.Bool(flags.IsAutoUpdated),
LBPool: c.String("lb-pool"), LBPool: c.String(flags.LBPool),
Tags: tags, Tags: tags,
Log: log, Log: log,
LogTransport: logTransport, LogTransport: logTransport,
Observer: observer, Observer: observer,
ReportedVersion: info.Version(), ReportedVersion: info.Version(),
// Note TUN-3758 , we use Int because UInt is not supported with altsrc // Note TUN-3758 , we use Int because UInt is not supported with altsrc
Retries: uint(c.Int("retries")), // nolint: gosec Retries: uint(c.Int(flags.Retries)), // nolint: gosec
RunFromTerminal: isRunningFromTerminal(), RunFromTerminal: isRunningFromTerminal(),
NamedTunnel: namedTunnel, NamedTunnel: namedTunnel,
ProtocolSelector: protocolSelector, ProtocolSelector: protocolSelector,
EdgeTLSConfigs: edgeTLSConfigs, EdgeTLSConfigs: edgeTLSConfigs,
FeatureSelector: featureSelector, FeatureSelector: featureSelector,
MaxEdgeAddrRetries: uint8(c.Int("max-edge-addr-retries")), // nolint: gosec MaxEdgeAddrRetries: uint8(c.Int(flags.MaxEdgeAddrRetries)), // nolint: gosec
RPCTimeout: c.Duration(rpcTimeout), RPCTimeout: c.Duration(flags.RpcTimeout),
WriteStreamTimeout: c.Duration(writeStreamTimeout), WriteStreamTimeout: c.Duration(flags.WriteStreamTimeout),
DisableQUICPathMTUDiscovery: c.Bool(quicDisablePathMTUDiscovery), DisableQUICPathMTUDiscovery: c.Bool(flags.QuicDisablePathMTUDiscovery),
QUICConnectionLevelFlowControlLimit: c.Uint64(quicConnLevelFlowControlLimit), QUICConnectionLevelFlowControlLimit: c.Uint64(flags.QuicConnLevelFlowControlLimit),
QUICStreamLevelFlowControlLimit: c.Uint64(quicStreamLevelFlowControlLimit), QUICStreamLevelFlowControlLimit: c.Uint64(flags.QuicStreamLevelFlowControlLimit),
} }
icmpRouter, err := newICMPRouter(c, log) icmpRouter, err := newICMPRouter(c, log)
if err != nil { if err != nil {
@ -234,7 +264,7 @@ func prepareTunnelConfig(
Ingress: &ingressRules, Ingress: &ingressRules,
WarpRouting: ingress.NewWarpRoutingConfig(&cfg.WarpRouting), WarpRouting: ingress.NewWarpRoutingConfig(&cfg.WarpRouting),
ConfigurationFlags: parseConfigFlags(c), ConfigurationFlags: parseConfigFlags(c),
WriteTimeout: c.Duration(writeStreamTimeout), WriteTimeout: tunnelConfig.WriteStreamTimeout,
} }
return tunnelConfig, orchestratorConfig, nil return tunnelConfig, orchestratorConfig, nil
} }
@ -252,9 +282,9 @@ func parseConfigFlags(c *cli.Context) map[string]string {
} }
func gracePeriod(c *cli.Context) (time.Duration, error) { func gracePeriod(c *cli.Context) (time.Duration, error) {
period := c.Duration("grace-period") period := c.Duration(flags.GracePeriod)
if period > connection.MaxGracePeriod { if period > connection.MaxGracePeriod {
return time.Duration(0), fmt.Errorf("grace-period must be equal or less than %v", connection.MaxGracePeriod) return time.Duration(0), fmt.Errorf("%s must be equal or less than %v", flags.GracePeriod, connection.MaxGracePeriod)
} }
return period, nil return period, nil
} }
@ -337,14 +367,14 @@ func newICMPRouter(c *cli.Context, logger *zerolog.Logger) (ingress.ICMPRouterSe
} }
func determineICMPSources(c *cli.Context, logger *zerolog.Logger) (netip.Addr, netip.Addr, error) { func determineICMPSources(c *cli.Context, logger *zerolog.Logger) (netip.Addr, netip.Addr, error) {
ipv4Src, err := determineICMPv4Src(c.String("icmpv4-src"), logger) ipv4Src, err := determineICMPv4Src(c.String(flags.ICMPV4Src), logger)
if err != nil { if err != nil {
return netip.Addr{}, netip.Addr{}, errors.Wrap(err, "failed to determine IPv4 source address for ICMP proxy") return netip.Addr{}, netip.Addr{}, errors.Wrap(err, "failed to determine IPv4 source address for ICMP proxy")
} }
logger.Info().Msgf("ICMP proxy will use %s as source for IPv4", ipv4Src) logger.Info().Msgf("ICMP proxy will use %s as source for IPv4", ipv4Src)
ipv6Src, zone, err := determineICMPv6Src(c.String("icmpv6-src"), logger, ipv4Src) ipv6Src, zone, err := determineICMPv6Src(c.String(flags.ICMPV6Src), logger, ipv4Src)
if err != nil { if err != nil {
return netip.Addr{}, netip.Addr{}, errors.Wrap(err, "failed to determine IPv6 source address for ICMP proxy") return netip.Addr{}, netip.Addr{}, errors.Wrap(err, "failed to determine IPv6 source address for ICMP proxy")
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/credentials" "github.com/cloudflare/cloudflared/credentials"
@ -57,7 +58,7 @@ func newSearchByID(id uuid.UUID, c *cli.Context, log *zerolog.Logger, fs fileSys
} }
func (s searchByID) Path() (string, error) { func (s searchByID) Path() (string, error) {
originCertPath := s.c.String(credentials.OriginCertFlag) originCertPath := s.c.String(cfdflags.OriginCert)
originCertLog := s.log.With(). originCertLog := s.log.With().
Str("originCertPath", originCertPath). Str("originCertPath", originCertPath).
Logger() Logger()

View File

@ -67,7 +67,7 @@ func login(c *cli.Context) error {
path, ok, err := checkForExistingCert() path, ok, err := checkForExistingCert()
if ok { if ok {
fmt.Fprintf(os.Stdout, "You have an existing certificate at %s which login would overwrite.\nIf this is intentional, please move or delete that file then run this command again.\n", path) log.Error().Err(err).Msgf("You have an existing certificate at %s which login would overwrite.\nIf this is intentional, please move or delete that file then run this command again.\n", path)
return nil return nil
} else if err != nil { } else if err != nil {
return err return err
@ -78,7 +78,8 @@ func login(c *cli.Context) error {
callbackStoreURL = c.String(callbackURLParamName) callbackStoreURL = c.String(callbackURLParamName)
) )
if c.Bool(fedRAMPParamName) { isFEDRamp := c.Bool(fedRAMPParamName)
if isFEDRamp {
baseloginURL = fedBaseLoginURL baseloginURL = fedBaseLoginURL
callbackStoreURL = fedCallbackStoreURL callbackStoreURL = fedCallbackStoreURL
} }
@ -99,7 +100,23 @@ func login(c *cli.Context) error {
log, log,
) )
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Failed to write the certificate due to the following error:\n%v\n\nYour browser will download the certificate instead. You will have to manually\ncopy it to the following path:\n\n%s\n", err, path) log.Error().Err(err).Msgf("Failed to write the certificate.\n\nYour browser will download the certificate instead. You will have to manually\ncopy it to the following path:\n\n%s\n", path)
return err
}
cert, err := credentials.DecodeOriginCert(resourceData)
if err != nil {
log.Error().Err(err).Msg("failed to decode origin certificate")
return err
}
if isFEDRamp {
cert.Endpoint = credentials.FedEndpoint
}
resourceData, err = cert.EncodeOriginCert()
if err != nil {
log.Error().Err(err).Msg("failed to encode origin certificate")
return err return err
} }
@ -107,7 +124,7 @@ func login(c *cli.Context) error {
return errors.Wrap(err, fmt.Sprintf("error writing cert to %s", path)) return errors.Wrap(err, fmt.Sprintf("error writing cert to %s", path))
} }
fmt.Fprintf(os.Stdout, "You have successfully logged in.\nIf you wish to copy your credentials to a server, they have been saved to:\n%s\n", path) log.Info().Msgf("You have successfully logged in.\nIf you wish to copy your credentials to a server, they have been saved to:\n%s\n", path)
return nil return nil
} }

View File

@ -11,6 +11,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
) )
@ -82,13 +83,13 @@ func RunQuickTunnel(sc *subcommandContext) error {
sc.log.Info().Msg(line) sc.log.Info().Msg(line)
} }
if !sc.c.IsSet("protocol") { if !sc.c.IsSet(flags.Protocol) {
sc.c.Set("protocol", "quic") _ = sc.c.Set(flags.Protocol, "quic")
} }
// Override the number of connections used. Quick tunnels shouldn't be used for production usage, // Override the number of connections used. Quick tunnels shouldn't be used for production usage,
// so, use a single connection instead. // so, use a single connection instead.
sc.c.Set(haConnectionsFlag, "1") _ = sc.c.Set(flags.HaConnections, "1")
return StartServer( return StartServer(
sc.c, sc.c,
buildInfo, buildInfo,

View File

@ -9,22 +9,26 @@ import (
"strings" "strings"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cfapi" "github.com/cloudflare/cloudflared/cfapi"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
"github.com/cloudflare/cloudflared/credentials" "github.com/cloudflare/cloudflared/credentials"
"github.com/cloudflare/cloudflared/logger" "github.com/cloudflare/cloudflared/logger"
) )
type errInvalidJSONCredential struct { const fedRampBaseApiURL = "https://api.fed.cloudflare.com/client/v4"
type invalidJSONCredentialError struct {
err error err error
path string path string
} }
func (e errInvalidJSONCredential) Error() string { func (e invalidJSONCredentialError) Error() string {
return "Invalid JSON when parsing tunnel credentials file" return "Invalid JSON when parsing tunnel credentials file"
} }
@ -51,8 +55,13 @@ func newSubcommandContext(c *cli.Context) (*subcommandContext, error) {
// Returns something that can find the given tunnel's credentials file. // Returns something that can find the given tunnel's credentials file.
func (sc *subcommandContext) credentialFinder(tunnelID uuid.UUID) CredFinder { func (sc *subcommandContext) credentialFinder(tunnelID uuid.UUID) CredFinder {
if path := sc.c.String(CredFileFlag); path != "" { if path := sc.c.String(CredFileFlag); path != "" {
// Expand path if CredFileFlag contains `~`
absPath, err := homedir.Expand(path)
if err != nil {
return newStaticPath(path, sc.fs) return newStaticPath(path, sc.fs)
} }
return newStaticPath(absPath, sc.fs)
}
return newSearchByID(tunnelID, sc.c, sc.log, sc.fs) return newSearchByID(tunnelID, sc.c, sc.log, sc.fs)
} }
@ -64,7 +73,16 @@ func (sc *subcommandContext) client() (cfapi.Client, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
sc.tunnelstoreClient, err = cred.Client(sc.c.String("api-url"), buildInfo.UserAgent(), sc.log)
var apiURL string
if cred.IsFEDEndpoint() {
sc.log.Info().Str("api-url", fedRampBaseApiURL).Msg("using fedramp base api")
apiURL = fedRampBaseApiURL
} else {
apiURL = sc.c.String(cfdflags.ApiURL)
}
sc.tunnelstoreClient, err = cred.Client(apiURL, buildInfo.UserAgent(), sc.log)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -73,7 +91,7 @@ func (sc *subcommandContext) client() (cfapi.Client, error) {
func (sc *subcommandContext) credential() (*credentials.User, error) { func (sc *subcommandContext) credential() (*credentials.User, error) {
if sc.userCredential == nil { if sc.userCredential == nil {
uc, err := credentials.Read(sc.c.String(credentials.OriginCertFlag), sc.log) uc, err := credentials.Read(sc.c.String(cfdflags.OriginCert), sc.log)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -94,13 +112,13 @@ func (sc *subcommandContext) readTunnelCredentials(credFinder CredFinder) (conne
var credentials connection.Credentials var credentials connection.Credentials
if err = json.Unmarshal(body, &credentials); err != nil { if err = json.Unmarshal(body, &credentials); err != nil {
if strings.HasSuffix(filePath, ".pem") { if filepath.Ext(filePath) == ".pem" {
return connection.Credentials{}, fmt.Errorf("The tunnel credentials file should be .json but you gave a .pem. " + return connection.Credentials{}, fmt.Errorf("The tunnel credentials file should be .json but you gave a .pem. " +
"The tunnel credentials file was originally created by `cloudflared tunnel create`. " + "The tunnel credentials file was originally created by `cloudflared tunnel create`. " +
"You may have accidentally used the filepath to cert.pem, which is generated by `cloudflared tunnel " + "You may have accidentally used the filepath to cert.pem, which is generated by `cloudflared tunnel " +
"login`.") "login`.")
} }
return connection.Credentials{}, errInvalidJSONCredential{path: filePath, err: err} return connection.Credentials{}, invalidJSONCredentialError{path: filePath, err: err}
} }
return credentials, nil return credentials, nil
} }
@ -122,7 +140,7 @@ func (sc *subcommandContext) create(name string, credentialsFilePath string, sec
if err != nil { if err != nil {
return nil, errors.Wrap(err, "Couldn't decode tunnel secret from base64") return nil, errors.Wrap(err, "Couldn't decode tunnel secret from base64")
} }
tunnelSecret = []byte(decodedSecret) tunnelSecret = decodedSecret
if len(tunnelSecret) < 32 { if len(tunnelSecret) < 32 {
return nil, errors.New("Decoded tunnel secret must be at least 32 bytes long") return nil, errors.New("Decoded tunnel secret must be at least 32 bytes long")
} }
@ -160,7 +178,7 @@ func (sc *subcommandContext) create(name string, credentialsFilePath string, sec
errorLines = append(errorLines, fmt.Sprintf("Cloudflared tried to delete the tunnel for you, but encountered an error. You should use `cloudflared tunnel delete %v` to delete the tunnel yourself, because the tunnel can't be run without the tunnelfile.", tunnel.ID)) errorLines = append(errorLines, fmt.Sprintf("Cloudflared tried to delete the tunnel for you, but encountered an error. You should use `cloudflared tunnel delete %v` to delete the tunnel yourself, because the tunnel can't be run without the tunnelfile.", tunnel.ID))
errorLines = append(errorLines, fmt.Sprintf("The delete tunnel error is: %v", deleteErr)) errorLines = append(errorLines, fmt.Sprintf("The delete tunnel error is: %v", deleteErr))
} else { } else {
errorLines = append(errorLines, fmt.Sprintf("The tunnel was deleted, because the tunnel can't be run without the credentials file")) errorLines = append(errorLines, "The tunnel was deleted, because the tunnel can't be run without the credentials file")
} }
errorMsg := strings.Join(errorLines, "\n") errorMsg := strings.Join(errorLines, "\n")
return nil, errors.New(errorMsg) return nil, errors.New(errorMsg)
@ -189,7 +207,7 @@ func (sc *subcommandContext) list(filter *cfapi.TunnelFilter) ([]*cfapi.Tunnel,
} }
func (sc *subcommandContext) delete(tunnelIDs []uuid.UUID) error { func (sc *subcommandContext) delete(tunnelIDs []uuid.UUID) error {
forceFlagSet := sc.c.Bool("force") forceFlagSet := sc.c.Bool(cfdflags.Force)
client, err := sc.client() client, err := sc.client()
if err != nil { if err != nil {
@ -229,7 +247,7 @@ func (sc *subcommandContext) findCredentials(tunnelID uuid.UUID) (connection.Cre
var err error var err error
if credentialsContents := sc.c.String(CredContentsFlag); credentialsContents != "" { if credentialsContents := sc.c.String(CredContentsFlag); credentialsContents != "" {
if err = json.Unmarshal([]byte(credentialsContents), &credentials); err != nil { if err = json.Unmarshal([]byte(credentialsContents), &credentials); err != nil {
err = errInvalidJSONCredential{path: "TUNNEL_CRED_CONTENTS", err: err} err = invalidJSONCredentialError{path: "TUNNEL_CRED_CONTENTS", err: err}
} }
} else { } else {
credFinder := sc.credentialFinder(tunnelID) credFinder := sc.credentialFinder(tunnelID)
@ -245,7 +263,7 @@ func (sc *subcommandContext) findCredentials(tunnelID uuid.UUID) (connection.Cre
func (sc *subcommandContext) run(tunnelID uuid.UUID) error { func (sc *subcommandContext) run(tunnelID uuid.UUID) error {
credentials, err := sc.findCredentials(tunnelID) credentials, err := sc.findCredentials(tunnelID)
if err != nil { if err != nil {
if e, ok := err.(errInvalidJSONCredential); ok { if e, ok := err.(invalidJSONCredentialError); ok {
sc.log.Error().Msgf("The credentials file at %s contained invalid JSON. This is probably caused by passing the wrong filepath. Reminder: the credentials file is a .json file created via `cloudflared tunnel create`.", e.path) sc.log.Error().Msgf("The credentials file at %s contained invalid JSON. This is probably caused by passing the wrong filepath. Reminder: the credentials file is a .json file created via `cloudflared tunnel create`.", e.path)
sc.log.Error().Msgf("Invalid JSON when parsing credentials file: %s", e.err.Error()) sc.log.Error().Msgf("Invalid JSON when parsing credentials file: %s", e.err.Error())
} }

View File

@ -16,15 +16,16 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
homedir "github.com/mitchellh/go-homedir" "github.com/mitchellh/go-homedir"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc" "github.com/urfave/cli/v2/altsrc"
"golang.org/x/net/idna" "golang.org/x/net/idna"
yaml "gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/cloudflare/cloudflared/cfapi" "github.com/cloudflare/cloudflared/cfapi"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
"github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/cmd/cloudflared/updater" "github.com/cloudflare/cloudflared/cmd/cloudflared/updater"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
@ -40,6 +41,7 @@ const (
CredFileFlag = "credentials-file" CredFileFlag = "credentials-file"
CredContentsFlag = "credentials-contents" CredContentsFlag = "credentials-contents"
TunnelTokenFlag = "token" TunnelTokenFlag = "token"
TunnelTokenFileFlag = "token-file"
overwriteDNSFlagName = "overwrite-dns" overwriteDNSFlagName = "overwrite-dns"
noDiagLogsFlagName = "no-diag-logs" noDiagLogsFlagName = "no-diag-logs"
noDiagMetricsFlagName = "no-diag-metrics" noDiagMetricsFlagName = "no-diag-metrics"
@ -48,7 +50,6 @@ const (
noDiagNetworkFlagName = "no-diag-network" noDiagNetworkFlagName = "no-diag-network"
diagContainerIDFlagName = "diag-container-id" diagContainerIDFlagName = "diag-container-id"
diagPodFlagName = "diag-pod-id" diagPodFlagName = "diag-pod-id"
metricsFlagName = "metrics"
LogFieldTunnelID = "tunnelID" LogFieldTunnelID = "tunnelID"
) )
@ -60,7 +61,7 @@ var (
Usage: "Include deleted tunnels in the list", Usage: "Include deleted tunnels in the list",
} }
listNameFlag = &cli.StringFlag{ listNameFlag = &cli.StringFlag{
Name: "name", Name: flags.Name,
Aliases: []string{"n"}, Aliases: []string{"n"},
Usage: "List tunnels with the given `NAME`", Usage: "List tunnels with the given `NAME`",
} }
@ -108,7 +109,7 @@ var (
EnvVars: []string{"TUNNEL_LIST_INVERT_SORT"}, EnvVars: []string{"TUNNEL_LIST_INVERT_SORT"},
} }
featuresFlag = altsrc.NewStringSliceFlag(&cli.StringSliceFlag{ featuresFlag = altsrc.NewStringSliceFlag(&cli.StringSliceFlag{
Name: "features", Name: flags.Features,
Aliases: []string{"F"}, Aliases: []string{"F"},
Usage: "Opt into various features that are still being developed or tested.", Usage: "Opt into various features that are still being developed or tested.",
}) })
@ -126,18 +127,23 @@ var (
}) })
tunnelTokenFlag = altsrc.NewStringFlag(&cli.StringFlag{ tunnelTokenFlag = altsrc.NewStringFlag(&cli.StringFlag{
Name: TunnelTokenFlag, Name: TunnelTokenFlag,
Usage: "The Tunnel token. When provided along with credentials, this will take precedence.", Usage: "The Tunnel token. When provided along with credentials, this will take precedence. Also takes precedence over token-file",
EnvVars: []string{"TUNNEL_TOKEN"}, EnvVars: []string{"TUNNEL_TOKEN"},
}) })
tunnelTokenFileFlag = altsrc.NewStringFlag(&cli.StringFlag{
Name: TunnelTokenFileFlag,
Usage: "Filepath at which to read the tunnel token. When provided along with credentials, this will take precedence.",
EnvVars: []string{"TUNNEL_TOKEN_FILE"},
})
forceDeleteFlag = &cli.BoolFlag{ forceDeleteFlag = &cli.BoolFlag{
Name: "force", Name: flags.Force,
Aliases: []string{"f"}, Aliases: []string{"f"},
Usage: "Deletes a tunnel even if tunnel is connected and it has dependencies associated to it. (eg. IP routes)." + Usage: "Deletes a tunnel even if tunnel is connected and it has dependencies associated to it. (eg. IP routes)." +
" It is not possible to delete tunnels that have connections or non-deleted dependencies, without this flag.", " It is not possible to delete tunnels that have connections or non-deleted dependencies, without this flag.",
EnvVars: []string{"TUNNEL_RUN_FORCE_OVERWRITE"}, EnvVars: []string{"TUNNEL_RUN_FORCE_OVERWRITE"},
} }
selectProtocolFlag = altsrc.NewStringFlag(&cli.StringFlag{ selectProtocolFlag = altsrc.NewStringFlag(&cli.StringFlag{
Name: "protocol", Name: flags.Protocol,
Value: connection.AutoSelectFlag, Value: connection.AutoSelectFlag,
Aliases: []string{"p"}, Aliases: []string{"p"},
Usage: fmt.Sprintf("Protocol implementation to connect with Cloudflare's edge network. %s", connection.AvailableProtocolFlagMessage), Usage: fmt.Sprintf("Protocol implementation to connect with Cloudflare's edge network. %s", connection.AvailableProtocolFlagMessage),
@ -145,7 +151,7 @@ var (
Hidden: true, Hidden: true,
}) })
postQuantumFlag = altsrc.NewBoolFlag(&cli.BoolFlag{ postQuantumFlag = altsrc.NewBoolFlag(&cli.BoolFlag{
Name: "post-quantum", Name: flags.PostQuantum,
Usage: "When given creates an experimental post-quantum secure tunnel", Usage: "When given creates an experimental post-quantum secure tunnel",
Aliases: []string{"pq"}, Aliases: []string{"pq"},
EnvVars: []string{"TUNNEL_POST_QUANTUM"}, EnvVars: []string{"TUNNEL_POST_QUANTUM"},
@ -181,17 +187,17 @@ var (
EnvVars: []string{"TUNNEL_CREATE_SECRET"}, EnvVars: []string{"TUNNEL_CREATE_SECRET"},
} }
icmpv4SrcFlag = &cli.StringFlag{ icmpv4SrcFlag = &cli.StringFlag{
Name: "icmpv4-src", Name: flags.ICMPV4Src,
Usage: "Source address to send/receive ICMPv4 messages. If not provided cloudflared will dial a local address to determine the source IP or fallback to 0.0.0.0.", Usage: "Source address to send/receive ICMPv4 messages. If not provided cloudflared will dial a local address to determine the source IP or fallback to 0.0.0.0.",
EnvVars: []string{"TUNNEL_ICMPV4_SRC"}, EnvVars: []string{"TUNNEL_ICMPV4_SRC"},
} }
icmpv6SrcFlag = &cli.StringFlag{ icmpv6SrcFlag = &cli.StringFlag{
Name: "icmpv6-src", Name: flags.ICMPV6Src,
Usage: "Source address and the interface name to send/receive ICMPv6 messages. If not provided cloudflared will dial a local address to determine the source IP or fallback to ::.", Usage: "Source address and the interface name to send/receive ICMPv6 messages. If not provided cloudflared will dial a local address to determine the source IP or fallback to ::.",
EnvVars: []string{"TUNNEL_ICMPV6_SRC"}, EnvVars: []string{"TUNNEL_ICMPV6_SRC"},
} }
metricsFlag = &cli.StringFlag{ metricsFlag = &cli.StringFlag{
Name: metricsFlagName, Name: flags.Metrics,
Usage: "The metrics server address i.e.: 127.0.0.1:12345. If your instance is running in a Docker/Kubernetes environment you need to setup port forwarding for your application.", Usage: "The metrics server address i.e.: 127.0.0.1:12345. If your instance is running in a Docker/Kubernetes environment you need to setup port forwarding for your application.",
Value: "", Value: "",
} }
@ -231,7 +237,7 @@ var (
Value: false, Value: false,
} }
maxActiveFlowsFlag = &cli.Uint64Flag{ maxActiveFlowsFlag = &cli.Uint64Flag{
Name: "max-active-flows", Name: flags.MaxActiveFlows,
Usage: "Overrides the remote configuration for max active private network flows (TCP/UDP) that this cloudflared instance supports", Usage: "Overrides the remote configuration for max active private network flows (TCP/UDP) that this cloudflared instance supports",
EnvVars: []string{"TUNNEL_MAX_ACTIVE_FLOWS"}, EnvVars: []string{"TUNNEL_MAX_ACTIVE_FLOWS"},
} }
@ -337,7 +343,7 @@ func listCommand(c *cli.Context) error {
if !c.Bool("show-deleted") { if !c.Bool("show-deleted") {
filter.NoDeleted() filter.NoDeleted()
} }
if name := c.String("name"); name != "" { if name := c.String(flags.Name); name != "" {
filter.ByName(name) filter.ByName(name)
} }
if namePrefix := c.String("name-prefix"); namePrefix != "" { if namePrefix := c.String("name-prefix"); namePrefix != "" {
@ -467,9 +473,9 @@ func buildReadyCommand() *cli.Command {
} }
func readyCommand(c *cli.Context) error { func readyCommand(c *cli.Context) error {
metricsOpts := c.String("metrics") metricsOpts := c.String(flags.Metrics)
if !c.IsSet("metrics") { if !c.IsSet(flags.Metrics) {
return fmt.Errorf("--metrics has to be provided") return errors.New("--metrics has to be provided")
} }
requestURL := fmt.Sprintf("http://%s/ready", metricsOpts) requestURL := fmt.Sprintf("http://%s/ready", metricsOpts)
@ -708,6 +714,7 @@ func buildRunCommand() *cli.Command {
selectProtocolFlag, selectProtocolFlag,
featuresFlag, featuresFlag,
tunnelTokenFlag, tunnelTokenFlag,
tunnelTokenFileFlag,
icmpv4SrcFlag, icmpv4SrcFlag,
icmpv6SrcFlag, icmpv6SrcFlag,
maxActiveFlowsFlag, maxActiveFlowsFlag,
@ -748,12 +755,22 @@ func runCommand(c *cli.Context) error {
"your origin will not be reachable. You should remove the `hostname` property to avoid this warning.") "your origin will not be reachable. You should remove the `hostname` property to avoid this warning.")
} }
tokenStr := c.String(TunnelTokenFlag)
// Check if tokenStr is blank before checking for tokenFile
if tokenStr == "" {
if tokenFile := c.String(TunnelTokenFileFlag); tokenFile != "" {
data, err := os.ReadFile(tokenFile)
if err != nil {
return cliutil.UsageError("Failed to read token file: " + err.Error())
}
tokenStr = strings.TrimSpace(string(data))
}
}
// Check if token is provided and if not use default tunnelID flag method // Check if token is provided and if not use default tunnelID flag method
if tokenStr := c.String(TunnelTokenFlag); tokenStr != "" { if tokenStr != "" {
if token, err := ParseToken(tokenStr); err == nil { if token, err := ParseToken(tokenStr); err == nil {
return sc.runWithCredentials(token.Credentials()) return sc.runWithCredentials(token.Credentials())
} }
return cliutil.UsageError("Provided Tunnel token is not valid.") return cliutil.UsageError("Provided Tunnel token is not valid.")
} else { } else {
tunnelRef := c.Args().First() tunnelRef := c.Args().First()
@ -1079,7 +1096,7 @@ func diagCommand(ctx *cli.Context) error {
log := sctx.log log := sctx.log
options := diagnostic.Options{ options := diagnostic.Options{
KnownAddresses: metrics.GetMetricsKnownAddresses(metrics.Runtime), KnownAddresses: metrics.GetMetricsKnownAddresses(metrics.Runtime),
Address: sctx.c.String(metricsFlagName), Address: sctx.c.String(flags.Metrics),
ContainerID: sctx.c.String(diagContainerIDFlagName), ContainerID: sctx.c.String(diagContainerIDFlagName),
PodID: sctx.c.String(diagPodFlagName), PodID: sctx.c.String(diagPodFlagName),
Toggles: diagnostic.Toggles{ Toggles: diagnostic.Toggles{

View File

@ -22,7 +22,7 @@ var (
Usage: "The ID or name of the virtual network to which the route is associated to.", Usage: "The ID or name of the virtual network to which the route is associated to.",
} }
routeAddError = errors.New("You must supply exactly one argument, the ID or CIDR of the route you want to delete") errAddRoute = errors.New("You must supply exactly one argument, the ID or CIDR of the route you want to delete")
) )
func buildRouteIPSubcommand() *cli.Command { func buildRouteIPSubcommand() *cli.Command {
@ -32,7 +32,7 @@ func buildRouteIPSubcommand() *cli.Command {
UsageText: "cloudflared tunnel [--config FILEPATH] route COMMAND [arguments...]", UsageText: "cloudflared tunnel [--config FILEPATH] route COMMAND [arguments...]",
Description: `cloudflared can provision routes for any IP space in your corporate network. Users enrolled in Description: `cloudflared can provision routes for any IP space in your corporate network. Users enrolled in
your Cloudflare for Teams organization can reach those IPs through the Cloudflare WARP your Cloudflare for Teams organization can reach those IPs through the Cloudflare WARP
client. You can then configure L7/L4 filtering on https://dash.teams.cloudflare.com to client. You can then configure L7/L4 filtering on https://one.dash.cloudflare.com to
determine who can reach certain routes. determine who can reach certain routes.
By default IP routes all exist within a single virtual network. If you use the same IP By default IP routes all exist within a single virtual network. If you use the same IP
space(s) in different physical private networks, all meant to be reachable via IP routes, space(s) in different physical private networks, all meant to be reachable via IP routes,
@ -187,7 +187,7 @@ func deleteRouteCommand(c *cli.Context) error {
} }
if c.NArg() != 1 { if c.NArg() != 1 {
return routeAddError return errAddRoute
} }
var routeId uuid.UUID var routeId uuid.UUID
@ -195,7 +195,7 @@ func deleteRouteCommand(c *cli.Context) error {
if err != nil { if err != nil {
_, network, err := net.ParseCIDR(c.Args().First()) _, network, err := net.ParseCIDR(c.Args().First())
if err != nil || network == nil { if err != nil || network == nil {
return routeAddError return errAddRoute
} }
var vnetId *uuid.UUID var vnetId *uuid.UUID

View File

@ -15,13 +15,14 @@ import (
"golang.org/x/term" "golang.org/x/term"
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/logger" "github.com/cloudflare/cloudflared/logger"
) )
const ( const (
DefaultCheckUpdateFreq = time.Hour * 24 DefaultCheckUpdateFreq = time.Hour * 24
noUpdateInShellMessage = "cloudflared will not automatically update when run from the shell. To enable auto-updates, run cloudflared as a service: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/as-a-service/" noUpdateInShellMessage = "cloudflared will not automatically update when run from the shell. To enable auto-updates, run cloudflared as a service: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configure-tunnels/local-management/as-a-service/"
noUpdateOnWindowsMessage = "cloudflared will not automatically update on Windows systems." noUpdateOnWindowsMessage = "cloudflared will not automatically update on Windows systems."
noUpdateManagedPackageMessage = "cloudflared will not automatically update if installed by a package manager." noUpdateManagedPackageMessage = "cloudflared will not automatically update if installed by a package manager."
isManagedInstallFile = ".installedFromPackageManager" isManagedInstallFile = ".installedFromPackageManager"
@ -38,6 +39,7 @@ var (
// BinaryUpdated implements ExitCoder interface, the app will exit with status code 11 // BinaryUpdated implements ExitCoder interface, the app will exit with status code 11
// https://pkg.go.dev/github.com/urfave/cli/v2?tab=doc#ExitCoder // https://pkg.go.dev/github.com/urfave/cli/v2?tab=doc#ExitCoder
// nolint: errname
type statusSuccess struct { type statusSuccess struct {
newVersion string newVersion string
} }
@ -50,16 +52,16 @@ func (u *statusSuccess) ExitCode() int {
return 11 return 11
} }
// UpdateErr implements ExitCoder interface, the app will exit with status code 10 // statusError implements ExitCoder interface, the app will exit with status code 10
type statusErr struct { type statusError struct {
err error err error
} }
func (e *statusErr) Error() string { func (e *statusError) Error() string {
return fmt.Sprintf("failed to update cloudflared: %v", e.err) return fmt.Sprintf("failed to update cloudflared: %v", e.err)
} }
func (e *statusErr) ExitCode() int { func (e *statusError) ExitCode() int {
return 10 return 10
} }
@ -79,7 +81,7 @@ type UpdateOutcome struct {
} }
func (uo *UpdateOutcome) noUpdate() bool { func (uo *UpdateOutcome) noUpdate() bool {
return uo.Error == nil && uo.Updated == false return uo.Error == nil && !uo.Updated
} }
func Init(info *cliutil.BuildInfo) { func Init(info *cliutil.BuildInfo) {
@ -153,7 +155,7 @@ func Update(c *cli.Context) error {
log.Info().Msg("cloudflared is set to update from staging") log.Info().Msg("cloudflared is set to update from staging")
} }
isForced := c.Bool("force") isForced := c.Bool(cfdflags.Force)
if isForced { if isForced {
log.Info().Msg("cloudflared is set to upgrade to the latest publish version regardless of the current version") log.Info().Msg("cloudflared is set to upgrade to the latest publish version regardless of the current version")
} }
@ -166,7 +168,7 @@ func Update(c *cli.Context) error {
intendedVersion: c.String("version"), intendedVersion: c.String("version"),
}) })
if updateOutcome.Error != nil { if updateOutcome.Error != nil {
return &statusErr{updateOutcome.Error} return &statusError{updateOutcome.Error}
} }
if updateOutcome.noUpdate() { if updateOutcome.noUpdate() {
@ -252,7 +254,7 @@ func (a *AutoUpdater) Run(ctx context.Context) error {
pid, err := a.listeners.StartProcess() pid, err := a.listeners.StartProcess()
if err != nil { if err != nil {
a.log.Err(err).Msg("Unable to restart server automatically") a.log.Err(err).Msg("Unable to restart server automatically")
return &statusErr{err: err} return &statusError{err: err}
} }
// stop old process after autoupdate. Otherwise we create a new process // stop old process after autoupdate. Otherwise we create a new process
// after each update // after each update

View File

@ -10,9 +10,9 @@ import (
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
"path"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings"
"text/template" "text/template"
"time" "time"
@ -134,7 +134,7 @@ func (v *WorkersVersion) Apply() error {
if err := os.Rename(newFilePath, v.targetPath); err != nil { if err := os.Rename(newFilePath, v.targetPath); err != nil {
//attempt rollback //attempt rollback
os.Rename(oldFilePath, v.targetPath) _ = os.Rename(oldFilePath, v.targetPath)
return err return err
} }
os.Remove(oldFilePath) os.Remove(oldFilePath)
@ -181,7 +181,7 @@ func download(url, filepath string, isCompressed bool) error {
tr := tar.NewReader(gr) tr := tar.NewReader(gr)
// advance the reader pass the header, which will be the single binary file // advance the reader pass the header, which will be the single binary file
tr.Next() _, _ = tr.Next()
r = tr r = tr
} }
@ -198,7 +198,7 @@ func download(url, filepath string, isCompressed bool) error {
// isCompressedFile is a really simple file extension check to see if this is a macos tar and gzipped // isCompressedFile is a really simple file extension check to see if this is a macos tar and gzipped
func isCompressedFile(urlstring string) bool { func isCompressedFile(urlstring string) bool {
if strings.HasSuffix(urlstring, ".tgz") { if path.Ext(urlstring) == ".tgz" {
return true return true
} }
@ -206,7 +206,7 @@ func isCompressedFile(urlstring string) bool {
if err != nil { if err != nil {
return false return false
} }
return strings.HasSuffix(u.Path, ".tgz") return path.Ext(u.Path) == ".tgz"
} }
// writeBatchFile writes a batch file out to disk // writeBatchFile writes a batch file out to disk
@ -249,7 +249,6 @@ func runWindowsBatch(batchFile string) error {
if exitError, ok := err.(*exec.ExitError); ok { if exitError, ok := err.(*exec.ExitError); ok {
return fmt.Errorf("Error during update : %s;", string(exitError.Stderr)) return fmt.Errorf("Error during update : %s;", string(exitError.Stderr))
} }
} }
return err return err
} }

View File

@ -26,7 +26,7 @@ import (
const ( const (
windowsServiceName = "Cloudflared" windowsServiceName = "Cloudflared"
windowsServiceDescription = "Cloudflared agent" windowsServiceDescription = "Cloudflared agent"
windowsServiceUrl = "https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/run-tunnel/as-a-service/windows/" windowsServiceUrl = "https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/configure-tunnels/local-management/as-a-service/windows/"
recoverActionDelay = time.Second * 20 recoverActionDelay = time.Second * 20
failureCountResetPeriod = time.Hour * 24 failureCountResetPeriod = time.Hour * 24

View File

@ -60,6 +60,7 @@ type Credentials struct {
AccountTag string AccountTag string
TunnelSecret []byte TunnelSecret []byte
TunnelID uuid.UUID TunnelID uuid.UUID
Endpoint string
} }
func (c *Credentials) Auth() pogs.TunnelAuth { func (c *Credentials) Auth() pogs.TunnelAuth {
@ -74,13 +75,16 @@ type TunnelToken struct {
AccountTag string `json:"a"` AccountTag string `json:"a"`
TunnelSecret []byte `json:"s"` TunnelSecret []byte `json:"s"`
TunnelID uuid.UUID `json:"t"` TunnelID uuid.UUID `json:"t"`
Endpoint string `json:"e,omitempty"`
} }
func (t TunnelToken) Credentials() Credentials { func (t TunnelToken) Credentials() Credentials {
// nolint: gosimple
return Credentials{ return Credentials{
AccountTag: t.AccountTag, AccountTag: t.AccountTag,
TunnelSecret: t.TunnelSecret, TunnelSecret: t.TunnelSecret,
TunnelID: t.TunnelID, TunnelID: t.TunnelID,
Endpoint: t.Endpoint,
} }
} }

View File

@ -9,6 +9,7 @@ import (
const ( const (
logFieldOriginCertPath = "originCertPath" logFieldOriginCertPath = "originCertPath"
FedEndpoint = "fed"
) )
type User struct { type User struct {
@ -32,6 +33,10 @@ func (c User) CertPath() string {
return c.certPath return c.certPath
} }
func (c User) IsFEDEndpoint() bool {
return c.cert.Endpoint == FedEndpoint
}
// Client uses the user credentials to create a Cloudflare API client // Client uses the user credentials to create a Cloudflare API client
func (c *User) Client(apiURL string, userAgent string, log *zerolog.Logger) (cfapi.Client, error) { func (c *User) Client(apiURL string, userAgent string, log *zerolog.Logger) (cfapi.Client, error) {
if apiURL == "" { if apiURL == "" {
@ -45,7 +50,6 @@ func (c *User) Client(apiURL string, userAgent string, log *zerolog.Logger) (cfa
userAgent, userAgent,
log, log,
) )
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -3,7 +3,7 @@ package credentials
import ( import (
"io/fs" "io/fs"
"os" "os"
"path" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -13,8 +13,8 @@ func TestCredentialsRead(t *testing.T) {
file, err := os.ReadFile("test-cloudflare-tunnel-cert-json.pem") file, err := os.ReadFile("test-cloudflare-tunnel-cert-json.pem")
require.NoError(t, err) require.NoError(t, err)
dir := t.TempDir() dir := t.TempDir()
certPath := path.Join(dir, originCertFile) certPath := filepath.Join(dir, originCertFile)
os.WriteFile(certPath, file, fs.ModePerm) _ = os.WriteFile(certPath, file, fs.ModePerm)
user, err := Read(certPath, &nopLog) user, err := Read(certPath, &nopLog)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, certPath, user.CertPath()) require.Equal(t, certPath, user.CertPath())

View File

@ -1,11 +1,13 @@
package credentials package credentials
import ( import (
"bytes"
"encoding/json" "encoding/json"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/mitchellh/go-homedir" "github.com/mitchellh/go-homedir"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -15,19 +17,30 @@ import (
const ( const (
DefaultCredentialFile = "cert.pem" DefaultCredentialFile = "cert.pem"
OriginCertFlag = "origincert"
) )
type namedTunnelToken struct { type OriginCert struct {
ZoneID string `json:"zoneID"` ZoneID string `json:"zoneID"`
AccountID string `json:"accountID"` AccountID string `json:"accountID"`
APIToken string `json:"apiToken"` APIToken string `json:"apiToken"`
Endpoint string `json:"endpoint,omitempty"`
} }
type OriginCert struct { func (oc *OriginCert) UnmarshalJSON(data []byte) error {
ZoneID string var aux struct {
APIToken string ZoneID string `json:"zoneID"`
AccountID string AccountID string `json:"accountID"`
APIToken string `json:"apiToken"`
Endpoint string `json:"endpoint,omitempty"`
}
if err := json.Unmarshal(data, &aux); err != nil {
return fmt.Errorf("error parsing OriginCert: %v", err)
}
oc.ZoneID = aux.ZoneID
oc.AccountID = aux.AccountID
oc.APIToken = aux.APIToken
oc.Endpoint = strings.ToLower(aux.Endpoint)
return nil
} }
// FindDefaultOriginCertPath returns the first path that contains a cert.pem file. If none of the // FindDefaultOriginCertPath returns the first path that contains a cert.pem file. If none of the
@ -42,40 +55,56 @@ func FindDefaultOriginCertPath() string {
return "" return ""
} }
func DecodeOriginCert(blocks []byte) (*OriginCert, error) {
return decodeOriginCert(blocks)
}
func (cert *OriginCert) EncodeOriginCert() ([]byte, error) {
if cert == nil {
return nil, fmt.Errorf("originCert cannot be nil")
}
buffer, err := json.Marshal(cert)
if err != nil {
return nil, fmt.Errorf("originCert marshal failed: %v", err)
}
block := pem.Block{
Type: "ARGO TUNNEL TOKEN",
Headers: map[string]string{},
Bytes: buffer,
}
var out bytes.Buffer
err = pem.Encode(&out, &block)
if err != nil {
return nil, fmt.Errorf("pem encoding failed: %v", err)
}
return out.Bytes(), nil
}
func decodeOriginCert(blocks []byte) (*OriginCert, error) { func decodeOriginCert(blocks []byte) (*OriginCert, error) {
if len(blocks) == 0 { if len(blocks) == 0 {
return nil, fmt.Errorf("Cannot decode empty certificate") return nil, fmt.Errorf("cannot decode empty certificate")
} }
originCert := OriginCert{} originCert := OriginCert{}
block, rest := pem.Decode(blocks) block, rest := pem.Decode(blocks)
for { for block != nil {
if block == nil {
break
}
switch block.Type { switch block.Type {
case "PRIVATE KEY", "CERTIFICATE": case "PRIVATE KEY", "CERTIFICATE":
// this is for legacy purposes. // this is for legacy purposes.
break
case "ARGO TUNNEL TOKEN": case "ARGO TUNNEL TOKEN":
if originCert.ZoneID != "" || originCert.APIToken != "" { if originCert.ZoneID != "" || originCert.APIToken != "" {
return nil, fmt.Errorf("Found multiple tokens in the certificate") return nil, fmt.Errorf("found multiple tokens in the certificate")
} }
// The token is a string, // The token is a string,
// Try the newer JSON format // Try the newer JSON format
ntt := namedTunnelToken{} _ = json.Unmarshal(block.Bytes, &originCert)
if err := json.Unmarshal(block.Bytes, &ntt); err == nil {
originCert.ZoneID = ntt.ZoneID
originCert.APIToken = ntt.APIToken
originCert.AccountID = ntt.AccountID
}
default: default:
return nil, fmt.Errorf("Unknown block %s in the certificate", block.Type) return nil, fmt.Errorf("unknown block %s in the certificate", block.Type)
} }
block, rest = pem.Decode(rest) block, rest = pem.Decode(rest)
} }
if originCert.ZoneID == "" || originCert.APIToken == "" { if originCert.ZoneID == "" || originCert.APIToken == "" {
return nil, fmt.Errorf("Missing token in the certificate") return nil, fmt.Errorf("missing token in the certificate")
} }
return &originCert, nil return &originCert, nil

View File

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
"os" "os"
"path" "path/filepath"
"testing" "testing"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -16,27 +16,25 @@ const (
originCertFile = "cert.pem" originCertFile = "cert.pem"
) )
var ( var nopLog = zerolog.Nop().With().Logger()
nopLog = zerolog.Nop().With().Logger()
)
func TestLoadOriginCert(t *testing.T) { func TestLoadOriginCert(t *testing.T) {
cert, err := decodeOriginCert([]byte{}) cert, err := decodeOriginCert([]byte{})
assert.Equal(t, fmt.Errorf("Cannot decode empty certificate"), err) assert.Equal(t, fmt.Errorf("cannot decode empty certificate"), err)
assert.Nil(t, cert) assert.Nil(t, cert)
blocks, err := os.ReadFile("test-cert-unknown-block.pem") blocks, err := os.ReadFile("test-cert-unknown-block.pem")
assert.NoError(t, err) require.NoError(t, err)
cert, err = decodeOriginCert(blocks) cert, err = decodeOriginCert(blocks)
assert.Equal(t, fmt.Errorf("Unknown block RSA PRIVATE KEY in the certificate"), err) assert.Equal(t, fmt.Errorf("unknown block RSA PRIVATE KEY in the certificate"), err)
assert.Nil(t, cert) assert.Nil(t, cert)
} }
func TestJSONArgoTunnelTokenEmpty(t *testing.T) { func TestJSONArgoTunnelTokenEmpty(t *testing.T) {
blocks, err := os.ReadFile("test-cert-no-token.pem") blocks, err := os.ReadFile("test-cert-no-token.pem")
assert.NoError(t, err) require.NoError(t, err)
cert, err := decodeOriginCert(blocks) cert, err := decodeOriginCert(blocks)
assert.Equal(t, fmt.Errorf("Missing token in the certificate"), err) assert.Equal(t, fmt.Errorf("missing token in the certificate"), err)
assert.Nil(t, cert) assert.Nil(t, cert)
} }
@ -52,51 +50,21 @@ func TestJSONArgoTunnelToken(t *testing.T) {
func CloudflareTunnelTokenTest(t *testing.T, path string) { func CloudflareTunnelTokenTest(t *testing.T, path string) {
blocks, err := os.ReadFile(path) blocks, err := os.ReadFile(path)
assert.NoError(t, err) require.NoError(t, err)
cert, err := decodeOriginCert(blocks) cert, err := decodeOriginCert(blocks)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, cert) assert.NotNil(t, cert)
assert.Equal(t, "7b0a4d77dfb881c1a3b7d61ea9443e19", cert.ZoneID) assert.Equal(t, "7b0a4d77dfb881c1a3b7d61ea9443e19", cert.ZoneID)
key := "test-service-key" key := "test-service-key"
assert.Equal(t, key, cert.APIToken) assert.Equal(t, key, cert.APIToken)
} }
type mockFile struct {
path string
data []byte
err error
}
type mockFileSystem struct {
files map[string]mockFile
}
func newMockFileSystem(files ...mockFile) *mockFileSystem {
fs := mockFileSystem{map[string]mockFile{}}
for _, f := range files {
fs.files[f.path] = f
}
return &fs
}
func (fs *mockFileSystem) ReadFile(path string) ([]byte, error) {
if f, ok := fs.files[path]; ok {
return f.data, f.err
}
return nil, os.ErrNotExist
}
func (fs *mockFileSystem) ValidFilePath(path string) bool {
_, exists := fs.files[path]
return exists
}
func TestFindOriginCert_Valid(t *testing.T) { func TestFindOriginCert_Valid(t *testing.T) {
file, err := os.ReadFile("test-cloudflare-tunnel-cert-json.pem") file, err := os.ReadFile("test-cloudflare-tunnel-cert-json.pem")
require.NoError(t, err) require.NoError(t, err)
dir := t.TempDir() dir := t.TempDir()
certPath := path.Join(dir, originCertFile) certPath := filepath.Join(dir, originCertFile)
os.WriteFile(certPath, file, fs.ModePerm) _ = os.WriteFile(certPath, file, fs.ModePerm)
path, err := FindOriginCert(certPath, &nopLog) path, err := FindOriginCert(certPath, &nopLog)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, certPath, path) require.Equal(t, certPath, path)
@ -104,7 +72,32 @@ func TestFindOriginCert_Valid(t *testing.T) {
func TestFindOriginCert_Missing(t *testing.T) { func TestFindOriginCert_Missing(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
certPath := path.Join(dir, originCertFile) certPath := filepath.Join(dir, originCertFile)
_, err := FindOriginCert(certPath, &nopLog) _, err := FindOriginCert(certPath, &nopLog)
require.Error(t, err) require.Error(t, err)
} }
func TestEncodeDecodeOriginCert(t *testing.T) {
cert := OriginCert{
ZoneID: "zone",
AccountID: "account",
APIToken: "token",
Endpoint: "FED",
}
blocks, err := cert.EncodeOriginCert()
require.NoError(t, err)
decodedCert, err := DecodeOriginCert(blocks)
require.NoError(t, err)
assert.NotNil(t, cert)
assert.Equal(t, "zone", decodedCert.ZoneID)
assert.Equal(t, "account", decodedCert.AccountID)
assert.Equal(t, "token", decodedCert.APIToken)
assert.Equal(t, FedEndpoint, decodedCert.Endpoint)
}
func TestEncodeDecodeNilOriginCert(t *testing.T) {
var cert *OriginCert
blocks, err := cert.EncodeOriginCert()
assert.Equal(t, fmt.Errorf("originCert cannot be nil"), err)
require.Nil(t, blocks)
}

View File

@ -87,3 +87,4 @@ M2i4QoOFcSKIG+v4SuvgEJHgG8vGvxh2qlSxnMWuPV+7/1P5ATLqDj1PlKms+BNR
y7sc5AT9PclkL3Y9MNzOu0LXyBkGYcl8M0EQfLv9VPbWT+NXiMg/O2CHiT02pAAz y7sc5AT9PclkL3Y9MNzOu0LXyBkGYcl8M0EQfLv9VPbWT+NXiMg/O2CHiT02pAAz
uQicoQq3yzeQh20wtrtaXzTNmA== uQicoQq3yzeQh20wtrtaXzTNmA==
-----END RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----

View File

@ -9,7 +9,7 @@ import (
"net/url" "net/url"
"strconv" "strconv"
"github.com/cloudflare/cloudflared/logger" cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
) )
type httpClient struct { type httpClient struct {
@ -86,12 +86,12 @@ func (client *httpClient) GetLogConfiguration(ctx context.Context) (*LogConfigur
return nil, fmt.Errorf("error convertin pid to int: %w", err) return nil, fmt.Errorf("error convertin pid to int: %w", err)
} }
logFile, exists := data[logger.LogFileFlag] logFile, exists := data[cfdflags.LogFile]
if exists { if exists {
return &LogConfiguration{logFile, "", uid}, nil return &LogConfiguration{logFile, "", uid}, nil
} }
logDirectory, exists := data[logger.LogDirectoryFlag] logDirectory, exists := data[cfdflags.LogDirectory]
if exists { if exists {
return &LogConfiguration{"", logDirectory, uid}, nil return &LogConfiguration{"", logDirectory, uid}, nil
} }

View File

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path"
"path/filepath" "path/filepath"
"sync" "sync"
"time" "time"
@ -16,6 +15,7 @@ import (
"golang.org/x/term" "golang.org/x/term"
"gopkg.in/natefinch/lumberjack.v2" "gopkg.in/natefinch/lumberjack.v2"
cfdflags "github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/management" "github.com/cloudflare/cloudflared/management"
) )
@ -23,14 +23,6 @@ const (
EnableTerminalLog = false EnableTerminalLog = false
DisableTerminalLog = true DisableTerminalLog = true
LogLevelFlag = "loglevel"
LogFileFlag = "logfile"
LogDirectoryFlag = "log-directory"
LogTransportLevelFlag = "transport-loglevel"
LogSSHDirectoryFlag = "log-directory"
LogSSHLevelFlag = "log-level"
dirPermMode = 0744 // rwxr--r-- dirPermMode = 0744 // rwxr--r--
filePermMode = 0644 // rw-r--r-- filePermMode = 0644 // rw-r--r--
@ -137,15 +129,15 @@ func newZerolog(loggerConfig *Config) *zerolog.Logger {
} }
func CreateTransportLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger { func CreateTransportLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger {
return createFromContext(c, LogTransportLevelFlag, LogDirectoryFlag, disableTerminal) return createFromContext(c, cfdflags.TransportLogLevel, cfdflags.LogDirectory, disableTerminal)
} }
func CreateLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger { func CreateLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger {
return createFromContext(c, LogLevelFlag, LogDirectoryFlag, disableTerminal) return createFromContext(c, cfdflags.LogLevel, cfdflags.LogDirectory, disableTerminal)
} }
func CreateSSHLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger { func CreateSSHLoggerFromContext(c *cli.Context, disableTerminal bool) *zerolog.Logger {
return createFromContext(c, LogSSHLevelFlag, LogSSHDirectoryFlag, disableTerminal) return createFromContext(c, cfdflags.LogLevelSSH, cfdflags.LogDirectory, disableTerminal)
} }
func createFromContext( func createFromContext(
@ -155,7 +147,7 @@ func createFromContext(
disableTerminal bool, disableTerminal bool,
) *zerolog.Logger { ) *zerolog.Logger {
logLevel := c.String(logLevelFlagName) logLevel := c.String(logLevelFlagName)
logFile := c.String(LogFileFlag) logFile := c.String(cfdflags.LogFile)
logDirectory := c.String(logDirectoryFlagName) logDirectory := c.String(logDirectoryFlagName)
loggerConfig := CreateConfig( loggerConfig := CreateConfig(
@ -167,7 +159,7 @@ func createFromContext(
log := newZerolog(loggerConfig) log := newZerolog(loggerConfig)
if incompatibleFlagsSet := logFile != "" && logDirectory != ""; incompatibleFlagsSet { if incompatibleFlagsSet := logFile != "" && logDirectory != ""; incompatibleFlagsSet {
log.Error().Msgf("Your config includes values for both %s (%s) and %s (%s), but they are incompatible. %s takes precedence.", LogFileFlag, logFile, logDirectoryFlagName, logDirectory, LogFileFlag) log.Error().Msgf("Your config includes values for both %s (%s) and %s (%s), but they are incompatible. %s takes precedence.", cfdflags.LogFile, logFile, logDirectoryFlagName, logDirectory, cfdflags.LogFile)
} }
return log return log
} }
@ -206,7 +198,6 @@ var (
func createFileWriter(config FileConfig) (io.Writer, error) { func createFileWriter(config FileConfig) (io.Writer, error) {
singleFileInit.once.Do(func() { singleFileInit.once.Do(func() {
var logFile io.Writer var logFile io.Writer
fullpath := config.Fullpath() fullpath := config.Fullpath()
@ -257,7 +248,7 @@ func createRollingLogger(config RollingConfig) (io.Writer, error) {
} }
rotatingFileInit.writer = &lumberjack.Logger{ rotatingFileInit.writer = &lumberjack.Logger{
Filename: path.Join(config.Dirname, config.Filename), Filename: filepath.Join(config.Dirname, config.Filename),
MaxBackups: config.maxBackups, MaxBackups: config.maxBackups,
MaxSize: config.maxSize, MaxSize: config.maxSize,
MaxAge: config.maxAge, MaxAge: config.maxAge,

View File

@ -74,7 +74,7 @@ type EventLog struct {
type LogEventType int8 type LogEventType int8
const ( const (
// Cloudflared events are signficant to cloudflared operations like connection state changes. // Cloudflared events are significant to cloudflared operations like connection state changes.
// Cloudflared is also the default event type for any events that haven't been separated into a proper event type. // Cloudflared is also the default event type for any events that haven't been separated into a proper event type.
Cloudflared LogEventType = iota Cloudflared LogEventType = iota
HTTP HTTP
@ -129,7 +129,7 @@ func (e *LogEventType) UnmarshalJSON(data []byte) error {
// LogLevel corresponds to the zerolog logging levels // LogLevel corresponds to the zerolog logging levels
// "panic", "fatal", and "trace" are exempt from this list as they are rarely used and, at least // "panic", "fatal", and "trace" are exempt from this list as they are rarely used and, at least
// the the first two are limited to failure conditions that lead to cloudflared shutting down. // the first two are limited to failure conditions that lead to cloudflared shutting down.
type LogLevel int8 type LogLevel int8
const ( const (

View File

@ -11,6 +11,7 @@ import (
pkgerrors "github.com/pkg/errors" pkgerrors "github.com/pkg/errors"
"github.com/rs/zerolog" "github.com/rs/zerolog"
"github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
cfdflow "github.com/cloudflare/cloudflared/flow" cfdflow "github.com/cloudflare/cloudflared/flow"
@ -120,7 +121,7 @@ func (o *Orchestrator) UpdateConfig(version int32, config []byte) *pogs.UpdateCo
// overrideRemoteWarpRoutingWithLocalValues overrides the ingress.WarpRoutingConfig that comes from the remote with // overrideRemoteWarpRoutingWithLocalValues overrides the ingress.WarpRoutingConfig that comes from the remote with
// the local values if there is any. // the local values if there is any.
func (o *Orchestrator) overrideRemoteWarpRoutingWithLocalValues(remoteWarpRouting *ingress.WarpRoutingConfig) error { func (o *Orchestrator) overrideRemoteWarpRoutingWithLocalValues(remoteWarpRouting *ingress.WarpRoutingConfig) error {
return o.overrideMaxActiveFlows(o.config.ConfigurationFlags["max-active-flows"], remoteWarpRouting) return o.overrideMaxActiveFlows(o.config.ConfigurationFlags[flags.MaxActiveFlows], remoteWarpRouting)
} }
// overrideMaxActiveFlows checks the local configuration flags, and if a value is found for the flags.MaxActiveFlows // overrideMaxActiveFlows checks the local configuration flags, and if a value is found for the flags.MaxActiveFlows
@ -133,7 +134,7 @@ func (o *Orchestrator) overrideMaxActiveFlows(maxActiveFlowsLocalConfig string,
maxActiveFlowsLocalOverride, err := strconv.ParseUint(maxActiveFlowsLocalConfig, 10, 64) maxActiveFlowsLocalOverride, err := strconv.ParseUint(maxActiveFlowsLocalConfig, 10, 64)
if err != nil { if err != nil {
return pkgerrors.Wrapf(err, "failed to parse %s", "max-active-flows") return pkgerrors.Wrapf(err, "failed to parse %s", flags.MaxActiveFlows)
} }
// Override the value that comes from the remote with the local value // Override the value that comes from the remote with the local value

View File

@ -19,6 +19,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/cloudflare/cloudflared/cmd/cloudflared/flags"
"github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/config"
"github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/connection"
"github.com/cloudflare/cloudflared/ingress" "github.com/cloudflare/cloudflared/ingress"
@ -421,7 +423,7 @@ func TestOverrideWarpRoutingConfigWithLocalValues(t *testing.T) {
// Add a local override for the maxActiveFlows // Add a local override for the maxActiveFlows
localValue := uint64(500) localValue := uint64(500)
remoteConfig.ConfigurationFlags["max-active-flows"] = fmt.Sprintf("%d", localValue) remoteConfig.ConfigurationFlags[flags.MaxActiveFlows] = fmt.Sprintf("%d", localValue)
// Force a configuration refresh // Force a configuration refresh
err = orchestrator.updateIngress(remoteIngress, remoteWarpConfig) err = orchestrator.updateIngress(remoteIngress, remoteWarpConfig)
require.NoError(t, err) require.NoError(t, err)
@ -430,7 +432,7 @@ func TestOverrideWarpRoutingConfigWithLocalValues(t *testing.T) {
assertMaxActiveFlows(orchestrator, localValue) assertMaxActiveFlows(orchestrator, localValue)
// Remove local override for the maxActiveFlows // Remove local override for the maxActiveFlows
delete(remoteConfig.ConfigurationFlags, "max-active-flows") delete(remoteConfig.ConfigurationFlags, flags.MaxActiveFlows)
// Force a configuration refresh // Force a configuration refresh
err = orchestrator.updateIngress(remoteIngress, remoteWarpConfig) err = orchestrator.updateIngress(remoteIngress, remoteWarpConfig)
require.NoError(t, err) require.NoError(t, err)

View File

@ -79,8 +79,8 @@ func (b *BackoffHandler) BackoffTimer() <-chan time.Time {
} else { } else {
b.retries++ b.retries++
} }
maxTimeToWait := time.Duration(b.GetBaseTime() * 1 << (b.retries)) maxTimeToWait := b.GetBaseTime() * (1 << b.retries)
timeToWait := time.Duration(rand.Int63n(maxTimeToWait.Nanoseconds())) timeToWait := time.Duration(rand.Int63n(maxTimeToWait.Nanoseconds())) // #nosec G404
return b.Clock.After(timeToWait) return b.Clock.After(timeToWait)
} }
@ -99,11 +99,11 @@ func (b *BackoffHandler) Backoff(ctx context.Context) bool {
} }
} }
// Sets a grace period within which the the backoff timer is maintained. After the grace // Sets a grace period within which the backoff timer is maintained. After the grace
// period expires, the number of retries & backoff duration is reset. // period expires, the number of retries & backoff duration is reset.
func (b *BackoffHandler) SetGracePeriod() time.Duration { func (b *BackoffHandler) SetGracePeriod() time.Duration {
maxTimeToWait := b.GetBaseTime() * 2 << (b.retries + 1) maxTimeToWait := b.GetBaseTime() * 2 << (b.retries + 1)
timeToWait := time.Duration(rand.Int63n(maxTimeToWait.Nanoseconds())) timeToWait := time.Duration(rand.Int63n(maxTimeToWait.Nanoseconds())) // #nosec G404
b.resetDeadline = b.Clock.Now().Add(timeToWait) b.resetDeadline = b.Clock.Now().Add(timeToWait)
return timeToWait return timeToWait
@ -118,7 +118,7 @@ func (b BackoffHandler) GetBaseTime() time.Duration {
// Retries returns the number of retries consumed so far. // Retries returns the number of retries consumed so far.
func (b *BackoffHandler) Retries() int { func (b *BackoffHandler) Retries() int {
return int(b.retries) return int(b.retries) // #nosec G115
} }
func (b *BackoffHandler) ReachedMaxRetries() bool { func (b *BackoffHandler) ReachedMaxRetries() bool {

View File

@ -247,9 +247,7 @@ func (s *Supervisor) startFirstTunnel(
ctx context.Context, ctx context.Context,
connectedSignal *signal.Signal, connectedSignal *signal.Signal,
) { ) {
var ( var err error
err error
)
const firstConnIndex = 0 const firstConnIndex = 0
isStaticEdge := len(s.config.EdgeAddrs) > 0 isStaticEdge := len(s.config.EdgeAddrs) > 0
defer func() { defer func() {
@ -300,9 +298,7 @@ func (s *Supervisor) startTunnel(
index int, index int,
connectedSignal *signal.Signal, connectedSignal *signal.Signal,
) { ) {
var ( var err error
err error
)
defer func() { defer func() {
s.tunnelErrors <- tunnelError{index: index, err: err} s.tunnelErrors <- tunnelError{index: index, err: err}
}() }()

View File

@ -70,7 +70,6 @@ func RunTransfer(transferURL *url.URL, appAUD, resourceName, key, value string,
} }
return resourceData, nil return resourceData, nil
} }
// BuildRequestURL creates a request suitable for a resource transfer. // BuildRequestURL creates a request suitable for a resource transfer.