protocol.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. // Package localapi serves the nebula command registry over a local IPC endpoint so the
  2. // user who ran nebula can inspect and control it from a CLI on the same machine.
  3. //
  4. // Access is restricted by the filesystem (a 0600 socket) and by a peer credential check
  5. // on every connection. Which commands are served is decided by the caller that builds
  6. // the Server, and the filtering happens here, on the serving side, rather than in the
  7. // client.
  8. //
  9. // # Protocol
  10. //
  11. // One JSON object in, one JSON object out, both newline terminated. It is an API, not a
  12. // command line: a request names a command and passes its options as named parameters,
  13. // rather than shipping an argv the daemon has to parse. A client that is itself a CLI
  14. // asks for the schema first (Request.Describe) and turns the user's flags into those
  15. // parameters; a client that is not need never think in flags at all.
  16. package localapi
  17. import (
  18. "bufio"
  19. "bytes"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io"
  24. )
  25. // ProtocolVersion is the version of the request and response envelopes. A client sending
  26. // a version this server does not know gets a sentence back rather than a parse error,
  27. // which matters because the daemon and the CLI are upgraded independently.
  28. const ProtocolVersion = 1
  29. // MaxRequestBytes bounds the request. A request names a command and its parameters, so it
  30. // has no business being large, and an unbounded read is a way for a local process to
  31. // consume memory the packet path needs.
  32. const MaxRequestBytes = 64 * 1024
  33. // Request is the single JSON object a client sends.
  34. type Request struct {
  35. Version int `json:"version"`
  36. // Describe asks for the schema of every command this surface serves, in place of
  37. // running one. Command, Params and Args are ignored.
  38. Describe bool `json:"describe,omitempty"`
  39. // Command names the command to run.
  40. Command string `json:"command,omitempty"`
  41. // Params carries the command's options by name, with JSON's own types, true rather
  42. // than "true", 3 rather than "3", or as the strings a command line parsed them from,
  43. // which is what nebula ctl sends. Unknown names are an error, so a typo is reported
  44. // instead of ignored. The schema lists json and pretty on every command because the
  45. // command lines take them; here they are refused, since Format is how a request
  46. // chooses its rendering.
  47. Params map[string]any `json:"params,omitempty"`
  48. // Args carries the command's operands, the values that are not options: the vpn
  49. // address `print-tunnel` prints, for instance. They stay positional because the
  50. // commands do not name them.
  51. Args []string `json:"args,omitempty"`
  52. // Format asks for a rendering other than the default. "" and "json" return the
  53. // command's result as a JSON value, which is what a program wants. "text" asks the
  54. // daemon to run the command's own human rendering and return it as a string, which is
  55. // how `nebula ctl` shows an operator the same output the ssh server would.
  56. Format string `json:"format,omitempty"`
  57. }
  58. // Response is the single JSON object a server sends back.
  59. type Response struct {
  60. Version int `json:"version"`
  61. // Result is what the request produced: the command's output, or the schema when the
  62. // request was a Describe. It is a JSON value when the command emitted JSON, so a
  63. // caller reads it directly instead of parsing a string that happens to contain JSON,
  64. // and a JSON string otherwise.
  65. //
  66. // Whitespace inside a JSON result is not preserved: an envelope normalises it, and
  67. // in an API it carries no meaning anyway. Formatting a result for a human to read is
  68. // the client's job, which is what Pretty is for.
  69. Result json.RawMessage `json:"result,omitempty"`
  70. // Error explains a failure in a sentence, and is absent on success. It is the only
  71. // signal a caller needs: there is no separate status field, because a command that
  72. // failed always says why and one that succeeded never does. A command line client
  73. // turns its presence into a non-zero exit.
  74. //
  75. // A command that ran and refused sets Error too, alongside its Result when the
  76. // caller asked for JSON. That is how a refusal and a request that never ran are
  77. // told apart: the first has both, the second has Error alone.
  78. Error string `json:"error,omitempty"`
  79. }
  80. // readFrame reads one frame, a newline terminated JSON object, from r into v. With
  81. // writeFrame it is where the framing rule lives, for both directions: a frame is a
  82. // single line, a line over max bytes is refused rather than buffered, and a final line
  83. // with no newline before EOF still counts. what names the frame in errors ("request", "response"); a
  84. // read failure is returned wrapped, so a caller can still see io.EOF or a timeout in it.
  85. func readFrame(r io.Reader, max int, what string, v any) error {
  86. br := bufio.NewReader(io.LimitReader(r, int64(max)+1))
  87. line, err := br.ReadBytes('\n')
  88. if err != nil && (len(line) == 0 || !errors.Is(err, io.EOF)) {
  89. // EOF after a partial line is the unterminated final line the rule allows, and
  90. // an oversized line looks the same once the LimitReader cuts it off, so both go
  91. // on to be judged by their length. Anything else is a failed read, whatever was
  92. // buffered first: a deadline that lands mid frame is a timeout, not a parse
  93. // error in half a document.
  94. return fmt.Errorf("could not read %s: %w", what, err)
  95. }
  96. // The limit is on the body, not the frame, so the terminator does not count
  97. // against it. A body that exceeds max is cut off by the LimitReader before its
  98. // newline, so a missing terminator is also what an oversized line looks like.
  99. body := bytes.TrimSuffix(line, []byte{'\n'})
  100. if len(body) > max {
  101. return fmt.Errorf("%s exceeded %d bytes", what, max)
  102. }
  103. if err := json.Unmarshal(body, v); err != nil {
  104. return fmt.Errorf("could not parse %s: %w", what, err)
  105. }
  106. return nil
  107. }
  108. // writeFrame writes v to w as one frame: the JSON object and the newline that ends it.
  109. func writeFrame(w io.Writer, v any) error {
  110. body, err := json.Marshal(v)
  111. if err != nil {
  112. return fmt.Errorf("could not encode frame: %w", err)
  113. }
  114. _, err = w.Write(append(body, '\n'))
  115. return err
  116. }