diff --git a/cmd/src/auth.go b/cmd/src/auth.go index e2147787d6..eff5f4bbec 100644 --- a/cmd/src/auth.go +++ b/cmd/src/auth.go @@ -16,7 +16,7 @@ Usage: The commands are: - token prints the current authentication token + token prints the current authentication token or Authorization header Use "src auth [command] -h" for more information about a command. ` diff --git a/cmd/src/auth_token.go b/cmd/src/auth_token.go index 3b78499593..6112799f03 100644 --- a/cmd/src/auth_token.go +++ b/cmd/src/auth_token.go @@ -23,8 +23,11 @@ type oauthTokenRefresher interface { func init() { flagSet := flag.NewFlagSet("token", flag.ExitOnError) + header := flagSet.Bool("header", false, "print the token as an Authorization header") usageFunc := func() { - fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n") + fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src auth token':\n\n") + fmt.Fprintf(flag.CommandLine.Output(), "Print the current authentication token.\n") + fmt.Fprintf(flag.CommandLine.Output(), "Use --header to print a complete Authorization header instead.\n\n") flagSet.PrintDefaults() } @@ -38,6 +41,7 @@ func init() { return err } + token = formatAuthTokenOutput(token, cfg.AuthMode(), *header) fmt.Println(token) return nil } @@ -66,3 +70,15 @@ func resolveAuthToken(ctx context.Context, cfg *config) (string, error) { return token.AccessToken, nil } + +func formatAuthTokenOutput(token string, mode AuthMode, header bool) string { + if !header { + return token + } + + if mode == AuthModeAccessToken { + return fmt.Sprintf("Authorization: token %s", token) + } + + return fmt.Sprintf("Authorization: Bearer %s", token) +} diff --git a/cmd/src/auth_token_test.go b/cmd/src/auth_token_test.go index 8471be37f2..f1884263b3 100644 --- a/cmd/src/auth_token_test.go +++ b/cmd/src/auth_token_test.go @@ -103,6 +103,53 @@ func TestResolveAuthToken(t *testing.T) { }) } +func TestFormatAuthTokenOutput(t *testing.T) { + tests := []struct { + name string + token string + mode AuthMode + header bool + want string + }{ + { + name: "raw access token", + token: "access-token", + mode: AuthModeAccessToken, + header: false, + want: "access-token", + }, + { + name: "raw oauth token", + token: "oauth-token", + mode: AuthModeOAuth, + header: false, + want: "oauth-token", + }, + { + name: "authorization header for access token", + token: "access-token", + mode: AuthModeAccessToken, + header: true, + want: "Authorization: token access-token", + }, + { + name: "authorization header for oauth token", + token: "oauth-token", + mode: AuthModeOAuth, + header: true, + want: "Authorization: Bearer oauth-token", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := formatAuthTokenOutput(test.token, test.mode, test.header); got != test.want { + t.Fatalf("formatAuthTokenOutput(%q, %v, %v) = %q, want %q", test.token, test.mode, test.header, got, test.want) + } + }) + } +} + func stubAuthTokenDependencies(t *testing.T) func() { t.Helper()