server_matrix.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "heckel.io/ntfy/log"
  7. "heckel.io/ntfy/util"
  8. "io"
  9. "net/http"
  10. "strings"
  11. )
  12. // Matrix Push Gateway / UnifiedPush / ntfy integration:
  13. //
  14. // ntfy implements a Matrix Push Gateway (as defined in https://spec.matrix.org/v1.2/push-gateway-api/),
  15. // in combination with UnifiedPush as the Provider Push Protocol (as defined in https://unifiedpush.org/developers/gateway/).
  16. //
  17. // In the picture below, ntfy is the Push Gateway (mostly in this file), as well as the Push Provider (ntfy's
  18. // main functionality). UnifiedPush is the Provider Push Protocol, as implemented by the ntfy server and the
  19. // ntfy Android app.
  20. //
  21. // +--------------------+ +-------------------+
  22. // Matrix HTTP | | | |
  23. // Notification Protocol | App Developer | | Device Vendor |
  24. // | | | |
  25. // +-------------------+ | +----------------+ | | +---------------+ |
  26. // | | | | | | | | | |
  27. // | Matrix homeserver +-----> Push Gateway +------> Push Provider | |
  28. // | | | | | | | | | |
  29. // +-^-----------------+ | +----------------+ | | +----+----------+ |
  30. // | | | | | |
  31. // Matrix | | | | | |
  32. // Client/Server API + | | | | |
  33. // | | +--------------------+ +-------------------+
  34. // | +--+-+ |
  35. // | | <-------------------------------------------+
  36. // +---+ |
  37. // | | Provider Push Protocol
  38. // +----+
  39. //
  40. // Mobile Device or Client
  41. //
  42. // matrixRequest represents a Matrix message, as it is sent to a Push Gateway (as per
  43. // this spec: https://spec.matrix.org/v1.2/push-gateway-api/).
  44. //
  45. // From the message, we only require the "pushkey", as it represents our target topic URL.
  46. // A message may look like this (excerpt):
  47. //
  48. // {
  49. // "notification": {
  50. // "devices": [
  51. // {
  52. // "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1",
  53. // ...
  54. // }
  55. // ]
  56. // }
  57. // }
  58. type matrixRequest struct {
  59. Notification *struct {
  60. Devices []*struct {
  61. PushKey string `json:"pushkey"`
  62. } `json:"devices"`
  63. } `json:"notification"`
  64. }
  65. // matrixResponse represents the response to a Matrix push gateway message, as defined
  66. // in the spec (https://spec.matrix.org/v1.2/push-gateway-api/).
  67. type matrixResponse struct {
  68. Rejected []string `json:"rejected"`
  69. }
  70. // errMatrix represents an error when handing Matrix gateway messages
  71. type errMatrix struct {
  72. pushKey string
  73. err error
  74. }
  75. func (e errMatrix) Error() string {
  76. if e.err != nil {
  77. return fmt.Sprintf("message with push key %s rejected: %s", e.pushKey, e.err.Error())
  78. }
  79. return fmt.Sprintf("message with push key %s rejected", e.pushKey)
  80. }
  81. const (
  82. // matrixPushKeyHeader is a header that's used internally to pass the Matrix push key (from the matrixRequest)
  83. // along with the request. The push key is only used if an error occurs down the line.
  84. matrixPushKeyHeader = "X-Matrix-Pushkey"
  85. )
  86. // newRequestFromMatrixJSON reads the request body as a Matrix JSON message, parses the "pushkey", and creates a new
  87. // HTTP request that looks like a normal ntfy request from it.
  88. //
  89. // It basically converts a Matrix push gatewqy request:
  90. //
  91. // POST /_matrix/push/v1/notify HTTP/1.1
  92. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  93. //
  94. // to a ntfy request, looking like this:
  95. //
  96. // POST /upDAHJKFFDFD?up=1 HTTP/1.1
  97. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  98. func newRequestFromMatrixJSON(r *http.Request, baseURL string, messageLimit int) (*http.Request, error) {
  99. if baseURL == "" {
  100. return nil, errHTTPInternalErrorMissingBaseURL
  101. }
  102. body, err := util.Peek(r.Body, messageLimit)
  103. if err != nil {
  104. return nil, err
  105. }
  106. defer r.Body.Close()
  107. if body.LimitReached {
  108. return nil, errHTTPEntityTooLargeMatrixRequestTooLarge
  109. }
  110. var m matrixRequest
  111. if err := json.Unmarshal(body.PeekedBytes, &m); err != nil {
  112. return nil, errHTTPBadRequestMatrixMessageInvalid
  113. } else if m.Notification == nil || len(m.Notification.Devices) == 0 || m.Notification.Devices[0].PushKey == "" {
  114. return nil, errHTTPBadRequestMatrixMessageInvalid
  115. }
  116. pushKey := m.Notification.Devices[0].PushKey // We ignore other devices for now, see discussion in #316
  117. if !strings.HasPrefix(pushKey, baseURL+"/") {
  118. return nil, &errMatrix{pushKey: pushKey, err: wrapErrHTTP(errHTTPBadRequestMatrixPushkeyBaseURLMismatch, "received push key: %s, configured base URL: %s", pushKey, baseURL)}
  119. }
  120. newRequest, err := http.NewRequest(http.MethodPost, pushKey, io.NopCloser(bytes.NewReader(body.PeekedBytes)))
  121. if err != nil {
  122. return nil, &errMatrix{pushKey: pushKey, err: err}
  123. }
  124. newRequest.RemoteAddr = r.RemoteAddr // Not strictly necessary, since visitor was already extracted
  125. if r.Header.Get("X-Forwarded-For") != "" {
  126. newRequest.Header.Set("X-Forwarded-For", r.Header.Get("X-Forwarded-For"))
  127. }
  128. newRequest.Header.Set(matrixPushKeyHeader, pushKey)
  129. return newRequest, nil
  130. }
  131. // writeMatrixDiscoveryResponse writes the UnifiedPush Matrix Gateway Discovery response to the given http.ResponseWriter,
  132. // as per the spec (https://unifiedpush.org/developers/gateway/).
  133. func writeMatrixDiscoveryResponse(w http.ResponseWriter) error {
  134. w.Header().Set("Content-Type", "application/json")
  135. _, err := io.WriteString(w, `{"unifiedpush":{"gateway":"matrix"}}`+"\n")
  136. return err
  137. }
  138. // writeMatrixError logs and writes the errMatrix to the given http.ResponseWriter as a matrixResponse
  139. func writeMatrixError(w http.ResponseWriter, r *http.Request, v *visitor, err *errMatrix) error {
  140. log.Debug("%s Matrix gateway error: %s", logHTTPPrefix(v, r), err.Error())
  141. return writeMatrixResponse(w, err.pushKey)
  142. }
  143. // writeMatrixSuccess writes a successful matrixResponse (no rejected push key) to the given http.ResponseWriter
  144. func writeMatrixSuccess(w http.ResponseWriter) error {
  145. return writeMatrixResponse(w, "")
  146. }
  147. // writeMatrixResponse writes a matrixResponse to the given http.ResponseWriter, as defined in
  148. // the spec (https://spec.matrix.org/v1.2/push-gateway-api/)
  149. func writeMatrixResponse(w http.ResponseWriter, rejectedPushKey string) error {
  150. rejected := make([]string, 0)
  151. if rejectedPushKey != "" {
  152. rejected = append(rejected, rejectedPushKey)
  153. }
  154. response := &matrixResponse{
  155. Rejected: rejected,
  156. }
  157. w.Header().Set("Content-Type", "application/json")
  158. if err := json.NewEncoder(w).Encode(response); err != nil {
  159. return err
  160. }
  161. return nil
  162. }