cli/internal/cmd/php/cmd_deploy.go
Snider f47e8211fb feat(mcp): add workspace root validation to prevent path traversal (#100)
* feat(mcp): add workspace root validation to prevent path traversal

- Add workspaceRoot field to Service for restricting file operations
- Add WithWorkspaceRoot() option for configuring the workspace directory
- Add validatePath() helper to check paths are within workspace
- Apply validation to all file operation handlers
- Default to current working directory for security
- Add comprehensive tests for path validation

Closes #82

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: move CLI commands from pkg/ to internal/cmd/

- Move 18 CLI command packages to internal/cmd/ (not externally importable)
- Keep 16 library packages in pkg/ (externally importable)
- Update all import paths throughout codebase
- Cleaner separation between CLI logic and reusable libraries

CLI commands moved: ai, ci, dev, docs, doctor, gitcmd, go, monitor,
php, pkgcmd, qa, sdk, security, setup, test, updater, vm, workspace

Libraries remaining: agentic, build, cache, cli, container, devops,
errors, framework, git, i18n, io, log, mcp, process, release, repos

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(mcp): use pkg/io Medium for sandboxed file operations

Replace manual path validation with pkg/io.Medium for all file operations.
This delegates security (path traversal, symlink bypass) to the sandboxed
local.Medium implementation.

Changes:
- Add io.NewSandboxed() for creating sandboxed Medium instances
- Refactor MCP Service to use io.Medium instead of direct os.* calls
- Remove validatePath and resolvePathWithSymlinks functions
- Update tests to verify Medium-based behaviour

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: correct import path and workflow references

- Fix pkg/io/io.go import from core-gui to core
- Update CI workflows to use internal/cmd/updater path

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(security): address CodeRabbit review issues for path validation

- pkg/io/local: add symlink resolution and boundary-aware containment
  - Reject absolute paths in sandboxed Medium
  - Use filepath.EvalSymlinks to prevent symlink bypass attacks
  - Fix prefix check to prevent /tmp/root matching /tmp/root2

- pkg/mcp: fix resolvePath to validate and return errors
  - Changed resolvePath from (string) to (string, error)
  - Update deleteFile, renameFile, listDirectory, fileExists to handle errors
  - Changed New() to return (*Service, error) instead of *Service
  - Properly propagate option errors instead of silently discarding

- pkg/io: wrap errors with E() helper for consistent context
  - Copy() and MockMedium.Read() now use coreerr.E()

- tests: rename to use _Good/_Bad/_Ugly suffixes per coding guidelines
  - Fix hardcoded /tmp in TestPath to use t.TempDir()
  - Add TestResolvePath_Bad_SymlinkTraversal test

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* style: fix gofmt formatting

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* style: fix gofmt formatting across all files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-01 21:59:34 +00:00

361 lines
9.7 KiB
Go

package php
import (
"context"
"os"
"time"
"github.com/host-uk/core/pkg/cli"
"github.com/host-uk/core/pkg/i18n"
"github.com/spf13/cobra"
)
// Deploy command styles (aliases to shared)
var (
phpDeployStyle = cli.SuccessStyle
phpDeployPendingStyle = cli.WarningStyle
phpDeployFailedStyle = cli.ErrorStyle
)
func addPHPDeployCommands(parent *cobra.Command) {
// Main deploy command
addPHPDeployCommand(parent)
// Deploy status subcommand (using colon notation: deploy:status)
addPHPDeployStatusCommand(parent)
// Deploy rollback subcommand
addPHPDeployRollbackCommand(parent)
// Deploy list subcommand
addPHPDeployListCommand(parent)
}
var (
deployStaging bool
deployForce bool
deployWait bool
)
func addPHPDeployCommand(parent *cobra.Command) {
deployCmd := &cobra.Command{
Use: "deploy",
Short: i18n.T("cmd.php.deploy.short"),
Long: i18n.T("cmd.php.deploy.long"),
RunE: func(cmd *cobra.Command, args []string) error {
cwd, err := os.Getwd()
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.get", "working directory"), err)
}
env := EnvProduction
if deployStaging {
env = EnvStaging
}
cli.Print("%s %s\n\n", dimStyle.Render(i18n.T("cmd.php.label.deploy")), i18n.T("cmd.php.deploy.deploying", map[string]interface{}{"Environment": env}))
ctx := context.Background()
opts := DeployOptions{
Dir: cwd,
Environment: env,
Force: deployForce,
Wait: deployWait,
}
status, err := Deploy(ctx, opts)
if err != nil {
return cli.Err("%s: %w", i18n.T("cmd.php.error.deploy_failed"), err)
}
printDeploymentStatus(status)
if deployWait {
if IsDeploymentSuccessful(status.Status) {
cli.Print("\n%s %s\n", successStyle.Render(i18n.Label("done")), i18n.T("common.success.completed", map[string]any{"Action": "Deployment completed"}))
} else {
cli.Print("\n%s %s\n", errorStyle.Render(i18n.Label("warning")), i18n.T("cmd.php.deploy.warning_status", map[string]interface{}{"Status": status.Status}))
}
} else {
cli.Print("\n%s %s\n", successStyle.Render(i18n.Label("done")), i18n.T("cmd.php.deploy.triggered"))
}
return nil
},
}
deployCmd.Flags().BoolVar(&deployStaging, "staging", false, i18n.T("cmd.php.deploy.flag.staging"))
deployCmd.Flags().BoolVar(&deployForce, "force", false, i18n.T("cmd.php.deploy.flag.force"))
deployCmd.Flags().BoolVar(&deployWait, "wait", false, i18n.T("cmd.php.deploy.flag.wait"))
parent.AddCommand(deployCmd)
}
var (
deployStatusStaging bool
deployStatusDeploymentID string
)
func addPHPDeployStatusCommand(parent *cobra.Command) {
statusCmd := &cobra.Command{
Use: "deploy:status",
Short: i18n.T("cmd.php.deploy_status.short"),
Long: i18n.T("cmd.php.deploy_status.long"),
RunE: func(cmd *cobra.Command, args []string) error {
cwd, err := os.Getwd()
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.get", "working directory"), err)
}
env := EnvProduction
if deployStatusStaging {
env = EnvStaging
}
cli.Print("%s %s\n\n", dimStyle.Render(i18n.T("cmd.php.label.deploy")), i18n.ProgressSubject("check", "deployment status"))
ctx := context.Background()
opts := StatusOptions{
Dir: cwd,
Environment: env,
DeploymentID: deployStatusDeploymentID,
}
status, err := DeployStatus(ctx, opts)
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.get", "status"), err)
}
printDeploymentStatus(status)
return nil
},
}
statusCmd.Flags().BoolVar(&deployStatusStaging, "staging", false, i18n.T("cmd.php.deploy_status.flag.staging"))
statusCmd.Flags().StringVar(&deployStatusDeploymentID, "id", "", i18n.T("cmd.php.deploy_status.flag.id"))
parent.AddCommand(statusCmd)
}
var (
rollbackStaging bool
rollbackDeploymentID string
rollbackWait bool
)
func addPHPDeployRollbackCommand(parent *cobra.Command) {
rollbackCmd := &cobra.Command{
Use: "deploy:rollback",
Short: i18n.T("cmd.php.deploy_rollback.short"),
Long: i18n.T("cmd.php.deploy_rollback.long"),
RunE: func(cmd *cobra.Command, args []string) error {
cwd, err := os.Getwd()
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.get", "working directory"), err)
}
env := EnvProduction
if rollbackStaging {
env = EnvStaging
}
cli.Print("%s %s\n\n", dimStyle.Render(i18n.T("cmd.php.label.deploy")), i18n.T("cmd.php.deploy_rollback.rolling_back", map[string]interface{}{"Environment": env}))
ctx := context.Background()
opts := RollbackOptions{
Dir: cwd,
Environment: env,
DeploymentID: rollbackDeploymentID,
Wait: rollbackWait,
}
status, err := Rollback(ctx, opts)
if err != nil {
return cli.Err("%s: %w", i18n.T("cmd.php.error.rollback_failed"), err)
}
printDeploymentStatus(status)
if rollbackWait {
if IsDeploymentSuccessful(status.Status) {
cli.Print("\n%s %s\n", successStyle.Render(i18n.Label("done")), i18n.T("common.success.completed", map[string]any{"Action": "Rollback completed"}))
} else {
cli.Print("\n%s %s\n", errorStyle.Render(i18n.Label("warning")), i18n.T("cmd.php.deploy_rollback.warning_status", map[string]interface{}{"Status": status.Status}))
}
} else {
cli.Print("\n%s %s\n", successStyle.Render(i18n.Label("done")), i18n.T("cmd.php.deploy_rollback.triggered"))
}
return nil
},
}
rollbackCmd.Flags().BoolVar(&rollbackStaging, "staging", false, i18n.T("cmd.php.deploy_rollback.flag.staging"))
rollbackCmd.Flags().StringVar(&rollbackDeploymentID, "id", "", i18n.T("cmd.php.deploy_rollback.flag.id"))
rollbackCmd.Flags().BoolVar(&rollbackWait, "wait", false, i18n.T("cmd.php.deploy_rollback.flag.wait"))
parent.AddCommand(rollbackCmd)
}
var (
deployListStaging bool
deployListLimit int
)
func addPHPDeployListCommand(parent *cobra.Command) {
listCmd := &cobra.Command{
Use: "deploy:list",
Short: i18n.T("cmd.php.deploy_list.short"),
Long: i18n.T("cmd.php.deploy_list.long"),
RunE: func(cmd *cobra.Command, args []string) error {
cwd, err := os.Getwd()
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.get", "working directory"), err)
}
env := EnvProduction
if deployListStaging {
env = EnvStaging
}
limit := deployListLimit
if limit == 0 {
limit = 10
}
cli.Print("%s %s\n\n", dimStyle.Render(i18n.T("cmd.php.label.deploy")), i18n.T("cmd.php.deploy_list.recent", map[string]interface{}{"Environment": env}))
ctx := context.Background()
deployments, err := ListDeployments(ctx, cwd, env, limit)
if err != nil {
return cli.Err("%s: %w", i18n.T("i18n.fail.list", "deployments"), err)
}
if len(deployments) == 0 {
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.info")), i18n.T("cmd.php.deploy_list.none_found"))
return nil
}
for i, d := range deployments {
printDeploymentSummary(i+1, &d)
}
return nil
},
}
listCmd.Flags().BoolVar(&deployListStaging, "staging", false, i18n.T("cmd.php.deploy_list.flag.staging"))
listCmd.Flags().IntVar(&deployListLimit, "limit", 0, i18n.T("cmd.php.deploy_list.flag.limit"))
parent.AddCommand(listCmd)
}
func printDeploymentStatus(status *DeploymentStatus) {
// Status with color
statusStyle := phpDeployStyle
switch status.Status {
case "queued", "building", "deploying", "pending", "rolling_back":
statusStyle = phpDeployPendingStyle
case "failed", "error", "cancelled":
statusStyle = phpDeployFailedStyle
}
cli.Print("%s %s\n", dimStyle.Render(i18n.Label("status")), statusStyle.Render(status.Status))
if status.ID != "" {
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.id")), status.ID)
}
if status.URL != "" {
cli.Print("%s %s\n", dimStyle.Render(i18n.Label("url")), linkStyle.Render(status.URL))
}
if status.Branch != "" {
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.branch")), status.Branch)
}
if status.Commit != "" {
commit := status.Commit
if len(commit) > 7 {
commit = commit[:7]
}
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.commit")), commit)
if status.CommitMessage != "" {
// Truncate long messages
msg := status.CommitMessage
if len(msg) > 60 {
msg = msg[:57] + "..."
}
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.message")), msg)
}
}
if !status.StartedAt.IsZero() {
cli.Print("%s %s\n", dimStyle.Render(i18n.Label("started")), status.StartedAt.Format(time.RFC3339))
}
if !status.CompletedAt.IsZero() {
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.completed")), status.CompletedAt.Format(time.RFC3339))
if !status.StartedAt.IsZero() {
duration := status.CompletedAt.Sub(status.StartedAt)
cli.Print("%s %s\n", dimStyle.Render(i18n.T("cmd.php.label.duration")), duration.Round(time.Second))
}
}
}
func printDeploymentSummary(index int, status *DeploymentStatus) {
// Status with color
statusStyle := phpDeployStyle
switch status.Status {
case "queued", "building", "deploying", "pending", "rolling_back":
statusStyle = phpDeployPendingStyle
case "failed", "error", "cancelled":
statusStyle = phpDeployFailedStyle
}
// Format: #1 [finished] abc1234 - commit message (2 hours ago)
id := status.ID
if len(id) > 8 {
id = id[:8]
}
commit := status.Commit
if len(commit) > 7 {
commit = commit[:7]
}
msg := status.CommitMessage
if len(msg) > 40 {
msg = msg[:37] + "..."
}
age := ""
if !status.StartedAt.IsZero() {
age = i18n.TimeAgo(status.StartedAt)
}
cli.Print(" %s %s %s",
dimStyle.Render(cli.Sprintf("#%d", index)),
statusStyle.Render(cli.Sprintf("[%s]", status.Status)),
id,
)
if commit != "" {
cli.Print(" %s", commit)
}
if msg != "" {
cli.Print(" - %s", msg)
}
if age != "" {
cli.Print(" %s", dimStyle.Render(cli.Sprintf("(%s)", age)))
}
cli.Blank()
}