agi.go 18 KB

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