server_matrix.go 7.2 KB

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