From 98a32103703d41ae93bc4a6a73a6a18cd5880a67 Mon Sep 17 00:00:00 2001 From: Hostodo Hermes Date: Sun, 25 Oct 2026 02:10:58 +0000 Subject: [PATCH] feat: odo instances protect/unprotect Adds the protection field to instance list/show, protect and unprotect commands with an explicit UNPROTECT confirmation, and blocks reinstall/rename client-side with the server error surfaced. --- README.md | 10 +++ cmd/auth/login.go | 10 ++- cmd/instances/list.go | 3 + cmd/instances/protection.go | 80 +++++++++++++++++ cmd/instances/protection_test.go | 31 +++++++ cmd/instances/reinstall.go | 4 + cmd/instances/rename.go | 3 + cmd/protection_test.go | 145 +++++++++++++++++++++++++++++++ cmd/root.go | 3 + pkg/api/client.go | 44 +++++++++- pkg/api/instances.go | 27 ++++-- pkg/api/models.go | 11 ++- pkg/api/protection_test.go | 118 +++++++++++++++++++++++++ pkg/auth/oauth.go | 7 +- pkg/auth/oauth_test.go | 42 +++++++++ pkg/ui/formatters.go | 7 +- pkg/ui/protection_test.go | 39 +++++++++ pkg/ui/table.go | 8 ++ 18 files changed, 576 insertions(+), 16 deletions(-) create mode 100644 cmd/instances/protection.go create mode 100644 cmd/instances/protection_test.go create mode 100644 cmd/protection_test.go create mode 100644 pkg/api/protection_test.go create mode 100644 pkg/auth/oauth_test.go create mode 100644 pkg/ui/protection_test.go diff --git a/README.md b/README.md index 43fe775..93a0304 100644 --- a/README.md +++ b/README.md @@ -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 +odo instances unprotect # Type UNPROTECT +odo instances unprotect --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 diff --git a/cmd/auth/login.go b/cmd/auth/login.go index 18f75c0..d18c8c8 100644 --- a/cmd/auth/login.go +++ b/cmd/auth/login.go @@ -40,6 +40,7 @@ Example: } func init() { + loginCmd.Flags().Bool("protection", false, "Request vms:protection scope (requires explicit browser approval)") AuthCmd.AddCommand(loginCmd) } @@ -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) diff --git a/cmd/instances/list.go b/cmd/instances/list.go index 74322e3..1b9a07a 100644 --- a/cmd/instances/list.go +++ b/cmd/instances/list.go @@ -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) diff --git a/cmd/instances/protection.go b/cmd/instances/protection.go new file mode 100644 index 0000000..8b26447 --- /dev/null +++ b/cmd/instances/protection.go @@ -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 + " ", + 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 +} diff --git a/cmd/instances/protection_test.go b/cmd/instances/protection_test.go new file mode 100644 index 0000000..849810e --- /dev/null +++ b/cmd/instances/protection_test.go @@ -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) + } + } +} diff --git a/cmd/instances/reinstall.go b/cmd/instances/reinstall.go index 8887385..d5bf3b7 100644 --- a/cmd/instances/reinstall.go +++ b/cmd/instances/reinstall.go @@ -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) } diff --git a/cmd/instances/rename.go b/cmd/instances/rename.go index 02864c7..a7237a4 100644 --- a/cmd/instances/rename.go +++ b/cmd/instances/rename.go @@ -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) diff --git a/cmd/protection_test.go b/cmd/protection_test.go new file mode 100644 index 0000000..a4e65f0 --- /dev/null +++ b/cmd/protection_test.go @@ -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) + } + }) + } +} diff --git a/cmd/root.go b/cmd/root.go index c8ea089..c251215 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -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) diff --git a/pkg/api/client.go b/pkg/api/client.go index d936d72..641aafc 100644 --- a/pkg/api/client.go +++ b/pkg/api/client.go @@ -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)) } @@ -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 +} diff --git a/pkg/api/instances.go b/pkg/api/instances.go index 5d213b8..005e86b 100644 --- a/pkg/api/instances.go +++ b/pkg/api/instances.go @@ -3,7 +3,6 @@ package api import ( "encoding/json" "fmt" - "io" "time" ) @@ -32,12 +31,9 @@ func (c *Client) GetInstance(instanceID string) (*Instance, error) { if err != nil { return nil, err } - defer resp.Body.Close() - - // Read body once, try both unmarshal strategies - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("failed to read response: %w", err) + var body json.RawMessage + if err := parseResponse(resp, &body); err != nil { + return nil, err } // Try wrapped format first: {"instance": {...}} @@ -73,6 +69,23 @@ func (c *Client) GetInstancePowerStatus(instanceID string) (string, error) { return wrappedResp.Instance.PowerStatus, nil } +// SetInstanceProtection changes protection only; it never retries or reauthorizes. +func (c *Client) SetInstanceProtection(instanceID string, enabled bool, confirmation string) (*Instance, error) { + body := struct { + Enabled bool `json:"enabled"` + Confirmation string `json:"confirmation,omitempty"` + }{enabled, confirmation} + resp, err := c.Patch(fmt.Sprintf("/client/instances/%s/protection/", instanceID), body) + if err != nil { + return nil, err + } + var result InstanceDetailResponse + if err := parseResponse(resp, &result); err != nil { + return nil, err + } + return &result.Instance, nil +} + // StartInstance starts a stopped instance func (c *Client) StartInstance(instanceID string) error { path := fmt.Sprintf("/client/instances/%s/start/", instanceID) diff --git a/pkg/api/models.go b/pkg/api/models.go index c1f2893..d2d5300 100644 --- a/pkg/api/models.go +++ b/pkg/api/models.go @@ -66,6 +66,7 @@ type Instance struct { MainIP string `json:"main_ip"` Status string `json:"status"` PowerStatus string `json:"power_status"` + ProtectionEnabled bool `json:"protection_enabled"` AutorenewalEnabled bool `json:"autorenewal_enabled"` AutoRenewalPaymentMethod string `json:"auto_renewal_payment_method"` IPs []string `json:"ips"` @@ -131,9 +132,13 @@ type CLISessionsResponse struct { // ErrorResponse represents an API error type ErrorResponse struct { - Detail string `json:"detail"` - Message string `json:"message"` - Code int `json:"code"` + Detail string `json:"detail"` + Message string `json:"message"` + Code string `json:"code"` + InstanceID string `json:"instance_id"` + Operation string `json:"operation"` + ProtectionEnabled *bool `json:"protection_enabled,omitempty"` + HTTPStatus int `json:"-"` } // PlanCategory represents a plan category associated with a region diff --git a/pkg/api/protection_test.go b/pkg/api/protection_test.go new file mode 100644 index 0000000..3d7e4b1 --- /dev/null +++ b/pkg/api/protection_test.go @@ -0,0 +1,118 @@ +package api + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestProtectionAndPowerRequests(t *testing.T) { + injectToken(t) + var calls []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls = append(calls, r.Method+" "+r.URL.Path) + if strings.HasSuffix(r.URL.Path, "/protection/") { + var body map[string]interface{} + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + enabled := body["enabled"] == true + if enabled && body["confirmation"] != nil { + t.Error("enable must omit confirmation") + } + if !enabled && body["confirmation"] != "UNPROTECT ins::abc" { + t.Error("missing canonical confirmation") + } + writeJSON(w, 200, InstanceDetailResponse{Instance: Instance{InstanceID: "ins::abc", ProtectionEnabled: enabled}}) + return + } + writeJSON(w, 200, map[string]string{}) + })) + defer srv.Close() + client := newTestClient(t, srv.URL) + for _, enabled := range []bool{true, false} { + confirmation := "" + if !enabled { + confirmation = "UNPROTECT ins::abc" + } + inst, err := client.SetInstanceProtection("ins::abc", enabled, confirmation) + if err != nil { + t.Fatal(err) + } + if inst.ProtectionEnabled != enabled { + t.Fatalf("wrong state: %+v", inst) + } + } + if err := client.StartInstance("ins::abc"); err != nil { + t.Fatal(err) + } + for _, force := range []bool{false, true} { + if err := client.StopInstance("ins::abc", force); err != nil { + t.Fatal(err) + } + if err := client.RebootInstance("ins::abc", force); err != nil { + t.Fatal(err) + } + } + if len(calls) != 7 || calls[0] != "PATCH /client/instances/ins::abc/protection/" { + t.Fatalf("unexpected calls: %v", calls) + } +} + +func TestStructuredAndLegacyErrors(t *testing.T) { + for _, tc := range []struct { + status int + body, code, detail string + }{ + {423, `{"code":"protected","detail":"Protected VM","instance_id":"ins::abc","operation":"rename","protection_enabled":true}`, "protected", "Protected VM"}, + {409, `{"code":"busy","detail":"Busy VM"}`, "busy", "Busy VM"}, + {403, `{"code":"forbidden_scope","detail":"Scope denied"}`, "forbidden_scope", "Scope denied"}, + {400, `{"detail":"Legacy detail"}`, "", "Legacy detail"}, + {400, `{"code":400,"detail":"Numeric code"}`, "400", "Numeric code"}, + {400, `{"message":"Old message"}`, "", "Old message"}, + } { + t.Run(tc.code+tc.detail, func(t *testing.T) { + resp := &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body))} + err := parseResponse(resp, nil) + var apiErr *ErrorResponse + if !errors.As(err, &apiErr) || apiErr.Code != tc.code || apiErr.Detail != tc.detail || apiErr.HTTPStatus != tc.status { + t.Fatalf("lost error data: %#v", err) + } + if tc.code == "protected" && (apiErr.InstanceID != "ins::abc" || apiErr.Operation != "rename" || apiErr.ProtectionEnabled == nil || !*apiErr.ProtectionEnabled) { + t.Fatalf("lost protection metadata: %+v", apiErr) + } + if tc.code == "forbidden_scope" && !strings.Contains(err.Error(), "odo login --protection") { + t.Fatal("missing reauthorization advice") + } + }) + } +} + +func TestProtectionFailuresNeverRetryOrLogin(t *testing.T) { + injectToken(t) + for _, status := range []int{403, 409, 423} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + calls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + writeJSON(w, status, map[string]interface{}{"code": "forbidden_scope", "detail": "Denied"}) + })) + defer srv.Close() + client := newTestClient(t, srv.URL) + if _, err := client.SetInstanceProtection("ins::abc", false, "UNPROTECT ins::abc"); err == nil { + t.Fatal("expected error") + } + if calls != 1 { + t.Fatalf("unexpected retries: %d", calls) + } + if _, err := client.GetInstance("ins::abc"); err == nil { + t.Fatal("GET must not decode errors as an empty VM") + } + }) + } +} diff --git a/pkg/auth/oauth.go b/pkg/auth/oauth.go index b006b50..b38265d 100644 --- a/pkg/auth/oauth.go +++ b/pkg/auth/oauth.go @@ -62,16 +62,19 @@ func NewDeviceFlowClient(baseURL string) *DeviceFlowClient { } // InitiateDeviceFlow starts the device authorization flow -func (c *DeviceFlowClient) InitiateDeviceFlow(deviceName, deviceID string) (*DeviceCodeResponse, error) { +func (c *DeviceFlowClient) InitiateDeviceFlow(deviceName, deviceID string, scopes ...string) (*DeviceCodeResponse, error) { url := c.BaseURL + "/v1/oauth/device/authorize" - body := map[string]string{} + body := map[string]interface{}{} if deviceName != "" { body["device_name"] = deviceName } if deviceID != "" { body["device_id"] = deviceID } + if len(scopes) > 0 { + body["scopes"] = scopes + } jsonBody, err := json.Marshal(body) if err != nil { diff --git a/pkg/auth/oauth_test.go b/pkg/auth/oauth_test.go new file mode 100644 index 0000000..851b617 --- /dev/null +++ b/pkg/auth/oauth_test.go @@ -0,0 +1,42 @@ +package auth + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +func TestDeviceFlowScopesAreExplicitOptIn(t *testing.T) { + for _, scopes := range [][]string{nil, {"vms:protection"}, {"vms:read", "vms:console", "vms:power", "account:read", "vms:protection"}} { + 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) + } + var body map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + var got []string + if raw, exists := body["scopes"]; exists { + if len(scopes) == 0 { + t.Error("default login must omit scopes") + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Error(err) + } + } + if !reflect.DeepEqual(got, scopes) { + t.Errorf("scopes=%v want %v", got, scopes) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"device_code":"test","user_code":"test"}`)) + })) + _, err := NewDeviceFlowClient(srv.URL).InitiateDeviceFlow("device", "id", scopes...) + srv.Close() + if err != nil { + t.Fatal(err) + } + } +} diff --git a/pkg/ui/formatters.go b/pkg/ui/formatters.go index 555a734..082866b 100644 --- a/pkg/ui/formatters.go +++ b/pkg/ui/formatters.go @@ -47,7 +47,7 @@ func FormatInstancesSimpleTable(instances []api.Instance) string { // Header header := fmt.Sprintf( - "%-*s %-*s %-*s %-*s %-*s %*s %*s %*s", + "%-*s %-*s %-*s %-*s %-*s %*s %*s %*s PROTECTION", idWidth, "ID", hostnameWidth, "HOSTNAME", ipWidth, "IP ADDRESS", @@ -63,7 +63,7 @@ func FormatInstancesSimpleTable(instances []api.Instance) string { // Rows for _, instance := range instances { row := fmt.Sprintf( - "%-*s %-*s %-*s %-*s %-*s %*d %*d %*d", + "%-*s %-*s %-*s %-*s %-*s %*d %*d %*d %t", idWidth, truncate(instance.InstanceID, idWidth), hostnameWidth, truncate(instance.Hostname, hostnameWidth), ipWidth, truncate(instance.MainIP, ipWidth), @@ -72,6 +72,7 @@ func FormatInstancesSimpleTable(instances []api.Instance) string { ramWidth, instance.RAM, cpuWidth, instance.VCPU, diskWidth, instance.Disk, + instance.ProtectionEnabled, ) sb.WriteString(row + "\n") } @@ -100,6 +101,7 @@ func FormatInstancesDetailedTable(instances []api.Instance) string { } sb.WriteString(fmt.Sprintf(" Status: %s\n", instance.Status)) sb.WriteString(fmt.Sprintf(" Power: %s\n", instance.PowerStatus)) + sb.WriteString(fmt.Sprintf(" Protection: %t\n", instance.ProtectionEnabled)) sb.WriteString(fmt.Sprintf(" Resources: %d MB RAM, %d CPU, %d GB Disk\n", instance.RAM, instance.VCPU, instance.Disk)) sb.WriteString(fmt.Sprintf(" Bandwidth: %.2f / %d GB\n", @@ -130,6 +132,7 @@ func FormatInstanceDetail(instance *api.Instance) string { sb.WriteString(fmt.Sprintf(" Hostname: %s\n", instance.Hostname)) sb.WriteString(fmt.Sprintf(" Status: %s\n", GetPowerStatusBadge(instance.Status))) sb.WriteString(fmt.Sprintf(" Power: %s\n", GetPowerStatusBadge(instance.PowerStatus))) + sb.WriteString(fmt.Sprintf(" Protection: %t\n", instance.ProtectionEnabled)) sb.WriteString("\n") // Network diff --git a/pkg/ui/protection_test.go b/pkg/ui/protection_test.go new file mode 100644 index 0000000..8a9bfa6 --- /dev/null +++ b/pkg/ui/protection_test.go @@ -0,0 +1,39 @@ +package ui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/hostodo/odo-cli/v2/pkg/api" +) + +func TestProtectionVisibility(t *testing.T) { + instances := []api.Instance{{InstanceID: "ins::abc", ProtectionEnabled: true}} + json, err := FormatInstancesJSON(instances) + if err != nil || !strings.Contains(json, `"protection_enabled": true`) { + t.Fatalf("missing JSON protection: %s %v", json, err) + } + for name, output := range map[string]string{ + "simple": FormatInstancesSimpleTable(instances), + "details": FormatInstancesDetailedTable(instances), + "status": FormatInstanceDetail(&instances[0]), + "tui": NewTableModel(instances, nil).View(), + } { + if !strings.Contains(strings.ToLower(output), "protect") || !strings.Contains(output, "true") { + t.Errorf("%s missing state: %s", name, output) + } + } +} + +func TestProtectedTUIBlocksOnlyRenameAndReinstall(t *testing.T) { + for key, action := range map[rune]string{'n': "", 'i': "", 's': "start", 'S': "stop", 'x': "force-stop", 'r': "restart", 'R': "force-restart"} { + m := NewTableModel([]api.Instance{{ProtectionEnabled: true}}, nil) + m.mode = DetailMode + updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{key}}) + got := updated.(TableModel) + if got.APIAction != action || got.mode == RenameMode { + t.Errorf("key %c: action=%s mode=%v", key, got.APIAction, got.mode) + } + } +} diff --git a/pkg/ui/table.go b/pkg/ui/table.go index 3d0db8d..193453c 100644 --- a/pkg/ui/table.go +++ b/pkg/ui/table.go @@ -55,6 +55,7 @@ func NewTableModel(instances []api.Instance, fetchPower PowerStatusFunc) TableMo {Title: "Hostname", Width: 25}, {Title: "IP Address", Width: 16}, {Title: "Status", Width: 14}, + {Title: "Protected", Width: 9}, {Title: "RAM", Width: 10}, {Title: "CPU", Width: 6}, {Title: "Disk", Width: 8}, @@ -67,6 +68,7 @@ func NewTableModel(instances []api.Instance, fetchPower PowerStatusFunc) TableMo truncate(instance.Hostname, 25), instance.MainIP, instance.Status, + fmt.Sprintf("%t", instance.ProtectionEnabled), fmt.Sprintf("%d MB", instance.RAM), fmt.Sprintf("%d", instance.VCPU), fmt.Sprintf("%d GB", instance.Disk), @@ -185,12 +187,18 @@ func (m TableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.quitting = true return m, tea.Quit case "n": + if m.instances[m.selectedInstance].ProtectionEnabled { + return m, nil + } m.mode = RenameMode m.renameInput.SetValue(m.instances[m.selectedInstance].Hostname) m.renameInput.Focus() m.renameInput.CursorEnd() return m, textinput.Blink case "i": + if m.instances[m.selectedInstance].ProtectionEnabled { + return m, nil + } m.APIAction = "reinstall" m.ActionInstance = &m.instances[m.selectedInstance] m.quitting = true