From 4dc34be6993df62138d7b2133b225b65535732cc Mon Sep 17 00:00:00 2001 From: kranthi Date: Tue, 1 Dec 2026 18:28:57 -0700 Subject: [PATCH 1/2] secrets: uigraph secrets set, link and list `uigraph secrets set ` reads the value from a hidden prompt or stdin and never from argv: an extra argument or --value is refused without echoing it, so a value can't end up in shell history or a process list. `secrets link --from ` stores a reference (vault:// or aws-sm://) instead of a value, and `secrets list` shows names and status only. Configuration comes from UIGRAPH_AUTOPILOT_URL, UIGRAPH_ORG_ID and UIGRAPH_USER_TOKEN. Adds golang.org/x/term for the hidden prompt. Tests: a value as a third argument or --value is refused and never echoed (each shown failing without its check). Co-Authored-By: Claude Sonnet 5.5 --- cmd/secrets.go | 216 ++++++++++++++++++++++++++++++++++++++++++ cmd/secrets_test.go | 141 +++++++++++++++++++++++++++ go.mod | 2 + go.sum | 4 + pkg/secrets/client.go | 119 +++++++++++++++++++++++ 5 files changed, 482 insertions(+) create mode 100644 cmd/secrets.go create mode 100644 cmd/secrets_test.go create mode 100644 pkg/secrets/client.go diff --git a/cmd/secrets.go b/cmd/secrets.go new file mode 100644 index 0000000..c9d1267 --- /dev/null +++ b/cmd/secrets.go @@ -0,0 +1,216 @@ +package cmd + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "strings" + + "github.com/spf13/cobra" + "golang.org/x/term" + + "github.com/uigraph-oss/uigraph-cli/pkg/secrets" +) + +// Autopilot test secrets. A value is never taken from the command line, +// where it would land in shell history and in ps output: set reads it from +// a hidden prompt, or from stdin when piped. Nothing prints it back. + +var ( + secAutopilotURL string + secOrg string + secFrom string +) + +var secretsCmd = &cobra.Command{ + Use: "secrets", + Short: "Set the test secrets Autopilot uses to verify a service", + Long: `Set the test-grade secrets a service's runtime: profile declares. Values are +write-only: once stored they can be replaced or revoked, never read back. An org +admin approves each one before Autopilot uses it, and only verification runs see it. + +Needs your own token in UIGRAPH_USER_TOKEN, plus --autopilot-url (UIGRAPH_AUTOPILOT_URL) +and --org (UIGRAPH_ORG_ID).`, +} + +var secretsSetCmd = &cobra.Command{ + Use: "set ", + Short: "Store a value (read from a hidden prompt or stdin, never from arguments)", + Example: ` uigraph secrets set billing STRIPE_TEST_KEY + pbpaste | uigraph secrets set billing STRIPE_TEST_KEY`, + Args: exactArgs(2, "set ; the value is read from a hidden prompt or stdin, never from arguments"), + RunE: func(cmd *cobra.Command, args []string) error { + c, org, err := secretsClient() + if err != nil { + return err + } + value, err := readSecretValue(cmd.InOrStdin(), cmd.ErrOrStderr()) + if err != nil { + return err + } + v, err := c.Set(cmd.Context(), org, args[0], args[1], value) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "✓ Stored %s for %s as a test-grade secret (version %d). %s\n", + v.Name, v.Service, v.Version, approvalNote(v)) + return nil + }, +} + +var secretsLinkCmd = &cobra.Command{ + Use: "link --from ", + Short: "Point at a value in an existing secret manager instead of storing it", + Example: ` uigraph secrets link billing STRIPE_TEST_KEY --from vault://ci/billing/stripe-test-key + uigraph secrets link billing STRIPE_TEST_KEY --from aws-sm://ci/billing/stripe-test-key`, + Args: exactArgs(2, "link --from "), + RunE: func(cmd *cobra.Command, args []string) error { + if secFrom == "" { + return errors.New("--from is required, e.g. --from vault://ci/billing/stripe-test-key") + } + c, org, err := secretsClient() + if err != nil { + return err + } + v, err := c.Link(cmd.Context(), org, args[0], args[1], secFrom) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "✓ Linked %s for %s to %s. Autopilot reads it at run time. %s\n", + v.Name, v.Service, v.Ref, approvalNote(v)) + return nil + }, +} + +var secretsListCmd = &cobra.Command{ + Use: "list [service]", + Short: "List secrets and their status (never their values)", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + c, org, err := secretsClient() + if err != nil { + return err + } + service := "" + if len(args) == 1 { + service = args[0] + } + items, err := c.List(cmd.Context(), org, service) + if err != nil { + return err + } + out := cmd.OutOrStdout() + if len(items) == 0 { + fmt.Fprintln(out, "No secrets set.") + return nil + } + for _, v := range items { + status := "waiting for approval" + switch { + case v.Revoked: + status = "revoked" + case v.Approved: + status = "approved by " + v.ApprovedBy + } + extra := "" + if v.RotationDue { + extra = ", rotation due" + } + fmt.Fprintf(out, "%s/%s\t%s\t%s, set by %s, rotated %s%s\n", v.Service, v.Name, v.Kind, status, + v.SetBy, v.RotatedAt.Format("2006-01-02"), extra) + } + return nil + }, +} + +func approvalNote(v *secrets.View) string { + if v.Approved { + return "Approved." + } + return "Waiting for admin approval." +} + +// exactArgs is cobra.ExactArgs with an error that never repeats what was +// typed: a value pasted as an extra argument must not be echoed back. +func exactArgs(n int, usage string) cobra.PositionalArgs { + return func(_ *cobra.Command, args []string) error { + if len(args) != n { + return fmt.Errorf("expected %d arguments: %s", n, usage) + } + return nil + } +} + +func secretsClient() (*secrets.Client, string, error) { + base := firstSet(secAutopilotURL, os.Getenv("UIGRAPH_AUTOPILOT_URL")) + org := firstSet(secOrg, os.Getenv("UIGRAPH_ORG_ID")) + token := os.Getenv("UIGRAPH_USER_TOKEN") + switch { + case base == "": + return nil, "", errors.New("set --autopilot-url or UIGRAPH_AUTOPILOT_URL") + case org == "": + return nil, "", errors.New("set --org or UIGRAPH_ORG_ID") + case token == "": + return nil, "", errors.New("set UIGRAPH_USER_TOKEN to your own UIGraph token") + } + return &secrets.Client{BaseURL: base, Token: token}, org, nil +} + +func firstSet(vals ...string) string { + for _, v := range vals { + if v != "" { + return v + } + } + return "" +} + +// Swapped in tests. +var ( + stdinIsTerminal = func(in io.Reader) bool { + f, ok := in.(*os.File) + return ok && term.IsTerminal(int(f.Fd())) + } + readHidden = func(in io.Reader) ([]byte, error) { + return term.ReadPassword(int(in.(*os.File).Fd())) + } +) + +// readSecretValue reads the value from a hidden prompt on a terminal, or +// from stdin when piped (one trailing newline dropped). It never echoes it. +func readSecretValue(in io.Reader, prompt io.Writer) (string, error) { + var raw []byte + if stdinIsTerminal(in) { + fmt.Fprint(prompt, "Paste value (input hidden): ") + b, err := readHidden(in) + fmt.Fprintln(prompt) + if err != nil { + return "", fmt.Errorf("read value: %w", err) + } + raw = b + } else { + b, err := io.ReadAll(io.LimitReader(bufio.NewReader(in), 64<<10)) + if err != nil { + return "", fmt.Errorf("read value from stdin: %w", err) + } + raw = b + } + v := strings.TrimSuffix(strings.TrimSuffix(string(raw), "\n"), "\r") + if v == "" { + return "", errors.New("no value given: paste it at the prompt or pipe it on stdin") + } + return v, nil +} + +func init() { + for _, c := range []*cobra.Command{secretsSetCmd, secretsLinkCmd, secretsListCmd} { + c.Flags().StringVar(&secAutopilotURL, "autopilot-url", "", "UIGraph URL serving /api/v1/autopilot (default UIGRAPH_AUTOPILOT_URL)") + c.Flags().StringVar(&secOrg, "org", "", "Org id (default UIGRAPH_ORG_ID)") + secretsCmd.AddCommand(c) + } + secretsLinkCmd.Flags().StringVar(&secFrom, "from", "", "Reference to the value: vault:///[#field] or aws-sm://") + // Registered here rather than in root.go so this command stays in its own file. + rootCmd.AddCommand(secretsCmd) +} diff --git a/cmd/secrets_test.go b/cmd/secrets_test.go new file mode 100644 index 0000000..afcce30 --- /dev/null +++ b/cmd/secrets_test.go @@ -0,0 +1,141 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const testValue = "sk_test_51CLIsecretVALUEneverEchoed" + +type captured struct { + calls int + method string + path string + auth string + body map[string]string +} + +func fakeAutopilot(t *testing.T) (*httptest.Server, *captured) { + t.Helper() + c := &captured{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.calls++ + c.method, c.path, c.auth = r.Method, r.URL.Path, r.Header.Get("Authorization") + _ = json.NewDecoder(r.Body).Decode(&c.body) + parts := strings.Split(r.URL.Path, "/") + resp := map[string]any{"service": parts[len(parts)-2], "name": parts[len(parts)-1], "kind": "value", "version": 1, "setBy": "u1"} + if ref, ok := c.body["ref"]; ok { + resp["kind"], resp["ref"] = "ref", ref + } + _ = json.NewEncoder(w).Encode(resp) + })) + t.Cleanup(srv.Close) + t.Setenv("UIGRAPH_AUTOPILOT_URL", srv.URL) + t.Setenv("UIGRAPH_ORG_ID", "org1") + t.Setenv("UIGRAPH_USER_TOKEN", "user-token") + return srv, c +} + +func runSecrets(t *testing.T, stdin io.Reader, args ...string) (string, error) { + t.Helper() + secAutopilotURL, secOrg, secFrom = "", "", "" + var out bytes.Buffer + rootCmd.SetIn(stdin) + rootCmd.SetOut(&out) + rootCmd.SetErr(&out) + rootCmd.SetArgs(args) + err := rootCmd.ExecuteContext(context.Background()) + t.Cleanup(func() { rootCmd.SetIn(nil); rootCmd.SetOut(nil); rootCmd.SetErr(nil) }) + if err != nil { + out.WriteString(err.Error()) + } + return out.String(), err +} + +// The value can't come from argv: there is no flag for it, and an extra +// argument is refused without being repeated or sent anywhere. +func TestSetNeverTakesTheValueFromArgs(t *testing.T) { + _, c := fakeAutopilot(t) + if secretsSetCmd.Flags().Lookup("value") != nil { + t.Fatal("set has a --value flag") + } + out, err := runSecrets(t, strings.NewReader(""), "secrets", "set", "billing", "STRIPE_TEST_KEY", testValue) + if err == nil { + t.Fatal("a value given as an argument was accepted") + } + if strings.Contains(out, testValue) { + t.Fatalf("the argument was echoed: %s", out) + } + if c.calls != 0 { + t.Fatal("a request was sent") + } + out, err = runSecrets(t, strings.NewReader(""), "secrets", "set", "billing", "STRIPE_TEST_KEY", "--value", testValue) + if err == nil || strings.Contains(out, testValue) || c.calls != 0 { + t.Fatalf("--value: %v %q calls=%d", err, out, c.calls) + } +} + +func TestSetReadsStdinAndDoesNotEcho(t *testing.T) { + _, c := fakeAutopilot(t) + out, err := runSecrets(t, strings.NewReader(testValue+"\n"), "secrets", "set", "billing", "STRIPE_TEST_KEY") + if err != nil { + t.Fatalf("%v: %s", err, out) + } + if c.method != "PUT" || c.path != "/api/v1/autopilot/orgs/org1/secrets/billing/STRIPE_TEST_KEY" || + c.auth != "Bearer user-token" || c.body["value"] != testValue { + t.Fatalf("request: %+v", c) + } + if strings.Contains(out, testValue) { + t.Fatalf("value echoed: %s", out) + } + if !strings.Contains(out, "Waiting for admin approval") { + t.Fatalf("output: %s", out) + } +} + +func TestSetPromptsHiddenOnATerminal(t *testing.T) { + _, c := fakeAutopilot(t) + origTerm, origRead := stdinIsTerminal, readHidden + t.Cleanup(func() { stdinIsTerminal, readHidden = origTerm, origRead }) + hidden := false + stdinIsTerminal = func(io.Reader) bool { return true } + readHidden = func(io.Reader) ([]byte, error) { hidden = true; return []byte(testValue), nil } + + out, err := runSecrets(t, strings.NewReader(""), "secrets", "set", "billing", "STRIPE_TEST_KEY") + if err != nil { + t.Fatalf("%v: %s", err, out) + } + if !hidden || c.body["value"] != testValue { + t.Fatalf("hidden=%v body=%v", hidden, c.body) + } + if !strings.Contains(out, "Paste value (input hidden):") || strings.Contains(out, testValue) { + t.Fatalf("output: %q", out) + } +} + +func TestSetRefusesEmpty(t *testing.T) { + _, c := fakeAutopilot(t) + if _, err := runSecrets(t, strings.NewReader("\n"), "secrets", "set", "billing", "STRIPE_TEST_KEY"); err == nil || c.calls != 0 { + t.Fatalf("empty value: %v calls=%d", err, c.calls) + } +} + +func TestLinkSendsAReference(t *testing.T) { + _, c := fakeAutopilot(t) + out, err := runSecrets(t, strings.NewReader(""), "secrets", "link", "billing", "STRIPE_TEST_KEY", "--from", "vault://ci/billing/stripe-test-key") + if err != nil { + t.Fatalf("%v: %s", err, out) + } + if c.body["ref"] != "vault://ci/billing/stripe-test-key" || c.body["value"] != "" { + t.Fatalf("body: %v", c.body) + } + if _, err := runSecrets(t, strings.NewReader(""), "secrets", "link", "billing", "STRIPE_TEST_KEY"); err == nil { + t.Fatal("link without --from accepted") + } +} diff --git a/go.mod b/go.mod index 4dfb176..4b99a75 100644 --- a/go.mod +++ b/go.mod @@ -4,10 +4,12 @@ go 1.23.0 require ( github.com/spf13/cobra v1.8.0 + golang.org/x/term v0.27.0 gopkg.in/yaml.v3 v3.0.1 ) require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/sys v0.28.0 // indirect ) diff --git a/go.sum b/go.sum index 3926859..eb0aaf3 100644 --- a/go.sum +++ b/go.sum @@ -6,6 +6,10 @@ github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/pkg/secrets/client.go b/pkg/secrets/client.go new file mode 100644 index 0000000..12699cd --- /dev/null +++ b/pkg/secrets/client.go @@ -0,0 +1,119 @@ +// Package secrets calls UIGraph Autopilot's secret store as the engineer, +// with their own user token. Values are write-only: the store never returns +// one, and nothing here can ask for one. +package secrets + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +type Client struct { + BaseURL string // the UIGraph URL serving /api/v1/autopilot + Token string + HTTP *http.Client +} + +// View is the store's description of a secret. It never holds a value. +type View struct { + Service string `json:"service"` + Name string `json:"name"` + Kind string `json:"kind"` + Ref string `json:"ref,omitempty"` + Version int `json:"version"` + SetBy string `json:"setBy"` + RotatedAt time.Time `json:"rotatedAt"` + RotationDue bool `json:"rotationDue"` + Approved bool `json:"approved"` + ApprovedBy string `json:"approvedBy,omitempty"` + Revoked bool `json:"revoked"` + LastUsedAt *time.Time `json:"lastUsedAt,omitempty"` +} + +func (c *Client) url(orgID string, parts ...string) string { + u := strings.TrimRight(c.BaseURL, "/") + "/api/v1/autopilot/orgs/" + url.PathEscape(orgID) + "/secrets" + for _, p := range parts { + u += "/" + url.PathEscape(p) + } + return u +} + +// Set stores value for (service, name). It is sent only in the request body. +func (c *Client) Set(ctx context.Context, orgID, service, name, value string) (*View, error) { + var v View + return &v, c.do(ctx, http.MethodPut, c.url(orgID, service, name), map[string]string{"value": value}, &v) +} + +// Link stores a reference (vault://…, aws-sm://…) for Autopilot to resolve at use time. +func (c *Client) Link(ctx context.Context, orgID, service, name, ref string) (*View, error) { + var v View + return &v, c.do(ctx, http.MethodPut, c.url(orgID, service, name), map[string]string{"ref": ref}, &v) +} + +func (c *Client) List(ctx context.Context, orgID, service string) ([]View, error) { + u := c.url(orgID) + if service != "" { + u += "?service=" + url.QueryEscape(service) + } + var out struct { + Items []View `json:"items"` + } + return out.Items, c.do(ctx, http.MethodGet, u, nil, &out) +} + +func (c *Client) do(ctx context.Context, method, u string, body, out any) error { + var rd io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + return err + } + rd = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, u, rd) + if err != nil { + return err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set("Authorization", "Bearer "+c.Token) + hc := c.HTTP + if hc == nil { + hc = &http.Client{Timeout: 30 * time.Second} + } + resp, err := hc.Do(req) + if err != nil { + // The error names the URL, never the body. + return err + } + defer func() { _ = resp.Body.Close() }() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + switch resp.StatusCode { + case http.StatusOK: + case http.StatusUnauthorized: + return fmt.Errorf("autopilot refused the token (401): check UIGRAPH_USER_TOKEN and the org id") + case http.StatusForbidden: + return fmt.Errorf("not allowed (403): secrets are set by org members with their own token") + default: + var e struct { + Error string `json:"error"` + } + _ = json.Unmarshal(b, &e) + if e.Error == "" { + e.Error = http.StatusText(resp.StatusCode) + } + return fmt.Errorf("autopilot answered %d: %s", resp.StatusCode, e.Error) + } + if err := json.Unmarshal(b, out); err != nil { + return fmt.Errorf("autopilot response: %w", err) + } + return nil +} From e83fc93264d2ba488601e528b54595d3c608c8e1 Mon Sep 17 00:00:00 2001 From: kranthi Date: Tue, 1 Dec 2026 18:41:44 -0700 Subject: [PATCH 2/2] uigraph secrets set, link and list for Autopilot test secrets (P3) set reads the value from a hidden prompt on a terminal or from stdin, never from argv: there is no --value flag, and an extra argument is refused without being repeated or sent. The value is not echoed. link --from vault://... or aws-sm://... stores a reference for Autopilot to resolve at use time. list shows status, never values. Uses UIGRAPH_USER_TOKEN, UIGRAPH_AUTOPILOT_URL and UIGRAPH_ORG_ID like the runtime commands. Adds golang.org/x/term for the no-echo prompt. Tests fail with the guards removed: accepting the value as an argument, echoing it, and echoing arguments in the error. Co-Authored-By: Claude Sonnet 5.5 --- cmd/secrets.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cmd/secrets.go b/cmd/secrets.go index c9d1267..1cc101a 100644 --- a/cmd/secrets.go +++ b/cmd/secrets.go @@ -54,7 +54,7 @@ var secretsSetCmd = &cobra.Command{ if err != nil { return err } - fmt.Fprintf(cmd.OutOrStdout(), "✓ Stored %s for %s as a test-grade secret (version %d). %s\n", + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ Stored %s for %s as a test-grade secret (version %d). %s\n", v.Name, v.Service, v.Version, approvalNote(v)) return nil }, @@ -78,7 +78,7 @@ var secretsLinkCmd = &cobra.Command{ if err != nil { return err } - fmt.Fprintf(cmd.OutOrStdout(), "✓ Linked %s for %s to %s. Autopilot reads it at run time. %s\n", + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ Linked %s for %s to %s. Autopilot reads it at run time. %s\n", v.Name, v.Service, v.Ref, approvalNote(v)) return nil }, @@ -103,7 +103,7 @@ var secretsListCmd = &cobra.Command{ } out := cmd.OutOrStdout() if len(items) == 0 { - fmt.Fprintln(out, "No secrets set.") + _, _ = fmt.Fprintln(out, "No secrets set.") return nil } for _, v := range items { @@ -118,7 +118,7 @@ var secretsListCmd = &cobra.Command{ if v.RotationDue { extra = ", rotation due" } - fmt.Fprintf(out, "%s/%s\t%s\t%s, set by %s, rotated %s%s\n", v.Service, v.Name, v.Kind, status, + _, _ = fmt.Fprintf(out, "%s/%s\t%s\t%s, set by %s, rotated %s%s\n", v.Service, v.Name, v.Kind, status, v.SetBy, v.RotatedAt.Format("2006-01-02"), extra) } return nil @@ -183,9 +183,9 @@ var ( func readSecretValue(in io.Reader, prompt io.Writer) (string, error) { var raw []byte if stdinIsTerminal(in) { - fmt.Fprint(prompt, "Paste value (input hidden): ") + _, _ = fmt.Fprint(prompt, "Paste value (input hidden): ") b, err := readHidden(in) - fmt.Fprintln(prompt) + _, _ = fmt.Fprintln(prompt) if err != nil { return "", fmt.Errorf("read value: %w", err) }