protocol.go 6.9 KB

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