Debian Codegraph @

plugin/plugin.go

raw symbols SCIP
1 // Package plugin implements the age plugin protocol.
2 //
3 // [Recipient] and [Identity] are plugin clients, that execute plugin binaries to
4 // perform encryption and decryption operations.
5 //
6 // [Plugin] is a framework for writing age plugins, that exposes an [age.Recipient]
7 // and/or [age.Identity] implementation as a plugin binary.
8 package plugin
9
10 import (
11 "bufio"
12 "errors"
13 "flag"
14 "fmt"
15 "io"
16 "os"
17 "slices"
18 "strconv"
19 "strings"
20
21 "filippo.io/age"
22 "filippo.io/age/internal/format"
23 )
24
25 // TODO: add plugin test framework.
26
27 // Plugin is a framework for writing age plugins. It allows exposing regular
28 // [age.Recipient] and [age.Identity] implementations as plugins, and handles
29 // all the protocol details.
30 type Plugin struct {
31 name string
32 fs *flag.FlagSet
33 sm *string
34
35 recipient func([]byte) (age.Recipient, error)
36 idAsRecipient func([]byte) (age.Recipient, error)
37 identity func([]byte) (age.Identity, error)
38
39 stdin io.Reader
40 stdout, stderr io.Writer
41
42 sr *format.StanzaReader
43 // broken is set if the protocol broke down during an interaction function
44 // called by a Recipient or Identity.
45 broken bool
46 }
47
48 // New creates a new Plugin with the given case-insensitive name.
49 //
50 // For example, a plugin named "frood" would be invoked as "age-plugin-frood".
51 func New(name string) (*Plugin, error) {
52 if !validPluginName(name) {
53 return nil, fmt.Errorf("invalid plugin name: %q", name)
54 }
55 return &Plugin{name: strings.ToLower(name), stdin: os.Stdin,
56 stdout: os.Stdout, stderr: os.Stderr}, nil
57 }
58
59 // Name returns the name of the plugin.
60 func (p *Plugin) Name() string {
61 return p.name
62 }
63
64 // RegisterFlags registers the plugin's flags with the given [flag.FlagSet], or
65 // with the default [flag.CommandLine] if fs is nil. It must be called before
66 // [flag.Parse] and [Plugin.Main].
67 //
68 // This allows the plugin to expose additional flags when invoked manually, for
69 // example to implement a keygen mode.
70 func (p *Plugin) RegisterFlags(fs *flag.FlagSet) {
71 if fs == nil {
72 fs = flag.CommandLine
73 }
74 p.fs = fs
75 p.sm = fs.String("age-plugin", "", "age-plugin state machine")
76 }
77
78 // HandleRecipient registers a function to parse recipients of the form
79 // age1name1... into [age.Recipient] values. data is the decoded Bech32 payload.
80 //
81 // If the returned Recipient implements [age.RecipientWithLabels], Plugin will
82 // use it and enforce consistency across every returned stanza in an execution.
83 // If the client supports labels, they will be passed through the protocol.
84 //
85 // It must be called before [Plugin.Main], and can be called at most once.
86 // Otherwise, it panics.
87 func (p *Plugin) HandleRecipient(f func(data []byte) (age.Recipient, error)) {
88 if p.recipient != nil {
89 panic("HandleRecipient called twice")
90 }
91 p.recipient = f
92 }
93
94 // HandleIdentityAsRecipient registers a function to parse identities of the
95 // form AGE-PLUGIN-NAME-1... into [age.Recipient] values, for when identities
96 // are used as recipients. data is the decoded Bech32 payload.
97 //
98 // If the returned Recipient implements [age.RecipientWithLabels], Plugin will
99 // use it and enforce consistency across every returned stanza in an execution.
100 // If the client supports labels, they will be passed through the protocol.
101 //
102 // It must be called before [Plugin.Main], and can be called at most once.
103 // Otherwise, it panics.
104 func (p *Plugin) HandleIdentityAsRecipient(f func(data []byte) (age.Recipient, error)) {
105 if p.idAsRecipient != nil {
106 panic("HandleIdentityAsRecipient called twice")
107 }
108 p.idAsRecipient = f
109 }
110
111 // HandleIdentity registers a function to parse identities of the form
112 // AGE-PLUGIN-NAME-1... into [age.Identity] values. data is the decoded Bech32
113 // payload.
114 //
115 // It must be called before [Plugin.Main], and can be called at most once.
116 // Otherwise, it panics.
117 func (p *Plugin) HandleIdentity(f func(data []byte) (age.Identity, error)) {
118 if p.identity != nil {
119 panic("HandleIdentity called twice")
120 }
121 p.identity = f
122 }
123
124 // HandleRecipientEncoding is like [Plugin.HandleRecipient] but provides the
125 // full recipient encoding string to the callback.
126 //
127 // It allows using functions like ParseRecipient directly.
128 func (p *Plugin) HandleRecipientEncoding(f func(recipient string) (age.Recipient, error)) {
129 p.HandleRecipient(func(data []byte) (age.Recipient, error) {
130 return f(EncodeRecipient(p.name, data))
131 })
132 }
133
134 // HandleIdentityEncodingAsRecipient is like [Plugin.HandleIdentityAsRecipient] but
135 // provides the full identity encoding string to the callback.
136 func (p *Plugin) HandleIdentityEncodingAsRecipient(f func(identity string) (age.Recipient, error)) {
137 p.HandleIdentityAsRecipient(func(data []byte) (age.Recipient, error) {
138 return f(EncodeIdentity(p.name, data))
139 })
140 }
141
142 // HandleIdentityEncoding is like [Plugin.HandleIdentity] but provides the
143 // full identity encoding string to the callback.
144 //
145 // It allows using functions like ParseIdentity directly.
146 func (p *Plugin) HandleIdentityEncoding(f func(identity string) (age.Identity, error)) {
147 p.HandleIdentity(func(data []byte) (age.Identity, error) {
148 return f(EncodeIdentity(p.name, data))
149 })
150 }
151
152 // Main runs the plugin protocol. It returns an exit code to pass to os.Exit.
153 //
154 // It automatically calls [Plugin.RegisterFlags] and [flag.Parse] if they were
155 // not called before.
156 func (p *Plugin) Main() int {
157 if p.fs == nil {
158 p.RegisterFlags(nil)
159 }
160 if !p.fs.Parsed() {
161 p.fs.Parse(os.Args[1:])
162 }
163 if *p.sm == "recipient-v1" {
164 return p.RecipientV1()
165 }
166 if *p.sm == "identity-v1" {
167 return p.IdentityV1()
168 }
169 fmt.Fprintf(p.stderr, "unknown state machine %q", *p.sm)
170 return 4
171 }
172
173 // SetIO sets the plugin's input and output streams, which default to
174 // stdin/stdout/stderr.
175 //
176 // It must be called before [Plugin.Main].
177 func (p *Plugin) SetIO(stdin io.Reader, stdout, stderr io.Writer) {
178 p.stdin = stdin
179 p.stdout = stdout
180 p.stderr = stderr
181 }
182
183 // RecipientV1 implements the recipient-v1 state machine. It returns an exit
184 // code to pass to os.Exit.
185 //
186 // Most plugins should call [Plugin.Main] instead of this method.
187 func (p *Plugin) RecipientV1() int {
188 if p.recipient == nil && p.idAsRecipient == nil {
189 return p.fatalf("recipient-v1 not supported")
190 }
191
192 var recipientStrings, identityStrings []string
193 var fileKeys [][]byte
194 var supportsLabels bool
195
196 p.sr = format.NewStanzaReader(bufio.NewReader(p.stdin))
197 ReadLoop:
198 for {
199 s, err := p.sr.ReadStanza()
200 if err != nil {
201 return p.fatalf("failed to read stanza: %v", err)
202 }
203
204 switch s.Type {
205 case "add-recipient":
206 if err := expectStanzaWithNoBody(s, 1); err != nil {
207 return p.fatalf("%v", err)
208 }
209 recipientStrings = append(recipientStrings, s.Args[0])
210 case "add-identity":
211 if err := expectStanzaWithNoBody(s, 1); err != nil {
212 return p.fatalf("%v", err)
213 }
214 identityStrings = append(identityStrings, s.Args[0])
215 case "extension-labels":
216 if err := expectStanzaWithNoBody(s, 0); err != nil {
217 return p.fatalf("%v", err)
218 }
219 supportsLabels = true
220 case "wrap-file-key":
221 if err := expectStanzaWithBody(s, 0); err != nil {
222 return p.fatalf("%v", err)
223 }
224 fileKeys = append(fileKeys, s.Body)
225 case "done":
226 if err := expectStanzaWithNoBody(s, 0); err != nil {
227 return p.fatalf("%v", err)
228 }
229 break ReadLoop
230 default:
231 // Unsupported stanzas in uni-directional phases are ignored.
232 }
233 }
234
235 if len(recipientStrings)+len(identityStrings) == 0 {
236 return p.fatalf("no recipients or identities provided")
237 }
238 if len(fileKeys) == 0 {
239 return p.fatalf("no file keys provided")
240 }
241
242 var recipients, identities []age.Recipient
243 for i, s := range recipientStrings {
244 name, data, err := ParseRecipient(s)
245 if err != nil {
246 return p.recipientError(i, err)
247 }
248 if name != p.name {
249 return p.recipientError(i, fmt.Errorf("unsupported plugin name: %q", name))
250 }
251 if p.recipient == nil {
252 return p.recipientError(i, fmt.Errorf("recipient encodings not supported"))
253 }
254 r, err := p.recipient(data)
255 if err != nil {
256 return p.recipientError(i, err)
257 }
258 recipients = append(recipients, r)
259 }
260 for i, s := range identityStrings {
261 name, data, err := ParseIdentity(s)
262 if err != nil {
263 return p.identityError(i, err)
264 }
265 if name != p.name {
266 return p.identityError(i, fmt.Errorf("unsupported plugin name: %q", name))
267 }
268 if p.idAsRecipient == nil {
269 return p.identityError(i, fmt.Errorf("identity encodings not supported"))
270 }
271 r, err := p.idAsRecipient(data)
272 if err != nil {
273 return p.identityError(i, err)
274 }
275 identities = append(identities, r)
276 }
277
278 // Technically labels should be per-file key, but the client-side protocol
279 // extension shipped like this, and it doesn't feel worth making a v2.
280 var labels []string
281
282 stanzas := make([][]*age.Stanza, len(fileKeys))
283 for i, fk := range fileKeys {
284 for j, r := range recipients {
285 ss, ll, err := wrapWithLabels(r, fk)
286 if p.broken {
287 return 2
288 } else if err != nil {
289 return p.recipientError(j, err)
290 }
291 if i == 0 && j == 0 {
292 labels = ll
293 } else if err := checkLabels(ll, labels); err != nil {
294 return p.recipientError(j, err)
295 }
296 stanzas[i] = append(stanzas[i], ss...)
297 }
298 for j, r := range identities {
299 ss, ll, err := wrapWithLabels(r, fk)
300 if p.broken {
301 return 2
302 } else if err != nil {
303 return p.identityError(j, err)
304 }
305 if i == 0 && j == 0 && len(recipients) == 0 {
306 labels = ll
307 } else if err := checkLabels(ll, labels); err != nil {
308 return p.identityError(j, err)
309 }
310 stanzas[i] = append(stanzas[i], ss...)
311 }
312 }
313
314 if sent, err := writeGrease(p.stdout); err != nil {
315 return p.fatalf("failed to write grease: %v", err)
316 } else if sent {
317 if err := expectUnsupported(p.sr); err != nil {
318 return p.fatalf("%v", err)
319 }
320 }
321
322 if supportsLabels {
323 if err := writeStanza(p.stdout, "labels", labels...); err != nil {
324 return p.fatalf("failed to write labels stanza: %v", err)
325 }
326 if err := expectOk(p.sr); err != nil {
327 return p.fatalf("%v", err)
328 }
329 }
330
331 for i, ss := range stanzas {
332 for _, s := range ss {
333 if err := (&format.Stanza{Type: "recipient-stanza",
334 Args: append([]string{fmt.Sprint(i), s.Type}, s.Args...),
335 Body: s.Body}).Marshal(p.stdout); err != nil {
336 return p.fatalf("failed to write recipient-stanza: %v", err)
337 }
338 if err := expectOk(p.sr); err != nil {
339 return p.fatalf("%v", err)
340 }
341 }
342 if sent, err := writeGrease(p.stdout); err != nil {
343 return p.fatalf("failed to write grease: %v", err)
344 } else if sent {
345 if err := expectUnsupported(p.sr); err != nil {
346 return p.fatalf("%v", err)
347 }
348 }
349 }
350
351 if err := writeStanza(p.stdout, "done"); err != nil {
352 return p.fatalf("failed to write done stanza: %v", err)
353 }
354 return 0
355 }
356
357 func wrapWithLabels(r age.Recipient, fileKey []byte) ([]*age.Stanza, []string, error) {
358 if r, ok := r.(age.RecipientWithLabels); ok {
359 return r.WrapWithLabels(fileKey)
360 }
361 s, err := r.Wrap(fileKey)
362 return s, nil, err
363 }
364
365 func checkLabels(ll, labels []string) error {
366 if !slices.Equal(ll, labels) {
367 return fmt.Errorf("labels %q do not match previous recipients %q", ll, labels)
368 }
369 return nil
370 }
371
372 // IdentityV1 implements the identity-v1 state machine. It returns an exit code
373 // to pass to os.Exit.
374 //
375 // Most plugins should call [Plugin.Main] instead of this method.
376 func (p *Plugin) IdentityV1() int {
377 if p.identity == nil {
378 return p.fatalf("identity-v1 not supported")
379 }
380
381 var files [][]*age.Stanza
382 var identityStrings []string
383
384 p.sr = format.NewStanzaReader(bufio.NewReader(p.stdin))
385 ReadLoop:
386 for {
387 s, err := p.sr.ReadStanza()
388 if err != nil {
389 return p.fatalf("failed to read stanza: %v", err)
390 }
391
392 switch s.Type {
393 case "add-identity":
394 if err := expectStanzaWithNoBody(s, 1); err != nil {
395 return p.fatalf("%v", err)
396 }
397 identityStrings = append(identityStrings, s.Args[0])
398 case "recipient-stanza":
399 if len(s.Args) < 2 {
400 return p.fatalf("recipient-stanza stanza has %d arguments, want >=2", len(s.Args))
401 }
402 i, err := strconv.Atoi(s.Args[0])
403 if err != nil {
404 return p.fatalf("failed to parse recipient-stanza stanza argument: %v", err)
405 }
406 if i < 0 {
407 return p.fatalf("unexpected file index %d, previous was %d", i, len(files)-1)
408 }
409 ss := &age.Stanza{Type: s.Args[1], Args: s.Args[2:], Body: s.Body}
410 switch i {
411 case len(files):
412 files = append(files, []*age.Stanza{ss})
413 case len(files) - 1:
414 files[len(files)-1] = append(files[len(files)-1], ss)
415 default:
416 return p.fatalf("unexpected file index %d, previous was %d", i, len(files)-1)
417 }
418 case "done":
419 if err := expectStanzaWithNoBody(s, 0); err != nil {
420 return p.fatalf("%v", err)
421 }
422 break ReadLoop
423 default:
424 // Unsupported stanzas in uni-directional phases are ignored.
425 }
426 }
427
428 if len(identityStrings) == 0 {
429 return p.fatalf("no identities provided")
430 }
431 if len(files) == 0 {
432 return p.fatalf("no stanzas provided")
433 }
434
435 var identities []age.Identity
436 for i, s := range identityStrings {
437 name, data, err := ParseIdentity(s)
438 if err != nil {
439 return p.identityError(i, err)
440 }
441 if name != p.name {
442 return p.identityError(i, fmt.Errorf("unsupported plugin name: %q", name))
443 }
444 if p.identity == nil {
445 return p.identityError(i, fmt.Errorf("identity encodings not supported"))
446 }
447 r, err := p.identity(data)
448 if err != nil {
449 return p.identityError(i, err)
450 }
451 identities = append(identities, r)
452 }
453
454 for i, ss := range files {
455 if sent, err := writeGrease(p.stdout); err != nil {
456 return p.fatalf("failed to write grease: %v", err)
457 } else if sent {
458 if err := expectUnsupported(p.sr); err != nil {
459 return p.fatalf("%v", err)
460 }
461 }
462
463 // TODO: there should be a mechanism to let the plugin decide the order
464 // in which identities are tried.
465 for _, id := range identities {
466 fk, err := id.Unwrap(ss)
467 if p.broken {
468 return 2
469 } else if errors.Is(err, age.ErrIncorrectIdentity) {
470 continue
471 } else if err != nil {
472 if err := p.writeError([]string{"stanza", fmt.Sprint(i), "0"}, err); err != nil {
473 return p.fatalf("%v", err)
474 }
475 // Note that we don't exit here, as the protocol allows
476 // continuing with other files.
477 break
478 }
479
480 s := &format.Stanza{Type: "file-key", Args: []string{fmt.Sprint(i)}, Body: fk}
481 if err := s.Marshal(p.stdout); err != nil {
482 return p.fatalf("failed to write file-key: %v", err)
483 }
484 if err := expectOk(p.sr); err != nil {
485 return p.fatalf("%v", err)
486 }
487 break
488 }
489 }
490
491 if err := writeStanza(p.stdout, "done"); err != nil {
492 return p.fatalf("failed to write done stanza: %v", err)
493 }
494 return 0
495 }
496
497 // DisplayMessage requests that the client display a message to the user. The
498 // message should start with a lowercase letter and have no final period.
499 // DisplayMessage returns an error if the client can't display the message, and
500 // may return before the message has been displayed to the user.
501 //
502 // It must only be called by a Wrap or Unwrap method invoked by [Plugin.Main].
503 func (p *Plugin) DisplayMessage(message string) error {
504 if err := writeStanzaWithBody(p.stdout, "msg", []byte(message)); err != nil {
505 return p.fatalInteractf("failed to write msg stanza: %v", err)
506 }
507 s, err := readOkOrFail(p.sr)
508 if err != nil {
509 return p.fatalInteractf("%v", err)
510 }
511 if s.Type == "fail" {
512 return fmt.Errorf("client failed to display message")
513 }
514 if err := expectStanzaWithNoBody(s, 0); err != nil {
515 return p.fatalInteractf("%v", err)
516 }
517 return nil
518 }
519
520 // RequestValue requests a secret or public input from the user through the
521 // client, with the provided prompt. It returns an error if the client can't
522 // request the input or if the user dismisses the prompt.
523 //
524 // It must only be called by a Wrap or Unwrap method invoked by [Plugin.Main].
525 func (p *Plugin) RequestValue(prompt string, secret bool) (string, error) {
526 t := "request-public"
527 if secret {
528 t = "request-secret"
529 }
530 if err := writeStanzaWithBody(p.stdout, t, []byte(prompt)); err != nil {
531 return "", p.fatalInteractf("failed to write stanza: %v", err)
532 }
533 s, err := readOkOrFail(p.sr)
534 if err != nil {
535 return "", p.fatalInteractf("%v", err)
536 }
537 if s.Type == "fail" {
538 return "", fmt.Errorf("client failed to request value")
539 }
540 if err := expectStanzaWithAnyBody(s, 0); err != nil {
541 return "", p.fatalInteractf("%v", err)
542 }
543 return string(s.Body), nil
544 }
545
546 // Confirm requests a confirmation from the user through the client, with the
547 // provided prompt. The yes and no value are the choices provided to the user.
548 // no may be empty. The return value choseYes indicates whether the user
549 // selected the yes or no option. Confirm returns an error if the client can't
550 // request the confirmation.
551 //
552 // It must only be called by a Wrap or Unwrap method invoked by [Plugin.Main].
553 func (p *Plugin) Confirm(prompt, yes, no string) (choseYes bool, err error) {
554 args := []string{format.EncodeToString([]byte(yes))}
555 if no != "" {
556 args = append(args, format.EncodeToString([]byte(no)))
557 }
558 s := &format.Stanza{Type: "confirm", Args: args, Body: []byte(prompt)}
559 if err := s.Marshal(p.stdout); err != nil {
560 return false, p.fatalInteractf("failed to write confirm stanza: %v", err)
561 }
562 s, err = readOkOrFail(p.sr)
563 if err != nil {
564 return false, p.fatalInteractf("%v", err)
565 }
566 if s.Type == "fail" {
567 return false, fmt.Errorf("client failed to request confirmation")
568 }
569 if err := expectStanzaWithNoBody(s, 1); err != nil {
570 return false, p.fatalInteractf("%v", err)
571 }
572 return s.Args[0] == "yes", nil
573 }
574
575 // fatalInteractf prints the error to stderr and sets the broken flag, so the
576 // Wrap/Unwrap caller can exit with an error.
577 func (p *Plugin) fatalInteractf(format string, args ...any) error {
578 p.broken = true
579 fmt.Fprintf(p.stderr, format, args...)
580 return fmt.Errorf(format, args...)
581 }
582
583 func (p *Plugin) fatalf(format string, args ...any) int {
584 fmt.Fprintf(p.stderr, format, args...)
585 return 1
586 }
587
588 func expectStanzaWithNoBody(s *format.Stanza, wantArgs int) error {
589 if len(s.Args) != wantArgs {
590 return fmt.Errorf("%s stanza has %d arguments, want %d", s.Type, len(s.Args), wantArgs)
591 }
592 if len(s.Body) != 0 {
593 return fmt.Errorf("%s stanza has %d bytes of body, want 0", s.Type, len(s.Body))
594 }
595 return nil
596 }
597
598 func expectStanzaWithBody(s *format.Stanza, wantArgs int) error {
599 if err := expectStanzaWithAnyBody(s, wantArgs); err != nil {
600 return err
601 }
602 if len(s.Body) == 0 {
603 return fmt.Errorf("%s stanza has 0 bytes of body, want >0", s.Type)
604 }
605 return nil
606 }
607
608 func expectStanzaWithAnyBody(s *format.Stanza, wantArgs int) error {
609 if len(s.Args) != wantArgs {
610 return fmt.Errorf("%s stanza has %d arguments, want %d", s.Type, len(s.Args), wantArgs)
611 }
612 return nil
613 }
614
615 func (p *Plugin) recipientError(idx int, err error) int {
616 if err := p.writeError([]string{"recipient", fmt.Sprint(idx)}, err); err != nil {
617 return p.fatalf("%v", err)
618 }
619 return 3
620 }
621
622 func (p *Plugin) identityError(idx int, err error) int {
623 if err := p.writeError([]string{"identity", fmt.Sprint(idx)}, err); err != nil {
624 return p.fatalf("%v", err)
625 }
626 return 3
627 }
628
629 func expectOk(sr *format.StanzaReader) error {
630 ok, err := sr.ReadStanza()
631 if err != nil {
632 return fmt.Errorf("failed to read OK stanza: %v", err)
633 }
634 if ok.Type != "ok" {
635 return fmt.Errorf("expected OK stanza, got %q", ok.Type)
636 }
637 return expectStanzaWithNoBody(ok, 0)
638 }
639
640 func readOkOrFail(sr *format.StanzaReader) (*format.Stanza, error) {
641 s, err := sr.ReadStanza()
642 if err != nil {
643 return nil, fmt.Errorf("failed to read response stanza: %v", err)
644 }
645 switch s.Type {
646 case "fail":
647 if err := expectStanzaWithNoBody(s, 0); err != nil {
648 return nil, fmt.Errorf("%v", err)
649 }
650 return s, nil
651 case "ok":
652 return s, nil
653 default:
654 return nil, fmt.Errorf("expected ok or fail stanza, got %q", s.Type)
655 }
656 }
657
658 func expectUnsupported(sr *format.StanzaReader) error {
659 unsupported, err := sr.ReadStanza()
660 if err != nil {
661 return fmt.Errorf("failed to read unsupported stanza: %v", err)
662 }
663 if unsupported.Type != "unsupported" {
664 return fmt.Errorf("expected unsupported stanza, got %q", unsupported.Type)
665 }
666 return expectStanzaWithNoBody(unsupported, 0)
667 }
668
669 func (p *Plugin) writeError(args []string, err error) error {
670 s := &format.Stanza{Type: "error", Args: args}
671 s.Body = []byte(err.Error())
672 if err := s.Marshal(p.stdout); err != nil {
673 return fmt.Errorf("failed to write error stanza: %v", err)
674 }
675 if err := expectOk(p.sr); err != nil {
676 return fmt.Errorf("%v", err)
677 }
678 return nil
679 }