agi.go 17 KB

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