response.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package webapi
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "encoding/json"
  6. "encoding/xml"
  7. "fmt"
  8. "log/slog"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "github.com/mk6i/open-oscar-server/wire"
  13. )
  14. // Web API status codes. These are the client's own vocabulary, not HTTP codes,
  15. // and it reads them from the envelope rather than from the HTTP status — which
  16. // is why several of them ship on an HTTP 200 (see SendEnvelopeStatus).
  17. const (
  18. // statusMoreAuthRequired is what makes a failed sign-in a demand for better
  19. // credentials rather than an error: paired with the detail code naming what
  20. // was wrong, it is what tells a client to say "incorrect password".
  21. statusMoreAuthRequired = 330
  22. // statusRateLimited is swallowed by the client on the IM path, so that the
  23. // rateLimit event owns the user-facing message instead of a generic send
  24. // failure alert.
  25. statusRateLimited = 430
  26. statusMissingParameter = 460
  27. // statusParameterError is for a parameter that is present but unusable.
  28. statusParameterError = 462
  29. // statusNoSuchService is what the client accepts as "this account has no such
  30. // linked service". Its getAttributes callback treats 601 as an expected
  31. // outcome and returns early; any other status sends it into the success
  32. // branch, where it dereferences response.data.serviceName and marks the
  33. // service associated. A 404 therefore both crashes the callback and, if it
  34. // did not, would advertise a linked account that does not exist.
  35. statusNoSuchService = 601
  36. // statusSendFailed is one of the two codes (602/603) the client recognizes as
  37. // "recipient offline or blocked". Any other code, and an empty body most of
  38. // all, falls through to its generic "Bummer. Your message failed." alert.
  39. statusSendFailed = 602
  40. // detailBadPassword is the statusDetailCode under statusMoreAuthRequired that
  41. // names a wrong password specifically.
  42. detailBadPassword = 3011
  43. )
  44. // BaseResponse is the standard response envelope for all Web API responses.
  45. // It supports both JSON and XML marshaling.
  46. type BaseResponse struct {
  47. Response ResponseBody `json:"response"`
  48. }
  49. // MarshalXML renders the envelope as the Web API's flat <response> root, where
  50. // JSON nests the same body under a "response" key. Reconciling the two shapes
  51. // here is what lets one struct describe a response in both formats.
  52. func (b BaseResponse) MarshalXML(e *xml.Encoder, _ xml.StartElement) error {
  53. return e.EncodeElement(b.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  54. }
  55. // ResponseBody contains the status and data for API responses.
  56. type ResponseBody struct {
  57. StatusCode int `json:"statusCode" xml:"statusCode"`
  58. StatusText string `json:"statusText" xml:"statusText"`
  59. RequestID string `json:"requestId,omitempty" xml:"requestId,omitempty"`
  60. // Data is never omitted. Every Web API method sends a data element even when
  61. // it carries no payload, and the client dereferences response.data on any
  62. // success; SendResponse substitutes an empty object when a handler sets none.
  63. Data interface{} `json:"data" xml:"data"`
  64. }
  65. // ErrorResponse represents an error response with proper XML/JSON support.
  66. type ErrorResponse struct {
  67. Response struct {
  68. StatusCode int `json:"statusCode" xml:"statusCode"`
  69. // StatusDetailCode names which failure of a status code this is, e.g. 3011
  70. // (bad password) under 330. Omitted when unset, which a client would
  71. // otherwise read as a detail code of its own.
  72. StatusDetailCode int `json:"statusDetailCode,omitempty" xml:"statusDetailCode,omitempty"`
  73. StatusText string `json:"statusText" xml:"statusText"`
  74. // RequestID echoes the client's correlation id, the same way BaseResponse
  75. // carries it. A client that indexes replies by it cannot match a failure
  76. // that omits it, so an error needs it as much as a success does.
  77. RequestID string `json:"requestId,omitempty" xml:"requestId,omitempty"`
  78. // Data carries an empty object for the same reason the JSONP error path
  79. // sends one: a client callback that reaches response.data on a failure
  80. // throws a TypeError when it is absent.
  81. Data interface{} `json:"data" xml:"data"`
  82. } `json:"response"`
  83. }
  84. // MarshalXML renders the error envelope with the same flat root as BaseResponse.
  85. func (e ErrorResponse) MarshalXML(enc *xml.Encoder, _ xml.StartElement) error {
  86. return enc.EncodeElement(e.Response, xml.StartElement{Name: xml.Name{Local: "response"}})
  87. }
  88. // newErrorResponse builds the error envelope every format shares.
  89. func newErrorResponse(statusCode int, message string) ErrorResponse {
  90. return newErrorResponseDetail(statusCode, 0, message)
  91. }
  92. // newErrorResponseDetail builds the error envelope with a statusDetailCode.
  93. func newErrorResponseDetail(statusCode, detailCode int, message string) ErrorResponse {
  94. resp := ErrorResponse{}
  95. resp.Response.StatusCode = statusCode
  96. resp.Response.StatusDetailCode = detailCode
  97. resp.Response.StatusText = message
  98. resp.Response.Data = struct{}{}
  99. return resp
  100. }
  101. // requestFormat returns the format the client asked for. A POST sends "f" in
  102. // its body, as clientLogin does.
  103. func requestFormat(r *http.Request) string {
  104. return strings.ToLower(param(r, "f"))
  105. }
  106. // requestIDFromRequest returns the client's correlation id from the "r" parameter,
  107. // echoed in response.requestId on every path. It may arrive in the POST body, so it
  108. // is read from either location.
  109. func requestIDFromRequest(r *http.Request) string {
  110. if r == nil {
  111. return ""
  112. }
  113. return param(r, "r")
  114. }
  115. // normalizeEnvelope fills in the envelope fields a handler does not set itself:
  116. // the request correlation id, and an empty data object for a response that
  117. // carries no payload. Both are things every encoder needs and none can infer —
  118. // and encoding/xml has no way to render a nil data at all.
  119. func normalizeEnvelope(r *http.Request, data interface{}) interface{} {
  120. br, ok := data.(BaseResponse)
  121. if !ok {
  122. return data
  123. }
  124. if br.Response.RequestID == "" {
  125. br.Response.RequestID = requestIDFromRequest(r)
  126. }
  127. if br.Response.Data == nil {
  128. br.Response.Data = struct{}{}
  129. }
  130. return br
  131. }
  132. // SendResponse sends a response in the requested format (JSON, JSONP, XML, or AMF).
  133. // This is the centralized function that all handlers should use for responses.
  134. func SendResponse(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  135. data = normalizeEnvelope(r, data)
  136. format := requestFormat(r)
  137. callback := jsonpCallback(r)
  138. // Check for AMF format first
  139. if format == "amf" || format == "amf3" {
  140. sendAMF(w, r, data, logger)
  141. return
  142. }
  143. // Check Accept header for AMF
  144. accept := strings.ToLower(r.Header.Get("Accept"))
  145. if strings.Contains(accept, "application/x-amf") ||
  146. strings.Contains(accept, "application/amf") {
  147. sendAMF(w, r, data, logger)
  148. return
  149. }
  150. // If callback is provided, it's JSONP
  151. if callback != "" {
  152. sendJSONP(w, r, callback, data, logger)
  153. return
  154. }
  155. // Check for XML format
  156. if format == "xml" {
  157. sendXML(w, data, logger)
  158. return
  159. }
  160. // Default to JSON
  161. sendJSON(w, data, logger)
  162. }
  163. // SendError sends an error response in the format the client asked for.
  164. //
  165. // When the client requested JSONP, the error must be delivered as an executable
  166. // callback: a bare JSON body inside a <script> tag is a syntax error, which the
  167. // Web AIM client reports as the generic "Failed to load script tag, probably
  168. // malformed JS at that url" instead of the real statusText.
  169. func SendError(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  170. sendErrorEnvelope(w, r, statusCode, newErrorResponse(statusCode, message))
  171. }
  172. // SendErrorDetail sends an error carrying a statusDetailCode, which is how a
  173. // client tells one failure of a status code from another. The HTTP status is
  174. // separate because the API codes are not HTTP codes: a bad clientLogin password
  175. // is 330/3011 on an HTTP 401.
  176. func SendErrorDetail(w http.ResponseWriter, r *http.Request, httpStatus, statusCode, detailCode int, message string) {
  177. sendErrorEnvelope(w, r, httpStatus, newErrorResponseDetail(statusCode, detailCode, message))
  178. }
  179. // SendOK sends the success envelope every Web API method answers with, carrying
  180. // data as its payload.
  181. //
  182. // Pass nil for a bare acknowledgement: SendResponse substitutes the empty data
  183. // object the client dereferences unconditionally on success.
  184. func SendOK(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  185. resp := BaseResponse{}
  186. resp.Response.StatusCode = 200
  187. resp.Response.StatusText = "Ok"
  188. resp.Response.Data = data
  189. SendResponse(w, r, resp, logger)
  190. }
  191. // SendEnvelopeStatus reports a non-success outcome that the client must read
  192. // from the envelope, leaving the HTTP status at 200.
  193. //
  194. // This is the counterpart to SendError, which puts the code on the HTTP response
  195. // too. Use it where a 4xx would keep the client from ever reading statusCode: the
  196. // AIM client's request layer routes any non-2xx to its error handlers, which
  197. // synthesize a generic failure and never look at the body. That makes the
  198. // difference between "recipient is offline" (602) or "no such linked service"
  199. // (601) and a generic "your message failed" alert.
  200. //
  201. // It carries no data element; SendResponse substitutes an empty one. A caller
  202. // that needs to send data alongside a non-200 status builds the envelope itself.
  203. func SendEnvelopeStatus(w http.ResponseWriter, r *http.Request, statusCode int, statusText string, logger *slog.Logger) {
  204. resp := BaseResponse{}
  205. resp.Response.StatusCode = statusCode
  206. resp.Response.StatusText = statusText
  207. SendResponse(w, r, resp, logger)
  208. }
  209. // sendErrorEnvelope writes an error envelope in the format the client asked for.
  210. func sendErrorEnvelope(w http.ResponseWriter, r *http.Request, httpStatus int, resp ErrorResponse) {
  211. resp.Response.RequestID = requestIDFromRequest(r)
  212. if callback := jsonpCallback(r); callback != "" && isValidCallback(callback) {
  213. sendJSONPError(w, r, callback, resp)
  214. return
  215. }
  216. // A client that gets a format it cannot parse reports the failure as an
  217. // unreadable response rather than as this statusText. The Content-Type is the
  218. // fallback signal, naming the format a handler already began writing.
  219. format := requestFormat(r)
  220. contentType := w.Header().Get("Content-Type")
  221. switch {
  222. case format == "xml" || strings.Contains(contentType, "xml"):
  223. sendXMLError(w, httpStatus, resp)
  224. case format == "amf" || format == "amf3" || strings.Contains(contentType, "amf"):
  225. sendAMFError(w, httpStatus, resp)
  226. default:
  227. sendJSONError(w, httpStatus, resp)
  228. }
  229. }
  230. // sendJSONPError writes an error envelope wrapped in the client's JSONP callback.
  231. //
  232. // The HTTP status is deliberately left at 200: browsers do not execute the body
  233. // of a <script> tag that came back with a 4xx or 5xx, so a status-carrying JSONP
  234. // error never reaches the callback at all. The real status travels in the
  235. // envelope, which is where the Web AIM client reads it from regardless.
  236. func sendJSONPError(w http.ResponseWriter, r *http.Request, callback string, resp ErrorResponse) {
  237. envelope := map[string]any{
  238. "statusCode": resp.Response.StatusCode,
  239. "statusText": resp.Response.StatusText,
  240. // Callbacks that reach response.data on a failure throw a TypeError when
  241. // it is absent, which aborts whatever the client was doing mid-startup.
  242. // Its XHR path fabricates an empty data for transport failures; JSONP
  243. // delivers the envelope verbatim, so the empty data has to come from here.
  244. "data": map[string]any{},
  245. }
  246. if resp.Response.StatusDetailCode != 0 {
  247. envelope["statusDetailCode"] = resp.Response.StatusDetailCode
  248. }
  249. // The client indexes JSONP replies by response.requestId and discards any
  250. // reply that lacks one ("Request id is missing from the server response"),
  251. // leaving the request pending until it times out.
  252. if id := requestIDFromRequest(r); id != "" {
  253. envelope["requestId"] = id
  254. }
  255. body, err := json.Marshal(map[string]any{"response": envelope})
  256. if err != nil {
  257. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  258. return
  259. }
  260. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  261. _, _ = w.Write([]byte(callback))
  262. _, _ = w.Write([]byte("("))
  263. _, _ = w.Write(body)
  264. _, _ = w.Write([]byte(");"))
  265. }
  266. // sendJSONError sends a JSON error response.
  267. func sendJSONError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  268. w.Header().Set("Content-Type", "application/json")
  269. w.WriteHeader(httpStatus)
  270. _ = json.NewEncoder(w).Encode(resp)
  271. }
  272. // sendXMLError sends an XML error response.
  273. func sendXMLError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  274. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  275. w.WriteHeader(httpStatus)
  276. // Write XML declaration and marshal the response
  277. xmlData, err := xml.Marshal(resp)
  278. if err != nil {
  279. // Fall back to simple text response
  280. http.Error(w, resp.Response.StatusText, httpStatus)
  281. return
  282. }
  283. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  284. _, _ = w.Write([]byte(xmlOutput))
  285. }
  286. // sendJSON sends a JSON response.
  287. func sendJSON(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  288. w.Header().Set("Content-Type", "application/json")
  289. body, err := json.Marshal(data)
  290. if err != nil {
  291. if logger != nil {
  292. logger.Error("failed to encode JSON response", "err", err.Error())
  293. }
  294. return
  295. }
  296. if logger != nil {
  297. logger.Debug("JSON response", "body", string(body))
  298. }
  299. if _, err := w.Write(body); err != nil && logger != nil {
  300. logger.Error("failed to write JSON response", "err", err.Error())
  301. }
  302. }
  303. // sendXML sends an XML response.
  304. func sendXML(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  305. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  306. // Every payload is a struct whose xml tags name its elements, and the
  307. // envelope's MarshalXML renders the flat <response> root the Web API uses.
  308. xmlData, err := xml.Marshal(data)
  309. if err != nil {
  310. if logger != nil {
  311. logger.Error("failed to marshal XML response", "err", err.Error())
  312. }
  313. sendXMLError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  314. return
  315. }
  316. // Write XML declaration and data
  317. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  318. // Set content length for proper response handling
  319. w.Header().Set("Content-Length", strconv.Itoa(len(xmlOutput)))
  320. _, _ = w.Write([]byte(xmlOutput))
  321. }
  322. // jsonpCallback returns the JSONP callback name from the request.
  323. // Web AIM clients use the "c" query parameter; other callers may use "callback".
  324. func jsonpCallback(r *http.Request) string {
  325. if r == nil {
  326. return ""
  327. }
  328. if callback := r.URL.Query().Get("c"); callback != "" {
  329. return callback
  330. }
  331. return r.URL.Query().Get("callback")
  332. }
  333. // sendJSONP sends a JSONP response with the specified callback.
  334. func sendJSONP(w http.ResponseWriter, r *http.Request, callback string, data interface{}, logger *slog.Logger) {
  335. // Validate callback to prevent XSS. This is the one error here that cannot be
  336. // delivered as JSONP: there is no callback name safe to write.
  337. if !isValidCallback(callback) {
  338. sendJSONError(w, http.StatusBadRequest, newErrorResponse(http.StatusBadRequest, "invalid callback parameter"))
  339. return
  340. }
  341. jsonData, err := json.Marshal(data)
  342. if err != nil {
  343. if logger != nil {
  344. logger.Error("failed to marshal response", "err", err.Error())
  345. }
  346. // The client is on the <script> transport, so the error has to be
  347. // executable JS for it to see anything but a load failure.
  348. sendJSONPError(w, r, callback, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  349. return
  350. }
  351. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  352. _, _ = w.Write([]byte(callback))
  353. _, _ = w.Write([]byte("("))
  354. _, _ = w.Write(jsonData)
  355. _, _ = w.Write([]byte(");"))
  356. }
  357. // isValidCallback validates a JSONP callback name to prevent XSS.
  358. func isValidCallback(callback string) bool {
  359. if len(callback) == 0 || len(callback) > 100 {
  360. return false
  361. }
  362. // Allow alphanumeric, underscore, dollar sign, and dot (for namespace)
  363. for _, r := range callback {
  364. if (r < 'a' || r > 'z') &&
  365. (r < 'A' || r > 'Z') &&
  366. (r < '0' || r > '9') &&
  367. r != '_' && r != '$' && r != '.' {
  368. return false
  369. }
  370. }
  371. return true
  372. }
  373. // sendAMF sends an AMF response
  374. func sendAMF(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  375. amfData, err := wire.MarshalAMF3(data)
  376. if err != nil {
  377. if logger != nil {
  378. logger.Error("failed to encode AMF response",
  379. "err", err.Error(),
  380. "dataType", fmt.Sprintf("%T", data))
  381. }
  382. // Fall back to JSON error
  383. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "AMF encoding failed"))
  384. return
  385. }
  386. w.Header().Set("Content-Type", "application/x-amf")
  387. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  388. // Debug logging if enabled
  389. if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
  390. hexPreview := ""
  391. if len(amfData) > 0 {
  392. previewLen := len(amfData)
  393. if previewLen > 64 {
  394. previewLen = 64
  395. }
  396. hexPreview = hex.EncodeToString(amfData[:previewLen])
  397. }
  398. logger.Debug("sending AMF response",
  399. "size", len(amfData),
  400. "path", r.URL.Path,
  401. "hexPreview", hexPreview)
  402. }
  403. if _, err := w.Write(amfData); err != nil {
  404. if logger != nil {
  405. logger.Error("failed to write AMF response",
  406. "err", err.Error())
  407. }
  408. }
  409. }
  410. // sendAMFError sends an AMF error response, falling back to JSON for a payload
  411. // AMF3 cannot represent.
  412. func sendAMFError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  413. amfData, err := wire.MarshalAMF3(resp)
  414. if err != nil {
  415. sendJSONError(w, httpStatus, resp)
  416. return
  417. }
  418. w.Header().Set("Content-Type", "application/x-amf")
  419. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  420. w.WriteHeader(httpStatus)
  421. _, _ = w.Write(amfData)
  422. }