* 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>
305 lines
7 KiB
Go
305 lines
7 KiB
Go
package php
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
|
|
"github.com/host-uk/core/pkg/cli"
|
|
)
|
|
|
|
// LinkedPackage represents a linked local package.
|
|
type LinkedPackage struct {
|
|
Name string `json:"name"`
|
|
Path string `json:"path"`
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
// composerRepository represents a composer repository entry.
|
|
type composerRepository struct {
|
|
Type string `json:"type"`
|
|
URL string `json:"url,omitempty"`
|
|
Options map[string]any `json:"options,omitempty"`
|
|
}
|
|
|
|
// readComposerJSON reads and parses composer.json from the given directory.
|
|
func readComposerJSON(dir string) (map[string]json.RawMessage, error) {
|
|
composerPath := filepath.Join(dir, "composer.json")
|
|
data, err := os.ReadFile(composerPath)
|
|
if err != nil {
|
|
return nil, cli.WrapVerb(err, "read", "composer.json")
|
|
}
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
return nil, cli.WrapVerb(err, "parse", "composer.json")
|
|
}
|
|
|
|
return raw, nil
|
|
}
|
|
|
|
// writeComposerJSON writes the composer.json to the given directory.
|
|
func writeComposerJSON(dir string, raw map[string]json.RawMessage) error {
|
|
composerPath := filepath.Join(dir, "composer.json")
|
|
|
|
data, err := json.MarshalIndent(raw, "", " ")
|
|
if err != nil {
|
|
return cli.WrapVerb(err, "marshal", "composer.json")
|
|
}
|
|
|
|
// Add trailing newline
|
|
data = append(data, '\n')
|
|
|
|
if err := os.WriteFile(composerPath, data, 0644); err != nil {
|
|
return cli.WrapVerb(err, "write", "composer.json")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// getRepositories extracts repositories from raw composer.json.
|
|
func getRepositories(raw map[string]json.RawMessage) ([]composerRepository, error) {
|
|
reposRaw, ok := raw["repositories"]
|
|
if !ok {
|
|
return []composerRepository{}, nil
|
|
}
|
|
|
|
var repos []composerRepository
|
|
if err := json.Unmarshal(reposRaw, &repos); err != nil {
|
|
return nil, cli.WrapVerb(err, "parse", "repositories")
|
|
}
|
|
|
|
return repos, nil
|
|
}
|
|
|
|
// setRepositories sets repositories in raw composer.json.
|
|
func setRepositories(raw map[string]json.RawMessage, repos []composerRepository) error {
|
|
if len(repos) == 0 {
|
|
delete(raw, "repositories")
|
|
return nil
|
|
}
|
|
|
|
reposData, err := json.Marshal(repos)
|
|
if err != nil {
|
|
return cli.WrapVerb(err, "marshal", "repositories")
|
|
}
|
|
|
|
raw["repositories"] = reposData
|
|
return nil
|
|
}
|
|
|
|
// getPackageInfo reads package name and version from a composer.json in the given path.
|
|
func getPackageInfo(packagePath string) (name, version string, err error) {
|
|
composerPath := filepath.Join(packagePath, "composer.json")
|
|
data, err := os.ReadFile(composerPath)
|
|
if err != nil {
|
|
return "", "", cli.WrapVerb(err, "read", "package composer.json")
|
|
}
|
|
|
|
var pkg struct {
|
|
Name string `json:"name"`
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
if err := json.Unmarshal(data, &pkg); err != nil {
|
|
return "", "", cli.WrapVerb(err, "parse", "package composer.json")
|
|
}
|
|
|
|
if pkg.Name == "" {
|
|
return "", "", cli.Err("package name not found in composer.json")
|
|
}
|
|
|
|
return pkg.Name, pkg.Version, nil
|
|
}
|
|
|
|
// LinkPackages adds path repositories to composer.json for local package development.
|
|
func LinkPackages(dir string, packages []string) error {
|
|
if !IsPHPProject(dir) {
|
|
return cli.Err("not a PHP project (missing composer.json)")
|
|
}
|
|
|
|
raw, err := readComposerJSON(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
repos, err := getRepositories(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, packagePath := range packages {
|
|
// Resolve absolute path
|
|
absPath, err := filepath.Abs(packagePath)
|
|
if err != nil {
|
|
return cli.Err("failed to resolve path %s: %w", packagePath, err)
|
|
}
|
|
|
|
// Verify the path exists and has a composer.json
|
|
if !IsPHPProject(absPath) {
|
|
return cli.Err("not a PHP package (missing composer.json): %s", absPath)
|
|
}
|
|
|
|
// Get package name for validation
|
|
pkgName, _, err := getPackageInfo(absPath)
|
|
if err != nil {
|
|
return cli.Err("failed to get package info from %s: %w", absPath, err)
|
|
}
|
|
|
|
// Check if already linked
|
|
alreadyLinked := false
|
|
for _, repo := range repos {
|
|
if repo.Type == "path" && repo.URL == absPath {
|
|
alreadyLinked = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if alreadyLinked {
|
|
continue
|
|
}
|
|
|
|
// Add path repository
|
|
repos = append(repos, composerRepository{
|
|
Type: "path",
|
|
URL: absPath,
|
|
Options: map[string]any{
|
|
"symlink": true,
|
|
},
|
|
})
|
|
|
|
cli.Print("Linked: %s -> %s\n", pkgName, absPath)
|
|
}
|
|
|
|
if err := setRepositories(raw, repos); err != nil {
|
|
return err
|
|
}
|
|
|
|
return writeComposerJSON(dir, raw)
|
|
}
|
|
|
|
// UnlinkPackages removes path repositories from composer.json.
|
|
func UnlinkPackages(dir string, packages []string) error {
|
|
if !IsPHPProject(dir) {
|
|
return cli.Err("not a PHP project (missing composer.json)")
|
|
}
|
|
|
|
raw, err := readComposerJSON(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
repos, err := getRepositories(raw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Build set of packages to unlink
|
|
toUnlink := make(map[string]bool)
|
|
for _, pkg := range packages {
|
|
toUnlink[pkg] = true
|
|
}
|
|
|
|
// Filter out unlinked packages
|
|
filtered := make([]composerRepository, 0, len(repos))
|
|
for _, repo := range repos {
|
|
if repo.Type != "path" {
|
|
filtered = append(filtered, repo)
|
|
continue
|
|
}
|
|
|
|
// Check if this repo should be unlinked
|
|
shouldUnlink := false
|
|
|
|
// Try to get package name from the path
|
|
if IsPHPProject(repo.URL) {
|
|
pkgName, _, err := getPackageInfo(repo.URL)
|
|
if err == nil && toUnlink[pkgName] {
|
|
shouldUnlink = true
|
|
cli.Print("Unlinked: %s\n", pkgName)
|
|
}
|
|
}
|
|
|
|
// Also check if path matches any of the provided names
|
|
for pkg := range toUnlink {
|
|
if repo.URL == pkg || filepath.Base(repo.URL) == pkg {
|
|
shouldUnlink = true
|
|
cli.Print("Unlinked: %s\n", repo.URL)
|
|
break
|
|
}
|
|
}
|
|
|
|
if !shouldUnlink {
|
|
filtered = append(filtered, repo)
|
|
}
|
|
}
|
|
|
|
if err := setRepositories(raw, filtered); err != nil {
|
|
return err
|
|
}
|
|
|
|
return writeComposerJSON(dir, raw)
|
|
}
|
|
|
|
// UpdatePackages runs composer update for specific packages.
|
|
func UpdatePackages(dir string, packages []string) error {
|
|
if !IsPHPProject(dir) {
|
|
return cli.Err("not a PHP project (missing composer.json)")
|
|
}
|
|
|
|
args := []string{"update"}
|
|
args = append(args, packages...)
|
|
|
|
cmd := exec.Command("composer", args...)
|
|
cmd.Dir = dir
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
|
|
return cmd.Run()
|
|
}
|
|
|
|
// ListLinkedPackages returns all path repositories from composer.json.
|
|
func ListLinkedPackages(dir string) ([]LinkedPackage, error) {
|
|
if !IsPHPProject(dir) {
|
|
return nil, cli.Err("not a PHP project (missing composer.json)")
|
|
}
|
|
|
|
raw, err := readComposerJSON(dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
repos, err := getRepositories(raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
linked := make([]LinkedPackage, 0)
|
|
for _, repo := range repos {
|
|
if repo.Type != "path" {
|
|
continue
|
|
}
|
|
|
|
pkg := LinkedPackage{
|
|
Path: repo.URL,
|
|
}
|
|
|
|
// Try to get package info
|
|
if IsPHPProject(repo.URL) {
|
|
name, version, err := getPackageInfo(repo.URL)
|
|
if err == nil {
|
|
pkg.Name = name
|
|
pkg.Version = version
|
|
}
|
|
}
|
|
|
|
if pkg.Name == "" {
|
|
pkg.Name = filepath.Base(repo.URL)
|
|
}
|
|
|
|
linked = append(linked, pkg)
|
|
}
|
|
|
|
return linked, nil
|
|
}
|