response.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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/server/webapi/amf3"
  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. format := strings.ToLower(r.URL.Query().Get("f"))
  105. if format == "" && r.Method == http.MethodPost {
  106. _ = r.ParseForm()
  107. format = strings.ToLower(r.FormValue("f"))
  108. }
  109. return format
  110. }
  111. // requestIDFromRequest returns the Web AIM client request correlation id from the
  112. // "r" query parameter. JSONP callbacks require this echoed in response.requestId.
  113. func requestIDFromRequest(r *http.Request) string {
  114. if r == nil {
  115. return ""
  116. }
  117. return r.URL.Query().Get("r")
  118. }
  119. // normalizeEnvelope fills in the envelope fields a handler does not set itself:
  120. // the request correlation id, and an empty data object for a response that
  121. // carries no payload. Both are things every encoder needs and none can infer —
  122. // and encoding/xml has no way to render a nil data at all.
  123. func normalizeEnvelope(r *http.Request, data interface{}) interface{} {
  124. br, ok := data.(BaseResponse)
  125. if !ok {
  126. return data
  127. }
  128. if br.Response.RequestID == "" {
  129. br.Response.RequestID = requestIDFromRequest(r)
  130. }
  131. if br.Response.Data == nil {
  132. br.Response.Data = struct{}{}
  133. }
  134. return br
  135. }
  136. // SendResponse sends a response in the requested format (JSON, JSONP, XML, or AMF).
  137. // This is the centralized function that all handlers should use for responses.
  138. func SendResponse(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  139. data = normalizeEnvelope(r, data)
  140. format := requestFormat(r)
  141. callback := jsonpCallback(r)
  142. // Check for AMF format first
  143. if format == "amf" || format == "amf3" {
  144. sendAMF(w, r, data, logger)
  145. return
  146. }
  147. // Check Accept header for AMF
  148. accept := strings.ToLower(r.Header.Get("Accept"))
  149. if strings.Contains(accept, "application/x-amf") ||
  150. strings.Contains(accept, "application/amf") {
  151. sendAMF(w, r, data, logger)
  152. return
  153. }
  154. // If callback is provided, it's JSONP
  155. if callback != "" {
  156. sendJSONP(w, r, callback, data, logger)
  157. return
  158. }
  159. // Check for XML format
  160. if format == "xml" {
  161. sendXML(w, data, logger)
  162. return
  163. }
  164. // Default to JSON
  165. sendJSON(w, data, logger)
  166. }
  167. // SendError sends an error response in the format the client asked for.
  168. //
  169. // When the client requested JSONP, the error must be delivered as an executable
  170. // callback: a bare JSON body inside a <script> tag is a syntax error, which the
  171. // Web AIM client reports as the generic "Failed to load script tag, probably
  172. // malformed JS at that url" instead of the real statusText.
  173. func SendError(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  174. sendErrorEnvelope(w, r, statusCode, newErrorResponse(statusCode, message))
  175. }
  176. // SendErrorDetail sends an error carrying a statusDetailCode, which is how a
  177. // client tells one failure of a status code from another. The HTTP status is
  178. // separate because the API codes are not HTTP codes: a bad clientLogin password
  179. // is 330/3011 on an HTTP 401.
  180. func SendErrorDetail(w http.ResponseWriter, r *http.Request, httpStatus, statusCode, detailCode int, message string) {
  181. sendErrorEnvelope(w, r, httpStatus, newErrorResponseDetail(statusCode, detailCode, message))
  182. }
  183. // SendOK sends the success envelope every Web API method answers with, carrying
  184. // data as its payload.
  185. //
  186. // Pass nil for a bare acknowledgement: SendResponse substitutes the empty data
  187. // object the client dereferences unconditionally on success.
  188. func SendOK(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  189. resp := BaseResponse{}
  190. resp.Response.StatusCode = 200
  191. resp.Response.StatusText = "OK"
  192. resp.Response.Data = data
  193. SendResponse(w, r, resp, logger)
  194. }
  195. // SendEnvelopeStatus reports a non-success outcome that the client must read
  196. // from the envelope, leaving the HTTP status at 200.
  197. //
  198. // This is the counterpart to SendError, which puts the code on the HTTP response
  199. // too. Use it where a 4xx would keep the client from ever reading statusCode: the
  200. // AIM client's request layer routes any non-2xx to its error handlers, which
  201. // synthesize a generic failure and never look at the body. That makes the
  202. // difference between "recipient is offline" (602) or "no such linked service"
  203. // (601) and a generic "your message failed" alert.
  204. //
  205. // It carries no data element; SendResponse substitutes an empty one. A caller
  206. // that needs to send data alongside a non-200 status builds the envelope itself.
  207. func SendEnvelopeStatus(w http.ResponseWriter, r *http.Request, statusCode int, statusText string, logger *slog.Logger) {
  208. resp := BaseResponse{}
  209. resp.Response.StatusCode = statusCode
  210. resp.Response.StatusText = statusText
  211. SendResponse(w, r, resp, logger)
  212. }
  213. // sendErrorEnvelope writes an error envelope in the format the client asked for.
  214. func sendErrorEnvelope(w http.ResponseWriter, r *http.Request, httpStatus int, resp ErrorResponse) {
  215. resp.Response.RequestID = requestIDFromRequest(r)
  216. if callback := jsonpCallback(r); callback != "" && isValidCallback(callback) {
  217. sendJSONPError(w, r, callback, resp)
  218. return
  219. }
  220. // A client that gets a format it cannot parse reports the failure as an
  221. // unreadable response rather than as this statusText. The Content-Type is the
  222. // fallback signal, naming the format a handler already began writing.
  223. format := requestFormat(r)
  224. contentType := w.Header().Get("Content-Type")
  225. switch {
  226. case format == "xml" || strings.Contains(contentType, "xml"):
  227. sendXMLError(w, httpStatus, resp)
  228. case format == "amf" || format == "amf3" || strings.Contains(contentType, "amf"):
  229. sendAMFError(w, httpStatus, resp)
  230. default:
  231. sendJSONError(w, httpStatus, resp)
  232. }
  233. }
  234. // sendJSONPError writes an error envelope wrapped in the client's JSONP callback.
  235. //
  236. // The HTTP status is deliberately left at 200: browsers do not execute the body
  237. // of a <script> tag that came back with a 4xx or 5xx, so a status-carrying JSONP
  238. // error never reaches the callback at all. The real status travels in the
  239. // envelope, which is where the Web AIM client reads it from regardless.
  240. func sendJSONPError(w http.ResponseWriter, r *http.Request, callback string, resp ErrorResponse) {
  241. envelope := map[string]any{
  242. "statusCode": resp.Response.StatusCode,
  243. "statusText": resp.Response.StatusText,
  244. // Callbacks that reach response.data on a failure throw a TypeError when
  245. // it is absent, which aborts whatever the client was doing mid-startup.
  246. // Its XHR path fabricates an empty data for transport failures; JSONP
  247. // delivers the envelope verbatim, so the empty data has to come from here.
  248. "data": map[string]any{},
  249. }
  250. if resp.Response.StatusDetailCode != 0 {
  251. envelope["statusDetailCode"] = resp.Response.StatusDetailCode
  252. }
  253. // The client indexes JSONP replies by response.requestId and discards any
  254. // reply that lacks one ("Request id is missing from the server response"),
  255. // leaving the request pending until it times out.
  256. if id := requestIDFromRequest(r); id != "" {
  257. envelope["requestId"] = id
  258. }
  259. body, err := json.Marshal(map[string]any{"response": envelope})
  260. if err != nil {
  261. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  262. return
  263. }
  264. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  265. _, _ = w.Write([]byte(callback))
  266. _, _ = w.Write([]byte("("))
  267. _, _ = w.Write(body)
  268. _, _ = w.Write([]byte(");"))
  269. }
  270. // sendJSONError sends a JSON error response.
  271. func sendJSONError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  272. w.Header().Set("Content-Type", "application/json")
  273. w.WriteHeader(httpStatus)
  274. _ = json.NewEncoder(w).Encode(resp)
  275. }
  276. // sendXMLError sends an XML error response.
  277. func sendXMLError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  278. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  279. w.WriteHeader(httpStatus)
  280. // Write XML declaration and marshal the response
  281. xmlData, err := xml.Marshal(resp)
  282. if err != nil {
  283. // Fall back to simple text response
  284. http.Error(w, resp.Response.StatusText, httpStatus)
  285. return
  286. }
  287. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  288. _, _ = w.Write([]byte(xmlOutput))
  289. }
  290. // sendJSON sends a JSON response.
  291. func sendJSON(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  292. w.Header().Set("Content-Type", "application/json")
  293. body, err := json.Marshal(data)
  294. if err != nil {
  295. if logger != nil {
  296. logger.Error("failed to encode JSON response", "err", err.Error())
  297. }
  298. return
  299. }
  300. if logger != nil {
  301. logger.Debug("JSON response", "body", string(body))
  302. }
  303. if _, err := w.Write(body); err != nil && logger != nil {
  304. logger.Error("failed to write JSON response", "err", err.Error())
  305. }
  306. }
  307. // sendXML sends an XML response.
  308. func sendXML(w http.ResponseWriter, data interface{}, logger *slog.Logger) {
  309. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  310. // Every payload is a struct whose xml tags name its elements, and the
  311. // envelope's MarshalXML renders the flat <response> root the Web API uses.
  312. xmlData, err := xml.Marshal(data)
  313. if err != nil {
  314. if logger != nil {
  315. logger.Error("failed to marshal XML response", "err", err.Error())
  316. }
  317. sendXMLError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  318. return
  319. }
  320. // Write XML declaration and data
  321. xmlOutput := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>%s`, xmlData)
  322. // Set content length for proper response handling
  323. w.Header().Set("Content-Length", strconv.Itoa(len(xmlOutput)))
  324. _, _ = w.Write([]byte(xmlOutput))
  325. }
  326. // jsonpCallback returns the JSONP callback name from the request.
  327. // Web AIM clients use the "c" query parameter; other callers may use "callback".
  328. func jsonpCallback(r *http.Request) string {
  329. if r == nil {
  330. return ""
  331. }
  332. if callback := r.URL.Query().Get("c"); callback != "" {
  333. return callback
  334. }
  335. return r.URL.Query().Get("callback")
  336. }
  337. // sendJSONP sends a JSONP response with the specified callback.
  338. func sendJSONP(w http.ResponseWriter, r *http.Request, callback string, data interface{}, logger *slog.Logger) {
  339. // Validate callback to prevent XSS. This is the one error here that cannot be
  340. // delivered as JSONP: there is no callback name safe to write.
  341. if !isValidCallback(callback) {
  342. sendJSONError(w, http.StatusBadRequest, newErrorResponse(http.StatusBadRequest, "invalid callback parameter"))
  343. return
  344. }
  345. jsonData, err := json.Marshal(data)
  346. if err != nil {
  347. if logger != nil {
  348. logger.Error("failed to marshal response", "err", err.Error())
  349. }
  350. // The client is on the <script> transport, so the error has to be
  351. // executable JS for it to see anything but a load failure.
  352. sendJSONPError(w, r, callback, newErrorResponse(http.StatusInternalServerError, "internal server error"))
  353. return
  354. }
  355. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  356. _, _ = w.Write([]byte(callback))
  357. _, _ = w.Write([]byte("("))
  358. _, _ = w.Write(jsonData)
  359. _, _ = w.Write([]byte(");"))
  360. }
  361. // isValidCallback validates a JSONP callback name to prevent XSS.
  362. func isValidCallback(callback string) bool {
  363. if len(callback) == 0 || len(callback) > 100 {
  364. return false
  365. }
  366. // Allow alphanumeric, underscore, dollar sign, and dot (for namespace)
  367. for _, r := range callback {
  368. if (r < 'a' || r > 'z') &&
  369. (r < 'A' || r > 'Z') &&
  370. (r < '0' || r > '9') &&
  371. r != '_' && r != '$' && r != '.' {
  372. return false
  373. }
  374. }
  375. return true
  376. }
  377. // sendAMF sends an AMF response
  378. func sendAMF(w http.ResponseWriter, r *http.Request, data interface{}, logger *slog.Logger) {
  379. amfData, err := amf3.Marshal(data)
  380. if err != nil {
  381. if logger != nil {
  382. logger.Error("failed to encode AMF response",
  383. "err", err.Error(),
  384. "dataType", fmt.Sprintf("%T", data))
  385. }
  386. // Fall back to JSON error
  387. sendJSONError(w, http.StatusInternalServerError, newErrorResponse(http.StatusInternalServerError, "AMF encoding failed"))
  388. return
  389. }
  390. w.Header().Set("Content-Type", "application/x-amf")
  391. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  392. // Debug logging if enabled
  393. if logger != nil && logger.Enabled(context.TODO(), slog.LevelDebug) {
  394. hexPreview := ""
  395. if len(amfData) > 0 {
  396. previewLen := len(amfData)
  397. if previewLen > 64 {
  398. previewLen = 64
  399. }
  400. hexPreview = hex.EncodeToString(amfData[:previewLen])
  401. }
  402. logger.Debug("sending AMF response",
  403. "size", len(amfData),
  404. "path", r.URL.Path,
  405. "hexPreview", hexPreview)
  406. }
  407. if _, err := w.Write(amfData); err != nil {
  408. if logger != nil {
  409. logger.Error("failed to write AMF response",
  410. "err", err.Error())
  411. }
  412. }
  413. }
  414. // sendAMFError sends an AMF error response, falling back to JSON for a payload
  415. // AMF3 cannot represent.
  416. func sendAMFError(w http.ResponseWriter, httpStatus int, resp ErrorResponse) {
  417. amfData, err := amf3.Marshal(resp)
  418. if err != nil {
  419. sendJSONError(w, httpStatus, resp)
  420. return
  421. }
  422. w.Header().Set("Content-Type", "application/x-amf")
  423. w.Header().Set("Content-Length", strconv.Itoa(len(amfData)))
  424. w.WriteHeader(httpStatus)
  425. _, _ = w.Write(amfData)
  426. }