agi.go 17 KB

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