Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
216 changes: 216 additions & 0 deletions cmd/secrets.go
Original file line number Diff line number Diff line change
@@ -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 <service> <NAME>",
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 <service> <NAME>; 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 <service> <NAME> --from <reference>",
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 <service> <NAME> --from <reference>"),
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://<mount>/<path>[#field] or aws-sm://<name or ARN>")
// Registered here rather than in root.go so this command stays in its own file.
rootCmd.AddCommand(secretsCmd)
}
141 changes: 141 additions & 0 deletions cmd/secrets_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
Loading
Loading