|
| 1 | +// Package enablessh provides the brev enableSSH command for enabling SSH access |
| 2 | +// to a registered external node. |
| 3 | +package enablessh |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "os/user" |
| 11 | + "path/filepath" |
| 12 | + "runtime" |
| 13 | + "strings" |
| 14 | + |
| 15 | + nodev1connect "buf.build/gen/go/brevdev/devplane/connectrpc/go/devplaneapi/v1/devplaneapiv1connect" |
| 16 | + nodev1 "buf.build/gen/go/brevdev/devplane/protocolbuffers/go/devplaneapi/v1" |
| 17 | + "connectrpc.com/connect" |
| 18 | + |
| 19 | + "github.com/brevdev/brev-cli/pkg/cmd/register" |
| 20 | + "github.com/brevdev/brev-cli/pkg/config" |
| 21 | + "github.com/brevdev/brev-cli/pkg/entity" |
| 22 | + breverrors "github.com/brevdev/brev-cli/pkg/errors" |
| 23 | + "github.com/brevdev/brev-cli/pkg/terminal" |
| 24 | + |
| 25 | + "github.com/spf13/cobra" |
| 26 | +) |
| 27 | + |
| 28 | +// EnableSSHStore defines the store methods needed by the enableSSH command. |
| 29 | +type EnableSSHStore interface { |
| 30 | + GetCurrentUser() (*entity.User, error) |
| 31 | + GetBrevHomePath() (string, error) |
| 32 | + GetAccessToken() (string, error) |
| 33 | +} |
| 34 | + |
| 35 | +// enableSSHDeps bundles the side-effecting dependencies of runEnableSSH so they |
| 36 | +// can be replaced in tests. |
| 37 | +type enableSSHDeps struct { |
| 38 | + goos string |
| 39 | + newNodeClient func(provider register.TokenProvider, baseURL string) nodev1connect.ExternalNodeServiceClient |
| 40 | + registrationStore register.RegistrationStore |
| 41 | +} |
| 42 | + |
| 43 | +func prodEnableSSHDeps(brevHome string) enableSSHDeps { |
| 44 | + return enableSSHDeps{ |
| 45 | + goos: runtime.GOOS, |
| 46 | + newNodeClient: register.NewNodeServiceClient, |
| 47 | + registrationStore: register.NewFileRegistrationStore(brevHome), |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func NewCmdEnableSSH(t *terminal.Terminal, store EnableSSHStore) *cobra.Command { |
| 52 | + cmd := &cobra.Command{ |
| 53 | + Annotations: map[string]string{"configuration": ""}, |
| 54 | + Use: "enableSSH", |
| 55 | + DisableFlagsInUseLine: true, |
| 56 | + Short: "Enable SSH access to this registered device", |
| 57 | + Long: "Enable SSH access to this registered device for the current Brev user.", |
| 58 | + Example: " brev enableSSH", |
| 59 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 60 | + brevHome, err := store.GetBrevHomePath() |
| 61 | + if err != nil { |
| 62 | + return breverrors.WrapAndTrace(err) |
| 63 | + } |
| 64 | + return runEnableSSH(cmd.Context(), t, store, prodEnableSSHDeps(brevHome)) |
| 65 | + }, |
| 66 | + } |
| 67 | + |
| 68 | + return cmd |
| 69 | +} |
| 70 | + |
| 71 | +func runEnableSSH(ctx context.Context, t *terminal.Terminal, s EnableSSHStore, deps enableSSHDeps) error { |
| 72 | + if deps.goos != "linux" { |
| 73 | + return fmt.Errorf("brev enableSSH is only supported on Linux") |
| 74 | + } |
| 75 | + |
| 76 | + registered, err := deps.registrationStore.Exists() |
| 77 | + if err != nil { |
| 78 | + return breverrors.WrapAndTrace(err) |
| 79 | + } |
| 80 | + if !registered { |
| 81 | + return fmt.Errorf("no registration found; this machine does not appear to be registered\nRun 'brev register' to register your device first") |
| 82 | + } |
| 83 | + |
| 84 | + reg, err := deps.registrationStore.Load() |
| 85 | + if err != nil { |
| 86 | + return fmt.Errorf("failed to read registration file: %w", err) |
| 87 | + } |
| 88 | + |
| 89 | + brevUser, err := s.GetCurrentUser() |
| 90 | + if err != nil { |
| 91 | + return breverrors.WrapAndTrace(err) |
| 92 | + } |
| 93 | + |
| 94 | + return EnableSSH(ctx, t, deps.newNodeClient, s, reg, brevUser) |
| 95 | +} |
| 96 | + |
| 97 | +// EnableSSH grants SSH access to the given node for the specified Brev user. |
| 98 | +// It is exported so that the register command can reuse it after registration. |
| 99 | +func EnableSSH( |
| 100 | + ctx context.Context, |
| 101 | + t *terminal.Terminal, |
| 102 | + newClient func(register.TokenProvider, string) nodev1connect.ExternalNodeServiceClient, |
| 103 | + tokenProvider register.TokenProvider, |
| 104 | + reg *register.DeviceRegistration, |
| 105 | + brevUser *entity.User, |
| 106 | +) error { |
| 107 | + u, err := user.Current() |
| 108 | + if err != nil { |
| 109 | + return fmt.Errorf("failed to determine current Linux user: %w", err) |
| 110 | + } |
| 111 | + linuxUser := u.Username |
| 112 | + |
| 113 | + checkSSHDaemon(t) |
| 114 | + |
| 115 | + t.Vprint("") |
| 116 | + t.Vprint(t.Green("Enabling SSH access on this device")) |
| 117 | + t.Vprint("") |
| 118 | + t.Vprintf(" Node: %s (%s)\n", reg.DisplayName, reg.ExternalNodeID) |
| 119 | + t.Vprintf(" Brev user: %s\n", brevUser.ID) |
| 120 | + t.Vprintf(" Linux user: %s\n", linuxUser) |
| 121 | + t.Vprint("") |
| 122 | + |
| 123 | + client := newClient(tokenProvider, config.GlobalConfig.GetBrevPublicAPIURL()) |
| 124 | + if _, err := client.GrantNodeSSHAccess(ctx, connect.NewRequest(&nodev1.GrantNodeSSHAccessRequest{ |
| 125 | + ExternalNodeId: reg.ExternalNodeID, |
| 126 | + UserId: brevUser.ID, |
| 127 | + LinuxUser: linuxUser, |
| 128 | + OrganizationId: reg.OrgID, |
| 129 | + })); err != nil { |
| 130 | + return fmt.Errorf("failed to enable SSH access: %w", err) |
| 131 | + } |
| 132 | + |
| 133 | + if brevUser.PublicKey != "" { |
| 134 | + if err := installAuthorizedKey(u, brevUser.PublicKey); err != nil { |
| 135 | + t.Vprintf(" %s\n", t.Yellow(fmt.Sprintf("Warning: failed to install SSH public key: %v", err))) |
| 136 | + } else { |
| 137 | + t.Vprint(" Brev public key added to authorized_keys.") |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + t.Vprint(t.Green(fmt.Sprintf("SSH access enabled. You can now SSH to this device via: brev shell %s", reg.DisplayName))) |
| 142 | + return nil |
| 143 | +} |
| 144 | + |
| 145 | +// installAuthorizedKey appends the given public key to the user's |
| 146 | +// ~/.ssh/authorized_keys if it isn't already present. |
| 147 | +func installAuthorizedKey(u *user.User, pubKey string) error { |
| 148 | + pubKey = strings.TrimSpace(pubKey) |
| 149 | + if pubKey == "" { |
| 150 | + return nil |
| 151 | + } |
| 152 | + |
| 153 | + sshDir := filepath.Join(u.HomeDir, ".ssh") |
| 154 | + if err := os.MkdirAll(sshDir, 0o700); err != nil { |
| 155 | + return fmt.Errorf("creating .ssh directory: %w", err) |
| 156 | + } |
| 157 | + |
| 158 | + authKeysPath := filepath.Join(sshDir, "authorized_keys") |
| 159 | + |
| 160 | + existing, err := os.ReadFile(authKeysPath) // #nosec G304 |
| 161 | + if err != nil && !os.IsNotExist(err) { |
| 162 | + return fmt.Errorf("reading authorized_keys: %w", err) |
| 163 | + } |
| 164 | + |
| 165 | + if strings.Contains(string(existing), pubKey) { |
| 166 | + return nil // already present |
| 167 | + } |
| 168 | + |
| 169 | + // Ensure existing content ends with a newline before appending. |
| 170 | + content := string(existing) |
| 171 | + if len(content) > 0 && !strings.HasSuffix(content, "\n") { |
| 172 | + content += "\n" |
| 173 | + } |
| 174 | + content += pubKey + "\n" |
| 175 | + |
| 176 | + if err := os.WriteFile(authKeysPath, []byte(content), 0o600); err != nil { |
| 177 | + return fmt.Errorf("writing authorized_keys: %w", err) |
| 178 | + } |
| 179 | + |
| 180 | + return nil |
| 181 | +} |
| 182 | + |
| 183 | +// checkSSHDaemon prints a warning if neither "ssh" nor "sshd" systemd services |
| 184 | +// appear to be active. It never returns an error — it is best-effort. |
| 185 | +func checkSSHDaemon(t *terminal.Terminal) { |
| 186 | + for _, svc := range []string{"ssh", "sshd"} { |
| 187 | + out, err := exec.Command("systemctl", "is-active", svc).Output() //nolint:gosec // fixed service names |
| 188 | + if err == nil && len(out) > 0 && string(out[:len(out)-1]) == "active" { |
| 189 | + return |
| 190 | + } |
| 191 | + } |
| 192 | + t.Vprintf(" %s\n", t.Yellow("Warning: SSH daemon does not appear to be running. SSH access may not work until sshd is started.")) |
| 193 | +} |
0 commit comments