|
| 1 | +package env |
| 2 | + |
| 3 | +// Local env files with at-rest encryption (the SOPS+age GitOps pattern): |
| 4 | +// secrets live encrypted in the repo, get decrypted on the operator's |
| 5 | +// machine at deploy time, and ride the existing deploy-env path to the |
| 6 | +// container. Nothing new is persisted anywhere — the encrypted file stays |
| 7 | +// the source of truth. |
| 8 | +// |
| 9 | +// Decryption shells out to the local `age` / `sops` binaries (mirroring how |
| 10 | +// the server-side secret store shells out to age on the host) so teploy |
| 11 | +// carries no crypto dependencies and interoperates with files produced by |
| 12 | +// the standard tools. |
| 13 | + |
| 14 | +import ( |
| 15 | + "errors" |
| 16 | + "fmt" |
| 17 | + "os" |
| 18 | + "os/exec" |
| 19 | + "path/filepath" |
| 20 | + "strings" |
| 21 | + |
| 22 | + "gopkg.in/yaml.v3" |
| 23 | +) |
| 24 | + |
| 25 | +// LoadLocalEnvFiles reads each file (paths relative to dir), decrypting as |
| 26 | +// needed, and returns the merged KEY=value map (later files win). |
| 27 | +// |
| 28 | +// - `*.age` — age-encrypted dotenv; decrypted with the |
| 29 | +// identity file from $TEPLOY_AGE_IDENTITY, $SOPS_AGE_KEY_FILE, or |
| 30 | +// ~/.config/teploy/age.txt (first that exists). |
| 31 | +// - `*.sops.*` / `*.enc.*` — SOPS-encrypted (any age/KMS backend |
| 32 | +// configured in .sops.yaml); decrypted via `sops -d`. dotenv, YAML, and |
| 33 | +// JSON payloads are supported — YAML/JSON contribute their top-level |
| 34 | +// scalar keys. |
| 35 | +// - anything else — plain dotenv, read as-is. |
| 36 | +func LoadLocalEnvFiles(dir string, paths []string) (map[string]string, error) { |
| 37 | + merged := make(map[string]string) |
| 38 | + for _, p := range paths { |
| 39 | + full := p |
| 40 | + if !filepath.IsAbs(full) { |
| 41 | + full = filepath.Join(dir, p) |
| 42 | + } |
| 43 | + var ( |
| 44 | + content string |
| 45 | + err error |
| 46 | + ) |
| 47 | + switch { |
| 48 | + case strings.HasSuffix(full, ".age"): |
| 49 | + content, err = decryptAgeFile(full) |
| 50 | + case isSopsName(full): |
| 51 | + content, err = decryptSopsFile(full) |
| 52 | + default: |
| 53 | + var raw []byte |
| 54 | + raw, err = os.ReadFile(full) |
| 55 | + content = string(raw) |
| 56 | + } |
| 57 | + if err != nil { |
| 58 | + return nil, fmt.Errorf("env file %s: %w", p, err) |
| 59 | + } |
| 60 | + vars, err := parseEnvContent(full, content) |
| 61 | + if err != nil { |
| 62 | + return nil, fmt.Errorf("env file %s: %w", p, err) |
| 63 | + } |
| 64 | + for k, v := range vars { |
| 65 | + merged[k] = v |
| 66 | + } |
| 67 | + } |
| 68 | + return merged, nil |
| 69 | +} |
| 70 | + |
| 71 | +func isSopsName(path string) bool { |
| 72 | + base := filepath.Base(path) |
| 73 | + return strings.Contains(base, ".sops.") || strings.Contains(base, ".enc.") |
| 74 | +} |
| 75 | + |
| 76 | +// ageIdentityFile resolves the age identity (private key) file to decrypt |
| 77 | +// with. Explicit env vars first, then the teploy-conventional location. |
| 78 | +func ageIdentityFile() (string, error) { |
| 79 | + for _, envVar := range []string{"TEPLOY_AGE_IDENTITY", "SOPS_AGE_KEY_FILE"} { |
| 80 | + if p := os.Getenv(envVar); p != "" { |
| 81 | + return p, nil |
| 82 | + } |
| 83 | + } |
| 84 | + home, err := os.UserHomeDir() |
| 85 | + if err == nil { |
| 86 | + conventional := filepath.Join(home, ".config", "teploy", "age.txt") |
| 87 | + if _, statErr := os.Stat(conventional); statErr == nil { |
| 88 | + return conventional, nil |
| 89 | + } |
| 90 | + } |
| 91 | + return "", fmt.Errorf("no age identity found — set TEPLOY_AGE_IDENTITY (or SOPS_AGE_KEY_FILE), or put the key at ~/.config/teploy/age.txt") |
| 92 | +} |
| 93 | + |
| 94 | +func decryptAgeFile(path string) (string, error) { |
| 95 | + if _, err := exec.LookPath("age"); err != nil { |
| 96 | + return "", fmt.Errorf("`age` binary not found — install age (https://age-encryption.org) to use .age env files") |
| 97 | + } |
| 98 | + identity, err := ageIdentityFile() |
| 99 | + if err != nil { |
| 100 | + return "", err |
| 101 | + } |
| 102 | + out, err := exec.Command("age", "-d", "-i", identity, path).Output() |
| 103 | + if err != nil { |
| 104 | + return "", fmt.Errorf("age decrypt failed: %w%s", err, stderrOf(err)) |
| 105 | + } |
| 106 | + return string(out), nil |
| 107 | +} |
| 108 | + |
| 109 | +func decryptSopsFile(path string) (string, error) { |
| 110 | + if _, err := exec.LookPath("sops"); err != nil { |
| 111 | + return "", fmt.Errorf("`sops` binary not found — install sops (https://github.com/getsops/sops) to use SOPS env files") |
| 112 | + } |
| 113 | + out, err := exec.Command("sops", "-d", path).Output() |
| 114 | + if err != nil { |
| 115 | + return "", fmt.Errorf("sops decrypt failed: %w%s", err, stderrOf(err)) |
| 116 | + } |
| 117 | + return string(out), nil |
| 118 | +} |
| 119 | + |
| 120 | +func stderrOf(err error) string { |
| 121 | + var ee *exec.ExitError |
| 122 | + if errors.As(err, &ee) && len(ee.Stderr) > 0 { |
| 123 | + return ": " + strings.TrimSpace(string(ee.Stderr)) |
| 124 | + } |
| 125 | + return "" |
| 126 | +} |
| 127 | + |
| 128 | +// parseEnvContent interprets decrypted payloads: YAML/JSON files contribute |
| 129 | +// their top-level scalar keys; everything else is parsed as dotenv. |
| 130 | +func parseEnvContent(path, content string) (map[string]string, error) { |
| 131 | + name := strings.ToLower(filepath.Base(path)) |
| 132 | + // Strip encryption suffixes to find the underlying format: |
| 133 | + // secrets.yaml.age -> secrets.yaml, secrets.sops.json -> secrets.json. |
| 134 | + name = strings.TrimSuffix(name, ".age") |
| 135 | + name = strings.ReplaceAll(name, ".sops.", ".") |
| 136 | + name = strings.ReplaceAll(name, ".enc.", ".") |
| 137 | + if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".json") { |
| 138 | + var doc map[string]any |
| 139 | + if err := yaml.Unmarshal([]byte(content), &doc); err != nil { |
| 140 | + return nil, fmt.Errorf("parsing %s: %w", filepath.Base(path), err) |
| 141 | + } |
| 142 | + vars := make(map[string]string, len(doc)) |
| 143 | + for k, v := range doc { |
| 144 | + switch val := v.(type) { |
| 145 | + case string: |
| 146 | + vars[k] = val |
| 147 | + case int, int64, float64, bool: |
| 148 | + vars[k] = fmt.Sprintf("%v", val) |
| 149 | + default: |
| 150 | + // Nested structures (and SOPS's own `sops:` metadata block, |
| 151 | + // which survives in the plaintext of some formats) are not |
| 152 | + // env material. |
| 153 | + } |
| 154 | + } |
| 155 | + delete(vars, "sops") |
| 156 | + return vars, nil |
| 157 | + } |
| 158 | + return parseEnv(content), nil |
| 159 | +} |
0 commit comments