agi.go 18 KB

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