From 08bccd3a48e97f0974700adbfeadfcdd73a73282 Mon Sep 17 00:00:00 2001 From: fabriciojs Date: Fri, 27 Nov 2026 17:27:15 -0300 Subject: [PATCH 1/9] feat(cloud): say why a deploy failed, keep credentials out of output - Print the deploy's error, hint and detail from the status API, and the logs URL as soon as the deploy is created (and again on failure). - timedout is a final state; a failed status poll retries with backoff instead of waiting out the 15-minute timeout. - Send x-kool-client (claude-code, AI_AGENT, gemini-cli, copilot-cli, cursor, ci or human) so the panel can tell which deploys an agent ran. - --verbose and echoed command lines redact credential fields and token-like values (new core/redact); help and errors prefer KOOL_API_TOKEN over --token, which shows in the process list. - Log out of the Kool registry only, after the push; a failed logout no longer fails a deploy that already pushed. Label docker login failures. - An interrupt after the deploy started prints the deploy id and logs URL instead of dying silently; the rollout continues. - kool cloud exec accepts a leading --; setup's reference link is fixed; the stale embedded kool.deploy.yml template (rejected by the validator) is removed. Commands reference docs regenerated. Co-Authored-By: Claude Opus 5.5 --- commands/cloud.go | 13 +- commands/cloud_deploy.go | 228 ++++++++++--- commands/cloud_deploy_exec.go | 8 +- commands/cloud_deploy_exec_test.go | 32 ++ commands/cloud_deploy_test.go | 217 +++++++++++++ commands/cloud_setup.go | 2 +- commands/cloud_test.go | 72 +++++ core/redact/redact.go | 301 ++++++++++++++++++ core/redact/redact_test.go | 186 +++++++++++ core/shell/shell.go | 5 +- core/shell/shell_test.go | 34 ++ .../kool-cloud-deploy.md | 2 +- .../kool-cloud-destroy.md | 2 +- docs/05-Commands-Reference/kool-cloud-exec.md | 4 +- docs/05-Commands-Reference/kool-cloud-help.md | 2 +- docs/05-Commands-Reference/kool-cloud-logs.md | 2 +- .../05-Commands-Reference/kool-cloud-setup.md | 2 +- docs/05-Commands-Reference/kool-cloud.md | 5 +- services/cloud/api/client.go | 69 ++++ services/cloud/api/client_test.go | 46 +++ services/cloud/api/deploy_status.go | 23 +- services/cloud/api/deploy_status_test.go | 51 +++ services/cloud/api/endpoint.go | 10 +- services/cloud/api/endpoint_test.go | 95 ++++++ services/cloud/build.go | 49 ++- services/cloud/build_test.go | 62 ++++ templates/kool.deploy.yml | 105 ------ 27 files changed, 1431 insertions(+), 196 deletions(-) create mode 100644 commands/cloud_test.go create mode 100644 core/redact/redact.go create mode 100644 core/redact/redact_test.go create mode 100644 services/cloud/api/client.go create mode 100644 services/cloud/api/client_test.go create mode 100644 services/cloud/api/deploy_status_test.go create mode 100644 services/cloud/build_test.go delete mode 100644 templates/kool.deploy.yml diff --git a/commands/cloud.go b/commands/cloud.go index f1ea9c01..9f17d206 100644 --- a/commands/cloud.go +++ b/commands/cloud.go @@ -47,9 +47,12 @@ func AddKoolCloud(root *cobra.Command) { // NewCloudCommand initializes new kool cloud command func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) { cloudCmd = &cobra.Command{ - Use: "cloud COMMAND [flags]", - Short: "Interact with Kool.dev Cloud and manage your deployments.", - Long: "The cloud subcommand encapsulates a set of APIs to interact with Kool.dev Cloud and deploy, access and tail logs from your deployments.", + Use: "cloud COMMAND [flags]", + Short: "Interact with Kool.dev Cloud and manage your deployments.", + Long: `The cloud subcommand encapsulates a set of APIs to interact with Kool.dev Cloud and deploy, access and tail logs from your deployments. + +Authentication: the API token is read from the KOOL_API_TOKEN environment variable. +Prefer it over the --token flag, whose value shows up in the process list (ps) and in your shell history.`, Example: `kool cloud deploy`, // add cobra usage help content DisableFlagsInUseLine: true, @@ -85,7 +88,7 @@ func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) { // if no token is set, we try to get it from the environment if cloud.flags.Token == "" && cloud.env.Get("KOOL_API_TOKEN") == "" { if requiredFlags { - err = fmt.Errorf("missing Kool.dev Cloud API token - please set it via --token or KOOL_API_TOKEN environment variable") + err = fmt.Errorf("missing Kool.dev Cloud API token - please set the KOOL_API_TOKEN environment variable (preferred over --token, whose value shows up in the process list)") return } } else if cloud.flags.Token != "" { @@ -96,7 +99,7 @@ func NewCloudCommand(cloud *Cloud) (cloudCmd *cobra.Command) { }, } - cloudCmd.PersistentFlags().StringVarP(&cloud.flags.Token, "token", "", "", "Token to authenticate with Kool.dev Cloud API") + cloudCmd.PersistentFlags().StringVarP(&cloud.flags.Token, "token", "", "", "Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list") cloudCmd.PersistentFlags().StringVarP(&cloud.flags.DeployDomain, "domain", "", "", "Environment domain name to deploy to") return diff --git a/commands/cloud_deploy.go b/commands/cloud_deploy.go index 093926f1..3f2bf3f1 100644 --- a/commands/cloud_deploy.go +++ b/commands/cloud_deploy.go @@ -1,17 +1,21 @@ package commands import ( + "errors" "fmt" "kool-dev/kool/core/environment" + "kool-dev/kool/core/shell" "kool-dev/kool/core/utils" "kool-dev/kool/services/cloud" "kool-dev/kool/services/cloud/api" "kool-dev/kool/services/cloud/setup" "kool-dev/kool/services/tgz" "os" + "os/signal" "path/filepath" "strconv" "strings" + "syscall" "time" "github.com/spf13/cobra" @@ -99,6 +103,12 @@ func (d *KoolDeploy) Execute(args []string) (err error) { } s.Stop() + if deployCreated.LogsUrl != "" { + d.Shell().Info(strings.Repeat("-", 40)) + d.Shell().Info("Logs available at: ", deployCreated.LogsUrl) + d.Shell().Info(strings.Repeat("-", 40)) + } + var chPingDone = make(chan bool) go func() { for { @@ -139,18 +149,18 @@ func (d *KoolDeploy) Execute(args []string) (err error) { // ends ping chPingDone <- true - if deployCreated.LogsUrl != "" { - d.Shell().Info(strings.Repeat("-", 40)) - d.Shell().Info("Logs available at: ", deployCreated.LogsUrl) - d.Shell().Info(strings.Repeat("-", 40)) - } - s = utils.MakeFastLoading("Start deploying...", "Deploy started.", d.Shell().OutStream()) if _, err = deployer.StartDeploy(deployCreated); err != nil { return } s.Stop() + // from here on the deploy rolls out on Kool.dev Cloud whether this process + // stays or not, so an interrupt must not end it as if the deploy failed + interrupted := make(chan os.Signal, 1) + signal.Notify(interrupted, os.Interrupt, syscall.SIGTERM) + defer signal.Stop(interrupted) + timeout := 15 * time.Minute if d.flags.Timeout > 0 { timeout = time.Duration(d.flags.Timeout) * time.Minute @@ -158,68 +168,182 @@ func (d *KoolDeploy) Execute(args []string) (err error) { timeout = time.Duration(min) * time.Minute } - var finishes = make(chan bool) + var finishes = make(chan deployWaitResult, 1) - go func(deployCreated *api.DeployCreateResponse, finishes chan bool) { - var ( - status *api.DeployStatusResponse - lastStatus string - err error - ) + go func(deployCreated *api.DeployCreateResponse, finishes chan deployWaitResult) { + var result deployWaitResult - s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream()) + result.status, result.err = d.pollDeployStatus(func() (*api.DeployStatusResponse, error) { + return api.NewDeployStatus(deployCreated).Run() + }, time.Sleep) - for { - if status, err = api.NewDeployStatus(deployCreated).Run(); err != nil { - return - } + finishes <- result + }(deployCreated, finishes) - if lastStatus != status.Status { - lastStatus = status.Status - d.Shell().Println(" > deploy:", lastStatus) - } + s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream()) - if err != nil { - s.Stop() - finishes <- false - d.Shell().Error(err) - break - } + err = d.waitDeploy(deployCreated, finishes, time.After(timeout), interrupted, func(finished bool) { + if !finished { + // the deploy did not finish as far as we know + s.FinalMSG = "" + } + s.Stop() + }) - if status.Status == "success" || status.Status == "failed" { - s.Stop() - finishes <- status.Status == "success" - break - } + return +} + +// waitDeploy waits for whichever comes first: the deploy to finish, the +// timeout or the CLI being interrupted, stopping the loading indicator +// before printing the outcome +func (d *KoolDeploy) waitDeploy(deployCreated *api.DeployCreateResponse, finishes <-chan deployWaitResult, timeout <-chan time.Time, interrupted <-chan os.Signal, stopLoading func(finished bool)) (err error) { + select { + case result := <-finishes: + stopLoading(result.err == nil) - time.Sleep(time.Second * 2) + if result.err != nil { + err = withDeployLogs(result.err, deployCreated.LogsUrl) + return } - }(deployCreated, finishes) - var success bool - select { - case success = <-finishes: - { - if success { - d.Shell().Success("Deploy finished: ", deployCreated.Deploy.Environment.Name) - d.Shell().Success("") - d.Shell().Success("Access your environment at: ", deployCreated.Deploy.Url) - d.Shell().Success("") - } else { - err = fmt.Errorf("deploy failed") + if result.status.Status != "success" { + err = deployFailedError(result.status, deployCreated.LogsUrl) + return + } + + d.Shell().Success("Deploy finished: ", deployCreated.Deploy.Environment.Name) + d.Shell().Success("") + d.Shell().Success("Access your environment at: ", deployCreated.Deploy.Url) + d.Shell().Success("") + + case <-timeout: + stopLoading(false) + err = withDeployLogs(fmt.Errorf("timeout waiting deploy to finish"), deployCreated.LogsUrl) + + case sig := <-interrupted: + stopLoading(false) + err = deployInterruptedError(deployCreated, sig) + } + + return +} + +// deployInterruptedError tells that the CLI stopped waiting for a deploy that +// was already started: the deploy is neither cancelled nor reported as failed, +// it keeps rolling out on Kool.dev Cloud. The exit code follows the shell +// convention for a process ended by a signal (130 for SIGINT). +func deployInterruptedError(deployCreated *api.DeployCreateResponse, sig os.Signal) error { + var msg strings.Builder + + fmt.Fprintf(&msg, "interrupted (%s) while waiting for deploy %d to finish.\n", sig, deployCreated.Deploy.ID) + msg.WriteString("The deploy was already started: it keeps rolling out on Kool.dev Cloud and was neither cancelled nor reported as failed.\n") + + if deployCreated.LogsUrl != "" { + fmt.Fprintf(&msg, "Check how it goes at: %s\n", deployCreated.LogsUrl) + } + + msg.WriteString("Once it is live, see your services logs with: kool cloud logs SERVICE") + + code := 130 + if s, isSyscall := sig.(syscall.Signal); isSyscall { + code = 128 + int(s) + } + + return shell.ErrExitable{Err: errors.New(msg.String()), Code: code} +} + +const ( + // deployStatusPollInterval is the wait between deploy status checks + deployStatusPollInterval = 2 * time.Second + // deployStatusMaxAttempts is how many failed status checks in a row we take before giving up + deployStatusMaxAttempts = 5 + // deployStatusMaxBackoff caps the wait before retrying a failed status check + deployStatusMaxBackoff = 10 * time.Second +) + +// deployWaitResult holds the outcome of waiting for a deploy to finish +type deployWaitResult struct { + status *api.DeployStatusResponse + err error +} + +// isFinalDeployStatus tells whether the deploy is done, either successfully or not +func isFinalDeployStatus(status string) bool { + return status == "success" || status == "failed" || status == "timedout" +} + +// pollDeployStatus checks the deploy status until it reaches a final state, +// printing every status change. A failed check is retried with a short +// backoff, giving up after deployStatusMaxAttempts failures in a row. +func (d *KoolDeploy) pollDeployStatus(fetch func() (*api.DeployStatusResponse, error), wait func(time.Duration)) (status *api.DeployStatusResponse, err error) { + var ( + current *api.DeployStatusResponse + lastStatus string + failures int + backoff = deployStatusPollInterval + ) + + for { + if current, err = fetch(); err != nil { + if failures++; failures >= deployStatusMaxAttempts { + err = fmt.Errorf("failed checking deploy status %d times in a row: %s", failures, strings.TrimSpace(err.Error())) return } - break + + d.Shell().Warning(fmt.Sprintf(" > could not check deploy status (attempt %d of %d), retrying in %s: %s", failures, deployStatusMaxAttempts, backoff, strings.TrimSpace(err.Error()))) + wait(backoff) + + if backoff *= 2; backoff > deployStatusMaxBackoff { + backoff = deployStatusMaxBackoff + } + continue } - case <-time.After(timeout): - { - err = fmt.Errorf("timeout waiting deploy to finish") - break + failures, backoff, status = 0, deployStatusPollInterval, current + + if lastStatus != status.Status { + lastStatus = status.Status + d.Shell().Println(" > deploy:", lastStatus) } + + if isFinalDeployStatus(status.Status) { + return + } + + wait(deployStatusPollInterval) } +} - return +// deployFailedError explains why a deploy did not succeed, with the reason +// reported by Kool.dev Cloud and where to find the full logs. +func deployFailedError(status *api.DeployStatusResponse, logsURL string) error { + msg := "deploy failed" + if status.Status == "timedout" { + msg = "deploy timed out" + } + + if reason := strings.TrimSpace(status.Error); reason != "" { + msg += ": " + reason + } + + if hint := strings.TrimSpace(status.Hint); hint != "" { + msg += "\nHint: " + hint + } + + if detail := strings.TrimSpace(status.Detail); detail != "" { + msg += "\nDetail: " + detail + } + + return withDeployLogs(errors.New(msg), logsURL) +} + +// withDeployLogs appends where to find the deploy logs to the given error +func withDeployLogs(err error, logsURL string) error { + if logsURL == "" { + return err + } + + return fmt.Errorf("%w\nLogs available at: %s", err, logsURL) } func (d *KoolDeploy) createReleaseFile() (filename string, err error) { diff --git a/commands/cloud_deploy_exec.go b/commands/cloud_deploy_exec.go index b3556a0e..8abe6d01 100644 --- a/commands/cloud_deploy_exec.go +++ b/commands/cloud_deploy_exec.go @@ -26,7 +26,7 @@ type KoolDeployExecFlags struct { // NewDeployExecCommand inits Cobra command for kool deploy exec func NewDeployExecCommand(deployExec *KoolDeployExec) (cmd *cobra.Command) { cmd = &cobra.Command{ - Use: "exec SERVICE [COMMAND] [--] [ARG...]", + Use: "exec SERVICE [--] [COMMAND] [ARG...]", Short: "Execute a command inside a running service container deployed to Kool.dev Cloud", Long: `After deploying an application to Kool.dev Cloud using 'kool deploy', execute a COMMAND inside the specified SERVICE container (similar to an SSH session). @@ -68,6 +68,12 @@ func (e *KoolDeployExec) Execute(args []string) (err error) { service = args[0] args = args[1:] + // flags parsing stops at SERVICE, so in "kool cloud exec SERVICE -- COMMAND" + // the "--" reaches us as an argument; it is not part of the command + if len(args) > 0 && args[0] == "--" { + args = args[1:] + } + if url := e.env.Get("KOOL_API_URL"); url != "" { api.SetBaseURL(url) } diff --git a/commands/cloud_deploy_exec_test.go b/commands/cloud_deploy_exec_test.go index 72db9c60..1b733a01 100644 --- a/commands/cloud_deploy_exec_test.go +++ b/commands/cloud_deploy_exec_test.go @@ -86,3 +86,35 @@ func TestKoolDeployExec(t *testing.T) { t.Error("bad kubectl command args") } } + +func TestKoolDeployExecStripsLeadingDashes(t *testing.T) { + tests := []struct { + args []string + expected string + }{ + {[]string{"app", "--", "php", "artisan", "migrate"}, "-c default -- php artisan migrate"}, + {[]string{"app", "--", "ls", "--", "-la"}, "-c default -- ls -- -la"}, + {[]string{"app", "--"}, "-c default -- bash"}, + {[]string{"app", "env"}, "-c default -- env"}, + } + + for _, tt := range tests { + e := newFakeKoolDeployExec() + e.Flags.Container = "default" + e.env.Set("KOOL_DEPLOY_DOMAIN", "example.com") + + fakeKubectl := &builder.FakeCommand{} + mock := e.cloud.(*fakeK8S) + mock.MockAuthenticateCloudService = "cloud-service" + mock.MockKubectlKube = fakeKubectl + + if err := e.Execute(tt.args); err != nil { + t.Errorf("unexpected error running %v: %v", tt.args, err) + continue + } + + if str := strings.Join(fakeKubectl.ArgsAppend, " "); !strings.HasSuffix(str, tt.expected) { + t.Errorf("running %v: expected kubectl args ending with %q; got %q", tt.args, tt.expected, str) + } + } +} diff --git a/commands/cloud_deploy_test.go b/commands/cloud_deploy_test.go index add45b69..6e0f3a9f 100644 --- a/commands/cloud_deploy_test.go +++ b/commands/cloud_deploy_test.go @@ -1,13 +1,18 @@ package commands import ( + "errors" "kool-dev/kool/core/environment" "kool-dev/kool/core/shell" + "kool-dev/kool/services/cloud/api" "kool-dev/kool/services/cloud/setup" "os" "path/filepath" + "reflect" "strings" + "syscall" "testing" + "time" ) func TestNewKoolDeploy(t *testing.T) { @@ -197,3 +202,215 @@ func mockConfig(tmpDir string, t *testing.T, mock []byte) { t.Fatal(err) } } + +// fakeDeployStatuses returns a fetch function that replies with the given +// statuses in order; an empty status means a failed status check +func fakeDeployStatuses(statuses ...string) (fetch func() (*api.DeployStatusResponse, error), calls *int) { + calls = new(int) + fetch = func() (*api.DeployStatusResponse, error) { + status := statuses[*calls] + *calls++ + if status == "" { + return nil, errors.New("\n503 - unavailable\n") + } + return &api.DeployStatusResponse{Status: status, Error: "error for " + status}, nil + } + return +} + +func TestPollDeployStatusFinalStates(t *testing.T) { + for _, final := range []string{"success", "failed", "timedout"} { + fake := fakeKoolDeploy("") + fetch, calls := fakeDeployStatuses("building", "deploying", "deploying", final) + var waits []time.Duration + + status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + + if err != nil { + t.Errorf("unexpected error polling until %s: %v", final, err) + } + if status == nil || status.Status != final { + t.Errorf("expected final status %s; got %+v", final, status) + } + if *calls != 4 { + t.Errorf("expected 4 status checks until %s; got %d", final, *calls) + } + if expected := []time.Duration{2 * time.Second, 2 * time.Second, 2 * time.Second}; !reflect.DeepEqual(waits, expected) { + t.Errorf("expected waits %v; got %v", expected, waits) + } + + lines := fake.shell.(*shell.FakeShell).OutLines + if expected := []string{"> deploy: building", "> deploy: deploying", "> deploy: " + final}; !reflect.DeepEqual(lines, expected) { + t.Errorf("expected status changes %v; got %v", expected, lines) + } + } +} + +func TestPollDeployStatusRetriesFailedChecks(t *testing.T) { + fake := fakeKoolDeploy("") + fetch, calls := fakeDeployStatuses("deploying", "", "", "", "deploying", "", "failed") + var waits []time.Duration + + status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + + if err != nil { + t.Errorf("unexpected error when status checks recover: %v", err) + } + if status == nil || status.Status != "failed" { + t.Errorf("expected failed status; got %+v", status) + } + if *calls != 7 { + t.Errorf("expected 7 status checks; got %d", *calls) + } + + // backoff doubles while checks fail and resets after one succeeds + expected := []time.Duration{2 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 2 * time.Second, 2 * time.Second} + if !reflect.DeepEqual(waits, expected) { + t.Errorf("expected waits %v; got %v", expected, waits) + } + + fakeShell := fake.shell.(*shell.FakeShell) + if !fakeShell.CalledWarning { + t.Error("expected a warning for failed status checks") + } else if warning := fakeShell.WarningOutput[0].(string); !strings.Contains(warning, "attempt 1 of 5") || !strings.Contains(warning, "503 - unavailable") { + t.Errorf("unexpected warning for failed status check: %q", warning) + } +} + +func TestPollDeployStatusGivesUp(t *testing.T) { + fake := fakeKoolDeploy("") + fetch, calls := fakeDeployStatuses("deploying", "", "", "", "", "", "success") + var waits []time.Duration + + status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + + if err == nil || err.Error() != "failed checking deploy status 5 times in a row: 503 - unavailable" { + t.Errorf("unexpected error after failed status checks: %v", err) + } + if status == nil || status.Status != "deploying" { + t.Errorf("expected last known status; got %+v", status) + } + if *calls != 6 { + t.Errorf("expected 6 status checks; got %d", *calls) + } + + expected := []time.Duration{2 * time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 10 * time.Second} + if !reflect.DeepEqual(waits, expected) { + t.Errorf("expected waits %v; got %v", expected, waits) + } +} + +func TestDeployFailedError(t *testing.T) { + tests := []struct { + status api.DeployStatusResponse + logsURL string + expected string + }{ + {api.DeployStatusResponse{Status: "failed"}, "", "deploy failed"}, + {api.DeployStatusResponse{Status: "failed"}, "https://kool.dev/deploys/1", "deploy failed\nLogs available at: https://kool.dev/deploys/1"}, + {api.DeployStatusResponse{Status: "failed", Error: " pods not ready \n"}, "https://kool.dev/deploys/1", "deploy failed: pods not ready\nLogs available at: https://kool.dev/deploys/1"}, + {api.DeployStatusResponse{Status: "timedout", Error: "build took too long"}, "", "deploy timed out: build took too long"}, + { + api.DeployStatusResponse{Status: "failed", Error: "migrate hook failed", Hint: "check your migrations", Detail: "SQLSTATE[42S01]"}, + "https://kool.dev/deploys/1", + "deploy failed: migrate hook failed\nHint: check your migrations\nDetail: SQLSTATE[42S01]\nLogs available at: https://kool.dev/deploys/1", + }, + } + + for _, tt := range tests { + if err := deployFailedError(&tt.status, tt.logsURL); err.Error() != tt.expected { + t.Errorf("expected error %q; got %q", tt.expected, err.Error()) + } + } +} + +func TestWithDeployLogs(t *testing.T) { + timeoutErr := errors.New("timeout waiting deploy to finish") + + if err := withDeployLogs(timeoutErr, ""); err != timeoutErr { + t.Errorf("expected the same error without logs URL; got %v", err) + } + + err := withDeployLogs(timeoutErr, "https://kool.dev/deploys/1") + if err.Error() != "timeout waiting deploy to finish\nLogs available at: https://kool.dev/deploys/1" { + t.Errorf("unexpected error with logs URL: %v", err) + } + if !errors.Is(err, timeoutErr) { + t.Error("expected the error with logs URL to wrap the original error") + } +} + +func fakeStartedDeploy() *api.DeployCreateResponse { + deploy := &api.DeployCreateResponse{LogsUrl: "https://kool.dev/deploys/44417"} + deploy.Deploy.ID = 44417 + deploy.Deploy.Url = "https://app.example.com" + deploy.Deploy.Environment.Name = "app" + return deploy +} + +func TestWaitDeployInterrupted(t *testing.T) { + for sig, code := range map[os.Signal]int{os.Interrupt: 130, syscall.SIGTERM: 143} { + fake := fakeKoolDeploy("") + interrupted := make(chan os.Signal, 1) + interrupted <- sig + + var stopped, finished bool + err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), make(chan time.Time), interrupted, func(f bool) { + stopped, finished = true, f + }) + + if !stopped || finished { + t.Errorf("expected the loading indicator stopped as not finished; got stopped=%v finished=%v", stopped, finished) + } + + var exitable shell.ErrExitable + if !errors.As(err, &exitable) || exitable.Code != code { + t.Errorf("expected exit code %d on %s; got %v", code, sig, err) + continue + } + + for _, expected := range []string{ + "while waiting for deploy 44417 to finish", + "keeps rolling out on Kool.dev Cloud and was neither cancelled nor reported as failed", + "https://kool.dev/deploys/44417", + } { + if !strings.Contains(err.Error(), expected) { + t.Errorf("expected interrupt message to contain %q; got %q", expected, err.Error()) + } + } + + if strings.Contains(err.Error(), "deploy failed") { + t.Errorf("an interrupt must not read as a failed deploy; got %q", err.Error()) + } + } +} + +func TestWaitDeployOutcomes(t *testing.T) { + fake := fakeKoolDeploy("") + finishes := make(chan deployWaitResult, 1) + finishes <- deployWaitResult{status: &api.DeployStatusResponse{Status: "success"}} + + var finished bool + if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(f bool) { finished = f }); err != nil { + t.Errorf("unexpected error for a successful deploy: %v", err) + } + if !finished || !fake.shell.(*shell.FakeShell).CalledSuccess { + t.Error("expected the successful deploy to be reported as finished") + } + + fake = fakeKoolDeploy("") + finishes <- deployWaitResult{status: &api.DeployStatusResponse{Status: "failed", Error: "pods not ready"}} + if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(bool) {}); err == nil || !strings.HasPrefix(err.Error(), "deploy failed: pods not ready") { + t.Errorf("expected failed deploy error; got %v", err) + } + + timeout := make(chan time.Time, 1) + timeout <- time.Now() + finished = true + if err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), timeout, make(chan os.Signal), func(f bool) { finished = f }); err == nil || !strings.HasPrefix(err.Error(), "timeout waiting deploy to finish") { + t.Errorf("expected timeout error; got %v", err) + } + if finished { + t.Error("expected the loading indicator stopped as not finished on timeout") + } +} diff --git a/commands/cloud_setup.go b/commands/cloud_setup.go index c476a280..91493523 100644 --- a/commands/cloud_setup.go +++ b/commands/cloud_setup.go @@ -278,7 +278,7 @@ func (s *KoolCloudSetup) Execute(args []string) (err error) { s.Shell().Println("") s.Shell().Println("Configuration file: " + s.setupParser.ConfigFilePath()) s.Shell().Println("") - s.Shell().Println("Reference: https://kool.dev/docs/deploy-to-kool-cloud/kool-cloud-yml-reference") + s.Shell().Println("Reference: https://kool.dev/docs/kool-cloud/kool-cloud-yml-reference") s.Shell().Println("") return diff --git a/commands/cloud_test.go b/commands/cloud_test.go new file mode 100644 index 00000000..c6cc7e4d --- /dev/null +++ b/commands/cloud_test.go @@ -0,0 +1,72 @@ +package commands + +import ( + "io" + "kool-dev/kool/core/environment" + "strings" + "testing" + + "github.com/spf13/cobra" +) + +// newTestCloudCommand wires a cloud command with a no-op subcommand under a +// fake root, as its PersistentPreRunE calls the root's one +func newTestCloudCommand() (root *cobra.Command, cloud *Cloud) { + cloud = NewCloud() + cloud.env = environment.NewFakeEnvStorage() + + cloudCmd := NewCloudCommand(cloud) + cloudCmd.AddCommand(&cobra.Command{Use: "deploy", RunE: func(*cobra.Command, []string) error { return nil }}) + + root = &cobra.Command{Use: "kool", PersistentPreRunE: func(*cobra.Command, []string) error { return nil }} + root.AddCommand(cloudCmd) + root.SetOut(io.Discard) + root.SetErr(io.Discard) + + return +} + +func TestCloudCommandHelpPrefersTokenFromEnv(t *testing.T) { + cmd := NewCloudCommand(NewCloud()) + + if !strings.Contains(cmd.Long, "KOOL_API_TOKEN") || !strings.Contains(cmd.Long, "process list") { + t.Errorf("expected cloud help to say the token is read from KOOL_API_TOKEN, preferred over --token; got %q", cmd.Long) + } + + token := cmd.PersistentFlags().Lookup("token") + if token == nil { + t.Fatal("expected the --token flag to still exist") + } + + if !strings.Contains(token.Usage, "KOOL_API_TOKEN") || !strings.Contains(token.Usage, "process list") { + t.Errorf("expected --token help to point to KOOL_API_TOKEN; got %q", token.Usage) + } +} + +func TestCloudCommandToken(t *testing.T) { + root, cloud := newTestCloudCommand() + root.SetArgs([]string{"cloud", "deploy", "--domain", "app.example.com"}) + + if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "KOOL_API_TOKEN environment variable") { + t.Errorf("expected missing token error pointing to KOOL_API_TOKEN; got %v", err) + } + + // the token is read from the environment + cloud.env.Set("KOOL_API_TOKEN", "env-token") + if err := root.Execute(); err != nil { + t.Errorf("unexpected error with KOOL_API_TOKEN set: %v", err) + } + + // --token keeps working, and wins over the environment + root, cloud = newTestCloudCommand() + cloud.env.Set("KOOL_API_TOKEN", "env-token") + root.SetArgs([]string{"cloud", "deploy", "--domain", "app.example.com", "--token", "flag-token"}) + + if err := root.Execute(); err != nil { + t.Errorf("unexpected error with --token: %v", err) + } + + if token := cloud.env.Get("KOOL_API_TOKEN"); token != "flag-token" { + t.Errorf("expected --token to be shared as KOOL_API_TOKEN; got %q", token) + } +} diff --git a/core/redact/redact.go b/core/redact/redact.go new file mode 100644 index 00000000..b4c960e5 --- /dev/null +++ b/core/redact/redact.go @@ -0,0 +1,301 @@ +// Package redact hides credentials from what the CLI prints for debugging, +// such as the API responses and commands echoed by --verbose. +package redact + +import ( + "bytes" + "encoding/json" + "io" + "regexp" + "strings" +) + +// Placeholder replaces every redacted value +const Placeholder = "[REDACTED]" + +// minTokenLength is the shortest run of characters taken as a token +const minTokenLength = 32 + +var ( + // secretKeyWords mark a key, flag or variable name as holding a + // credential when the name contains any of them + secretKeyWords = []string{ + "password", "passwd", "passphrase", "secret", "token", "credential", + "authorization", "apikey", "api_key", "privatekey", "private_key", + "accesskey", "access_key", + } + + // secretKeyParts mark a name as holding a credential when they are + // one of its parts, e.g. DB_PASS, SENTRY_DSN or docker.login + secretKeyParts = map[string]bool{ + "key": true, "pass": true, "auth": true, "dsn": true, "login": true, + } + + // secretFlags take a credential as their value + secretFlags = map[string]bool{ + "token": true, "password": true, "pass": true, "secret": true, + "client-secret": true, "api-key": true, "apikey": true, + "api-token": true, "access-token": true, "auth-token": true, + } + + // loginFlags take a credential as their value in a login command + loginFlags = map[string]bool{"u": true, "username": true, "p": true} + + bearerRe = regexp.MustCompile(`(?i)\b(bearer\s+)[A-Za-z0-9._~+/=\-]+`) + urlUserinfoRe = regexp.MustCompile(`([A-Za-z][A-Za-z0-9+.\-]*://[^\s:/@]+:)[^\s/@]+@`) + keySepRe = regexp.MustCompile(`([A-Za-z0-9_.\-]+)("?[ \t]*[=:][ \t]*"?)`) + valueRe = regexp.MustCompile(`^[^\s"'&,;]+`) + tokenRunRe = regexp.MustCompile(`[A-Za-z0-9_+/\-]{32,}={0,2}`) +) + +// IsSensitiveKey tells whether a key, flag or variable name looks like it +// holds a credential +func IsSensitiveKey(name string) bool { + lower := strings.ToLower(name) + + for _, word := range secretKeyWords { + if strings.Contains(lower, word) { + return true + } + } + + if strings.HasSuffix(lower, "key") { + return true + } + + for _, part := range strings.FieldsFunc(lower, isNotAlphanumeric) { + if secretKeyParts[part] { + return true + } + } + + return false +} + +// JSON redacts a JSON document: values under credential-like keys, and any +// token-looking value. When raw is not valid JSON it is redacted as Text. +func JSON(raw []byte) string { + var ( + doc any + dec = json.NewDecoder(bytes.NewReader(raw)) + ) + + dec.UseNumber() + if err := dec.Decode(&doc); err != nil { + return Text(string(raw)) + } + + if err := dec.Decode(&struct{}{}); err != io.EOF { + // trailing data; not a single JSON document + return Text(string(raw)) + } + + var ( + out bytes.Buffer + enc = json.NewEncoder(&out) + ) + + enc.SetEscapeHTML(false) + if err := enc.Encode(redactValue(doc)); err != nil { + return Text(string(raw)) + } + + return strings.TrimSuffix(out.String(), "\n") +} + +// Text redacts credentials found in free text: bearer tokens, passwords in +// URLs, values of credential-like key=value pairs and token-looking values +func Text(s string) string { + s = bearerRe.ReplaceAllString(s, "${1}"+Placeholder) + s = urlUserinfoRe.ReplaceAllString(s, "${1}"+Placeholder+"@") + + s = redactKeyValues(s) + + return tokenRunRe.ReplaceAllStringFunc(s, func(run string) string { + if looksLikeToken(run) { + return Placeholder + } + return run + }) +} + +// redactKeyValues redacts the values of credential-like pairs such as +// password=..., token: ... or "secret":"..." +func redactKeyValues(s string) string { + var ( + redacted strings.Builder + last int + ) + + for _, m := range keySepRe.FindAllStringSubmatchIndex(s, -1) { + if m[0] < last || !IsSensitiveKey(s[m[2]:m[3]]) { + // either inside a value already redacted or not a credential + continue + } + + value := valueRe.FindString(s[m[1]:]) + if value == "" { + continue + } + + redacted.WriteString(s[last:m[1]]) + redacted.WriteString(Placeholder) + last = m[1] + len(value) + } + + redacted.WriteString(s[last:]) + + return redacted.String() +} + +// Args redacts the arguments of a command line: values of credential flags +// (--token, --password, and -u/-p of a login command), credential-like +// KEY=VALUE pairs and token-looking values +func Args(args []string) []string { + var ( + redacted = make([]string, len(args)) + isLogin bool + redactValue bool + ) + + for _, arg := range args { + if arg == "login" { + isLogin = true + break + } + } + + for i, arg := range args { + if redactValue { + redacted[i] = Placeholder + redactValue = false + continue + } + + if strings.HasPrefix(arg, "-") { + flag, value, hasValue := strings.Cut(arg, "=") + + if isSecretFlag(flag, isLogin) { + if hasValue { + redacted[i] = flag + "=" + Placeholder + } else { + redacted[i] = arg + redactValue = true + } + continue + } + + if hasValue { + redacted[i] = flag + "=" + redactArg(value) + continue + } + } + + redacted[i] = redactArg(arg) + } + + return redacted +} + +// redactArg redacts a single argument: the value of a credential-like +// KEY=VALUE pair, or any token-looking value +func redactArg(arg string) string { + if key, _, isPair := strings.Cut(arg, "="); isPair && !strings.HasPrefix(arg, "-") && IsSensitiveKey(key) { + return key + "=" + Placeholder + } + + return Text(arg) +} + +// isSecretFlag tells whether the given flag (with its dashes) takes a credential as value +func isSecretFlag(flag string, isLogin bool) bool { + name := strings.ToLower(strings.TrimLeft(flag, "-")) + + return secretFlags[name] || (isLogin && loginFlags[name]) +} + +func redactValue(value any) any { + switch v := value.(type) { + case map[string]any: + for key, item := range v { + if IsSensitiveKey(key) && !isBlank(item) { + v[key] = Placeholder + } else { + v[key] = redactValue(item) + } + } + case []any: + for i := range v { + v[i] = redactValue(v[i]) + } + case string: + return Text(v) + } + + return value +} + +// isBlank tells whether a value holds nothing worth hiding; keeping those +// as they are shows when a credential is missing +func isBlank(value any) bool { + switch v := value.(type) { + case nil, bool: + return true + case string: + return v == "" + } + + return false +} + +// looksLikeToken tells whether a run of characters looks like a generated +// credential: at least minTokenLength characters with letters and digits, +// either in mixed case or with no separators at all - which leaves out +// file paths and names-like-this-1234 +func looksLikeToken(run string) bool { + core := strings.TrimRight(run, "=") + + if len(core) < minTokenLength || isPath(core) { + return false + } + + var upper, lower, digit, separator bool + for _, r := range core { + switch { + case r >= 'a' && r <= 'z': + lower = true + case r >= 'A' && r <= 'Z': + upper = true + case r >= '0' && r <= '9': + digit = true + default: + separator = true + } + } + + if !digit || (!upper && !lower) { + return false + } + + return (upper && lower) || !separator +} + +// isPath tells whether a run looks like an absolute file path rather than +// a base64 token: it starts with a slash and has no long segment +func isPath(run string) bool { + if !strings.HasPrefix(run, "/") { + return false + } + + for _, segment := range strings.Split(run, "/") { + if len(segment) >= minTokenLength { + return false + } + } + + return true +} + +func isNotAlphanumeric(r rune) bool { + return (r < 'a' || r > 'z') && (r < '0' || r > '9') +} diff --git a/core/redact/redact_test.go b/core/redact/redact_test.go new file mode 100644 index 00000000..d8e772d4 --- /dev/null +++ b/core/redact/redact_test.go @@ -0,0 +1,186 @@ +package redact + +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) + +// fakeRegistryToken looks like the base64 registry password returned by /deploy/create +var fakeRegistryToken = strings.Repeat("eyJwYXlsb2FkIjoiQUFBQUJCQkJDQ0NDIn0+/Zm9vYmFy", 40) + "==" + +func TestIsSensitiveKey(t *testing.T) { + for _, key := range []string{ + "password", "DB_PASSWORD", "login", "token", "KOOL_API_TOKEN", "accessToken", + "client_secret", "APP_KEY", "AWS_ACCESS_KEY_ID", "apiKey", "DB_PASS", + "SENTRY_DSN", "Authorization", "--token", "aws_secret_access_key", + } { + if !IsSensitiveKey(key) { + t.Errorf("expected %q to be a sensitive key", key) + } + } + + for _, key := range []string{ + "id", "status", "image_prefix", "image_repository", "image_tag", "url", + "logs_url", "name", "PWD", "region", "DB_HOST", "platform", + } { + if IsSensitiveKey(key) { + t.Errorf("expected %q not to be a sensitive key", key) + } + } +} + +func TestJSONRedactsDeployCreateCredentials(t *testing.T) { + raw := []byte(`{"deploy":{"id":44417,"url":"https://app.example.com","environment":{"name":"app","env":{"APP_ENV":"production","DB_PASSWORD":"hunter2","SOME_VALUE":"Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIo"}}},` + + `"stuff":{"image_prefix":"123456789012.dkr.ecr.us-east-1.amazonaws.com","image_repository":"kool-cloud/app","image_tag":"20261127"},` + + `"docker":{"login":"AWS","password":"` + fakeRegistryToken + `"},"logs_url":"https://kool.dev/deploys/44417?a=1&b=2"}`) + + redacted := JSON(raw) + + for _, secret := range []string{fakeRegistryToken[:40], `"AWS"`, "hunter2", "Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIo"} { + if strings.Contains(redacted, secret) { + t.Errorf("expected %q to be redacted; got %s", secret, redacted) + } + } + + var doc struct { + Deploy struct { + ID int `json:"id"` + URL string `json:"url"` + Environment struct { + Env map[string]string `json:"env"` + } `json:"environment"` + } `json:"deploy"` + Stuff map[string]string `json:"stuff"` + Docker map[string]string `json:"docker"` + Logs string `json:"logs_url"` + } + + if err := json.Unmarshal([]byte(redacted), &doc); err != nil { + t.Fatalf("redacted JSON must still be valid JSON: %v (%s)", err, redacted) + } + + if doc.Docker["login"] != Placeholder || doc.Docker["password"] != Placeholder { + t.Errorf("expected docker credentials to be redacted; got %v", doc.Docker) + } + + if env := doc.Deploy.Environment.Env; env["DB_PASSWORD"] != Placeholder || env["SOME_VALUE"] != Placeholder || env["APP_ENV"] != "production" { + t.Errorf("unexpected redaction of environment variables: %v", env) + } + + // what helps debugging stays as it was + if doc.Deploy.ID != 44417 || doc.Deploy.URL != "https://app.example.com" || doc.Logs != "https://kool.dev/deploys/44417?a=1&b=2" { + t.Errorf("unexpected change to non-credential fields: %s", redacted) + } + + if expected := map[string]string{"image_prefix": "123456789012.dkr.ecr.us-east-1.amazonaws.com", "image_repository": "kool-cloud/app", "image_tag": "20261127"}; !reflect.DeepEqual(doc.Stuff, expected) { + t.Errorf("unexpected change to the image config: %v", doc.Stuff) + } +} + +func TestJSONKeepsBlankCredentials(t *testing.T) { + if redacted := JSON([]byte(`{"token":"","password":null,"has_login":true}`)); redacted != `{"has_login":true,"password":null,"token":""}` { + t.Errorf("expected blank credentials to be kept as they are; got %s", redacted) + } +} + +func TestJSONRedactsExecToken(t *testing.T) { + redacted := JSON([]byte(`{"server":"https://k8s.example.com:6443","namespace":"dev-app","path":"pod/app-1","token":"short-k8s-token","ca.crt":"-----BEGIN CERTIFICATE-----\nMIIBdzCCAR2gAwIBAgIBADAKBggqhkjOPQQDAjAjMSEwHwYDVQQDDBhrM3Mtc2Vy\n-----END CERTIFICATE-----"}`)) + + if strings.Contains(redacted, "short-k8s-token") || strings.Contains(redacted, "MIIBdzCCAR2gAwIBAgIBADAKBggqhkjOPQQDAjAjMSEwHwYDVQQDDBhrM3Mtc2Vy") { + t.Errorf("expected exec credentials to be redacted; got %s", redacted) + } + + if !strings.Contains(redacted, `"namespace":"dev-app"`) || !strings.Contains(redacted, `"server":"https://k8s.example.com:6443"`) { + t.Errorf("unexpected change to non-credential fields: %s", redacted) + } +} + +func TestJSONFallsBackToText(t *testing.T) { + for _, raw := range []string{ + `password=hunter2`, + `{"password":"hunter2"} trailing`, + `{"password":"hunter2"`, + } { + if redacted := JSON([]byte(raw)); strings.Contains(redacted, "hunter2") { + t.Errorf("expected password to be redacted from %q; got %q", raw, redacted) + } + } +} + +func TestText(t *testing.T) { + tests := []struct { + in, expected string + }{ + {"Authorization: Bearer abc.def-123", "Authorization: [REDACTED] [REDACTED]"}, + {"got bearer abc123", "got bearer [REDACTED]"}, + {"mysql://root:hunter2@db:3306/app", "mysql://root:[REDACTED]@db:3306/app"}, + {"https://kool.dev/api/deploy/status?id=12&token=abc", "https://kool.dev/api/deploy/status?id=12&token=[REDACTED]"}, + {"DB_PASSWORD=hunter2 DB_HOST=db", "DB_PASSWORD=[REDACTED] DB_HOST=db"}, + {`{"secret": "hunter2", "id": 1}`, `{"secret": "[REDACTED]", "id": 1}`}, + {"login with " + fakeRegistryToken + " now", "login with [REDACTED] now"}, + {"key 1|Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIoPq", "key 1|[REDACTED]"}, + {"hex 0123456789abcdef0123456789abcdef0123", "hex [REDACTED]"}, + // not credentials + {"Going to call: https://kool.dev/api/deploy/create?", "Going to call: https://kool.dev/api/deploy/create?"}, + {"/Users/someone/Projects/Kool2026/apps/node-20/src", "/Users/someone/Projects/Kool2026/apps/node-20/src"}, + {"dev-my-app-example-com-2026-11-27-production", "dev-my-app-example-com-2026-11-27-production"}, + {"KOOL_DEPLOY_DOMAIN_EXTRAS_FOR_SOME_REASON_123", "KOOL_DEPLOY_DOMAIN_EXTRAS_FOR_SOME_REASON_123"}, + {"short Zx9kQ2LmP4rT", "short Zx9kQ2LmP4rT"}, + {"linux/amd64", "linux/amd64"}, + } + + for _, tt := range tests { + if got := Text(tt.in); got != tt.expected { + t.Errorf("Text(%q): expected %q; got %q", tt.in, tt.expected, got) + } + } +} + +func TestArgs(t *testing.T) { + tests := []struct { + in, expected []string + }{ + { + []string{"login", "-u", "AWS", "--password-stdin", "123456789012.dkr.ecr.us-east-1.amazonaws.com"}, + []string{"login", "-u", "[REDACTED]", "--password-stdin", "123456789012.dkr.ecr.us-east-1.amazonaws.com"}, + }, + { + []string{"login", "--username=robot", "-p", "hunter2", "registry.kool.dev"}, + []string{"login", "--username=[REDACTED]", "-p", "[REDACTED]", "registry.kool.dev"}, + }, + { + []string{"--server", "https://k8s.example.com", "--token", "short-k8s-token", "--namespace", "dev-app", "exec", "-i", "pod/app", "--", "bash"}, + []string{"--server", "https://k8s.example.com", "--token", "[REDACTED]", "--namespace", "dev-app", "exec", "-i", "pod/app", "--", "bash"}, + }, + { + []string{"cloud", "deploy", "--token=abc", "--domain", "app.example.com"}, + []string{"cloud", "deploy", "--token=[REDACTED]", "--domain", "app.example.com"}, + }, + { + []string{"build", "-t", "registry/app:web-1", "--platform", "linux/amd64", "--build-arg", "NPM_TOKEN=hunter2", "--build-arg", "NODE_ENV=production", "--build-arg=DB_PASSWORD=hunter2", "/Users/someone/app"}, + []string{"build", "-t", "registry/app:web-1", "--platform", "linux/amd64", "--build-arg", "NPM_TOKEN=[REDACTED]", "--build-arg", "NODE_ENV=production", "--build-arg=DB_PASSWORD=[REDACTED]", "/Users/someone/app"}, + }, + { + // -p and -u are only credentials in a login command + []string{"run", "-p", "8080:80", "-u", "1000", "-e", "SECRET=" + fakeRegistryToken, "image", fakeRegistryToken}, + []string{"run", "-p", "8080:80", "-u", "1000", "-e", "SECRET=[REDACTED]", "image", "[REDACTED]"}, + }, + } + + for _, tt := range tests { + if got := Args(tt.in); !reflect.DeepEqual(got, tt.expected) { + t.Errorf("Args(%v):\nexpected %v\n got %v", tt.in, tt.expected, got) + } + } +} + +func TestArgsDoesNotChangeInput(t *testing.T) { + in := []string{"--token", "abc"} + _ = Args(in) + + if in[1] != "abc" { + t.Error("Args must not change the given slice") + } +} diff --git a/core/shell/shell.go b/core/shell/shell.go index c8d0b367..34d080e6 100644 --- a/core/shell/shell.go +++ b/core/shell/shell.go @@ -7,6 +7,7 @@ import ( "io" "kool-dev/kool/core/builder" "kool-dev/kool/core/environment" + "kool-dev/kool/core/redact" "os" "os/exec" "os/signal" @@ -155,7 +156,7 @@ func (s *DefaultShell) Exec(command builder.Command, extraArgs ...string) (outSt if verbose { _, _ = fmt.Fprintf(s.ErrStream(), "$ (exec) %s %s\n", exe, - strings.Join(args, " "), + strings.Join(redact.Args(args), " "), ) } @@ -195,7 +196,7 @@ func (s *DefaultShell) Interactive(originalCmd builder.Command, extraArgs ...str checker.IsTerminal(cmdptr.in), checker.IsTerminal(cmdptr.out), cmdptr.Command.Cmd(), - strings.Join(cmdptr.Args(), " "), + strings.Join(redact.Args(cmdptr.Args()), " "), ) } diff --git a/core/shell/shell_test.go b/core/shell/shell_test.go index d3caa07a..56ecaa28 100644 --- a/core/shell/shell_test.go +++ b/core/shell/shell_test.go @@ -516,3 +516,37 @@ func TestVerboseRecursive(t *testing.T) { t.Errorf("unexpected StdErr verbose output: %v", verboseOutput) } } + +func TestVerboseRedactsCredentials(t *testing.T) { + s := NewShell() + + s.(*DefaultShell).env = environment.NewFakeEnvStorage() + s.(*DefaultShell).env.Set("KOOL_VERBOSE", "true") + + buff := bytes.NewBuffer([]byte("")) + s.SetErrStream(buff) + + if _, err := s.Exec(builder.NewCommand("echo", "login", "-u", "AWS", "--password-stdin", "registry.example.com")); err != nil { + t.Fatalf("unexpected error from Exec: %v", err) + } + + kubectl := &builder.FakeCommand{MockCmd: "kool-fake-kubectl", ArgsAppend: []string{"--server", "https://k8s.example.com", "--token", "k8s-secret-token", "exec", "pod/app"}} + _ = s.Interactive(kubectl, "--build-arg", "NPM_TOKEN=npm-secret") + + verboseOutput := buff.String() + + for _, secret := range []string{"AWS", "k8s-secret-token", "npm-secret"} { + if strings.Contains(verboseOutput, secret) { + t.Errorf("verbose output printed a credential (%q): %s", secret, verboseOutput) + } + } + + for _, expected := range []string{ + "$ (exec) echo login -u [REDACTED] --password-stdin registry.example.com", + "kool-fake-kubectl --server https://k8s.example.com --token [REDACTED] exec pod/app --build-arg NPM_TOKEN=[REDACTED]", + } { + if !strings.Contains(verboseOutput, expected) { + t.Errorf("expected verbose output to contain %q; got %s", expected, verboseOutput) + } + } +} diff --git a/docs/05-Commands-Reference/kool-cloud-deploy.md b/docs/05-Commands-Reference/kool-cloud-deploy.md index b24e6a9c..04bdcb3d 100644 --- a/docs/05-Commands-Reference/kool-cloud-deploy.md +++ b/docs/05-Commands-Reference/kool-cloud-deploy.md @@ -21,7 +21,7 @@ kool cloud deploy ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud-destroy.md b/docs/05-Commands-Reference/kool-cloud-destroy.md index e6ee12d5..8c6df403 100644 --- a/docs/05-Commands-Reference/kool-cloud-destroy.md +++ b/docs/05-Commands-Reference/kool-cloud-destroy.md @@ -17,7 +17,7 @@ kool cloud destroy ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud-exec.md b/docs/05-Commands-Reference/kool-cloud-exec.md index 10a6dea1..03cb4aff 100644 --- a/docs/05-Commands-Reference/kool-cloud-exec.md +++ b/docs/05-Commands-Reference/kool-cloud-exec.md @@ -9,7 +9,7 @@ execute a COMMAND inside the specified SERVICE container (similar to an SSH sess Must use a KOOL_API_TOKEN environment variable for authentication. ``` -kool cloud exec SERVICE [COMMAND] [--] [ARG...] +kool cloud exec SERVICE [--] [COMMAND] [ARG...] ``` ### Options @@ -24,7 +24,7 @@ kool cloud exec SERVICE [COMMAND] [--] [ARG...] ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud-help.md b/docs/05-Commands-Reference/kool-cloud-help.md index 1fd24574..cab394fc 100644 --- a/docs/05-Commands-Reference/kool-cloud-help.md +++ b/docs/05-Commands-Reference/kool-cloud-help.md @@ -22,7 +22,7 @@ kool cloud help [command] [flags] ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud-logs.md b/docs/05-Commands-Reference/kool-cloud-logs.md index 29c483fa..9e71548d 100644 --- a/docs/05-Commands-Reference/kool-cloud-logs.md +++ b/docs/05-Commands-Reference/kool-cloud-logs.md @@ -26,7 +26,7 @@ kool cloud logs [OPTIONS] SERVICE ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud-setup.md b/docs/05-Commands-Reference/kool-cloud-setup.md index fc10de42..77be34b8 100644 --- a/docs/05-Commands-Reference/kool-cloud-setup.md +++ b/docs/05-Commands-Reference/kool-cloud-setup.md @@ -17,7 +17,7 @@ kool cloud setup ``` --domain string Environment domain name to deploy to --output string Output format: json (machine-readable). For 'kool run', place before the script name. - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list --verbose Increases output verbosity -w, --working_dir string Changes the working directory for the command ``` diff --git a/docs/05-Commands-Reference/kool-cloud.md b/docs/05-Commands-Reference/kool-cloud.md index 057bab29..fc407ceb 100644 --- a/docs/05-Commands-Reference/kool-cloud.md +++ b/docs/05-Commands-Reference/kool-cloud.md @@ -6,6 +6,9 @@ Interact with Kool.dev Cloud and manage your deployments. The cloud subcommand encapsulates a set of APIs to interact with Kool.dev Cloud and deploy, access and tail logs from your deployments. +Authentication: the API token is read from the KOOL_API_TOKEN environment variable. +Prefer it over the --token flag, whose value shows up in the process list (ps) and in your shell history. + ### Examples ``` @@ -17,7 +20,7 @@ kool cloud deploy ``` --domain string Environment domain name to deploy to -h, --help help for cloud - --token string Token to authenticate with Kool.dev Cloud API + --token string Token to authenticate with Kool.dev Cloud API. Prefer the KOOL_API_TOKEN environment variable, read when --token is not given: a --token value shows up in the process list ``` ### Options inherited from parent commands diff --git a/services/cloud/api/client.go b/services/cloud/api/client.go new file mode 100644 index 00000000..56386250 --- /dev/null +++ b/services/cloud/api/client.go @@ -0,0 +1,69 @@ +package api + +import ( + "kool-dev/kool/core/environment" + "strings" +) + +// maxClientLength limits the size of a client name taken from AI_AGENT +const maxClientLength = 40 + +// detectClient tells who is running the CLI, so the API can know which +// deploys were run by a person, a CI pipeline or a coding agent. +// +// Besides CLAUDECODE and the generic AI_AGENT, it only relies on markers +// each agent documents setting for the commands it runs: +// - GEMINI_CLI=1: https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/shell.md +// - COPILOT_CLI=1: https://github.com/github/copilot-cli/blob/main/changelog.md +// - CURSOR_AGENT: https://cursor.com/docs/agent/tools/terminal +func detectClient(env environment.EnvStorage) string { + if env.Get("CLAUDECODE") == "1" { + return "claude-code" + } + + if client := sanitizeClient(env.Get("AI_AGENT")); client != "" { + return client + } + + if env.Get("GEMINI_CLI") == "1" { + return "gemini-cli" + } + + if env.Get("COPILOT_CLI") == "1" { + return "copilot-cli" + } + + if env.Get("CURSOR_AGENT") != "" { + return "cursor" + } + + if isEnvSet(env.Get("CI")) || isEnvSet(env.Get("GITHUB_ACTIONS")) { + return "ci" + } + + return "human" +} + +// sanitizeClient lowercases the given value and keeps only [a-z0-9._-], +// up to maxClientLength characters +func sanitizeClient(value string) string { + var client strings.Builder + + for _, r := range strings.ToLower(value) { + if client.Len() == maxClientLength { + break + } + + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '.' || r == '_' || r == '-' { + client.WriteRune(r) + } + } + + return client.String() +} + +// isEnvSet tells whether a flag-like variable is set, not counting +// explicit opt-outs such as CI=false +func isEnvSet(value string) bool { + return value != "" && value != "0" && strings.ToLower(value) != "false" +} diff --git a/services/cloud/api/client_test.go b/services/cloud/api/client_test.go new file mode 100644 index 00000000..b813714e --- /dev/null +++ b/services/cloud/api/client_test.go @@ -0,0 +1,46 @@ +package api + +import ( + "kool-dev/kool/core/environment" + "strings" + "testing" +) + +func TestDetectClient(t *testing.T) { + tests := []struct { + name string + envs map[string]string + expected string + }{ + {"no markers", map[string]string{}, "human"}, + {"claude code", map[string]string{"CLAUDECODE": "1"}, "claude-code"}, + {"claude code wins over AI_AGENT and CI", map[string]string{"CLAUDECODE": "1", "AI_AGENT": "other", "CI": "true"}, "claude-code"}, + {"CLAUDECODE other than 1", map[string]string{"CLAUDECODE": "0"}, "human"}, + {"AI_AGENT", map[string]string{"AI_AGENT": "pi"}, "pi"}, + {"AI_AGENT sanitized", map[string]string{"AI_AGENT": " My Agent/v1.2_beta-3!\n"}, "myagentv1.2_beta-3"}, + {"AI_AGENT truncated", map[string]string{"AI_AGENT": strings.Repeat("a", 50)}, strings.Repeat("a", 40)}, + {"AI_AGENT empty after sanitizing", map[string]string{"AI_AGENT": "!!!", "CI": "1"}, "ci"}, + {"AI_AGENT wins over documented markers", map[string]string{"AI_AGENT": "pi", "GEMINI_CLI": "1"}, "pi"}, + {"gemini cli", map[string]string{"GEMINI_CLI": "1"}, "gemini-cli"}, + {"copilot cli", map[string]string{"COPILOT_CLI": "1"}, "copilot-cli"}, + {"cursor", map[string]string{"CURSOR_AGENT": "1"}, "cursor"}, + {"agent wins over CI", map[string]string{"GEMINI_CLI": "1", "GITHUB_ACTIONS": "true"}, "gemini-cli"}, + {"CI", map[string]string{"CI": "true"}, "ci"}, + {"GITHUB_ACTIONS", map[string]string{"GITHUB_ACTIONS": "true"}, "ci"}, + {"CI opted out", map[string]string{"CI": "false"}, "human"}, + {"CI zero", map[string]string{"CI": "0"}, "human"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env := environment.NewFakeEnvStorage() + for k, v := range tt.envs { + env.Set(k, v) + } + + if client := detectClient(env); client != tt.expected { + t.Errorf("expected client %q; got %q", tt.expected, client) + } + }) + } +} diff --git a/services/cloud/api/deploy_status.go b/services/cloud/api/deploy_status.go index d62b8d51..60873b6d 100644 --- a/services/cloud/api/deploy_status.go +++ b/services/cloud/api/deploy_status.go @@ -7,10 +7,27 @@ type DeployStatus struct { Endpoint } -// DeployCreateResponse holds data returned from the deploy endpoint +// DeployStatusService holds a service listed in the deploy status +type DeployStatusService struct { + Name string `json:"name"` + Type string `json:"type"` + Size string `json:"size"` +} + +// DeployStatusResponse holds data returned from the deploy status endpoint. +// Error is only set once a deploy has failed or timed out; Hint and Detail +// are optional extras explaining the failure, printed when present. type DeployStatusResponse struct { - ID int `json:"id"` - Status string `json:"status"` + ID int `json:"id"` + Status string `json:"status"` + Type string `json:"type"` + Url string `json:"url"` + Error string `json:"error"` + Hint string `json:"hint"` + Detail string `json:"detail"` + StartedAt string `json:"started_at"` + CompletedAt string `json:"completed_at"` + Services []DeployStatusService `json:"services"` } // NewDeployCreate creates a new DeployCreate instance diff --git a/services/cloud/api/deploy_status_test.go b/services/cloud/api/deploy_status_test.go new file mode 100644 index 00000000..69150380 --- /dev/null +++ b/services/cloud/api/deploy_status_test.go @@ -0,0 +1,51 @@ +package api + +import ( + "encoding/json" + "testing" +) + +func TestDeployStatusResponseDecodesPanelShape(t *testing.T) { + raw := []byte(`{ + "id": 42, + "status": "failed", + "type": "local", + "url": "https://app.example.com", + "error": "Error building images", + "started_at": "2026-11-27T10:00:00+00:00", + "completed_at": "2026-11-27T10:05:00+00:00", + "services": [{"name": "app", "type": "web", "size": "small"}], + "wordpress_credentials": null + }`) + + resp := &DeployStatusResponse{} + if err := json.Unmarshal(raw, resp); err != nil { + t.Fatalf("unexpected error decoding status: %v", err) + } + + if resp.ID != 42 || resp.Status != "failed" || resp.Type != "local" || resp.Url != "https://app.example.com" { + t.Errorf("bad decoded status: %+v", resp) + } + + if resp.Error != "Error building images" || resp.Hint != "" || resp.Detail != "" { + t.Errorf("bad decoded error fields: %+v", resp) + } + + if resp.StartedAt != "2026-11-27T10:00:00+00:00" || resp.CompletedAt != "2026-11-27T10:05:00+00:00" { + t.Errorf("bad decoded timestamps: %+v", resp) + } + + if len(resp.Services) != 1 || resp.Services[0] != (DeployStatusService{"app", "web", "small"}) { + t.Errorf("bad decoded services: %+v", resp.Services) + } + + // while running, the panel sends nulls for the fields it does not know yet + resp = &DeployStatusResponse{} + if err := json.Unmarshal([]byte(`{"id": 42, "status": "deploying", "url": null, "error": null, "completed_at": null, "services": []}`), resp); err != nil { + t.Fatalf("unexpected error decoding status with nulls: %v", err) + } + + if resp.Status != "deploying" || resp.Url != "" || resp.Error != "" || resp.CompletedAt != "" { + t.Errorf("bad decoded running status: %+v", resp) + } +} diff --git a/services/cloud/api/endpoint.go b/services/cloud/api/endpoint.go index f22f087b..0eedcd0e 100644 --- a/services/cloud/api/endpoint.go +++ b/services/cloud/api/endpoint.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "kool-dev/kool/core/environment" + "kool-dev/kool/core/redact" "mime/multipart" "net/http" "net/url" @@ -20,6 +21,10 @@ type HTTPRequester interface { var httpRequester HTTPRequester = http.DefaultClient +// verboseOutput is where --verbose prints the API calls and responses, +// always with credentials redacted +var verboseOutput io.Writer = os.Stderr + // Endpoint interface encapsulates the behaviour necessary for consuming // an API endpoint type Endpoint interface { @@ -182,7 +187,7 @@ func (e *DefaultEndpoint) DoCall() (err error) { reqURL := fmt.Sprintf("%s/%s?%s", apiBaseURL, e.path, e.query.Encode()) if verbose { - fmt.Fprintf(os.Stderr, "[Kool.dev Cloud] Going to call: %s\n", reqURL) + _, _ = fmt.Fprintf(verboseOutput, "[Kool.dev Cloud] Going to call: %s\n", redact.Text(reqURL)) } if request, err = http.NewRequest(e.method, reqURL, body); err != nil { @@ -190,6 +195,7 @@ func (e *DefaultEndpoint) DoCall() (err error) { } request.Header.Add("x-kool-cli-version", cliVersion) + request.Header.Add("x-kool-client", detectClient(e.env)) if e.contentType != "" { request.Header.Add("Content-type", e.contentType) @@ -209,7 +215,7 @@ func (e *DefaultEndpoint) DoCall() (err error) { } if verbose { - fmt.Fprintf(os.Stderr, "[Kool.dev Cloud] Got: %s\n", string(raw)) + _, _ = fmt.Fprintf(verboseOutput, "[Kool.dev Cloud] Got: %s\n", redact.JSON(raw)) } if e.statusCode >= 400 { diff --git a/services/cloud/api/endpoint_test.go b/services/cloud/api/endpoint_test.go index cc3ebfdb..b6be00d6 100644 --- a/services/cloud/api/endpoint_test.go +++ b/services/cloud/api/endpoint_test.go @@ -1,6 +1,7 @@ package api import ( + "bytes" "errors" "io" "kool-dev/kool/core/environment" @@ -89,9 +90,12 @@ func TestNewDefaultEndpoint(t *testing.T) { type fakeHTTP struct { err error resp *http.Response + + calledRequest *http.Request } func (f *fakeHTTP) Do(r *http.Request) (*http.Response, error) { + f.calledRequest = r return f.resp, f.err } @@ -288,3 +292,94 @@ func TestDoCallPost(t *testing.T) { t.Errorf("bad contentType: %s", e.contentType) } } + +func TestDoCallSetsClientHeaders(t *testing.T) { + e := newFakeDefaultEndpoint("GET") + e.env.Set("KOOL_API_TOKEN", "fake token") + e.env.Set("CLAUDECODE", "1") + + oldHTTPRequester := httpRequester + oldCliVersion := cliVersion + defer func() { + httpRequester = oldHTTPRequester + cliVersion = oldCliVersion + }() + + SetCliVersion("1.2.3") + fake := &fakeHTTP{resp: &http.Response{StatusCode: 200, Body: &fakeIOReaderCloser{ + fakeIOReader: fakeIOReader{data: []byte(`{}`)}, + }}} + httpRequester = fake + + var resp map[string]interface{} + e.SetResponseReceiver(&resp) + + if err := e.DoCall(); err != nil { + t.Fatalf("unexpected error from DoCall: %v", err) + } + + if v := fake.calledRequest.Header.Get("x-kool-cli-version"); v != "1.2.3" { + t.Errorf("bad x-kool-cli-version header: %q", v) + } + + if v := fake.calledRequest.Header.Get("x-kool-client"); v != "claude-code" { + t.Errorf("bad x-kool-client header: %q", v) + } +} + +func TestDoCallVerboseRedactsCredentials(t *testing.T) { + var ( + registryToken = strings.Repeat("eyJwYXlsb2FkIjoiQUFBQUJCQkJDQ0NDIn0+/Zm9vYmFy", 40) + "==" + apiToken = "123|Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIoPq" + verbose = new(bytes.Buffer) + ) + + e := newFakeDefaultEndpoint("POST") + e.env.Set("KOOL_API_TOKEN", apiToken) + e.env.Set("KOOL_VERBOSE", "1") + e.SetPath("deploy/create") + e.Query().Set("token", apiToken) + + oldHTTPRequester, oldVerboseOutput := httpRequester, verboseOutput + defer func() { + httpRequester, verboseOutput = oldHTTPRequester, oldVerboseOutput + }() + + verboseOutput = verbose + httpRequester = &fakeHTTP{resp: &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader( + `{"deploy":{"id":44417,"status":"building"},` + + `"stuff":{"image_prefix":"123456789012.dkr.ecr.us-east-1.amazonaws.com"},` + + `"docker":{"login":"AWS","password":"` + registryToken + `"}}`, + ))}} + + var resp DeployCreateResponse + e.SetResponseReceiver(&resp) + + if err := e.DoCall(); err != nil { + t.Fatalf("unexpected error from DoCall: %v", err) + } + + // the CLI itself still gets the credentials it needs + if resp.Docker.Login != "AWS" || resp.Docker.Password != registryToken { + t.Error("the response must not be redacted, only what --verbose prints") + } + + output := verbose.String() + + for _, secret := range []string{registryToken[:40], `"AWS"`, apiToken, "Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIoPq"} { + if strings.Contains(output, secret) { + t.Errorf("--verbose printed a credential (%q): %s", secret, output) + } + } + + for _, expected := range []string{ + "Going to call: " + apiBaseURL + "/deploy/create?token=[REDACTED]", + `"docker":{"login":"[REDACTED]","password":"[REDACTED]"}`, + `"deploy":{"id":44417,"status":"building"}`, + "123456789012.dkr.ecr.us-east-1.amazonaws.com", + } { + if !strings.Contains(output, expected) { + t.Errorf("expected --verbose to print %q; got %s", expected, output) + } + } +} diff --git a/services/cloud/build.go b/services/cloud/build.go index 0e79f787..77bd2a91 100644 --- a/services/cloud/build.go +++ b/services/cloud/build.go @@ -22,11 +22,10 @@ func BuildPushImageForDeploy(service string, config *DeployConfigService, deploy } var ( - env = environment.NewEnvStorage() - isVerbose = env.IsTrue("KOOL_VERBOSE") - sh = shell.NewShell() - image = fmt.Sprintf("%s/%s:%s-%s", deploy.Config.ImagePrefix, deploy.Config.ImageRepository, service, deploy.Config.ImageTag) - output string + env = environment.NewEnvStorage() + sh = shell.NewShell() + image = fmt.Sprintf("%s/%s:%s-%s", deploy.Config.ImagePrefix, deploy.Config.ImageRepository, service, deploy.Config.ImageTag) + output string ) // create a default io.Reader for stdin @@ -72,26 +71,42 @@ func BuildPushImageForDeploy(service string, config *DeployConfigService, deploy // login & push... dockerLogin := builder.NewCommand("docker", "login", "-u", deploy.Docker.Login, "--password-stdin", deploy.Config.ImagePrefix) if output, err = sh.Exec(dockerLogin); err != nil { - if isVerbose { - fmt.Println(output) - } + err = dockerLoginError(deploy.Config.ImagePrefix, output, err) return } + if deploy.Config.ImagePrefix != "" { + defer dockerLogout(sh, dockerLogoutCommand(deploy.Config.ImagePrefix)) + } + dockerPush := builder.NewCommand("docker", "push", image) - if err = sh.Interactive(dockerPush); err != nil { - return + err = sh.Interactive(dockerPush) + + return +} + +// dockerLogoutCommand logs out of the given registry only - a bare +// docker logout would log the user out of Docker Hub instead +func dockerLogoutCommand(registry string) builder.Command { + return builder.NewCommand("docker", "logout", registry) +} + +// dockerLogout runs the logout after the push; by then the image is pushed +// (or the push failed already), so a failed logout is only a warning +func dockerLogout(sh shell.Shell, logout builder.Command) { + if _, err := sh.Exec(logout); err != nil { + sh.Warning("failed to log out of the Kool.dev Cloud registry: ", err) } +} - dockerLogout := builder.NewCommand("docker", "logout") - if output, err = sh.Exec(dockerLogout); err != nil { - if isVerbose { - fmt.Println(output) - } - return +// dockerLoginError tells which registry docker login failed for, along +// with what docker printed - not only its exit status. +func dockerLoginError(registry, output string, err error) error { + if output = strings.TrimSpace(output); output != "" && !strings.Contains(err.Error(), output) { + return fmt.Errorf("docker login to %s failed: %s (%w)", registry, output, err) } - return + return fmt.Errorf("docker login to %s failed: %w", registry, err) } // parseContext parses the build context from the build configuration diff --git a/services/cloud/build_test.go b/services/cloud/build_test.go new file mode 100644 index 00000000..a35515c1 --- /dev/null +++ b/services/cloud/build_test.go @@ -0,0 +1,62 @@ +package cloud + +import ( + "errors" + "kool-dev/kool/core/builder" + "kool-dev/kool/core/shell" + "reflect" + "testing" +) + +func TestDockerLoginError(t *testing.T) { + exitErr := errors.New("exit status 1") + + err := dockerLoginError("registry.example.com", "Error response from daemon: unauthorized\n", exitErr) + if err.Error() != "docker login to registry.example.com failed: Error response from daemon: unauthorized (exit status 1)" { + t.Errorf("unexpected error message: %v", err) + } + if !errors.Is(err, exitErr) { + t.Error("expected the docker login error to wrap the original error") + } + + // the shell already merges the output into the error; do not repeat it + shellErr := errors.New("Error response from daemon: unauthorized (exit status 1)") + err = dockerLoginError("registry.example.com", "Error response from daemon: unauthorized", shellErr) + if err.Error() != "docker login to registry.example.com failed: Error response from daemon: unauthorized (exit status 1)" { + t.Errorf("unexpected error message: %v", err) + } + + err = dockerLoginError("registry.example.com", "", exitErr) + if err.Error() != "docker login to registry.example.com failed: exit status 1" { + t.Errorf("unexpected error message: %v", err) + } +} + +func TestDockerLogoutCommand(t *testing.T) { + logout := dockerLogoutCommand("123456789012.dkr.ecr.us-east-1.amazonaws.com") + + // a bare docker logout would log the user out of Docker Hub + if logout.Cmd() != "docker" || !reflect.DeepEqual(logout.Args(), []string{"logout", "123456789012.dkr.ecr.us-east-1.amazonaws.com"}) { + t.Errorf("expected docker logout of the Kool.dev Cloud registry only; got %s %v", logout.Cmd(), logout.Args()) + } +} + +func TestDockerLogout(t *testing.T) { + sh := &shell.FakeShell{} + dockerLogout(sh, &builder.FakeCommand{MockCmd: "docker"}) + + if !sh.CalledExec["docker"] { + t.Error("expected docker logout to run") + } + if sh.CalledWarning { + t.Error("unexpected warning for a successful logout") + } + + // the image is pushed by then; a failed logout must not fail the deploy + sh = &shell.FakeShell{} + dockerLogout(sh, &builder.FakeCommand{MockCmd: "docker", MockExecError: errors.New("logout failed")}) + + if !sh.CalledWarning { + t.Error("expected a warning for a failed logout") + } +} diff --git a/templates/kool.deploy.yml b/templates/kool.deploy.yml deleted file mode 100644 index d8aa78f2..00000000 --- a/templates/kool.deploy.yml +++ /dev/null @@ -1,105 +0,0 @@ -# Here you have a mirror of your docker-compose.yml with specific overrides and -# extra pieces of configuration focused on the deployment of your application. -services: - service: - # Applications usually will require a special image built for deployment. - build: Dockerfile - - # Tells Kool.dev Cloud that this service is accessible through the deployment URL. - # Note: only one service can be set to be public. - public: - # Tells the port that should be used for routing incoming HTTP traffic. - - port: 80 - # Sometimes you may have a second process you want to access as well, i.e. some - # websocket service that you spin up via a 'daemon' and listens on another port. - # You may do so by specifying a second port with a path - so all requests starting - # with such path prefix will be routed to that port instead of the default port above. - - port: 3000 - path: /ws - - # Tells what port the app will listen to (optional). - port: 80 - - # Tells your app's root folder so all other paths can be relative (optional). - root: /app - - # Containers are ephemeral, that means their filesystem do not persist across deployments. - # If you want to persist stuff into the disk across deployments, you can do so by defining persistent paths here. - persists: - # Total size of the volume you want to attach to the running container. - size: 1Gi - # Paths to persist - within that single volume, you can have one or more paths - # that are going to be mounted every time your containers are running. Note that - # such mounts include before/after hooks as well as daemon containers. - paths: - # The path within the container. Must be either aboslute or relative to the 'root' config. - - path: /app/some/path/persisted - # Tells the Deploy API to sync the folder from your built image to the persisted storage. - # This is very helpful to start off with a known folder structure. - sync: true - # Tells what user and group should own the persisted folder (only used along the sync: true) - chown: user:group - - # By default, Kool.dev Cloud will rollout new deployments in a blue-green fashion. - # If you want to disable it and make sure the current running container - # stopped before the new one is created, set 'recreate: true'. - recreate: false - - # Sometimes you may make changes to your app that wouldn't necessarily trigger - # new containers to be created by the kool cloud deploy process. - # - # For example, if you change only environment variables or use a fixed image tag - # like ':latest' that doesn't change. - # - # By setting `force: true`, you tell the API to always update this service. - force: false - - # Here we can define processes that behave like services and must be run in the cloud only. - # Usually, this is very helpful for queue workers and that kind of stuff. The processes will - # run as other containers in your deployment using the very same image as the main service. - daemons: - - command: [ start-queues, arg1, arg2 ] - # As mentioned above in the 'public' config, you may also want to have a daemon - # that serves specific requests. A common use case is WebSocket services. You can - # define that your daemon exposes a TCP port with the 'expose' entry. - - command: [ run-websocker-server, --port=3000 ] - expose: 3000 - - # Hooks - # - # It's possible that you want to run some extra steps either before or after every - # time your application is deployed. Such hooks are executed in standalone containers - # using the same Docker image about to be deployed. - # - # The 'before' hook is a special section where we can define commands to be executed - # right before a new deployment happens. - before: - - script_to_run.sh - # The 'after' hook is a special section where we can define procedures to be executed - # right after a new deployment finishes. - after: - - [ run-database-migrations, arg1, arg2 ] - - # The 'cron' config allows you to set scheduled actions to run in a Cron job fashion. - cron: - - { schedule: "* * * * *", command: [ run-some-task-every-minute ] } - - # Environment Variables to the cloud container - # - # You usually will want to provide a file containing the environment variables - # that your deployment should have. Such a file may contain special Kool variables - # that will be translated to their actual value by the Deploy API. - # - # There are two ways to provide such a file. - # - # 'environment' refers to a file with all of the environment variables available. - # The Deploy API will get the contents of this file and make all of them available - # as true environment variables for the container. You can check them in your deployed - # container via kool cloud exec env (assuming you have env available). - environment: kool.deploy.env - # - # 'env' is a different option that allows you to build a file inside your running container. - # This is useful for apps that have a .env file, but you do not want to have that built into your app Docker image. - env: - source: kool.deploy.env - target: .env From 9ee040ccf974cef3d3bd72fe00f958d5e1966e1d Mon Sep 17 00:00:00 2001 From: fabriciojs Date: Fri, 27 Nov 2026 17:27:15 -0300 Subject: [PATCH 2/9] feat(skills): draft kool-cloud-deploy skill and AGENTS.md snippet A short skill for coding agents deploying to Kool Cloud, with references for Laravel, Next.js (Prisma + SQLite), Vite/React SPAs, Node and static sites, plus the always-loaded AGENTS.md snippet kool create and kool cloud setup could write. Every kool.cloud.yml example passes the CLI validator; every Dockerfile passes docker build --check. Draft for review. Co-Authored-By: Claude Opus 5.5 --- skills/kool-cloud-deploy/SKILL.md | 94 +++++++++++++++++++ .../kool-cloud-deploy/references/laravel.md | 80 ++++++++++++++++ skills/kool-cloud-deploy/references/nextjs.md | 79 ++++++++++++++++ skills/kool-cloud-deploy/references/node.md | 64 +++++++++++++ skills/kool-cloud-deploy/references/spa.md | 68 ++++++++++++++ skills/kool-cloud-deploy/references/static.md | 54 +++++++++++ templates/agents/AGENTS.kool.md | 35 +++++++ 7 files changed, 474 insertions(+) create mode 100644 skills/kool-cloud-deploy/SKILL.md create mode 100644 skills/kool-cloud-deploy/references/laravel.md create mode 100644 skills/kool-cloud-deploy/references/nextjs.md create mode 100644 skills/kool-cloud-deploy/references/node.md create mode 100644 skills/kool-cloud-deploy/references/spa.md create mode 100644 skills/kool-cloud-deploy/references/static.md create mode 100644 templates/agents/AGENTS.kool.md diff --git a/skills/kool-cloud-deploy/SKILL.md b/skills/kool-cloud-deploy/SKILL.md new file mode 100644 index 00000000..dca1f474 --- /dev/null +++ b/skills/kool-cloud-deploy/SKILL.md @@ -0,0 +1,94 @@ +--- +name: kool-cloud-deploy +description: Deploy an app to Kool Cloud (kool.dev) with `kool cloud deploy` - write kool.cloud.yml, a production Dockerfile and .dockerignore, deploy headless, read failures, verify with curl. Use when asked to deploy, ship, host or publish an app on Kool, Kool Cloud or a *.kool.cloud domain, or when the repo has a kool.cloud.yml. Local Docker work (kool start/exec/run) is the kool-cli skill. +--- + +# Kool Cloud deploy + +## Before you start (ask the human; never work around these) +- `kool` CLI installed, Docker running (`docker info`). +- `KOOL_API_TOKEN` set in the environment, or in the git-ignored `.env` that the CLI loads from the working directory. A new environment needs a **project-scoped** token. Never ask for the token in chat, never echo it, never pass `--token` (it shows in `ps` and shell history). +- A domain: `.kool.cloud` has HTTPS at once; a custom domain needs its DNS pointed first (the panel shows the records). + +## Files: write them by hand (`kool cloud setup` exits without a TTY) +`kool.cloud.yml` at the repo root (`kool.deploy.yml` is the legacy name), a production `Dockerfile`, a `.dockerignore`, and optionally a git-ignored env file. No docker-compose.yml is needed. Smallest valid config: +```yaml +# kool.cloud.yml +services: + app: + build: . # a directory with a Dockerfile, never a Dockerfile path + expose: 80 # integer; the port the app listens on, bound to 0.0.0.0 + public: true # route the domain here; requires expose +``` +- `build`: a directory, or `{context: ., dockerfile: Dockerfile.prod, args: {K: "v"}}`. The map form needs `context`, and `dockerfile` is relative to the repo root. `image: name:tag` instead of `build` deploys a prebuilt image. +- `public: true` on one service. A list `[{port: 80}, {port: 3000, path: /ws}]` routes a path prefix to another port, and strips the prefix. +- `environment`: a map (plain env vars) or an env-file name (stored as a Secret). `"{{VAR}}"` is replaced by the environment variable VAR set in the Kool panel. Always quote placeholders; an unknown VAR stays literal. +- `size`: `micro` (the default: 128m CPU, 256Mi RAM), `small`, `medium`, `large`, `xlarge`, `2xlarge`. Each size doubles the one before, trials cap at `medium`, and cron and hooks default to `medium`. `replicas: N` adds pods. +- `persists: {size: 1Gi, paths: [{path: /app/data}]}` gives one disk per service. It makes every deploy stop-then-start (seconds of downtime) and pins the pods to one node. `sync: true` copies the image's copy of the path over the disk at **every pod start**: use it for skeleton folders, never for a database file. Relative paths need `root: /app`. +- `daemons: [{command: [...], size: small}]` are long-running extra containers in the same pod (queue workers), named `daemon0`, `daemon1`. If one crash-loops, the deploy fails. +- `cron: [{schedule: "*/5 * * * *", command: [...]}]` is a Kubernetes CronJob: a fresh pod per run, on the UTC clock. +- `before: [[cmd, arg]]` runs as an init container of **every new pod**. That includes the first deploy (the docs saying otherwise are stale), but also every restart, reschedule and replica. If it fails, the pod never starts and the deploy fails. +- `after: [[cmd, arg]]` runs **once per deploy**, as a Job after the new pods are up. If it fails, the release rolls back. +- Hooks, daemons and cron run with the same image, env and persisted paths. Their command is passed as **arguments to the image's ENTRYPOINT**, so start your app with `CMD`, and keep any `ENTRYPOINT` one that `exec`s its arguments. +- Services reach each other by service name (`cache:6379`). +- **If a docker-compose.yml exists, it is uploaded and merged under kool.cloud.yml.** Every compose service deploys unless kool.cloud.yml sets `deploy: false` on it, and compose keys you don't override (`image`, `command`, `environment`) carry over. + +## Rules for every stack +- **Architecture.** The shared Kool Cloud runs linux/amd64, which is the CLI's default build, so don't pass `--platform`. BYOC deploys go to the team's default cluster, or to the one named by `KOOL_CLOUD_CLUSTER=`. A BYOC cluster may be arm64 (Graviton): pass `--platform linux/arm64` only when the user says its nodes are arm64. A wrong-arch image is accepted, and fails about 5 minutes later with no useful message. +- On Apple Silicon the amd64 build runs under QEMU, which is slow, and Turbopack, Rolldown and esbuild can segfault (`qemu: uncaught target signal 11`). Build arch-independent output (JS bundles, assets) in a `FROM --platform=$BUILDPLATFORM` stage, and install native dependencies (`npm ci`, apt, pecl) in the final stage. +- **Add a `.dockerignore`**: `.git`, `.env*`, the env file, `node_modules`, build output, `*.db`, and `vendor` for PHP. Without it, secrets and host binaries end up in the image. +- **Deploy** with `kool cloud deploy --domain ` from the repo root, in the **foreground**, with your shell tool's longest timeout (20 minutes or more; a deploy usually takes 3 to 8 minutes, longer under QEMU). Never background it, and never end your turn while it runs. Interrupting it before `Deploy started.` fails the deploy; after that line the rollout continues on the server. +- **Never use `--verbose`.** It prints the registry password and every environment variable. Never paste output that holds secrets. +- **Logs and shell:** `kool cloud logs --domain ` (add `-c daemon0`, `-f` or `--tail 100`), and `kool cloud exec --domain ` (don't add `--`). Both see running pods only. They use your local `kubectl`, or else pull the `kooldev/toolkit:full` image. +- **Verify.** `Deploy finished` means the rollout finished, not that the app works. Run `curl -sS -o /dev/null -w '%{http_code}\n' https:///`, then a real page or API call, checking its content. + +## When it fails +| CLI prints | Do | +|---|---| +| `could not find required file 'kool.cloud.yml'`, `no kool.cloud.yml config files found` | Run from the repo root and create the file. | +| `build entry 'X' is not a directory` | Use `build: .` or the map form. | +| `defines a build directory ('X') that does not exist` | Fix the path; it is relative to the repo root. | +| ``is public, but it does not define the `expose` entry`` | Add `expose: ` as an integer. | +| `yaml: ...`, `cannot unmarshal` | Fix the YAML: `expose` must be an int and `{{ }}` must be quoted. | +| `missing deploy domain` | Pass `--domain `. | +| `missing Kool.dev Cloud API token` | Ask the human to export `KOOL_API_TOKEN`. | +| `setup command is not available in non-interactive mode` | Write the files yourself. | +| `file not found, not including on tarball: X` | Create X (the env file) first, or the deploy fails on the server. | +| `401 - Unauthenticated.` | The token is wrong or revoked: ask the human. | +| `402 - Your trial has expired...` | The human must add a payment method. | +| `token > ...project-scoped token` | Ask for a project-scoped token. | +| `token > This token is scoped to environment 'X'` | Deploy to domain X. | +| `environment > Token does not have permission for this environment.` | Another team owns the domain: pick another name. | +| `deploy > Kool Cloud no longer builds images...` | Upgrade the kool CLI. | +| A Docker build error | Fix the Dockerfile; reproduce with `docker build .`. | +| `qemu: uncaught target signal 11`, `exec format error` during the build | Move that step into a `$BUILDPLATFORM` stage. | +| `Cannot connect to the Docker daemon` | Ask the human to start Docker. | +| `deploy failed` | Read the reason; see below. | +| `timeout waiting deploy to finish` | The CLI stopped waiting (15 minutes; 3.9.0 also stops on one failed status check). Check the status and curl the URL before redeploying. | +| `500 - Server Error` from `logs` or `exec` | Nothing is running for that service yet, for example because the first deploy rolled back. | + +**Reading why a deploy failed.** Don't use `--verbose`. Take the ID from `Logs available at: https://kool.dev/deploys/?source=cli` and run this (the `printf` keeps the token out of argv): +```bash +curl -sS -H @<(printf 'Authorization: Bearer %s\n' "$KOOL_API_TOKEN") -H 'Accept: application/json' \ + "https://kool.dev/api/deploy//status" | jq -r '.status, .error' +``` +Without `jq`, drop the pipe: the JSON is small. Newer CLIs print the reason after `deploy failed:` themselves. +- `context deadline exceeded`, or pods not ready: the new pods were not ready within 5 minutes and the deploy rolled back. A container must accept TCP on `expose` within about 40 seconds of starting. Suspects, in order: + - a wrong-arch image; + - the app listening on 127.0.0.1 or on another port; + - a missing env var or database; + - OOM at `micro` (raise `size`); + - a crashing daemon or a failing `before` hook; + - an `ENTRYPOINT` that ignores its arguments. + + The failed pod is gone, so reproduce locally: `docker build -t smoke . && docker run --rm -p 8080: smoke`, then `docker rmi smoke`. +- `BackoffLimitExceeded`: an `after` hook failed. Run its command locally. +- `Malformed inline YAML` near `{{`: quote the placeholder. + +## Stack references (read the one that matches) +- Laravel: [references/laravel.md](references/laravel.md) +- Static HTML: [references/static.md](references/static.md) +- Vite/React SPA: [references/spa.md](references/spa.md) +- Next.js, with Prisma and SQLite: [references/nextjs.md](references/nextjs.md) +- Node API (Express, Nest): [references/node.md](references/node.md) +- Docs: https://kool.dev/docs/kool-cloud/kool-cloud-yml-reference. Where the docs disagree with this file, trust this file. diff --git a/skills/kool-cloud-deploy/references/laravel.md b/skills/kool-cloud-deploy/references/laravel.md new file mode 100644 index 00000000..2226658a --- /dev/null +++ b/skills/kool-cloud-deploy/references/laravel.md @@ -0,0 +1,80 @@ +# Laravel on Kool Cloud +This is the shape of a production Laravel app on Kool: the `kooldev/php` prod image, migrations in a hook, the queue worker as a daemon, the scheduler as a cron job, and env from a git-ignored file. +```yaml +# kool.cloud.yml +services: + app: + build: . + expose: 80 + public: true + size: small # micro (256Mi) is too small for php-fpm + nginx + root: /app + environment: kool.deploy.env # git-ignored dotenv file, uploaded at each deploy + readinessProbe: # the /up route ships with Laravel 11+ + httpGet: { path: /up, port: 80 } + after: # once per deploy, after the new pods are up + - [php, artisan, migrate, --force] + daemons: # Horizon: [php, artisan, horizon] at size medium + - command: [php, artisan, queue:work, --tries=3, --max-time=3600] + size: small + cron: + - schedule: "* * * * *" + command: [php, artisan, schedule:run] + persists: # only if files are stored locally (drop it for S3) + size: 1Gi + paths: + - { path: storage, sync: true, chown: "kool:kool" } # /app/storage, seeded from the image + database: + image: mysql:8.0 + cloud: true # managed shared MySQL 8; fills {{KOOL_DATABASE_*}} +``` +```dockerfile +# Dockerfile. Prod image: opcache on (validate_timestamps=0), nginx and php-fpm workers run +# as `kool`, and the entrypoint runs hooks/daemons/cron as `kool`. Don't add USER. +FROM kooldev/php:8.4-debian-nginx-prod AS app +COPY --chown=kool:kool composer.json composer.lock /app/ +RUN composer install --no-dev --prefer-dist --no-progress --no-scripts --no-autoloader +COPY --chown=kool:kool . /app +RUN composer install --no-dev --prefer-dist --no-progress --optimize-autoloader + +# Vite assets are arch-independent: build them natively (no package.json? delete the stage) +FROM --platform=$BUILDPLATFORM node:24-slim AS assets +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +COPY --from=app /app/vendor ./vendor +RUN npm run build + +FROM app +COPY --chown=kool:kool --from=assets /app/public/build /app/public/build +RUN ln -sfn /app/storage/app/public /app/public/storage +``` +Match the image tag to composer.json's PHP version: 8.2 to 8.5 exist. + +`.dockerignore`, one pattern per line: `.git`, `.env*`, `kool.deploy.env`, `node_modules`, `vendor`, `public/build`, `public/hot`, `public/storage`, `storage/logs/*.log`, `storage/framework/views/*.php`, `database/*.sqlite`. + +## kool.deploy.env (add it to .gitignore; never print it) +```dotenv +APP_ENV=production +APP_DEBUG=false +APP_URL=https://myapp.kool.cloud +LOG_CHANNEL=stderr +DB_CONNECTION=mysql +DB_HOST="{{KOOL_DATABASE_HOST}}" +DB_PORT="{{KOOL_DATABASE_PORT}}" +DB_DATABASE="{{KOOL_DATABASE_DATABASE}}" +DB_USERNAME="{{KOOL_DATABASE_USERNAME}}" +DB_PASSWORD="{{KOOL_DATABASE_PASSWORD}}" +``` +- **APP_KEY:** generate it once without displaying it, with `printf 'APP_KEY=base64:%s\n' "$(openssl rand -base64 32)" >> kool.deploy.env`, and never regenerate it: a new key breaks sessions and encrypted data. Or write `APP_KEY="{{APP_KEY}}"` and have the human set APP_KEY in the panel. +- **Variables:** only this file's variables reach the containers; the panel's variables only fill `{{ }}`. With your own database, delete the `database` service and write literal `DB_*` values. +- **Logs:** `LOG_CHANNEL=stderr` sends the logs to `kool cloud logs app`. + +## Notes +- **Migrations:** `after` runs once per deploy, so the new code serves for a few seconds before they finish. A `before` hook works too, the first deploy included, but it runs at every pod start and in each replica. With `replicas` above 1, a `before` hook needs `--isolated=1` and a Redis cache (the database cache's lock table doesn't exist on the first deploy). +- **Scheduler and queue:** each scheduler run is a fresh pod, so `runInBackground()` tasks die when the pod exits; send long work to the queue. Queue workers are daemons in the app pod, so they restart with every deploy and scale with `replicas`. +- **`storage` persistence:** ownership on the disk comes from the image (`COPY --chown`); `chown` applies only when the path is missing from the image. `persists` makes each deploy stop-then-start, and on a first deploy `before` hooks see an empty `storage`. +- **HTTPS:** TLS ends at Kool's ingress, so trust the proxy, or `asset()` URLs and redirects come out as `http://`. On Laravel 11+, put `$middleware->trustProxies(at: '*');` in `bootstrap/app.php`. +- **Caching:** don't run `config:cache` at build time (the env only arrives at runtime) or in a hook (hooks have their own filesystem). +- **docker-compose.yml (kool preset, Sail):** its services are merged in. Keep `environment:` on `app` so the compose `${...}` values don't carry over. Set `deploy: false` on compose services you don't deploy. To run Redis in the cluster, add `cache: {image: redis:7-alpine, expose: 6379}` and set `REDIS_HOST=cache`. diff --git a/skills/kool-cloud-deploy/references/nextjs.md b/skills/kool-cloud-deploy/references/nextjs.md new file mode 100644 index 00000000..5b38dd51 --- /dev/null +++ b/skills/kool-cloud-deploy/references/nextjs.md @@ -0,0 +1,79 @@ +# Next.js on Kool Cloud (including Prisma + SQLite) + +This shape is proven on Kool: Next.js 16 App Router, plus Prisma 7 with SQLite through `@prisma/adapter-better-sqlite3`. Without a database, drop the `prisma` lines and the `persists` and `DATABASE_URL` entries. + +```yaml +# kool.cloud.yml +services: + app: + build: . + expose: 3000 + public: true + size: small # micro (256Mi) is tight for `next start` + environment: + NODE_ENV: production + NEXT_TELEMETRY_DISABLED: "1" + DATABASE_URL: "file:/app/data/prod.db" # SQLite on the persisted disk + persists: + size: 1Gi + paths: + - path: /app/data # never `sync: true` here: it would overwrite the db +``` + +```dockerfile +# Dockerfile +# builder: the host's native arch. Turbopack's `next build` segfaults under QEMU on Apple +# Silicon, and .next plus the generated Prisma client are arch-independent. +FROM --platform=$BUILDPLATFORM node:24-bookworm-slim AS builder +RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /app +ENV NEXT_TELEMETRY_DISABLED=1 DATABASE_URL=file:/tmp/build.db +COPY package.json package-lock.json prisma.config.ts ./ +COPY prisma ./prisma +RUN npm ci +COPY . . +RUN npx prisma generate && npm run build + +# runner: the cluster's arch (amd64). npm ci here installs native modules +# (better-sqlite3, sharp) for that arch. +FROM node:24-bookworm-slim AS runner +RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ openssl ca-certificates \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY package.json package-lock.json prisma.config.ts ./ +COPY prisma ./prisma +RUN npm ci +COPY . . +COPY --from=builder /app/.next ./.next +COPY --from=builder /app/src/generated ./src/generated +RUN mkdir -p /app/data +ENV NODE_ENV=production +EXPOSE 3000 +CMD ["sh", "-c", "npx prisma migrate deploy && exec npx next start -H 0.0.0.0 -p 3000"] +``` +- `src/generated` is the Prisma 7 generator `output`; use the path from your schema. +- A config file with another name needs `--config ` on the prisma commands. + +```gitignore +# .dockerignore +.git +.env* +node_modules +.next +out +*.db +*.db-journal +``` +Without this, the host's `node_modules` (macOS/arm64 binaries) and `.env` overwrite the image's. + +## Notes +- **Migrations:** they run in `CMD`, before `next start`. The SQLite file lives inside this pod's disk, and `persists` makes each deploy stop-then-start, so there is only ever one writer. `before: [[npx, prisma, migrate, deploy]]` also works, the first deploy included. +- **Replicas:** keep one. SQLite can't be shared across pods; for more replicas, use a server database (Postgres or MySQL) through `DATABASE_URL`. +- **Prisma 7:** `prisma migrate deploy` needs `datasource.url` in `prisma.config.ts` (for example `env("DATABASE_URL")`), and Prisma no longer reads `.env` by itself. Keep `.env` out of the image, or its local `DATABASE_URL` wins at build time. +- **Native build tools:** `better-sqlite3` needs `python3 make g++` when no prebuilt binary matches. Always run `npm ci` inside the image, never copy `node_modules` in. +- **Dependencies in the runner:** it uses a full `npm ci` because the `prisma` CLI is usually a devDependency. Move `prisma` to `dependencies` to use `npm ci --omit=dev`. +- **`NEXT_PUBLIC_*` values are inlined at build time.** Pass them as build args (see spa.md); runtime `environment:` won't change them. +- **Build-time `DATABASE_URL`:** the builder's value is a throwaway that only lets `prisma generate` and `next build` load the config. Pages that query the database at build time must be dynamic. +- **Bind to 0.0.0.0:** `-H 0.0.0.0` keeps `next start` listening on all interfaces whatever `HOSTNAME` holds; Kubernetes may set it to the pod name. +- **Verify:** `curl -sS https:/// | grep -i ''`. Then, if the app has a write API, POST to it and GET the result back, which proves the database is writable. To look at the file: `kool cloud exec --domain <d> app ls -la /app/data`. diff --git a/skills/kool-cloud-deploy/references/node.md b/skills/kool-cloud-deploy/references/node.md new file mode 100644 index 00000000..4e3a42a7 --- /dev/null +++ b/skills/kool-cloud-deploy/references/node.md @@ -0,0 +1,64 @@ +# Node API (Express, NestJS) on Kool Cloud + +The TypeScript build runs natively. The runtime stage installs only production dependencies, for the cluster's arch, and runs as the non-root `node` user. + +```yaml +# kool.cloud.yml +services: + app: + build: . + expose: 3000 + public: true + size: small + environment: + NODE_ENV: production + PORT: "3000" # the app must listen on it, on 0.0.0.0 + DATABASE_URL: "{{DATABASE_URL}}" # set DATABASE_URL in the Kool panel + readinessProbe: # optional; any route that answers 200 fast + httpGet: { path: /health, port: 3000 } + after: + - [npx, prisma, migrate, deploy] # or your ORM's migrate command; drop if none + daemons: + - command: [node, dist/worker.js] # optional background worker, same image +``` + +```dockerfile +# Dockerfile +# build: native arch, because the compiled JS is arch-independent. +FROM --platform=$BUILDPLATFORM node:24-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +RUN npm run build # nest build / tsc -> dist/ + +# runtime: the cluster's arch. npm ci here gets the native modules right. +FROM node:24-bookworm-slim +WORKDIR /app +ENV NODE_ENV=production +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev && npm cache clean --force +COPY --from=build /app/dist ./dist +USER node +EXPOSE 3000 +CMD ["node", "dist/main.js"] +``` +- **Plain JavaScript Express, with no build step:** drop the first stage, replace the `COPY --from=build` line with `COPY --chown=node:node . .`, and use `CMD ["node", "server.js"]`. +- **Migration CLIs** (`prisma`, `knex`, `typeorm`, `drizzle-kit`) must be in `dependencies`, because `--omit=dev` drops devDependencies. Prisma also needs `COPY prisma ./prisma` and `RUN npx prisma generate` in the runtime stage. + +```gitignore +# .dockerignore +.git +.env* +node_modules +dist +coverage +``` + +## Notes +- **Listening:** use `app.listen(process.env.PORT ?? 3000)`, or `'0.0.0.0'` as the host. A host of `localhost` or `127.0.0.1` fails the liveness probe, and the deploy rolls back after 5 minutes. Nest's default, `await app.listen(3000)`, is fine. +- **ENTRYPOINT:** keep the node image's `docker-entrypoint.sh` and use `CMD`. Hooks, daemons and cron commands are passed to it as arguments, and it runs them. +- **Databases:** `cloud: true` gives managed MySQL 8 only (see laravel.md). For Postgres or anything else, use an external `DATABASE_URL`, kept as a panel variable through `"{{DATABASE_URL}}"` or in a git-ignored env file (`environment: kool.deploy.env`). +- **Persisted paths:** a fresh `persists` path may mount root-owned. If the app writes there while running as `USER node`, check that it can write (`kool cloud exec ... touch <path>/x`), or drop `USER` for that service, as the proven Next.js setup does. +- **Workers and scheduled jobs:** a queue consumer is a daemon (`command: [node, dist/worker.js]`, logs with `-c daemon0`). A scheduled job is a `cron` entry that runs a script and exits; don't keep a `node-cron` loop inside the web process if `replicas` is above 1. +- **Verify:** `curl -sS https://<domain>/health`, then one real endpoint with its expected JSON, for example `curl -sS -X POST -H 'content-type: application/json' -d '{...}' https://<domain>/api/...`. diff --git a/skills/kool-cloud-deploy/references/spa.md b/skills/kool-cloud-deploy/references/spa.md new file mode 100644 index 00000000..15f88cc3 --- /dev/null +++ b/skills/kool-cloud-deploy/references/spa.md @@ -0,0 +1,68 @@ +# Vite / React SPA on Kool Cloud + +Build the bundle in a node stage, then serve `dist/` from nginx with an SPA fallback. + +```yaml +# kool.cloud.yml +services: + app: + build: + context: . + args: # VITE_* values are baked in at build time + VITE_API_URL: "https://api.example.com" + expose: 80 + public: true +``` +With no `VITE_*` variables, `build: .` is enough. + +```dockerfile +# Dockerfile +# The bundle is arch-independent: build it natively. On Apple Silicon an amd64 node +# stage would run under QEMU, where Rolldown or esbuild can segfault. +FROM --platform=$BUILDPLATFORM node:24-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY . . +ARG VITE_API_URL +ENV VITE_API_URL=$VITE_API_URL +RUN npm run build + +FROM nginx:1.27-alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html +EXPOSE 80 +``` +For pnpm or yarn, replace the lockfile and the install command (`pnpm install --frozen-lockfile`, `yarn install --immutable`). + +```nginx +# nginx.conf +server { + listen 80; + root /usr/share/nginx/html; + index index.html; + location /assets/ { + expires 1y; + add_header Cache-Control "public, immutable"; + try_files $uri =404; + } + location / { + try_files $uri $uri/ /index.html; # SPA fallback: BrowserRouter deep links + } +} +``` + +```gitignore +# .dockerignore +.git +.env* +node_modules +dist +``` + +## Notes +- **The fallback is required.** Without `try_files ... /index.html`, deep links such as `/pricing` return 404 from nginx. HashRouter doesn't need it. +- **`VITE_*` values are compile-time.** Setting `environment:` in kool.cloud.yml has no effect on a built SPA. Pass build args as above: `"$VAR"` is read from your shell, and `"{{VAR}}"` from the environment's variables in the Kool panel. Never put secrets in `VITE_*`, because they ship to every browser. +- **`.env*` stays out of the image.** Vite would read a local `.env.production` during the build and bake its values into the bundle. +- **Other build output.** Some tools emit `build/` instead of `dist/` (for example Create React App), and some apps use a custom `base` path. Adjust the `COPY --from=build` path to match. +- **Verify:** `curl -sS https://<domain>/ | grep -i '<title>'`, then `curl -sS -o /dev/null -w '%{http_code}\n' https://<domain>/some/deep/route`, which must print 200. diff --git a/skills/kool-cloud-deploy/references/static.md b/skills/kool-cloud-deploy/references/static.md new file mode 100644 index 00000000..ad738ecb --- /dev/null +++ b/skills/kool-cloud-deploy/references/static.md @@ -0,0 +1,54 @@ +# Static site (plain HTML/CSS/JS) on Kool Cloud + +nginx serves the files as they are, with no build step. Files in a `dist/` or `public/` folder work the same way: copy that folder instead. + +```yaml +# kool.cloud.yml +services: + app: + build: . + expose: 80 + public: true +``` + +```dockerfile +# Dockerfile +FROM nginx:1.27-alpine +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY . /usr/share/nginx/html +EXPOSE 80 +``` +`nginx:alpine` is multi-arch, so the image builds for amd64 without emulating any build step. Keep the image's own `CMD`: it runs nginx in the foreground. + +```nginx +# nginx.conf +server { + listen 80; + root /usr/share/nginx/html; + index index.html; + location / { + try_files $uri $uri/ $uri.html =404; + } +} +``` +`try_files` makes `/about` serve `about.html`. Change `=404` to `/404.html` if the site has a custom error page. + +```gitignore +# .dockerignore +.git +.env* +Dockerfile +nginx.conf +.dockerignore +kool.cloud.yml +docker-compose.yml +node_modules +README.md +``` +`COPY .` would otherwise publish these files, including `.git` and any `.env`, at public URLs. + +## Notes +- Don't write a docker-compose.yml: Kool doesn't need one. If one already exists, its services are merged into the deploy, so check that every service in it is meant to be deployed. +- The site's content is baked into the image, so redeploy after every change: `kool cloud deploy --domain <name>.kool.cloud`. +- Verify: `curl -sS https://<domain>/ | grep -i '<title>'`, and request one asset, such as `/app.js`, to check it returns 200. +- Forms or a waitlist need a backend that the browser can reach. Use an external form service, or deploy an API (see node.md) as its own app on its own domain. diff --git a/templates/agents/AGENTS.kool.md b/templates/agents/AGENTS.kool.md new file mode 100644 index 00000000..4ef181c2 --- /dev/null +++ b/templates/agents/AGENTS.kool.md @@ -0,0 +1,35 @@ +<!-- kool:begin (written by kool; edits between these markers are replaced on update) --> +## Kool: local Docker and Kool Cloud deploys + +**Local dev** (defined in docker-compose.yml and kool.yml): +- `kool start` / `kool stop` / `kool status` +- `kool exec <service> <cmd>` +- `kool logs -f <service>` +- `kool run <script>`; list scripts with `kool run --json` + +**Deploy to Kool Cloud.** The full guide is the `kool-cloud-deploy` skill (github.com/kool-dev/kool, `skills/kool-cloud-deploy`). Docs: https://kool.dev/docs/kool-cloud/kool-cloud-yml-reference + +- **Files.** Write them by hand: `kool cloud setup` needs a TTY. + - `kool.cloud.yml` at the repo root, plus a production `Dockerfile` and a `.dockerignore` (`.git`, `.env*`, env files, `node_modules`, build output, `*.db`). + - No docker-compose.yml is needed. If one exists, its services deploy too, unless kool.cloud.yml sets `deploy: false` on them. + - Minimal config: `services: {app: {build: ., expose: <port>, public: true}}`. `build` is a directory, not a Dockerfile path. `expose` is an integer and is required by `public`. The app must listen on 0.0.0.0:<port>. +- **Token.** It comes from `KOOL_API_TOKEN` in the environment or the git-ignored `.env`. Never pass `--token`, never print the token, never ask for it in chat. +- **Deploy.** Run `kool cloud deploy --domain <unique-name>.kool.cloud` from the repo root, in the foreground, with the longest tool timeout (20 minutes or more). Never background it, and never end the session while it runs. +- **Architecture.** The shared cloud is linux/amd64, the CLI default: don't pass `--platform`. For a BYOC cluster, pass `--platform linux/arm64` only if the user says its nodes are arm64. On Apple Silicon, build JS/assets in a `FROM --platform=$BUILDPLATFORM` stage, because QEMU can segfault. +- **Never `--verbose`.** It prints the registry password and the environment's variables. +- **Hooks.** + - `after` runs once per deploy, after the rollout. + - `before` is an init container in every new pod: it runs on the first deploy, on restarts and in each replica. + - Hook, `daemons` and `cron` commands are passed as arguments to the image ENTRYPOINT, so start the app with `CMD`. +- **Debug.** + - `kool cloud logs --domain <d> <service>` (daemons: `-c daemon0`) and `kool cloud exec --domain <d> <service> <cmd>`. + - On `deploy failed`, read `.error` from `GET https://kool.dev/api/deploy/<ID>/status`. The ID is in the printed `Logs available at:` URL; the skill shows a token-safe curl. + - "Pods not ready" or `context deadline exceeded` means the new pods weren't ready within 5 minutes and the deploy rolled back. Common causes: + - a wrong-arch image; + - the app bound to 127.0.0.1 or to another port; + - a missing env var or database; + - an out-of-memory kill at the default `micro` size (set `size: small`); + - a crashing daemon. +- **`persists`.** It gives one disk per service and makes each deploy stop-then-start. Never set `sync: true` on a database path. +- **Verify.** Curl the URL, then a real page or API call. `Deploy finished` only means the rollout finished. +<!-- kool:end --> From 8359d7875f71f493f9ae490c529ca44000fc124b Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 17:45:55 -0300 Subject: [PATCH 3/9] fix(redact): redact quoted values through their closing quote password='...' was left as it was, and a double-quoted value with a space showed everything after it. A quoted value now runs through its closing quote, skipping escaped characters, before falling back to the unquoted pattern; blank values are still kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- core/redact/redact.go | 48 ++++++++++++++++++++++++++++++++++---- core/redact/redact_test.go | 18 ++++++++++++++ 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/core/redact/redact.go b/core/redact/redact.go index b4c960e5..598638cb 100644 --- a/core/redact/redact.go +++ b/core/redact/redact.go @@ -133,14 +133,15 @@ func redactKeyValues(s string) string { continue } - value := valueRe.FindString(s[m[1]:]) - if value == "" { + start, end := valueBounds(s, m[1], s[m[4]:m[5]]) + if start == end { + // blank value; keeping it shows the credential is missing continue } - redacted.WriteString(s[last:m[1]]) + redacted.WriteString(s[last:start]) redacted.WriteString(Placeholder) - last = m[1] + len(value) + last = end } redacted.WriteString(s[last:]) @@ -148,6 +149,45 @@ func redactKeyValues(s string) string { return redacted.String() } +// valueBounds finds the value of a credential-like pair that starts at +// from, right after the given separator. A quoted value runs through its +// closing quote, skipping escaped characters, and keeps its quotes; any +// other value runs up to the next space or delimiter. +func valueBounds(s string, from int, sep string) (start, end int) { + var quote byte + + start = from + if strings.HasSuffix(sep, `"`) { + // the separator took the opening quote, as in "secret":"..." + quote = '"' + } else if from < len(s) && (s[from] == '"' || s[from] == '\'') { + quote = s[from] + start++ + } + + if quote != 0 { + if n := closingQuote(s[start:], quote); n >= 0 { + return start, start + n + } + } + + return start, start + len(valueRe.FindString(s[start:])) +} + +// closingQuote returns the index of the first unescaped quote in s, or -1 +func closingQuote(s string, quote byte) int { + for i := 0; i < len(s); i++ { + switch s[i] { + case '\\': + i++ + case quote: + return i + } + } + + return -1 +} + // Args redacts the arguments of a command line: values of credential flags // (--token, --password, and -u/-p of a login command), credential-like // KEY=VALUE pairs and token-looking values diff --git a/core/redact/redact_test.go b/core/redact/redact_test.go index d8e772d4..15868f11 100644 --- a/core/redact/redact_test.go +++ b/core/redact/redact_test.go @@ -102,6 +102,8 @@ func TestJSONFallsBackToText(t *testing.T) { `<html>password=hunter2</html>`, `{"password":"hunter2"} trailing`, `{"password":"hunter2"`, + `{"password":"hunter 2 hunter2"`, + `<html>password='hunter2'</html>`, } { if redacted := JSON([]byte(raw)); strings.Contains(redacted, "hunter2") { t.Errorf("expected password to be redacted from %q; got %q", raw, redacted) @@ -122,6 +124,17 @@ func TestText(t *testing.T) { {"login with " + fakeRegistryToken + " now", "login with [REDACTED] now"}, {"key 1|Zx9kQ2LmP4rT7vWb1NcY8sHd3FgJ6aKe0uIoPq", "key 1|[REDACTED]"}, {"hex 0123456789abcdef0123456789abcdef0123", "hex [REDACTED]"}, + // quoted values are redacted through their closing quote + {"password='hunter2'", "password='[REDACTED]'"}, + {`password="hunter 2" DB_HOST=db`, `password="[REDACTED]" DB_HOST=db`}, + {"token: 'hunter 2' id=1", "token: '[REDACTED]' id=1"}, + {`password='it\'s secret' id=1`, `password='[REDACTED]' id=1`}, + {`{"secret":"ab\"cd ef","id":1}`, `{"secret":"[REDACTED]","id":1}`}, + {`"secret": "a token=b c", "id": 1`, `"secret": "[REDACTED]", "id": 1`}, + {`password="hunter2`, `password="[REDACTED]`}, + // blank credentials stay as they are + {`password='' token=""`, `password='' token=""`}, + {`{"secret": "", "id": 1}`, `{"secret": "", "id": 1}`}, // not credentials {"Going to call: https://kool.dev/api/deploy/create?", "Going to call: https://kool.dev/api/deploy/create?"}, {"/Users/someone/Projects/Kool2026/apps/node-20/src", "/Users/someone/Projects/Kool2026/apps/node-20/src"}, @@ -167,6 +180,11 @@ func TestArgs(t *testing.T) { []string{"run", "-p", "8080:80", "-u", "1000", "-e", "SECRET=" + fakeRegistryToken, "image", fakeRegistryToken}, []string{"run", "-p", "8080:80", "-u", "1000", "-e", "SECRET=[REDACTED]", "image", "[REDACTED]"}, }, + { + // a shell script passed as a single argument + []string{"sh", "-c", "echo token: 'hunter 2' && echo secret: \"hunter 2\""}, + []string{"sh", "-c", "echo token: '[REDACTED]' && echo secret: \"[REDACTED]\""}, + }, } for _, tt := range tests { From 16c27dd2e921c5dddcf3117161d9eda9e0cfaa3f Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 17:46:14 -0300 Subject: [PATCH 4/9] fix(cloud): redact the reason, hint and detail of a failed deploy They are printed on the ordinary error path, not only with --verbose, and may quote the app's own output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- commands/cloud_deploy.go | 10 ++++++---- commands/cloud_deploy_test.go | 6 ++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/commands/cloud_deploy.go b/commands/cloud_deploy.go index 3f2bf3f1..c0ddee56 100644 --- a/commands/cloud_deploy.go +++ b/commands/cloud_deploy.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "kool-dev/kool/core/environment" + "kool-dev/kool/core/redact" "kool-dev/kool/core/shell" "kool-dev/kool/core/utils" "kool-dev/kool/services/cloud" @@ -315,7 +316,8 @@ func (d *KoolDeploy) pollDeployStatus(fetch func() (*api.DeployStatusResponse, e } // deployFailedError explains why a deploy did not succeed, with the reason -// reported by Kool.dev Cloud and where to find the full logs. +// reported by Kool.dev Cloud and where to find the full logs. The reason, +// hint and detail are redacted, as they may quote the app's own output. func deployFailedError(status *api.DeployStatusResponse, logsURL string) error { msg := "deploy failed" if status.Status == "timedout" { @@ -323,15 +325,15 @@ func deployFailedError(status *api.DeployStatusResponse, logsURL string) error { } if reason := strings.TrimSpace(status.Error); reason != "" { - msg += ": " + reason + msg += ": " + redact.Text(reason) } if hint := strings.TrimSpace(status.Hint); hint != "" { - msg += "\nHint: " + hint + msg += "\nHint: " + redact.Text(hint) } if detail := strings.TrimSpace(status.Detail); detail != "" { - msg += "\nDetail: " + detail + msg += "\nDetail: " + redact.Text(detail) } return withDeployLogs(errors.New(msg), logsURL) diff --git a/commands/cloud_deploy_test.go b/commands/cloud_deploy_test.go index 6e0f3a9f..f7ec71a4 100644 --- a/commands/cloud_deploy_test.go +++ b/commands/cloud_deploy_test.go @@ -315,6 +315,12 @@ func TestDeployFailedError(t *testing.T) { "https://kool.dev/deploys/1", "deploy failed: migrate hook failed\nHint: check your migrations\nDetail: SQLSTATE[42S01]\nLogs available at: https://kool.dev/deploys/1", }, + { + // credentials quoted by the diagnostics never reach the output + api.DeployStatusResponse{Status: "failed", Error: "connect mysql://app:hunter2@db/app failed", Hint: "check DB_PASSWORD='hunter2'", Detail: "DB_PASSWORD=hunter2 DB_HOST=db"}, + "https://kool.dev/deploys/1", + "deploy failed: connect mysql://app:[REDACTED]@db/app failed\nHint: check DB_PASSWORD='[REDACTED]'\nDetail: DB_PASSWORD=[REDACTED] DB_HOST=db\nLogs available at: https://kool.dev/deploys/1", + }, } for _, tt := range tests { From 37e14389aaadf13ac16116e8e8091e039503e84e Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 17:46:41 -0300 Subject: [PATCH 5/9] fix(cloud): don't end a failed deploy with "Deploy finished." The loading indicator printed its completion message for failed and timed-out deploys too, right before the failure. Only a successful deploy keeps it now. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- commands/cloud_deploy.go | 12 +++++----- commands/cloud_deploy_test.go | 43 ++++++++++++++++++++++------------- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/commands/cloud_deploy.go b/commands/cloud_deploy.go index c0ddee56..d86494a8 100644 --- a/commands/cloud_deploy.go +++ b/commands/cloud_deploy.go @@ -183,9 +183,9 @@ func (d *KoolDeploy) Execute(args []string) (err error) { s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream()) - err = d.waitDeploy(deployCreated, finishes, time.After(timeout), interrupted, func(finished bool) { - if !finished { - // the deploy did not finish as far as we know + err = d.waitDeploy(deployCreated, finishes, time.After(timeout), interrupted, func(succeeded bool) { + if !succeeded { + // only a successful deploy ends with "Deploy finished." s.FinalMSG = "" } s.Stop() @@ -196,11 +196,11 @@ func (d *KoolDeploy) Execute(args []string) (err error) { // waitDeploy waits for whichever comes first: the deploy to finish, the // timeout or the CLI being interrupted, stopping the loading indicator -// before printing the outcome -func (d *KoolDeploy) waitDeploy(deployCreated *api.DeployCreateResponse, finishes <-chan deployWaitResult, timeout <-chan time.Time, interrupted <-chan os.Signal, stopLoading func(finished bool)) (err error) { +// before printing the outcome; succeeded tells whether the deploy is live +func (d *KoolDeploy) waitDeploy(deployCreated *api.DeployCreateResponse, finishes <-chan deployWaitResult, timeout <-chan time.Time, interrupted <-chan os.Signal, stopLoading func(succeeded bool)) (err error) { select { case result := <-finishes: - stopLoading(result.err == nil) + stopLoading(result.err == nil && result.status.Status == "success") if result.err != nil { err = withDeployLogs(result.err, deployCreated.LogsUrl) diff --git a/commands/cloud_deploy_test.go b/commands/cloud_deploy_test.go index f7ec71a4..8ce6f399 100644 --- a/commands/cloud_deploy_test.go +++ b/commands/cloud_deploy_test.go @@ -360,13 +360,13 @@ func TestWaitDeployInterrupted(t *testing.T) { interrupted := make(chan os.Signal, 1) interrupted <- sig - var stopped, finished bool - err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), make(chan time.Time), interrupted, func(f bool) { - stopped, finished = true, f + var stopped, succeeded bool + err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), make(chan time.Time), interrupted, func(ok bool) { + stopped, succeeded = true, ok }) - if !stopped || finished { - t.Errorf("expected the loading indicator stopped as not finished; got stopped=%v finished=%v", stopped, finished) + if !stopped || succeeded { + t.Errorf("expected the loading indicator stopped as not succeeded; got stopped=%v succeeded=%v", stopped, succeeded) } var exitable shell.ErrExitable @@ -396,27 +396,38 @@ func TestWaitDeployOutcomes(t *testing.T) { finishes := make(chan deployWaitResult, 1) finishes <- deployWaitResult{status: &api.DeployStatusResponse{Status: "success"}} - var finished bool - if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(f bool) { finished = f }); err != nil { + var succeeded bool + if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(ok bool) { succeeded = ok }); err != nil { t.Errorf("unexpected error for a successful deploy: %v", err) } - if !finished || !fake.shell.(*shell.FakeShell).CalledSuccess { + if !succeeded || !fake.shell.(*shell.FakeShell).CalledSuccess { t.Error("expected the successful deploy to be reported as finished") } - fake = fakeKoolDeploy("") - finishes <- deployWaitResult{status: &api.DeployStatusResponse{Status: "failed", Error: "pods not ready"}} - if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(bool) {}); err == nil || !strings.HasPrefix(err.Error(), "deploy failed: pods not ready") { - t.Errorf("expected failed deploy error; got %v", err) + // a deploy that ended unsuccessfully must not stop the loading + // indicator with its "Deploy finished." message + for status, expected := range map[string]string{"failed": "deploy failed: pods not ready", "timedout": "deploy timed out: pods not ready"} { + fake = fakeKoolDeploy("") + finishes <- deployWaitResult{status: &api.DeployStatusResponse{Status: status, Error: "pods not ready"}} + succeeded = true + if err := fake.waitDeploy(fakeStartedDeploy(), finishes, make(chan time.Time), make(chan os.Signal), func(ok bool) { succeeded = ok }); err == nil || !strings.HasPrefix(err.Error(), expected) { + t.Errorf("expected %q error; got %v", expected, err) + } + if succeeded { + t.Errorf("expected the loading indicator stopped as not succeeded for a %s deploy", status) + } + if fake.shell.(*shell.FakeShell).CalledSuccess { + t.Errorf("a %s deploy must not be reported as a success", status) + } } timeout := make(chan time.Time, 1) timeout <- time.Now() - finished = true - if err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), timeout, make(chan os.Signal), func(f bool) { finished = f }); err == nil || !strings.HasPrefix(err.Error(), "timeout waiting deploy to finish") { + succeeded = true + if err := fake.waitDeploy(fakeStartedDeploy(), make(chan deployWaitResult), timeout, make(chan os.Signal), func(ok bool) { succeeded = ok }); err == nil || !strings.HasPrefix(err.Error(), "timeout waiting deploy to finish") { t.Errorf("expected timeout error; got %v", err) } - if finished { - t.Error("expected the loading indicator stopped as not finished on timeout") + if succeeded { + t.Error("expected the loading indicator stopped as not succeeded on timeout") } } From 55f24665faf4c12bef6cf4042602114ab39b9c0b Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 17:49:00 -0300 Subject: [PATCH 6/9] fix(cloud): stop polling the deploy status once waiting ends After a timeout or an interrupt the status poller kept running and printing, which shows when kool cloud deploy runs inside another kool command. Polling now stops, with its sleep and its request, as soon as waiting ends, and a single status check gives up after 30 seconds so a hung request is retried like any other failed check. Endpoint gains SetContext, which cancels the request once done. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- commands/cloud_deploy.go | 59 ++++++++++++++++++++--- commands/cloud_deploy_test.go | 75 +++++++++++++++++++++++++++-- services/cloud/api/endpoint.go | 16 +++++- services/cloud/api/endpoint_test.go | 65 +++++++++++++++++++++++++ 4 files changed, 204 insertions(+), 11 deletions(-) diff --git a/commands/cloud_deploy.go b/commands/cloud_deploy.go index d86494a8..c33fc94b 100644 --- a/commands/cloud_deploy.go +++ b/commands/cloud_deploy.go @@ -1,6 +1,7 @@ package commands import ( + "context" "errors" "fmt" "kool-dev/kool/core/environment" @@ -169,14 +170,22 @@ func (d *KoolDeploy) Execute(args []string) (err error) { timeout = time.Duration(min) * time.Minute } + // polling stops, with its sleep and status request, as soon as waiting + // ends: this command may run inside another kool command, which must not + // get status lines after it + polling, stopPolling := context.WithCancel(context.Background()) + defer stopPolling() + var finishes = make(chan deployWaitResult, 1) go func(deployCreated *api.DeployCreateResponse, finishes chan deployWaitResult) { var result deployWaitResult - result.status, result.err = d.pollDeployStatus(func() (*api.DeployStatusResponse, error) { - return api.NewDeployStatus(deployCreated).Run() - }, time.Sleep) + result.status, result.err = d.pollDeployStatus(polling, func() (*api.DeployStatusResponse, error) { + return checkDeployStatus(polling, deployCreated) + }, func(wait time.Duration) { + sleepContext(polling, wait) + }) finishes <- result }(deployCreated, finishes) @@ -184,6 +193,8 @@ func (d *KoolDeploy) Execute(args []string) (err error) { s = utils.MakeSlowLoading("Waiting deploy to finish...", "Deploy finished.", d.Shell().OutStream()) err = d.waitDeploy(deployCreated, finishes, time.After(timeout), interrupted, func(succeeded bool) { + stopPolling() + if !succeeded { // only a successful deploy ends with "Deploy finished." s.FinalMSG = "" @@ -260,6 +271,8 @@ const ( deployStatusMaxAttempts = 5 // deployStatusMaxBackoff caps the wait before retrying a failed status check deployStatusMaxBackoff = 10 * time.Second + // deployStatusRequestTimeout is how long a single status check may take + deployStatusRequestTimeout = 30 * time.Second ) // deployWaitResult holds the outcome of waiting for a deploy to finish @@ -275,8 +288,9 @@ func isFinalDeployStatus(status string) bool { // pollDeployStatus checks the deploy status until it reaches a final state, // printing every status change. A failed check is retried with a short -// backoff, giving up after deployStatusMaxAttempts failures in a row. -func (d *KoolDeploy) pollDeployStatus(fetch func() (*api.DeployStatusResponse, error), wait func(time.Duration)) (status *api.DeployStatusResponse, err error) { +// backoff, giving up after deployStatusMaxAttempts failures in a row. Once +// ctx is done it stops and prints nothing else, returning ctx's error. +func (d *KoolDeploy) pollDeployStatus(ctx context.Context, fetch func() (*api.DeployStatusResponse, error), wait func(time.Duration)) (status *api.DeployStatusResponse, err error) { var ( current *api.DeployStatusResponse lastStatus string @@ -284,8 +298,13 @@ func (d *KoolDeploy) pollDeployStatus(fetch func() (*api.DeployStatusResponse, e backoff = deployStatusPollInterval ) - for { - if current, err = fetch(); err != nil { + for ctx.Err() == nil { + if current, err = fetch(); ctx.Err() != nil { + // waiting ended during the check + break + } + + if err != nil { if failures++; failures >= deployStatusMaxAttempts { err = fmt.Errorf("failed checking deploy status %d times in a row: %s", failures, strings.TrimSpace(err.Error())) return @@ -313,6 +332,32 @@ func (d *KoolDeploy) pollDeployStatus(fetch func() (*api.DeployStatusResponse, e wait(deployStatusPollInterval) } + + err = ctx.Err() + return +} + +// checkDeployStatus fetches the deploy status once, giving up after +// deployStatusRequestTimeout or as soon as ctx is done +func checkDeployStatus(ctx context.Context, deployCreated *api.DeployCreateResponse) (*api.DeployStatusResponse, error) { + ctx, cancel := context.WithTimeout(ctx, deployStatusRequestTimeout) + defer cancel() + + check := api.NewDeployStatus(deployCreated) + check.SetContext(ctx) + + return check.Run() +} + +// sleepContext waits for the given duration, or less if ctx is done first +func sleepContext(ctx context.Context, wait time.Duration) { + timer := time.NewTimer(wait) + defer timer.Stop() + + select { + case <-ctx.Done(): + case <-timer.C: + } } // deployFailedError explains why a deploy did not succeed, with the reason diff --git a/commands/cloud_deploy_test.go b/commands/cloud_deploy_test.go index 8ce6f399..d4aaae6d 100644 --- a/commands/cloud_deploy_test.go +++ b/commands/cloud_deploy_test.go @@ -1,6 +1,7 @@ package commands import ( + "context" "errors" "kool-dev/kool/core/environment" "kool-dev/kool/core/shell" @@ -224,7 +225,7 @@ func TestPollDeployStatusFinalStates(t *testing.T) { fetch, calls := fakeDeployStatuses("building", "deploying", "deploying", final) var waits []time.Duration - status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + status, err := fake.pollDeployStatus(context.Background(), fetch, func(d time.Duration) { waits = append(waits, d) }) if err != nil { t.Errorf("unexpected error polling until %s: %v", final, err) @@ -251,7 +252,7 @@ func TestPollDeployStatusRetriesFailedChecks(t *testing.T) { fetch, calls := fakeDeployStatuses("deploying", "", "", "", "deploying", "", "failed") var waits []time.Duration - status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + status, err := fake.pollDeployStatus(context.Background(), fetch, func(d time.Duration) { waits = append(waits, d) }) if err != nil { t.Errorf("unexpected error when status checks recover: %v", err) @@ -282,7 +283,7 @@ func TestPollDeployStatusGivesUp(t *testing.T) { fetch, calls := fakeDeployStatuses("deploying", "", "", "", "", "", "success") var waits []time.Duration - status, err := fake.pollDeployStatus(fetch, func(d time.Duration) { waits = append(waits, d) }) + status, err := fake.pollDeployStatus(context.Background(), fetch, func(d time.Duration) { waits = append(waits, d) }) if err == nil || err.Error() != "failed checking deploy status 5 times in a row: 503 - unavailable" { t.Errorf("unexpected error after failed status checks: %v", err) @@ -300,6 +301,74 @@ func TestPollDeployStatusGivesUp(t *testing.T) { } } +func TestPollDeployStatusStopsOnceWaitingEnds(t *testing.T) { + fake := fakeKoolDeploy("") + fetch, calls := fakeDeployStatuses("building", "deploying", "deploying", "success") + ctx, cancel := context.WithCancel(context.Background()) + + // waiting ends (timeout or interrupt) during the second wait + var waits int + status, err := fake.pollDeployStatus(ctx, fetch, func(time.Duration) { + if waits++; waits == 2 { + cancel() + } + }) + + if !errors.Is(err, context.Canceled) { + t.Errorf("expected polling to stop with the context error; got %v", err) + } + if status == nil || status.Status != "deploying" { + t.Errorf("expected last known status; got %+v", status) + } + if *calls != 2 { + t.Errorf("expected no status check once waiting ended; got %d checks", *calls) + } + + lines := fake.shell.(*shell.FakeShell).OutLines + if expected := []string{"> deploy: building", "> deploy: deploying"}; !reflect.DeepEqual(lines, expected) { + t.Errorf("expected nothing printed once waiting ended; got %v", lines) + } +} + +func TestPollDeployStatusStopsDuringCheck(t *testing.T) { + fake := fakeKoolDeploy("") + ctx, cancel := context.WithCancel(context.Background()) + + // waiting ends while a status check is in flight, which then fails + status, err := fake.pollDeployStatus(ctx, func() (*api.DeployStatusResponse, error) { + cancel() + return nil, context.Canceled + }, func(time.Duration) { + t.Error("expected no wait once waiting ended") + }) + + if !errors.Is(err, context.Canceled) || status != nil { + t.Errorf("expected polling to stop with the context error; got %+v, %v", status, err) + } + + fakeShell := fake.shell.(*shell.FakeShell) + if fakeShell.CalledWarning || len(fakeShell.OutLines) > 0 { + t.Errorf("expected nothing printed once waiting ended; got %v %v", fakeShell.WarningOutput, fakeShell.OutLines) + } +} + +func TestSleepContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + start := time.Now() + sleepContext(ctx, time.Minute) + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Errorf("expected the sleep to end once the context is done; took %s", elapsed) + } + + start = time.Now() + sleepContext(context.Background(), 10*time.Millisecond) + if elapsed := time.Since(start); elapsed < 10*time.Millisecond { + t.Errorf("expected to sleep for the given duration; took %s", elapsed) + } +} + func TestDeployFailedError(t *testing.T) { tests := []struct { status api.DeployStatusResponse diff --git a/services/cloud/api/endpoint.go b/services/cloud/api/endpoint.go index 0eedcd0e..048bd6ba 100644 --- a/services/cloud/api/endpoint.go +++ b/services/cloud/api/endpoint.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "context" "encoding/json" "fmt" "io" @@ -35,6 +36,7 @@ type Endpoint interface { Query() url.Values SetRawBody(io.Reader) SetContentType(string) + SetContext(context.Context) StatusCode() int PostFile(string, string, string) error @@ -50,6 +52,7 @@ type DefaultEndpoint struct { rawBody io.Reader env environment.EnvStorage statusCode int + ctx context.Context postBodyBuff bytes.Buffer postBodyFmtr *multipart.Writer @@ -125,6 +128,12 @@ func (e *DefaultEndpoint) SetContentType(contentType string) { e.contentType = contentType } +// SetContext sets the context of the request: once it is done, the +// request is cancelled +func (e *DefaultEndpoint) SetContext(ctx context.Context) { + e.ctx = ctx +} + // Body sets the URL path to be called func (e *DefaultEndpoint) Body() url.Values { if e.body == nil { @@ -190,7 +199,12 @@ func (e *DefaultEndpoint) DoCall() (err error) { _, _ = fmt.Fprintf(verboseOutput, "[Kool.dev Cloud] Going to call: %s\n", redact.Text(reqURL)) } - if request, err = http.NewRequest(e.method, reqURL, body); err != nil { + ctx := e.ctx + if ctx == nil { + ctx = context.Background() + } + + if request, err = http.NewRequestWithContext(ctx, e.method, reqURL, body); err != nil { return } diff --git a/services/cloud/api/endpoint_test.go b/services/cloud/api/endpoint_test.go index b6be00d6..b9d0a964 100644 --- a/services/cloud/api/endpoint_test.go +++ b/services/cloud/api/endpoint_test.go @@ -2,13 +2,16 @@ package api import ( "bytes" + "context" "errors" "io" "kool-dev/kool/core/environment" "net/http" + "net/http/httptest" "net/url" "strings" "testing" + "time" ) func newFakeDefaultEndpoint(method string) *DefaultEndpoint { @@ -383,3 +386,65 @@ func TestDoCallVerboseRedactsCredentials(t *testing.T) { } } } + +func TestDoCallStopsOnceContextIsDone(t *testing.T) { + e := newFakeDefaultEndpoint("GET") + e.env.Set("KOOL_API_TOKEN", "fake token") + + oldHTTPRequester, oldAPIBaseURL := httpRequester, apiBaseURL + defer func() { + httpRequester, apiBaseURL = oldHTTPRequester, oldAPIBaseURL + }() + + received, release := make(chan struct{}), make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(received) + // the API never answers + select { + case <-r.Context().Done(): + case <-release: + } + })) + defer server.Close() + defer close(release) + + httpRequester, apiBaseURL = server.Client(), server.URL + + ctx, cancel := context.WithCancel(context.Background()) + e.SetContext(ctx) + e.SetPath("deploy/1/status") + e.SetResponseReceiver(&struct{}{}) + + done := make(chan error, 1) + go func() { done <- e.DoCall() }() + + <-received + cancel() + + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Errorf("expected the call to be cancelled; got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("expected the call to stop once its context is done") + } +} + +func TestDoCallWithoutContext(t *testing.T) { + e := newFakeDefaultEndpoint("GET") + e.env.Set("KOOL_API_TOKEN", "fake token") + + oldHTTPRequester := httpRequester + defer func() { + httpRequester = oldHTTPRequester + }() + + httpRequester = &fakeHTTP{err: errors.New("fake http error")} + + _ = e.DoCall() + + if ctx := httpRequester.(*fakeHTTP).calledRequest.Context(); ctx != context.Background() { + t.Errorf("expected a request without context to use the background one; got %v", ctx) + } +} From a3d123299c9df3eacd53b56cbe7c1dfd03856e75 Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 17:49:17 -0300 Subject: [PATCH 7/9] docs(skills): keep nginx.conf in the static site's build context The example's .dockerignore left out nginx.conf, which the Dockerfile copies, so the build failed. It stays in the context now and is removed from the web root after COPY . so it isn't published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- skills/kool-cloud-deploy/references/static.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/kool-cloud-deploy/references/static.md b/skills/kool-cloud-deploy/references/static.md index ad738ecb..10e7b690 100644 --- a/skills/kool-cloud-deploy/references/static.md +++ b/skills/kool-cloud-deploy/references/static.md @@ -16,9 +16,10 @@ services: FROM nginx:1.27-alpine COPY nginx.conf /etc/nginx/conf.d/default.conf COPY . /usr/share/nginx/html +RUN rm /usr/share/nginx/html/nginx.conf EXPOSE 80 ``` -`nginx:alpine` is multi-arch, so the image builds for amd64 without emulating any build step. Keep the image's own `CMD`: it runs nginx in the foreground. +`nginx:alpine` is multi-arch, so the image builds for amd64 without emulating any build step. Keep the image's own `CMD`: it runs nginx in the foreground. The first `COPY` needs `nginx.conf` in the build context, so don't list it in `.dockerignore`; the `RUN rm` keeps it off the site. ```nginx # nginx.conf @@ -38,7 +39,6 @@ server { .git .env* Dockerfile -nginx.conf .dockerignore kool.cloud.yml docker-compose.yml From 5a66c7408b930ddc897dd6da2e072208c76d1c95 Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 18:52:39 -0300 Subject: [PATCH 8/9] test(cloud): decode every deploy status shape the API answers with Covers running, success (with a service size left null and with WordPress credentials), failed and timed out deploys with and without an error, a response without a services list, and responses carrying the optional hint and detail. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- services/cloud/api/deploy_status_test.go | 149 +++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/services/cloud/api/deploy_status_test.go b/services/cloud/api/deploy_status_test.go index 69150380..a9f124a5 100644 --- a/services/cloud/api/deploy_status_test.go +++ b/services/cloud/api/deploy_status_test.go @@ -2,6 +2,10 @@ package api import ( "encoding/json" + "io" + "net/http" + "reflect" + "strings" "testing" ) @@ -49,3 +53,148 @@ func TestDeployStatusResponseDecodesPanelShape(t *testing.T) { t.Errorf("bad decoded running status: %+v", resp) } } + +// TestDeployStatusDecodesEveryPanelShape goes through DoCall with every shape +// the deploy status endpoint can answer with: the released panel's (without +// hint and detail) and the panel's that explains failures (with them). +func TestDeployStatusDecodesEveryPanelShape(t *testing.T) { + const ( + startedAt = "2026-11-27T10:00:00+00:00" + completedAt = "2026-11-27T10:05:00+00:00" + ) + + cases := []struct { + name string + raw string + expected DeployStatusResponse + }{ + { + name: "running, nothing known yet", + raw: `{"id": 7, "status": "building", "type": "deploy", "url": "https://app.example.com", + "error": null, "started_at": "` + startedAt + `", "completed_at": null, + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "building", Type: "deploy", Url: "https://app.example.com", + StartedAt: startedAt, Services: []DeployStatusService{}}, + }, + { + name: "legacy deploy without a type", + raw: `{"id": 7, "status": "deploying", "type": null, "url": "https://app.example.com", + "error": null, "started_at": "` + startedAt + `", "completed_at": null, + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "deploying", Url: "https://app.example.com", + StartedAt: startedAt, Services: []DeployStatusService{}}, + }, + { + name: "success, with a service inheriting the default size", + raw: `{"id": 7, "status": "success", "type": "deploy", "url": "https://app.example.com", + "error": null, "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [{"name": "app", "type": "service", "size": "2xlarge"}, {"name": "worker", "type": "daemon", "size": null}], + "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "success", Type: "deploy", Url: "https://app.example.com", + StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{{"app", "service", "2xlarge"}, {"worker", "daemon", ""}}}, + }, + { + name: "WordPress success, with its credentials", + raw: `{"id": 7, "status": "success", "type": "deploy", "url": "https://wp.example.com", + "error": null, "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [{"name": "wordpress", "type": "service", "size": "small"}], + "wordpress_credentials": {"url": "https://wp.example.com/wp-admin", "username": "admin", "password": "not-a-real-one"}}`, + expected: DeployStatusResponse{ID: 7, Status: "success", Type: "deploy", Url: "https://wp.example.com", + StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{{"wordpress", "service", "small"}}}, + }, + { + name: "failed, with no error found in the log", + raw: `{"id": 7, "status": "failed", "type": "deploy", "url": "https://app.example.com", + "error": null, "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "failed", Type: "deploy", Url: "https://app.example.com", + StartedAt: startedAt, CompletedAt: completedAt, Services: []DeployStatusService{}}, + }, + { + name: "failed, with the last error line", + raw: `{"id": 7, "status": "failed", "type": "deploy", "url": "https://app.example.com", + "error": "UPGRADE FAILED: context deadline exceeded", "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "failed", Type: "deploy", Url: "https://app.example.com", + Error: "UPGRADE FAILED: context deadline exceeded", StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{}}, + }, + { + name: "timed out, with the last error line", + raw: `{"id": 7, "status": "timedout", "type": "deploy", "url": "https://app.example.com", + "error": "Timeout building images for deploy.", "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "timedout", Type: "deploy", Url: "https://app.example.com", + Error: "Timeout building images for deploy.", StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{}}, + }, + { + name: "without a services list", + raw: `{"id": 7, "status": "creating", "started_at": "` + startedAt + `"}`, + expected: DeployStatusResponse{ID: 7, Status: "creating", StartedAt: startedAt}, + }, + { + name: "failed, explained with error, hint and detail", + raw: `{"id": 7, "status": "failed", "type": "deploy", "url": "https://app.example.com", + "error": "UPGRADE FAILED: pre-upgrade hooks failed: 1 error occurred:", + "hint": "A release hook job failed: check its output.", + "detail": "job app-before0 failed: BackoffLimitExceeded", + "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [{"name": "app", "type": "service", "size": "medium"}], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "failed", Type: "deploy", Url: "https://app.example.com", + Error: "UPGRADE FAILED: pre-upgrade hooks failed: 1 error occurred:", + Hint: "A release hook job failed: check its output.", + Detail: "job app-before0 failed: BackoffLimitExceeded", + StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{{"app", "service", "medium"}}}, + }, + { + name: "failed, explained with an error only", + raw: `{"id": 7, "status": "failed", "type": "deploy", "url": "https://app.example.com", + "error": "Error building images: exit status 1", "hint": null, "detail": null, + "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "failed", Type: "deploy", Url: "https://app.example.com", + Error: "Error building images: exit status 1", StartedAt: startedAt, CompletedAt: completedAt, + Services: []DeployStatusService{}}, + }, + { + name: "success, with no failure to explain", + raw: `{"id": 7, "status": "success", "type": "deploy", "url": "https://app.example.com", + "error": null, "hint": null, "detail": null, + "started_at": "` + startedAt + `", "completed_at": "` + completedAt + `", + "services": [], "wordpress_credentials": null}`, + expected: DeployStatusResponse{ID: 7, Status: "success", Type: "deploy", Url: "https://app.example.com", + StartedAt: startedAt, CompletedAt: completedAt, Services: []DeployStatusService{}}, + }, + } + + oldHTTPRequester := httpRequester + defer func() { httpRequester = oldHTTPRequester }() + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + httpRequester = &fakeHTTP{resp: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(tc.raw)), + }} + + endpoint := newFakeDefaultEndpoint("GET") + endpoint.env.Set("KOOL_API_TOKEN", "fake token") + + status := &DeployStatus{Endpoint: endpoint} + status.SetPath("deploy/7/status") + + resp, err := status.Run() + if err != nil { + t.Fatalf("unexpected error decoding status: %v", err) + } + + if !reflect.DeepEqual(*resp, tc.expected) { + t.Errorf("bad decoded status:\n got: %+v\nwant: %+v", *resp, tc.expected) + } + }) + } +} From 2e1d955a0a826a6ace6d306560291489841df4f8 Mon Sep 17 00:00:00 2001 From: fabriciojs <fajosesouza@gmail.com> Date: Fri, 27 Nov 2026 18:53:27 -0300 Subject: [PATCH 9/9] fix(cloud): call the API's destroy endpoint at DELETE /deploy `kool cloud destroy` sent DELETE /deploy/destroy, a path the API does not serve, so it failed with a 404 instead of scheduling the environment for deletion. The endpoint is DELETE /deploy, as the CLI called it before 3.0.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- services/cloud/api/deploy_destroy.go | 3 +- services/cloud/api/deploy_destroy_test.go | 53 +++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 services/cloud/api/deploy_destroy_test.go diff --git a/services/cloud/api/deploy_destroy.go b/services/cloud/api/deploy_destroy.go index e6a94dbd..d1be5bd4 100644 --- a/services/cloud/api/deploy_destroy.go +++ b/services/cloud/api/deploy_destroy.go @@ -18,7 +18,8 @@ func NewDeployDestroy() (d *DeployDestroy) { Endpoint: NewDefaultEndpoint("DELETE"), } - d.SetPath("deploy/destroy") + // the API serves environment destroys at DELETE /deploy + d.SetPath("deploy") return } diff --git a/services/cloud/api/deploy_destroy_test.go b/services/cloud/api/deploy_destroy_test.go new file mode 100644 index 00000000..a66a7cf2 --- /dev/null +++ b/services/cloud/api/deploy_destroy_test.go @@ -0,0 +1,53 @@ +package api + +import ( + "io" + "net/http" + "strings" + "testing" +) + +func TestDeployDestroyCallsDeleteDeploy(t *testing.T) { + oldHTTPRequester := httpRequester + oldBaseURL := apiBaseURL + defer func() { + httpRequester = oldHTTPRequester + apiBaseURL = oldBaseURL + }() + + apiBaseURL = "https://kool.test/api" + + // the API answers with the deleting deploy, its environment included + fake := &fakeHTTP{resp: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"id": 12, "environment_id": 34, "status": "deleting", + "url": "https://app.example.com", "project": "app", + "environment": {"id": 34, "domain": "app.example.com", "project": {"id": 5, "name": "app"}}}`)), + }} + httpRequester = fake + + endpoint := newFakeDefaultEndpoint("DELETE") + endpoint.env.Set("KOOL_API_TOKEN", "fake token") + + destroy := NewDeployDestroy() + endpoint.SetPath(destroy.Endpoint.(*DefaultEndpoint).path) + destroy.Endpoint = endpoint + destroy.Query().Set("domain", "app.example.com") + + resp, err := destroy.Call() + if err != nil { + t.Fatalf("unexpected error destroying: %v", err) + } + + if fake.calledRequest.Method != http.MethodDelete { + t.Errorf("bad method: %s", fake.calledRequest.Method) + } + + if url := fake.calledRequest.URL.String(); url != "https://kool.test/api/deploy?domain=app.example.com" { + t.Errorf("bad destroy URL: %s", url) + } + + if resp.Environment.ID != 34 { + t.Errorf("bad decoded environment ID: %d", resp.Environment.ID) + } +}