engine_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. package playground
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "encoding/json"
  6. "image"
  7. "image/color"
  8. "image/png"
  9. "strings"
  10. "testing"
  11. "time"
  12. )
  13. // run is a helper: a WebApp script with the given code and drive.
  14. func runCode(t *testing.T, code string, files []File, mod func(*Request)) *Result {
  15. t.Helper()
  16. req := Request{Script: "web:/Playground/main.agi", Code: code, Files: files, TimeoutSec: 5}
  17. if mod != nil {
  18. mod(&req)
  19. }
  20. return Run(req, Hooks{})
  21. }
  22. func TestResponses(t *testing.T) {
  23. cases := []struct {
  24. name, code, want, ctype string
  25. }{
  26. {"sendResp", `sendResp("hi")`, "hi", "text/plain"},
  27. {"echo appends", `echo("a"); echo("b")`, "ab", "text/plain"},
  28. {"sendOK", `sendOK()`, "ok", "text/plain"},
  29. {"sendJSONResp object", `sendJSONResp({a:1})`, `{"a":1}`, "application/json"},
  30. {"sendJSONResp string", `sendJSONResp("[1]")`, `[1]`, "application/json"},
  31. {"globals", `sendResp(USERNAME + " " + __FILE__)`, "developer web/Playground/main.agi", "text/plain"},
  32. }
  33. for _, c := range cases {
  34. t.Run(c.name, func(t *testing.T) {
  35. res := runCode(t, c.code, nil, nil)
  36. if res.Error != nil {
  37. t.Fatalf("error: %+v", res.Error)
  38. }
  39. if res.Response != c.want || res.ContentType != c.ctype {
  40. t.Errorf("got %q (%s), want %q (%s)", res.Response, res.ContentType, c.want, c.ctype)
  41. }
  42. })
  43. }
  44. }
  45. func TestExitKeepsResponse(t *testing.T) {
  46. res := runCode(t, `sendResp("early"); exit(); sendResp("late")`, nil, nil)
  47. if !res.Exited || res.Response != "early" {
  48. t.Fatalf("exit: got %q exited=%v", res.Response, res.Exited)
  49. }
  50. }
  51. func TestScriptErrorAndTimeout(t *testing.T) {
  52. res := runCode(t, `var a = ; `, nil, nil)
  53. if res.Error == nil || res.Status != 500 {
  54. t.Fatalf("syntax error not reported: %+v", res)
  55. }
  56. res = runCode(t, `while(true){}`, nil, func(r *Request) { r.TimeoutSec = 1 })
  57. if res.Error == nil || res.Error.Kind != "timeout" {
  58. t.Fatalf("timeout not reported: %+v", res.Error)
  59. }
  60. }
  61. func TestConsoleAndRaiseError(t *testing.T) {
  62. res := runCode(t, `console.log("x", 1); requirelib("filelib"); filelib.readFile("user:/missing.txt");`, nil, nil)
  63. if len(res.Console) < 2 || res.Console[0].Text != "x 1" {
  64. t.Fatalf("console: %+v", res.Console)
  65. }
  66. if !strings.Contains(res.Console[1].Text, "[AGI] FileLibError: ") {
  67. t.Errorf("missing RaiseError log: %+v", res.Console[1])
  68. }
  69. if res.Error == nil || !strings.HasPrefix(res.Error.Message, "FileLibError: ") {
  70. t.Errorf("an uncaught failure should end the script with its error: %+v", res.Error)
  71. }
  72. }
  73. func TestFilelib(t *testing.T) {
  74. files := []File{
  75. {Path: "user:/Docs/a.txt", Data: []byte("hello")},
  76. {Path: "user:/Docs/b10.txt", Data: []byte("1234567890")},
  77. {Path: "user:/Docs/b2.txt", Data: []byte("12")},
  78. {Path: "user:/Docs/.hidden", Data: []byte("x")},
  79. }
  80. code := `requirelib("filelib");
  81. var out = {};
  82. out.read = filelib.readFile("user:/Docs/a.txt");
  83. out.write = filelib.writeFile("user:/Docs/new.txt", "abc");
  84. try { filelib.writeFile("user:/Nope/new.txt", "abc"); out.noParent = "wrote"; } catch(e) { out.noParent = e.name; }
  85. out.glob = filelib.glob("user:/Docs/*.txt");
  86. out.smart = filelib.glob("user:/Docs/b*.txt", "smart");
  87. out.size = filelib.filesize("user:/Docs/b10.txt");
  88. out.exists = filelib.fileExists("user:/Docs/a.txt");
  89. out.mkdir = filelib.mkdir("user:/Made/Deep");
  90. out.isDir = filelib.isDir("user:/Made");
  91. out.walk = filelib.walk("user:/Made", "folder");
  92. out.md5 = filelib.md5("user:/Docs/a.txt");
  93. out.readdir = filelib.readdir("user:/Docs").map(function(e){ return e.Filename; });
  94. out.root = filelib.rootName("user:/");
  95. out.del = filelib.deleteFile("user:/Docs/a.txt");
  96. out.gone = filelib.fileExists("user:/Docs/a.txt");
  97. out.hex = filelib.readBinaryFile("user:/Docs/b2.txt");
  98. out.b64 = filelib.readBinaryFile("user:/Docs/b2.txt", "base64");
  99. out.writeBin = filelib.writeBinaryFile("user:/Docs/bin.dat", "AAH/", "base64");
  100. out.binBack = filelib.readBinaryFile("user:/Docs/bin.dat", "hex");
  101. try { filelib.writeBinaryFile("user:/Docs/bad.dat", "zz", "hex"); out.badHex = "wrote"; } catch(e) { out.badHex = e.name; }
  102. try { filelib.readFile("web:/Playground/main.agi"); out.web = "read"; } catch(e) { out.web = e.name; }
  103. try { filelib.readFile("user:/missing.txt"); out.missing = "read"; } catch(e) { out.missing = e.name; }
  104. out.isDirMissing = filelib.isDir("user:/none");
  105. sendJSONResp(out);`
  106. res := runCode(t, code, files, nil)
  107. if res.Error != nil {
  108. t.Fatalf("error: %+v", res.Error)
  109. }
  110. var out map[string]interface{}
  111. if err := json.Unmarshal([]byte(res.Response), &out); err != nil {
  112. t.Fatal(err)
  113. }
  114. checks := map[string]string{
  115. "read": "hello", "write": "true", "noParent": "FileLibError", "size": "10", "exists": "true",
  116. "mkdir": "true", "isDir": "true", "md5": "5d41402abc4b2a76b9719d911017c592", "root": "User",
  117. "del": "true", "gone": "false", "hex": "3132", "web": "PermissionDenied", "isDirMissing": "false",
  118. "b64": "MTI=", "writeBin": "true", "binBack": "0001ff", "badHex": "FileLibError", "missing": "FileLibError",
  119. "glob": "[user:/Docs/a.txt user:/Docs/b10.txt user:/Docs/b2.txt user:/Docs/new.txt]",
  120. "smart": "[user:/Docs/b2.txt user:/Docs/b10.txt]",
  121. "walk": "[user:/Made user:/Made/Deep]",
  122. "readdir": "[a.txt b10.txt b2.txt new.txt]",
  123. }
  124. for k, want := range checks {
  125. if got := fmtValue(out[k]); got != want {
  126. t.Errorf("%s = %s, want %s", k, got, want)
  127. }
  128. }
  129. written := map[string]bool{}
  130. for _, f := range res.Written {
  131. written[f.Path] = true
  132. }
  133. if !written["user:/Docs/new.txt"] || !written["user:/Made/Deep"] {
  134. t.Errorf("changes missing: %+v", res.Written)
  135. }
  136. if len(res.Removed) != 1 || res.Removed[0] != "user:/Docs/a.txt" {
  137. t.Errorf("removed = %v", res.Removed)
  138. }
  139. }
  140. func fmtValue(v interface{}) string {
  141. switch x := v.(type) {
  142. case []interface{}:
  143. parts := make([]string, len(x))
  144. for i, e := range x {
  145. parts[i] = fmtValue(e)
  146. }
  147. return "[" + strings.Join(parts, " ") + "]"
  148. case float64:
  149. b, _ := json.Marshal(x)
  150. return string(b)
  151. case bool:
  152. if x {
  153. return "true"
  154. }
  155. return "false"
  156. case string:
  157. return x
  158. }
  159. b, _ := json.Marshal(v)
  160. return string(b)
  161. }
  162. func TestRelativePathsOnlyForDriveScripts(t *testing.T) {
  163. files := []File{{Path: "user:/Scripts/data.txt", Data: []byte("near")}}
  164. code := `requirelib("filelib"); sendResp(filelib.readFile("data.txt"));`
  165. res := Run(Request{Script: "user:/Scripts/run.agi", Code: code, Files: files, TimeoutSec: 5}, Hooks{})
  166. if res.Response != "near" || res.Mode != "serverless" {
  167. t.Errorf("drive script: %q (%s)", res.Response, res.Mode)
  168. }
  169. res = runCode(t, `requirelib("filelib"); try { filelib.readFile("data.txt"); sendResp("read"); } catch(e) { sendResp(e.name); }`, files, nil)
  170. if res.Response != "PermissionDenied" {
  171. t.Errorf("WebApp script reading a relative path: %q", res.Response)
  172. }
  173. }
  174. func TestRequestModes(t *testing.T) {
  175. res := runCode(t, `sendResp(name + "/" + typeof getPara)`, nil, func(r *Request) {
  176. r.Form = map[string]string{"name": "amy"}
  177. })
  178. if res.Response != "amy/undefined" {
  179. t.Errorf("webapp form: %q", res.Response)
  180. }
  181. res = runCode(t, `sendResp(a + POST_data)`, nil, func(r *Request) {
  182. r.ContentType = "application/json"
  183. r.Body = `{"a":"x"}`
  184. })
  185. if res.Response != `x{"a":"x"}` {
  186. t.Errorf("webapp json: %q", res.Response)
  187. }
  188. res = Run(Request{Script: "user:/s.agi", Code: `sendResp(REQ_METHOD + getPara("q") + postPara("p") + readBody())`,
  189. Method: "POST", Query: map[string]string{"q": "1"}, Form: map[string]string{"p": "2"}, TimeoutSec: 5}, Hooks{})
  190. if res.Response != "POST12p=2" {
  191. t.Errorf("serverless: %q", res.Response)
  192. }
  193. }
  194. func TestDatabaseState(t *testing.T) {
  195. code := `newDBTableIfNotExists("notes");
  196. writeDBItem("notes", "k", "v");
  197. var bad;
  198. try { writeDBItem("auth", "k", "v"); bad = "wrote"; } catch(e) { bad = e.name; }
  199. sendJSONResp({v: readDBItem("notes", "k"), all: listDBTable("notes"), bad: bad, missing: readDBItem("none", "k")});`
  200. res := runCode(t, code, nil, nil)
  201. if res.Response != `{"all":{"k":"v"},"bad":"AGIError","missing":false,"v":"v"}` {
  202. t.Errorf("db: %s", res.Response)
  203. }
  204. if res.State.DB["notes"]["k"] != "v" {
  205. t.Fatalf("state not returned: %+v", res.State.DB)
  206. }
  207. res = runCode(t, `sendResp(readDBItem("notes", "k"))`, nil, func(r *Request) { r.State = res.State })
  208. if res.Response != "v" {
  209. t.Errorf("state not reused: %q", res.Response)
  210. }
  211. }
  212. func TestIncludesAndExecd(t *testing.T) {
  213. files := []File{
  214. {Path: "web:/Playground/lib.js", Data: []byte(`function twice(x){ return x * 2; }`)},
  215. {Path: "web:/Playground/child.agi", Data: []byte(`requirelib("filelib"); filelib.writeFile("user:/child.txt", PARENT_PAYLOAD + PARENT_DETACHED);`)},
  216. }
  217. res := runCode(t, `includes("lib.js"); execd("child.agi", "hi"); sendResp(twice(21));`, files, nil)
  218. if res.Response != "42" {
  219. t.Errorf("includes: %q", res.Response)
  220. }
  221. found := false
  222. for _, f := range res.Written {
  223. if f.Path == "user:/child.txt" && string(f.Data) == "hitrue" {
  224. found = true
  225. }
  226. }
  227. if !found {
  228. t.Errorf("execd child did not run: %+v", res.Written)
  229. }
  230. res = Run(Request{Script: "user:/x.agi", Code: `sendResp(typeof includes)`, TimeoutSec: 5}, Hooks{})
  231. if res.Response != "undefined" {
  232. t.Errorf("includes should only exist for WebApp scripts, got %q", res.Response)
  233. }
  234. }
  235. func TestUserFunctions(t *testing.T) {
  236. code := `var r = [userIsAdmin(), createUser("bob", "pw", "user"), userExists("bob"), removeUser("bob"), userExists("bob")]; sendResp(r.join(","));`
  237. res := runCode(t, code, nil, func(r *Request) { r.User.Admin = true })
  238. if res.Response != "true,true,true,true,false" {
  239. t.Errorf("admin: %q", res.Response)
  240. }
  241. res = runCode(t, `try { createUser("bob","pw","user"); sendResp("created"); } catch(e) { sendResp(e.name + ": " + e.message); }`, nil, nil)
  242. if res.Response != "AGIError: Permission Denied: createUser require admin permission" {
  243. t.Errorf("non-admin createUser: %q", res.Response)
  244. }
  245. }
  246. func TestHTTPMock(t *testing.T) {
  247. mocks := Mocks{HTTP: HTTPMock{Rules: []HTTPRule{
  248. {Method: "GET", URL: "https://api.example.com/users/*", Body: `{"id":7}`},
  249. {Method: "POST", URL: "/example\\.com\\/echo$/", Status: 201, Body: "got {{body}}"},
  250. {URL: "https://down.example.com/", Error: "dial tcp: connection refused"},
  251. }}}
  252. code := `requirelib("http");
  253. var a = JSON.parse(http.get("https://api.example.com/users/7")).id;
  254. var b = http.request({url: "https://example.com/echo", method: "POST", json: {x: 1}});
  255. var c, d;
  256. try { http.request({url: "https://down.example.com/"}); } catch(err) { c = err.name + ": " + err.message; }
  257. try { http.get("https://nowhere.example.com/"); } catch(err) { d = err.name; }
  258. var e = http.getCode("https://api.example.com/users/1");
  259. sendJSONResp({a: a, bStatus: b.status, bBody: b.body, cErr: c, d: d, e: e});`
  260. res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
  261. want := `{"a":7,"bBody":"got {\"x\":1}","bStatus":201,"cErr":"HTTPError: dial tcp: connection refused","d":"HTTPError","e":200}`
  262. if res.Response != want {
  263. t.Errorf("http:\n got %s\nwant %s", res.Response, want)
  264. }
  265. if len(res.Calls) != 5 {
  266. t.Errorf("calls recorded: %d", len(res.Calls))
  267. }
  268. }
  269. func TestLLMMock(t *testing.T) {
  270. mocks := Mocks{LLM: LLMMock{Mode: "rules", Reply: "fallback", Rules: []TextRule{{Match: "capital", Reply: "Paris"}}, ChunkSize: 2, ChunkDelayMs: 1}}
  271. code := `requirelib("llm");
  272. var parts = [];
  273. var s = llm.streamRequest([{role:"user", content:"hello"}], {}, function(d){ parts.push(d.content); });
  274. sendJSONResp({a: llm.chat("What is the capital of France?"), b: llm.request([{role:"user",content:"hi"}]).choices[0].message.content, s: parts.join("|"), u: llm.usage().totalRequests});`
  275. res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
  276. if res.Response != `{"a":"Paris","b":"fallback","s":"fa|ll|ba|ck","u":3}` {
  277. t.Errorf("llm: %s", res.Response)
  278. }
  279. mocks.LLM.Error = "quota exceeded"
  280. res = runCode(t, `requirelib("llm"); try { llm.chat("x") } catch(e) { sendResp(e.name + ": " + e.message) }`, nil, func(r *Request) { r.Mocks = mocks })
  281. if res.Response != "LLMError: quota exceeded" {
  282. t.Errorf("llm error: %q", res.Response)
  283. }
  284. }
  285. func TestCNNMock(t *testing.T) {
  286. files := []File{{Path: "user:/cat.jpg", Data: []byte("x")}}
  287. code := `requirelib("cnn");
  288. var r = cnn.classify("user:/cat.jpg", {top_k: 3});
  289. var j = cnn.detect("user:/cat.jpg", {async: true});
  290. var j2 = cnn.job(j.id);
  291. var a = cnn.analyze("user:/cat.jpg", ["detect", "faces"]);
  292. try { cnn.classify("user:/none.jpg") } catch(e) { var err = e.name }
  293. sendJSONResp({label: r.data[0].label, status: j2.status, n: j2.result.data.length, faces: a.results.faces.object, err: err});`
  294. res := runCode(t, code, files, nil)
  295. if res.Response != `{"err":"CNNError","faces":"face_detection","label":"tabby cat","n":2,"status":"succeeded"}` {
  296. t.Errorf("cnn: %s (%+v)", res.Response, res.Error)
  297. }
  298. }
  299. func TestSQLiteAndGenericMocks(t *testing.T) {
  300. mocks := Mocks{
  301. SQLite: []SQLRule{{Fn: "query", Match: "FROM notes", Result: `[{"id":1,"title":"a"}]`}},
  302. Generic: map[string]string{"git.status": `{"branch":"main"}`},
  303. }
  304. code := `requirelib("sqlite"); requirelib("git");
  305. var db = sqlite.open("user:/app.db");
  306. var rows = db.query("SELECT * FROM notes");
  307. var ins = db.exec("INSERT INTO notes VALUES (?)", ["x"]);
  308. sendJSONResp({rows: rows, ins: ins.rowsAffected, git: git.status("user:/repo").branch, none: git.log("user:/repo")});`
  309. res := runCode(t, code, nil, func(r *Request) {
  310. r.Mocks = mocks
  311. r.Catalog = map[string][]string{"git": {"git.status", "git.log"}}
  312. })
  313. if res.Response != `{"git":"main","ins":0,"none":null,"rows":[{"id":1,"title":"a"}]}` {
  314. t.Errorf("mocks: %s (%+v)", res.Response, res.Error)
  315. }
  316. res = runCode(t, `sendResp(requirelib("nosuchlib"))`, nil, nil)
  317. if res.Response != "false" {
  318. t.Errorf("unknown lib: %q", res.Response)
  319. }
  320. }
  321. func TestWebsocket(t *testing.T) {
  322. mocks := Mocks{WS: WSMock{Script: []WSScripted{{AfterMs: 10, Text: "ping"}, {AfterMs: 10, Text: "bye"}}, CloseAfterMs: 10}}
  323. code := `requirelib("websocket");
  324. websocket.upgrade(10);
  325. var got = [];
  326. while (true) {
  327. var m = websocket.read(2000);
  328. if (m === false) break;
  329. if (m === null) { got.push("timeout"); break; }
  330. got.push(m);
  331. websocket.send("echo:" + m);
  332. }
  333. sendResp(got.join(","));`
  334. res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
  335. if res.Response != "ping,bye" {
  336. t.Errorf("ws read: %q", res.Response)
  337. }
  338. var out []string
  339. for _, f := range res.WS {
  340. if f.Dir == "out" {
  341. out = append(out, f.Text)
  342. }
  343. }
  344. if strings.Join(out, ",") != "echo:ping,echo:bye" {
  345. t.Errorf("ws frames: %+v", res.WS)
  346. }
  347. live := make(chan WSIn, 2)
  348. live <- WSIn{Text: "live"}
  349. code = `requirelib("websocket"); websocket.upgrade(10);
  350. var got = "";
  351. websocket.onMessage = function(m){ got += m; };
  352. delay(200);
  353. sendResp(got);`
  354. res = runCode(t, code, nil, func(r *Request) { r.Live = live })
  355. if res.Response != "live" {
  356. t.Errorf("onMessage pump: %q", res.Response)
  357. }
  358. }
  359. func pngBytes(w, h int) []byte {
  360. img := image.NewRGBA(image.Rect(0, 0, w, h))
  361. for y := 0; y < h; y++ {
  362. for x := 0; x < w; x++ {
  363. img.Set(x, y, color.RGBA{uint8(x), uint8(y), 128, 255})
  364. }
  365. }
  366. var buf bytes.Buffer
  367. png.Encode(&buf, img)
  368. return buf.Bytes()
  369. }
  370. func TestImagelib(t *testing.T) {
  371. files := []File{{Path: "user:/a.png", Data: pngBytes(200, 100)}}
  372. code := `requirelib("imagelib");
  373. var d = imagelib.getImageDimension("user:/a.png");
  374. imagelib.resizeImage("user:/a.png", "user:/small.jpg", 50, 0);
  375. var s = imagelib.getImageDimension("user:/small.jpg");
  376. imagelib.cropImage("user:/a.png", "user:/crop.png", 10, 10, 30, 20);
  377. var c = imagelib.getImageDimension("user:/crop.png");
  378. var p = imagelib.renderPreview("user:/a.png", "", 40, 40);
  379. sendResp([d, s, c, [p.width, p.height], p.dataURL.indexOf("data:image/jpeg")].join(";"));`
  380. res := runCode(t, code, files, nil)
  381. if res.Response != "200,100;50,25;30,20;40,20;0" {
  382. t.Errorf("imagelib: %q (%+v)", res.Response, res.Error)
  383. }
  384. }
  385. func TestZiplib(t *testing.T) {
  386. files := []File{{Path: "user:/src/a.txt", Data: []byte("A")}, {Path: "user:/src/sub/b.txt", Data: []byte("B")}}
  387. code := `requirelib("ziplib"); requirelib("filelib");
  388. var ok = ziplib.createZipFile("user:/src", "user:/out.zip");
  389. var valid = ziplib.isValidZipFile("user:/out.zip");
  390. ziplib.extractZipFile("user:/out.zip", "user:/x");
  391. var tgz = ziplib.createAnyZipFile(["user:/src/a.txt"], "user:/a.tar.gz");
  392. ziplib.extractAnyFile("user:/a.tar.gz", "user:/y");
  393. var tree = JSON.parse(ziplib.listZipFileContents("user:/out.zip"));
  394. sendResp([ok, valid, filelib.readFile("user:/x/src/sub/b.txt"), tgz, filelib.readFile("user:/y/a.txt"), tree.children.src.isDir].join(","));`
  395. res := runCode(t, code, files, nil)
  396. if res.Response != "true,true,B,true,A,true" {
  397. t.Errorf("ziplib: %q (%+v) %+v", res.Response, res.Error, res.Console)
  398. }
  399. var zipData []byte
  400. for _, f := range res.Written {
  401. if f.Path == "user:/out.zip" {
  402. zipData = f.Data
  403. }
  404. }
  405. zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
  406. if err != nil {
  407. t.Fatal(err)
  408. }
  409. var names []string
  410. for _, f := range zr.File {
  411. names = append(names, f.Name)
  412. }
  413. if strings.Join(names, ",") != "src/,src/a.txt,src/sub/,src/sub/b.txt" {
  414. t.Errorf("zip entries: %v", names)
  415. }
  416. }
  417. func TestZipSlipRefused(t *testing.T) {
  418. var buf bytes.Buffer
  419. zw := zip.NewWriter(&buf)
  420. w, _ := zw.Create("../../evil.txt")
  421. w.Write([]byte("x"))
  422. zw.Close()
  423. files := []File{{Path: "user:/bad.zip", Data: buf.Bytes()}}
  424. res := runCode(t, `requirelib("ziplib"); try { ziplib.extractZipFile("user:/bad.zip", "user:/out"); sendResp("extracted"); } catch(e) { sendResp(e.name); }`, files, nil)
  425. if res.Response != "ZipLibError" {
  426. t.Errorf("zip slip extracted: %q", res.Response)
  427. }
  428. for _, f := range res.Written {
  429. if strings.Contains(f.Path, "evil") {
  430. t.Errorf("wrote %s", f.Path)
  431. }
  432. }
  433. }
  434. func TestShareSchedulerNotification(t *testing.T) {
  435. files := []File{{Path: "user:/a.txt", Data: []byte("x")}, {Path: "web:/Playground/task.agi", Data: []byte("")}}
  436. code := `requirelib("share"); requirelib("scheduler"); requirelib("notification");
  437. var id = share.shareFile("user:/a.txt", 0);
  438. var r = [share.checkShareExists(id), share.fileIsShared("user:/a.txt"), share.getFileShareUUID("user:/a.txt") == id];
  439. r.push(scheduler.register("t1", "Playground", 3600, "desc", "task.agi"));
  440. r.push(scheduler.registered("t1", "Playground"));
  441. r.push(notification.send("Hello", "World", notification.PRIORITY_HIGH));
  442. sendResp(r.join(","));`
  443. res := runCode(t, code, files, nil)
  444. if res.Response != "true,true,true,true,true,true" {
  445. t.Errorf("share/scheduler/notification: %q %+v", res.Response, res.Console)
  446. }
  447. if len(res.State.Shares) != 1 || len(res.State.Tasks) != 1 || len(res.Notifications) != 1 {
  448. t.Errorf("state: %+v notifications: %+v", res.State, res.Notifications)
  449. }
  450. }
  451. // TestLibraryErrors checks that each library throws its own named error,
  452. // which a script can catch, and logs it
  453. func TestLibraryErrors(t *testing.T) {
  454. files := []File{{Path: "user:/a.txt", Data: []byte("x")}, {Path: "web:/Playground/task.agi", Data: []byte("")}}
  455. cases := []struct {
  456. name, lib, call, want string
  457. }{
  458. {"appdata escape", "appdata", `appdata.readFile("../../secret")`, "AppdataError: Path escape detected"},
  459. {"appdata missing", "appdata", `appdata.readFile("Playground/none.txt")`, "AppdataError: File not exists"},
  460. {"appdata no dir", "appdata", `appdata.listDir("Nowhere")`, "AppdataError: Directory not exists"},
  461. {"share missing file", "share", `share.shareFile("user:/none.txt", 0)`, "ShareError: share failed: file not exists"},
  462. {"share remove unknown", "share", `share.removeShare("nope")`, "ShareError: failed to remove share: share UUID not exists"},
  463. {"notification no title", "notification", `notification.send()`, "NotificationError: title is undefined"},
  464. {"notification not admin", "notification", `notification.sendToUser("bob", "hi")`, "NotificationError: Permission Denied: sendToUser require admin permission"},
  465. {"scheduler no app", "scheduler", `scheduler.register("t1")`, "SchedulerError: app name not given"},
  466. {"scheduler no script", "scheduler", `scheduler.register("t1", "Playground", 60, "", "none.agi")`, "SchedulerError: app script not found: web:/Playground/none.agi"},
  467. {"scheduler unregister unknown", "scheduler", `scheduler.unregister("nope")`, "SchedulerError: job not found: nope"},
  468. {"websocket refused", "websocket", `websocket.upgrade(10)`, "WebSocketError: websocket: the client did not ask for a WebSocket upgrade"},
  469. }
  470. for _, c := range cases {
  471. code := `requirelib("` + c.lib + `"); try { ` + c.call + `; sendResp("no error"); } catch(e) { sendResp(e.name + ": " + e.message); }`
  472. res := runCode(t, code, files, func(r *Request) { r.Mocks.WS.Refuse = true })
  473. if res.Response != c.want {
  474. t.Errorf("%s: got %q, want %q", c.name, res.Response, c.want)
  475. }
  476. logged := false
  477. for _, l := range res.Console {
  478. if strings.Contains(l.Text, "[AGI] "+c.want) {
  479. logged = true
  480. }
  481. }
  482. if !logged {
  483. t.Errorf("%s: error not logged: %+v", c.name, res.Console)
  484. }
  485. }
  486. //Answers that are not failures stay values
  487. code := `requirelib("share"); requirelib("websocket"); requirelib("imagelib");
  488. sendJSONResp([share.getFileShareUUID("user:/a.txt"), share.checkSharePermission("nope"), websocket.send("x"), imagelib.loadThumbString("user:/a.txt")]);`
  489. res := runCode(t, code, files, nil)
  490. if res.Response != `[null,null,false,false]` {
  491. t.Errorf("answers: %s %+v", res.Response, res.Error)
  492. }
  493. }
  494. func TestStreamingHooks(t *testing.T) {
  495. var lines []string
  496. Run(Request{Script: "web:/P/x.agi", Code: `console.log("a"); console.log("b");`, TimeoutSec: 5}, Hooks{Log: func(l LogLine) { lines = append(lines, l.Text) }})
  497. if strings.Join(lines, "") != "ab" {
  498. t.Errorf("hooks: %v", lines)
  499. }
  500. }
  501. func TestDelay(t *testing.T) {
  502. start := time.Now()
  503. runCode(t, `delay(120)`, nil, nil)
  504. if time.Since(start) < 100*time.Millisecond {
  505. t.Errorf("delay did not wait")
  506. }
  507. }