agi.http_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package agi
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "net/url"
  9. "strings"
  10. "testing"
  11. "github.com/robertkrimen/otto"
  12. "imuslab.com/arozos/mod/agi/static"
  13. user "imuslab.com/arozos/mod/user"
  14. )
  15. // ─── body builder ────────────────────────────────────────────────────────────
  16. func TestBuildHTTPRequestBody(t *testing.T) {
  17. //bodyBase64 takes precedence and decodes to raw bytes
  18. t.Run("base64", func(t *testing.T) {
  19. raw := []byte{0x00, 0x01, 0x02, 0xff}
  20. opt := httpRequestOptions{BodyBase64: base64.StdEncoding.EncodeToString(raw)}
  21. r, ct, err := buildHTTPRequestBody(opt)
  22. if err != nil {
  23. t.Fatalf("unexpected error: %v", err)
  24. }
  25. if ct != "application/octet-stream" {
  26. t.Errorf("unexpected content-type: %q", ct)
  27. }
  28. got, _ := io.ReadAll(r)
  29. if string(got) != string(raw) {
  30. t.Errorf("binary body not decoded correctly: %v", got)
  31. }
  32. })
  33. t.Run("invalid base64", func(t *testing.T) {
  34. _, _, err := buildHTTPRequestBody(httpRequestOptions{BodyBase64: "!!!not base64!!!"})
  35. if err == nil {
  36. t.Error("expected error for invalid base64 body")
  37. }
  38. })
  39. t.Run("form", func(t *testing.T) {
  40. opt := httpRequestOptions{Form: map[string]string{"a": "1", "b": "hello world"}}
  41. r, ct, err := buildHTTPRequestBody(opt)
  42. if err != nil {
  43. t.Fatalf("unexpected error: %v", err)
  44. }
  45. if ct != "application/x-www-form-urlencoded" {
  46. t.Errorf("unexpected content-type: %q", ct)
  47. }
  48. got, _ := io.ReadAll(r)
  49. values, _ := url.ParseQuery(string(got))
  50. if values.Get("a") != "1" || values.Get("b") != "hello world" {
  51. t.Errorf("form not encoded correctly: %q", string(got))
  52. }
  53. })
  54. t.Run("json", func(t *testing.T) {
  55. opt := httpRequestOptions{JSON: json.RawMessage(`{"x":1}`)}
  56. r, ct, err := buildHTTPRequestBody(opt)
  57. if err != nil {
  58. t.Fatalf("unexpected error: %v", err)
  59. }
  60. if ct != "application/json" {
  61. t.Errorf("unexpected content-type: %q", ct)
  62. }
  63. got, _ := io.ReadAll(r)
  64. if strings.TrimSpace(string(got)) != `{"x":1}` {
  65. t.Errorf("json body mismatch: %q", string(got))
  66. }
  67. })
  68. t.Run("raw", func(t *testing.T) {
  69. opt := httpRequestOptions{Body: "plain text"}
  70. r, ct, err := buildHTTPRequestBody(opt)
  71. if err != nil {
  72. t.Fatalf("unexpected error: %v", err)
  73. }
  74. if ct != "" {
  75. t.Errorf("raw body should carry no default content-type, got %q", ct)
  76. }
  77. got, _ := io.ReadAll(r)
  78. if string(got) != "plain text" {
  79. t.Errorf("raw body mismatch: %q", string(got))
  80. }
  81. })
  82. t.Run("empty", func(t *testing.T) {
  83. r, ct, err := buildHTTPRequestBody(httpRequestOptions{})
  84. if err != nil || r != nil || ct != "" {
  85. t.Errorf("empty options should yield no body, got r=%v ct=%q err=%v", r, ct, err)
  86. }
  87. })
  88. }
  89. // ─── request execution ───────────────────────────────────────────────────────
  90. func TestDoHTTPRequestMethodHeadersAndBody(t *testing.T) {
  91. var gotMethod, gotHeader, gotBody, gotContentType string
  92. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  93. gotMethod = r.Method
  94. gotHeader = r.Header.Get("X-Custom")
  95. gotContentType = r.Header.Get("Content-Type")
  96. b, _ := io.ReadAll(r.Body)
  97. gotBody = string(b)
  98. w.Header().Set("X-Reply", "pong")
  99. w.WriteHeader(201)
  100. io.WriteString(w, "created")
  101. }))
  102. defer srv.Close()
  103. resp := doHTTPRequest(httpRequestOptions{
  104. URL: srv.URL,
  105. Method: "put",
  106. Headers: map[string]string{"X-Custom": "yes"},
  107. Body: "the payload",
  108. })
  109. if resp.Error != "" {
  110. t.Fatalf("unexpected error: %s", resp.Error)
  111. }
  112. if gotMethod != "PUT" {
  113. t.Errorf("method not applied/uppercased, got %q", gotMethod)
  114. }
  115. if gotHeader != "yes" {
  116. t.Errorf("custom header not sent, got %q", gotHeader)
  117. }
  118. if gotBody != "the payload" {
  119. t.Errorf("body not sent, got %q", gotBody)
  120. }
  121. if gotContentType != "" {
  122. t.Errorf("raw body should not set a content-type, got %q", gotContentType)
  123. }
  124. if resp.Status != 201 || !resp.Ok {
  125. t.Errorf("status/ok mismatch: status=%d ok=%v", resp.Status, resp.Ok)
  126. }
  127. if resp.Body != "created" {
  128. t.Errorf("response body mismatch: %q", resp.Body)
  129. }
  130. if len(resp.Headers["X-Reply"]) == 0 || resp.Headers["X-Reply"][0] != "pong" {
  131. t.Errorf("response headers not captured: %v", resp.Headers)
  132. }
  133. }
  134. func TestDoHTTPRequestFormAndContentTypeOverride(t *testing.T) {
  135. var gotContentType, gotBody string
  136. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  137. gotContentType = r.Header.Get("Content-Type")
  138. b, _ := io.ReadAll(r.Body)
  139. gotBody = string(b)
  140. io.WriteString(w, "ok")
  141. }))
  142. defer srv.Close()
  143. //Form body sets the urlencoded content type by default.
  144. resp := doHTTPRequest(httpRequestOptions{URL: srv.URL, Method: "POST", Form: map[string]string{"k": "v"}})
  145. if resp.Error != "" {
  146. t.Fatalf("unexpected error: %s", resp.Error)
  147. }
  148. if gotContentType != "application/x-www-form-urlencoded" {
  149. t.Errorf("form content-type not defaulted, got %q", gotContentType)
  150. }
  151. if values, _ := url.ParseQuery(gotBody); values.Get("k") != "v" {
  152. t.Errorf("form body mismatch: %q", gotBody)
  153. }
  154. //Explicit contentType option overrides the default.
  155. doHTTPRequest(httpRequestOptions{URL: srv.URL, Method: "POST", Body: "x", ContentType: "text/csv"})
  156. if gotContentType != "text/csv" {
  157. t.Errorf("contentType override not applied, got %q", gotContentType)
  158. }
  159. }
  160. func TestDoHTTPRequestBinaryResponse(t *testing.T) {
  161. raw := []byte{0x10, 0x20, 0x30, 0xff, 0x00}
  162. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  163. w.Write(raw)
  164. }))
  165. defer srv.Close()
  166. resp := doHTTPRequest(httpRequestOptions{URL: srv.URL, ResponseType: "base64"})
  167. if resp.Error != "" {
  168. t.Fatalf("unexpected error: %s", resp.Error)
  169. }
  170. decoded, err := base64.StdEncoding.DecodeString(resp.Body)
  171. if err != nil {
  172. t.Fatalf("response body was not valid base64: %v", err)
  173. }
  174. if string(decoded) != string(raw) {
  175. t.Errorf("binary response mismatch: %v", decoded)
  176. }
  177. }
  178. func TestDoHTTPRequestBasicAuth(t *testing.T) {
  179. var gotUser, gotPass string
  180. var ok bool
  181. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  182. gotUser, gotPass, ok = r.BasicAuth()
  183. io.WriteString(w, "ok")
  184. }))
  185. defer srv.Close()
  186. doHTTPRequest(httpRequestOptions{URL: srv.URL, Username: "alice", Password: "s3cr3t"})
  187. if !ok || gotUser != "alice" || gotPass != "s3cr3t" {
  188. t.Errorf("basic auth not applied: user=%q pass=%q ok=%v", gotUser, gotPass, ok)
  189. }
  190. }
  191. func TestDoHTTPRequestNoFollowRedirect(t *testing.T) {
  192. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  193. if r.URL.Path == "/start" {
  194. http.Redirect(w, r, "/dest", http.StatusFound)
  195. return
  196. }
  197. io.WriteString(w, "final")
  198. }))
  199. defer srv.Close()
  200. follow := false
  201. resp := doHTTPRequest(httpRequestOptions{URL: srv.URL + "/start", FollowRedirect: &follow})
  202. if resp.Error != "" {
  203. t.Fatalf("unexpected error: %s", resp.Error)
  204. }
  205. if resp.Status != http.StatusFound {
  206. t.Errorf("expected 302 when not following redirect, got %d", resp.Status)
  207. }
  208. if len(resp.Headers["Location"]) == 0 || !strings.HasSuffix(resp.Headers["Location"][0], "/dest") {
  209. t.Errorf("expected Location header, got %v", resp.Headers)
  210. }
  211. }
  212. func TestDoHTTPRequestMissingURL(t *testing.T) {
  213. resp := doHTTPRequest(httpRequestOptions{})
  214. if resp.Error == "" {
  215. t.Error("expected an error when url is missing")
  216. }
  217. }
  218. // ─── JS object exposure ─────────────────────────────────────────────────────
  219. func TestInjectHTTPLib_JSObjectExposed(t *testing.T) {
  220. g := minimalGateway()
  221. vm := otto.New()
  222. payload := &static.AgiLibInjectionPayload{VM: vm, User: &user.User{Username: "alice"}}
  223. g.injectHTTPFunctions(payload)
  224. for _, method := range []string{"request", "get", "post", "put", "patch", "delete", "postForm", "postJSON", "head", "download", "getb64", "getCode", "redirect"} {
  225. val, err := vm.Run(`typeof http.` + method)
  226. if err != nil {
  227. t.Fatalf("evaluating http.%s: %v", method, err)
  228. }
  229. s, _ := val.ToString()
  230. if s != "function" {
  231. t.Errorf("http.%s should be a function, got %q", method, s)
  232. }
  233. }
  234. }
  235. func TestHTTPRequestFromVM(t *testing.T) {
  236. var gotMethod, gotBody string
  237. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  238. gotMethod = r.Method
  239. b, _ := io.ReadAll(r.Body)
  240. gotBody = string(b)
  241. io.WriteString(w, "hello vm")
  242. }))
  243. defer srv.Close()
  244. g := minimalGateway()
  245. vm := otto.New()
  246. payload := &static.AgiLibInjectionPayload{VM: vm, User: &user.User{Username: "alice"}}
  247. g.injectHTTPFunctions(payload)
  248. val, err := vm.Run(`
  249. var resp = http.request({url: "` + srv.URL + `", method: "POST", body: "vm-body"});
  250. resp.status + "|" + resp.ok + "|" + resp.body;
  251. `)
  252. if err != nil {
  253. t.Fatalf("vm run error: %v", err)
  254. }
  255. out, _ := val.ToString()
  256. if out != "200|true|hello vm" {
  257. t.Errorf("unexpected VM response object: %q", out)
  258. }
  259. if gotMethod != "POST" || gotBody != "vm-body" {
  260. t.Errorf("request not sent as expected: method=%q body=%q", gotMethod, gotBody)
  261. }
  262. }