Files
molecule-cli/internal/cmd/root.go
sdk-dev 0ec3db81e6
CI / Test / test (pull_request) Successful in 2m3s
Release Go binaries / test (pull_request) Successful in 2m9s
Release Go binaries / release (pull_request) Waiting to run
fix(cli): address CR2 review on #13 — path-escaping, config binding, CP-admin targeting
CR2 review findings on PR #13 (branch feat/management-cli-verbs):

1. [HIGH] PathEscape user-controlled path segments. platform.go built paths
   via fmt.Sprintf on raw caller IDs (GetWorkspace/DeleteWorkspace/
   RestartWorkspace/ListWorkspaceAgents/GetAgent/GetPeers/GetDelegations) and
   the agent-send / workspace-delegate runHTTP call sites concatenated raw IDs.
   An ID with '/', '?' or '#' could alter the endpoint or leak into the query.
   Wrapped every caller-supplied segment in url.PathEscape (management.go
   already did this). DeleteWorkspace's ?confirm=true is now injection-safe.
   Severity note: this runs under the user's own management creds, so it is
   primarily robustness/correctness rather than a privilege-escalation hole.

2. [MED] Config not bound to globals. viper read the config file but the
   flag-backed apiURL/outputFormat globals were never populated from it, so
   `molecule config set api_url` did not affect newClient()/cpURL(). Added
   applyConfigDefaults(): config file is adopted only when no env override and
   the global is still at its built-in default, so precedence stays
   flag > env > config file > default.

3. [MED] MintWorkspaceToken sent a nil body → JSON `null`. Now sends an empty
   object (struct{}{}) → `{}`, matching sibling tooling and avoiding rejection
   by a handler that decodes into a struct/map.

4. [MED] cpURL defaulted to apiURL (tenant host), so an unset MOLECULE_CP_URL
   would send the privileged CP-admin bearer to a tenant host. cpURL() no
   longer falls back to apiURL; cpAdminClient() now requires an explicit
   MOLECULE_CP_URL and fails fast otherwise. Updated org.go help text.

5. [LOW] config set now os.MkdirAll's the config dir before WriteConfig/
   SafeWriteConfig, which otherwise fail on a fresh machine where ~/.config
   doesn't exist yet.

Tests: added path-segment escaping coverage (platform + delete), MintWorkspaceToken
body={}, applyConfigDefaults precedence, config-set mkdir, and CP-admin credential
targeting; retargeted TestCPURLFallback → TestCPURLNoTenantFallback.
go build/vet/test all green; gofmt clean on edited files.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-31 23:44:52 -07:00

260 lines
8.7 KiB
Go

// Package cmd implements the CLI command tree.
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"os"
"runtime"
"text/tabwriter"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.moleculesai.app/cli/internal/client"
"gopkg.in/yaml.v3"
)
// Version is set at build time via -ldflags.
var Version = "dev"
// Global flags.
var (
verbose bool
outputFormat string
jsonOutput bool
configPath string
apiURL string
)
// rootCmd is the top-level molecule command.
var rootCmd = &cobra.Command{
Use: "molecule",
Version: Version,
Short: "molecule — Molecule AI platform CLI",
Long: `molecule is the CLI for the Molecule AI agent platform.
Manage workspaces, inspect agents, audit the platform, and configure
agent behaviour from the terminal.
Quick start:
molecule workspace list
molecule agent list
molecule platform health`,
SilenceUsage: true,
SilenceErrors: true,
}
func init() {
rootCmd.PersistentFlags().StringVar(&apiURL, "api-url",
envOr("MOLECULE_API_URL", "http://localhost:8080"),
"Platform API base URL (env: MOLECULE_API_URL)")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false,
"Enable verbose (DEBUG-level) output to stderr")
rootCmd.PersistentFlags().StringVarP(&outputFormat, "output", "o", "table",
"Output format: table | json | yaml")
rootCmd.PersistentFlags().BoolVar(&jsonOutput, "json", false,
"Shorthand for --output json")
rootCmd.PersistentFlags().StringVar(&configPath, "config", "",
"Path to config file (default ~/.config/molecule.yaml or ./molecule.yaml)")
// --json wins over -o; resolved before any command runs.
rootCmd.PersistentPreRun = func(_ *cobra.Command, _ []string) {
if jsonOutput {
outputFormat = "json"
}
}
rootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
return &exitError{code: 2, msg: err.Error()}
})
rootCmd.SetErr(os.Stderr)
}
// Execute runs the CLI.
func Execute() error {
// Load config file.
if configPath != "" {
viper.SetConfigFile(configPath)
} else {
viper.SetConfigName("molecule")
viper.AddConfigPath("$HOME/.config")
viper.AddConfigPath(".")
}
viper.AutomaticEnv()
_ = viper.ReadInConfig() // ignore not-found; env vars win
// Fold config-file values into the globals the client reads (see
// applyConfigDefaults). Without this, `molecule config set api_url …` lands
// only in viper and never reaches newClient()/cpURL().
applyConfigDefaults()
// rootCmd has SilenceErrors=true, so cobra prints nothing on error.
// Route the error through handleErr so user-facing messages (including
// exitError fail-fast guidance like the org-verb credential errors) are
// printed to stderr with the right exit code instead of being swallowed.
return handleErr(rootCmd.Execute())
}
// applyConfigDefaults folds config-file values (read into viper) into the
// flag-backed globals that the client actually reads (apiURL, outputFormat).
//
// The cobra flags drive these globals, but a value written by
// `molecule config set api_url …` only lands in viper. Precedence we want:
// explicit --flag > MOLECULE_API_URL / MOL_OUTPUT env > config file > built-in
// default. The flag default already folds in the env var, and an explicit flag
// is applied by cobra during rootCmd.Execute() (after this runs), so here we
// only adopt the config value when the global is still at its untouched
// built-in default and no env override is present — making the config file the
// next source after env, and below an explicit flag.
func applyConfigDefaults() {
if os.Getenv("MOLECULE_API_URL") == "" && apiURL == "http://localhost:8080" {
if v := viper.GetString("api_url"); v != "" {
apiURL = v
}
}
if os.Getenv("MOL_OUTPUT") == "" && outputFormat == "table" {
if v := viper.GetString("output"); v != "" {
outputFormat = v
}
}
}
// envOr returns the value of env var key, or fallback if unset/empty.
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
// newClient builds a Platform client authenticated with the management API
// key (MOLECULE_API_KEY) and org id (MOLECULE_ORG_ID). All management verbs
// go through this so they don't 401 a hardened tenant.
func newClient() *client.Platform {
return client.NewWithAuth(apiURL, authToken(), orgID())
}
// cpURL returns the explicitly-configured control-plane base URL for
// org-lifecycle verbs (org list/create), or "" when MOLECULE_CP_URL is unset.
//
// Org ops live on the CP (api.moleculesai.app), authenticated with the
// privileged CP-admin bearer (MOLECULE_CP_ADMIN_TOKEN). We deliberately do NOT
// fall back to the tenant api-url: silently pointing the CP-admin surface at a
// tenant host would send that privileged bearer to a host that has no business
// seeing it (a self-host / customer tenant). Callers must require a non-empty
// value before sending the admin token. A combined dev host still works — set
// MOLECULE_CP_URL explicitly (it may equal MOLECULE_API_URL).
func cpURL() string {
return os.Getenv("MOLECULE_CP_URL")
}
// cpAdminClient builds a Platform client for the CP ADMIN surface
// (/api/v1/admin/orgs). It authenticates with the dedicated CP-admin bearer
// (MOLECULE_CP_ADMIN_TOKEN) and sends NO X-Molecule-Org-Id header — the admin
// routes are not org-scoped at the gate. Crucially it never carries the tenant
// Org API Key (MOLECULE_API_KEY), so the org credential is never leaked to the
// control plane. Returns an error when the admin token is unset so callers
// fail fast with a clear two-credential message instead of a bare 401.
func cpAdminClient() (*client.Platform, error) {
tok := cpAdminToken()
if tok == "" {
return nil, &exitError{code: 2, msg: "this verb hits the control-plane admin API and requires a CP admin bearer token in MOLECULE_CP_ADMIN_TOKEN (distinct from the tenant MOLECULE_API_KEY / Org API Key, which has no standing on the control plane). See `molecule org --help`."}
}
// Require an explicit CP URL: never send the privileged CP-admin bearer to
// the tenant api-url. Sending MOLECULE_CP_ADMIN_TOKEN to a tenant host (which
// may be customer-controlled) would leak a control-plane credential.
base := cpURL()
if base == "" {
return nil, &exitError{code: 2, msg: "this verb hits the control-plane admin API and requires the CP base URL in MOLECULE_CP_URL (e.g. https://api.moleculesai.app). It is intentionally NOT defaulted to MOLECULE_API_URL so the CP-admin bearer is never sent to a tenant host. See `molecule org --help`."}
}
// OrgID is intentionally empty: AdminGate does not route on it.
return client.NewWithAuth(base, tok, ""), nil
}
// init registers all subcommand trees.
func init() {
rootCmd.AddCommand(workspaceCmd)
rootCmd.AddCommand(agentCmd)
rootCmd.AddCommand(platformCmd)
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(connectCmd)
// Management verbs (PLATFORM-MANAGEMENT-API.md §5(b)).
rootCmd.AddCommand(orgCmd)
rootCmd.AddCommand(secretCmd)
rootCmd.AddCommand(templateCmd)
rootCmd.AddCommand(bundleCmd)
rootCmd.AddCommand(eventsCmd)
rootCmd.AddCommand(approvalsCmd)
}
// exitError wraps a user-facing error with a specific exit code.
type exitError struct {
code int
msg string
}
func (e *exitError) Error() string { return e.msg }
// handleErr converts an error to the right exit code.
func handleErr(err error) error {
if err == nil {
return nil
}
if ee, ok := err.(*exitError); ok {
fmt.Fprintf(os.Stderr, "%s\n", ee.msg)
os.Exit(ee.code)
}
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
return nil
}
// printJSON writes v as JSON to stdout.
func printJSON(v interface{}) error {
return json.NewEncoder(os.Stdout).Encode(v)
}
// printRaw pretty-prints a raw JSON response body to stdout. Used by verbs
// that wrap loose/pass-through endpoints (events, secrets lists, budget,
// exports, allowlist). Honors --output yaml by re-marshaling through a
// generic value; otherwise prints indented JSON.
func printRaw(raw []byte) error {
if len(raw) == 0 {
return nil
}
if outputFormat == "yaml" {
var v interface{}
if err := json.Unmarshal(raw, &v); err != nil {
return err
}
return printYAML(v)
}
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
// Not valid JSON — print verbatim.
fmt.Println(string(raw))
return nil
}
fmt.Println(buf.String())
return nil
}
// printYAML writes v as YAML to stdout.
func printYAML(v interface{}) error {
enc := yaml.NewEncoder(os.Stdout)
enc.SetIndent(2)
return enc.Encode(v)
}
// kv writes a key-value pair to the tabwriter (only if v is non-empty).
func kv(w *tabwriter.Writer, k, v string) {
if v == "" {
return
}
fmt.Fprintf(w, "%s:\t%s\n", k, v)
}
func versionInfo() string {
return fmt.Sprintf("molecule %s (go %s)", Version, runtime.Version())
}