Debian Codegraph @

plugin/client.go

raw symbols SCIP
1 // Copyright 2021 Google LLC
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6
7 package plugin
8
9 import (
10 "bufio"
11 "crypto/rand"
12 "errors"
13 "fmt"
14 "io"
15 mathrand "math/rand/v2"
16 "os"
17 "path/filepath"
18 "strconv"
19 "strings"
20 "time"
21
22 exec "golang.org/x/sys/execabs"
23
24 "filippo.io/age"
25 "filippo.io/age/internal/format"
26 )
27
28 type Recipient struct {
29 name string
30 encoding string
31 ui *ClientUI
32
33 // identity is true when encoding is an identity string.
34 identity bool
35 }
36
37 var _ age.Recipient = &Recipient{}
38 var _ age.RecipientWithLabels = &Recipient{}
39
40 func NewRecipient(s string, ui *ClientUI) (*Recipient, error) {
41 name, _, err := ParseRecipient(s)
42 if err != nil {
43 return nil, err
44 }
45 return &Recipient{
46 name: name, encoding: s, ui: ui,
47 }, nil
48 }
49
50 // Name returns the plugin name, which is used in the recipient ("age1name1...")
51 // and identity ("AGE-PLUGIN-NAME-1...") encodings, as well as in the plugin
52 // binary name ("age-plugin-name").
53 func (r *Recipient) Name() string {
54 return r.name
55 }
56
57 // String returns the recipient encoding string ("age1name1...") or
58 // "<identity-based recipient>" if r was created by [Identity.Recipient].
59 func (r *Recipient) String() string {
60 if r.identity {
61 return "<identity-based recipient>"
62 }
63 return r.encoding
64 }
65
66 func (r *Recipient) Wrap(fileKey []byte) (stanzas []*age.Stanza, err error) {
67 stanzas, _, err = r.WrapWithLabels(fileKey)
68 return
69 }
70
71 func (r *Recipient) WrapWithLabels(fileKey []byte) (stanzas []*age.Stanza, labels []string, err error) {
72 defer func() {
73 if err != nil {
74 err = fmt.Errorf("%s plugin: %w", r.name, err)
75 }
76 }()
77
78 conn, err := openClientConnection(r.name, "recipient-v1")
79 if err != nil {
80 return nil, nil, fmt.Errorf("couldn't start plugin: %w", err)
81 }
82 defer conn.Close()
83
84 // Phase 1: client sends recipient or identity and file key
85 addType := "add-recipient"
86 if r.identity {
87 addType = "add-identity"
88 }
89 if err := writeStanza(conn, addType, r.encoding); err != nil {
90 return nil, nil, err
91 }
92 if _, err := writeGrease(conn); err != nil {
93 return nil, nil, err
94 }
95 if err := writeStanzaWithBody(conn, "wrap-file-key", fileKey); err != nil {
96 return nil, nil, err
97 }
98 if err := writeStanza(conn, "extension-labels"); err != nil {
99 return nil, nil, err
100 }
101 if err := writeStanza(conn, "done"); err != nil {
102 return nil, nil, err
103 }
104
105 // Phase 2: plugin responds with stanzas
106 sr := format.NewStanzaReader(bufio.NewReader(conn))
107 ReadLoop:
108 for {
109 s, err := r.ui.readStanza(r.name, sr)
110 if err != nil {
111 return nil, nil, err
112 }
113
114 switch s.Type {
115 case "recipient-stanza":
116 if len(s.Args) < 2 {
117 return nil, nil, fmt.Errorf("malformed recipient stanza: unexpected argument count")
118 }
119 n, err := strconv.Atoi(s.Args[0])
120 if err != nil {
121 return nil, nil, fmt.Errorf("malformed recipient stanza: invalid index")
122 }
123 // We only send a single file key, so the index must be 0.
124 if n != 0 {
125 return nil, nil, fmt.Errorf("malformed recipient stanza: unexpected index")
126 }
127
128 stanzas = append(stanzas, &age.Stanza{
129 Type: s.Args[1],
130 Args: s.Args[2:],
131 Body: s.Body,
132 })
133
134 if err := writeStanza(conn, "ok"); err != nil {
135 return nil, nil, err
136 }
137 case "labels":
138 if labels != nil {
139 return nil, nil, fmt.Errorf("repeated labels stanza")
140 }
141 labels = s.Args
142
143 if err := writeStanza(conn, "ok"); err != nil {
144 return nil, nil, err
145 }
146 case "error":
147 if err := writeStanza(conn, "ok"); err != nil {
148 return nil, nil, err
149 }
150
151 return nil, nil, fmt.Errorf("%s", s.Body)
152 case "done":
153 break ReadLoop
154 default:
155 if ok, err := r.ui.handle(r.name, conn, s); err != nil {
156 return nil, nil, err
157 } else if !ok {
158 if err := writeStanza(conn, "unsupported"); err != nil {
159 return nil, nil, err
160 }
161 }
162 }
163 }
164
165 if len(stanzas) == 0 {
166 return nil, nil, fmt.Errorf("received zero recipient stanzas")
167 }
168
169 return stanzas, labels, nil
170 }
171
172 type Identity struct {
173 name string
174 encoding string
175 ui *ClientUI
176 }
177
178 var _ age.Identity = &Identity{}
179
180 func NewIdentity(s string, ui *ClientUI) (*Identity, error) {
181 name, _, err := ParseIdentity(s)
182 if err != nil {
183 return nil, err
184 }
185 return &Identity{
186 name: name, encoding: s, ui: ui,
187 }, nil
188 }
189
190 func NewIdentityWithoutData(name string, ui *ClientUI) (*Identity, error) {
191 s := EncodeIdentity(name, nil)
192 if s == "" {
193 return nil, fmt.Errorf("invalid plugin name: %q", name)
194 }
195 return &Identity{
196 name: strings.ToLower(name), encoding: s, ui: ui,
197 }, nil
198 }
199
200 // Name returns the plugin name, which is used in the recipient ("age1name1...")
201 // and identity ("AGE-PLUGIN-NAME-1...") encodings, as well as in the plugin
202 // binary name ("age-plugin-name").
203 func (i *Identity) Name() string {
204 return i.name
205 }
206
207 // String returns the identity encoding string ("AGE-PLUGIN-NAME-1...").
208 func (i *Identity) String() string {
209 return i.encoding
210 }
211
212 // Recipient returns a Recipient wrapping this identity. When that Recipient is
213 // used to encrypt a file key, the identity encoding is provided as-is to the
214 // plugin, which is expected to support encrypting to identities.
215 func (i *Identity) Recipient() *Recipient {
216 return &Recipient{
217 name: i.name,
218 encoding: i.encoding,
219 identity: true,
220 ui: i.ui,
221 }
222 }
223
224 func (i *Identity) Unwrap(stanzas []*age.Stanza) (fileKey []byte, err error) {
225 defer func() {
226 if err != nil {
227 err = fmt.Errorf("%s plugin: %w", i.name, err)
228 }
229 }()
230
231 conn, err := openClientConnection(i.name, "identity-v1")
232 if err != nil {
233 return nil, fmt.Errorf("couldn't start plugin: %w", err)
234 }
235 defer conn.Close()
236
237 // Phase 1: client sends the plugin the identity string and the stanzas
238 if err := writeStanza(conn, "add-identity", i.encoding); err != nil {
239 return nil, err
240 }
241 if _, err := writeGrease(conn); err != nil {
242 return nil, err
243 }
244 for _, rs := range stanzas {
245 s := &format.Stanza{
246 Type: "recipient-stanza",
247 Args: append([]string{"0", rs.Type}, rs.Args...),
248 Body: rs.Body,
249 }
250 if err := s.Marshal(conn); err != nil {
251 return nil, err
252 }
253 }
254 if err := writeStanza(conn, "done"); err != nil {
255 return nil, err
256 }
257
258 // Phase 2: plugin responds with various commands and a file key
259 sr := format.NewStanzaReader(bufio.NewReader(conn))
260 ReadLoop:
261 for {
262 s, err := i.ui.readStanza(i.name, sr)
263 if err != nil {
264 return nil, err
265 }
266
267 switch s.Type {
268 case "file-key":
269 if len(s.Args) != 1 {
270 return nil, fmt.Errorf("malformed file-key stanza: unexpected arguments count")
271 }
272 n, err := strconv.Atoi(s.Args[0])
273 if err != nil {
274 return nil, fmt.Errorf("malformed file-key stanza: invalid index")
275 }
276 // We only send a single file key, so the index must be 0.
277 if n != 0 {
278 return nil, fmt.Errorf("malformed file-key stanza: unexpected index")
279 }
280 if fileKey != nil {
281 return nil, fmt.Errorf("received duplicated file-key stanza")
282 }
283
284 fileKey = s.Body
285
286 if err := writeStanza(conn, "ok"); err != nil {
287 return nil, err
288 }
289 case "error":
290 if err := writeStanza(conn, "ok"); err != nil {
291 return nil, err
292 }
293
294 return nil, fmt.Errorf("%s", s.Body)
295 case "done":
296 break ReadLoop
297 default:
298 if ok, err := i.ui.handle(i.name, conn, s); err != nil {
299 return nil, err
300 } else if !ok {
301 if err := writeStanza(conn, "unsupported"); err != nil {
302 return nil, err
303 }
304 }
305 }
306 }
307
308 if fileKey == nil {
309 return nil, age.ErrIncorrectIdentity
310 }
311 return fileKey, nil
312 }
313
314 // ClientUI holds callbacks that will be invoked by (Un)Wrap if the plugin
315 // wishes to interact with the user. If any of them is nil or returns an error,
316 // failure will be reported to the plugin, but note that the error is otherwise
317 // discarded. Implementations are encouraged to display errors to the user
318 // before returning them.
319 type ClientUI struct {
320 // DisplayMessage displays the message, which is expected to have lowercase
321 // initials and no final period.
322 DisplayMessage func(name, message string) error
323
324 // RequestValue requests a secret or public input, with the provided prompt.
325 RequestValue func(name, prompt string, secret bool) (string, error)
326
327 // Confirm requests a confirmation with the provided prompt. The yes and no
328 // value are the choices provided to the user. no may be empty. The return
329 // value indicates whether the user selected the yes or no option.
330 Confirm func(name, prompt, yes, no string) (choseYes bool, err error)
331
332 // WaitTimer is invoked once (Un)Wrap has been waiting for 5 seconds on the
333 // plugin, for example because the plugin is waiting for an external event
334 // (e.g. a hardware token touch). Unlike the other callbacks, WaitTimer runs
335 // in a separate goroutine, and if missing it's simply ignored.
336 WaitTimer func(name string)
337 }
338
339 func (c *ClientUI) handle(name string, conn *clientConnection, s *format.Stanza) (ok bool, err error) {
340 switch s.Type {
341 case "msg":
342 if c.DisplayMessage == nil {
343 return true, writeStanza(conn, "fail")
344 }
345 if err := c.DisplayMessage(name, string(s.Body)); err != nil {
346 return true, writeStanza(conn, "fail")
347 }
348 return true, writeStanza(conn, "ok")
349 case "request-secret", "request-public":
350 if c.RequestValue == nil {
351 return true, writeStanza(conn, "fail")
352 }
353 secret, err := c.RequestValue(name, string(s.Body), s.Type == "request-secret")
354 if err != nil {
355 return true, writeStanza(conn, "fail")
356 }
357 return true, writeStanzaWithBody(conn, "ok", []byte(secret))
358 case "confirm":
359 if len(s.Args) != 1 && len(s.Args) != 2 {
360 return true, fmt.Errorf("malformed confirm stanza: unexpected number of arguments")
361 }
362 if c.Confirm == nil {
363 return true, writeStanza(conn, "fail")
364 }
365 yes, err := format.DecodeString(s.Args[0])
366 if err != nil {
367 return true, fmt.Errorf("malformed confirm stanza: invalid YES option encoding")
368 }
369 var no []byte
370 if len(s.Args) == 2 {
371 no, err = format.DecodeString(s.Args[1])
372 if err != nil {
373 return true, fmt.Errorf("malformed confirm stanza: invalid NO option encoding")
374 }
375 }
376 choseYes, err := c.Confirm(name, string(s.Body), string(yes), string(no))
377 if err != nil {
378 return true, writeStanza(conn, "fail")
379 }
380 result := "yes"
381 if !choseYes {
382 result = "no"
383 }
384 return true, writeStanza(conn, "ok", result)
385 default:
386 return false, nil
387 }
388 }
389
390 // readStanza calls r.ReadStanza and, if set, invokes WaitTimer in a separate
391 // goroutine if the call takes longer than 5 seconds.
392 func (c *ClientUI) readStanza(name string, r *format.StanzaReader) (*format.Stanza, error) {
393 if c.WaitTimer != nil {
394 defer time.AfterFunc(5*time.Second, func() { c.WaitTimer(name) }).Stop()
395 }
396 return r.ReadStanza()
397 }
398
399 type clientConnection struct {
400 cmd *exec.Cmd
401 io.Reader // stdout
402 io.Writer // stdin
403 close func()
404 }
405
406 // NotFoundError is returned by [Recipient.Wrap] and [Identity.Unwrap] when the
407 // plugin binary cannot be found.
408 type NotFoundError struct {
409 // Name is the plugin (not binary) name.
410 Name string
411 // Err is the underlying error, usually an [exec.Error] wrapping
412 // [exec.ErrNotFound].
413 Err error
414 }
415
416 func (e *NotFoundError) Error() string {
417 return fmt.Sprintf("%q plugin not found: %v", e.Name, e.Err)
418 }
419
420 func (e *NotFoundError) Unwrap() error {
421 return e.Err
422 }
423
424 var testOnlyPluginPath string
425
426 func openClientConnection(name, protocol string) (*clientConnection, error) {
427 path := "age-plugin-" + name
428 if testOnlyPluginPath != "" {
429 path = filepath.Join(testOnlyPluginPath, path)
430 } else if strings.ContainsRune(name, os.PathSeparator) {
431 return nil, fmt.Errorf("invalid plugin name: %q", name)
432 }
433 cmd := exec.Command(path, "--age-plugin="+protocol)
434
435 stdout, err := cmd.StdoutPipe()
436 if err != nil {
437 return nil, err
438 }
439 stdin, err := cmd.StdinPipe()
440 if err != nil {
441 return nil, err
442 }
443
444 cc := &clientConnection{
445 cmd: cmd,
446 Reader: stdout,
447 Writer: stdin,
448 close: func() {
449 stdin.Close()
450 stdout.Close()
451 },
452 }
453
454 if os.Getenv("AGEDEBUG") == "plugin" {
455 cc.Reader = io.TeeReader(cc.Reader, os.Stderr)
456 cc.Writer = io.MultiWriter(cc.Writer, os.Stderr)
457 cmd.Stderr = os.Stderr
458 }
459
460 // Avoid running plugins in the client's working directory, as it might
461 // differ between clients.
462 cmd.Dir = os.TempDir()
463
464 if err := cmd.Start(); err != nil {
465 if errors.Is(err, exec.ErrNotFound) {
466 return nil, &NotFoundError{Name: name, Err: err}
467 }
468 return nil, err
469 }
470
471 return cc, nil
472 }
473
474 func (cc *clientConnection) Close() error {
475 // Close stdin and stdout and send SIGINT (if supported) to the plugin,
476 // then wait for it to cleanup and exit.
477 cc.close()
478 cc.cmd.Process.Signal(os.Interrupt)
479 return cc.cmd.Wait()
480 }
481
482 func writeStanza(conn io.Writer, t string, args ...string) error {
483 s := &format.Stanza{Type: t, Args: args}
484 return s.Marshal(conn)
485 }
486
487 func writeStanzaWithBody(conn io.Writer, t string, body []byte) error {
488 s := &format.Stanza{Type: t, Body: body}
489 return s.Marshal(conn)
490 }
491
492 func writeGrease(conn io.Writer) (sent bool, err error) {
493 if mathrand.IntN(3) == 0 {
494 return false, nil
495 }
496 s := &format.Stanza{Type: fmt.Sprintf("grease-%x", mathrand.Int())}
497 for i := 0; i < mathrand.IntN(3); i++ {
498 s.Args = append(s.Args, fmt.Sprintf("%d", mathrand.IntN(100)))
499 }
500 if mathrand.IntN(2) == 0 {
501 s.Body = make([]byte, mathrand.IntN(100))
502 rand.Read(s.Body)
503 }
504 return true, s.Marshal(conn)
505 }