agi.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. package agi
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/robertkrimen/otto"
  14. uuid "github.com/satori/go.uuid"
  15. "imuslab.com/arozos/mod/agi/static"
  16. apt "imuslab.com/arozos/mod/apt"
  17. "imuslab.com/arozos/mod/filesystem"
  18. "imuslab.com/arozos/mod/filesystem/arozfs"
  19. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  20. "imuslab.com/arozos/mod/git"
  21. "imuslab.com/arozos/mod/info/logger"
  22. "imuslab.com/arozos/mod/iot"
  23. "imuslab.com/arozos/mod/meetroom"
  24. notification "imuslab.com/arozos/mod/notification"
  25. "imuslab.com/arozos/mod/share"
  26. "imuslab.com/arozos/mod/sharedspace"
  27. "imuslab.com/arozos/mod/time/nightly"
  28. user "imuslab.com/arozos/mod/user"
  29. "imuslab.com/arozos/mod/utils"
  30. )
  31. /*
  32. ArOZ Online Javascript Gateway Interface (AGI)
  33. author: tobychui
  34. This script load plugins written in Javascript and run them in VM inside golang
  35. DO NOT CONFUSE PLUGIN WITH SUBSERVICE :))
  36. */
  37. var (
  38. AgiVersion string = "3.7" //Defination of the agi runtime version. Update this when new function is added
  39. //AGI Internal Error Standard
  40. errExitcall = errors.New("errExit")
  41. errTimeout = errors.New("errTimeout")
  42. // agiLogger is a stdout-only fallback used when no system-wide logger is
  43. // available. Scripts should use g.Option.Logger when present.
  44. agiLogger, _ = logger.NewTmpLogger()
  45. )
  46. type AgiPackage struct {
  47. InitRoot string //The initialization of the root for the module that request this package
  48. }
  49. type AgiSysInfo struct {
  50. //System information
  51. BuildVersion string
  52. InternalVersion string
  53. LoadedModule []string
  54. //System Handlers
  55. Logger *logger.Logger
  56. UserHandler *user.UserHandler
  57. ReservedTables []string
  58. PackageManager *apt.AptPackageManager
  59. ModuleRegisterParser func(string) error
  60. ModuleListProvider func(username string) string //Returns JSON of accessible modules for a user
  61. ExtIconRegisterParser func(ext, iconPath string) //Called when registerExtensionIcon() fires in an init.agi
  62. FileSystemRender *metadata.RenderHandler
  63. IotManager *iot.Manager
  64. ShareManager *share.Manager
  65. NightlyManager *nightly.TaskManager
  66. MeetRoomManager *meetroom.Manager //MeetRoom rooms for the meetroom lib (nil disables the lib)
  67. SharedSpaceManager *sharedspace.Manager //Shared collaboration spaces for the sharedspace lib (nil disables the lib)
  68. GitManager *git.Manager //Version control backend for the git lib (nil disables the lib)
  69. //NotificationSender routes a notification raised by an AGI script into the
  70. //ArozOS core notification system (nil disables the notification lib).
  71. NotificationSender func(*notification.NotificationPayload) error
  72. //Scanning Roots
  73. StartupRoot string
  74. ActivateScope []string
  75. TempFolderPath string
  76. }
  77. type Gateway struct {
  78. ReservedTables []string
  79. NightlyScripts []string
  80. //AllowAccessPkgs map[string][]AgiPackage
  81. LoadedAGILibrary map[string]AgiLibInjectionIntergface
  82. Option *AgiSysInfo
  83. endpointStats map[string]*EndpointStats // per-UUID execution statistics (in-memory)
  84. statsMux sync.RWMutex // guards endpointStats
  85. vmReg *vmRegistry // live VM lifecycle registry
  86. }
  87. func NewGateway(option AgiSysInfo) (*Gateway, error) {
  88. //Handle startup registration of ajgi modules
  89. gatewayObject := Gateway{
  90. ReservedTables: option.ReservedTables,
  91. NightlyScripts: []string{},
  92. LoadedAGILibrary: map[string]AgiLibInjectionIntergface{},
  93. Option: &option,
  94. endpointStats: make(map[string]*EndpointStats),
  95. vmReg: newVMRegistry(),
  96. }
  97. //Start all WebApps Registration
  98. gatewayObject.InitiateAllWebAppModules()
  99. gatewayObject.RegisterNightlyOperations()
  100. //Load all the other libs entry points into the memoary
  101. gatewayObject.LoadAllFunctionalModules()
  102. return &gatewayObject, nil
  103. }
  104. func (g *Gateway) RegisterNightlyOperations() {
  105. g.Option.NightlyManager.RegisterNightlyTask(func() {
  106. //This function will execute nightly
  107. for _, scriptFile := range g.NightlyScripts {
  108. if static.IsValidAGIScript(scriptFile) {
  109. //Valid script file. Execute it with system
  110. for _, username := range g.Option.UserHandler.GetAuthAgent().ListUsers() {
  111. userinfo, err := g.Option.UserHandler.GetUserInfoFromUsername(username)
  112. if err != nil {
  113. continue
  114. }
  115. if static.CheckUserAccessToScript(userinfo, scriptFile, "") {
  116. //This user can access the module that provide this script.
  117. //Execute this script on his account.
  118. logger.PrintAndLog("Agi", "[AGI_Nightly] WIP ("+scriptFile+")", nil)
  119. }
  120. }
  121. } else {
  122. //Invalid script. Skipping
  123. logger.PrintAndLog("Agi", "[AGI_Nightly] Invalid script file: "+scriptFile, nil)
  124. }
  125. }
  126. })
  127. }
  128. func (g *Gateway) InitiateAllWebAppModules() {
  129. startupScripts, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(g.Option.StartupRoot)) + "/*/init.agi")
  130. for _, script := range startupScripts {
  131. scriptContentByte, _ := os.ReadFile(script)
  132. scriptContent := string(scriptContentByte)
  133. logger.PrintAndLog("Agi", "[AGI] Gateway script loaded ("+script+")", nil)
  134. //Create a new vm for this request
  135. vm := otto.New()
  136. //Only allow non user based operations
  137. g.injectStandardLibs(vm, script, "./web/")
  138. g.injectAppdataLibFunctions(&static.AgiLibInjectionPayload{
  139. VM: vm,
  140. })
  141. _, err := vm.Run(scriptContent)
  142. if err != nil {
  143. logger.PrintAndLog("Agi", "[AGI] Load Failed: "+script+". Skipping.", nil)
  144. logger.PrintAndLog("Agi", fmt.Sprint(err), nil)
  145. continue
  146. }
  147. }
  148. }
  149. func (g *Gateway) RunScript(script string) error {
  150. //Create a new vm for this request
  151. vm := otto.New()
  152. //Only allow non user based operations
  153. g.injectStandardLibs(vm, "", "./web/")
  154. _, err := vm.Run(script)
  155. if err != nil {
  156. logger.PrintAndLog("Agi", fmt.Sprint("[AGI] Script Execution Failed: ", err.Error()), nil)
  157. return err
  158. }
  159. return nil
  160. }
  161. func (g *Gateway) RaiseError(err error) {
  162. if err == nil {
  163. return
  164. }
  165. logger.PrintAndLog("Agi", "[AGI] Runtime Error "+err.Error(), nil)
  166. //To be implemented
  167. }
  168. // Check if this table is restricted table. Return true if the access is valid
  169. func (g *Gateway) filterDBTable(tablename string, existsCheck bool) bool {
  170. //Check if table is restricted
  171. if utils.StringInArray(g.ReservedTables, tablename) {
  172. return false
  173. }
  174. //Check if table exists
  175. if existsCheck {
  176. if !g.Option.UserHandler.GetDatabase().TableExists(tablename) {
  177. return false
  178. }
  179. }
  180. return true
  181. }
  182. // Handle request from RESTFUL API
  183. func (g *Gateway) APIHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  184. scriptContent, err := utils.PostPara(r, "script")
  185. if err != nil {
  186. w.WriteHeader(http.StatusBadRequest)
  187. w.Write([]byte("400 - Bad Request (Missing script content)"))
  188. return
  189. }
  190. g.ExecuteAGIScript(scriptContent, nil, "", "", w, r, thisuser)
  191. }
  192. // Handle user requests
  193. func (g *Gateway) InterfaceHandler(w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  194. //Get user object from the request
  195. //startupRoot := g.Option.StartupRoot
  196. //startupRoot = filepath.ToSlash(filepath.Clean(startupRoot))
  197. //Get the script files for the plugin
  198. scriptFile, err := utils.GetPara(r, "script")
  199. if err != nil {
  200. w.WriteHeader(http.StatusInternalServerError)
  201. w.Write([]byte("500 - Internal Server Error: Invalid script path"))
  202. return
  203. }
  204. scriptFile = static.SpecialURIDecode(scriptFile)
  205. //Check if the script path exists
  206. scriptExists := false
  207. scriptScope := "./web/"
  208. for _, thisScope := range g.Option.ActivateScope {
  209. thisScope = arozfs.ToSlash(filepath.Clean(thisScope))
  210. if utils.FileExists(arozfs.ToSlash(filepath.Join(thisScope, scriptFile))) {
  211. scriptExists = true
  212. scriptFile = arozfs.ToSlash(filepath.Join(thisScope, scriptFile))
  213. scriptScope = thisScope
  214. break
  215. }
  216. }
  217. if !scriptExists {
  218. w.WriteHeader(http.StatusInternalServerError)
  219. w.Write([]byte("500 - Internal Server Error: Script not exists"))
  220. return
  221. }
  222. //Check for user permission on this module
  223. moduleName := static.GetScriptRoot(scriptFile, scriptScope)
  224. if !thisuser.GetModuleAccessPermission(moduleName) {
  225. w.WriteHeader(http.StatusForbidden)
  226. if g.Option.BuildVersion == "development" {
  227. w.Write([]byte("403 Forbidden: User do not have permission to access " + moduleName))
  228. } else {
  229. w.Write([]byte("403 Forbidden"))
  230. }
  231. return
  232. }
  233. //Check the given file is actually agi script
  234. if !(filepath.Ext(scriptFile) == ".agi" || filepath.Ext(scriptFile) == ".js") {
  235. w.WriteHeader(http.StatusForbidden)
  236. if g.Option.BuildVersion == "development" {
  237. w.Write([]byte("AGI script must have file extension of .agi or .js"))
  238. } else {
  239. w.Write([]byte("403 Forbidden"))
  240. }
  241. return
  242. }
  243. //Get the content of the script
  244. scriptContentByte, err := os.ReadFile(scriptFile)
  245. if err != nil {
  246. w.WriteHeader(http.StatusInternalServerError)
  247. w.Write([]byte("500 - Internal Server Error: Script load error =>" + err.Error()))
  248. return
  249. }
  250. scriptContent := string(scriptContentByte)
  251. g.ExecuteAGIScript(scriptContent, nil, scriptFile, scriptScope, w, r, thisuser)
  252. }
  253. /*
  254. Executing the given AGI Script contents. Requires:
  255. scriptContent: The AGI command sequence
  256. scriptFile: The filepath of the script file
  257. scriptScope: The scope of the script file, aka the module base path
  258. w / r : Web request and response writer
  259. thisuser: userObject
  260. */
  261. func (g *Gateway) ExecuteAGIScript(scriptContent string, fsh *filesystem.FileSystemHandler, scriptFile string, scriptScope string, w http.ResponseWriter, r *http.Request, thisuser *user.User) {
  262. // Check if developer debug mode is requested via URL query param (set AGI_DEV=true in ao_module)
  263. devMode := r.URL.Query().Get("agi_devmode") == "true"
  264. //Create a new vm for this request
  265. vm := otto.New()
  266. vm.Interrupt = make(chan func(), 1) // required for force-stop support
  267. //Inject standard libs into the vm; capture execID for registry correlation
  268. execID := g.injectStandardLibs(vm, scriptFile, scriptScope)
  269. releaseLibResources := g.injectUserFunctions(vm, fsh, scriptFile, scriptScope, thisuser, w, r)
  270. username := ""
  271. if thisuser != nil {
  272. username = thisuser.Username
  273. }
  274. // Register in the VM lifecycle registry so it can be listed and force-stopped
  275. g.vmReg.register(&VMRecord{
  276. ExecID: execID,
  277. ScriptFile: scriptFile,
  278. Username: username,
  279. StartTime: time.Now(),
  280. interruptCh: vm.Interrupt,
  281. })
  282. defer func() {
  283. g.vmReg.unregister(execID)
  284. //Release library resources (open SQLite handles, etc.) on every exit path
  285. releaseLibResources()
  286. if caught := recover(); caught != nil {
  287. switch caught {
  288. case errForceStop:
  289. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, username), nil)
  290. w.WriteHeader(http.StatusServiceUnavailable)
  291. w.Write([]byte("503 - Script execution was force-terminated"))
  292. case errExitcall:
  293. // exit() in AGI script — clean early termination, not an error.
  294. // check anything else in the buffered response and send it before returning, if needed.
  295. value, err := vm.Get("HTTP_RESP")
  296. if err == nil {
  297. valueString, err := value.ToString()
  298. if err == nil && valueString != "" {
  299. w.Write([]byte(valueString))
  300. }
  301. }
  302. default:
  303. panic(caught) // re-panic anything we don't own
  304. }
  305. }
  306. }()
  307. //Detect cotent type
  308. contentType := r.Header.Get("Content-type")
  309. if strings.Contains(contentType, "application/json") {
  310. //For people who use Angular
  311. body, _ := io.ReadAll(r.Body)
  312. fields := map[string]interface{}{}
  313. json.Unmarshal(body, &fields)
  314. for k, v := range fields {
  315. vm.Set(k, v)
  316. }
  317. vm.Set("POST_data", string(body))
  318. } else {
  319. r.ParseForm()
  320. //Insert all paramters into the vm
  321. for k, v := range r.PostForm {
  322. if len(v) == 1 {
  323. vm.Set(k, v[0])
  324. } else {
  325. vm.Set(k, v)
  326. }
  327. }
  328. }
  329. _, err := vm.Run(scriptContent)
  330. if err != nil {
  331. username := ""
  332. if thisuser != nil {
  333. username = thisuser.Username
  334. }
  335. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, username, err.Error()), nil)
  336. if devMode {
  337. // Return a detailed JSON error payload for developer inspection
  338. errMsg := err.Error()
  339. stackTrace := errMsg
  340. if ottoErr, ok := err.(*otto.Error); ok {
  341. stackTrace = ottoErr.String()
  342. }
  343. errPayload, _ := json.Marshal(map[string]interface{}{
  344. "error": true,
  345. "message": errMsg,
  346. "stacktrace": stackTrace,
  347. "script": scriptFile,
  348. "user": username,
  349. })
  350. w.Header().Set("Content-Type", "application/json")
  351. w.WriteHeader(http.StatusInternalServerError)
  352. w.Write(errPayload)
  353. } else {
  354. scriptpath, _ := filepath.Abs(scriptFile)
  355. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  356. }
  357. return
  358. }
  359. //Get the return valu from the script
  360. value, err := vm.Get("HTTP_RESP")
  361. if err != nil {
  362. utils.SendTextResponse(w, "")
  363. return
  364. }
  365. valueString, err := value.ToString()
  366. //Get respond header type from the vm
  367. header, _ := vm.Get("HTTP_HEADER")
  368. headerString, _ := header.ToString()
  369. if headerString != "" {
  370. w.Header().Set("Content-Type", headerString)
  371. }
  372. w.Write([]byte(valueString))
  373. }
  374. /*
  375. Execute AGI script with given user information
  376. scriptFile must be realpath resolved by fsa VirtualPathToRealPath function
  377. Pass in http.Request pointer to enable serverless GET / POST request
  378. */
  379. // ExecuteAGIScriptAsUser runs an AGI script on behalf of targetUser.
  380. // Returns (execID, output, error) where execID matches the EXECUTION_ID
  381. // constant injected into the script's VM environment.
  382. func (g *Gateway) ExecuteAGIScriptAsUser(fsh *filesystem.FileSystemHandler, scriptFile string, targetUser *user.User, w http.ResponseWriter, r *http.Request) (string, string, error) {
  383. //Create a new vm for this request
  384. vm := otto.New()
  385. //Inject standard libs into the vm; capture the execution ID for log correlation.
  386. execID := g.injectStandardLibs(vm, scriptFile, "")
  387. releaseLibResources := g.injectUserFunctions(vm, fsh, scriptFile, "", targetUser, w, r)
  388. if r != nil {
  389. //Inject serverless script to enable access to GET / POST paramters
  390. g.injectServerlessFunctions(vm, scriptFile, "", targetUser, r)
  391. }
  392. //Inject interrupt Channel
  393. vm.Interrupt = make(chan func(), 1)
  394. // Register in the VM lifecycle registry
  395. g.vmReg.register(&VMRecord{
  396. ExecID: execID,
  397. ScriptFile: scriptFile,
  398. Username: targetUser.Username,
  399. StartTime: time.Now(),
  400. interruptCh: vm.Interrupt,
  401. })
  402. //Create a panic recovery logic
  403. defer func() {
  404. g.vmReg.unregister(execID)
  405. //Release library resources (open SQLite handles, etc.) on every exit path
  406. releaseLibResources()
  407. if caught := recover(); caught != nil {
  408. if caught == errTimeout {
  409. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] Execution timeout: %s (user: %s)", scriptFile, targetUser.Username), nil)
  410. return
  411. } else if caught == errExitcall {
  412. //Exit gracefully
  413. return
  414. } else if caught == errForceStop {
  415. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, targetUser.Username), nil)
  416. if w != nil {
  417. w.WriteHeader(http.StatusServiceUnavailable)
  418. w.Write([]byte("503 - Script execution was force-terminated"))
  419. }
  420. } else {
  421. //Something screwed. Return Internal Server Error
  422. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM crash in %s (user: %s): %v", scriptFile, targetUser.Username, caught), nil)
  423. if w != nil {
  424. devMode := r != nil && r.URL.Query().Get("agi_devmode") == "true"
  425. if devMode {
  426. errPayload, _ := json.Marshal(map[string]interface{}{
  427. "error": true,
  428. "message": fmt.Sprintf("VM crash: %v", caught),
  429. "stacktrace": fmt.Sprintf("VM crash: %v", caught),
  430. "script": scriptFile,
  431. "user": targetUser.Username,
  432. })
  433. w.Header().Set("Content-Type", "application/json")
  434. w.WriteHeader(http.StatusInternalServerError)
  435. w.Write(errPayload)
  436. } else {
  437. w.WriteHeader(http.StatusInternalServerError)
  438. w.Write([]byte("500 - ECMA VM crashed due to unknown reason"))
  439. }
  440. }
  441. }
  442. }
  443. }()
  444. //Create a max runtime of 5 minutes
  445. go func() {
  446. time.Sleep(300 * time.Second) // Stop after 300 seconds
  447. vm.Interrupt <- func() {
  448. panic(errTimeout)
  449. }
  450. }()
  451. //Try to read the script content.
  452. // When fsh is nil (e.g. app-root scripts), fall back to reading from the OS filesystem.
  453. var scriptContent []byte
  454. var err error
  455. if fsh != nil {
  456. scriptContent, err = fsh.FileSystemAbstraction.ReadFile(scriptFile)
  457. } else {
  458. scriptContent, err = os.ReadFile(scriptFile)
  459. }
  460. if err != nil {
  461. return execID, "", err
  462. }
  463. _, err = vm.Run(scriptContent)
  464. if err != nil {
  465. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, targetUser.Username, err.Error()), nil)
  466. return execID, "", err
  467. }
  468. //Get the return value from the script
  469. value, err := vm.Get("HTTP_RESP")
  470. if err != nil {
  471. return execID, "", err
  472. }
  473. if w != nil {
  474. //Serverless: Get respond header type from the vm
  475. header, _ := vm.Get("HTTP_HEADER")
  476. headerString, _ := header.ToString()
  477. if headerString != "" {
  478. w.Header().Set("Content-Type", headerString)
  479. }
  480. }
  481. valueString, err := value.ToString()
  482. if err != nil {
  483. return execID, "", err
  484. }
  485. return execID, valueString, nil
  486. }
  487. /*
  488. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  489. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  490. //Do something with it, after done
  491. closerFunction();
  492. */
  493. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  494. uuid := uuid.NewV4().String()
  495. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  496. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  497. return tmpFileLocation, func() {
  498. os.RemoveAll(filepath.Dir(tmpFileLocation))
  499. }
  500. }
  501. /*
  502. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  503. */
  504. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  505. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  506. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  507. if err != nil {
  508. return "", nil, err
  509. }
  510. defer f.Close()
  511. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  512. if err != nil {
  513. return "", nil, err
  514. }
  515. io.Copy(dest, f)
  516. dest.Close()
  517. return buffFile, func() {
  518. closerFunc()
  519. }, nil
  520. }