From c78b9a751d9715360a66fa909b965f00481e544c Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Wed, 2 Dec 2026 10:56:09 -0700 Subject: [PATCH] Package secretctl in every dotfiles profile --- home/dev.nix | 10 +- tools/secretctl/go.mod | 7 + tools/secretctl/go.sum | 4 + tools/secretctl/help.go | 205 ++++++++++++++ tools/secretctl/main.go | 569 +++++++++++++++++++++++++++++++++++++++ tools/secretctl/store.go | 302 +++++++++++++++++++++ 6 files changed, 1096 insertions(+), 1 deletion(-) create mode 100644 tools/secretctl/go.mod create mode 100644 tools/secretctl/go.sum create mode 100644 tools/secretctl/help.go create mode 100644 tools/secretctl/main.go create mode 100644 tools/secretctl/store.go diff --git a/home/dev.nix b/home/dev.nix index c68f5e9..f029969 100644 --- a/home/dev.nix +++ b/home/dev.nix @@ -1,11 +1,19 @@ { config, lib, pkgs, ... }: +let + secretctl = pkgs.buildGoModule { + pname = "secretctl"; + version = "1.0.0"; + src = ../tools/secretctl; + vendorHash = "sha256-kp9Y6eG6YiFc+/3hCKYlm147JW/pWZ/dQ8Ds+m2fA34="; + }; +in { home.packages = with pkgs; [ # everyday CLI curl wget jq yq-go ripgrep fd tree unzip zip file which rsync tmux nmap rclone gnupg # forges and secrets - tea gh bitwarden-cli gitea-mcp-server + tea gh bitwarden-cli gitea-mcp-server secretctl # VPN client; `dot system` installs its root daemon unit netbird # nix tooling diff --git a/tools/secretctl/go.mod b/tools/secretctl/go.mod new file mode 100644 index 0000000..d694bf8 --- /dev/null +++ b/tools/secretctl/go.mod @@ -0,0 +1,7 @@ +module secretctl + +go 1.21 + +require golang.org/x/term v0.18.0 + +require golang.org/x/sys v0.18.0 // indirect diff --git a/tools/secretctl/go.sum b/tools/secretctl/go.sum new file mode 100644 index 0000000..e674772 --- /dev/null +++ b/tools/secretctl/go.sum @@ -0,0 +1,4 @@ +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= diff --git a/tools/secretctl/help.go b/tools/secretctl/help.go new file mode 100644 index 0000000..5ba3c18 --- /dev/null +++ b/tools/secretctl/help.go @@ -0,0 +1,205 @@ +package main + +import ( + "io" + "os" + "regexp" +) + +func regexpQuote(s string) string { return regexp.QuoteMeta(s) } + +func compileRegexp(p string) (*regexp.Regexp, error) { return regexp.Compile(p) } + +func printHelp(w io.Writer) { + io.WriteString(w, `secretctl — keep secrets out of sight and out of argv + +secretctl manages environment variables stored in a plain-text file +(default ~/secrets.txt) and injects them into child processes. Secret +values are never printed, never stored in argv, and never logged. + +USAGE + secretctl [global flags] [command flags] [arguments] + +COMMANDS + list List secret names (values are never shown). + search [-i] [-F] List secret names matching a regular expression. + -F literal match -i case-insensitive + get ... -- ... Run with the named secrets injected into + its environment. Values are never printed. + run --all -- ... Run with every secret injected. Use + sparingly; the child can read all secrets. + add Add a new secret. The value is read from the + terminal without echo, or from stdin if piped. + set Change the value of an existing secret. + rm Remove a secret. + check Verify file permissions and syntax. + help [command] Show help for a command. + version Print the version. + +GLOBAL FLAGS + -f, --file Secrets file to use (default: ~/secrets.txt, or + $SECRETCTL_FILE if set). + -h, --help Show this help. + --version Print the version. + +EXAMPLES + secretctl list + secretctl search 'GIT.*TOKEN' + secretctl get GITEA_DOGE_TOKEN -- git push + secretctl run --all -- make deploy + secretctl add GITEA_DOGE_TOKEN + printf '%s' "$VAL" | secretctl add API_KEY + secretctl set GITEA_DOGE_TOKEN + secretctl rm OLD_TOKEN + secretctl check + +FILE FORMAT + One KEY=value pair per line. Blank lines and lines starting with "#" + are ignored, as is an optional leading "export ". Values may be + double-quoted ("...", with \n \t \r \" \\ escapes) or single-quoted + ('...'); unquoted values are trimmed and may end with a " #" comment. + secretctl quotes values on write only when necessary and preserves + comments and ordering. + +SECURITY + * Values travel only through the environment of a child process. + secretctl has no command that prints a value. + * Values are never accepted as command-line arguments (argv is visible + in ps and shell history); add/set read stdin or a hidden prompt. + * The file is written atomically with mode 0600. + * Prefer "get KEY -- cmd" over "run --all -- cmd": a child should see + only the secrets it needs. + * Run "secretctl check" if you suspect the file permissions drifted. +`) +} + +func printListHelp() { + io.WriteString(os.Stdout, `secretctl list — list secret names + +USAGE + secretctl list + +Prints the name of every secret in the file, one per line, in file order. +Values are never shown. +`) +} + +func printSearchHelp() { + io.WriteString(os.Stdout, `secretctl search — find secret names + +USAGE + secretctl search [-i] [-F] + +Prints the names of secrets whose name matches . Values are never +shown. + +FLAGS + -F, --fixed Treat as a literal string instead of a regexp. + -i Case-insensitive match. + +EXAMPLES + secretctl search TOKEN + secretctl search '^GIT.*_(TOKEN|PAT)$' + secretctl search -i -F 'github' +`) +} + +func printGetHelp() { + io.WriteString(os.Stdout, `secretctl get — run a command with secrets injected + +USAGE + secretctl get [KEY...] -- [args...] + +Runs with the named secrets added to its environment. The values +are never printed and never appear in argv. + +The "--" separator is required. Everything after it is the command and its +arguments and is not interpreted by secretctl. + +EXAMPLES + secretctl get GITEA_DOGE_TOKEN -- git push origin main + secretctl get DB_PASSWORD API_KEY -- ./server --debug + secretctl get GITEA_DOGE_TOKEN -- sh -c 'curl -H "Authorization: token $GITEA_DOGE_TOKEN" ...' + +EXIT STATUS + The exit status of , or 1 if secretctl fails before starting it. +`) +} + +func printRunHelp() { + io.WriteString(os.Stdout, `secretctl run — run a command with multiple secrets injected + +USAGE + secretctl run --all -- [args...] + secretctl run -e [-e ...] -- [args...] + +Like "get", but convenient for selecting many secrets. --all injects every +secret in the file; the child can then read all of them, so prefer "get" +or "-e" when a command needs only a few. + +EXAMPLES + secretctl run -e DB_HOST -e DB_PASSWORD -- psql + secretctl run --all -- ./deploy.sh +`) +} + +func printAddHelp() { + io.WriteString(os.Stdout, `secretctl add — add a new secret + +USAGE + secretctl add [--allow-empty] + +The value is read from the terminal without echo (entered twice for +confirmation). If stdin is not a terminal, the value is read from stdin +until EOF, so multi-line values (e.g. private keys) work. + +Values are never accepted as command-line arguments, because argv is +visible to other users (ps) and recorded in shell history. + +FLAGS + --allow-empty Store an empty value. + +EXAMPLES + secretctl add GITEA_DOGE_TOKEN + printf '%s' "$TOKEN" | secretctl add GITEA_DOGE_TOKEN + pbpaste | secretctl add SIGNING_KEY +`) +} + +func printSetHelp() { + io.WriteString(os.Stdout, `secretctl set — change the value of an existing secret + +USAGE + secretctl set [--allow-empty] + +Reads the new value the same way "add" does (hidden prompt or stdin) and +replaces the existing value. Use "add" to create a new secret. + +EXAMPLES + secretctl set GITEA_DOGE_TOKEN + op read op://private/gitea/token | secretctl set GITEA_DOGE_TOKEN +`) +} + +func printRmHelp() { + io.WriteString(os.Stdout, `secretctl rm — remove a secret + +USAGE + secretctl rm + +Deletes the named secret from the file. Comments and other secrets are +preserved. +`) +} + +func printCheckHelp() { + io.WriteString(os.Stdout, `secretctl check — verify the secrets file + +USAGE + secretctl check + +Checks that the file exists, parses without errors, has no duplicate names, +and is readable only by you (mode 0600). Exits non-zero if anything is +wrong. +`) +} diff --git a/tools/secretctl/main.go b/tools/secretctl/main.go new file mode 100644 index 0000000..9f2acad --- /dev/null +++ b/tools/secretctl/main.go @@ -0,0 +1,569 @@ +// Command secretctl manages environment variables stored in ~/secrets.txt and +// injects them into child processes without ever printing their values. +package main + +import ( + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + + "golang.org/x/term" +) + +const version = "1.0.0" + +var ( + errHelp = errors.New("help requested") + errVersion = errors.New("version requested") +) + +type exitError struct{ code int } + +func (e *exitError) Error() string { return fmt.Sprintf("exit status %d", e.code) } + +type globals struct{ file string } + +func main() { + g, rest, err := parseGlobals(os.Args[1:]) + switch { + case errors.Is(err, errHelp): + printHelp(os.Stdout) + return + case errors.Is(err, errVersion): + fmt.Println("secretctl " + version) + return + case err != nil: + fatal(err) + } + if len(rest) == 0 { + printHelp(os.Stdout) + return + } + + cmd, args := rest[0], rest[1:] + var runErr error + switch cmd { + case "help": + runErr = cmdHelp(args) + case "version": + fmt.Println("secretctl " + version) + case "list", "ls": + runErr = cmdList(g, args) + case "search", "find": + runErr = cmdSearch(g, args) + case "get": + runErr = cmdGet(g, args) + case "run", "exec": + runErr = cmdRun(g, args) + case "add": + runErr = cmdAdd(g, args) + case "set", "change": + runErr = cmdSet(g, args) + case "rm", "remove", "delete": + runErr = cmdRm(g, args) + case "check": + runErr = cmdCheck(g, args) + default: + runErr = fmt.Errorf("unknown command %q (see \"secretctl --help\")", cmd) + } + if runErr != nil { + var ee *exitError + if errors.As(runErr, &ee) { + os.Exit(ee.code) + } + fatal(runErr) + } +} + +func fatal(err error) { + fmt.Fprintf(os.Stderr, "secretctl: %v\n", err) + os.Exit(1) +} + +// ---- global flags ---------------------------------------------------------- + +func defaultPath() string { + if p := os.Getenv("SECRETCTL_FILE"); p != "" { + return p + } + home, err := os.UserHomeDir() + if err != nil { + return "secrets.txt" + } + return filepath.Join(home, "secrets.txt") +} + +func expandPath(p string) string { + if p == "~" || strings.HasPrefix(p, "~/") { + if home, err := os.UserHomeDir(); err == nil { + return filepath.Join(home, p[1:]) + } + } + return p +} + +func parseGlobals(args []string) (*globals, []string, error) { + g := &globals{file: defaultPath()} + i := 0 + for i < len(args) { + a := args[i] + if a == "--" { + i++ + break + } + if !strings.HasPrefix(a, "-") || a == "-" { + break + } + switch { + case a == "-h" || a == "--help": + return g, nil, errHelp + case a == "--version": + return g, nil, errVersion + case a == "-f" || a == "--file": + if i+1 >= len(args) { + return g, nil, fmt.Errorf("flag %s requires a value", a) + } + g.file = args[i+1] + i += 2 + case strings.HasPrefix(a, "--file="): + g.file = strings.TrimPrefix(a, "--file=") + i++ + case strings.HasPrefix(a, "-f="): + g.file = strings.TrimPrefix(a, "-f=") + i++ + default: + return g, nil, fmt.Errorf("unknown flag %q (global flags go before the command; see secretctl --help)", a) + } + } + g.file = expandPath(g.file) + return g, args[i:], nil +} + +func isHelpArg(a string) bool { return a == "-h" || a == "--help" } + +// ---- process injection ----------------------------------------------------- + +// mergeEnv returns base with any keys present in extra replaced. +func mergeEnv(base []string, extra map[string]string) []string { + out := make([]string, 0, len(base)+len(extra)) + for _, kv := range base { + k := kv + if i := strings.IndexByte(kv, '='); i >= 0 { + k = kv[:i] + } + if _, ok := extra[k]; ok { + continue + } + out = append(out, kv) + } + for k, v := range extra { + out = append(out, k+"="+v) + } + return out +} + +// execWithEnv runs argv with the extra environment and propagates its exit code. +func execWithEnv(extra map[string]string, argv []string) error { + cmd := exec.Command(argv[0], argv[1:]...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.Env = mergeEnv(os.Environ(), extra) + if err := cmd.Run(); err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) { + code := ee.ExitCode() + if code < 0 { + code = 1 + } + return &exitError{code: code} + } + return err + } + return nil +} + +// readValueFor reads a secret. On a TTY it prompts twice without echo; when +// piped it consumes stdin (so multi-line values such as private keys work). +func readValueFor(prompt string, allowEmpty bool) (string, error) { + var v string + if term.IsTerminal(int(os.Stdin.Fd())) { + fmt.Fprint(os.Stderr, prompt) + b, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + if err != nil { + return "", err + } + fmt.Fprint(os.Stderr, "Repeat: ") + b2, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + if err != nil { + return "", err + } + if string(b) != string(b2) { + return "", errors.New("values did not match; nothing was saved") + } + v = string(b) + } else { + data, err := io.ReadAll(os.Stdin) + if err != nil { + return "", err + } + v = strings.TrimRight(string(data), "\r\n") + } + if v == "" && !allowEmpty { + return "", errors.New("empty value; nothing was saved (pass --allow-empty to store an empty value)") + } + return v, nil +} + +// ---- commands -------------------------------------------------------------- + +func cmdList(g *globals, args []string) error { + if len(args) > 0 && isHelpArg(args[0]) { + printListHelp() + return nil + } + if len(args) > 0 { + return errors.New("list takes no arguments") + } + s, err := load(g.file, false) + if err != nil { + return err + } + entries := s.entries() + if len(entries) == 0 { + fmt.Fprintln(os.Stderr, "secretctl: no secrets defined") + return nil + } + for _, e := range entries { + fmt.Println(e.Key) + } + return nil +} + +func cmdSearch(g *globals, args []string) error { + ci, fixed := false, false + for len(args) > 0 { + a := args[0] + if a == "--" { + args = args[1:] + break + } + if isHelpArg(a) { + printSearchHelp() + return nil + } + if a == "-i" { + ci = true + args = args[1:] + continue + } + if a == "-F" || a == "--fixed" { + fixed = true + args = args[1:] + continue + } + if strings.HasPrefix(a, "-") && len(a) > 1 { + return fmt.Errorf("unknown flag %q", a) + } + break + } + if len(args) != 1 { + return errors.New("usage: secretctl search [-i] [-F] ") + } + pattern := args[0] + if fixed { + pattern = regexpQuote(pattern) + } + if ci { + pattern = "(?i)" + pattern + } + re, err := compileRegexp(pattern) + if err != nil { + return fmt.Errorf("invalid regular expression (use -F for a literal search): %v", err) + } + s, err := load(g.file, false) + if err != nil { + return err + } + for _, e := range s.entries() { + if re.MatchString(e.Key) { + fmt.Println(e.Key) + } + } + return nil +} + +func cmdGet(g *globals, args []string) error { + if len(args) > 0 && isHelpArg(args[0]) { + printGetHelp() + return nil + } + dash := -1 + for i, a := range args { + if a == "--" { + dash = i + break + } + } + if dash < 0 { + return errors.New("missing \"--\" separator\n" + + "secretctl never prints secret values; give it a command to inject them into:\n" + + " secretctl get [KEY...] -- [args...]") + } + keys, cmdArgs := args[:dash], args[dash+1:] + if len(keys) == 0 { + return errors.New("no secret names given\nusage: secretctl get [KEY...] -- [args...]") + } + if len(cmdArgs) == 0 { + return errors.New("no command given after \"--\"") + } + for _, k := range keys { + if !validKey(k) { + return fmt.Errorf("invalid secret name %q", k) + } + } + s, err := load(g.file, false) + if err != nil { + return err + } + env := make(map[string]string, len(keys)) + var missing []string + for _, k := range keys { + if l := s.find(k); l != nil { + env[k] = l.entry.Value + } else { + missing = append(missing, k) + } + } + if len(missing) > 0 { + return fmt.Errorf("undefined secret(s): %s (see \"secretctl list\")", strings.Join(missing, ", ")) + } + return execWithEnv(env, cmdArgs) +} + +func cmdRun(g *globals, args []string) error { + all := false + var only []string +loop: + for len(args) > 0 { + a := args[0] + switch { + case a == "--": + args = args[1:] + break loop + case isHelpArg(a): + printRunHelp() + return nil + case a == "-a" || a == "--all": + all = true + args = args[1:] + case a == "-e" || a == "--env": + if len(args) < 2 { + return fmt.Errorf("flag %s requires a value", a) + } + only = append(only, args[1]) + args = args[2:] + case strings.HasPrefix(a, "-"): + return fmt.Errorf("unknown flag %q before \"--\"", a) + default: + return fmt.Errorf("unexpected argument %q before \"--\"", a) + } + } + if len(args) == 0 { + return errors.New("no command given\nusage: secretctl run [--all | -e KEY ...] -- [args...]") + } + if all && len(only) > 0 { + return errors.New("--all and -e are mutually exclusive") + } + if !all && len(only) == 0 { + return errors.New("nothing to inject; pass -e KEY or --all") + } + s, err := load(g.file, false) + if err != nil { + return err + } + env := map[string]string{} + if all { + for _, e := range s.entries() { + env[e.Key] = e.Value + } + } else { + var missing []string + for _, k := range only { + if !validKey(k) { + return fmt.Errorf("invalid secret name %q", k) + } + if l := s.find(k); l != nil { + env[k] = l.entry.Value + } else { + missing = append(missing, k) + } + } + if len(missing) > 0 { + return fmt.Errorf("undefined secret(s): %s", strings.Join(missing, ", ")) + } + } + return execWithEnv(env, args) +} + +func cmdAdd(g *globals, args []string) error { + allowEmpty := false + var pos []string + for _, a := range args { + switch { + case isHelpArg(a): + printAddHelp() + return nil + case a == "--allow-empty": + allowEmpty = true + case strings.HasPrefix(a, "-") && len(a) > 1: + return fmt.Errorf("unknown flag %q", a) + default: + pos = append(pos, a) + } + } + if len(pos) != 1 { + return errors.New("usage: secretctl add [--allow-empty]") + } + key := pos[0] + if !validKey(key) { + return fmt.Errorf("invalid variable name %q (must match [A-Za-z_][A-Za-z0-9_]*)", key) + } + s, err := load(g.file, true) + if err != nil { + return err + } + if s.find(key) != nil { + return fmt.Errorf("%s already exists; use \"secretctl set %s\" to change it", key, key) + } + val, err := readValueFor(fmt.Sprintf("Value for %s: ", key), allowEmpty) + if err != nil { + return err + } + s.add(key, val) + if err := s.save(); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "added %s to %s\n", key, g.file) + return nil +} + +func cmdSet(g *globals, args []string) error { + allowEmpty := false + var pos []string + for _, a := range args { + switch { + case isHelpArg(a): + printSetHelp() + return nil + case a == "--allow-empty": + allowEmpty = true + case strings.HasPrefix(a, "-") && len(a) > 1: + return fmt.Errorf("unknown flag %q", a) + default: + pos = append(pos, a) + } + } + if len(pos) != 1 { + return errors.New("usage: secretctl set [--allow-empty]") + } + key := pos[0] + s, err := load(g.file, false) + if err != nil { + return err + } + if s.find(key) == nil { + return fmt.Errorf("%s not found; use \"secretctl add %s\" to create it", key, key) + } + val, err := readValueFor(fmt.Sprintf("New value for %s: ", key), allowEmpty) + if err != nil { + return err + } + s.set(key, val) + if err := s.save(); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "updated %s in %s\n", key, g.file) + return nil +} + +func cmdRm(g *globals, args []string) error { + if len(args) > 0 && isHelpArg(args[0]) { + printRmHelp() + return nil + } + if len(args) != 1 { + return errors.New("usage: secretctl rm ") + } + key := args[0] + s, err := load(g.file, false) + if err != nil { + return err + } + if !s.remove(key) { + return fmt.Errorf("%s not found", key) + } + if err := s.save(); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "removed %s from %s\n", key, g.file) + return nil +} + +func cmdCheck(g *globals, args []string) error { + if len(args) > 0 && isHelpArg(args[0]) { + printCheckHelp() + return nil + } + if len(args) > 0 { + return errors.New("check takes no arguments") + } + info, err := os.Stat(g.file) + if err != nil { + return fmt.Errorf("%s: %v", g.file, err) + } + s, err := load(g.file, false) + if err != nil { + return err + } + mode := info.Mode().Perm() + if mode&0o077 != 0 { + return fmt.Errorf("%s has permissions %04o; it should be 0600\n run: chmod 600 %s", g.file, mode, g.file) + } + fmt.Printf("%s: ok, %d secret(s), permissions %04o\n", g.file, len(s.entries()), mode) + return nil +} + +func cmdHelp(args []string) error { + if len(args) == 0 { + printHelp(os.Stdout) + return nil + } + switch args[0] { + case "list": + printListHelp() + case "search": + printSearchHelp() + case "get": + printGetHelp() + case "run": + printRunHelp() + case "add": + printAddHelp() + case "set": + printSetHelp() + case "rm": + printRmHelp() + case "check": + printCheckHelp() + default: + return fmt.Errorf("unknown command %q", args[0]) + } + return nil +} diff --git a/tools/secretctl/store.go b/tools/secretctl/store.go new file mode 100644 index 0000000..9d73195 --- /dev/null +++ b/tools/secretctl/store.go @@ -0,0 +1,302 @@ +package main + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" +) + +// Entry is a single KEY=value pair in the secrets file. +type Entry struct { + Key string + Value string + Line int +} + +type line struct { + raw string + entry *Entry +} + +// Store is the parsed contents of a secrets file. +type Store struct { + path string + lines []line +} + +var keyRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +func validKey(s string) bool { return keyRE.MatchString(s) } + +// load parses the secrets file. When allowMissing is true a missing file +// yields an empty store (used by "add"). +func load(path string, allowMissing bool) (*Store, error) { + s := &Store{path: path} + data, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + if allowMissing { + return s, nil + } + return nil, fmt.Errorf("secrets file not found: %s\n create it with: secretctl add MY_SECRET", path) + } + return nil, err + } + warnPerms(path) + + text := strings.ReplaceAll(string(data), "\r\n", "\n") + if text == "" { + return s, nil + } + raws := strings.Split(text, "\n") + if raws[len(raws)-1] == "" { // drop artifact of the trailing newline + raws = raws[:len(raws)-1] + } + seen := map[string]int{} + for i, raw := range raws { + l, err := parseLine(raw, i+1) + if err != nil { + return nil, err + } + if l.entry != nil { + if prev, ok := seen[l.entry.Key]; ok { + return nil, fmt.Errorf("line %d: duplicate variable %q (first defined on line %d)", + i+1, l.entry.Key, prev) + } + seen[l.entry.Key] = i + 1 + } + s.lines = append(s.lines, l) + } + return s, nil +} + +func warnPerms(path string) { + if runtime.GOOS == "windows" { + return + } + info, err := os.Stat(path) + if err != nil { + return + } + if mode := info.Mode().Perm(); mode&0o077 != 0 { + fmt.Fprintf(os.Stderr, + "secretctl: warning: %s has permissions %04o (should be 0600); run: chmod 600 %s\n", + path, mode, path) + } +} + +// parseLine never echoes file content in its errors — the line might hold a +// secret we failed to understand. +func parseLine(raw string, no int) (line, error) { + trimmed := strings.TrimSpace(raw) + if trimmed == "" || strings.HasPrefix(trimmed, "#") { + return line{raw: raw}, nil + } + body := trimmed + if strings.HasPrefix(body, "export ") { + body = strings.TrimSpace(body[len("export "):]) + } + eq := strings.IndexByte(body, '=') + if eq < 0 { + return line{}, fmt.Errorf("line %d: expected KEY=value", no) + } + key := strings.TrimSpace(body[:eq]) + if !validKey(key) { + return line{}, fmt.Errorf("line %d: invalid variable name (must match [A-Za-z_][A-Za-z0-9_]*)", no) + } + val, err := parseValue(body[eq+1:]) + if err != nil { + return line{}, fmt.Errorf("line %d: %v", no, err) + } + return line{raw: raw, entry: &Entry{Key: key, Value: val, Line: no}}, nil +} + +func parseValue(s string) (string, error) { + if s == "" { + return "", nil + } + switch s[0] { + case '"': + var b strings.Builder + for i := 1; i < len(s); { + c := s[i] + if c == '\\' && i+1 < len(s) { + switch s[i+1] { + case 'n': + b.WriteByte('\n') + case 'r': + b.WriteByte('\r') + case 't': + b.WriteByte('\t') + case '"': + b.WriteByte('"') + case '\\': + b.WriteByte('\\') + default: + b.WriteByte('\\') + b.WriteByte(s[i+1]) + } + i += 2 + continue + } + if c == '"' { + if err := checkTrailer(s[i+1:]); err != nil { + return "", err + } + return b.String(), nil + } + b.WriteByte(c) + i++ + } + return "", errors.New("unterminated double-quoted value") + case '\'': + for i := 1; i < len(s); i++ { + if s[i] == '\'' { + if err := checkTrailer(s[i+1:]); err != nil { + return "", err + } + return s[1:i], nil + } + } + return "", errors.New("unterminated single-quoted value") + default: + v := s + if i := strings.Index(v, " #"); i >= 0 { + v = v[:i] + } + if i := strings.Index(v, "\t#"); i >= 0 { + v = v[:i] + } + return strings.TrimRight(v, " \t"), nil + } +} + +func checkTrailer(rest string) error { + rest = strings.TrimSpace(rest) + if rest == "" || strings.HasPrefix(rest, "#") { + return nil + } + return errors.New("unexpected characters after closing quote") +} + +var plainSafe = regexp.MustCompile(`^[A-Za-z0-9_@%+=:,./-]*$`) + +func formatValue(v string) string { + if plainSafe.MatchString(v) { + return v + } + var b strings.Builder + b.WriteByte('"') + for _, r := range v { + switch r { + case '\\': + b.WriteString(`\\`) + case '"': + b.WriteString(`\"`) + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + default: + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String() +} + +func (s *Store) entries() []*Entry { + out := make([]*Entry, 0, len(s.lines)) + for i := range s.lines { + if s.lines[i].entry != nil { + out = append(out, s.lines[i].entry) + } + } + return out +} + +func (s *Store) find(key string) *line { + for i := range s.lines { + if s.lines[i].entry != nil && s.lines[i].entry.Key == key { + return &s.lines[i] + } + } + return nil +} + +func (s *Store) add(key, val string) { + s.lines = append(s.lines, line{ + raw: key + "=" + formatValue(val), + entry: &Entry{Key: key, Value: val}, + }) +} + +func (s *Store) set(key, val string) bool { + for i := range s.lines { + if s.lines[i].entry != nil && s.lines[i].entry.Key == key { + s.lines[i].entry.Value = val + s.lines[i].raw = key + "=" + formatValue(val) + return true + } + } + return false +} + +func (s *Store) remove(key string) bool { + for i := range s.lines { + if s.lines[i].entry != nil && s.lines[i].entry.Key == key { + s.lines = append(s.lines[:i], s.lines[i+1:]...) + return true + } + } + return false +} + +// save writes the file atomically with mode 0600. +func (s *Store) save() error { + var b strings.Builder + for i, l := range s.lines { + if i > 0 { + b.WriteByte('\n') + } + b.WriteString(l.raw) + } + out := b.String() + if out != "" && !strings.HasSuffix(out, "\n") { + out += "\n" + } + + dir := filepath.Dir(s.path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".secrets-*") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.WriteString(out); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, s.path) +}