diff --git a/internal/bootstrap.go b/internal/bootstrap.go index 32092b7..fb7bdd4 100644 --- a/internal/bootstrap.go +++ b/internal/bootstrap.go @@ -84,14 +84,12 @@ func newRootCommand(dependencies *components.Components) *cobra.Command { return err } - if _, err := fmt.Fprintf(command.ErrOrStderr(), "Broker: %s (%s)\n", components.RedactedURL(broker.BrokerURL), broker.Origin); err != nil { - return err - } if err := components.WarnIfKeyTravelsUnencrypted(command.ErrOrStderr(), broker.BrokerURL, broker.APIKey); err != nil { return err } dependencies.HTTPClient.UseBroker(broker.BrokerURL, broker.APIKey) dependencies.HTTPClient.ExplainAuthFailures(broker.BrokerURL) + dependencies.HTTPClient.ExplainConnectionFailures(broker.BrokerURL, broker.Origin) return nil }, diff --git a/internal/bootstrap_test.go b/internal/bootstrap_test.go index cc0ba67..c7b5fe4 100644 --- a/internal/bootstrap_test.go +++ b/internal/bootstrap_test.go @@ -184,7 +184,7 @@ func TestUsageErrorsComeBeforeAnyBrokerResolution(t *testing.T) { } } -func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStderr(t *testing.T) { +func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileWithoutAnnouncingIt(t *testing.T) { envBroker := startBrokerStub(t) defaultBroker := startBrokerStub(t) globexBroker := startBrokerStub(t) @@ -197,7 +197,6 @@ func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStde envProfile string args []string broker brokerStub - brokerLine string authorization string }{ { @@ -206,27 +205,23 @@ func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStde envKey: "bdk_env", args: []string{"--profile", "globex"}, broker: envBroker, - brokerLine: "Broker: " + envBroker.url + " (from BIDIREKT_BROKER_URL)\n", authorization: "Bearer bdk_env", }, { name: "the default profile is used without --profile and BIDIREKT_PROFILE", broker: defaultBroker, - brokerLine: "Broker: " + defaultBroker.url + " (profile: default)\n", authorization: "Bearer bdk_default", }, { name: "--profile selects the profile", args: []string{"--profile", "globex"}, broker: globexBroker, - brokerLine: "Broker: " + globexBroker.url + " (profile: globex)\n", authorization: "Bearer bdk_globex", }, { name: "BIDIREKT_PROFILE selects the profile", envProfile: "globex", broker: globexBroker, - brokerLine: "Broker: " + globexBroker.url + " (profile: globex)\n", authorization: "Bearer bdk_globex", }, { @@ -234,7 +229,6 @@ func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStde envProfile: "default", args: []string{"--profile", "globex"}, broker: globexBroker, - brokerLine: "Broker: " + globexBroker.url + " (profile: globex)\n", authorization: "Bearer bdk_globex", }, } @@ -252,7 +246,7 @@ func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStde require.NoError(t, execution.err) assert.Equal(t, "pets participant created\n", execution.stdout) - assert.Equal(t, test.brokerLine, execution.stderr) + assert.Empty(t, execution.stderr) assert.Equal(t, requestsBefore+1, test.broker.requests.Load()) authorizations := test.broker.authorizations() assert.Equal(t, test.authorization, authorizations[len(authorizations)-1]) @@ -372,18 +366,54 @@ func TestKeyWithoutThePrefixNeverLeavesTheMachine(t *testing.T) { } } -func TestBrokerLineHidesThePasswordAndTheKey(t *testing.T) { - isolateEnvironment(t) - broker := startBrokerStub(t) - t.Setenv("BIDIREKT_BROKER_URL", strings.Replace(broker.url, "http://", "http://ci:segredo@", 1)) - t.Setenv("BIDIREKT_API_KEY", "bdk_segredo") +func TestUnreachableBrokerFailsNamingItsURLAndOrigin(t *testing.T) { + closedServer := httptest.NewServer(http.NotFoundHandler()) + closedServer.Close() + unreachableURL := closedServer.URL - execution := executeRoot(t, components.New(), "create-participant", "pets") + tests := []struct { + name string + envURL string + envKey string + config string + brokerAt string + fromWhere string + }{ + { + name: "from BIDIREKT_BROKER_URL, hiding the password and the key", + envURL: strings.Replace(unreachableURL, "http://", "http://ci:segredo@", 1), + envKey: "bdk_segredo", + brokerAt: strings.Replace(unreachableURL, "http://", "http://ci:xxxxx@", 1), + fromWhere: "from BIDIREKT_BROKER_URL", + }, + { + name: "from the active profile", + config: `{"profiles":{"default":{"brokerUrl":"` + unreachableURL + `","apiKey":"bdk_segredo"}}}`, + brokerAt: unreachableURL, + fromWhere: "profile: default", + }, + } - require.NoError(t, execution.err) - assert.Equal(t, "Broker: "+strings.Replace(broker.url, "http://", "http://ci:xxxxx@", 1)+" (from BIDIREKT_BROKER_URL)\n", execution.stderr) - assert.NotContains(t, execution.stderr+execution.stdout, "segredo") - assert.Equal(t, int32(1), broker.requests.Load()) + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + configFilePath := isolateEnvironment(t) + if test.config != "" { + writeConfigFile(t, configFilePath, test.config) + } + t.Setenv("BIDIREKT_BROKER_URL", test.envURL) + t.Setenv("BIDIREKT_API_KEY", test.envKey) + + execution := executeRoot(t, components.New(), "create-participant", "pets") + var printed bytes.Buffer + printError(&printed, execution.err) + + require.Error(t, execution.err) + assert.True(t, strings.HasPrefix(printed.String(), "cannot reach the broker at "+test.brokerAt+" ("+test.fromWhere+"): dial tcp "), printed.String()) + assert.Contains(t, printed.String(), "connection refused") + assert.NotContains(t, printed.String()+execution.stderr+execution.stdout, "segredo") + assert.Empty(t, execution.stderr) + }) + } } func TestInvalidBrokerURLFailsNamingItsOrigin(t *testing.T) { @@ -579,7 +609,7 @@ func TestAuthFailuresPrintOnlyTheirHint(t *testing.T) { require.Error(t, execution.err) assert.Equal(t, status.hint(server.URL)+"\n", printed.String()) assert.Empty(t, execution.stdout) - assert.Equal(t, "Broker: "+server.URL+" (from BIDIREKT_BROKER_URL)\n", execution.stderr) + assert.Empty(t, execution.stderr) }) } } @@ -611,7 +641,7 @@ func TestKeyOverPlainHTTPToARemoteHostWarnsAndTheRequestProceeds(t *testing.T) { execution := executeRoot(t, dependencies, "create-participant", "pets") require.NoError(t, execution.err) - assert.Equal(t, "Broker: "+brokerURL+" (from BIDIREKT_BROKER_URL)\nwarning: the API key travels unencrypted to "+brokerURL+"\n", execution.stderr) + assert.Equal(t, "warning: the API key travels unencrypted to "+brokerURL+"\n", execution.stderr) assert.Equal(t, []string{brokerURL + "/api/participants"}, requested) assert.NotContains(t, execution.stderr, "bdk_acme") } diff --git a/internal/components/broker_unreachable_error.go b/internal/components/broker_unreachable_error.go new file mode 100644 index 0000000..a2e157f --- /dev/null +++ b/internal/components/broker_unreachable_error.go @@ -0,0 +1,19 @@ +package components + +type BrokerUnreachableError struct { + BrokerURL string + Origin string + Cause error +} + +func (this BrokerUnreachableError) Error() string { + return "cannot reach the broker at " + this.BrokerURL + " (" + this.Origin + "): " + this.Cause.Error() +} + +func (this BrokerUnreachableError) UserText() string { + return this.Error() +} + +func (this BrokerUnreachableError) Unwrap() error { + return this.Cause +} diff --git a/internal/components/http_client.go b/internal/components/http_client.go index eb5cccf..5e493ad 100644 --- a/internal/components/http_client.go +++ b/internal/components/http_client.go @@ -3,14 +3,17 @@ package components import ( "context" "encoding/json" + "errors" "fmt" "net/http" + "net/url" "resty.dev/v3" ) type HTTPClient struct { - restClient *resty.Client + restClient *resty.Client + unreachableAt *BrokerUnreachableError } func NewHTTPClient() *HTTPClient { @@ -56,12 +59,29 @@ func (this *HTTPClient) ExplainAuthFailures(brokerURL string) { }) } -func (this *HTTPClient) Get(ctx context.Context, url string) (*resty.Response, error) { - return this.restClient.R().SetContext(ctx).Get(url) +func (this *HTTPClient) ExplainConnectionFailures(brokerURL, origin string) { + this.unreachableAt = &BrokerUnreachableError{BrokerURL: RedactedURL(brokerURL), Origin: origin} } -func (this *HTTPClient) Post(ctx context.Context, url string, body any) (*resty.Response, error) { - return this.restClient.R().SetContext(ctx).SetBody(body).Post(url) +func (this *HTTPClient) Get(ctx context.Context, path string) (*resty.Response, error) { + response, err := this.restClient.R().SetContext(ctx).Get(path) + return response, this.explainConnectionFailure(err) +} + +func (this *HTTPClient) Post(ctx context.Context, path string, body any) (*resty.Response, error) { + response, err := this.restClient.R().SetContext(ctx).SetBody(body).Post(path) + return response, this.explainConnectionFailure(err) +} + +func (this *HTTPClient) explainConnectionFailure(err error) error { + var transportErr *url.Error + if this.unreachableAt == nil || !errors.As(err, &transportErr) || errors.Is(err, context.Canceled) { + return err + } + + unreachable := *this.unreachableAt + unreachable.Cause = transportErr.Err + return unreachable } func explainUpgradeRequired(_ *resty.Client, response *resty.Response) error { diff --git a/tests/e2e/commands.bats b/tests/e2e/commands.bats index c25e347..8f1804e 100644 --- a/tests/e2e/commands.bats +++ b/tests/e2e/commands.bats @@ -20,7 +20,6 @@ setup() { run env -u BIDIREKT_BROKER_URL -u BIDIREKT_API_KEY bidirekt list-participants --profile "e2e_$RUN" assert_success - assert_line "Broker: $BIDIREKT_BROKER_URL (profile: e2e_$RUN)" } @test "fails without BIDIREKT_BROKER_URL, BIDIREKT_API_KEY or profile, naming profile e2e" { @@ -42,14 +41,19 @@ the config file has the profile e2e_$RUN — pass --profile e2e_$RUN or set BIDI run env -u BIDIREKT_BROKER_URL -u BIDIREKT_API_KEY BIDIREKT_CONFIG_FILE="$config_file" bidirekt list-participants --profile no_key assert_failure 1 - assert_output "Broker: $BIDIREKT_BROKER_URL (profile: no_key) -not signed in to $BIDIREKT_BROKER_URL — run \"bidirekt login\" or set BIDIREKT_BROKER_URL and BIDIREKT_API_KEY" + assert_output "not signed in to $BIDIREKT_BROKER_URL — run \"bidirekt login\" or set BIDIREKT_BROKER_URL and BIDIREKT_API_KEY" } -@test "prints only the broker line on stderr for a localhost broker" { +@test "prints nothing on stderr for a localhost broker" { run --separate-stderr bidirekt list-participants assert_success - assert_equal "$stderr" "Broker: $BIDIREKT_BROKER_URL (from BIDIREKT_BROKER_URL)" + assert_equal "$stderr" "" +} + +@test "names the broker and where its URL came from when the broker is unreachable" { + run env BIDIREKT_BROKER_URL=http://127.0.0.1:9 bidirekt list-participants + assert_failure 1 + assert_output --partial "cannot reach the broker at http://127.0.0.1:9 (from BIDIREKT_BROKER_URL): " } @test "create participant todo_api" {