From 049a50868f299b3e7f3df6a462390fa522b4d84e Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 17:17:35 -0600 Subject: [PATCH 1/9] feat(cli): add devsy login against the platform gateway `devsy login ` prompts for email and password (no echo on a terminal), signs in with POST /v1/auth/login, picks the org (only org, --org, or a numbered prompt), creates a read/write API key named devsy-cli, and stores the key, key IDs, org and gateway URL under `gateway:` in config.yaml (mode 0600). The password and session token are never stored or printed, and the key is never printed. Failures before the key is saved leave the config untouched; a key that cannot be saved is revoked. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/login/login.go | 284 ++++++++++++++++ cmd/login/login_test.go | 516 ++++++++++++++++++++++++++++++ cmd/root.go | 2 + pkg/config/config.go | 23 ++ pkg/platformclient/client.go | 246 ++++++++++++++ pkg/platformclient/client_test.go | 109 +++++++ 6 files changed, 1180 insertions(+) create mode 100644 cmd/login/login.go create mode 100644 cmd/login/login_test.go create mode 100644 pkg/platformclient/client.go create mode 100644 pkg/platformclient/client_test.go diff --git a/cmd/login/login.go b/cmd/login/login.go new file mode 100644 index 000000000..262820d02 --- /dev/null +++ b/cmd/login/login.go @@ -0,0 +1,284 @@ +// Package login implements `devsy login`, which signs in to a platform gateway +// and stores an org-scoped API key in the devsy config. +package login + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + "strconv" + "strings" + "time" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/platformclient" + "github.com/spf13/cobra" + "golang.org/x/term" +) + +const ( + // KeyName names the API key that login creates, so users can tell it apart + // from other keys in the org. + KeyName = "devsy-cli" + + sessionCleanupTimeout = 5 * time.Second +) + +var keyScopes = []string{"read", "write"} + +// Cmd holds the state of one `devsy login` run. +type Cmd struct { + // Org selects the org by ID or name. Empty means: use the only org, or ask. + Org string + + In io.Reader + Out io.Writer + ErrOut io.Writer + + // HTTPClient is optional. Nil selects the platform client default. + HTTPClient *http.Client + + stdinIsTerminal bool + readSecret func() (string, error) + + reader *bufio.Reader +} + +func newCmd() *Cmd { + return &Cmd{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr} +} + +// NewLoginCmd creates the `devsy login` command. +func NewLoginCmd() *cobra.Command { + c := newCmd() + loginCmd := &cobra.Command{ + Use: "login GATEWAY_URL", + Short: "Log in to a Devsy platform gateway", + Long: "Log in to a Devsy platform gateway with your email and password.\n\n" + + "Login creates an API key named " + KeyName + " for one of your organizations " + + "and stores it in the devsy config file with mode 0600. " + + "Your password and session token are never stored.", + Example: ` devsy login https://gateway.example.com + devsy login https://gateway.example.com --org "Acme Labs"`, + Args: cobra.ExactArgs(1), + RunE: func(cobraCmd *cobra.Command, args []string) error { + c.In = cobraCmd.InOrStdin() + c.Out = cobraCmd.OutOrStdout() + c.ErrOut = cobraCmd.ErrOrStderr() + c.useTerminalInput() + return c.Run(cobraCmd.Context(), args[0]) + }, + } + loginCmd.Flags().StringVar(&c.Org, "org", "", "Organization ID or name to log in to") + return loginCmd +} + +// Run signs in to the gateway and stores the resulting API key. The config is +// written only after every gateway call has succeeded. +func (c *Cmd) Run(ctx context.Context, gatewayURL string) error { + baseURL, err := platformclient.NormalizeURL(gatewayURL) + if err != nil { + return err + } + c.reader = bufio.NewReader(c.In) + + email, password, err := c.promptCredentials() + if err != nil { + return err + } + + client := platformclient.New(baseURL, c.HTTPClient) + session, err := client.Login(ctx, email, password) + if err != nil { + return fmt.Errorf("logging in: %w", err) + } + defer logoutSession(client, session.Token) + + selected, err := c.selectOrg(ctx, client, session.Token) + if err != nil { + return err + } + + key, err := client.CreateAPIKey(ctx, session.Token, platformclient.CreateKeyRequest{ + OrgID: selected.ID, + Name: KeyName, + Scopes: keyScopes, + }) + if err != nil { + return fmt.Errorf("creating API key for org %q: %w", selected.Name, err) + } + + credentials := &config.GatewayCredentials{ + URL: baseURL, + OrgID: selected.ID, + OrgName: selected.Name, + KeyID: key.KeyID, + KeyRecordID: key.ID, + APIKey: key.Key, + } + if err := storeCredentials(credentials); err != nil { + revokeUnstoredKey(client, session.Token, credentials) + return fmt.Errorf("saving login to config: %w", err) + } + + _, _ = fmt.Fprintf(c.Out, "Logged in as %s (org: %s)\n", email, selected.Name) + return nil +} + +// useTerminalInput reads the password without echo when stdin is a terminal. +func (c *Cmd) useTerminalInput() { + file, ok := c.In.(*os.File) + if !ok { + return + } + fd := int(file.Fd()) //nolint:gosec // fd fits in int + if !term.IsTerminal(fd) { + return + } + c.stdinIsTerminal = true + c.readSecret = func() (string, error) { + secret, err := term.ReadPassword(fd) + return string(secret), err + } +} + +func storeCredentials(credentials *config.GatewayCredentials) error { + return config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway = credentials + return nil + }) +} + +// logoutSession ends the session login used to mint the key. It is best effort: +// the session expires on its own if the gateway cannot be reached. +func logoutSession(client *platformclient.Client, token string) { + ctx, cancel := context.WithTimeout(context.Background(), sessionCleanupTimeout) + defer cancel() + _ = client.Logout(ctx, token) +} + +// revokeUnstoredKey revokes a key that could not be saved, since nothing else +// holds its secret and it would otherwise stay active unused. +func revokeUnstoredKey( + client *platformclient.Client, + token string, + credentials *config.GatewayCredentials, +) { + ctx, cancel := context.WithTimeout(context.Background(), sessionCleanupTimeout) + defer cancel() + _ = client.RevokeAPIKey(ctx, token, credentials.OrgID, credentials.KeyRecordID) +} + +func (c *Cmd) promptCredentials() (email, password string, err error) { + email, err = c.promptLine("Email: ") + if err != nil { + return "", "", fmt.Errorf("reading email: %w", err) + } + if email == "" { + return "", "", errors.New("email is required") + } + password, err = c.promptPassword("Password: ") + if err != nil { + return "", "", fmt.Errorf("reading password: %w", err) + } + if password == "" { + return "", "", errors.New("password is required") + } + return email, password, nil +} + +func (c *Cmd) promptLine(label string) (string, error) { + _, _ = fmt.Fprint(c.ErrOut, label) + line, err := c.reader.ReadString('\n') + if err != nil && (!errors.Is(err, io.EOF) || line == "") { + return "", err + } + return strings.TrimSpace(line), nil +} + +func (c *Cmd) promptPassword(label string) (string, error) { + if !c.stdinIsTerminal || c.readSecret == nil { + _, _ = fmt.Fprint(c.ErrOut, label) + line, err := c.reader.ReadString('\n') + if err != nil && (!errors.Is(err, io.EOF) || line == "") { + return "", err + } + return strings.TrimRight(line, "\r\n"), nil + } + _, _ = fmt.Fprint(c.ErrOut, label) + secret, err := c.readSecret() + _, _ = fmt.Fprintln(c.ErrOut) + return secret, err +} + +func (c *Cmd) selectOrg( + ctx context.Context, + client *platformclient.Client, + token string, +) (platformclient.Org, error) { + orgs, err := client.ListOrgs(ctx, token) + if err != nil { + return platformclient.Org{}, fmt.Errorf("listing organizations: %w", err) + } + if len(orgs) == 0 { + return platformclient.Org{}, errors.New( + "your account belongs to no organizations; create or join one first", + ) + } + if c.Org != "" { + return matchOrg(orgs, c.Org) + } + if len(orgs) == 1 { + return orgs[0], nil + } + return c.promptOrg(orgs) +} + +func matchOrg(orgs []platformclient.Org, selector string) (platformclient.Org, error) { + for _, o := range orgs { + if o.ID == selector { + return o, nil + } + } + var matches []platformclient.Org + for _, o := range orgs { + if o.Name == selector { + matches = append(matches, o) + } + } + switch len(matches) { + case 0: + return platformclient.Org{}, fmt.Errorf( + "organization %q not found among your organizations", selector, + ) + case 1: + return matches[0], nil + default: + return platformclient.Org{}, fmt.Errorf( + "organization name %q matches %d organizations; use the organization ID", + selector, len(matches), + ) + } +} + +func (c *Cmd) promptOrg(orgs []platformclient.Org) (platformclient.Org, error) { + _, _ = fmt.Fprintln(c.ErrOut, "Select an organization:") + for i, o := range orgs { + _, _ = fmt.Fprintf(c.ErrOut, " %d) %s (%s)\n", i+1, o.Name, o.Role) + } + answer, err := c.promptLine(fmt.Sprintf("Organization [1-%d]: ", len(orgs))) + if err != nil { + return platformclient.Org{}, fmt.Errorf("reading organization choice: %w", err) + } + choice, err := strconv.Atoi(answer) + if err != nil || choice < 1 || choice > len(orgs) { + return platformclient.Org{}, fmt.Errorf( + "invalid organization choice %q, expected a number from 1 to %d", answer, len(orgs), + ) + } + return orgs[choice-1], nil +} diff --git a/cmd/login/login_test.go b/cmd/login/login_test.go new file mode 100644 index 000000000..b2a9a96f5 --- /dev/null +++ b/cmd/login/login_test.go @@ -0,0 +1,516 @@ +package login + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/stretchr/testify/suite" +) + +const ( + testEmail = "alice@example.test" + testPassword = "correct-horse-battery-staple" + testToken = "sess_0123456789abcdef0123456789abcdef" + testKeyID = "AbCdEfGh12345678" + testSecret = "S3cretS3cretS3cretS3cretS3cretS3cretS3cr" + testFullKey = "dvsy_" + testKeyID + "_" + testSecret + testKeyRecID = "7d9f4c1e-0000-4000-8000-000000000001" + + orgAcme = "Acme Labs" + orgGlobex = "Globex" + routeLogin = "POST /v1/auth/login" + orgOne = "org-1" + orgTwo = "org-2" + roleOwner = "owner" + roleAdmin = "admin" +) + +var keyPattern = regexp.MustCompile(`dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+`) + +type org struct { + ID, Name, Role string +} + +type recordedCall struct { + Method, Path, Auth string + Body map[string]any +} + +// fakeGateway implements the gateway routes the login flow uses. +type fakeGateway struct { + server *httptest.Server + + mu sync.Mutex + calls []recordedCall + + password string + orgs []org + createKeyCode int +} + +func newFakeGateway() *fakeGateway { + g := &fakeGateway{ + password: testPassword, + orgs: []org{{ID: orgOne, Name: orgAcme, Role: roleOwner}}, + createKeyCode: http.StatusCreated, + } + g.server = httptest.NewServer(http.HandlerFunc(g.handle)) + return g +} + +func (g *fakeGateway) handle(w http.ResponseWriter, r *http.Request) { + call := recordedCall{Method: r.Method, Path: r.URL.Path, Auth: r.Header.Get("Authorization")} + if r.Body != nil { + _ = json.NewDecoder(r.Body).Decode(&call.Body) + } + g.mu.Lock() + g.calls = append(g.calls, call) + g.mu.Unlock() + + switch call.Method + " " + call.Path { + case routeLogin: + g.login(w, call) + case "GET /v1/orgs": + g.listOrgs(w, call) + case "POST /v1/auth/logout": + w.WriteHeader(http.StatusNoContent) + default: + g.orgKeyRoute(w, call) + } +} + +func (g *fakeGateway) orgKeyRoute(w http.ResponseWriter, call recordedCall) { + switch { + case call.Method == http.MethodPost && strings.HasSuffix(call.Path, "/api-keys"): + g.createKey(w, call) + case call.Method == http.MethodDelete && strings.Contains(call.Path, "/api-keys/"): + w.WriteHeader(http.StatusNoContent) + default: + writeEnvelope(w, http.StatusNotFound, "not_found", "no such route") + } +} + +func (g *fakeGateway) login(w http.ResponseWriter, call recordedCall) { + if call.Body["email"] != testEmail || call.Body["password"] != g.password { + writeEnvelope( + w, http.StatusUnauthorized, "invalid_credentials", "invalid email or password", + ) + return + } + writeJSON(w, http.StatusOK, map[string]string{"token": testToken}) +} + +func (g *fakeGateway) listOrgs(w http.ResponseWriter, call recordedCall) { + if call.Auth != "Bearer "+testToken { + writeEnvelope(w, http.StatusUnauthorized, "unauthorized", "missing session") + return + } + out := make([]map[string]string, 0, len(g.orgs)) + for _, o := range g.orgs { + out = append(out, map[string]string{"id": o.ID, "name": o.Name, "role": o.Role}) + } + writeJSON(w, http.StatusOK, map[string]any{"orgs": out}) +} + +func (g *fakeGateway) createKey(w http.ResponseWriter, call recordedCall) { + if g.createKeyCode != http.StatusCreated { + writeEnvelope(w, g.createKeyCode, "forbidden", "owner or admin role required") + return + } + writeJSON(w, http.StatusCreated, map[string]any{ + "id": testKeyRecID, + "key_id": testKeyID, + "name": call.Body["name"], + "scopes": call.Body["scopes"], + "key": testFullKey, + }) +} + +func (g *fakeGateway) called(method, path string) []recordedCall { + g.mu.Lock() + defer g.mu.Unlock() + var out []recordedCall + for _, c := range g.calls { + if c.Method == method && c.Path == path { + out = append(out, c) + } + } + return out +} + +func (g *fakeGateway) sequence() []string { + g.mu.Lock() + defer g.mu.Unlock() + out := make([]string, 0, len(g.calls)) + for _, c := range g.calls { + out = append(out, c.Method+" "+c.Path) + } + return out +} + +func writeJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} + +func writeEnvelope(w http.ResponseWriter, status int, code, message string) { + body := map[string]string{"code": code, "message": message} + writeJSON(w, status, map[string]any{"error": body}) +} + +type LoginSuite struct { + suite.Suite + + gateway *fakeGateway + home string + out *bytes.Buffer + errOut *bytes.Buffer + h helpers +} + +func TestLoginSuite(t *testing.T) { + suite.Run(t, new(LoginSuite)) +} + +func (s *LoginSuite) SetupTest() { + s.h = helpers{s: s} + s.home = s.T().TempDir() + s.T().Setenv(config.EnvHome, s.home) + s.T().Setenv(config.EnvConfig, "") + config.ResetPathManager() + s.T().Cleanup(config.ResetPathManager) + + s.gateway = newFakeGateway() + s.T().Cleanup(s.gateway.server.Close) + s.out = &bytes.Buffer{} + s.errOut = &bytes.Buffer{} +} + +// helpers are kept off LoginSuite so the suite's exported test methods stay +// ahead of every unexported method. +type helpers struct{ s *LoginSuite } + +func (h helpers) newCmd(in string) *Cmd { + c := newCmd() + c.In = strings.NewReader(in) + c.Out = h.s.out + c.ErrOut = h.s.errOut + return c +} + +func (h helpers) run(c *Cmd) error { + return c.Run(context.Background(), h.s.gateway.server.URL) +} + +func (h helpers) credentials() input { + return input{email: testEmail, password: testPassword} +} + +func (h helpers) configPath() string { + path, err := config.GetConfigPath() + h.s.Require().NoError(err) + return path +} + +func (h helpers) writeLooseConfig(content []byte) { + //nolint:gosec // loose mode is the precondition under test + err := os.WriteFile(h.configPath(), content, 0o644) + h.s.Require().NoError(err) +} + +func (h helpers) combinedOutput() string { + return h.s.out.String() + h.s.errOut.String() +} + +type input struct{ email, password string } + +func (i input) String() string { return i.email + "\n" + i.password + "\n" } + +func (s *LoginSuite) TestSuccessStoresKeyAndPrintsEmailAndOrg() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + stdout := s.out.String() + s.Contains(stdout, testEmail) + s.Contains(stdout, orgAcme) + + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Require().NotNil(cfg.Gateway) + s.Equal(s.gateway.server.URL, cfg.Gateway.URL) + s.Equal(orgOne, cfg.Gateway.OrgID) + s.Equal(orgAcme, cfg.Gateway.OrgName) + s.Equal(testKeyID, cfg.Gateway.KeyID) + s.Equal(testKeyRecID, cfg.Gateway.KeyRecordID) + s.Equal(testFullKey, cfg.Gateway.APIKey) +} + +func (s *LoginSuite) TestCallsGatewayInOrderWithScopesAndSessionToken() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + s.Equal([]string{ + routeLogin, + "GET /v1/orgs", + "POST /v1/orgs/org-1/api-keys", + "POST /v1/auth/logout", + }, s.gateway.sequence()) + + create := s.gateway.called("POST", "/v1/orgs/org-1/api-keys") + s.Require().Len(create, 1) + s.Equal("Bearer "+testToken, create[0].Auth) + s.Equal("devsy-cli", create[0].Body["name"]) + s.Equal([]any{"read", "write"}, create[0].Body["scopes"]) +} + +func (s *LoginSuite) TestOutputNeverContainsKeyPasswordOrToken() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + all := s.h.combinedOutput() + s.NotRegexp(keyPattern, all) + s.NotContains(all, testSecret) + s.NotContains(all, testPassword) + s.NotContains(all, testToken) +} + +func (s *LoginSuite) TestConfigFileModeIs0600() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + info, err := os.Stat(s.h.configPath()) + s.Require().NoError(err) + s.Equal(os.FileMode(0o600), info.Mode().Perm()) +} + +func (s *LoginSuite) TestExistingLooseConfigModeIsTightenedTo0600() { + s.h.writeLooseConfig([]byte("defaultContext: default\n")) + + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + info, err := os.Stat(s.h.configPath()) + s.Require().NoError(err) + s.Equal(os.FileMode(0o600), info.Mode().Perm()) + raw, err := os.ReadFile(s.h.configPath()) + s.Require().NoError(err) + s.Contains(string(raw), "defaultContext: default") +} + +func (s *LoginSuite) TestNothingUnderConfigDirHoldsPasswordOrSessionToken() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + err := filepath.WalkDir(s.home, func(path string, d os.DirEntry, walkErr error) error { + s.Require().NoError(walkErr) + if d.IsDir() { + return nil + } + raw, readErr := readTestFile(path) + if readErr != nil { + return nil // lock files may be unreadable transient entries + } + s.NotContains(string(raw), testPassword, path) + s.NotContains(string(raw), testToken, path) + return nil + }) + s.Require().NoError(err) +} + +func (s *LoginSuite) TestWrongPasswordFailsAndLeavesConfigUntouched() { + existing := []byte("defaultContext: default\n") + s.h.writeLooseConfig(existing) + before, err := os.Stat(s.h.configPath()) + s.Require().NoError(err) + + err = s.h.run(s.h.newCmd(input{testEmail, "wrong-password-123"}.String())) + + s.Require().Error(err) + s.Contains(err.Error(), "invalid email or password") + after, readErr := os.ReadFile(s.h.configPath()) + s.Require().NoError(readErr) + s.Equal(existing, after) + afterInfo, statErr := os.Stat(s.h.configPath()) + s.Require().NoError(statErr) + s.Equal(before.Mode(), afterInfo.Mode()) + s.Equal(before.ModTime(), afterInfo.ModTime()) +} + +func (s *LoginSuite) TestWrongPasswordCreatesNoConfigAndNoAPIKey() { + err := s.h.run(s.h.newCmd(input{testEmail, "wrong-password-123"}.String())) + + s.Require().Error(err) + _, statErr := os.Stat(s.h.configPath()) + s.True(errors.Is(statErr, os.ErrNotExist), "config file must not be created") + s.Equal([]string{routeLogin}, s.gateway.sequence()) + s.NotContains(s.h.combinedOutput(), "wrong-password-123") +} + +func (s *LoginSuite) TestSingleOrgIsUsedWithoutPrompting() { + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String()))) + + s.NotContains(s.errOut.String(), "Select") +} + +func (s *LoginSuite) TestMultipleOrgsPromptsForChoice() { + s.gateway.orgs = []org{ + {ID: orgOne, Name: orgAcme, Role: roleOwner}, + {ID: orgTwo, Name: orgGlobex, Role: roleAdmin}, + } + + s.Require().NoError(s.h.run(s.h.newCmd(s.h.credentials().String() + "2\n"))) + + s.Contains(s.errOut.String(), orgAcme) + s.Contains(s.errOut.String(), orgGlobex) + s.Len(s.gateway.called("POST", "/v1/orgs/org-2/api-keys"), 1) + s.Empty(s.gateway.called("POST", "/v1/orgs/org-1/api-keys")) + s.Contains(s.out.String(), orgGlobex) + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Equal(orgTwo, cfg.Gateway.OrgID) + s.Equal(orgGlobex, cfg.Gateway.OrgName) +} + +func (s *LoginSuite) TestInvalidOrgChoiceFailsWithoutKeyOrConfig() { + s.gateway.orgs = []org{ + {ID: orgOne, Name: orgAcme, Role: roleOwner}, + {ID: orgTwo, Name: orgGlobex, Role: roleAdmin}, + } + + err := s.h.run(s.h.newCmd(s.h.credentials().String() + "9\n")) + + s.Require().Error(err) + s.Empty(s.gateway.called("POST", "/v1/orgs/org-1/api-keys")) + s.Empty(s.gateway.called("POST", "/v1/orgs/org-2/api-keys")) + _, statErr := os.Stat(s.h.configPath()) + s.True(errors.Is(statErr, os.ErrNotExist)) +} + +func (s *LoginSuite) TestOrgFlagSelectsByNameOrID() { + s.gateway.orgs = []org{ + {ID: orgOne, Name: orgAcme, Role: roleOwner}, + {ID: orgTwo, Name: orgGlobex, Role: roleAdmin}, + } + + for _, selector := range []string{orgGlobex, orgTwo} { + c := s.h.newCmd(s.h.credentials().String()) + c.Org = selector + s.Require().NoError(s.h.run(c), selector) + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Equal(orgTwo, cfg.Gateway.OrgID, selector) + s.NotContains(s.errOut.String(), "Select") + } +} + +func (s *LoginSuite) TestUnknownOrgFlagFailsWithoutKeyOrConfig() { + c := s.h.newCmd(s.h.credentials().String()) + c.Org = "does-not-exist" + + err := s.h.run(c) + + s.Require().Error(err) + s.Contains(err.Error(), "does-not-exist") + s.Empty(s.gateway.called("POST", "/v1/orgs/org-1/api-keys")) + _, statErr := os.Stat(s.h.configPath()) + s.True(errors.Is(statErr, os.ErrNotExist)) +} + +func (s *LoginSuite) TestNoOrgsFails() { + s.gateway.orgs = nil + + err := s.h.run(s.h.newCmd(s.h.credentials().String())) + + s.Require().Error(err) + s.Contains(err.Error(), "no organizations") +} + +func (s *LoginSuite) TestKeyCreationRefusedLeavesConfigUntouched() { + s.gateway.createKeyCode = http.StatusForbidden + + err := s.h.run(s.h.newCmd(s.h.credentials().String())) + + s.Require().Error(err) + s.Contains(err.Error(), "owner or admin role required") + _, statErr := os.Stat(s.h.configPath()) + s.True(errors.Is(statErr, os.ErrNotExist)) + s.NotContains(s.h.combinedOutput(), testToken) +} + +func (s *LoginSuite) TestPasswordIsReadWithoutEchoFromTerminal() { + c := s.h.newCmd(testEmail + "\n") + c.stdinIsTerminal = true + secretReads := 0 + c.readSecret = func() (string, error) { + secretReads++ + return testPassword, nil + } + + s.Require().NoError(s.h.run(c)) + + s.Equal(1, secretReads) + s.NotContains(s.h.combinedOutput(), testPassword) + s.Contains(s.errOut.String(), "Password") +} + +func (s *LoginSuite) TestEmptyEmailOrPasswordIsRejectedBeforeAnyRequest() { + for _, in := range []string{"\n\n", testEmail + "\n\n"} { + err := s.h.run(s.h.newCmd(in)) + s.Require().Error(err, in) + } + s.Empty(s.gateway.sequence()) +} + +func (s *LoginSuite) TestFailedConfigWriteRevokesIssuedKey() { + blocker := filepath.Join(s.home, "blocker") + s.Require().NoError(os.WriteFile(blocker, nil, 0o600)) + s.T().Setenv(config.EnvConfig, filepath.Join(blocker, "config.yaml")) + + err := s.h.run(s.h.newCmd(s.h.credentials().String())) + + s.Require().Error(err) + s.Len(s.gateway.called("DELETE", "/v1/orgs/org-1/api-keys/"+testKeyRecID), 1) + s.NotRegexp(keyPattern, err.Error()) + s.NotRegexp(keyPattern, s.h.combinedOutput()) +} + +func (s *LoginSuite) TestGatewayURLTrailingSlashIsTrimmed() { + c := s.h.newCmd(s.h.credentials().String()) + + s.Require().NoError(c.Run(context.Background(), s.gateway.server.URL+"/")) + + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Equal(s.gateway.server.URL, cfg.Gateway.URL) +} + +func (s *LoginSuite) TestGatewayURLWithoutHTTPSchemeIsRejected() { + for _, raw := range []string{"", "localhost:8180", "ftp://example.test", "http://"} { + err := s.h.newCmd(s.h.credentials().String()).Run(context.Background(), raw) + s.Require().Error(err, raw) + } + s.Empty(s.gateway.sequence()) +} + +func (s *LoginSuite) TestUnreachableGatewayFailsWithoutConfig() { + dead := httptest.NewServer(http.NotFoundHandler()) + url := dead.URL + dead.Close() + + err := s.h.newCmd(s.h.credentials().String()).Run(context.Background(), url) + + s.Require().Error(err) + s.NotContains(err.Error(), testPassword) + _, statErr := os.Stat(s.h.configPath()) + s.True(errors.Is(statErr, os.ErrNotExist)) +} + +func readTestFile(path string) ([]byte, error) { + return os.ReadFile(path) //nolint:gosec // path comes from walking the test temp dir +} diff --git a/cmd/root.go b/cmd/root.go index 47ef5805b..5a0baed40 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -20,6 +20,7 @@ import ( "github.com/devsy-org/devsy/cmd/flags" "github.com/devsy-org/devsy/cmd/ide" cmdinternal "github.com/devsy-org/devsy/cmd/internal" + "github.com/devsy-org/devsy/cmd/login" "github.com/devsy-org/devsy/cmd/machine" "github.com/devsy-org/devsy/cmd/mcp" "github.com/devsy-org/devsy/cmd/pro" @@ -392,6 +393,7 @@ func registerSubcommands(rootCmd *cobra.Command, globalFlags *flags.GlobalFlags) envcmd.NewEnvCmd(globalFlags), feature.NewFeatureCmd(globalFlags), ide.NewIDECmd(globalFlags), + login.NewLoginCmd(), machine.NewMachineCmd(globalFlags), mcp.NewMCPCmd(globalFlags), provider.NewProviderCmd(globalFlags), diff --git a/pkg/config/config.go b/pkg/config/config.go index 2de0014eb..d3387915f 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -25,6 +25,9 @@ type Config struct { // Contexts holds the config contexts Contexts map[string]*ContextConfig `json:"contexts,omitempty"` + // Gateway holds the managed platform gateway login written by `devsy login`. + Gateway *GatewayCredentials `json:"gateway,omitempty"` + // Origin holds the path where this config was loaded from Origin string `json:"-"` @@ -32,6 +35,26 @@ type Config struct { OriginalContext string `json:"-"` } +// GatewayCredentials is the platform gateway login. It holds an org-scoped API +// key, never the account password or a session token. +type GatewayCredentials struct { + // URL is the gateway base URL without a trailing slash. + URL string `json:"url"` + + // OrgID and OrgName identify the org the key belongs to. + OrgID string `json:"orgId"` + OrgName string `json:"orgName"` + + // KeyID is the public key identifier (api_keys.key_id). + KeyID string `json:"keyId"` + + // KeyRecordID is the key's record ID (api_keys.id), used to revoke it. + KeyRecordID string `json:"keyRecordId"` + + // APIKey is the full secret key. It must never be printed or logged. + APIKey string `json:"apiKey"` +} + type ContextConfig struct { // DefaultProvider is the default provider to use DefaultProvider string `json:"defaultProvider,omitempty"` diff --git a/pkg/platformclient/client.go b/pkg/platformclient/client.go new file mode 100644 index 000000000..bb374fad6 --- /dev/null +++ b/pkg/platformclient/client.go @@ -0,0 +1,246 @@ +// Package platformclient is a small HTTP client for the Devsy platform gateway. +package platformclient + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + defaultTimeout = 30 * time.Second + maxResponseBytes = 1 << 20 +) + +// APIError is an error response from the gateway. It never carries request +// data, so it is safe to show to the user. +type APIError struct { + Status int + Code string + Message string +} + +func (e *APIError) Error() string { + if e.Message == "" { + return fmt.Sprintf("gateway returned status %d", e.Status) + } + return e.Message +} + +// Client talks to one gateway. +type Client struct { + BaseURL string + HTTP *http.Client +} + +// New returns a client for the gateway at baseURL. A nil httpClient selects one +// with a timeout that does not follow redirects, so credentials are never +// replayed to another host. +func New(baseURL string, httpClient *http.Client) *Client { + if httpClient == nil { + httpClient = &http.Client{ + Timeout: defaultTimeout, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } + } + return &Client{BaseURL: strings.TrimRight(baseURL, "/"), HTTP: httpClient} +} + +// NormalizeURL validates a user-supplied gateway URL and returns it without a +// trailing slash. +func NormalizeURL(raw string) (string, error) { + raw = strings.TrimSpace(raw) + parsed, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("invalid gateway URL %q: %w", raw, err) + } + if (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { + return "", fmt.Errorf("invalid gateway URL %q: expected http(s)://host[:port]", raw) + } + if parsed.User != nil { + return "", errors.New("gateway URL must not contain credentials") + } + parsed.RawQuery = "" + parsed.Fragment = "" + return strings.TrimRight(parsed.String(), "/"), nil +} + +// Session is the result of a successful password login. +type Session struct { + Token string `json:"token"` +} + +// Org is an organization the user belongs to. +type Org struct { + ID string `json:"id"` + Name string `json:"name"` + Role string `json:"role"` +} + +// APIKey is a newly created key. Key holds the full secret and is returned by +// the gateway only once. +type APIKey struct { + ID string `json:"id"` + KeyID string `json:"key_id"` + Key string `json:"key"` +} + +// CreateKeyRequest describes an API key to create. +type CreateKeyRequest struct { + OrgID string + Name string + Scopes []string +} + +// Login exchanges an email and password for a session token. +func (c *Client) Login(ctx context.Context, email, password string) (Session, error) { + var session Session + err := c.do(ctx, request{ + method: http.MethodPost, + path: "/v1/auth/login", + body: map[string]string{"email": email, "password": password}, + }, &session) + if err != nil { + return Session{}, err + } + if session.Token == "" { + return Session{}, errors.New("gateway returned no session token") + } + return session, nil +} + +// Logout revokes a session token. +func (c *Client) Logout(ctx context.Context, token string) error { + return c.do(ctx, request{method: http.MethodPost, path: "/v1/auth/logout", bearer: token}, nil) +} + +// ListOrgs lists the orgs the session's user belongs to. +func (c *Client) ListOrgs(ctx context.Context, token string) ([]Org, error) { + var resp struct { + Orgs []Org `json:"orgs"` + } + err := c.do(ctx, request{method: http.MethodGet, path: "/v1/orgs", bearer: token}, &resp) + if err != nil { + return nil, err + } + return resp.Orgs, nil +} + +// CreateAPIKey creates an org-scoped key with the requested scopes. +func (c *Client) CreateAPIKey( + ctx context.Context, + token string, + req CreateKeyRequest, +) (APIKey, error) { + var key APIKey + err := c.do(ctx, request{ + method: http.MethodPost, + path: "/v1/orgs/" + url.PathEscape(req.OrgID) + "/api-keys", + bearer: token, + body: map[string]any{"name": req.Name, "scopes": req.Scopes}, + }, &key) + if err != nil { + return APIKey{}, err + } + if key.ID == "" || key.KeyID == "" || key.Key == "" { + return APIKey{}, errors.New("gateway returned an incomplete api key") + } + return key, nil +} + +// RevokeAPIKey revokes the key with the given record ID. +func (c *Client) RevokeAPIKey(ctx context.Context, token, orgID, keyRecordID string) error { + return c.do(ctx, request{ + method: http.MethodDelete, + path: "/v1/orgs/" + url.PathEscape(orgID) + "/api-keys/" + url.PathEscape(keyRecordID), + bearer: token, + }, nil) +} + +type request struct { + method string + path string + bearer string + body any +} + +func (c *Client) do(ctx context.Context, r request, out any) error { + req, err := c.newRequest(ctx, r) + if err != nil { + return err + } + resp, err := c.HTTP.Do(req) + if err != nil { + // url.Error embeds only the method and URL, never the body or headers. + return fmt.Errorf("calling gateway: %w", err) + } + defer func() { _ = resp.Body.Close() }() + + return decodeResponse(resp, out) +} + +func decodeResponse(resp *http.Response, out any) error { + data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) + if err != nil { + return fmt.Errorf("reading gateway response: %w", err) + } + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return parseAPIError(resp.StatusCode, data) + } + if out == nil || len(data) == 0 { + return nil + } + if err := json.Unmarshal(data, out); err != nil { + return fmt.Errorf("decoding gateway response: %w", err) + } + return nil +} + +func (c *Client) newRequest(ctx context.Context, r request) (*http.Request, error) { + var reader io.Reader + if r.body != nil { + encoded, err := json.Marshal(r.body) + if err != nil { + return nil, fmt.Errorf("encoding request: %w", err) + } + reader = bytes.NewReader(encoded) + } + req, err := http.NewRequestWithContext(ctx, r.method, c.BaseURL+r.path, reader) + if err != nil { + return nil, fmt.Errorf("building request: %w", err) + } + req.Header.Set("Accept", "application/json") + if r.body != nil { + req.Header.Set("Content-Type", "application/json") + } + if r.bearer != "" { + req.Header.Set("Authorization", "Bearer "+r.bearer) + } + return req, nil +} + +type errorBody struct { + Code string `json:"code"` + Message string `json:"message"` +} + +func parseAPIError(status int, data []byte) *APIError { + apiErr := &APIError{Status: status} + var envelope struct { + Error errorBody `json:"error"` + } + if json.Unmarshal(data, &envelope) == nil { + apiErr.Code = envelope.Error.Code + apiErr.Message = envelope.Error.Message + } + return apiErr +} diff --git a/pkg/platformclient/client_test.go b/pkg/platformclient/client_test.go new file mode 100644 index 000000000..c47dd7765 --- /dev/null +++ b/pkg/platformclient/client_test.go @@ -0,0 +1,109 @@ +package platformclient + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/suite" +) + +type ClientSuite struct { + suite.Suite +} + +func TestClientSuite(t *testing.T) { + suite.Run(t, new(ClientSuite)) +} + +func (s *ClientSuite) TestNormalizeURL() { + const local = "http://localhost:8180" + tests := map[string]string{ + local: local, + local + "/": local, + " https://gw.example.test//": "https://gw.example.test", + "https://gw.example.test/a/": "https://gw.example.test/a", + } + for raw, want := range tests { + got, err := NormalizeURL(raw) + s.Require().NoError(err, raw) + s.Equal(want, got, raw) + } +} + +func (s *ClientSuite) TestNormalizeURLRejectsBadInput() { + for _, raw := range []string{ + "", "localhost:8180", "ftp://x.test", "http://", "http://user:pw@x.test", + } { + _, err := NormalizeURL(raw) + s.Require().Error(err, raw) + s.NotContains(err.Error(), "pw@") + } +} + +func (s *ClientSuite) TestErrorEnvelopeBecomesAPIError() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte( + `{"error":{"code":"invalid_credentials","message":"invalid email or password"}}`, + )) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).Login(context.Background(), "a@example.test", "pw") + + var apiErr *APIError + s.Require().ErrorAs(err, &apiErr) + s.Equal(http.StatusUnauthorized, apiErr.Status) + s.Equal("invalid_credentials", apiErr.Code) + s.Equal("invalid email or password", err.Error()) +} + +func (s *ClientSuite) TestNonEnvelopeErrorBodyIsNotEchoed() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusBadGateway) + _, _ = w.Write([]byte("upstream said: secret-token-abc")) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).ListOrgs(context.Background(), "tok") + + s.Require().Error(err) + s.NotContains(err.Error(), "secret-token-abc") + s.Contains(err.Error(), "502") +} + +func (s *ClientSuite) TestRedirectsAreNotFollowed() { + var followed atomic.Bool + target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + followed.Store(true) + })) + defer target.Close() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).Login(context.Background(), "a@example.test", "pw") + + s.Require().Error(err) + s.False(followed.Load(), "login credentials must not be replayed to a redirect target") +} + +func (s *ClientSuite) TestIncompleteKeyResponseIsAnError() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"id":"1","key_id":"k"}`)) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).CreateAPIKey( + context.Background(), + "tok", + CreateKeyRequest{OrgID: "org", Name: "n", Scopes: []string{"read"}}, + ) + + s.Require().Error(err) +} From 00a56639900cea363a5556590fe81d3f13ef8b08 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 17:47:58 -0600 Subject: [PATCH 2/9] feat(cli): list and create workspaces through the platform gateway Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/workspace/create.go | 83 +++++++ cmd/workspace/list.go | 39 ++- cmd/workspace/platform.go | 69 ++++++ cmd/workspace/platform_test.go | 263 +++++++++++++++++++++ cmd/workspace/workspace.go | 1 + hack/platform-e2e/workspace-list-create.sh | 167 +++++++++++++ pkg/platformclient/workspaces.go | 98 ++++++++ pkg/platformclient/workspaces_test.go | 153 ++++++++++++ 8 files changed, 867 insertions(+), 6 deletions(-) create mode 100644 cmd/workspace/create.go create mode 100644 cmd/workspace/platform.go create mode 100644 cmd/workspace/platform_test.go create mode 100644 hack/platform-e2e/workspace-list-create.sh create mode 100644 pkg/platformclient/workspaces.go create mode 100644 pkg/platformclient/workspaces_test.go diff --git a/cmd/workspace/create.go b/cmd/workspace/create.go new file mode 100644 index 000000000..1a4a99967 --- /dev/null +++ b/cmd/workspace/create.go @@ -0,0 +1,83 @@ +package workspace + +import ( + "context" + "errors" + "fmt" + "io" + "os" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/output" + "github.com/spf13/cobra" +) + +const templateFlag = "template" + +// CreateCmd holds the configuration of `devsy workspace create`. +type CreateCmd struct { + *flags.GlobalFlags + + Template string + + // Out receives the result. Nil selects stdout. + Out io.Writer +} + +// NewCreateCmd creates the `devsy workspace create` command, which asks the +// platform gateway for a new workspace. +func NewCreateCmd(globalFlags *flags.GlobalFlags) *cobra.Command { + cmd := &CreateCmd{GlobalFlags: globalFlags} + createCmd := &cobra.Command{ + Use: "create NAME --template TEMPLATE", + Short: "Create a workspace on the platform gateway", + Long: "Create a workspace on the platform gateway you are logged in to.\n\n" + + "The gateway accepts the request and the workspace is built in the " + + "background, so it is not ready when this command returns. " + + "Run 'devsy workspace list' to follow its phase.", + Example: " devsy workspace create my-workspace --template go-dev", + Args: cobra.ExactArgs(1), + RunE: func(cobraCmd *cobra.Command, args []string) error { + cmd.Out = cobraCmd.OutOrStdout() + return cmd.Run(cobraCmd.Context(), args[0]) + }, + } + createCmd.Flags(). + StringVar(&cmd.Template, templateFlag, "", "Template to create the workspace from") + _ = createCmd.MarkFlagRequired(templateFlag) + return createCmd +} + +// Run sends the create request and returns once the gateway has accepted it. +func (cmd *CreateCmd) Run(ctx context.Context, name string) error { + devsyConfig, err := config.LoadConfig(cmd.Context, cmd.Provider) + if err != nil { + return err + } + creds := platformCredentials(devsyConfig) + if creds == nil { + return errors.New( + "not logged in to a platform gateway: run 'devsy login ' first", + ) + } + mode, err := output.ResolveMode(cmd.ResultFormat) + if err != nil { + return err + } + + created, err := newPlatformClient(creds).CreateWorkspace(ctx, creds.APIKey, name, cmd.Template) + if err != nil { + return fmt.Errorf("creating workspace %q: %w", name, err) + } + + out := cmd.Out + if out == nil { + out = os.Stdout + } + if mode == output.ModeJSON { + return writePlatformJSON(out, created) + } + _, err = fmt.Fprintf(out, "Workspace %s accepted (phase: %s)\n", created.Name, created.Phase) + return err +} diff --git a/cmd/workspace/list.go b/cmd/workspace/list.go index 988ea4f14..b4c41a006 100644 --- a/cmd/workspace/list.go +++ b/cmd/workspace/list.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "fmt" + "io" + "os" "sort" "time" @@ -24,6 +26,9 @@ type ListCmd struct { *flags.GlobalFlags SkipPlatform bool + + // Out receives platform gateway output. Nil selects stdout. + Out io.Writer } // NewListCmd creates a new destroy command. @@ -38,6 +43,7 @@ func NewListCmd(globalFlags *flags.GlobalFlags) *cobra.Command { Args: cobra.NoArgs, Annotations: telemetry.SkipInUIAnnotation(), RunE: func(cobraCmd *cobra.Command, _ []string) error { + cmd.Out = cobraCmd.OutOrStdout() return cmd.Run(cobraCmd.Context()) }, } @@ -63,24 +69,45 @@ func (cmd *ListCmd) Run(ctx context.Context) error { return err } - workspaces, err := workspace.List(ctx, devsyConfig, cmd.SkipPlatform, cmd.Owner) + mode, err := output.ResolveMode(cmd.ResultFormat) if err != nil { return err } - mode, err := output.ResolveMode(cmd.ResultFormat) + if creds := cmd.gatewayLogin(devsyConfig); creds != nil { + return listPlatformWorkspaces(ctx, cmd.writer(), creds, mode) + } + + workspaces, err := workspace.List(ctx, devsyConfig, cmd.SkipPlatform, cmd.Owner) if err != nil { return err } + return printWorkspaces(workspaces, mode) +} + +// gatewayLogin returns the platform gateway login to list from. --skip-platform +// keeps a logged-in user able to list local workspaces. +func (cmd *ListCmd) gatewayLogin(devsyConfig *config.Config) *config.GatewayCredentials { + if cmd.SkipPlatform { + return nil + } + return platformCredentials(devsyConfig) +} + +func (cmd *ListCmd) writer() io.Writer { + if cmd.Out == nil { + return os.Stdout + } + return cmd.Out +} + +func printWorkspaces(workspaces []*provider.Workspace, mode string) error { switch mode { case output.ModeJSON: - if err := printJSONWorkspaces(workspaces); err != nil { - return err - } + return printJSONWorkspaces(workspaces) case output.ModePlain: printPlainWorkspaces(workspaces) } - return nil } diff --git a/cmd/workspace/platform.go b/cmd/workspace/platform.go new file mode 100644 index 000000000..e078cfc72 --- /dev/null +++ b/cmd/workspace/platform.go @@ -0,0 +1,69 @@ +package workspace + +import ( + "context" + "encoding/json" + "fmt" + "io" + "sort" + "text/tabwriter" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/output" + "github.com/devsy-org/devsy/pkg/platformclient" +) + +// platformCredentials returns the gateway login when the active config is a +// platform login, and nil otherwise. A login missing its URL or key is treated +// as no login, so a half-written config falls back to local workspaces. +func platformCredentials(cfg *config.Config) *config.GatewayCredentials { + if cfg == nil || cfg.Gateway == nil || cfg.Gateway.URL == "" || cfg.Gateway.APIKey == "" { + return nil + } + return cfg.Gateway +} + +func newPlatformClient(creds *config.GatewayCredentials) *platformclient.Client { + return platformclient.New(creds.URL, nil) +} + +func listPlatformWorkspaces( + ctx context.Context, + out io.Writer, + creds *config.GatewayCredentials, + mode string, +) error { + workspaces, err := newPlatformClient(creds).ListWorkspaces(ctx, creds.APIKey) + if err != nil { + return fmt.Errorf("listing workspaces: %w", err) + } + sort.SliceStable(workspaces, func(i, j int) bool { + return workspaces[i].Name < workspaces[j].Name + }) + + if mode == output.ModeJSON { + if workspaces == nil { + workspaces = []platformclient.Workspace{} + } + return writePlatformJSON(out, workspaces) + } + return writePlatformTable(out, workspaces) +} + +func writePlatformJSON(out io.Writer, v any) error { + encoded, err := json.Marshal(v) + if err != nil { + return fmt.Errorf("encoding workspaces: %w", err) + } + _, err = fmt.Fprintln(out, string(encoded)) + return err +} + +func writePlatformTable(out io.Writer, workspaces []platformclient.Workspace) error { + tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(tw, "NAME\tPHASE") + for _, ws := range workspaces { + _, _ = fmt.Fprintf(tw, "%s\t%s\n", ws.Name, ws.Phase) + } + return tw.Flush() +} diff --git a/cmd/workspace/platform_test.go b/cmd/workspace/platform_test.go new file mode 100644 index 000000000..7b73f1804 --- /dev/null +++ b/cmd/workspace/platform_test.go @@ -0,0 +1,263 @@ +package workspace + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/output" + "github.com/spf13/cobra" + "github.com/stretchr/testify/suite" +) + +const ( + platTestKey = "test-api-key-placeholder" + platTemplate = "smoke-template" + platName = "ws-one" + platWsA = "ws-a" + + fieldName = "name" + fieldPhase = "phase" + phaseRunning = "Running" + phasePending = "Pending" +) + +type platformCall struct { + Method, Path, Auth string + Body map[string]string +} + +type fakePlatformGateway struct { + server *httptest.Server + + mu sync.Mutex + calls []platformCall + workspaces []map[string]string + status int +} + +func newFakePlatformGateway() *fakePlatformGateway { + g := &fakePlatformGateway{} + g.server = httptest.NewServer(http.HandlerFunc(g.handle)) + return g +} + +func (g *fakePlatformGateway) handle(w http.ResponseWriter, r *http.Request) { + call := platformCall{Method: r.Method, Path: r.URL.Path, Auth: r.Header.Get("Authorization")} + if r.Body != nil { + _ = json.NewDecoder(r.Body).Decode(&call.Body) + } + g.mu.Lock() + g.calls = append(g.calls, call) + status := g.status + g.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + if status != 0 { + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"error":{"code":"unauthorized","message":"invalid api key"}}`)) + return + } + switch call.Method + " " + call.Path { + case "GET /v1/workspaces": + _ = json.NewEncoder(w).Encode(g.workspaces) + case "POST /v1/workspaces": + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]string{ + fieldName: call.Body[fieldName], + fieldPhase: phasePending, + }) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func (g *fakePlatformGateway) recorded() []platformCall { + g.mu.Lock() + defer g.mu.Unlock() + return append([]platformCall(nil), g.calls...) +} + +type PlatformSuite struct { + suite.Suite + + gateway *fakePlatformGateway + out *bytes.Buffer +} + +func TestPlatformSuite(t *testing.T) { + suite.Run(t, new(PlatformSuite)) +} + +func (s *PlatformSuite) SetupTest() { + s.T().Setenv(config.EnvHome, s.T().TempDir()) + s.T().Setenv(config.EnvConfig, "") + s.T().Setenv("DEVSY_UI", "") + config.ResetPathManager() + s.T().Cleanup(config.ResetPathManager) + + s.gateway = newFakePlatformGateway() + s.T().Cleanup(s.gateway.server.Close) + s.out = &bytes.Buffer{} +} + +func (s *PlatformSuite) TestListPrintsOneRowPerWorkspaceWithNameAndPhase() { + s.login() + s.gateway.workspaces = []map[string]string{ + {fieldName: platWsA, fieldPhase: phaseRunning}, + {fieldName: "ws-b", fieldPhase: "Sleeping"}, + {fieldName: "ws-c", fieldPhase: "Failed"}, + } + + s.Require().NoError(s.list(output.ModePlain)) + + lines := strings.Split(strings.TrimSpace(s.out.String()), "\n") + s.Require().Len(lines, 4, s.out.String()) + s.Equal([]string{"NAME", "PHASE"}, strings.Fields(lines[0])) + s.Equal([]string{platWsA, phaseRunning}, strings.Fields(lines[1])) + s.Equal([]string{"ws-b", "Sleeping"}, strings.Fields(lines[2])) + s.Equal([]string{"ws-c", "Failed"}, strings.Fields(lines[3])) +} + +func (s *PlatformSuite) TestListSendsTheStoredKey() { + s.login() + + s.Require().NoError(s.list(output.ModePlain)) + + calls := s.gateway.recorded() + s.Require().Len(calls, 1) + s.Equal("GET", calls[0].Method) + s.Equal("/v1/workspaces", calls[0].Path) + s.Equal("Bearer "+platTestKey, calls[0].Auth) + s.NotContains(s.out.String(), platTestKey) +} + +func (s *PlatformSuite) TestListWithNoWorkspacesPrintsOnlyTheHeader() { + s.login() + + s.Require().NoError(s.list(output.ModePlain)) + + s.Equal([]string{"NAME", "PHASE"}, strings.Fields(s.out.String())) +} + +func (s *PlatformSuite) TestListJSONHasNameAndPhaseOnly() { + s.login() + s.gateway.workspaces = []map[string]string{{fieldName: platWsA, fieldPhase: phaseRunning}} + + s.Require().NoError(s.list(output.ModeJSON)) + + var rows []map[string]string + s.Require().NoError(json.Unmarshal(s.out.Bytes(), &rows)) + s.Equal([]map[string]string{{fieldName: platWsA, fieldPhase: phaseRunning}}, rows) +} + +func (s *PlatformSuite) TestListUnauthorizedSuggestsLogin() { + s.login() + s.gateway.status = http.StatusUnauthorized + + err := s.list(output.ModePlain) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.Contains(err.Error(), "listing workspaces") + s.NotContains(err.Error(), platTestKey) +} + +func (s *PlatformSuite) TestCreatePostsNameAndTemplateAndDoesNotPoll() { + s.login() + + s.Require().NoError(s.create(platName, "--template", platTemplate)) + + calls := s.gateway.recorded() + s.Require().Len(calls, 1, "create must not poll the gateway") + s.Equal("POST", calls[0].Method) + s.Equal("/v1/workspaces", calls[0].Path) + s.Equal("Bearer "+platTestKey, calls[0].Auth) + s.Equal(map[string]string{fieldName: platName, "template": platTemplate}, calls[0].Body) + s.Contains(s.out.String(), platName) + s.NotContains(s.out.String(), platTestKey) +} + +func (s *PlatformSuite) TestCreateRequiresTemplate() { + s.login() + + err := s.create(platName) + + s.Require().Error(err) + s.Contains(err.Error(), "template") + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestCreateRequiresExactlyOneName() { + s.login() + + s.Require().Error(s.create("--template", platTemplate)) + s.Require().Error(s.create("a", "b", "--template", platTemplate)) + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestCreateWithoutLoginSuggestsLogin() { + err := s.create(platName, "--template", platTemplate) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestCreateUnauthorizedSuggestsLogin() { + s.login() + s.gateway.status = http.StatusUnauthorized + + err := s.create(platName, "--template", platTemplate) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.Contains(err.Error(), "creating workspace") + s.NotContains(err.Error(), platTestKey) +} + +func (s *PlatformSuite) TestPlatformCredentialsOnlyForACompleteLogin() { + s.Nil(platformCredentials(nil)) + s.Nil(platformCredentials(&config.Config{})) + s.Nil(platformCredentials(&config.Config{Gateway: &config.GatewayCredentials{URL: "http://x"}})) + s.Nil(platformCredentials(&config.Config{Gateway: &config.GatewayCredentials{APIKey: "k"}})) + + creds := &config.GatewayCredentials{URL: "http://x", APIKey: "k"} + s.Same(creds, platformCredentials(&config.Config{Gateway: creds})) +} + +func (s *PlatformSuite) login() { + s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway = &config.GatewayCredentials{ + URL: s.gateway.server.URL, + OrgID: "org-1", + OrgName: "Acme", + KeyID: "AbCdEfGh12345678", + KeyRecordID: "rec-1", + APIKey: platTestKey, + } + return nil + })) +} + +func (s *PlatformSuite) execute(cmd *cobra.Command, args ...string) error { + cmd.SetOut(s.out) + cmd.SetErr(s.out) + cmd.SetArgs(args) + return cmd.ExecuteContext(context.Background()) +} + +func (s *PlatformSuite) list(format string) error { + return s.execute(NewListCmd(&flags.GlobalFlags{ResultFormat: format})) +} + +func (s *PlatformSuite) create(args ...string) error { + return s.execute(NewCreateCmd(&flags.GlobalFlags{ResultFormat: output.ModePlain}), args...) +} diff --git a/cmd/workspace/workspace.go b/cmd/workspace/workspace.go index 5d48d0076..189b7ad12 100644 --- a/cmd/workspace/workspace.go +++ b/cmd/workspace/workspace.go @@ -19,6 +19,7 @@ func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command { cmd.AddCommand(NewSSHCmd(globalFlags)) cmd.AddCommand(NewExecCmd(globalFlags)) cmd.AddCommand(NewListCmd(globalFlags)) + cmd.AddCommand(NewCreateCmd(globalFlags)) cmd.AddCommand(NewStatusCmd(globalFlags)) cmd.AddCommand(NewEventsCmd(globalFlags)) cmd.AddCommand(NewDescribeCmd(globalFlags)) diff --git a/hack/platform-e2e/workspace-list-create.sh b/hack/platform-e2e/workspace-list-create.sh new file mode 100644 index 000000000..c2c5f84ec --- /dev/null +++ b/hack/platform-e2e/workspace-list-create.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +# tuistory end-to-end check of `devsy workspace list` and `devsy workspace create` +# against a live platform gateway (VAL-CLI-005, VAL-CLI-006). +# +# Every devsy command runs as a real terminal session driven by tuistory. The +# CLI never polls; this script does the waiting. +# +# Requires: tuistory, curl, jq, a devsy binary, and a gateway whose controller can +# run the template named by TEMPLATE. Evidence is written to $EVIDENCE_DIR. +# +# GATEWAY gateway URL (default http://localhost:8180) +# DEVSY_BIN devsy binary (default dist/devsy-e2e) +# TEMPLATE WorkspaceTemplate name (default smoke-template) +# RUNNING_WAIT seconds to reach Running (default 120) +set -euo pipefail + +GATEWAY="${GATEWAY:-http://localhost:8180}" +DEVSY_BIN="$(cd "$(dirname "${DEVSY_BIN:-dist/devsy-e2e}")" && pwd)/$(basename "${DEVSY_BIN:-dist/devsy-e2e}")" +TEMPLATE="${TEMPLATE:-smoke-template}" +RUNNING_WAIT="${RUNNING_WAIT:-120}" +export PATH="$HOME/.bun/bin:$PATH" + +RUN="$(date +%s)-$RANDOM" +EVIDENCE_DIR="${EVIDENCE_DIR:-$(pwd)/dist/platform-e2e/$RUN}" +WORK="$(mktemp -d)" +SESSION_PREFIX="wslc-$RUN" +EMAIL="cli-$RUN@example.test" +PASSWORD="pw-$RUN-$RANDOM$RANDOM" +WS_NAME="ws-cli-$RUN" +WS_NAME_2="ws-cli2-$RUN" +mkdir -p "$EVIDENCE_DIR" + +export DEVSY_HOME="$WORK/home" +mkdir -p "$DEVSY_HOME" + +fail() { echo "FAIL: $*" >&2; exit 1; } +log() { echo "[wslc] $*"; } + +cleanup() { + local status=$? + tuistory -s "$SESSION_PREFIX-login" close >/dev/null 2>&1 || true + rm -rf "$WORK" + return "$status" +} +trap cleanup EXIT + +# The runner prints the exit status on its own line so a transcript shows it. +RUNNER="$WORK/run.sh" +cat >"$RUNNER" <<'EOF' +#!/bin/sh +"$@" +echo "EXIT=$?" +EOF +chmod +x "$RUNNER" + +api() { curl -sS -H 'Content-Type: application/json' "$@"; } + +# tui NAME TIMEOUT_MS ARGS...: run devsy in a terminal, wait for EXIT=n, save the +# transcript to $EVIDENCE_DIR/NAME.txt, and set TUI_EXIT. +tui() { + local name="$1" timeout="$2" + shift 2 + local session="$SESSION_PREFIX-$name" + tuistory launch "$RUNNER $DEVSY_BIN $*" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout "$timeout" >/dev/null || + fail "$name: command did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/$name.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + TUI_EXIT="$(grep -Eo 'EXIT=[0-9]+' "$EVIDENCE_DIR/$name.txt" | tail -1 | cut -d= -f2)" +} + +# list_pairs FILE: print "name phase" lines from a plain list transcript. +list_pairs() { + awk 'NF == 2 && $1 != "NAME" && $1 !~ /^EXIT=/ {print $1, $2}' "$1" | sort +} + +stored_key() { + awk '/^gateway:/ {g=1; next} g && /^ apiKey:/ {gsub(/"/, "", $2); print $2; exit}' \ + "$DEVSY_HOME/config.yaml" +} + +log "creating test user and org ($EMAIL)" +api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" >/dev/null +TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" | jq -r .token)" +[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || fail "could not log in through the gateway" +api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $TOKEN" \ + -d "$(jq -n --arg n "Org $RUN" '{name: $n}')" >/dev/null + +log "devsy login (tuistory)" +LOGIN_SESSION="$SESSION_PREFIX-login" +tuistory launch "$RUNNER $DEVSY_BIN login $GATEWAY" -s "$LOGIN_SESSION" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Email' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$EMAIL" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Password' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$PASSWORD" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait '/EXIT=[0-9]+/' --timeout 30000 >/dev/null || fail "login did not finish" +tuistory -s "$LOGIN_SESSION" snapshot --trim >"$EVIDENCE_DIR/login.txt" +grep -q 'EXIT=0' "$EVIDENCE_DIR/login.txt" || fail "login failed: $(cat "$EVIDENCE_DIR/login.txt")" + +# VAL-CLI-006: create exits 0, then the list shows Running within the deadline. +log "VAL-CLI-006: devsy workspace create $WS_NAME --template $TEMPLATE" +tui create 30000 workspace create "$WS_NAME" --template "$TEMPLATE" +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-006: create exited $TUI_EXIT" + +# wait_running NAME LABEL: poll the CLI list until NAME is Running or the deadline passes. +wait_running() { + local name="$1" label="$2" attempt=0 deadline=$((SECONDS + RUNNING_WAIT)) + while :; do + attempt=$((attempt + 1)) + tui "$label-$attempt" 30000 workspace list + [ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-006: list exited $TUI_EXIT" + if list_pairs "$EVIDENCE_DIR/$label-$attempt.txt" | grep -qx "$name Running"; then + break + fi + [ "$SECONDS" -lt "$deadline" ] || + fail "VAL-CLI-006: $name not Running within ${RUNNING_WAIT}s" + sleep 2 + done + log "VAL-CLI-006: $name is Running after $((RUNNING_WAIT - (deadline - SECONDS)))s" +} + +wait_running "$WS_NAME" list-wait + +# A second workspace makes the VAL-CLI-005 comparison cover more than one row. +log "devsy workspace create $WS_NAME_2 --template $TEMPLATE" +tui create-2 30000 workspace create "$WS_NAME_2" --template "$TEMPLATE" +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-006: second create exited $TUI_EXIT" +wait_running "$WS_NAME_2" list-wait-2nd + +# VAL-CLI-005: the CLI rows are exactly the gateway's (name, phase) pairs. +log "VAL-CLI-005: compare devsy workspace list with GET /v1/workspaces" +KEY="$(stored_key)" +[ -n "$KEY" ] || fail "no API key in the devsy config" +tui list 30000 workspace list +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-005: list exited $TUI_EXIT" +api -H "Authorization: Bearer $KEY" "$GATEWAY/v1/workspaces" >"$EVIDENCE_DIR/gateway-workspaces.json" +jq -r '.[] | "\(.name) \(.phase)"' "$EVIDENCE_DIR/gateway-workspaces.json" | sort >"$WORK/gateway.pairs" +list_pairs "$EVIDENCE_DIR/list.txt" >"$WORK/cli.pairs" +cp "$WORK/gateway.pairs" "$EVIDENCE_DIR/gateway.pairs" +cp "$WORK/cli.pairs" "$EVIDENCE_DIR/cli.pairs" +[ "$(wc -l <"$WORK/gateway.pairs")" -ge 2 ] || fail "VAL-CLI-005: expected at least two workspaces" +diff "$WORK/gateway.pairs" "$WORK/cli.pairs" || fail "VAL-CLI-005: CLI rows differ from the gateway" + +for name in "$WS_NAME" "$WS_NAME_2"; do + api -X DELETE -H "Authorization: Bearer $KEY" "$GATEWAY/v1/workspaces/$name" >/dev/null || true +done + +# A key the gateway no longer accepts gives an authentication error that names devsy login. +log "401: revoke the stored key, then devsy workspace list must fail and suggest devsy login" +KEY_RECORD_ID="$(awk '/^gateway:/ {g=1; next} g && /^ keyRecordId:/ {gsub(/"/, "", $2); print $2; exit}' "$DEVSY_HOME/config.yaml")" +ORG_ID="$(awk '/^gateway:/ {g=1; next} g && /^ orgId:/ {gsub(/"/, "", $2); print $2; exit}' "$DEVSY_HOME/config.yaml")" +code="$(curl -sS -o /dev/null -w '%{http_code}' -X DELETE -H "Authorization: Bearer $TOKEN" \ + "$GATEWAY/v1/orgs/$ORG_ID/api-keys/$KEY_RECORD_ID")" +[ "$code" = 204 ] || fail "could not revoke the key (status $code)" +tui list-revoked 30000 workspace list +[ "$TUI_EXIT" != 0 ] || fail "list succeeded with a revoked key" +grep -q "devsy login" "$EVIDENCE_DIR/list-revoked.txt" || fail "401 error does not mention devsy login" + +grep -rEq 'dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+' "$EVIDENCE_DIR" && fail "transcript contains an API key" + +log "PASS VAL-CLI-005 VAL-CLI-006 (evidence: $EVIDENCE_DIR)" diff --git a/pkg/platformclient/workspaces.go b/pkg/platformclient/workspaces.go new file mode 100644 index 000000000..010c0dc55 --- /dev/null +++ b/pkg/platformclient/workspaces.go @@ -0,0 +1,98 @@ +package platformclient + +import ( + "context" + "errors" + "net/http" +) + +// Workspace is one workspace as the gateway reports it. Phase is read from the +// cluster on every request, so it is a snapshot. +type Workspace struct { + Name string `json:"name"` + Phase string `json:"phase"` +} + +// AuthError is a 401 on a call made with a stored API key. The key is missing, +// revoked, or unknown, and signing in again issues a new one. +type AuthError struct { + Cause *APIError +} + +func (e *AuthError) Error() string { + return "authentication failed: the gateway did not accept the stored API key; " + + "run 'devsy login' to sign in again" +} + +func (e *AuthError) Unwrap() error { return e.Cause } + +// PermissionError is a 403 on a call made with a stored API key. +type PermissionError struct { + Cause *APIError +} + +func (e *PermissionError) Error() string { + if e.Cause.Message == "" { + return "permission denied" + } + return "permission denied: " + e.Cause.Message +} + +func (e *PermissionError) Unwrap() error { return e.Cause } + +var errNoKey = errors.New("not logged in: run 'devsy login' to sign in") + +// ListWorkspaces lists the workspaces of the key's org. +func (c *Client) ListWorkspaces(ctx context.Context, apiKey string) ([]Workspace, error) { + var out []Workspace + err := c.doWithKey(ctx, request{ + method: http.MethodGet, + path: "/v1/workspaces", + bearer: apiKey, + }, &out) + if err != nil { + return nil, err + } + return out, nil +} + +// CreateWorkspace asks the gateway to create a workspace from a template. The +// gateway answers 202 once the request is recorded; the workspace is not ready +// yet, and callers that need it ready poll ListWorkspaces. +func (c *Client) CreateWorkspace( + ctx context.Context, + apiKey, name, template string, +) (Workspace, error) { + var out Workspace + err := c.doWithKey(ctx, request{ + method: http.MethodPost, + path: "/v1/workspaces", + bearer: apiKey, + body: map[string]string{"name": name, "template": template}, + }, &out) + if err != nil { + return Workspace{}, err + } + return out, nil +} + +// doWithKey is do for calls authenticated by an API key. It names a rejected +// key, which plain do cannot: login uses 401 for a wrong password. +func (c *Client) doWithKey(ctx context.Context, r request, out any) error { + if r.bearer == "" { + return errNoKey + } + err := c.do(ctx, r, out) + var apiErr *APIError + if !errors.As(err, &apiErr) { + return err + } + switch apiErr.Status { + case http.StatusUnauthorized: + return &AuthError{Cause: apiErr} + case http.StatusForbidden: + return &PermissionError{Cause: apiErr} + default: + return err + } +} diff --git a/pkg/platformclient/workspaces_test.go b/pkg/platformclient/workspaces_test.go new file mode 100644 index 000000000..2014266f7 --- /dev/null +++ b/pkg/platformclient/workspaces_test.go @@ -0,0 +1,153 @@ +package platformclient + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/suite" +) + +const wsTestName = "ws-a" + +const wsTestKey = "test-api-key-placeholder" + +type WorkspacesSuite struct { + suite.Suite +} + +func TestWorkspacesSuite(t *testing.T) { + suite.Run(t, new(WorkspacesSuite)) +} + +func (s *WorkspacesSuite) TestListSendsKeyAndMapsRows() { + var method, path, auth string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path, auth = r.Method, r.URL.Path, r.Header.Get("Authorization") + _, _ = w.Write([]byte( + `[{"name":"` + wsTestName + `","phase":"Running"},{"name":"ws-b","phase":"Pending"}]`, + )) + })) + defer srv.Close() + + got, err := New(srv.URL, nil).ListWorkspaces(context.Background(), wsTestKey) + + s.Require().NoError(err) + s.Equal(http.MethodGet, method) + s.Equal("/v1/workspaces", path) + s.Equal("Bearer "+wsTestKey, auth) + s.Equal( + []Workspace{{Name: wsTestName, Phase: "Running"}, {Name: "ws-b", Phase: "Pending"}}, + got, + ) +} + +func (s *WorkspacesSuite) TestListOfNothingIsEmpty() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(`[]`)) + })) + defer srv.Close() + + got, err := New(srv.URL, nil).ListWorkspaces(context.Background(), wsTestKey) + + s.Require().NoError(err) + s.Empty(got) +} + +func (s *WorkspacesSuite) TestCreatePostsNameAndTemplateOnly() { + var method, path, auth, contentType string + var body []byte + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path = r.Method, r.URL.Path + auth, contentType = r.Header.Get("Authorization"), r.Header.Get("Content-Type") + body, _ = io.ReadAll(r.Body) + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"name":"` + wsTestName + `","phase":"Pending"}`)) + })) + defer srv.Close() + + got, err := New( + srv.URL, + nil, + ).CreateWorkspace(context.Background(), wsTestKey, wsTestName, "tmpl") + + s.Require().NoError(err) + s.Equal(http.MethodPost, method) + s.Equal("/v1/workspaces", path) + s.Equal("Bearer "+wsTestKey, auth) + s.Equal("application/json", contentType) + var decoded map[string]string + s.Require().NoError(json.Unmarshal(body, &decoded)) + s.Equal(map[string]string{"name": wsTestName, "template": "tmpl"}, decoded) + s.Equal(Workspace{Name: wsTestName, Phase: "Pending"}, got) +} + +func (s *WorkspacesSuite) TestUnauthorizedSuggestsLogin() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":{"code":"unauthorized","message":"invalid api key"}}`)) + })) + defer srv.Close() + client := New(srv.URL, nil) + + _, listErr := client.ListWorkspaces(context.Background(), wsTestKey) + _, createErr := client.CreateWorkspace(context.Background(), wsTestKey, wsTestName, "tmpl") + + for _, err := range []error{listErr, createErr} { + var authErr *AuthError + s.Require().ErrorAs(err, &authErr) + s.Contains(err.Error(), "devsy login") + s.Contains(err.Error(), "authentication") + var apiErr *APIError + s.Require().ErrorAs(err, &apiErr) + s.Equal(http.StatusUnauthorized, apiErr.Status) + s.NotContains(err.Error(), wsTestKey) + } +} + +func (s *WorkspacesSuite) TestForbiddenIsAPermissionError() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":{"code":"forbidden","message":"key lacks write scope"}}`)) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).CreateWorkspace(context.Background(), wsTestKey, wsTestName, "tmpl") + + s.Require().Error(err) + s.Contains(err.Error(), "permission denied") + s.Contains(err.Error(), "key lacks write scope") + var authErr *AuthError + s.False(errors.As(err, &authErr), "a 403 is not an authentication failure") +} + +func (s *WorkspacesSuite) TestOtherErrorsKeepTheGatewayMessage() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusConflict) + _, _ = w.Write([]byte(`{"error":{"code":"conflict","message":"workspace already exists"}}`)) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).CreateWorkspace(context.Background(), wsTestKey, wsTestName, "tmpl") + + s.Require().Error(err) + s.Equal("workspace already exists", err.Error()) +} + +func (s *WorkspacesSuite) TestEmptyKeyFailsBeforeCallingTheGateway() { + called := false + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + called = true + })) + defer srv.Close() + + _, err := New(srv.URL, nil).ListWorkspaces(context.Background(), "") + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.False(called) +} From 79a132481fe91c078c979f86f500585d83cc9ef5 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 18:19:26 -0600 Subject: [PATCH 3/9] feat(cli): sleep, wake and delete workspaces through the platform gateway Add `devsy workspace sleep|wake NAME` and route `devsy workspace delete NAME...` to the gateway when logged in (--skip-platform keeps the local delete). Each call must be answered 202, otherwise the command exits non-zero with the gateway's message. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/workspace/delete.go | 43 +++- cmd/workspace/platform_lifecycle.go | 129 ++++++++++++ cmd/workspace/platform_lifecycle_test.go | 178 +++++++++++++++++ cmd/workspace/platform_test.go | 46 ++++- cmd/workspace/sleep.go | 69 +++++++ cmd/workspace/workspace.go | 2 + .../workspace-sleep-wake-delete.sh | 185 ++++++++++++++++++ pkg/platformclient/client.go | 10 + pkg/platformclient/workspaces.go | 46 +++++ pkg/platformclient/workspaces_test.go | 133 +++++++++++++ 10 files changed, 832 insertions(+), 9 deletions(-) create mode 100644 cmd/workspace/platform_lifecycle.go create mode 100644 cmd/workspace/platform_lifecycle_test.go create mode 100644 cmd/workspace/sleep.go create mode 100755 hack/platform-e2e/workspace-sleep-wake-delete.sh diff --git a/cmd/workspace/delete.go b/cmd/workspace/delete.go index 8051e7dd7..c0c047d90 100644 --- a/cmd/workspace/delete.go +++ b/cmd/workspace/delete.go @@ -3,6 +3,7 @@ package workspace import ( "context" "fmt" + "io" "os" "github.com/devsy-org/devsy/cmd/completion" @@ -28,6 +29,11 @@ const ( type DeleteCmd struct { *flags.GlobalFlags client2.DeleteOptions + + SkipPlatform bool + + // Out receives platform gateway output. Nil selects stdout. + Out io.Writer } // NewDeleteCmd creates a new command. @@ -44,8 +50,14 @@ func NewDeleteCmd(globalFlags *flags.GlobalFlags) *cobra.Command { Aliases "rm" and "down" perform the same full Devsy workspace teardown. For Docker Compose workspaces, teardown uses Docker/Podman Compose down. -Use --ignore-not-found to treat a missing workspace as success.`, +Use --ignore-not-found to treat a missing workspace as success. + +When you are logged in to a platform gateway ('devsy login'), the named +workspaces are deleted on the gateway. The gateway accepts the request and the +workspaces are removed in the background. Use --skip-platform to delete a local +workspace instead.`, RunE: func(cobraCmd *cobra.Command, args []string) error { + cmd.Out = cobraCmd.OutOrStdout() return cmd.Run(cobraCmd, args) }, ValidArgsFunction: func( @@ -74,6 +86,8 @@ Use --ignore-not-found to treat a missing workspace as success.`, cliflags.Bool(&cmd.RemoveVolumes, names.RemoveVolumes, false, "Remove named volumes associated with the workspace "+ "(docker compose only)"), + cliflags.Bool(&cmd.SkipPlatform, names.SkipPlatform, false, + "Don't delete on the platform gateway, even when logged in"), ) return deleteCmd } @@ -81,6 +95,9 @@ Use --ignore-not-found to treat a missing workspace as success.`, // Run runs the command logic. func (cmd *DeleteCmd) Run(cobraCmd *cobra.Command, args []string) error { ctx := cobraCmd.Context() + if handled, err := cmd.runPlatform(ctx, args); handled { + return err + } reporter, err := newWorkspaceStatusReporter( cmd.ResultFormat, os.Stdout, @@ -129,6 +146,30 @@ func (cmd *DeleteCmd) Run(cobraCmd *cobra.Command, args []string) error { return deleteErr } +// runPlatform deletes the named workspaces on the platform gateway when there +// is a gateway login. It reports handled=false when the delete is local: no +// login, --skip-platform, or no names (the interactive picker lists local +// workspaces). +func (cmd *DeleteCmd) runPlatform(ctx context.Context, args []string) (bool, error) { + if cmd.SkipPlatform || len(args) == 0 { + return false, nil + } + devsyConfig, err := config.LoadConfig(cmd.Context, cmd.Provider) + if err != nil { + return false, nil + } + creds := platformCredentials(devsyConfig) + if creds == nil { + return false, nil + } + target, err := newLifecycleTarget(cmd.GlobalFlags, creds, cmd.Out) + if err != nil { + return true, err + } + target.ignoreNotFound = cmd.IgnoreNotFound + return true, runPlatformLifecycle(ctx, target, deleteAction, args) +} + // deleteInteractively resolves the deletion target with a single interactive // selection and deletes that same client, so the operation is journaled under // the workspace that is actually deleted. diff --git a/cmd/workspace/platform_lifecycle.go b/cmd/workspace/platform_lifecycle.go new file mode 100644 index 000000000..18c142fa6 --- /dev/null +++ b/cmd/workspace/platform_lifecycle.go @@ -0,0 +1,129 @@ +package workspace + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "os" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/output" + "github.com/devsy-org/devsy/pkg/platformclient" +) + +// lifecycleAction is one asynchronous request to the gateway: it is accepted +// right away and the workspace follows in the background. +type lifecycleAction struct { + // requested is the past-tense label printed on success, e.g. "Sleep requested". + requested string + // gerund names the action in errors, e.g. "sleeping". + gerund string + call func(*platformclient.Client, context.Context, string, string) (platformclient.Workspace, error) +} + +var ( + sleepAction = lifecycleAction{ + requested: "Sleep requested", + gerund: "sleeping", + call: (*platformclient.Client).SleepWorkspace, + } + wakeAction = lifecycleAction{ + requested: "Wake requested", + gerund: "waking", + call: (*platformclient.Client).WakeWorkspace, + } + deleteAction = lifecycleAction{ + requested: "Delete requested", + gerund: "deleting", + call: (*platformclient.Client).DeleteWorkspace, + } +) + +var errNotLoggedIn = errors.New( + "not logged in to a platform gateway: run 'devsy login ' first", +) + +// lifecycleTarget is what a lifecycle request needs: the gateway login, where +// to print, and how. +type lifecycleTarget struct { + creds *config.GatewayCredentials + out io.Writer + mode string + // ignoreNotFound treats a 404 as success, for delete --ignore-not-found. + ignoreNotFound bool +} + +// runPlatformLifecycle sends the action for every name and keeps going after a +// failure, so one bad name does not hide the others. It returns every failure. +func runPlatformLifecycle( + ctx context.Context, + target lifecycleTarget, + action lifecycleAction, + names []string, +) error { + client := newPlatformClient(target.creds) + var errs []error + for _, name := range names { + ws, err := action.call(client, ctx, target.creds.APIKey, name) + if err != nil { + if target.ignoreNotFound && isNotFound(err) { + continue + } + errs = append(errs, fmt.Errorf("%s workspace %q: %w", action.gerund, name, err)) + continue + } + if err := printLifecycleResult(target, action, ws); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +func isNotFound(err error) bool { + var apiErr *platformclient.APIError + return errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound +} + +func printLifecycleResult( + target lifecycleTarget, + action lifecycleAction, + ws platformclient.Workspace, +) error { + if target.mode == output.ModeJSON { + return writePlatformJSON(target.out, ws) + } + _, err := fmt.Fprintf(target.out, "%s for workspace %s (phase: %s)\n", + action.requested, ws.Name, ws.Phase) + return err +} + +// resolveLifecycleTarget loads the gateway login. It fails when there is none. +func resolveLifecycleTarget(g *flags.GlobalFlags, out io.Writer) (lifecycleTarget, error) { + devsyConfig, err := config.LoadConfig(g.Context, g.Provider) + if err != nil { + return lifecycleTarget{}, err + } + creds := platformCredentials(devsyConfig) + if creds == nil { + return lifecycleTarget{}, errNotLoggedIn + } + return newLifecycleTarget(g, creds, out) +} + +func newLifecycleTarget( + g *flags.GlobalFlags, + creds *config.GatewayCredentials, + out io.Writer, +) (lifecycleTarget, error) { + mode, err := output.ResolveMode(g.ResultFormat) + if err != nil { + return lifecycleTarget{}, err + } + if out == nil { + out = os.Stdout + } + return lifecycleTarget{creds: creds, out: out, mode: mode}, nil +} diff --git a/cmd/workspace/platform_lifecycle_test.go b/cmd/workspace/platform_lifecycle_test.go new file mode 100644 index 000000000..9a703be14 --- /dev/null +++ b/cmd/workspace/platform_lifecycle_test.go @@ -0,0 +1,178 @@ +package workspace + +import ( + "encoding/json" + "net/http" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/output" + "github.com/spf13/cobra" +) + +type lifecycleCommand struct { + name string + method string + path string + build func(*flags.GlobalFlags) *cobra.Command + subject string +} + +func lifecycleCommands() []lifecycleCommand { + return []lifecycleCommand{ + { + "sleep", + http.MethodPost, + "/v1/workspaces/" + platName + "/sleep", + NewSleepCmd, + "sleeping", + }, + {"wake", http.MethodPost, "/v1/workspaces/" + platName + "/wake", NewWakeCmd, "waking"}, + {"delete", http.MethodDelete, "/v1/workspaces/" + platName, NewDeleteCmd, "deleting"}, + } +} + +func (s *PlatformSuite) run(tc lifecycleCommand, args ...string) error { + return s.execute(tc.build(&flags.GlobalFlags{ResultFormat: output.ModePlain}), args...) +} + +func (s *PlatformSuite) TestLifecycleCommandsCallTheirRouteWithTheStoredKey() { + for _, tc := range lifecycleCommands() { + s.Run(tc.name, func() { + s.SetupTest() + s.login() + + s.Require().NoError(s.run(tc, platName)) + + calls := s.gateway.recorded() + s.Require().Len(calls, 1, "the command must not poll the gateway") + s.Equal(tc.method, calls[0].Method) + s.Equal(tc.path, calls[0].Path) + s.Equal("Bearer "+platTestKey, calls[0].Auth) + s.Contains(s.out.String(), platName) + s.NotContains(s.out.String(), platTestKey) + }) + } +} + +func (s *PlatformSuite) TestLifecycleCommandsPrintJSONWhenAsked() { + s.login() + + cmd := NewSleepCmd(&flags.GlobalFlags{ResultFormat: output.ModeJSON}) + s.Require().NoError(s.execute(cmd, platName)) + + var got map[string]string + s.Require().NoError(json.Unmarshal(s.out.Bytes(), &got)) + s.Equal(platName, got[fieldName]) + s.Contains(got, fieldPhase) +} + +func (s *PlatformSuite) TestLifecycleCommandsFailWithTheGatewayMessage() { + for _, tc := range lifecycleCommands() { + s.Run(tc.name, func() { + s.SetupTest() + s.login() + s.gateway.status = http.StatusNotFound + s.gateway.message = "workspace not found" + + err := s.run(tc, platName) + + s.Require().Error(err) + s.Contains(err.Error(), "workspace not found") + s.Contains(err.Error(), tc.subject) + s.Contains(err.Error(), platName) + s.NotContains(err.Error(), platTestKey) + }) + } +} + +func (s *PlatformSuite) TestLifecycleCommandsShowThePermissionMessage() { + for _, tc := range lifecycleCommands() { + s.Run(tc.name, func() { + s.SetupTest() + s.login() + s.gateway.status = http.StatusForbidden + s.gateway.message = "key lacks write scope" + + err := s.run(tc, platName) + + s.Require().Error(err) + s.Contains(err.Error(), "permission denied: key lacks write scope") + }) + } +} + +func (s *PlatformSuite) TestLifecycleCommandsSuggestLoginOnUnauthorized() { + for _, tc := range lifecycleCommands() { + s.Run(tc.name, func() { + s.SetupTest() + s.login() + s.gateway.status = http.StatusUnauthorized + + err := s.run(tc, platName) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.NotContains(err.Error(), platTestKey) + }) + } +} + +func (s *PlatformSuite) TestSleepAndWakeWithoutLoginSuggestLogin() { + for _, tc := range lifecycleCommands()[:2] { + s.Run(tc.name, func() { + s.SetupTest() + + err := s.run(tc, platName) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.Empty(s.gateway.recorded()) + }) + } +} + +func (s *PlatformSuite) TestSleepAndWakeRequireExactlyOneName() { + for _, tc := range lifecycleCommands()[:2] { + s.Run(tc.name, func() { + s.SetupTest() + s.login() + + s.Require().Error(s.run(tc)) + s.Require().Error(s.run(tc, "a", "b")) + s.Empty(s.gateway.recorded()) + }) + } +} + +func (s *PlatformSuite) TestDeleteSeveralNamesDeletesEachAndReportsEveryFailure() { + s.login() + + s.Require().NoError(s.run(lifecycleCommands()[2], platWsA, "ws-b")) + + calls := s.gateway.recorded() + s.Require().Len(calls, 2) + s.Equal("/v1/workspaces/"+platWsA, calls[0].Path) + s.Equal("/v1/workspaces/ws-b", calls[1].Path) +} + +func (s *PlatformSuite) TestDeleteKeepsGoingAfterAFailureAndExitsNonZero() { + s.login() + s.gateway.status = http.StatusNotFound + s.gateway.message = "workspace not found" + + err := s.run(lifecycleCommands()[2], platWsA, "ws-b") + + s.Require().Error(err) + s.Len(s.gateway.recorded(), 2, "a failure must not stop the remaining deletes") + s.Contains(err.Error(), platWsA) + s.Contains(err.Error(), "ws-b") + s.Contains(err.Error(), "workspace not found") +} + +func (s *PlatformSuite) TestDeleteSkipPlatformLeavesTheGatewayAlone() { + s.login() + + _ = s.run(lifecycleCommands()[2], "--skip-platform", "no-such-local-workspace") + + s.Empty(s.gateway.recorded()) +} diff --git a/cmd/workspace/platform_test.go b/cmd/workspace/platform_test.go index 7b73f1804..4bea70b59 100644 --- a/cmd/workspace/platform_test.go +++ b/cmd/workspace/platform_test.go @@ -23,10 +23,11 @@ const ( platName = "ws-one" platWsA = "ws-a" - fieldName = "name" - fieldPhase = "phase" - phaseRunning = "Running" - phasePending = "Pending" + fieldName = "name" + fieldPhase = "phase" + phaseRunning = "Running" + phasePending = "Pending" + phaseSleeping = "Sleeping" ) type platformCall struct { @@ -41,6 +42,25 @@ type fakePlatformGateway struct { calls []platformCall workspaces []map[string]string status int + message string +} + +// lifecycleRoute recognises the sleep, wake and delete routes and returns the +// workspace name with the phase the real gateway answers with. +func lifecycleRoute(call platformCall) (name, phase string, ok bool) { + rest, found := strings.CutPrefix(call.Path, "/v1/workspaces/") + if !found { + return "", "", false + } + switch { + case call.Method == http.MethodDelete && !strings.Contains(rest, "/"): + return rest, "Deleting", true + case call.Method == http.MethodPost && strings.HasSuffix(rest, "/sleep"): + return strings.TrimSuffix(rest, "/sleep"), phaseRunning, true + case call.Method == http.MethodPost && strings.HasSuffix(rest, "/wake"): + return strings.TrimSuffix(rest, "/wake"), phaseSleeping, true + } + return "", "", false } func newFakePlatformGateway() *fakePlatformGateway { @@ -56,13 +76,23 @@ func (g *fakePlatformGateway) handle(w http.ResponseWriter, r *http.Request) { } g.mu.Lock() g.calls = append(g.calls, call) - status := g.status + status, message := g.status, g.message g.mu.Unlock() w.Header().Set("Content-Type", "application/json") if status != 0 { + if message == "" { + message = "invalid api key" + } w.WriteHeader(status) - _, _ = w.Write([]byte(`{"error":{"code":"unauthorized","message":"invalid api key"}}`)) + _ = json.NewEncoder(w).Encode(map[string]any{ + "error": map[string]string{"code": "error", "message": message}, + }) + return + } + if name, phase, ok := lifecycleRoute(call); ok { + w.WriteHeader(http.StatusAccepted) + _ = json.NewEncoder(w).Encode(map[string]string{fieldName: name, fieldPhase: phase}) return } switch call.Method + " " + call.Path { @@ -112,7 +142,7 @@ func (s *PlatformSuite) TestListPrintsOneRowPerWorkspaceWithNameAndPhase() { s.login() s.gateway.workspaces = []map[string]string{ {fieldName: platWsA, fieldPhase: phaseRunning}, - {fieldName: "ws-b", fieldPhase: "Sleeping"}, + {fieldName: "ws-b", fieldPhase: phaseSleeping}, {fieldName: "ws-c", fieldPhase: "Failed"}, } @@ -122,7 +152,7 @@ func (s *PlatformSuite) TestListPrintsOneRowPerWorkspaceWithNameAndPhase() { s.Require().Len(lines, 4, s.out.String()) s.Equal([]string{"NAME", "PHASE"}, strings.Fields(lines[0])) s.Equal([]string{platWsA, phaseRunning}, strings.Fields(lines[1])) - s.Equal([]string{"ws-b", "Sleeping"}, strings.Fields(lines[2])) + s.Equal([]string{"ws-b", phaseSleeping}, strings.Fields(lines[2])) s.Equal([]string{"ws-c", "Failed"}, strings.Fields(lines[3])) } diff --git a/cmd/workspace/sleep.go b/cmd/workspace/sleep.go new file mode 100644 index 000000000..b415ecf5e --- /dev/null +++ b/cmd/workspace/sleep.go @@ -0,0 +1,69 @@ +package workspace + +import ( + "io" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/spf13/cobra" +) + +// lifecycleCmd holds `devsy workspace sleep` and `devsy workspace wake`. +type lifecycleCmd struct { + *flags.GlobalFlags + + action lifecycleAction + + // Out receives the result. Nil selects stdout. + Out io.Writer +} + +func newLifecycleCobraCmd( + globalFlags *flags.GlobalFlags, + action lifecycleAction, + cobraCmd *cobra.Command, +) *cobra.Command { + cmd := &lifecycleCmd{GlobalFlags: globalFlags, action: action} + cobraCmd.Args = cobra.ExactArgs(1) + cobraCmd.RunE = func(c *cobra.Command, args []string) error { + cmd.Out = c.OutOrStdout() + return cmd.Run(c, args[0]) + } + return cobraCmd +} + +// Run sends the request and returns once the gateway has accepted it. +func (cmd *lifecycleCmd) Run(c *cobra.Command, name string) error { + target, err := resolveLifecycleTarget(cmd.GlobalFlags, cmd.Out) + if err != nil { + return err + } + return runPlatformLifecycle(c.Context(), target, cmd.action, []string{name}) +} + +// NewSleepCmd creates the `devsy workspace sleep` command, which asks the +// platform gateway to put a workspace to sleep. +func NewSleepCmd(globalFlags *flags.GlobalFlags) *cobra.Command { + return newLifecycleCobraCmd(globalFlags, sleepAction, &cobra.Command{ + Use: "sleep NAME", + Short: "Put a platform workspace to sleep", + Long: "Put a workspace on the platform gateway you are logged in to to sleep.\n\n" + + "The gateway accepts the request and the workspace scales down in the " + + "background, so it is not asleep when this command returns. " + + "Run 'devsy workspace list' to follow its phase.", + Example: " devsy workspace sleep my-workspace", + }) +} + +// NewWakeCmd creates the `devsy workspace wake` command, which asks the +// platform gateway to wake a sleeping workspace. +func NewWakeCmd(globalFlags *flags.GlobalFlags) *cobra.Command { + return newLifecycleCobraCmd(globalFlags, wakeAction, &cobra.Command{ + Use: "wake NAME", + Short: "Wake a sleeping platform workspace", + Long: "Wake a sleeping workspace on the platform gateway you are logged in to.\n\n" + + "The gateway accepts the request and the workspace starts in the " + + "background, so it is not running when this command returns. " + + "Run 'devsy workspace list' to follow its phase.", + Example: " devsy workspace wake my-workspace", + }) +} diff --git a/cmd/workspace/workspace.go b/cmd/workspace/workspace.go index 189b7ad12..aabef6419 100644 --- a/cmd/workspace/workspace.go +++ b/cmd/workspace/workspace.go @@ -20,6 +20,8 @@ func NewWorkspaceCmd(globalFlags *flags.GlobalFlags) *cobra.Command { cmd.AddCommand(NewExecCmd(globalFlags)) cmd.AddCommand(NewListCmd(globalFlags)) cmd.AddCommand(NewCreateCmd(globalFlags)) + cmd.AddCommand(NewSleepCmd(globalFlags)) + cmd.AddCommand(NewWakeCmd(globalFlags)) cmd.AddCommand(NewStatusCmd(globalFlags)) cmd.AddCommand(NewEventsCmd(globalFlags)) cmd.AddCommand(NewDescribeCmd(globalFlags)) diff --git a/hack/platform-e2e/workspace-sleep-wake-delete.sh b/hack/platform-e2e/workspace-sleep-wake-delete.sh new file mode 100755 index 000000000..fa32a07f0 --- /dev/null +++ b/hack/platform-e2e/workspace-sleep-wake-delete.sh @@ -0,0 +1,185 @@ +#!/usr/bin/env bash +# tuistory end-to-end check of `devsy workspace sleep|wake|delete` against a live +# platform gateway and controller (VAL-CLI-007, VAL-CLI-008). +# +# Every devsy command runs as a real terminal session driven by tuistory. The +# CLI never polls; this script does the waiting. +# +# Requires: tuistory, curl, jq, kubectl, a devsy binary, and a gateway plus +# controller running against the cluster in $KUBECONFIG_FILE. Evidence is written +# to $EVIDENCE_DIR. +# +# GATEWAY gateway URL (default http://localhost:8180) +# DEVSY_BIN devsy binary (default dist/devsy-e2e) +# TEMPLATE WorkspaceTemplate name (default smoke-template) +# KUBECONFIG_FILE kubeconfig of the k3d cluster (required) +# KUBE_CONTEXT kubectl context (default k3d-devsy) +# WS_NAMESPACE namespace of Workspace CRs (default default) +# RUNNING_WAIT seconds to reach Running (default 120) +# SLEEPING_WAIT seconds to reach Sleeping (default 60) +# DELETE_WAIT seconds for the CR to vanish (default 120) +set -euo pipefail + +GATEWAY="${GATEWAY:-http://localhost:8180}" +DEVSY_BIN="$(cd "$(dirname "${DEVSY_BIN:-dist/devsy-e2e}")" && pwd)/$(basename "${DEVSY_BIN:-dist/devsy-e2e}")" +TEMPLATE="${TEMPLATE:-smoke-template}" +KUBECONFIG_FILE="${KUBECONFIG_FILE:?set KUBECONFIG_FILE to the k3d kubeconfig}" +KUBE_CONTEXT="${KUBE_CONTEXT:-k3d-devsy}" +WS_NAMESPACE="${WS_NAMESPACE:-default}" +RUNNING_WAIT="${RUNNING_WAIT:-120}" +SLEEPING_WAIT="${SLEEPING_WAIT:-60}" +DELETE_WAIT="${DELETE_WAIT:-120}" +export PATH="$HOME/.bun/bin:$PATH" + +RUN="$(date +%s)-$RANDOM" +EVIDENCE_DIR="${EVIDENCE_DIR:-$(pwd)/dist/platform-e2e/sleep-wake-delete-$RUN}" +WORK="$(mktemp -d)" +SESSION_PREFIX="wssw-$RUN" +EMAIL="cli-sw-$RUN@example.test" +PASSWORD="pw-$RUN-$RANDOM$RANDOM" +WS_NAME="ws-sw-$RUN" +mkdir -p "$EVIDENCE_DIR" + +export DEVSY_HOME="$WORK/home" +mkdir -p "$DEVSY_HOME" + +fail() { echo "FAIL: $*" >&2; exit 1; } +log() { echo "[wssw] $*"; } +kc() { kubectl --kubeconfig "$KUBECONFIG_FILE" --context "$KUBE_CONTEXT" "$@"; } + +cleanup() { + local status=$? + tuistory -s "$SESSION_PREFIX-login" close >/dev/null 2>&1 || true + kc -n "$WS_NAMESPACE" delete workspace "$WS_NAME" --ignore-not-found --wait=false >/dev/null 2>&1 || true + rm -rf "$WORK" + return "$status" +} +trap cleanup EXIT + +# The runner prints the exit status on its own line so a transcript shows it. +RUNNER="$WORK/run.sh" +cat >"$RUNNER" <<'EOF' +#!/bin/sh +"$@" +echo "EXIT=$?" +EOF +chmod +x "$RUNNER" + +api() { curl -sS -H 'Content-Type: application/json' "$@"; } + +# tui NAME TIMEOUT_MS ARGS...: run devsy in a terminal, wait for EXIT=n, save the +# transcript to $EVIDENCE_DIR/NAME.txt, and set TUI_EXIT. +tui() { + local name="$1" timeout="$2" + shift 2 + local session="$SESSION_PREFIX-$name" + tuistory launch "$RUNNER $DEVSY_BIN $*" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout "$timeout" >/dev/null || + fail "$name: command did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/$name.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + TUI_EXIT="$(grep -Eo 'EXIT=[0-9]+' "$EVIDENCE_DIR/$name.txt" | tail -1 | cut -d= -f2)" +} + +# list_pairs FILE: print "name phase" lines from a plain list transcript. +list_pairs() { + awk 'NF == 2 && $1 != "NAME" && $1 !~ /^EXIT=/ {print $1, $2}' "$1" | sort +} + +# wait_list LABEL VAR SECONDS PATTERN: poll `devsy workspace list` until the row for +# $WS_NAME matches PATTERN ("Running", "Sleeping", or "-" for absent). VAR is set to +# the seconds it took. +wait_list() { + local label="$1" var="$2" limit="$3" want="$4" attempt=0 start=$SECONDS + while :; do + attempt=$((attempt + 1)) + tui "$label-$attempt" 30000 workspace list + [ "$TUI_EXIT" = 0 ] || fail "$label: list exited $TUI_EXIT" + local row + row="$(list_pairs "$EVIDENCE_DIR/$label-$attempt.txt" | awk -v n="$WS_NAME" '$1 == n {print $2}')" + if [ "$want" = "-" ]; then + [ -z "$row" ] && break + elif [ "$row" = "$want" ]; then + break + fi + [ $((SECONDS - start)) -lt "$limit" ] || + fail "$label: $WS_NAME is '${row:-absent}' after ${limit}s, wanted '$want'" + sleep 2 + done + printf -v "$var" '%s' "$((SECONDS - start))" +} + +log "creating test user and org ($EMAIL)" +api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" >/dev/null +TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" | jq -r .token)" +[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || fail "could not log in through the gateway" +api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $TOKEN" \ + -d "$(jq -n --arg n "Org $RUN" '{name: $n}')" >/dev/null + +log "devsy login (tuistory)" +LOGIN_SESSION="$SESSION_PREFIX-login" +tuistory launch "$RUNNER $DEVSY_BIN login $GATEWAY" -s "$LOGIN_SESSION" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Email' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$EMAIL" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Password' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$PASSWORD" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait '/EXIT=[0-9]+/' --timeout 30000 >/dev/null || fail "login did not finish" +tuistory -s "$LOGIN_SESSION" snapshot --trim >"$EVIDENCE_DIR/login.txt" +grep -q 'EXIT=0' "$EVIDENCE_DIR/login.txt" || fail "login failed: $(cat "$EVIDENCE_DIR/login.txt")" + +log "devsy workspace create $WS_NAME --template $TEMPLATE" +tui create 30000 workspace create "$WS_NAME" --template "$TEMPLATE" +[ "$TUI_EXIT" = 0 ] || fail "create exited $TUI_EXIT" +wait_list running-initial took "$RUNNING_WAIT" Running +log "$WS_NAME is Running after ${took}s" + +# VAL-CLI-007: sleep exits 0 and the list shows Sleeping within 60 seconds. +log "VAL-CLI-007: devsy workspace sleep $WS_NAME" +tui sleep 30000 workspace sleep "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-007: sleep exited $TUI_EXIT" +wait_list after-sleep took "$SLEEPING_WAIT" Sleeping +log "VAL-CLI-007: $WS_NAME is Sleeping after ${took}s (limit ${SLEEPING_WAIT}s)" + +# VAL-CLI-007: wake exits 0 and the list shows Running within 120 seconds. +log "VAL-CLI-007: devsy workspace wake $WS_NAME" +tui wake 30000 workspace wake "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-007: wake exited $TUI_EXIT" +wait_list after-wake took "$RUNNING_WAIT" Running +log "VAL-CLI-007: $WS_NAME is Running after ${took}s (limit ${RUNNING_WAIT}s)" + +# VAL-CLI-008: delete exits 0, the name leaves the list, and the CR is NotFound. +log "VAL-CLI-008: devsy workspace delete $WS_NAME" +tui delete 30000 workspace delete "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-008: delete exited $TUI_EXIT" +wait_list after-delete took "$DELETE_WAIT" - +log "VAL-CLI-008: $WS_NAME is gone from the list after ${took}s" + +start=$SECONDS +while :; do + if kc -n "$WS_NAMESPACE" get workspace "$WS_NAME" >"$EVIDENCE_DIR/kubectl-get.txt" 2>&1; then + [ $((SECONDS - start)) -lt "$DELETE_WAIT" ] || + fail "VAL-CLI-008: Workspace $WS_NAME still exists after ${DELETE_WAIT}s" + sleep 2 + else + grep -q NotFound "$EVIDENCE_DIR/kubectl-get.txt" || + fail "VAL-CLI-008: kubectl get failed without NotFound: $(cat "$EVIDENCE_DIR/kubectl-get.txt")" + break + fi +done +cat "$EVIDENCE_DIR/kubectl-get.txt" + +# A name that no longer exists is an error the CLI shows, with a non-zero exit. +tui delete-again 30000 workspace delete "$WS_NAME" +[ "$TUI_EXIT" != 0 ] || fail "deleting a missing workspace exited 0" +grep -q 'workspace not found' "$EVIDENCE_DIR/delete-again.txt" || + fail "missing-workspace error does not show the gateway message" + +grep -rEq 'dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+' "$EVIDENCE_DIR" && fail "transcript contains an API key" + +log "PASS VAL-CLI-007 VAL-CLI-008 (evidence: $EVIDENCE_DIR)" diff --git a/pkg/platformclient/client.go b/pkg/platformclient/client.go index bb374fad6..ecad722dd 100644 --- a/pkg/platformclient/client.go +++ b/pkg/platformclient/client.go @@ -171,6 +171,8 @@ type request struct { path string bearer string body any + // wantStatus, when set, makes any other 2xx answer an error. + wantStatus int } func (c *Client) do(ctx context.Context, r request, out any) error { @@ -185,6 +187,14 @@ func (c *Client) do(ctx context.Context, r request, out any) error { } defer func() { _ = resp.Body.Close() }() + if r.wantStatus != 0 && resp.StatusCode/100 == 2 && resp.StatusCode != r.wantStatus { + return &APIError{ + Status: resp.StatusCode, + Message: fmt.Sprintf( + "gateway answered %d, expected %d", resp.StatusCode, r.wantStatus, + ), + } + } return decodeResponse(resp, out) } diff --git a/pkg/platformclient/workspaces.go b/pkg/platformclient/workspaces.go index 010c0dc55..01a8184d7 100644 --- a/pkg/platformclient/workspaces.go +++ b/pkg/platformclient/workspaces.go @@ -4,6 +4,7 @@ import ( "context" "errors" "net/http" + "net/url" ) // Workspace is one workspace as the gateway reports it. Phase is read from the @@ -76,6 +77,51 @@ func (c *Client) CreateWorkspace( return out, nil } +// SleepWorkspace asks the gateway to put a workspace to sleep. The gateway +// answers 202 once the request is recorded; the phase changes later. +func (c *Client) SleepWorkspace(ctx context.Context, apiKey, name string) (Workspace, error) { + return c.lifecycle(ctx, request{ + method: http.MethodPost, + path: workspacePath(name) + "/sleep", + bearer: apiKey, + }) +} + +// WakeWorkspace asks the gateway to wake a sleeping workspace. The gateway +// answers 202 once the request is recorded; the phase changes later. +func (c *Client) WakeWorkspace(ctx context.Context, apiKey, name string) (Workspace, error) { + return c.lifecycle(ctx, request{ + method: http.MethodPost, + path: workspacePath(name) + "/wake", + bearer: apiKey, + }) +} + +// DeleteWorkspace asks the gateway to delete a workspace. The gateway answers +// 202 once the request is recorded; the workspace disappears later. +func (c *Client) DeleteWorkspace(ctx context.Context, apiKey, name string) (Workspace, error) { + return c.lifecycle(ctx, request{ + method: http.MethodDelete, + path: workspacePath(name), + bearer: apiKey, + }) +} + +func workspacePath(name string) string { + return "/v1/workspaces/" + url.PathEscape(name) +} + +// lifecycle sends a request that the gateway only accepts: anything but a 202 +// is an error. +func (c *Client) lifecycle(ctx context.Context, r request) (Workspace, error) { + r.wantStatus = http.StatusAccepted + var out Workspace + if err := c.doWithKey(ctx, r, &out); err != nil { + return Workspace{}, err + } + return out, nil +} + // doWithKey is do for calls authenticated by an API key. It names a rejected // key, which plain do cannot: login uses 401 for a wrong password. func (c *Client) doWithKey(ctx context.Context, r request, out any) error { diff --git a/pkg/platformclient/workspaces_test.go b/pkg/platformclient/workspaces_test.go index 2014266f7..595a98de3 100644 --- a/pkg/platformclient/workspaces_test.go +++ b/pkg/platformclient/workspaces_test.go @@ -138,6 +138,139 @@ func (s *WorkspacesSuite) TestOtherErrorsKeepTheGatewayMessage() { s.Equal("workspace already exists", err.Error()) } +type lifecycleCall func(*Client, context.Context, string, string) (Workspace, error) + +func lifecycleCalls() map[string]struct { + method, path string + call lifecycleCall +} { + return map[string]struct { + method, path string + call lifecycleCall + }{ + "sleep": { + http.MethodPost, "/v1/workspaces/" + wsTestName + "/sleep", + (*Client).SleepWorkspace, + }, + "wake": { + http.MethodPost, "/v1/workspaces/" + wsTestName + "/wake", + (*Client).WakeWorkspace, + }, + "delete": { + http.MethodDelete, "/v1/workspaces/" + wsTestName, + (*Client).DeleteWorkspace, + }, + } +} + +func (s *WorkspacesSuite) TestLifecycleCallsUseTheirRouteAndKeyAndAcceptA202() { + for name, tc := range lifecycleCalls() { + s.Run(name, func() { + var method, path, auth string + var body []byte + srv := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path, auth = r.Method, r.URL.Path, r.Header.Get("Authorization") + body, _ = io.ReadAll(r.Body) + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"name":"` + wsTestName + `","phase":"Deleting"}`)) + }), + ) + defer srv.Close() + + got, err := tc.call(New(srv.URL, nil), context.Background(), wsTestKey, wsTestName) + + s.Require().NoError(err) + s.Equal(tc.method, method) + s.Equal(tc.path, path) + s.Equal("Bearer "+wsTestKey, auth) + s.Empty(body) + s.Equal(Workspace{Name: wsTestName, Phase: "Deleting"}, got) + }) + } +} + +func (s *WorkspacesSuite) TestLifecycleCallsEscapeTheName() { + var rawPath string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rawPath = r.URL.EscapedPath() + w.WriteHeader(http.StatusAccepted) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).SleepWorkspace(context.Background(), wsTestKey, "a/b") + + s.Require().NoError(err) + s.Equal("/v1/workspaces/a%2Fb/sleep", rawPath) +} + +func (s *WorkspacesSuite) TestLifecycleCallsRejectASuccessThatIsNot202() { + for name, tc := range lifecycleCalls() { + s.Run(name, func() { + srv := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"` + wsTestName + `","phase":"Running"}`)) + }), + ) + defer srv.Close() + + _, err := tc.call(New(srv.URL, nil), context.Background(), wsTestKey, wsTestName) + + s.Require().Error(err) + s.Contains(err.Error(), "200") + }) + } +} + +func (s *WorkspacesSuite) TestLifecycleCallsKeepTheGatewayErrorMessage() { + cases := []struct { + status int + message string + want string + }{ + {http.StatusNotFound, "workspace not found", "workspace not found"}, + {http.StatusForbidden, "key lacks write scope", "permission denied: key lacks write scope"}, + {http.StatusUnauthorized, "invalid api key", "devsy login"}, + } + for name, tc := range lifecycleCalls() { + for _, c := range cases { + s.Run(name+"/"+http.StatusText(c.status), func() { + srv := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(c.status) + _, _ = w.Write( + []byte(`{"error":{"code":"x","message":"` + c.message + `"}}`), + ) + }), + ) + defer srv.Close() + + _, err := tc.call(New(srv.URL, nil), context.Background(), wsTestKey, wsTestName) + + s.Require().Error(err) + s.Contains(err.Error(), c.want) + s.NotContains(err.Error(), wsTestKey) + }) + } + } +} + +func (s *WorkspacesSuite) TestLifecycleCallsWithAnEmptyKeyFailBeforeCallingTheGateway() { + called := false + srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + called = true + })) + defer srv.Close() + + for _, tc := range lifecycleCalls() { + _, err := tc.call(New(srv.URL, nil), context.Background(), "", wsTestName) + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + } + s.False(called) +} + func (s *WorkspacesSuite) TestEmptyKeyFailsBeforeCallingTheGateway() { called := false srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { From 4dd0f528dfdaaf9f43447d118aa5ce8febfc16e1 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 18:37:14 -0600 Subject: [PATCH 4/9] feat(cli): state which scope a stored key lacks on a 403 A 403 from the platform gateway now reads "permission denied: the stored API key lacks write scope", naming read for GET calls and write for everything else, and the command exits non-zero. Adds the tuistory check for a read-only key creating a workspace (VAL-CLI-009). Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/root_test.go | 13 ++ cmd/workspace/platform_lifecycle_test.go | 5 +- cmd/workspace/platform_test.go | 15 ++ .../platform-e2e/workspace-readonly-denied.sh | 146 ++++++++++++++++++ pkg/platformclient/workspaces.go | 24 ++- pkg/platformclient/workspaces_test.go | 24 ++- 6 files changed, 217 insertions(+), 10 deletions(-) create mode 100755 hack/platform-e2e/workspace-readonly-denied.sh diff --git a/cmd/root_test.go b/cmd/root_test.go index 5b54f789b..62e4ce926 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -14,6 +14,7 @@ import ( devcconfig "github.com/devsy-org/devsy/pkg/devcontainer/config" "github.com/devsy-org/devsy/pkg/exitcode" "github.com/devsy-org/devsy/pkg/log" + "github.com/devsy-org/devsy/pkg/platformclient" "github.com/devsy-org/devsy/pkg/workspace" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -32,6 +33,18 @@ func TestExitCodeForError_GenericFailure(t *testing.T) { assert.Equal(t, exitcode.Failure, exitCodeForError(fmt.Errorf("boom"), true)) } +func TestExitCodeForError_PlatformPermissionDenied(t *testing.T) { + err := fmt.Errorf("creating workspace %q: %w", "ws-ro", &platformclient.PermissionError{ + Scope: "write", + Cause: &platformclient.APIError{Status: 403, Message: "insufficient scope"}, + }) + for _, machine := range []bool{false, true} { + assert.NotEqual(t, exitcode.Success, exitCodeForError(err, machine)) + assert.Equal(t, exitcode.Failure, exitCodeForError(err, machine)) + } + assert.Contains(t, clierr.Classify(err).Message, "stored API key lacks write scope") +} + func TestRenderCLIErrorRedactsEnvironmentSecrets(t *testing.T) { t.Setenv("DEVSY_ROOT_ERROR_SECRET", "root-error-secret-846302") r, w, err := os.Pipe() diff --git a/cmd/workspace/platform_lifecycle_test.go b/cmd/workspace/platform_lifecycle_test.go index 9a703be14..7d5622616 100644 --- a/cmd/workspace/platform_lifecycle_test.go +++ b/cmd/workspace/platform_lifecycle_test.go @@ -91,12 +91,13 @@ func (s *PlatformSuite) TestLifecycleCommandsShowThePermissionMessage() { s.SetupTest() s.login() s.gateway.status = http.StatusForbidden - s.gateway.message = "key lacks write scope" + s.gateway.message = "insufficient scope" err := s.run(tc, platName) s.Require().Error(err) - s.Contains(err.Error(), "permission denied: key lacks write scope") + s.Contains(err.Error(), "permission denied") + s.Contains(err.Error(), "stored API key lacks write scope") }) } } diff --git a/cmd/workspace/platform_test.go b/cmd/workspace/platform_test.go index 4bea70b59..d59a03f18 100644 --- a/cmd/workspace/platform_test.go +++ b/cmd/workspace/platform_test.go @@ -253,6 +253,21 @@ func (s *PlatformSuite) TestCreateUnauthorizedSuggestsLogin() { s.NotContains(err.Error(), platTestKey) } +func (s *PlatformSuite) TestCreateForbiddenStatesTheKeyLacksWriteScope() { + s.login() + s.gateway.status = http.StatusForbidden + s.gateway.message = "insufficient scope" + + err := s.create(platName, "--template", platTemplate) + + s.Require().Error(err) + s.Contains(err.Error(), "permission denied") + s.Contains(err.Error(), "stored API key lacks write scope") + s.Contains(err.Error(), "creating workspace") + s.NotContains(err.Error(), platTestKey) + s.NotContains(s.out.String(), "accepted", "a refused create prints no success line") +} + func (s *PlatformSuite) TestPlatformCredentialsOnlyForACompleteLogin() { s.Nil(platformCredentials(nil)) s.Nil(platformCredentials(&config.Config{})) diff --git a/hack/platform-e2e/workspace-readonly-denied.sh b/hack/platform-e2e/workspace-readonly-denied.sh new file mode 100755 index 000000000..16d4ecab4 --- /dev/null +++ b/hack/platform-e2e/workspace-readonly-denied.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +# tuistory end-to-end check that a read-only key cannot create a workspace +# through `devsy workspace create` (VAL-CLI-009). +# +# The CLI logs in through tuistory, then the stored key is replaced with a key +# created through the gateway with scopes [read]. Every devsy command runs as a +# real terminal session. Evidence is written to $EVIDENCE_DIR. +# +# Requires: tuistory, curl, jq, kubectl, a devsy binary, and a running gateway. +# +# GATEWAY gateway URL (default http://localhost:8180) +# DEVSY_BIN devsy binary (default dist/devsy-e2e) +# TEMPLATE WorkspaceTemplate name (default smoke-template) +# KUBECONFIG_FILE kubeconfig of the k3d cluster (required) +# KUBE_CONTEXT kubectl context (default k3d-devsy) +# WS_NAMESPACE namespace of Workspace CRs (default default) +set -euo pipefail + +GATEWAY="${GATEWAY:-http://localhost:8180}" +DEVSY_BIN="$(cd "$(dirname "${DEVSY_BIN:-dist/devsy-e2e}")" && pwd)/$(basename "${DEVSY_BIN:-dist/devsy-e2e}")" +TEMPLATE="${TEMPLATE:-smoke-template}" +KUBECONFIG_FILE="${KUBECONFIG_FILE:?set KUBECONFIG_FILE to the k3d kubeconfig}" +KUBE_CONTEXT="${KUBE_CONTEXT:-k3d-devsy}" +WS_NAMESPACE="${WS_NAMESPACE:-default}" +export PATH="$HOME/.bun/bin:$PATH" + +RUN="$(date +%s)-$RANDOM" +EVIDENCE_DIR="${EVIDENCE_DIR:-$(pwd)/dist/platform-e2e/readonly-denied-$RUN}" +WORK="$(mktemp -d)" +SESSION_PREFIX="wsro-$RUN" +EMAIL="cli-ro-$RUN@example.test" +PASSWORD="pw-$RUN-$RANDOM$RANDOM" +WS_NAME="ws-ro-$RUN" +mkdir -p "$EVIDENCE_DIR" + +export DEVSY_HOME="$WORK/home" +mkdir -p "$DEVSY_HOME" +CONFIG="$DEVSY_HOME/config.yaml" + +fail() { echo "FAIL: $*" >&2; exit 1; } +log() { echo "[wsro] $*"; } +kc() { kubectl --kubeconfig "$KUBECONFIG_FILE" --context "$KUBE_CONTEXT" "$@"; } + +cleanup() { + local status=$? + tuistory -s "$SESSION_PREFIX-login" close >/dev/null 2>&1 || true + kc -n "$WS_NAMESPACE" delete workspace "$WS_NAME" --ignore-not-found --wait=false >/dev/null 2>&1 || true + rm -rf "$WORK" + return "$status" +} +trap cleanup EXIT + +# The runner prints the exit status on its own line so a transcript shows it. +RUNNER="$WORK/run.sh" +cat >"$RUNNER" <<'EOF' +#!/bin/sh +"$@" +echo "EXIT=$?" +EOF +chmod +x "$RUNNER" + +api() { curl -sS -H 'Content-Type: application/json' "$@"; } + +# tui NAME TIMEOUT_MS ARGS...: run devsy in a terminal, wait for EXIT=n, save the +# transcript to $EVIDENCE_DIR/NAME.txt, and set TUI_EXIT. +tui() { + local name="$1" timeout="$2" + shift 2 + local session="$SESSION_PREFIX-$name" + tuistory launch "$RUNNER $DEVSY_BIN $*" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout "$timeout" >/dev/null || + fail "$name: command did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/$name.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + TUI_EXIT="$(grep -Eo 'EXIT=[0-9]+' "$EVIDENCE_DIR/$name.txt" | tail -1 | cut -d= -f2)" +} + +gateway_field() { + awk -v field="$1" '/^gateway:/ {g=1; next} g && $1 == field":" {gsub(/"/, "", $2); print $2; exit}' "$CONFIG" +} + +log "creating test user and org ($EMAIL)" +api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" >/dev/null +TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" | jq -r .token)" +[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || fail "could not log in through the gateway" +api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $TOKEN" \ + -d "$(jq -n --arg n "Org $RUN" '{name: $n}')" >/dev/null + +log "devsy login (tuistory)" +LOGIN_SESSION="$SESSION_PREFIX-login" +tuistory launch "$RUNNER $DEVSY_BIN login $GATEWAY" -s "$LOGIN_SESSION" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Email' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$EMAIL" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Password' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$PASSWORD" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait '/EXIT=[0-9]+/' --timeout 30000 >/dev/null || fail "login did not finish" +tuistory -s "$LOGIN_SESSION" snapshot --trim >"$EVIDENCE_DIR/login.txt" +grep -q 'EXIT=0' "$EVIDENCE_DIR/login.txt" || fail "login failed: $(cat "$EVIDENCE_DIR/login.txt")" + +ORG_ID="$(gateway_field orgId)" +[ -n "$ORG_ID" ] || fail "config has no orgId after login" + +log "creating a read-only key through the gateway (scopes [read])" +RO_KEY="$(api -X POST "$GATEWAY/v1/orgs/$ORG_ID/api-keys" -H "Authorization: Bearer $TOKEN" \ + -d '{"name":"cli-readonly","scopes":["read"]}' | jq -r .key)" +[ -n "$RO_KEY" ] && [ "$RO_KEY" != null ] || fail "could not create the read-only key" + +log "swapping the stored key for the read-only key" +# Rewrite in place so the file keeps its 0600 mode. +awk -v key="$RO_KEY" ' + /^gateway:/ {g=1} + g && /^ apiKey:/ {print " apiKey: " key; g=0; next} + {print} +' "$CONFIG" >"$WORK/config.swapped" +cat "$WORK/config.swapped" >"$CONFIG" +[ "$(gateway_field apiKey)" = "$RO_KEY" ] || fail "stored key was not swapped" + +log "the read-only key can still list" +tui list 30000 workspace list +[ "$TUI_EXIT" = 0 ] || fail "list with the read-only key exited $TUI_EXIT" + +log "VAL-CLI-009: devsy workspace create $WS_NAME --template $TEMPLATE with the read-only key" +tui create 30000 workspace create "$WS_NAME" --template "$TEMPLATE" +[ -n "$TUI_EXIT" ] && [ "$TUI_EXIT" != 0 ] || fail "VAL-CLI-009: create exited '${TUI_EXIT:-?}', expected non-zero" +grep -qi 'permission' "$EVIDENCE_DIR/create.txt" || + fail "VAL-CLI-009: create output has no permission error: $(cat "$EVIDENCE_DIR/create.txt")" +grep -q 'lacks write scope' "$EVIDENCE_DIR/create.txt" || + fail "VAL-CLI-009: create output does not say the key lacks write scope" +log "create exited $TUI_EXIT with a permission error" + +if kc -n "$WS_NAMESPACE" get workspace "$WS_NAME" >"$EVIDENCE_DIR/kubectl-get.txt" 2>&1; then + fail "VAL-CLI-009: Workspace $WS_NAME exists after a refused create" +fi +grep -q NotFound "$EVIDENCE_DIR/kubectl-get.txt" || + fail "VAL-CLI-009: kubectl get failed without NotFound: $(cat "$EVIDENCE_DIR/kubectl-get.txt")" +cat "$EVIDENCE_DIR/kubectl-get.txt" + +grep -rEq 'dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+' "$EVIDENCE_DIR" && fail "transcript contains an API key" + +log "PASS VAL-CLI-009 (evidence: $EVIDENCE_DIR)" diff --git a/pkg/platformclient/workspaces.go b/pkg/platformclient/workspaces.go index 01a8184d7..0175e061c 100644 --- a/pkg/platformclient/workspaces.go +++ b/pkg/platformclient/workspaces.go @@ -27,16 +27,21 @@ func (e *AuthError) Error() string { func (e *AuthError) Unwrap() error { return e.Cause } -// PermissionError is a 403 on a call made with a stored API key. +// PermissionError is a 403 on a call made with a stored API key. The gateway +// only answers 403 on these routes when the key lacks the scope the route +// needs, and its own message ("insufficient scope") does not say which one. type PermissionError struct { + // Scope is the scope the call needed: "read" or "write". + Scope string Cause *APIError } func (e *PermissionError) Error() string { - if e.Cause.Message == "" { - return "permission denied" + msg := "permission denied: the stored API key lacks " + e.Scope + " scope" + if e.Cause != nil && e.Cause.Message != "" { + msg += " (gateway: " + e.Cause.Message + ")" } - return "permission denied: " + e.Cause.Message + return msg } func (e *PermissionError) Unwrap() error { return e.Cause } @@ -137,8 +142,17 @@ func (c *Client) doWithKey(ctx context.Context, r request, out any) error { case http.StatusUnauthorized: return &AuthError{Cause: apiErr} case http.StatusForbidden: - return &PermissionError{Cause: apiErr} + return &PermissionError{Scope: scopeFor(r.method), Cause: apiErr} default: return err } } + +// scopeFor returns the scope the gateway requires for an HTTP method: reads +// need read, everything that changes a workspace needs write. +func scopeFor(method string) string { + if method == http.MethodGet || method == http.MethodHead { + return "read" + } + return "write" +} diff --git a/pkg/platformclient/workspaces_test.go b/pkg/platformclient/workspaces_test.go index 595a98de3..3f127e3e6 100644 --- a/pkg/platformclient/workspaces_test.go +++ b/pkg/platformclient/workspaces_test.go @@ -112,7 +112,7 @@ func (s *WorkspacesSuite) TestUnauthorizedSuggestsLogin() { func (s *WorkspacesSuite) TestForbiddenIsAPermissionError() { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"error":{"code":"forbidden","message":"key lacks write scope"}}`)) + _, _ = w.Write([]byte(`{"error":{"code":"forbidden","message":"insufficient scope"}}`)) })) defer srv.Close() @@ -120,11 +120,29 @@ func (s *WorkspacesSuite) TestForbiddenIsAPermissionError() { s.Require().Error(err) s.Contains(err.Error(), "permission denied") - s.Contains(err.Error(), "key lacks write scope") + s.Contains(err.Error(), "stored API key lacks write scope") + s.Contains(err.Error(), "insufficient scope") + s.NotContains(err.Error(), wsTestKey) + var permErr *PermissionError + s.Require().ErrorAs(err, &permErr) + s.Equal("write", permErr.Scope) var authErr *AuthError s.False(errors.As(err, &authErr), "a 403 is not an authentication failure") } +func (s *WorkspacesSuite) TestForbiddenListNamesTheReadScope() { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":{"code":"forbidden","message":"insufficient scope"}}`)) + })) + defer srv.Close() + + _, err := New(srv.URL, nil).ListWorkspaces(context.Background(), wsTestKey) + + s.Require().Error(err) + s.Contains(err.Error(), "stored API key lacks read scope") +} + func (s *WorkspacesSuite) TestOtherErrorsKeepTheGatewayMessage() { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusConflict) @@ -230,7 +248,7 @@ func (s *WorkspacesSuite) TestLifecycleCallsKeepTheGatewayErrorMessage() { want string }{ {http.StatusNotFound, "workspace not found", "workspace not found"}, - {http.StatusForbidden, "key lacks write scope", "permission denied: key lacks write scope"}, + {http.StatusForbidden, "insufficient scope", "stored API key lacks write scope"}, {http.StatusUnauthorized, "invalid api key", "devsy login"}, } for name, tc := range lifecycleCalls() { From 47793a9a311852ea8a9d974ca0fef268c60d5e73 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 18:51:37 -0600 Subject: [PATCH 5/9] feat(cli): add devsy logout that revokes the stored platform key `devsy logout` calls DELETE /v1/orgs/{org}/api-keys/{id} with the stored key as bearer. On 204 or 404 it clears the key, key ID and org from the config and keeps the gateway URL. Any other error exits non-zero and keeps the key. Because the URL stays, `devsy workspace list` now fails with an authentication error after logout instead of falling back to local workspaces; --skip-platform still lists local ones. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/logout/logout.go | 89 +++++++++ cmd/logout/logout_test.go | 285 ++++++++++++++++++++++++++++ cmd/root.go | 2 + cmd/workspace/list.go | 3 + cmd/workspace/platform.go | 11 +- cmd/workspace/platform_lifecycle.go | 6 + cmd/workspace/platform_test.go | 57 +++++- hack/platform-e2e/logout.sh | 148 +++++++++++++++ 8 files changed, 597 insertions(+), 4 deletions(-) create mode 100644 cmd/logout/logout.go create mode 100644 cmd/logout/logout_test.go create mode 100755 hack/platform-e2e/logout.sh diff --git a/cmd/logout/logout.go b/cmd/logout/logout.go new file mode 100644 index 000000000..95ab74cb6 --- /dev/null +++ b/cmd/logout/logout.go @@ -0,0 +1,89 @@ +// Package logout implements `devsy logout`, which revokes the stored platform +// API key and removes it from the devsy config. +package logout + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/platformclient" + "github.com/spf13/cobra" +) + +// NewLogoutCmd creates the `devsy logout` command. +func NewLogoutCmd() *cobra.Command { + return &cobra.Command{ + Use: "logout", + Short: "Log out of the Devsy platform gateway", + Long: "Log out of the Devsy platform gateway.\n\n" + + "Logout revokes the API key that `devsy login` stored, using the key itself, " + + "and then removes the key and org from the devsy config file. " + + "If the gateway cannot revoke the key, the key stays in the config " + + "so you can run logout again.", + Example: " devsy logout", + Args: cobra.NoArgs, + RunE: func(cobraCmd *cobra.Command, _ []string) error { + return run(cobraCmd.Context(), cobraCmd.OutOrStdout()) + }, + } +} + +func run(ctx context.Context, out io.Writer) error { + cfg, err := config.LoadConfig("", "") + if err != nil { + return err + } + creds := cfg.Gateway + if creds == nil || creds.APIKey == "" { + _, _ = fmt.Fprintln(out, "Not logged in to a platform gateway") + return nil + } + if err := revokeStoredKey(ctx, creds); err != nil { + return err + } + if err := clearLogin(creds); err != nil { + return fmt.Errorf("removing login from config: %w", err) + } + _, _ = fmt.Fprintf(out, "Logged out of %s\n", creds.URL) + return nil +} + +// revokeStoredKey revokes the key with itself as the bearer. A 404 means the +// key is already gone, which is the state logout wants. +func revokeStoredKey(ctx context.Context, creds *config.GatewayCredentials) error { + if creds.URL == "" || creds.OrgID == "" || creds.KeyRecordID == "" { + return errors.New( + "the stored login is incomplete and its key cannot be revoked; " + + "run 'devsy login' to replace it", + ) + } + client := platformclient.New(creds.URL, nil) + err := client.RevokeAPIKey(ctx, creds.APIKey, creds.OrgID, creds.KeyRecordID) + if err != nil && !alreadyRevoked(err) { + return fmt.Errorf("revoking API key at %s: %w", creds.URL, err) + } + return nil +} + +func alreadyRevoked(err error) bool { + var apiErr *platformclient.APIError + return errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound +} + +// clearLogin removes the key and org from the config but keeps the gateway URL, +// so commands can tell a logged-out user from one who never logged in. It does +// nothing when the config now holds a different key, because a login made since +// the revoke started must not be wiped. +func clearLogin(revoked *config.GatewayCredentials) error { + return config.UpdateConfig("", "", func(cfg *config.Config) error { + if cfg.Gateway == nil || cfg.Gateway.KeyRecordID != revoked.KeyRecordID { + return nil + } + cfg.Gateway = &config.GatewayCredentials{URL: cfg.Gateway.URL} + return nil + }) +} diff --git a/cmd/logout/logout_test.go b/cmd/logout/logout_test.go new file mode 100644 index 000000000..0da3eef19 --- /dev/null +++ b/cmd/logout/logout_test.go @@ -0,0 +1,285 @@ +package logout + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "regexp" + "sync" + "testing" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/stretchr/testify/suite" +) + +const ( + testKey = "test-api-key-placeholder" + testKeyID = "AbCdEfGh12345678" + testKeyRecID = "7d9f4c1e-0000-4000-8000-000000000001" + testOrgID = "org-1" + testOrgName = "Acme Labs" + + revokePath = "/v1/orgs/org-1/api-keys/" + testKeyRecID +) + +var keyPattern = regexp.MustCompile(`dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+`) + +type recordedCall struct { + Method, Path, Auth string +} + +// fakeGateway answers the revoke route with a configurable status. +type fakeGateway struct { + server *httptest.Server + + mu sync.Mutex + calls []recordedCall + status int +} + +func newFakeGateway() *fakeGateway { + g := &fakeGateway{status: http.StatusNoContent} + g.server = httptest.NewServer(http.HandlerFunc(g.handle)) + return g +} + +func (g *fakeGateway) handle(w http.ResponseWriter, r *http.Request) { + g.mu.Lock() + g.calls = append(g.calls, recordedCall{ + Method: r.Method, Path: r.URL.Path, Auth: r.Header.Get("Authorization"), + }) + status := g.status + g.mu.Unlock() + + if status == http.StatusNoContent { + w.WriteHeader(status) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{ + "error": map[string]string{"code": "error", "message": "gateway says no"}, + }) +} + +func (g *fakeGateway) recorded() []recordedCall { + g.mu.Lock() + defer g.mu.Unlock() + return append([]recordedCall(nil), g.calls...) +} + +type LogoutSuite struct { + suite.Suite + + gateway *fakeGateway + out *bytes.Buffer + errOut *bytes.Buffer +} + +func TestLogoutSuite(t *testing.T) { + suite.Run(t, new(LogoutSuite)) +} + +func (s *LogoutSuite) SetupTest() { + s.T().Setenv(config.EnvHome, s.T().TempDir()) + s.T().Setenv(config.EnvConfig, "") + config.ResetPathManager() + s.T().Cleanup(config.ResetPathManager) + + s.gateway = newFakeGateway() + s.T().Cleanup(s.gateway.server.Close) + s.out = &bytes.Buffer{} + s.errOut = &bytes.Buffer{} +} + +func (s *LogoutSuite) TestSuccessRevokesWithTheStoredKeyAndClearsTheLogin() { + s.login(s.gateway.server.URL) + + s.Require().NoError(s.run()) + + calls := s.gateway.recorded() + s.Require().Len(calls, 1) + s.Equal(http.MethodDelete, calls[0].Method) + s.Equal(revokePath, calls[0].Path) + s.Equal("Bearer "+testKey, calls[0].Auth) + s.assertLoggedOut() +} + +func (s *LogoutSuite) TestAlreadyRevokedKeyStillClearsTheLogin() { + s.login(s.gateway.server.URL) + s.gateway.status = http.StatusNotFound + + s.Require().NoError(s.run()) + + s.Len(s.gateway.recorded(), 1) + s.assertLoggedOut() +} + +func (s *LogoutSuite) TestOtherGatewayErrorsFailAndKeepTheKey() { + for _, status := range []int{ + http.StatusUnauthorized, + http.StatusForbidden, + http.StatusTooManyRequests, + http.StatusInternalServerError, + http.StatusServiceUnavailable, + } { + s.Run(http.StatusText(status), func() { + s.login(s.gateway.server.URL) + s.gateway.status = status + before := s.configBytes() + + err := s.run() + + s.Require().Error(err) + s.Contains(err.Error(), "revoking") + s.NotContains(err.Error(), testKey) + s.Equal(before, s.configBytes(), "a failed logout must not touch the config") + }) + } +} + +func (s *LogoutSuite) TestUnreachableGatewayFailsAndKeepsTheKey() { + s.login(s.gateway.server.URL) + s.gateway.server.Close() + before := s.configBytes() + + err := s.run() + + s.Require().Error(err) + s.NotContains(err.Error(), testKey) + s.Equal(before, s.configBytes()) +} + +func (s *LogoutSuite) TestKeyWithoutRecordIDCannotBeRevokedAndIsKept() { + s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway = &config.GatewayCredentials{ + URL: s.gateway.server.URL, OrgID: testOrgID, APIKey: testKey, + } + return nil + })) + before := s.configBytes() + + err := s.run() + + s.Require().Error(err) + s.Empty(s.gateway.recorded(), "nothing can be revoked without a key record ID") + s.Equal(before, s.configBytes()) +} + +func (s *LogoutSuite) TestWithoutALoginExitsCleanlyWithoutCallingTheGateway() { + s.Require().NoError(s.run()) + + s.Empty(s.gateway.recorded()) + s.Contains(s.out.String(), "Not logged in") +} + +func (s *LogoutSuite) TestLoggingOutTwiceIsHarmless() { + s.login(s.gateway.server.URL) + s.Require().NoError(s.run()) + s.out.Reset() + + s.Require().NoError(s.run()) + + s.Len(s.gateway.recorded(), 1, "the second logout has no key to revoke") + s.Contains(s.out.String(), "Not logged in") + s.assertLoggedOut() +} + +func (s *LogoutSuite) TestKeepsTheGatewayURLAsALoggedOutMarker() { + s.login(s.gateway.server.URL) + + s.Require().NoError(s.run()) + + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Require().NotNil(cfg.Gateway) + s.Equal(s.gateway.server.URL, cfg.Gateway.URL) +} + +func (s *LogoutSuite) TestLeavesANewerLoginUntouched() { + s.login(s.gateway.server.URL) + s.gateway.status = http.StatusNoContent + s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway.KeyRecordID = "rec-newer" + cfg.Gateway.APIKey = "newer-api-key-placeholder" + return nil + })) + + stale := &config.GatewayCredentials{ + URL: s.gateway.server.URL, OrgID: testOrgID, KeyRecordID: testKeyRecID, APIKey: testKey, + } + s.Require().NoError(clearLogin(stale)) + + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + s.Equal("rec-newer", cfg.Gateway.KeyRecordID) + s.Equal("newer-api-key-placeholder", cfg.Gateway.APIKey) +} + +func (s *LogoutSuite) TestNeverPrintsTheKey() { + s.login(s.gateway.server.URL) + s.Require().NoError(s.run()) + + combined := s.out.String() + s.errOut.String() + s.NotContains(combined, testKey) + s.False(keyPattern.MatchString(combined)) + s.Contains(combined, "Logged out") +} + +func (s *LogoutSuite) TestRejectsArguments() { + s.login(s.gateway.server.URL) + cmd := NewLogoutCmd() + cmd.SetOut(s.out) + cmd.SetErr(s.errOut) + cmd.SetArgs([]string{"extra"}) + + s.Require().Error(cmd.ExecuteContext(context.Background())) + s.Empty(s.gateway.recorded()) +} + +func (s *LogoutSuite) login(url string) { + s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway = &config.GatewayCredentials{ + URL: url, + OrgID: testOrgID, + OrgName: testOrgName, + KeyID: testKeyID, + KeyRecordID: testKeyRecID, + APIKey: testKey, + } + return nil + })) +} + +func (s *LogoutSuite) run() error { + cmd := NewLogoutCmd() + cmd.SetOut(s.out) + cmd.SetErr(s.errOut) + cmd.SetArgs(nil) + return cmd.ExecuteContext(context.Background()) +} + +func (s *LogoutSuite) configBytes() []byte { + path, err := config.GetConfigPath() + s.Require().NoError(err) + //nolint:gosec // path comes from config.GetConfigPath in a temp home + data, err := os.ReadFile(path) + s.Require().NoError(err) + return data +} + +func (s *LogoutSuite) assertLoggedOut() { + cfg, err := config.LoadConfig("", "") + s.Require().NoError(err) + if cfg.Gateway != nil { + s.Empty(cfg.Gateway.APIKey) + s.Empty(cfg.Gateway.KeyID) + s.Empty(cfg.Gateway.KeyRecordID) + s.Empty(cfg.Gateway.OrgID) + s.Empty(cfg.Gateway.OrgName) + } + s.NotContains(string(s.configBytes()), testKey) +} diff --git a/cmd/root.go b/cmd/root.go index 5a0baed40..beab14735 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -21,6 +21,7 @@ import ( "github.com/devsy-org/devsy/cmd/ide" cmdinternal "github.com/devsy-org/devsy/cmd/internal" "github.com/devsy-org/devsy/cmd/login" + "github.com/devsy-org/devsy/cmd/logout" "github.com/devsy-org/devsy/cmd/machine" "github.com/devsy-org/devsy/cmd/mcp" "github.com/devsy-org/devsy/cmd/pro" @@ -394,6 +395,7 @@ func registerSubcommands(rootCmd *cobra.Command, globalFlags *flags.GlobalFlags) feature.NewFeatureCmd(globalFlags), ide.NewIDECmd(globalFlags), login.NewLoginCmd(), + logout.NewLogoutCmd(), machine.NewMachineCmd(globalFlags), mcp.NewMCPCmd(globalFlags), provider.NewProviderCmd(globalFlags), diff --git a/cmd/workspace/list.go b/cmd/workspace/list.go index b4c41a006..99b503db3 100644 --- a/cmd/workspace/list.go +++ b/cmd/workspace/list.go @@ -74,6 +74,9 @@ func (cmd *ListCmd) Run(ctx context.Context) error { return err } + if !cmd.SkipPlatform && loggedOut(devsyConfig) { + return errLoggedOut + } if creds := cmd.gatewayLogin(devsyConfig); creds != nil { return listPlatformWorkspaces(ctx, cmd.writer(), creds, mode) } diff --git a/cmd/workspace/platform.go b/cmd/workspace/platform.go index e078cfc72..77246af49 100644 --- a/cmd/workspace/platform.go +++ b/cmd/workspace/platform.go @@ -14,8 +14,8 @@ import ( ) // platformCredentials returns the gateway login when the active config is a -// platform login, and nil otherwise. A login missing its URL or key is treated -// as no login, so a half-written config falls back to local workspaces. +// platform login, and nil otherwise. Callers that fall back to local +// workspaces on nil must check loggedOut first. func platformCredentials(cfg *config.Config) *config.GatewayCredentials { if cfg == nil || cfg.Gateway == nil || cfg.Gateway.URL == "" || cfg.Gateway.APIKey == "" { return nil @@ -23,6 +23,13 @@ func platformCredentials(cfg *config.Config) *config.GatewayCredentials { return cfg.Gateway } +// loggedOut reports whether the config holds a gateway URL but no key, which is +// what `devsy logout` leaves behind. Platform commands must refuse in that +// state instead of quietly falling back to local workspaces. +func loggedOut(cfg *config.Config) bool { + return cfg != nil && cfg.Gateway != nil && cfg.Gateway.URL != "" && cfg.Gateway.APIKey == "" +} + func newPlatformClient(creds *config.GatewayCredentials) *platformclient.Client { return platformclient.New(creds.URL, nil) } diff --git a/cmd/workspace/platform_lifecycle.go b/cmd/workspace/platform_lifecycle.go index 18c142fa6..3b0e47c15 100644 --- a/cmd/workspace/platform_lifecycle.go +++ b/cmd/workspace/platform_lifecycle.go @@ -46,6 +46,12 @@ var errNotLoggedIn = errors.New( "not logged in to a platform gateway: run 'devsy login ' first", ) +var errLoggedOut = errors.New( + "authentication required: you are logged out of the platform gateway; " + + "run 'devsy login ' to sign in again " + + "(use --skip-platform to list local workspaces)", +) + // lifecycleTarget is what a lifecycle request needs: the gateway login, where // to print, and how. type lifecycleTarget struct { diff --git a/cmd/workspace/platform_test.go b/cmd/workspace/platform_test.go index d59a03f18..5be36e89b 100644 --- a/cmd/workspace/platform_test.go +++ b/cmd/workspace/platform_test.go @@ -22,6 +22,7 @@ const ( platTemplate = "smoke-template" platName = "ws-one" platWsA = "ws-a" + urlX = "http://x" fieldName = "name" fieldPhase = "phase" @@ -271,13 +272,65 @@ func (s *PlatformSuite) TestCreateForbiddenStatesTheKeyLacksWriteScope() { func (s *PlatformSuite) TestPlatformCredentialsOnlyForACompleteLogin() { s.Nil(platformCredentials(nil)) s.Nil(platformCredentials(&config.Config{})) - s.Nil(platformCredentials(&config.Config{Gateway: &config.GatewayCredentials{URL: "http://x"}})) + s.Nil(platformCredentials(&config.Config{Gateway: &config.GatewayCredentials{URL: urlX}})) s.Nil(platformCredentials(&config.Config{Gateway: &config.GatewayCredentials{APIKey: "k"}})) - creds := &config.GatewayCredentials{URL: "http://x", APIKey: "k"} + creds := &config.GatewayCredentials{URL: urlX, APIKey: "k"} s.Same(creds, platformCredentials(&config.Config{Gateway: creds})) } +func (s *PlatformSuite) TestListAfterLogoutFailsWithAnAuthenticationError() { + s.loggedOut() + + err := s.list(output.ModePlain) + + s.Require().Error(err) + s.Contains(err.Error(), "authentication") + s.Contains(err.Error(), "devsy login") + s.Empty(s.gateway.recorded(), "a logged-out list must not call the gateway") +} + +func (s *PlatformSuite) TestListAfterLogoutWithSkipPlatformStaysLocal() { + s.loggedOut() + + s.Require().NoError(s.execute( + NewListCmd(&flags.GlobalFlags{ResultFormat: output.ModeJSON}), "--skip-platform", + )) + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestListWithoutAnyGatewayConfigStaysLocal() { + s.Require().NoError(s.list(output.ModeJSON)) + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestCreateAfterLogoutSuggestsLogin() { + s.loggedOut() + + err := s.create(platName, "--template", platTemplate) + + s.Require().Error(err) + s.Contains(err.Error(), "devsy login") + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestLoggedOutIsAGatewayURLWithoutAKey() { + s.False(loggedOut(nil)) + s.False(loggedOut(&config.Config{})) + s.False(loggedOut(&config.Config{Gateway: &config.GatewayCredentials{APIKey: "k"}})) + s.False(loggedOut(&config.Config{ + Gateway: &config.GatewayCredentials{URL: urlX, APIKey: "k"}, + })) + s.True(loggedOut(&config.Config{Gateway: &config.GatewayCredentials{URL: urlX}})) +} + +func (s *PlatformSuite) loggedOut() { + s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { + cfg.Gateway = &config.GatewayCredentials{URL: s.gateway.server.URL} + return nil + })) +} + func (s *PlatformSuite) login() { s.Require().NoError(config.UpdateConfig("", "", func(cfg *config.Config) error { cfg.Gateway = &config.GatewayCredentials{ diff --git a/hack/platform-e2e/logout.sh b/hack/platform-e2e/logout.sh new file mode 100755 index 000000000..bd7760681 --- /dev/null +++ b/hack/platform-e2e/logout.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# tuistory end-to-end check of `devsy logout` (VAL-CLI-010). +# +# The CLI logs in through tuistory, then `devsy logout` runs as a real terminal +# session. The check passes when logout exits 0, api_keys.revoked_at is set for +# the stored key, the config no longer holds the key, and `devsy workspace list` +# exits non-zero with an authentication error. Evidence is written to +# $EVIDENCE_DIR. +# +# Requires: tuistory, curl, jq, docker, a devsy binary, and a running gateway. +# +# GATEWAY gateway URL (default http://localhost:8180) +# DEVSY_BIN devsy binary (default dist/devsy-e2e) +# PG_CONTAINER Postgres container (default devsy-mission-pg) +set -euo pipefail + +GATEWAY="${GATEWAY:-http://localhost:8180}" +DEVSY_BIN="$(cd "$(dirname "${DEVSY_BIN:-dist/devsy-e2e}")" && pwd)/$(basename "${DEVSY_BIN:-dist/devsy-e2e}")" +PG_CONTAINER="${PG_CONTAINER:-devsy-mission-pg}" +export PATH="$HOME/.bun/bin:$PATH" + +RUN="$(date +%s)-$RANDOM" +EVIDENCE_DIR="${EVIDENCE_DIR:-$(pwd)/dist/platform-e2e/logout-$RUN}" +WORK="$(mktemp -d)" +SESSION_PREFIX="logout-$RUN" +EMAIL="cli-logout-$RUN@example.test" +PASSWORD="pw-$RUN-$RANDOM$RANDOM" +mkdir -p "$EVIDENCE_DIR" + +export DEVSY_HOME="$WORK/home" +mkdir -p "$DEVSY_HOME" +CONFIG="$DEVSY_HOME/config.yaml" + +fail() { echo "FAIL: $*" >&2; exit 1; } +log() { echo "[logout] $*"; } +psql_one() { + docker exec "$PG_CONTAINER" psql -U postgres -d devsy_platform -tA -c "$1" +} + +cleanup() { + local status=$? + tuistory -s "$SESSION_PREFIX-login" close >/dev/null 2>&1 || true + rm -rf "$WORK" + return "$status" +} +trap cleanup EXIT + +# The runner prints the exit status on its own line so a transcript shows it. +RUNNER="$WORK/run.sh" +cat >"$RUNNER" <<'EOF' +#!/bin/sh +"$@" +echo "EXIT=$?" +EOF +chmod +x "$RUNNER" + +api() { curl -sS -H 'Content-Type: application/json' "$@"; } + +# tui NAME TIMEOUT_MS ARGS...: run devsy in a terminal, wait for EXIT=n, save the +# transcript to $EVIDENCE_DIR/NAME.txt, and set TUI_EXIT. +tui() { + local name="$1" timeout="$2" + shift 2 + local session="$SESSION_PREFIX-$name" + tuistory launch "$RUNNER $DEVSY_BIN $*" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout "$timeout" >/dev/null || + fail "$name: command did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/$name.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + TUI_EXIT="$(grep -Eo 'EXIT=[0-9]+' "$EVIDENCE_DIR/$name.txt" | tail -1 | cut -d= -f2)" +} + +gateway_field() { + awk -v field="$1" '/^gateway:/ {g=1; next} g && $1 == field":" {gsub(/"/, "", $2); print $2; exit}' "$CONFIG" +} + +log "creating test user and org ($EMAIL)" +api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" >/dev/null +TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ + -d "$(jq -n --arg e "$EMAIL" --arg p "$PASSWORD" '{email: $e, password: $p}')" | jq -r .token)" +[ -n "$TOKEN" ] && [ "$TOKEN" != null ] || fail "could not log in through the gateway" +api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $TOKEN" \ + -d "$(jq -n --arg n "Org $RUN" '{name: $n}')" >/dev/null + +log "devsy login (tuistory)" +LOGIN_SESSION="$SESSION_PREFIX-login" +tuistory launch "$RUNNER $DEVSY_BIN login $GATEWAY" -s "$LOGIN_SESSION" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Email' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$EMAIL" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait 'Password' --timeout 15000 >/dev/null +tuistory -s "$LOGIN_SESSION" type "$PASSWORD" >/dev/null +tuistory -s "$LOGIN_SESSION" press enter >/dev/null +tuistory -s "$LOGIN_SESSION" wait '/EXIT=[0-9]+/' --timeout 30000 >/dev/null || fail "login did not finish" +tuistory -s "$LOGIN_SESSION" snapshot --trim >"$EVIDENCE_DIR/login.txt" +grep -q 'EXIT=0' "$EVIDENCE_DIR/login.txt" || fail "login failed: $(cat "$EVIDENCE_DIR/login.txt")" + +KEY_REC_ID="$(gateway_field keyRecordId)" +STORED_KEY="$(gateway_field apiKey)" +[ -n "$KEY_REC_ID" ] && [ -n "$STORED_KEY" ] || fail "config has no key after login" + +REVOKED_BEFORE="$(psql_one "select revoked_at is not null from api_keys where id = '$KEY_REC_ID'")" +[ "$REVOKED_BEFORE" = f ] || fail "key $KEY_REC_ID is not active before logout (revoked? '$REVOKED_BEFORE')" + +log "the stored key can list before logout" +tui list-before 30000 workspace list +[ "$TUI_EXIT" = 0 ] || fail "list before logout exited '${TUI_EXIT:-?}'" + +log "VAL-CLI-010: devsy logout" +tui logout 30000 logout +[ "$TUI_EXIT" = 0 ] || fail "VAL-CLI-010: logout exited '${TUI_EXIT:-?}': $(cat "$EVIDENCE_DIR/logout.txt")" + +REVOKED_AT="$(psql_one "select revoked_at from api_keys where id = '$KEY_REC_ID'")" +echo "api_keys.revoked_at = $REVOKED_AT" | tee "$EVIDENCE_DIR/psql-revoked-at.txt" +[ -n "$REVOKED_AT" ] || fail "VAL-CLI-010: api_keys.revoked_at is not set for $KEY_REC_ID" + +[ "$(stat -f '%Lp' "$CONFIG" 2>/dev/null || stat -c '%a' "$CONFIG")" = 600 ] || + fail "config mode is not 600 after logout" +grep -qF "$STORED_KEY" "$CONFIG" && fail "VAL-CLI-010: the key is still in the config" +[ -z "$(gateway_field apiKey)" ] || fail "VAL-CLI-010: config still has apiKey" +[ -z "$(gateway_field keyId)" ] || fail "VAL-CLI-010: config still has keyId" +[ -z "$(gateway_field keyRecordId)" ] || fail "VAL-CLI-010: config still has keyRecordId" +[ -z "$(gateway_field orgId)" ] || fail "VAL-CLI-010: config still has orgId" +log "config holds no key, key ID, or org" + +log "the revoked key is refused by the gateway" +CODE="$(curl -sS -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $STORED_KEY" "$GATEWAY/v1/workspaces")" +[ "$CODE" = 401 ] || fail "VAL-CLI-010: the revoked key got HTTP $CODE, expected 401" + +log "VAL-CLI-010: devsy workspace list after logout" +tui list-after 30000 workspace list +[ -n "$TUI_EXIT" ] && [ "$TUI_EXIT" != 0 ] || + fail "VAL-CLI-010: list after logout exited '${TUI_EXIT:-?}', expected non-zero" +grep -qi 'authentication' "$EVIDENCE_DIR/list-after.txt" || + fail "VAL-CLI-010: list output has no authentication error: $(cat "$EVIDENCE_DIR/list-after.txt")" + +log "logging out again is harmless" +tui logout-again 30000 logout +[ "$TUI_EXIT" = 0 ] || fail "second logout exited '${TUI_EXIT:-?}'" + +grep -rEq 'dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+' "$EVIDENCE_DIR" && fail "transcript contains an API key" +grep -rqF "$STORED_KEY" "$EVIDENCE_DIR" && fail "evidence contains the stored key" +grep -rqF "$PASSWORD" "$EVIDENCE_DIR" "$DEVSY_HOME" && fail "password found in evidence or config" + +log "PASS VAL-CLI-010 (evidence: $EVIDENCE_DIR)" From 7c0dcd482fda5c7c41d93df1247c4200a52c7c24 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 18:58:11 -0600 Subject: [PATCH 6/9] test(cli): add tuistory cross-org and full-lifecycle platform e2e cross-lifecycle.sh runs workspace create, sleep, wake and delete as an org A user and requires kubectl, GET /v1/workspaces and `devsy workspace list` to agree at every step (VAL-CROSS-001). cross-org-delete.sh checks that an org A CLI session cannot delete an org B workspace (VAL-CROSS-002). Both are run by the new cli:test:e2e:platform mise task. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- hack/platform-e2e/cross-lifecycle.sh | 91 ++++++++++++++ hack/platform-e2e/cross-org-delete.sh | 58 +++++++++ hack/platform-e2e/lib.sh | 174 ++++++++++++++++++++++++++ mise.toml | 13 ++ 4 files changed, 336 insertions(+) create mode 100755 hack/platform-e2e/cross-lifecycle.sh create mode 100755 hack/platform-e2e/cross-org-delete.sh create mode 100755 hack/platform-e2e/lib.sh diff --git a/hack/platform-e2e/cross-lifecycle.sh b/hack/platform-e2e/cross-lifecycle.sh new file mode 100755 index 000000000..eeb3bc8af --- /dev/null +++ b/hack/platform-e2e/cross-lifecycle.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# tuistory end-to-end check of the full CLI lifecycle against the real platform +# (VAL-CROSS-001). +# +# Logged in as an org A user, `devsy workspace create`, `sleep`, `wake` and +# `delete` run in sequence. Each command must exit 0. After each step the script +# waits for the expected state, then reads the state three ways (kubectl phase of +# the Workspace CR, GET /v1/workspaces on the gateway, and `devsy workspace list`) +# and requires all three to agree. The table of states per step goes to +# $EVIDENCE_DIR/state-table.txt. +# +# Requires: tuistory, curl, jq, kubectl, a devsy binary, and a gateway plus +# controller running against the cluster in $KUBECONFIG_FILE. See lib.sh for the +# environment variables. +# +# RUNNING_WAIT seconds to reach Running (default 120) +# SLEEPING_WAIT seconds to reach Sleeping (default 60) +# DELETE_WAIT seconds for the CR to vanish (default 120) +set -euo pipefail + +PREFIX=xlife +# shellcheck source=lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +RUNNING_WAIT="${RUNNING_WAIT:-120}" +SLEEPING_WAIT="${SLEEPING_WAIT:-60}" +DELETE_WAIT="${DELETE_WAIT:-120}" + +EMAIL="cli-xlife-$RUN@example.test" +PASSWORD="pw-$RUN-$RANDOM$RANDOM" +WS_NAME="ws-xlife-$RUN" +TABLE="$EVIDENCE_DIR/state-table.txt" +track_workspace "$WS_NAME" + +printf '%-10s %-8s %-9s %-9s %-9s %s\n' STEP EXIT KUBECTL GATEWAY CLI SECONDS >"$TABLE" + +# settle STEP EXIT WANT LIMIT: poll the three views until every one of them shows +# WANT ("Running", "Sleeping", or "absent"), then append a row to the state table. +# A step fails when the views never agree on WANT within LIMIT seconds. +settle() { + local step="$1" exit_code="$2" want="$3" limit="$4" attempt=0 start=$SECONDS + local kube gate cli + while :; do + attempt=$((attempt + 1)) + kube="$(kube_phase "$WS_NAME")" + gate="$(gateway_phase "$KEY" "$WS_NAME")" + cli="$(cli_phase "$step-list-$attempt" "$WS_NAME")" + if [ "$kube" = "$want" ] && [ "$gate" = "$want" ] && [ "$cli" = "$want" ]; then + break + fi + [ $((SECONDS - start)) -lt "$limit" ] || + fail "$step: states never agreed on '$want' within ${limit}s (kubectl=$kube gateway=$gate cli=$cli)" + sleep 2 + done + printf '%-10s %-8s %-9s %-9s %-9s %s\n' "$step" "$exit_code" "$kube" "$gate" "$cli" \ + "$((SECONDS - start))" >>"$TABLE" + log "$step: kubectl=$kube gateway=$gate cli=$cli (agreed after $((SECONDS - start))s)" +} + +log "creating org A user ($EMAIL)" +signup_user "$EMAIL" "$PASSWORD" "Org A $RUN" +log "devsy login (tuistory)" +cli_login "$EMAIL" "$PASSWORD" +KEY="$(config_gateway_field apiKey)" +[ -n "$KEY" ] || fail "config has no apiKey after login" + +log "devsy workspace create $WS_NAME --template $TEMPLATE" +tui create 30000 workspace create "$WS_NAME" --template "$TEMPLATE" +[ "$TUI_EXIT" = 0 ] || fail "create exited '${TUI_EXIT:-?}'" +settle create "$TUI_EXIT" Running "$RUNNING_WAIT" + +log "devsy workspace sleep $WS_NAME" +tui sleep 30000 workspace sleep "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "sleep exited '${TUI_EXIT:-?}'" +settle sleep "$TUI_EXIT" Sleeping "$SLEEPING_WAIT" + +log "devsy workspace wake $WS_NAME" +tui wake 30000 workspace wake "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "wake exited '${TUI_EXIT:-?}'" +settle wake "$TUI_EXIT" Running "$RUNNING_WAIT" + +log "devsy workspace delete $WS_NAME" +tui delete 30000 workspace delete "$WS_NAME" +[ "$TUI_EXIT" = 0 ] || fail "delete exited '${TUI_EXIT:-?}'" +settle delete "$TUI_EXIT" absent "$DELETE_WAIT" + +no_key_in_evidence + +echo +cat "$TABLE" +log "PASS VAL-CROSS-001 (evidence: $EVIDENCE_DIR)" diff --git a/hack/platform-e2e/cross-org-delete.sh b/hack/platform-e2e/cross-org-delete.sh new file mode 100755 index 000000000..f5b85fbf6 --- /dev/null +++ b/hack/platform-e2e/cross-org-delete.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# tuistory end-to-end check that a CLI session for org A cannot delete an org B +# workspace (VAL-CROSS-002). +# +# W_B is created in org B straight through the gateway. The CLI is logged in to +# org A and runs `devsy workspace delete W_B`. The command must exit non-zero, +# W_B must still exist on the cluster (and not be terminating), and org B must +# still see it through the gateway. +# +# Requires: tuistory, curl, jq, kubectl, a devsy binary, and a running gateway +# and controller. See lib.sh for the environment variables. +set -euo pipefail + +PREFIX=xorg +# shellcheck source=lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +EMAIL_A="cli-xorg-a-$RUN@example.test" +EMAIL_B="cli-xorg-b-$RUN@example.test" +PASSWORD_A="pw-a-$RUN-$RANDOM$RANDOM" +PASSWORD_B="pw-b-$RUN-$RANDOM$RANDOM" +W_B="ws-xorg-b-$RUN" + +log "creating org B user ($EMAIL_B) and workspace $W_B" +signup_user "$EMAIL_B" "$PASSWORD_B" "Org B $RUN" +create_org_workspace "$SESSION_TOKEN" "$ORG_ID" "$W_B" +KEY_B="$ORG_KEY" + +log "creating org A user ($EMAIL_A)" +signup_user "$EMAIL_A" "$PASSWORD_A" "Org A $RUN" +log "devsy login to org A (tuistory)" +cli_login "$EMAIL_A" "$PASSWORD_A" + +kc -n "$WS_NAMESPACE" get workspace "$W_B" >"$EVIDENCE_DIR/kubectl-before.txt" 2>&1 || + fail "$W_B does not exist before the delete: $(cat "$EVIDENCE_DIR/kubectl-before.txt")" + +log "VAL-CROSS-002: devsy workspace delete $W_B as an org A user" +tui delete 30000 workspace delete "$W_B" +[ -n "$TUI_EXIT" ] && [ "$TUI_EXIT" != 0 ] || + fail "VAL-CROSS-002: delete of $W_B exited '${TUI_EXIT:-?}', expected non-zero" +log "delete exited $TUI_EXIT" + +kc -n "$WS_NAMESPACE" get workspace "$W_B" >"$EVIDENCE_DIR/kubectl-after.txt" 2>&1 || + fail "VAL-CROSS-002: $W_B is gone after the refused delete: $(cat "$EVIDENCE_DIR/kubectl-after.txt")" +cat "$EVIDENCE_DIR/kubectl-after.txt" + +DELETION_TS="$(kc -n "$WS_NAMESPACE" get workspace "$W_B" -o jsonpath='{.metadata.deletionTimestamp}')" +[ -z "$DELETION_TS" ] || fail "VAL-CROSS-002: $W_B is terminating (deletionTimestamp $DELETION_TS)" + +# The refusal must not have changed anything org B can see. +PHASE_B="$(gateway_phase "$KEY_B" "$W_B")" +[ "$PHASE_B" != absent ] && [ "$PHASE_B" != Deleting ] || + fail "VAL-CROSS-002: org B sees $W_B as '$PHASE_B' after the refused delete" +log "org B still sees $W_B (phase $PHASE_B)" + +no_key_in_evidence + +log "PASS VAL-CROSS-002 (evidence: $EVIDENCE_DIR)" diff --git a/hack/platform-e2e/lib.sh b/hack/platform-e2e/lib.sh new file mode 100755 index 000000000..3c2e9ee8a --- /dev/null +++ b/hack/platform-e2e/lib.sh @@ -0,0 +1,174 @@ +#!/usr/bin/env bash +# Shared helpers for the tuistory platform e2e scripts that need two orgs. Source +# this file; it does not run anything by itself. +# +# Every devsy command runs as a real terminal session driven by tuistory. The +# caller must set PREFIX (short script tag) before sourcing. +# +# GATEWAY gateway URL (default http://localhost:8180) +# DEVSY_BIN devsy binary (default dist/devsy-e2e) +# TEMPLATE WorkspaceTemplate name (default smoke-template) +# KUBECONFIG_FILE kubeconfig of the k3d cluster (required) +# KUBE_CONTEXT kubectl context (default k3d-devsy) +# WS_NAMESPACE namespace of Workspace CRs (default default) +# EVIDENCE_DIR transcript directory (default dist/platform-e2e/-) + +: "${PREFIX:?set PREFIX before sourcing lib.sh}" + +GATEWAY="${GATEWAY:-http://localhost:8180}" +DEVSY_BIN="$(cd "$(dirname "${DEVSY_BIN:-dist/devsy-e2e}")" && pwd)/$(basename "${DEVSY_BIN:-dist/devsy-e2e}")" +TEMPLATE="${TEMPLATE:-smoke-template}" +KUBECONFIG_FILE="${KUBECONFIG_FILE:?set KUBECONFIG_FILE to the k3d kubeconfig}" +KUBE_CONTEXT="${KUBE_CONTEXT:-k3d-devsy}" +WS_NAMESPACE="${WS_NAMESPACE:-default}" +export PATH="$HOME/.bun/bin:$PATH" + +RUN="$(date +%s)-$RANDOM" +EVIDENCE_DIR="${EVIDENCE_DIR:-$(pwd)/dist/platform-e2e/$PREFIX-$RUN}" +WORK="$(mktemp -d)" +SESSION_PREFIX="$PREFIX-$RUN" +mkdir -p "$EVIDENCE_DIR" + +export DEVSY_HOME="$WORK/home" +mkdir -p "$DEVSY_HOME" +CONFIG="$DEVSY_HOME/config.yaml" + +fail() { echo "FAIL: $*" >&2; exit 1; } +log() { echo "[$PREFIX] $*"; } +kc() { kubectl --kubeconfig "$KUBECONFIG_FILE" --context "$KUBE_CONTEXT" "$@"; } +api() { curl -sS -H 'Content-Type: application/json' "$@"; } + +# Workspaces to remove on exit; scripts append with track_workspace. +TRACKED_WORKSPACES=() +track_workspace() { TRACKED_WORKSPACES+=("$1"); } + +cleanup() { + local status=$? + tuistory -s "$SESSION_PREFIX-login" close >/dev/null 2>&1 || true + local ws + for ws in ${TRACKED_WORKSPACES[@]+"${TRACKED_WORKSPACES[@]}"}; do + kc -n "$WS_NAMESPACE" delete workspace "$ws" --ignore-not-found --wait=false >/dev/null 2>&1 || true + done + rm -rf "$WORK" + return "$status" +} +trap cleanup EXIT + +# The runner prints the exit status on its own line so a transcript shows it. +RUNNER="$WORK/run.sh" +cat >"$RUNNER" <<'EOF' +#!/bin/sh +"$@" +echo "EXIT=$?" +EOF +chmod +x "$RUNNER" + +# tui NAME TIMEOUT_MS ARGS...: run devsy in a terminal, wait for EXIT=n, save the +# transcript to $EVIDENCE_DIR/NAME.txt, and set TUI_EXIT. +tui() { + local name="$1" timeout="$2" + shift 2 + local session="$SESSION_PREFIX-$name" + tuistory launch "$RUNNER $DEVSY_BIN $*" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout "$timeout" >/dev/null || + fail "$name: command did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/$name.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + TUI_EXIT="$(grep -Eo 'EXIT=[0-9]+' "$EVIDENCE_DIR/$name.txt" | tail -1 | cut -d= -f2)" +} + +# list_pairs FILE: print "name phase" lines from a plain list transcript. +list_pairs() { + awk 'NF == 2 && $1 != "NAME" && $1 !~ /^EXIT=/ {print $1, $2}' "$1" | sort +} + +# signup_user EMAIL PASSWORD ORG_NAME: sign up, log in through the gateway, create +# an org, and set SESSION_TOKEN and ORG_ID. +signup_user() { + local email="$1" password="$2" org_name="$3" + api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$email" --arg p "$password" '{email: $e, password: $p}')" >/dev/null + SESSION_TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ + -d "$(jq -n --arg e "$email" --arg p "$password" '{email: $e, password: $p}')" | jq -r .token)" + [ -n "$SESSION_TOKEN" ] && [ "$SESSION_TOKEN" != null ] || fail "could not log in $email through the gateway" + ORG_ID="$(api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $SESSION_TOKEN" \ + -d "$(jq -n --arg n "$org_name" '{name: $n}')" | jq -r .id)" + [ -n "$ORG_ID" ] && [ "$ORG_ID" != null ] || fail "could not create org $org_name" +} + +# cli_login EMAIL PASSWORD: devsy login against the gateway in a tuistory session. +cli_login() { + local email="$1" password="$2" + local session="$SESSION_PREFIX-login" + tuistory launch "$RUNNER $DEVSY_BIN login $GATEWAY" -s "$session" --cols 200 --rows 40 \ + --env "DEVSY_HOME=$DEVSY_HOME" --env NO_COLOR=1 >/dev/null + tuistory -s "$session" wait 'Email' --timeout 15000 >/dev/null + tuistory -s "$session" type "$email" >/dev/null + tuistory -s "$session" press enter >/dev/null + tuistory -s "$session" wait 'Password' --timeout 15000 >/dev/null + tuistory -s "$session" type "$password" >/dev/null + tuistory -s "$session" press enter >/dev/null + tuistory -s "$session" wait '/EXIT=[0-9]+/' --timeout 30000 >/dev/null || fail "login did not finish" + tuistory -s "$session" snapshot --trim >"$EVIDENCE_DIR/login.txt" + tuistory -s "$session" close >/dev/null 2>&1 || true + grep -q 'EXIT=0' "$EVIDENCE_DIR/login.txt" || fail "login failed: $(cat "$EVIDENCE_DIR/login.txt")" +} + +# config_gateway_field FIELD: read a field of the gateway block of the devsy config. +config_gateway_field() { + awk -v field="$1" '/^gateway:/ {g=1; next} g && $1 == field":" {gsub(/"/, "", $2); print $2; exit}' "$CONFIG" +} + +# kube_phase NAME: the Workspace CR phase, or "absent" when the CR is NotFound. +kube_phase() { + local out + if out="$(kc -n "$WS_NAMESPACE" get workspace "$1" -o jsonpath='{.status.phase}' 2>&1)"; then + echo "${out:-Pending}" + elif grep -q NotFound <<<"$out"; then + echo absent + else + fail "kubectl get workspace $1: $out" + fi +} + +# gateway_phase KEY NAME: the phase GET /v1/workspaces shows for NAME, or "absent". +gateway_phase() { + local body phase + body="$(curl -sS -H "Authorization: Bearer $1" "$GATEWAY/v1/workspaces")" + phase="$(jq -r --arg n "$2" '[.[] | select(.name == $n) | .phase][0] // "absent"' <<<"$body")" || + fail "GET /v1/workspaces returned a non-list body" + echo "$phase" +} + +# cli_phase LABEL NAME: the phase `devsy workspace list` shows for NAME, or "absent". +cli_phase() { + tui "$1" 30000 workspace list + [ "$TUI_EXIT" = 0 ] || fail "$1: workspace list exited $TUI_EXIT" + list_pairs "$EVIDENCE_DIR/$1.txt" | awk -v n="$2" '$1 == n {found=$2} END {print found ? found : "absent"}' +} + +# create_org_workspace SESSION_TOKEN ORG_ID NAME: create a workspace in an org +# straight through the gateway with a throwaway read+write key, and set +# ORG_KEY_ID to that key's record id. +create_org_workspace() { + local token="$1" org="$2" name="$3" key + key="$(api -X POST "$GATEWAY/v1/orgs/$org/api-keys" -H "Authorization: Bearer $token" \ + -d '{"name":"e2e-seed","scopes":["read","write"]}')" + ORG_KEY="$(jq -r .key <<<"$key")" + ORG_KEY_ID="$(jq -r .id <<<"$key")" + [ -n "$ORG_KEY" ] && [ "$ORG_KEY" != null ] || fail "could not create an api key for org $org" + local code + code="$(api -o "$EVIDENCE_DIR/seed-$name.json" -w '%{http_code}' -X POST "$GATEWAY/v1/workspaces" \ + -H "Authorization: Bearer $ORG_KEY" \ + -d "$(jq -n --arg n "$name" --arg t "$TEMPLATE" '{name: $n, template: $t}')")" + [ "$code" = 202 ] || fail "seeding workspace $name returned $code" + track_workspace "$name" +} + +# no_key_in_evidence: fail when any transcript holds something shaped like an API key. +no_key_in_evidence() { + if grep -rEq 'dvsy_[A-Za-z0-9]+_[A-Za-z0-9_-]+' "$EVIDENCE_DIR"; then + fail "transcript contains an API key" + fi +} diff --git a/mise.toml b/mise.toml index 94780afa6..7261a58b1 100644 --- a/mise.toml +++ b/mise.toml @@ -169,6 +169,19 @@ depends = ["cli:test:e2e:build"] dir = "e2e" run = 'go tool ginkgo --focus "$usage_pattern"' +[tasks."cli:test:e2e:platform"] +description = "run the tuistory platform e2e scenarios (VAL-CROSS-001, VAL-CROSS-002); needs a live gateway, controller and KUBECONFIG_FILE" +shell = "bash -c" +run = ''' +set -euo pipefail +: "${KUBECONFIG_FILE:?set KUBECONFIG_FILE to the k3d kubeconfig}" +mkdir -p dist +go build -o dist/devsy-e2e . +for script in cross-lifecycle cross-org-delete; do + "hack/platform-e2e/${script}.sh" +done +''' + [tasks."cli:test:e2e:kind:setup"] description = "setup kind cluster for e2e tests" run = ''' From a3b3c832d7d3b4f89581678541e54294857a6e83 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 19:01:43 -0600 Subject: [PATCH 7/9] test(cli): add tuistory access-revocation e2e for member removal and key revoke access-revocation.sh logs a user in with devsy, removes them through DELETE /v1/orgs/{org}/members/{user} (204) and requires the next `devsy workspace list` to exit non-zero with an authentication error (VAL-CROSS-003). A second login's key is revoked through DELETE /v1/orgs/{org}/api-keys/{id} (204) and the next list must exit non-zero with the `devsy login` hint (VAL-CROSS-004). Both run in the cli:test:e2e:platform mise task. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- hack/platform-e2e/access-revocation.sh | 117 +++++++++++++++++++++++++ hack/platform-e2e/lib.sh | 20 +++-- mise.toml | 4 +- 3 files changed, 133 insertions(+), 8 deletions(-) create mode 100755 hack/platform-e2e/access-revocation.sh diff --git a/hack/platform-e2e/access-revocation.sh b/hack/platform-e2e/access-revocation.sh new file mode 100755 index 000000000..c5360c370 --- /dev/null +++ b/hack/platform-e2e/access-revocation.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +# tuistory end-to-end checks that the CLI loses access as soon as its credential +# is cut off on the platform. +# +# VAL-CROSS-003: user B joins org A and logs in with `devsy login`. The org A +# owner removes B through DELETE /v1/orgs/{org}/members/{user} (204). B's next +# `devsy workspace list` must exit non-zero with an authentication or permission +# error. +# +# VAL-CROSS-004: a second CLI session logs in with key K. The owner revokes K +# through DELETE /v1/orgs/{org}/api-keys/{id} (204). The next +# `devsy workspace list` must exit non-zero with the re-login hint. +# +# Each scenario runs `devsy workspace list` first and requires exit 0, so a +# failure afterwards cannot come from a broken setup. +# +# Requires: tuistory, curl, jq, kubectl, a devsy binary, and a running gateway. +# See lib.sh for the environment variables. +set -euo pipefail + +PREFIX=xrevoke +# shellcheck source=lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +PASSWORD_OWNER="pw-owner-$RUN-$RANDOM$RANDOM" +PASSWORD_B="pw-b-$RUN-$RANDOM$RANDOM" +PASSWORD_C="pw-c-$RUN-$RANDOM$RANDOM" +EMAIL_OWNER="cli-xrevoke-owner-$RUN@example.test" +EMAIL_B="cli-xrevoke-b-$RUN@example.test" +EMAIL_C="cli-xrevoke-c-$RUN@example.test" + +# expect_refused NAME LABEL: the transcript NAME must show a non-zero exit and an +# authentication or permission error that points at `devsy login` or names the +# denied permission. +expect_refused() { + local name="$1" label="$2" + [ -n "$TUI_EXIT" ] && [ "$TUI_EXIT" != 0 ] || + fail "$label: devsy workspace list exited '${TUI_EXIT:-?}', expected non-zero: $(cat "$EVIDENCE_DIR/$name.txt")" + grep -Eqi 'authentication|permission denied' "$EVIDENCE_DIR/$name.txt" || + fail "$label: output has no authentication or permission error: $(cat "$EVIDENCE_DIR/$name.txt")" + log "$label: exit $TUI_EXIT with an authentication or permission error" +} + +# add_member ORG OWNER_TOKEN EMAIL: add an existing user to the org as an admin. +# Only owners and admins can mint the API key that `devsy login` creates. +add_member() { + local code + code="$(api -o "$EVIDENCE_DIR/add-member.json" -w '%{http_code}' -X POST "$GATEWAY/v1/orgs/$1/members" \ + -H "Authorization: Bearer $2" -d "$(jq -n --arg e "$3" '{email: $e, role: "admin"}')")" + [ "$code" = 201 ] || fail "adding $3 to org $1 returned $code: $(cat "$EVIDENCE_DIR/add-member.json")" +} + +log "creating the org A owner ($EMAIL_OWNER)" +signup_user "$EMAIL_OWNER" "$PASSWORD_OWNER" "Org A $RUN" +OWNER_TOKEN="$SESSION_TOKEN" +ORG_A="$ORG_ID" + +# --- VAL-CROSS-003 --------------------------------------------------------- + +log "creating user B ($EMAIL_B) and adding it to org A" +register_user "$EMAIL_B" "$PASSWORD_B" +USER_B="$USER_ID" +add_member "$ORG_A" "$OWNER_TOKEN" "$EMAIL_B" + +log "devsy login as B (tuistory)" +cli_login "$EMAIL_B" "$PASSWORD_B" +mv "$EVIDENCE_DIR/login.txt" "$EVIDENCE_DIR/login-b.txt" + +tui b-list-before 30000 workspace list +[ "$TUI_EXIT" = 0 ] || fail "B's list before removal exited '${TUI_EXIT:-?}': $(cat "$EVIDENCE_DIR/b-list-before.txt")" + +log "VAL-CROSS-003: the owner removes B" +CODE="$(api -o /dev/null -w '%{http_code}' -X DELETE "$GATEWAY/v1/orgs/$ORG_A/members/$USER_B" \ + -H "Authorization: Bearer $OWNER_TOKEN")" +echo "DELETE /v1/orgs/$ORG_A/members/$USER_B -> $CODE" | tee "$EVIDENCE_DIR/remove-member.txt" +[ "$CODE" = 204 ] || fail "VAL-CROSS-003: removing B returned $CODE, expected 204" + +tui b-list-after 30000 workspace list +expect_refused b-list-after "VAL-CROSS-003" + +# --- VAL-CROSS-004 --------------------------------------------------------- + +log "creating user C ($EMAIL_C) and adding it to org A" +register_user "$EMAIL_C" "$PASSWORD_C" +add_member "$ORG_A" "$OWNER_TOKEN" "$EMAIL_C" + +# Start a fresh CLI home so C's key K is the only credential on disk. +export DEVSY_HOME="$WORK/home-c" +mkdir -p "$DEVSY_HOME" +CONFIG="$DEVSY_HOME/config.yaml" + +log "devsy login as C with key K (tuistory)" +cli_login "$EMAIL_C" "$PASSWORD_C" +mv "$EVIDENCE_DIR/login.txt" "$EVIDENCE_DIR/login-c.txt" +KEY_REC_ID="$(config_gateway_field keyRecordId)" +STORED_KEY="$(config_gateway_field apiKey)" +[ -n "$KEY_REC_ID" ] && [ -n "$STORED_KEY" ] || fail "config has no key after C's login" + +tui k-list-before 30000 workspace list +[ "$TUI_EXIT" = 0 ] || fail "list with K before revocation exited '${TUI_EXIT:-?}': $(cat "$EVIDENCE_DIR/k-list-before.txt")" + +log "VAL-CROSS-004: the owner revokes K ($KEY_REC_ID)" +CODE="$(api -o /dev/null -w '%{http_code}' -X DELETE "$GATEWAY/v1/orgs/$ORG_A/api-keys/$KEY_REC_ID" \ + -H "Authorization: Bearer $OWNER_TOKEN")" +echo "DELETE /v1/orgs/$ORG_A/api-keys/$KEY_REC_ID -> $CODE" | tee "$EVIDENCE_DIR/revoke-key.txt" +[ "$CODE" = 204 ] || fail "VAL-CROSS-004: revoking K returned $CODE, expected 204" + +tui k-list-after 30000 workspace list +expect_refused k-list-after "VAL-CROSS-004" +grep -q "devsy login" "$EVIDENCE_DIR/k-list-after.txt" || + fail "VAL-CROSS-004: output has no re-login hint: $(cat "$EVIDENCE_DIR/k-list-after.txt")" + +no_key_in_evidence +grep -rqF "$STORED_KEY" "$EVIDENCE_DIR" && fail "evidence contains K" +grep -rqF -e "$PASSWORD_B" -e "$PASSWORD_C" "$EVIDENCE_DIR" && fail "a password is in the evidence" + +log "PASS VAL-CROSS-003 and VAL-CROSS-004 (evidence: $EVIDENCE_DIR)" diff --git a/hack/platform-e2e/lib.sh b/hack/platform-e2e/lib.sh index 3c2e9ee8a..17dcf373a 100755 --- a/hack/platform-e2e/lib.sh +++ b/hack/platform-e2e/lib.sh @@ -83,15 +83,23 @@ list_pairs() { awk 'NF == 2 && $1 != "NAME" && $1 !~ /^EXIT=/ {print $1, $2}' "$1" | sort } -# signup_user EMAIL PASSWORD ORG_NAME: sign up, log in through the gateway, create -# an org, and set SESSION_TOKEN and ORG_ID. -signup_user() { - local email="$1" password="$2" org_name="$3" - api -X POST "$GATEWAY/v1/auth/signup" \ - -d "$(jq -n --arg e "$email" --arg p "$password" '{email: $e, password: $p}')" >/dev/null +# register_user EMAIL PASSWORD: sign up and log in through the gateway, and set +# USER_ID and SESSION_TOKEN. The user belongs to no org yet. +register_user() { + local email="$1" password="$2" + USER_ID="$(api -X POST "$GATEWAY/v1/auth/signup" \ + -d "$(jq -n --arg e "$email" --arg p "$password" '{email: $e, password: $p}')" | jq -r .id)" + [ -n "$USER_ID" ] && [ "$USER_ID" != null ] || fail "could not sign up $email" SESSION_TOKEN="$(api -X POST "$GATEWAY/v1/auth/login" \ -d "$(jq -n --arg e "$email" --arg p "$password" '{email: $e, password: $p}')" | jq -r .token)" [ -n "$SESSION_TOKEN" ] && [ "$SESSION_TOKEN" != null ] || fail "could not log in $email through the gateway" +} + +# signup_user EMAIL PASSWORD ORG_NAME: register a user, create an org, and set +# USER_ID, SESSION_TOKEN and ORG_ID. +signup_user() { + local email="$1" password="$2" org_name="$3" + register_user "$email" "$password" ORG_ID="$(api -X POST "$GATEWAY/v1/orgs" -H "Authorization: Bearer $SESSION_TOKEN" \ -d "$(jq -n --arg n "$org_name" '{name: $n}')" | jq -r .id)" [ -n "$ORG_ID" ] && [ "$ORG_ID" != null ] || fail "could not create org $org_name" diff --git a/mise.toml b/mise.toml index 7261a58b1..357e104ef 100644 --- a/mise.toml +++ b/mise.toml @@ -170,14 +170,14 @@ dir = "e2e" run = 'go tool ginkgo --focus "$usage_pattern"' [tasks."cli:test:e2e:platform"] -description = "run the tuistory platform e2e scenarios (VAL-CROSS-001, VAL-CROSS-002); needs a live gateway, controller and KUBECONFIG_FILE" +description = "run the tuistory platform e2e scenarios (VAL-CROSS-001 to VAL-CROSS-004); needs a live gateway, controller and KUBECONFIG_FILE" shell = "bash -c" run = ''' set -euo pipefail : "${KUBECONFIG_FILE:?set KUBECONFIG_FILE to the k3d kubeconfig}" mkdir -p dist go build -o dist/devsy-e2e . -for script in cross-lifecycle cross-org-delete; do +for script in cross-lifecycle cross-org-delete access-revocation; do "hack/platform-e2e/${script}.sh" done ''' From 9dc7ce33fef3b90ea3538a84b1eee69923c11c3f Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sat, 7 Nov 2026 19:19:38 -0600 Subject: [PATCH 8/9] fix(cli): refuse workspace delete after logout instead of deleting locally runPlatform returned handled=false for a logged-out config (gateway URL set, key cleared), so `devsy workspace delete NAME` fell through to the local delete path. Return the authentication error, as list and create already do. --skip-platform still deletes locally. The logged-out message now says "work with local workspaces" since it is shared by delete. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- cmd/workspace/delete.go | 8 +- cmd/workspace/platform_lifecycle.go | 2 +- cmd/workspace/platform_lifecycle_test.go | 111 ++++++++++++++++++++++- cmd/workspace/platform_test.go | 39 ++++++-- 4 files changed, 143 insertions(+), 17 deletions(-) diff --git a/cmd/workspace/delete.go b/cmd/workspace/delete.go index c0c047d90..f60592a76 100644 --- a/cmd/workspace/delete.go +++ b/cmd/workspace/delete.go @@ -148,8 +148,9 @@ func (cmd *DeleteCmd) Run(cobraCmd *cobra.Command, args []string) error { // runPlatform deletes the named workspaces on the platform gateway when there // is a gateway login. It reports handled=false when the delete is local: no -// login, --skip-platform, or no names (the interactive picker lists local -// workspaces). +// gateway config, --skip-platform, or no names (the interactive picker lists +// local workspaces). A logged-out config is refused rather than deleted +// locally, because the name was meant for the gateway. func (cmd *DeleteCmd) runPlatform(ctx context.Context, args []string) (bool, error) { if cmd.SkipPlatform || len(args) == 0 { return false, nil @@ -158,6 +159,9 @@ func (cmd *DeleteCmd) runPlatform(ctx context.Context, args []string) (bool, err if err != nil { return false, nil } + if loggedOut(devsyConfig) { + return true, errLoggedOut + } creds := platformCredentials(devsyConfig) if creds == nil { return false, nil diff --git a/cmd/workspace/platform_lifecycle.go b/cmd/workspace/platform_lifecycle.go index 3b0e47c15..5e99c1925 100644 --- a/cmd/workspace/platform_lifecycle.go +++ b/cmd/workspace/platform_lifecycle.go @@ -49,7 +49,7 @@ var errNotLoggedIn = errors.New( var errLoggedOut = errors.New( "authentication required: you are logged out of the platform gateway; " + "run 'devsy login ' to sign in again " + - "(use --skip-platform to list local workspaces)", + "(use --skip-platform to work with local workspaces)", ) // lifecycleTarget is what a lifecycle request needs: the gateway login, where diff --git a/cmd/workspace/platform_lifecycle_test.go b/cmd/workspace/platform_lifecycle_test.go index 7d5622616..6c11155ad 100644 --- a/cmd/workspace/platform_lifecycle_test.go +++ b/cmd/workspace/platform_lifecycle_test.go @@ -1,6 +1,7 @@ package workspace import ( + "context" "encoding/json" "net/http" @@ -72,12 +73,12 @@ func (s *PlatformSuite) TestLifecycleCommandsFailWithTheGatewayMessage() { s.SetupTest() s.login() s.gateway.status = http.StatusNotFound - s.gateway.message = "workspace not found" + s.gateway.message = msgNotFound err := s.run(tc, platName) s.Require().Error(err) - s.Contains(err.Error(), "workspace not found") + s.Contains(err.Error(), msgNotFound) s.Contains(err.Error(), tc.subject) s.Contains(err.Error(), platName) s.NotContains(err.Error(), platTestKey) @@ -91,7 +92,7 @@ func (s *PlatformSuite) TestLifecycleCommandsShowThePermissionMessage() { s.SetupTest() s.login() s.gateway.status = http.StatusForbidden - s.gateway.message = "insufficient scope" + s.gateway.message = msgScope err := s.run(tc, platName) @@ -159,7 +160,7 @@ func (s *PlatformSuite) TestDeleteSeveralNamesDeletesEachAndReportsEveryFailure( func (s *PlatformSuite) TestDeleteKeepsGoingAfterAFailureAndExitsNonZero() { s.login() s.gateway.status = http.StatusNotFound - s.gateway.message = "workspace not found" + s.gateway.message = msgNotFound err := s.run(lifecycleCommands()[2], platWsA, "ws-b") @@ -167,7 +168,107 @@ func (s *PlatformSuite) TestDeleteKeepsGoingAfterAFailureAndExitsNonZero() { s.Len(s.gateway.recorded(), 2, "a failure must not stop the remaining deletes") s.Contains(err.Error(), platWsA) s.Contains(err.Error(), "ws-b") - s.Contains(err.Error(), "workspace not found") + s.Contains(err.Error(), msgNotFound) +} + +func (s *PlatformSuite) TestDeleteAfterLogoutFailsWithAnAuthenticationError() { + s.loggedOut() + + err := s.run(lifecycleCommands()[2], platName) + + s.Require().Error(err) + s.Contains(err.Error(), "authentication") + s.Contains(err.Error(), "devsy login") + s.Empty(s.gateway.recorded(), "a logged-out delete must not call the gateway") +} + +func (s *PlatformSuite) TestDeleteAfterLogoutDoesNotFallBackToLocalEvenWithIgnoreNotFound() { + s.loggedOut() + + // A local delete of an unknown workspace succeeds under --ignore-not-found, + // so success here would mean the command quietly went local. + err := s.run(lifecycleCommands()[2], "--ignore-not-found", platName) + + s.Require().Error(err) + s.Contains(err.Error(), "authentication") + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestRunPlatformRefusesDeleteAfterLogout() { + s.loggedOut() + cmd := &DeleteCmd{GlobalFlags: &flags.GlobalFlags{ResultFormat: output.ModePlain}, Out: s.out} + + handled, err := cmd.runPlatform(context.Background(), []string{platName}) + + s.True(handled, "a logged-out delete must not be left to the local path") + s.Require().ErrorIs(err, errLoggedOut) +} + +func (s *PlatformSuite) TestRunPlatformLeavesLocalDeleteAloneWhenSkippedOrUnnamed() { + s.loggedOut() + cmd := &DeleteCmd{GlobalFlags: &flags.GlobalFlags{ResultFormat: output.ModePlain}, Out: s.out} + + handled, err := cmd.runPlatform(context.Background(), nil) + s.False(handled, "the interactive picker lists local workspaces") + s.NoError(err) + + cmd.SkipPlatform = true + handled, err = cmd.runPlatform(context.Background(), []string{platName}) + s.False(handled) + s.NoError(err) +} + +func (s *PlatformSuite) TestDeleteAfterLogoutWithSkipPlatformDeletesLocally() { + s.loggedOut() + + // Local deletion of a workspace that does not exist succeeds only when the + // command really runs the local path. + s.Require().NoError(s.run( + lifecycleCommands()[2], "--skip-platform", "--ignore-not-found", "no-such-local-workspace", + )) + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestDeleteAfterLogoutWithSkipPlatformReportsAMissingLocalWorkspace() { + s.loggedOut() + + err := s.run(lifecycleCommands()[2], "--skip-platform", "no-such-local-workspace") + + s.Require().Error(err, "the local path runs and finds nothing to delete") + s.NotContains(err.Error(), "authentication") + s.Empty(s.gateway.recorded()) +} + +func (s *PlatformSuite) TestDeleteIgnoreNotFoundTreatsA404AsSuccess() { + s.login() + s.gateway.status = http.StatusNotFound + s.gateway.message = msgNotFound + + s.Require().NoError(s.run(lifecycleCommands()[2], "--ignore-not-found", platName)) + + s.Len(s.gateway.recorded(), 1, "the delete is sent to the gateway, not run locally") + s.NotContains(s.out.String(), "Delete requested") +} + +func (s *PlatformSuite) TestDeleteIgnoreNotFoundStillReportsOtherFailures() { + s.login() + s.gateway.status = http.StatusForbidden + s.gateway.message = msgScope + + err := s.run(lifecycleCommands()[2], "--ignore-not-found", platName) + + s.Require().Error(err) + s.Contains(err.Error(), "permission denied") +} + +func (s *PlatformSuite) TestDeleteIgnoreNotFoundDeletesTheRestOfTheNames() { + s.login() + s.gateway.notFound = map[string]bool{platWsA: true} + + s.Require().NoError(s.run(lifecycleCommands()[2], "--ignore-not-found", platWsA, "ws-b")) + + s.Len(s.gateway.recorded(), 2) + s.Contains(s.out.String(), "ws-b") } func (s *PlatformSuite) TestDeleteSkipPlatformLeavesTheGatewayAlone() { diff --git a/cmd/workspace/platform_test.go b/cmd/workspace/platform_test.go index 5be36e89b..e0da91197 100644 --- a/cmd/workspace/platform_test.go +++ b/cmd/workspace/platform_test.go @@ -24,6 +24,9 @@ const ( platWsA = "ws-a" urlX = "http://x" + msgNotFound = "workspace not found" + msgScope = "insufficient scope" + fieldName = "name" fieldPhase = "phase" phaseRunning = "Running" @@ -44,6 +47,8 @@ type fakePlatformGateway struct { workspaces []map[string]string status int message string + // notFound lists workspace names whose lifecycle routes answer 404. + notFound map[string]bool } // lifecycleRoute recognises the sleep, wake and delete routes and returns the @@ -70,6 +75,28 @@ func newFakePlatformGateway() *fakePlatformGateway { return g } +func writeGatewayError(w http.ResponseWriter, status int, message string) { + if message == "" { + message = "invalid api key" + } + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{ + "error": map[string]string{"code": "error", "message": message}, + }) +} + +// failureFor returns the status and message the gateway answers with instead +// of success, or status 0. The caller holds g.mu. +func (g *fakePlatformGateway) failureFor(call platformCall) (int, string) { + if g.status != 0 { + return g.status, g.message + } + if name, _, ok := lifecycleRoute(call); ok && g.notFound[name] { + return http.StatusNotFound, msgNotFound + } + return 0, "" +} + func (g *fakePlatformGateway) handle(w http.ResponseWriter, r *http.Request) { call := platformCall{Method: r.Method, Path: r.URL.Path, Auth: r.Header.Get("Authorization")} if r.Body != nil { @@ -77,18 +104,12 @@ func (g *fakePlatformGateway) handle(w http.ResponseWriter, r *http.Request) { } g.mu.Lock() g.calls = append(g.calls, call) - status, message := g.status, g.message + status, message := g.failureFor(call) g.mu.Unlock() w.Header().Set("Content-Type", "application/json") if status != 0 { - if message == "" { - message = "invalid api key" - } - w.WriteHeader(status) - _ = json.NewEncoder(w).Encode(map[string]any{ - "error": map[string]string{"code": "error", "message": message}, - }) + writeGatewayError(w, status, message) return } if name, phase, ok := lifecycleRoute(call); ok { @@ -257,7 +278,7 @@ func (s *PlatformSuite) TestCreateUnauthorizedSuggestsLogin() { func (s *PlatformSuite) TestCreateForbiddenStatesTheKeyLacksWriteScope() { s.login() s.gateway.status = http.StatusForbidden - s.gateway.message = "insufficient scope" + s.gateway.message = msgScope err := s.create(platName, "--template", platTemplate) From 8388c3f4831f9e22afe96d53c768b7c62fd4c535 Mon Sep 17 00:00:00 2001 From: Samuel K Date: Sun, 8 Nov 2026 00:44:40 -0600 Subject: [PATCH 9/9] docs: document platform login and workspace commands Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- README.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/README.md b/README.md index 4394d75fb..d46bf7881 100644 --- a/README.md +++ b/README.md @@ -209,3 +209,44 @@ Every workspace starts from the same definition. + +

Platform commands

+ +Log in to a managed platform gateway and manage its workspaces from the CLI. + +```sh +devsy login https://gateway.example.com +devsy login https://gateway.example.com --org "Acme Labs" +devsy logout +``` + +`devsy login GATEWAY_URL` asks for your email and password, signs in, and creates an API key named `devsy-cli` with read and write scopes for one organization. Pass `--org` with an organization ID or name to choose it. Without `--org`, Devsy uses your only organization or asks you to pick one. + +The key is stored in the devsy config file under `gateway` (`url`, `apiKey`, `orgId`, `orgName`, `keyId`, `keyRecordId`). The file is written with mode 0600. Your password and session token are never stored. API keys have the form `dvsy__`. + +`devsy logout` revokes the stored key at the gateway and removes the key and organization from the config. It keeps the gateway URL. If the gateway cannot revoke the key, the key stays in the config so you can run `devsy logout` again. + +While logged in, these workspace commands run against the platform: + +```sh +devsy workspace list +devsy workspace create my-workspace --template my-template +devsy workspace sleep my-workspace +devsy workspace wake my-workspace +devsy workspace delete my-workspace +``` + +- `create` requires `--template`. `create`, `sleep`, `wake` and `delete` return once the gateway accepts the request and the change happens in the background. Run `devsy workspace list` to follow the workspace phase. +- Read-only API keys can list workspaces but are denied on `create`, `sleep`, `wake` and `delete`. +- After `devsy logout`, these commands fail with an authentication error that tells you to run `devsy login`. +- Pass `--skip-platform` to `list` or `delete` to keep the local behavior and work with local workspaces. + +### Platform e2e tests + +The scripts in `hack/platform-e2e` drive the platform commands through real terminal sessions with tuistory. They cover workspace list and create, sleep, wake and delete, read-only key denial, logout, and cross-org and access-revocation scenarios. Run the cross-lifecycle, cross-org-delete and access-revocation scenarios with: + +```sh +KUBECONFIG_FILE=/path/to/kubeconfig mise run cli:test:e2e:platform +``` + +They need a live gateway and controller. `lib.sh` documents the optional settings, such as `GATEWAY`, `TEMPLATE` and `DEVSY_BIN`.