Öffentliche Dateiansicht: Raw-Dateien, Tree, Releases und Issues sind ohne Login verfügbar.
cmd/push_op.go Raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package cmd

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"sort"
	"strings"

	"envault/vault"

	"github.com/spf13/cobra"
)

func init() {
	rootCmd.AddCommand(newSyncOPCmd())
}

type opVaultInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// newSyncOPCmd creates the `ev sync 1password` command.
func newSyncOPCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "sync",
		Short: "Sync secrets to external services",
	}
	cmd.AddCommand(newSync1PasswordCmd())
	return cmd
}

func newSync1PasswordCmd() *cobra.Command {
	var opVaultName string
	var projectName string

	cmd := &cobra.Command{
		Use:   "1password",
		Short: "Push project secrets to 1Password as Secure Notes",
		Long: `Creates or updates a 1Password Secure Note for one or all projects.

Each note is titled "ev: <project-name>" and contains all secrets in .env format.
If --op-vault is not set, the command lists available vaults interactively.

Requires the 1Password CLI (op) to be installed and signed in.`,
		Args: cobra.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			if _, err := exec.LookPath("op"); err != nil {
				return fmt.Errorf("1Password CLI (op) not found in PATH\nInstall from: https://developer.1password.com/docs/cli")
			}

			// Resolve 1Password vault
			if opVaultName == "" {
				chosen, err := selectOPVault()
				if err != nil {
					return err
				}
				opVaultName = chosen
			}

			// Open ev vault
			v, _, _, err := openVault()
			if err != nil {
				return err
			}

			// Determine which projects to sync
			var projects []string
			if projectName != "" {
				projects = []string{projectName}
			} else {
				projects = v.ListProjects()
			}

			if len(projects) == 0 {
				return fmt.Errorf("no projects found in vault")
			}

			for _, proj := range projects {
				if err := pushProjectToOP(proj, opVaultName, v); err != nil {
					fmt.Fprintf(os.Stderr, "  x %s: %v\n", proj, err)
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opVaultName, "op-vault", "", "1Password vault name or ID (default: interactive selection)")
	cmd.Flags().StringVarP(&projectName, "project", "p", "", "sync only this project (default: all projects)")
	return cmd
}

// pushProjectToOP creates or updates a 1Password Secure Note for the given project.
// The note content is the project's secrets in .env format.
func pushProjectToOP(project, opVaultName string, v *vault.Vault) error {
	vars := v.GetAll(project)
	if len(vars) == 0 {
		fmt.Fprintf(os.Stderr, "  - %s: no secrets, skipping\n", project)
		return nil
	}

	content := buildEnvContent(vars)
	title := "ev: " + project
	notesField := "notesPlain=" + content

	if opItemExists(title, opVaultName) {
		out, err := exec.Command("op", "item", "edit", title,
			"--vault", opVaultName,
			notesField,
		).CombinedOutput()
		if err != nil {
			return fmt.Errorf("op item edit failed: %s", strings.TrimSpace(string(out)))
		}
		fmt.Fprintf(os.Stderr, "  up %s: updated (%d secrets)\n", project, len(vars))
	} else {
		out, err := exec.Command("op", "item", "create",
			"--category", "Secure Note",
			"--title", title,
			"--vault", opVaultName,
			notesField,
		).CombinedOutput()
		if err != nil {
			return fmt.Errorf("op item create failed: %s", strings.TrimSpace(string(out)))
		}
		fmt.Fprintf(os.Stderr, "  + %s: created (%d secrets)\n", project, len(vars))
	}
	return nil
}

func opItemExists(title, vaultName string) bool {
	cmd := exec.Command("op", "item", "get", title, "--vault", vaultName)
	return cmd.Run() == nil
}

// selectOPVault lists available 1Password vaults and lets the user choose.
// Returns immediately if only one vault is available.
func selectOPVault() (string, error) {
	out, err := exec.Command("op", "vault", "list", "--format", "json").Output()
	if err != nil {
		return "", fmt.Errorf("listing 1Password vaults (are you signed in? run `op signin`): %w", err)
	}

	var vaults []opVaultInfo
	if err := json.Unmarshal(out, &vaults); err != nil {
		return "", fmt.Errorf("parsing vault list: %w", err)
	}

	if len(vaults) == 0 {
		return "", fmt.Errorf("no 1Password vaults found")
	}
	if len(vaults) == 1 {
		fmt.Fprintf(os.Stderr, "Using vault: %s\n", vaults[0].Name)
		return vaults[0].Name, nil
	}

	fmt.Fprintln(os.Stderr, "Available 1Password vaults:")
	for i, v := range vaults {
		fmt.Fprintf(os.Stderr, "  %d) %s\n", i+1, v.Name)
	}
	fmt.Fprint(os.Stderr, "Select vault: ")

	var choice int
	if _, err := fmt.Scan(&choice); err != nil || choice < 1 || choice > len(vaults) {
		return "", fmt.Errorf("invalid selection")
	}
	return vaults[choice-1].Name, nil
}

// buildEnvContent formats a vars map as a .env file string.
func buildEnvContent(vars map[string]string) string {
	keys := make([]string, 0, len(vars))
	for k := range vars {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	var sb strings.Builder
	for _, k := range keys {
		v := vars[k]
		if needsQuoting(v) {
			v = `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(v) + `"`
		}
		sb.WriteString(k)
		sb.WriteByte('=')
		sb.WriteString(v)
		sb.WriteByte('\n')
	}
	return sb.String()
}

func needsQuoting(s string) bool {
	return strings.ContainsAny(s, " \t\n\"'\\#$`!")
}