agi.file_test.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package agi
  2. import (
  3. "bytes"
  4. "os"
  5. "path/filepath"
  6. "testing"
  7. "time"
  8. "github.com/robertkrimen/otto"
  9. "imuslab.com/arozos/mod/agi/static"
  10. "imuslab.com/arozos/mod/filesystem"
  11. "imuslab.com/arozos/mod/filesystem/abstractions/localfs"
  12. "imuslab.com/arozos/mod/storage"
  13. user "imuslab.com/arozos/mod/user"
  14. )
  15. // newFsTestUser returns a user whose only storage is a read-write local file
  16. // system in a temporary folder, reachable as "test:/". The public hierarchy
  17. // keeps quota bookkeeping (which needs a database) out of the way.
  18. func newFsTestUser(t *testing.T) (*user.User, string) {
  19. t.Helper()
  20. dir := t.TempDir()
  21. fsh := &filesystem.FileSystemHandler{
  22. Name: "test",
  23. UUID: "test",
  24. Path: dir + "/",
  25. Hierarchy: "public",
  26. InitiationTime: time.Now().Unix(),
  27. FileSystemAbstraction: localfs.NewLocalFileSystemAbstraction("test", dir+"/", "public", false),
  28. Filesystem: "ext4",
  29. }
  30. u := &user.User{
  31. Username: "alice",
  32. HomeDirectories: &storage.StoragePool{
  33. Owner: "alice",
  34. Storages: []*filesystem.FileSystemHandler{fsh},
  35. },
  36. }
  37. return u, dir
  38. }
  39. // newFileLibTestVM returns a VM with filelib loaded for a user from newFsTestUser.
  40. func newFileLibTestVM(t *testing.T) (*otto.Otto, string) {
  41. t.Helper()
  42. u, dir := newFsTestUser(t)
  43. vm := otto.New()
  44. minimalGateway().injectFileLibFunctions(&static.AgiLibInjectionPayload{VM: vm, User: u})
  45. return vm, dir
  46. }
  47. // Scripts reach the library through the filelib object; a function that is
  48. // registered but never attached to it is undefined for them.
  49. func TestInjectFileLib_JSObjectExposed(t *testing.T) {
  50. vm, _ := newFileLibTestVM(t)
  51. present := []string{
  52. "writeFile", "readFile", "deleteFile", "walk", "glob", "aglob",
  53. "filesize", "fileExists", "isDir", "md5", "mkdir", "mtime",
  54. "rootName", "readdir", "readBinaryFile", "writeBinaryFile",
  55. }
  56. for _, fn := range present {
  57. val, err := vm.Run(`typeof filelib.` + fn)
  58. if err != nil {
  59. t.Fatalf("evaluating filelib.%s: %v", fn, err)
  60. }
  61. if s, _ := val.ToString(); s != "function" {
  62. t.Errorf("filelib.%s should be a function, got %q", fn, s)
  63. }
  64. }
  65. }
  66. func TestFileLibWriteBinaryFile(t *testing.T) {
  67. cases := []struct {
  68. name string
  69. hex string
  70. want bool
  71. wantBytes []byte // nil means no file is written
  72. }{
  73. {"ascii text", "68656c6c6f", true, []byte("hello")},
  74. {"zero and high bytes", "00ff10fe", true, []byte{0x00, 0xff, 0x10, 0xfe}},
  75. {"upper case hex", "DEADBEEF", true, []byte{0xde, 0xad, 0xbe, 0xef}},
  76. {"empty content", "", true, []byte{}},
  77. {"invalid hex", "zz", false, nil},
  78. {"odd length hex", "abc", false, nil},
  79. }
  80. for _, c := range cases {
  81. t.Run(c.name, func(t *testing.T) {
  82. vm, dir := newFileLibTestVM(t)
  83. vm.Set("hexContent", c.hex)
  84. val, err := vm.Run(`filelib.writeBinaryFile("test:/out.bin", hexContent)`)
  85. if err != nil {
  86. t.Fatalf("writeBinaryFile: %v", err)
  87. }
  88. if got, _ := val.ToBoolean(); got != c.want {
  89. t.Fatalf("writeBinaryFile returned %v, want %v", got, c.want)
  90. }
  91. content, err := os.ReadFile(filepath.Join(dir, "out.bin"))
  92. if c.wantBytes == nil {
  93. if err == nil {
  94. t.Errorf("a failed write left a file behind: %x", content)
  95. }
  96. return
  97. }
  98. if err != nil {
  99. t.Fatalf("file not written: %v", err)
  100. }
  101. if !bytes.Equal(content, c.wantBytes) {
  102. t.Errorf("file holds %x, want %x", content, c.wantBytes)
  103. }
  104. })
  105. }
  106. }
  107. func TestFileLibReadBinaryFile(t *testing.T) {
  108. cases := []struct {
  109. name string
  110. content []byte // nil means the file does not exist
  111. want string
  112. wantNil bool
  113. }{
  114. {"ascii text", []byte("hello"), "68656c6c6f", false},
  115. {"zero and high bytes", []byte{0x00, 0xff, 0x10, 0xfe}, "00ff10fe", false},
  116. {"empty file", []byte{}, "", false},
  117. {"missing file", nil, "", true},
  118. }
  119. for _, c := range cases {
  120. t.Run(c.name, func(t *testing.T) {
  121. vm, dir := newFileLibTestVM(t)
  122. if c.content != nil {
  123. if err := os.WriteFile(filepath.Join(dir, "in.bin"), c.content, 0644); err != nil {
  124. t.Fatalf("write fixture: %v", err)
  125. }
  126. }
  127. val, err := vm.Run(`filelib.readBinaryFile("test:/in.bin")`)
  128. if err != nil {
  129. t.Fatalf("readBinaryFile: %v", err)
  130. }
  131. if c.wantNil {
  132. if !val.IsNull() {
  133. t.Errorf("readBinaryFile of a missing file = %v, want null", val)
  134. }
  135. return
  136. }
  137. if got, _ := val.ToString(); got != c.want {
  138. t.Errorf("readBinaryFile = %q, want %q", got, c.want)
  139. }
  140. })
  141. }
  142. }
  143. // What writeBinaryFile writes, readBinaryFile reads back unchanged.
  144. func TestFileLibBinaryRoundTrip(t *testing.T) {
  145. vm, _ := newFileLibTestVM(t)
  146. val, err := vm.Run(`
  147. var data = "";
  148. for (var i = 0; i < 256; i++) {
  149. data += (i < 16 ? "0" : "") + i.toString(16);
  150. }
  151. filelib.writeBinaryFile("test:/all.bin", data) && filelib.readBinaryFile("test:/all.bin") === data;
  152. `)
  153. if err != nil {
  154. t.Fatalf("round trip: %v", err)
  155. }
  156. if ok, _ := val.ToBoolean(); !ok {
  157. t.Errorf("bytes 00-ff did not survive a write and read back")
  158. }
  159. }
  160. // Paths on storage the user has no access to are refused with an exception.
  161. func TestFileLibBinaryPermissionDenied(t *testing.T) {
  162. cases := []struct {
  163. name string
  164. script string
  165. }{
  166. {"read", `filelib.readBinaryFile("other:/x.bin")`},
  167. {"write", `filelib.writeBinaryFile("other:/x.bin", "00")`},
  168. }
  169. for _, c := range cases {
  170. t.Run(c.name, func(t *testing.T) {
  171. vm, _ := newFileLibTestVM(t)
  172. if _, err := vm.Run(c.script); err == nil {
  173. t.Errorf("%s on a storage outside the user's pool should throw", c.name)
  174. }
  175. })
  176. }
  177. }