Skip to content
Draft
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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ odo login

Uses OAuth device flow — a browser window opens for you to authorize the CLI. Your access token is stored in the OS keychain (macOS Keychain, Linux Secret Service). On headless systems without a keychain, a plain token file is stored at `~/.odo/token` with `0600` permissions.

Protection changes require an explicit opt-in: run `odo login --protection` (or `odo auth login --protection`) and explicitly approve `vms:protection` in the browser. Normal login does not request it, existing sessions do not gain it automatically, and commands never automatically log in again.

```bash
odo instances protect <hostname-or-id>
odo instances unprotect <hostname-or-id> # Type UNPROTECT <canonical-instance-id>
odo instances unprotect <hostname-or-id> --yes # Explicit automation confirmation
```

Protection state is visible in list/status, including JSON (`protection_enabled`). Protected instances cannot be renamed or reinstalled; reinstall `--yes` never bypasses protection. All power operations remain available. Backend protection and scope checks are authoritative.

### Basic Usage

```bash
Expand Down
10 changes: 9 additions & 1 deletion cmd/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Example:
}

func init() {
loginCmd.Flags().Bool("protection", false, "Request vms:protection scope (requires explicit browser approval)")
AuthCmd.AddCommand(loginCmd)
}

Expand Down Expand Up @@ -114,7 +115,14 @@ func runLogin(cmd *cobra.Command, args []string) {
fmt.Println()

// Initiate device flow (with device ID)
deviceCode, err := oauthClient.InitiateDeviceFlow(deviceName, deviceID)
var scopes []string
if protection, _ := cmd.Flags().GetBool("protection"); protection {
// Explicit scopes replace (rather than extend) device-flow defaults.
// Retain legacy CLI permissions when opting into protection changes.
scopes = []string{"vms:read", "vms:console", "vms:power", "account:read", "vms:protection"}
fmt.Println("Requesting vms:protection. Review and explicitly approve this scope in your browser.")
}
deviceCode, err := oauthClient.InitiateDeviceFlow(deviceName, deviceID, scopes...)
if err != nil {
fmt.Println(errorStyle.Render("Error: ") + "Failed to start authentication: " + err.Error())
os.Exit(1)
Expand Down
3 changes: 3 additions & 0 deletions cmd/instances/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ func runTUIAction(client *api.Client, tm ui.TableModel) {
fmt.Println("✓ Force restart command sent")

case "rename":
if instance.ProtectionEnabled {
exitWithError("Instance %s is protected; explicitly unprotect it before renaming", instance.InstanceID)
}
newHostname := tm.RenameTarget
if err := deploy.Validate(newHostname); err != nil {
exitWithError("Invalid hostname %q: %v", newHostname, err)
Expand Down
80 changes: 80 additions & 0 deletions cmd/instances/protection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package instances

import (
"bufio"
"fmt"
"io"
"strings"

"github.com/hostodo/odo-cli/v2/pkg/api"
"github.com/hostodo/odo-cli/v2/pkg/auth"
"github.com/hostodo/odo-cli/v2/pkg/config"
"github.com/hostodo/odo-cli/v2/pkg/resolver"
"github.com/spf13/cobra"
)

func init() {
for _, enabled := range []bool{true, false} {
name := "protect"
if !enabled {
name = "unprotect"
}
command := &cobra.Command{
Use: name + " <hostname-or-id>",
Short: name + " a VPS instance (requires vms:protection)",
Args: cobra.ExactArgs(1),
ValidArgsFunction: resolver.CompleteHostname,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if !auth.IsAuthenticated() {
return fmt.Errorf("not authenticated; run 'odo login --protection' and approve vms:protection")
}
client, err := api.NewClient(cfg)
if err != nil {
return err
}
result, err := resolver.ResolveInstance(client, args[0])
if err != nil {
return err
}
confirmation := ""
if !enabled {
yes, _ := cmd.Flags().GetBool("yes")
confirmation, err = confirmUnprotect(cmd.InOrStdin(), cmd.OutOrStdout(), result.Instance.InstanceID, yes)
if err != nil {
return err
}
}
instance, err := client.SetInstanceProtection(result.Instance.InstanceID, enabled, confirmation)
if err != nil {
return err
}
resolver.InvalidateCache()
fmt.Fprintf(cmd.OutOrStdout(), "%s (%s): protection_enabled=%t\n", instance.Hostname, instance.InstanceID, instance.ProtectionEnabled)
return nil
},
}
if !enabled {
command.Flags().BoolP("yes", "y", false, "Explicitly confirm unprotect for automation (never bypasses reinstall protection)")
}
InstancesCmd.AddCommand(command)
}
}

func confirmUnprotect(in io.Reader, out io.Writer, instanceID string, yes bool) (string, error) {
phrase := "UNPROTECT " + instanceID
if !yes {
fmt.Fprintf(out, "Disabling protection permits destructive changes. Type %s to confirm: ", phrase)
line, err := bufio.NewReader(in).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
if strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r") != phrase {
return "", fmt.Errorf("unprotect cancelled: confirmation must exactly match %q", phrase)
}
}
return phrase, nil
}
31 changes: 31 additions & 0 deletions cmd/instances/protection_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package instances

import (
"io"
"strings"
"testing"
)

func TestUnprotectConfirmation(t *testing.T) {
for _, tc := range []struct {
input string
yes, ok bool
}{
{"UNPROTECT ins::abc\n", false, true},
{"UNPROTECT ins::abc\r\n", false, true},
{"UNPROTECT hostname\n", false, false},
{" UNPROTECT ins::abc\n", false, false},
{"unprotect ins::abc\n", false, false},
{"yes\n", false, false},
{"", false, false},
{"", true, true},
} {
phrase, err := confirmUnprotect(strings.NewReader(tc.input), io.Discard, "ins::abc", tc.yes)
if (err == nil) != tc.ok {
t.Errorf("%q yes=%t: %v", tc.input, tc.yes, err)
}
if tc.ok && phrase != "UNPROTECT ins::abc" {
t.Errorf("wrong phrase %q", phrase)
}
}
}
4 changes: 4 additions & 0 deletions cmd/instances/reinstall.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ func runReinstall(cmd *cobra.Command, args []string) error {
}
instance := result.Instance

if instance.ProtectionEnabled {
return fmt.Errorf("instance %s is protected; explicitly unprotect it before reinstalling (--yes does not bypass protection)", instance.InstanceID)
}

if instance.IsSuspended {
return fmt.Errorf("instance %s is suspended and cannot be reinstalled", instance.Hostname)
}
Expand Down
3 changes: 3 additions & 0 deletions cmd/instances/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ func runRename(cmd *cobra.Command, args []string) {
}

instance := result.Instance
if instance.ProtectionEnabled && newHostname != instance.Hostname {
exitWithError("Instance %s is protected; explicitly unprotect it before renaming", instance.InstanceID)
}

fmt.Printf("Renaming instance %s (%s) to %s...\n", instance.Hostname, instance.MainIP, newHostname)

Expand Down
145 changes: 145 additions & 0 deletions cmd/protection_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package cmd

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)

func TestProtectionCommandProcess(t *testing.T) {
if os.Getenv("ODO_TEST_COMMAND") == "" {
return
}
var args []string
if err := json.Unmarshal([]byte(os.Getenv("ODO_TEST_COMMAND")), &args); err != nil {
panic(err)
}
rootCmd.SetArgs(args)
if err := Execute(); err != nil {
os.Exit(1)
}
os.Exit(0)
}

func TestProtectionCommands(t *testing.T) {
for _, tc := range []struct {
name string
args []string
protected, fail, patch bool
input string
}{
{"protect hostname", []string{"instances", "protect", "mybox"}, false, false, true, ""},
{"unprotect id yes", []string{"instances", "unprotect", "ins::abc", "--yes"}, true, false, true, ""},
{"unprotect hostname phrase", []string{"instances", "unprotect", "mybox"}, true, false, true, "UNPROTECT ins::abc\n"},
{"unprotect incorrect", []string{"instances", "unprotect", "mybox"}, true, true, false, "yes\n"},
{"rename protected", []string{"instances", "rename", "mybox", "newname"}, true, true, false, ""},
{"reinstall yes protected", []string{"instances", "reinstall", "mybox", "--yes"}, true, true, false, ""},
} {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
if err := os.MkdirAll(filepath.Join(home, ".odo"), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(home, ".odo", "token"), []byte("test-token"), 0600); err != nil {
t.Fatal(err)
}
calls := 0
patches := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Content-Type", "application/json")
instance := map[string]interface{}{"instance_id": "ins::abc", "hostname": "mybox", "protection_enabled": tc.protected}
if r.Method == "GET" && r.URL.Path == "/client/instances/" {
json.NewEncoder(w).Encode(map[string]interface{}{"results": []interface{}{instance}})
return
}
if r.Method == "PATCH" && r.URL.Path == "/client/instances/ins::abc/protection/" {
patches++
var body map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
if body["enabled"] == false && body["confirmation"] != "UNPROTECT ins::abc" {
t.Error("wrong confirmation")
}
instance["protection_enabled"] = body["enabled"]
json.NewEncoder(w).Encode(map[string]interface{}{"instance": instance})
return
}
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
w.WriteHeader(500)
}))
defer srv.Close()
args := append([]string{"--api-url", srv.URL, "--force-http"}, tc.args...)
encoded, _ := json.Marshal(args)
cmd := exec.Command(os.Args[0], "-test.run=^TestProtectionCommandProcess$")
cmd.Env = append(os.Environ(), "HOME="+home, "ODO_TEST_COMMAND="+string(encoded), "DBUS_SESSION_BUS_ADDRESS=unix:path=/nonexistent")
cmd.Stdin = strings.NewReader(tc.input)
output, err := cmd.CombinedOutput()
if (err != nil) != tc.fail {
t.Fatalf("exit=%v output=%s", err, output)
}
wantCalls := 1
if tc.patch {
wantCalls++
}
if calls != wantCalls || (patches == 1) != tc.patch {
t.Fatalf("calls=%d patches=%d output=%s", calls, patches, output)
}
})
}
}

func TestLoginProtectionFlagOnBothPaths(t *testing.T) {
for _, path := range [][]string{{"login"}, {"auth", "login"}} {
command, _, err := rootCmd.Find(path)
if err != nil || command.Flags().Lookup("protection") == nil {
t.Fatalf("missing --protection on %v", path)
}
}
}

func TestLoginForwardsScopesOnlyWithOptIn(t *testing.T) {
for _, args := range [][]string{{"login"}, {"login", "--protection"}, {"auth", "login", "--protection"}} {
t.Run(strings.Join(args, " "), func(t *testing.T) {
var body map[string]json.RawMessage
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/oauth/device/authorize" {
t.Errorf("unexpected path %s", r.URL.Path)
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
// Stop before polling/browser launch: this test covers the authorization request.
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"detail":"test stops after authorize request"}`))
}))
defer srv.Close()
encoded, _ := json.Marshal(append([]string{"--api-url", srv.URL, "--force-http"}, args...))
cmd := exec.Command(os.Args[0], "-test.run=^TestProtectionCommandProcess$")
cmd.Env = append(os.Environ(), "HOME="+t.TempDir(), "ODO_TEST_COMMAND="+string(encoded), "DBUS_SESSION_BUS_ADDRESS=unix:path=/nonexistent")
output, err := cmd.CombinedOutput()
if err == nil || body == nil {
t.Fatalf("expected test stop after request, err=%v output=%s", err, output)
}
if args[len(args)-1] != "--protection" {
if _, exists := body["scopes"]; exists {
t.Fatal("default login must omit scopes")
}
return
}
var scopes []string
if err := json.Unmarshal(body["scopes"], &scopes); err != nil {
t.Fatal(err)
}
if strings.Join(scopes, " ") != "vms:read vms:console vms:power account:read vms:protection" {
t.Fatalf("lost legacy or protection scopes: %v", scopes)
}
})
}
}
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ func init() {
rootCmd.AddCommand(completionCmd)

// Root-level auth aliases (visible)
if loginCmd, _, err := auth.AuthCmd.Find([]string{"login"}); err == nil {
loginAliasCmd.Flags().AddFlagSet(loginCmd.Flags())
}
rootCmd.AddCommand(loginAliasCmd)
rootCmd.AddCommand(logoutAliasCmd)
rootCmd.AddCommand(whoamiAliasCmd)
Expand Down
44 changes: 43 additions & 1 deletion pkg/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,14 @@ func parseResponse(resp *http.Response, v interface{}) error {
if resp.StatusCode >= 400 {
var errorResp ErrorResponse
if err := json.Unmarshal(body, &errorResp); err == nil {
return fmt.Errorf("API error (%d): %s", resp.StatusCode, errorResp.Detail)
errorResp.HTTPStatus = resp.StatusCode
if errorResp.Detail == "" {
errorResp.Detail = errorResp.Message
}
if errorResp.Detail == "" {
errorResp.Detail = string(body)
}
return &errorResp
}
return fmt.Errorf("API error (%d): %s", resp.StatusCode, string(body))
}
Expand All @@ -166,3 +173,38 @@ func parseResponse(resp *http.Response, v interface{}) error {

return nil
}

func (e *ErrorResponse) Error() string {
message := fmt.Sprintf("API error (%d): %s", e.HTTPStatus, e.Detail)
if e.Code != "" {
message += " [" + e.Code + "]"
}
if e.Code == "forbidden_scope" {
message += "; protection changes require explicit reauthorization: run 'odo login --protection' and approve vms:protection in your browser"
}
return message
}

// UnmarshalJSON accepts legacy numeric codes as well as structured string codes.
func (e *ErrorResponse) UnmarshalJSON(data []byte) error {
type alias ErrorResponse
var wire struct {
*alias
Code json.RawMessage `json:"code"`
}
wire.alias = (*alias)(e)
if err := json.Unmarshal(data, &wire); err != nil {
return err
}
if len(wire.Code) == 0 || string(wire.Code) == "null" {
return nil
}
if err := json.Unmarshal(wire.Code, &e.Code); err != nil {
var number json.Number
if err := json.Unmarshal(wire.Code, &number); err != nil {
return err
}
e.Code = number.String()
}
return nil
}
Loading
Loading