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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions internal/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
Expand Down
70 changes: 50 additions & 20 deletions internal/bootstrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -197,7 +197,6 @@ func TestBrokerComesFromTheEnvironmentPairOrTheActiveProfileAndIsAnnouncedOnStde
envProfile string
args []string
broker brokerStub
brokerLine string
authorization string
}{
{
Expand All @@ -206,35 +205,30 @@ 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",
},
{
name: "--profile wins over BIDIREKT_PROFILE",
envProfile: "default",
args: []string{"--profile", "globex"},
broker: globexBroker,
brokerLine: "Broker: " + globexBroker.url + " (profile: globex)\n",
authorization: "Bearer bdk_globex",
},
}
Expand All @@ -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])
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
})
}
}
Expand Down Expand Up @@ -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")
}
Expand Down
19 changes: 19 additions & 0 deletions internal/components/broker_unreachable_error.go
Original file line number Diff line number Diff line change
@@ -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
}
30 changes: 25 additions & 5 deletions internal/components/http_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
14 changes: 9 additions & 5 deletions tests/e2e/commands.bats
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand All @@ -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" {
Expand Down
Loading