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
35 changes: 33 additions & 2 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import (
"github.com/brevdev/brev-cli/pkg/cmd/workspacegroups"
"github.com/brevdev/brev-cli/pkg/cmd/writeconnectionevent"
"github.com/brevdev/brev-cli/pkg/config"
"github.com/brevdev/brev-cli/pkg/entity"
"github.com/brevdev/brev-cli/pkg/featureflag"
"github.com/brevdev/brev-cli/pkg/files"
"github.com/brevdev/brev-cli/pkg/remoteversion"
Expand Down Expand Up @@ -257,8 +258,20 @@ func NewBrevCommand() *cobra.Command { //nolint:funlen,gocognit,gocyclo // defin
cmds.SetUsageTemplate(usageTemplate)

// In-memory auth for external node commands — never touches credentials.json.
memAuthStore := store.NewMemoryAuthStore()
memAuthenticator := auth.StandardLogin("", "", nil)
// Pre-fill the cached email so the user sees a confirmation prompt instead of
// having to type it from scratch every time.
cachedEmail, _ := fsStore.GetCachedEmail()
memAuthenticator := auth.StandardLogin("", cachedEmail, nil)
if cachedEmail != "" {
if kas, ok := memAuthenticator.(auth.KasAuthenticator); ok {
kas.ShouldPromptEmail = true
memAuthenticator = kas
}
}
memAuthStore := &emailCachingAuthStore{
MemoryAuthStore: store.NewMemoryAuthStore(),
fileStore: fsStore,
}
memLoginAuth := auth.NewLoginAuth(memAuthStore, memAuthenticator)
memLoginAuth.WithShouldLogin(func() (bool, error) { return true, nil })

Expand Down Expand Up @@ -555,4 +568,22 @@ var (
_ store.Auth = auth.NoLoginAuth{}
_ auth.AuthStore = store.FileStore{}
_ auth.AuthStore = &store.MemoryAuthStore{}
_ auth.AuthStore = &emailCachingAuthStore{}
)

// emailCachingAuthStore wraps MemoryAuthStore and persists the login email
// to ~/.brev/cached-email after each successful authentication.
type emailCachingAuthStore struct {
*store.MemoryAuthStore
fileStore *store.FileStore
}

func (e *emailCachingAuthStore) SaveAuthTokens(tokens entity.AuthTokens) error {
if err := e.MemoryAuthStore.SaveAuthTokens(tokens); err != nil {
return breverrors.WrapAndTrace(err)
}
if email := auth.GetEmailFromToken(tokens.AccessToken); email != "" {
_ = e.fileStore.SaveCachedEmail(email)
}
return nil
}
75 changes: 75 additions & 0 deletions pkg/cmd/cmd_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package cmd

import (
"encoding/base64"
"encoding/json"
"testing"

"github.com/brevdev/brev-cli/pkg/entity"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// fakeJWT builds an unsigned JWT with the given claims (header.payload.signature).
func fakeJWT(t *testing.T, claims map[string]interface{}) string {
t.Helper()
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT"}`))
payload, err := json.Marshal(claims)
require.NoError(t, err)
return header + "." + base64.RawURLEncoding.EncodeToString(payload) + "."
}

func newTestFileStore(t *testing.T) *store.FileStore {
t.Helper()
fs := afero.NewMemMapFs()
err := fs.MkdirAll("/home/testuser/.brev", 0o755)
require.NoError(t, err)
return store.NewBasicStore().WithFileSystem(fs).WithUserHomeDirGetter(
func() (string, error) { return "/home/testuser", nil },
)
}

func TestEmailCachingAuthStore_SaveCachesEmail(t *testing.T) {
fs := newTestFileStore(t)
s := &emailCachingAuthStore{
MemoryAuthStore: store.NewMemoryAuthStore(),
fileStore: fs,
}

token := fakeJWT(t, map[string]interface{}{"email": "user@example.com"})
err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: token})
require.NoError(t, err)

cached, err := fs.GetCachedEmail()
require.NoError(t, err)
assert.Equal(t, "user@example.com", cached)
}

func TestEmailCachingAuthStore_NoEmailInToken(t *testing.T) {
fs := newTestFileStore(t)
s := &emailCachingAuthStore{
MemoryAuthStore: store.NewMemoryAuthStore(),
fileStore: fs,
}

token := fakeJWT(t, map[string]interface{}{"sub": "12345"})
err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: token})
require.NoError(t, err)

cached, err := fs.GetCachedEmail()
require.NoError(t, err)
assert.Equal(t, "", cached)
}

func TestEmailCachingAuthStore_EmptyAccessToken(t *testing.T) {
fs := newTestFileStore(t)
s := &emailCachingAuthStore{
MemoryAuthStore: store.NewMemoryAuthStore(),
fileStore: fs,
}

err := s.SaveAuthTokens(entity.AuthTokens{AccessToken: ""})
require.Error(t, err)
}
5 changes: 3 additions & 2 deletions pkg/cmd/deregister/deregister_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ type mockNetBirdManager struct {
err error
}

func (m *mockNetBirdManager) Install() error { return m.err }
func (m *mockNetBirdManager) Uninstall() error { m.called = true; return m.err }
func (m *mockNetBirdManager) Install() error { return m.err }
func (m *mockNetBirdManager) Uninstall() error { m.called = true; return m.err }
func (m *mockNetBirdManager) EnsureRunning() error { return m.err }

type mockNodeClientFactory struct {
serverURL string
Expand Down
5 changes: 3 additions & 2 deletions pkg/cmd/gpucreate/gpucreate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/brevdev/brev-cli/pkg/entity"
breverrors "github.com/brevdev/brev-cli/pkg/errors"
"github.com/brevdev/brev-cli/pkg/featureflag"
"github.com/brevdev/brev-cli/pkg/names"
"github.com/brevdev/brev-cli/pkg/store"
"github.com/brevdev/brev-cli/pkg/terminal"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -194,8 +195,8 @@ func NewCmdGPUCreate(t *terminal.Terminal, gpuCreateStore GPUCreateStore) *cobra
}
}

if name == "" {
return breverrors.NewValidationError("name is required (as argument or --name flag)")
if err := names.ValidateNodeName(name); err != nil {
return breverrors.WrapAndTrace(err)
}

if count < 1 {
Expand Down
6 changes: 6 additions & 0 deletions pkg/cmd/register/device_registration_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func (s *FileRegistrationStore) Load() (*DeviceRegistration, error) {
if err := files.ReadJSON(files.AppFs, path, &reg); err != nil {
return nil, breverrors.WrapAndTrace(err)
}
if reg.ExternalNodeID == "" || reg.OrgID == "" {
return nil, breverrors.New("malformed registration")
}
return &reg, nil
}

Expand Down Expand Up @@ -125,6 +128,9 @@ func sudoWriteFile(path string, data []byte) error {
if err := cmd.Run(); err != nil {
return fmt.Errorf("sudo tee %s failed: %w", path, err)
}
if err := exec.Command("sudo", "chmod", "644", path).Run(); err != nil { //nolint:gosec // fixed base path
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its best practice for us to not run sudo our selves but ask the user to run the command with sudo and elevate permisions. Can we make this change?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we run sudo commands in a few other places as well without asking the user (open and write-connection-event in particular).

I can do this in a follow up, and move the register and deregister commands to check if current user is sudo and prompt for password instead.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return fmt.Errorf("sudo chmod %s failed: %w", path, err)
}
return nil
}

Expand Down
42 changes: 42 additions & 0 deletions pkg/cmd/register/device_registration_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,48 @@ func Test_LoadRegistration_FailsWhenMissing(t *testing.T) {
}
}

func Test_LoadRegistration_RejectsMissingExternalNodeID(t *testing.T) {
cleanup := setupTestFs(t)
defer cleanup()

store := NewFileRegistrationStore()

reg := &DeviceRegistration{
ExternalNodeID: "",
DisplayName: "Test",
OrgID: "org_xyz",
}
if err := store.Save(reg); err != nil {
t.Fatalf("Save failed: %v", err)
}

_, err := store.Load()
if err == nil {
t.Fatal("expected error loading registration with empty ExternalNodeID")
}
}

func Test_LoadRegistration_RejectsMissingOrgID(t *testing.T) {
cleanup := setupTestFs(t)
defer cleanup()

store := NewFileRegistrationStore()

reg := &DeviceRegistration{
ExternalNodeID: "unode_abc",
DisplayName: "Test",
OrgID: "",
}
if err := store.Save(reg); err != nil {
t.Fatalf("Save failed: %v", err)
}

_, err := store.Load()
if err == nil {
t.Fatal("expected error loading registration with empty OrgID")
}
}

func Test_DeleteRegistration_FailsWhenMissing(t *testing.T) {
cleanup := setupTestFs(t)
defer cleanup()
Expand Down
30 changes: 30 additions & 0 deletions pkg/cmd/register/providers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package register

import (
"fmt"
"os/exec"
"runtime"
"strings"

nodev1connect "buf.build/gen/go/brevdev/devplane/connectrpc/go/devplaneapi/v1/devplaneapiv1connect"

Expand Down Expand Up @@ -38,6 +41,33 @@ type Netbird struct{}
func (Netbird) Install() error { return InstallNetbird() }
func (Netbird) Uninstall() error { return UninstallNetbird() }

// EnsureRunning checks if the netbird systemd service is active and attempts
// to start it if it is not. It also checks the netbird peer connection status
// and runs "netbird up" if the peer is disconnected.
func (Netbird) EnsureRunning() error {
out, err := exec.Command("systemctl", "is-active", "netbird").Output() //nolint:gosec // fixed service name
if err != nil || strings.TrimSpace(string(out)) != "active" {
if startErr := exec.Command("sudo", "systemctl", "start", "netbird").Run(); startErr != nil { //nolint:gosec // fixed service name
return fmt.Errorf("failed to start Brev tunnel service: %w", startErr)
}
}

statusOut, err := exec.Command("netbird", "status").Output() //nolint:gosec // fixed command
if err != nil {
// Service is running, just can't confirm peer status.
return nil
}

if netbirdManagementConnected(string(statusOut)) {
return nil
}

if upErr := exec.Command("sudo", "netbird", "up").Run(); upErr != nil { //nolint:gosec // fixed command
return fmt.Errorf("failed to reconnect Brev tunnel: %w", upErr)
}
return nil
}

// ShellSetupRunner runs setup scripts via shell.
type ShellSetupRunner struct{}

Expand Down
Loading
Loading