Skip to content

fix: ensure we are talking to coder on first user check #11130

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
merged 3 commits into from
Dec 11, 2023
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
35 changes: 35 additions & 0 deletions cli/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package cli_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"runtime"
"testing"

Expand Down Expand Up @@ -36,6 +38,39 @@ func TestLogin(t *testing.T) {
require.ErrorContains(t, err, errMsg)
})

t.Run("InitialUserNonCoderURLFail", func(t *testing.T) {
t.Parallel()

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not Found"))
}))
defer ts.Close()

badLoginURL := ts.URL
root, _ := clitest.New(t, "login", badLoginURL)
err := root.Run()
errMsg := fmt.Sprintf("Failed to check server %q for first user, is the URL correct and is coder accessible from your browser?", badLoginURL)
require.ErrorContains(t, err, errMsg)
})

t.Run("InitialUserNonCoderURLSuccess", func(t *testing.T) {
t.Parallel()

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Coder-Build-Version", "something")
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not Found"))
}))
defer ts.Close()

badLoginURL := ts.URL
root, _ := clitest.New(t, "login", badLoginURL)
err := root.Run()
// this means we passed the check for a valid coder server
require.ErrorContains(t, err, "the initial user cannot be created in non-interactive mode")
})

t.Run("InitialUserTTY", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
Expand Down
8 changes: 8 additions & 0 deletions codersdk/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,15 @@ func (c *Client) HasFirstUser(ctx context.Context) (bool, error) {
return false, err
}
defer res.Body.Close()

if res.StatusCode == http.StatusNotFound {
// ensure we are talking to coder and not
// some other service that returns 404
v := res.Header.Get("X-Coder-Build-Version")
if v == "" {
return false, xerrors.Errorf("missing build version header, not a coder instance")
}

return false, nil
}
if res.StatusCode != http.StatusOK {
Expand Down