-
Notifications
You must be signed in to change notification settings - Fork 75
src login command to help users configure authentication w/access token #317
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "flag" | ||
| "fmt" | ||
| "io" | ||
| "io/ioutil" | ||
| "os" | ||
| "strings" | ||
| ) | ||
|
|
||
| func init() { | ||
| usage := `'src login' helps you authenticate 'src' to access a Sourcegraph instance with your user credentials. | ||
|
|
||
| Usage: | ||
|
|
||
| src login SOURCEGRAPH_URL | ||
|
|
||
| Examples: | ||
|
|
||
| Authenticate to a Sourcegraph instance at https://sourcegraph.example.com: | ||
|
|
||
| $ src login https://sourcegraph.example.com | ||
|
|
||
| Authenticate to Sourcegraph.com: | ||
|
|
||
| $ src login https://sourcegraph.com | ||
| ` | ||
|
|
||
| flagSet := flag.NewFlagSet("login", flag.ExitOnError) | ||
| usageFunc := func() { | ||
| fmt.Fprintln(flag.CommandLine.Output(), usage) | ||
| } | ||
|
|
||
| handler := func(args []string) error { | ||
| if err := flagSet.Parse(args); err != nil { | ||
| return err | ||
| } | ||
| if len(args) != 1 { | ||
| return &usageError{errors.New("expected exactly one argument: the Sourcegraph URL")} | ||
| } | ||
| endpointArg := args[0] | ||
| return loginCmd(context.Background(), cfg, endpointArg, os.Stdout) | ||
| } | ||
|
|
||
| commands = append(commands, &command{ | ||
| flagSet: flagSet, | ||
| handler: handler, | ||
| usageFunc: usageFunc, | ||
| }) | ||
| } | ||
|
|
||
| var exitCode1 = &exitCodeError{exitCode: 1} | ||
|
|
||
| func loginCmd(ctx context.Context, cfg *config, endpointArg string, out io.Writer) error { | ||
| endpointArg = cleanEndpoint(endpointArg) | ||
|
|
||
| printProblem := func(problem string) { | ||
| fmt.Fprintf(out, "❌ Problem: %s\n", problem) | ||
| } | ||
|
|
||
| createAccessTokenMessage := fmt.Sprintf("\n"+`🛠 To fix: Create an access token at %s/user/settings/tokens, then set the following environment variables: | ||
|
|
||
| SRC_ENDPOINT=%s | ||
| SRC_ACCESS_TOKEN=(the access token you just created) | ||
|
|
||
| To verify that it's working, run this command again. | ||
| `, endpointArg, endpointArg) | ||
|
|
||
| if cfg.ConfigFilePath != "" { | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT and SRC_ACCESS_TOKEN instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.ConfigFilePath) | ||
| } | ||
|
|
||
| noToken := cfg.AccessToken == "" | ||
| endpointConflict := endpointArg != cfg.Endpoint | ||
| if noToken || endpointConflict { | ||
| fmt.Fprintln(out) | ||
| switch { | ||
| case noToken: | ||
| printProblem("No access token is configured.") | ||
| case endpointConflict: | ||
| printProblem(fmt.Sprintf("The configured endpoint is %s, not %s.", cfg.Endpoint, endpointArg)) | ||
| } | ||
| fmt.Fprintln(out, createAccessTokenMessage) | ||
| return exitCode1 | ||
| } | ||
|
|
||
| // See if the user is already authenticated. | ||
| query := `query CurrentUser { currentUser { username } }` | ||
| var result struct { | ||
| CurrentUser *struct{ Username string } | ||
| } | ||
| client := cfg.apiClient(nil, ioutil.Discard) | ||
| if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { | ||
| if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { | ||
| printProblem("Invalid access token.") | ||
| } else { | ||
| printProblem(fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) | ||
| } | ||
| fmt.Fprintln(out, createAccessTokenMessage) | ||
| fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)") | ||
| return exitCode1 | ||
| } | ||
|
|
||
| if result.CurrentUser == nil { | ||
| // This should never happen; we verified there is an access token, so there should always be | ||
| // a user. | ||
| printProblem(fmt.Sprintf("Unable to determine user on %s.", endpointArg)) | ||
| return exitCode1 | ||
| } | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "✔️ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) | ||
| fmt.Fprintln(out) | ||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "fmt" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestLogin(t *testing.T) { | ||
| check := func(t *testing.T, cfg *config, endpointArg string) (output string, err error) { | ||
| t.Helper() | ||
|
|
||
| var out bytes.Buffer | ||
| err = loginCmd(context.Background(), cfg, endpointArg, &out) | ||
| return strings.TrimSpace(out.String()), err | ||
| } | ||
|
|
||
| t.Run("different endpoint in config vs. arg", func(t *testing.T) { | ||
| out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") | ||
| if err != exitCode1 { | ||
| t.Fatal(err) | ||
| } | ||
| wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://sourcegraph.example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." | ||
| if out != wantOut { | ||
| t.Errorf("got output %q, want %q", out, wantOut) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("no access token", func(t *testing.T) { | ||
| out, err := check(t, &config{Endpoint: "https://example.com"}, "https://sourcegraph.example.com") | ||
| if err != exitCode1 { | ||
| t.Fatal(err) | ||
| } | ||
| wantOut := "❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://sourcegraph.example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://sourcegraph.example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." | ||
| if out != wantOut { | ||
| t.Errorf("got output %q, want %q", out, wantOut) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("warning when using config file", func(t *testing.T) { | ||
| out, err := check(t, &config{Endpoint: "https://example.com", ConfigFilePath: "f"}, "https://example.com") | ||
| if err != exitCode1 { | ||
| t.Fatal(err) | ||
| } | ||
| wantOut := "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT and SRC_ACCESS_TOKEN instead, and then remove f. See https://github.com/sourcegraph/src-cli#readme for more information.\n\n❌ Problem: No access token is configured.\n\n🛠 To fix: Create an access token at https://example.com/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=https://example.com\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again." | ||
| if out != wantOut { | ||
| t.Errorf("got output %q, want %q", out, wantOut) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("invalid access token", func(t *testing.T) { | ||
| // Dummy HTTP server to return HTTP 401/403. | ||
| s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| http.Error(w, "", http.StatusUnauthorized) | ||
| })) | ||
| defer s.Close() | ||
|
|
||
| endpoint := s.URL | ||
| out, err := check(t, &config{Endpoint: endpoint, AccessToken: "x"}, endpoint) | ||
| if err != exitCode1 { | ||
| t.Fatal(err) | ||
| } | ||
| wantOut := "❌ Problem: Invalid access token.\n\n🛠 To fix: Create an access token at $ENDPOINT/user/settings/tokens, then set the following environment variables:\n\n SRC_ENDPOINT=$ENDPOINT\n SRC_ACCESS_TOKEN=(the access token you just created)\n\n To verify that it's working, run this command again.\n\n (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md.)" | ||
| wantOut = strings.Replace(wantOut, "$ENDPOINT", endpoint, -1) | ||
| if out != wantOut { | ||
| t.Errorf("got output %q, want %q", out, wantOut) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("valid", func(t *testing.T) { | ||
| // Dummy HTTP server to return JSON response with currentUser. | ||
| s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| fmt.Fprintln(w, `{"data":{"currentUser":{"username":"alice"}}}`) | ||
| })) | ||
| defer s.Close() | ||
|
|
||
| endpoint := s.URL | ||
| out, err := check(t, &config{Endpoint: endpoint, AccessToken: "x"}, endpoint) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| wantOut := "✔️ Authenticated as alice on $ENDPOINT" | ||
| wantOut = strings.Replace(wantOut, "$ENDPOINT", endpoint, -1) | ||
| if out != wantOut { | ||
| t.Errorf("got output %q, want %q", out, wantOut) | ||
| } | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This stuff ended up being unnecessary, will revert.