Repository navigation
Expand file tree
/
Copy pathreceipts_cmd.go
More file actions
304 lines (289 loc) · 8.33 KB
/
Copy pathreceipts_cmd.go
File metadata and controls
304 lines (289 loc) · 8.33 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"github.com/renezander030/draftcat/internal/approval"
statestore "github.com/renezander030/draftcat/internal/state"
)
type receiptJSON struct {
Version int `json:"version"`
ReceiptID string `json:"receipt_id"`
RunID string `json:"run_id,omitempty"`
ActionID string `json:"action_id,omitempty"`
Pipeline string `json:"pipeline"`
Step string `json:"step"`
DecidedAt string `json:"decided_at"`
Decision string `json:"decision"`
OperatorID int64 `json:"operator_id"`
PayloadHash string `json:"payload_hash"`
Policy string `json:"policy,omitempty"`
PolicyHash string `json:"policy_hash,omitempty"`
BindingHash string `json:"binding_hash,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
Lifecycle string `json:"lifecycle"`
QuorumN int `json:"quorum_n"`
QuorumGot int `json:"quorum_got"`
Nonce string `json:"nonce,omitempty"`
Signature string `json:"signature,omitempty"`
Verification string `json:"verification"`
}
func receiptID(r statestore.ApprovalRecord) string {
if r.ReceiptID != "" {
return r.ReceiptID
}
return strconv.FormatInt(r.ID, 10)
}
// receiptVerdict is a receipt's verification status: ok, tampered or
// unsigned, and unverified when it is signed but no secret is at hand.
func receiptVerdict(secret []byte, r statestore.ApprovalRecord) string {
if r.Signature != "" && len(secret) == 0 {
return "unverified"
}
return statestore.VerifyApprovalRecord(secret, r)
}
func receiptView(r statestore.ApprovalRecord, secret []byte) receiptJSON {
expires := ""
if !r.ExpiresAt.IsZero() {
expires = r.ExpiresAt.UTC().Format(time.RFC3339)
}
verification := receiptVerdict(secret, r)
return receiptJSON{
Version: r.Version, ReceiptID: receiptID(r), RunID: r.RunID, ActionID: r.ActionID,
Pipeline: r.Pipeline, Step: r.Step, DecidedAt: r.DecidedAt.UTC().Format(time.RFC3339),
Decision: r.Decision, OperatorID: r.OperatorID, PayloadHash: r.PayloadHash,
Policy: r.Policy, PolicyHash: r.PolicyHash, BindingHash: r.BindingHash,
ExpiresAt: expires, Lifecycle: r.Lifecycle, QuorumN: r.QuorumN, QuorumGot: r.QuorumGot,
Nonce: r.Nonce, Signature: r.Signature,
Verification: verification,
}
}
func runReceiptsCmd(args []string) int {
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Usage: draftcat receipts <list|show|export|verify> [options]")
return 2
}
switch args[0] {
case "list":
return runReceiptsList(args[1:])
case "show":
return runReceiptsShow(args[1:])
case "export":
return runReceiptsExport(args[1:])
case "verify":
return runReceiptsVerify(args[1:])
case "-h", "--help", "help":
fmt.Println("Usage: draftcat receipts <list|show|export|verify> [options]")
fmt.Println(" list [--pipeline name] [--limit N] [--json] [--config path]")
fmt.Println(" show <receipt-id> [--config path]")
fmt.Println(" export [--pipeline name] [--limit N] [--out path] [--config path]")
fmt.Println(" verify <file.jsonl|-> [--json] check signed fields without opening SQLite")
return 0
default:
fmt.Fprintf(os.Stderr, "receipts: unknown command %q\n", args[0])
return 2
}
}
type receiptOptions struct {
pipeline string
config string
out string
limit int
json bool
receiptID string
}
func parseReceiptOptions(args []string, allowID bool) (receiptOptions, int) {
o := receiptOptions{config: "config.yaml", limit: 100}
for i := 0; i < len(args); i++ {
switch args[i] {
case "--pipeline":
if i+1 >= len(args) {
fmt.Fprintln(os.Stderr, "receipts: --pipeline requires a name")
return o, 2
}
o.pipeline = args[i+1]
i++
case "--config", "-config":
if i+1 >= len(args) {
fmt.Fprintln(os.Stderr, "receipts: --config requires a path")
return o, 2
}
o.config = args[i+1]
i++
case "--out":
if i+1 >= len(args) {
fmt.Fprintln(os.Stderr, "receipts: --out requires a path")
return o, 2
}
o.out = args[i+1]
i++
case "--limit":
if i+1 >= len(args) {
fmt.Fprintln(os.Stderr, "receipts: --limit requires a number")
return o, 2
}
n, err := strconv.Atoi(args[i+1])
if err != nil || n <= 0 {
fmt.Fprintln(os.Stderr, "receipts: --limit must be positive")
return o, 2
}
o.limit = n
i++
case "--json":
o.json = true
default:
if allowID && !strings.HasPrefix(args[i], "-") && o.receiptID == "" {
o.receiptID = args[i]
continue
}
fmt.Fprintf(os.Stderr, "receipts: unknown option %q\n", args[i])
return o, 2
}
}
return o, 0
}
func loadReceipts(o receiptOptions) (*statestore.StateStore, func(), []statestore.ApprovalRecord, int) {
st, closeStore, code := openStateForCmd(o.config)
if code != 0 {
return nil, closeStore, nil, code
}
var rows []statestore.ApprovalRecord
var err error
if o.pipeline == "" {
rows, err = st.AllApprovals(o.limit)
} else {
rows, err = st.ApprovalsForPipeline(o.pipeline, o.limit)
}
if err != nil {
closeStore()
fmt.Fprintf(os.Stderr, "receipts: read: %v\n", err)
return nil, func() {}, nil, 1
}
return st, closeStore, rows, 0
}
func runReceiptsList(args []string) int {
o, code := parseReceiptOptions(args, false)
if code != 0 {
return code
}
_, closeStore, rows, code := loadReceipts(o)
if code != 0 {
return code
}
defer closeStore()
secret := []byte(os.Getenv("DRAFTCAT_APPROVAL_SECRET"))
views := make([]receiptJSON, 0, len(rows))
for _, r := range rows {
views = append(views, receiptView(r, secret))
}
if o.json {
b, _ := json.MarshalIndent(views, "", " ")
fmt.Println(string(b))
return 0
}
if len(views) == 0 {
fmt.Println("No receipts recorded yet.")
return 0
}
for _, r := range views {
fmt.Printf("%s %-22s %-20s %-15s %s\n", r.DecidedAt, r.Pipeline, r.Step, r.Decision, r.ReceiptID)
}
return 0
}
func runReceiptsShow(args []string) int {
o, code := parseReceiptOptions(args, true)
if code != 0 {
return code
}
if o.receiptID == "" {
fmt.Fprintln(os.Stderr, "receipts show: receipt id required")
return 2
}
st, closeStore, code := openStateForCmd(o.config)
if code != 0 {
return code
}
defer closeStore()
r, err := st.ApprovalByReceiptID(o.receiptID)
if err != nil {
fmt.Fprintf(os.Stderr, "receipts show: %v\n", err)
return 1
}
secret := []byte(os.Getenv("DRAFTCAT_APPROVAL_SECRET"))
view := struct {
receiptJSON
Note *noteJSON `json:"note,omitempty"`
}{receiptJSON: receiptView(r, secret)}
if notes, err := st.ApprovalNotes([]string{r.ReceiptID}); err == nil {
if n, ok := notes[r.ReceiptID]; ok {
nv := noteView(n, secret)
view.Note = &nv
}
}
b, _ := json.MarshalIndent(view, "", " ")
fmt.Println(string(b))
return 0
}
// noteJSON is an operator's reason for a decision, with its own verification.
type noteJSON struct {
OperatorID int64 `json:"operator_id"`
Reason string `json:"reason"`
NotedAt string `json:"noted_at"`
Verification string `json:"verification"`
}
func noteView(n statestore.ApprovalNote, secret []byte) noteJSON {
v := "unsigned"
switch {
case n.Signature != "" && len(secret) == 0:
v = "unverified"
case n.Signature != "":
v = "tampered"
if approval.VerifyNote(secret, approval.NoteFields{ReceiptID: n.ReceiptID, OperatorID: n.OperatorID, Reason: n.Reason, NotedAt: n.NotedAt.Unix()}, n.Nonce, n.Signature) {
v = "ok"
}
}
return noteJSON{OperatorID: n.OperatorID, Reason: n.Reason, NotedAt: n.NotedAt.UTC().Format(time.RFC3339), Verification: v}
}
func runReceiptsExport(args []string) int {
o, code := parseReceiptOptions(args, false)
if code != 0 {
return code
}
_, closeStore, rows, code := loadReceipts(o)
if code != 0 {
return code
}
defer closeStore()
var dst io.Writer = os.Stdout
var f *os.File
if o.out != "" {
var err error
f, err = os.OpenFile(o.out, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
fmt.Fprintf(os.Stderr, "receipts export: %v\n", err)
return 1
}
defer func() { _ = f.Close() }()
dst = f
}
w := bufio.NewWriter(dst)
secret := []byte(os.Getenv("DRAFTCAT_APPROVAL_SECRET"))
for i := len(rows) - 1; i >= 0; i-- {
b, err := json.Marshal(receiptView(rows[i], secret))
if err != nil {
fmt.Fprintf(os.Stderr, "receipts export: row %d: %v\n", rows[i].ID, err)
continue
}
_, _ = w.Write(append(b, '\n'))
}
if err := w.Flush(); err != nil {
fmt.Fprintf(os.Stderr, "receipts export: %v\n", err)
return 1
}
return 0
}