-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoctor_bundle.go
More file actions
269 lines (239 loc) · 7.79 KB
/
Copy pathdoctor_bundle.go
File metadata and controls
269 lines (239 loc) · 7.79 KB
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package cli
import (
"archive/zip"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/GrayCodeAI/trace/cli/logging"
"github.com/GrayCodeAI/trace/cli/paths"
"github.com/GrayCodeAI/trace/cli/versioninfo"
"github.com/GrayCodeAI/trace/redact"
"github.com/spf13/cobra"
)
func newDoctorBundleCmd() *cobra.Command {
var outFlag string
var rawFlag bool
cmd := &cobra.Command{
Use: "bundle",
Short: "Produce a diagnostic bundle (zip) for bug reports — secrets are redacted by default",
Long: `Produce a zip archive containing logs, settings, and a git snapshot suitable
for attaching to bug reports.
The archive includes:
- logs/ (operational logs from .trace/logs/)
- settings/settings.json and settings/settings.local.json (if present)
- git-status.txt, git-log.txt, git-remote.txt
- version.txt with CLI version, Go version, OS/Arch
Redaction:
By default the bundle redacts known secrets (API keys, credentialed URIs,
database connection strings, bounded KEY=value credentials) from log files,
settings JSON, and git command output before zipping. Pass --raw to skip
redaction; use it only when support has explicitly requested an unredacted
bundle.
By default the archive is written to a path inside the OS temp directory and
that path is printed to stdout. Use --out to choose a specific path.`,
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
repoRoot, err := paths.WorktreeRoot(ctx)
if err != nil {
cmd.SilenceUsage = true
return errors.New("not a git repository")
}
outPath := outFlag
if outPath == "" {
outPath = filepath.Join(os.TempDir(), fmt.Sprintf("trace-bundle-%s.zip", time.Now().UTC().Format("20060102-150405")))
}
if err := writeDoctorBundle(ctx, repoRoot, outPath, rawFlag); err != nil {
return err
}
if rawFlag {
fmt.Fprintf(cmd.ErrOrStderr(), "Bundle written (RAW — contains unredacted contents): %s\n", outPath)
} else {
fmt.Fprintf(cmd.ErrOrStderr(), "Bundle written (redacted): %s\n", outPath)
}
fmt.Fprintln(cmd.OutOrStdout(), outPath)
return nil
},
}
cmd.Flags().StringVarP(&outFlag, "out", "o", "", "Path to write the bundle archive (default: OS temp dir)")
cmd.Flags().BoolVar(&rawFlag, "raw", false, "Skip secret redaction. The archive will contain raw log lines, settings, and git output. Use only when support has asked for an unredacted bundle.")
return cmd
}
func writeDoctorBundle(ctx context.Context, repoRoot, outPath string, raw bool) error {
// #nosec G304 -- outPath is user-provided via --out flag, a standard trusted CLI argument
out, err := os.OpenFile(outPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) //nolint:gosec // user-provided output path is intentional
if err != nil {
return fmt.Errorf("create bundle: %w", err)
}
if err := out.Chmod(0o600); err != nil {
_ = out.Close()
return fmt.Errorf("set bundle permissions: %w", err)
}
fileClosed := false
defer func() {
if !fileClosed {
_ = out.Close()
}
}()
zw := zip.NewWriter(out)
zipClosed := false
defer func() {
if !zipClosed {
_ = zw.Close()
}
}()
logsDir := filepath.Join(repoRoot, logging.LogsDir)
if err := addDirToZip(zw, logsDir, "logs", raw); err != nil {
return err
}
for _, name := range []string{"settings.json", "settings.local.json"} {
src := filepath.Join(repoRoot, ".trace", name)
if err := addFileToZip(zw, src, path.Join("settings", name), raw); err != nil {
return err
}
}
if err := addCommandOutput(ctx, zw, "git-status.txt", repoRoot, raw, "git", "status", "--short", "--branch"); err != nil {
return err
}
if err := addCommandOutput(ctx, zw, "git-log.txt", repoRoot, raw, "git", "log", "-n", "50", "--oneline"); err != nil {
return err
}
if err := addCommandOutput(ctx, zw, "git-remote.txt", repoRoot, raw, "git", "remote", "-v"); err != nil {
return err
}
if err := addStringToZip(zw, "version.txt", versionInfoString(), raw); err != nil {
return err
}
if err := zw.Close(); err != nil {
return fmt.Errorf("finalize bundle: %w", err)
}
zipClosed = true
if err := out.Close(); err != nil {
return fmt.Errorf("close bundle: %w", err)
}
fileClosed = true
return nil
}
func versionInfoString() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Trace CLI %s (%s)\n", versioninfo.Version, versioninfo.Commit)
fmt.Fprintf(&sb, "Go: %s\n", runtime.Version())
fmt.Fprintf(&sb, "OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
return sb.String()
}
func addDirToZip(zw *zip.Writer, srcDir, archivePrefix string, raw bool) error {
info, err := os.Stat(srcDir)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("stat %s: %w", srcDir, err)
}
if !info.IsDir() {
return nil
}
walkErr := filepath.Walk(srcDir, func(path string, fi os.FileInfo, werr error) error {
if werr != nil {
return werr
}
if fi.IsDir() {
return nil
}
rel, err := filepath.Rel(srcDir, path)
if err != nil {
return fmt.Errorf("rel: %w", err)
}
return addFileToZip(zw, path, zipEntryName(archivePrefix, rel), raw)
})
if walkErr != nil {
return fmt.Errorf("walk %s: %w", srcDir, walkErr)
}
return nil
}
func zipEntryName(parts ...string) string {
cleanParts := make([]string, 0, len(parts))
for _, part := range parts {
if part == "" {
continue
}
cleanParts = append(cleanParts, filepath.ToSlash(part))
}
return path.Join(cleanParts...)
}
func addFileToZip(zw *zip.Writer, src, archivePath string, raw bool) error {
// #nosec G304 -- src comes from repo-internal walk (settings files, logs dir), not external input
f, err := os.Open(src) //nolint:gosec // path comes from repo-internal walk
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("open %s: %w", src, err)
}
defer f.Close()
entryName := zipEntryName(archivePath)
w, err := zw.Create(entryName)
if err != nil {
return fmt.Errorf("zip create %s: %w", entryName, err)
}
if raw {
if _, err := io.Copy(w, f); err != nil {
return fmt.Errorf("zip copy %s: %w", entryName, err)
}
return nil
}
contents, err := io.ReadAll(f)
if err != nil {
return fmt.Errorf("read %s: %w", src, err)
}
redacted := redactBundleEntry(entryName, contents)
if _, err := w.Write(redacted); err != nil {
return fmt.Errorf("zip write %s: %w", entryName, err)
}
return nil
}
func addStringToZip(zw *zip.Writer, archivePath, contents string, raw bool) error {
entryName := zipEntryName(archivePath)
w, err := zw.Create(entryName)
if err != nil {
return fmt.Errorf("zip create %s: %w", entryName, err)
}
body := contents
if !raw {
body = string(redactBundleEntry(entryName, []byte(contents)))
}
if _, err := io.WriteString(w, body); err != nil {
return fmt.Errorf("zip write %s: %w", entryName, err)
}
return nil
}
func addCommandOutput(ctx context.Context, zw *zip.Writer, archivePath, dir string, raw bool, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
out = append(out, []byte(fmt.Sprintf("\n[error: %v]\n", err))...)
}
// addStringToZip applies redaction when raw=false; pass through verbatim otherwise.
return addStringToZip(zw, archivePath, string(out), raw)
}
// redactBundleEntry chooses a redaction strategy per file shape. JSON / JSONL
// entries get the field-aware redactor (preserves structure, skips ID fields);
// everything else uses the byte-level scrubber.
func redactBundleEntry(entryName string, contents []byte) []byte {
ext := strings.ToLower(path.Ext(entryName))
if ext == ".json" || ext == ".jsonl" {
out, err := redact.JSONLContent(string(contents))
if err == nil {
return []byte(out)
}
// Fall through to plain redaction if the JSON redactor refuses (malformed input, etc.)
}
return redact.Bytes(contents)
}