agi.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. "imuslab.com/arozos/mod/info/logger"
  20. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  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.0" //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. if caught == errForceStop {
  275. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, username), nil)
  276. w.WriteHeader(http.StatusServiceUnavailable)
  277. w.Write([]byte("503 - Script execution was force-terminated"))
  278. } else {
  279. panic(caught) // re-panic anything we don't own
  280. }
  281. }
  282. }()
  283. //Detect cotent type
  284. contentType := r.Header.Get("Content-type")
  285. if strings.Contains(contentType, "application/json") {
  286. //For people who use Angular
  287. body, _ := io.ReadAll(r.Body)
  288. fields := map[string]interface{}{}
  289. json.Unmarshal(body, &fields)
  290. for k, v := range fields {
  291. vm.Set(k, v)
  292. }
  293. vm.Set("POST_data", string(body))
  294. } else {
  295. r.ParseForm()
  296. //Insert all paramters into the vm
  297. for k, v := range r.PostForm {
  298. if len(v) == 1 {
  299. vm.Set(k, v[0])
  300. } else {
  301. vm.Set(k, v)
  302. }
  303. }
  304. }
  305. _, err := vm.Run(scriptContent)
  306. if err != nil {
  307. username := ""
  308. if thisuser != nil {
  309. username = thisuser.Username
  310. }
  311. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, username, err.Error()), nil)
  312. if devMode {
  313. // Return a detailed JSON error payload for developer inspection
  314. errMsg := err.Error()
  315. stackTrace := errMsg
  316. if ottoErr, ok := err.(*otto.Error); ok {
  317. stackTrace = ottoErr.String()
  318. }
  319. errPayload, _ := json.Marshal(map[string]interface{}{
  320. "error": true,
  321. "message": errMsg,
  322. "stacktrace": stackTrace,
  323. "script": scriptFile,
  324. "user": username,
  325. })
  326. w.Header().Set("Content-Type", "application/json")
  327. w.WriteHeader(http.StatusInternalServerError)
  328. w.Write(errPayload)
  329. } else {
  330. scriptpath, _ := filepath.Abs(scriptFile)
  331. g.RenderErrorTemplate(w, err.Error(), scriptpath)
  332. }
  333. return
  334. }
  335. //Get the return valu from the script
  336. value, err := vm.Get("HTTP_RESP")
  337. if err != nil {
  338. utils.SendTextResponse(w, "")
  339. return
  340. }
  341. valueString, err := value.ToString()
  342. //Get respond header type from the vm
  343. header, _ := vm.Get("HTTP_HEADER")
  344. headerString, _ := header.ToString()
  345. if headerString != "" {
  346. w.Header().Set("Content-Type", headerString)
  347. }
  348. w.Write([]byte(valueString))
  349. }
  350. /*
  351. Execute AGI script with given user information
  352. scriptFile must be realpath resolved by fsa VirtualPathToRealPath function
  353. Pass in http.Request pointer to enable serverless GET / POST request
  354. */
  355. // ExecuteAGIScriptAsUser runs an AGI script on behalf of targetUser.
  356. // Returns (execID, output, error) where execID matches the EXECUTION_ID
  357. // constant injected into the script's VM environment.
  358. func (g *Gateway) ExecuteAGIScriptAsUser(fsh *filesystem.FileSystemHandler, scriptFile string, targetUser *user.User, w http.ResponseWriter, r *http.Request) (string, string, error) {
  359. //Create a new vm for this request
  360. vm := otto.New()
  361. //Inject standard libs into the vm; capture the execution ID for log correlation.
  362. execID := g.injectStandardLibs(vm, scriptFile, "")
  363. g.injectUserFunctions(vm, fsh, scriptFile, "", targetUser, w, r)
  364. if r != nil {
  365. //Inject serverless script to enable access to GET / POST paramters
  366. g.injectServerlessFunctions(vm, scriptFile, "", targetUser, r)
  367. }
  368. //Inject interrupt Channel
  369. vm.Interrupt = make(chan func(), 1)
  370. // Register in the VM lifecycle registry
  371. g.vmReg.register(&VMRecord{
  372. ExecID: execID,
  373. ScriptFile: scriptFile,
  374. Username: targetUser.Username,
  375. StartTime: time.Now(),
  376. interruptCh: vm.Interrupt,
  377. })
  378. //Create a panic recovery logic
  379. defer func() {
  380. g.vmReg.unregister(execID)
  381. if caught := recover(); caught != nil {
  382. if caught == errTimeout {
  383. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] Execution timeout: %s (user: %s)", scriptFile, targetUser.Username), nil)
  384. return
  385. } else if caught == errExitcall {
  386. //Exit gracefully
  387. return
  388. } else if caught == errForceStop {
  389. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM %s force-stopped (script: %s, user: %s)", execID, scriptFile, targetUser.Username), nil)
  390. if w != nil {
  391. w.WriteHeader(http.StatusServiceUnavailable)
  392. w.Write([]byte("503 - Script execution was force-terminated"))
  393. }
  394. } else {
  395. //Something screwed. Return Internal Server Error
  396. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI] VM crash in %s (user: %s): %v", scriptFile, targetUser.Username, caught), nil)
  397. if w != nil {
  398. devMode := r != nil && r.URL.Query().Get("agi_devmode") == "true"
  399. if devMode {
  400. errPayload, _ := json.Marshal(map[string]interface{}{
  401. "error": true,
  402. "message": fmt.Sprintf("VM crash: %v", caught),
  403. "stacktrace": fmt.Sprintf("VM crash: %v", caught),
  404. "script": scriptFile,
  405. "user": targetUser.Username,
  406. })
  407. w.Header().Set("Content-Type", "application/json")
  408. w.WriteHeader(http.StatusInternalServerError)
  409. w.Write(errPayload)
  410. } else {
  411. w.WriteHeader(http.StatusInternalServerError)
  412. w.Write([]byte("500 - ECMA VM crashed due to unknown reason"))
  413. }
  414. }
  415. }
  416. }
  417. }()
  418. //Create a max runtime of 5 minutes
  419. go func() {
  420. time.Sleep(300 * time.Second) // Stop after 300 seconds
  421. vm.Interrupt <- func() {
  422. panic(errTimeout)
  423. }
  424. }()
  425. //Try to read the script content.
  426. // When fsh is nil (e.g. app-root scripts), fall back to reading from the OS filesystem.
  427. var scriptContent []byte
  428. var err error
  429. if fsh != nil {
  430. scriptContent, err = fsh.FileSystemAbstraction.ReadFile(scriptFile)
  431. } else {
  432. scriptContent, err = os.ReadFile(scriptFile)
  433. }
  434. if err != nil {
  435. return execID, "", err
  436. }
  437. _, err = vm.Run(scriptContent)
  438. if err != nil {
  439. logger.PrintAndLog("Agi", fmt.Sprintf("[AGI][%s] Script error in %s (user: %s): %s", execID, scriptFile, targetUser.Username, err.Error()), nil)
  440. return execID, "", err
  441. }
  442. //Get the return value from the script
  443. value, err := vm.Get("HTTP_RESP")
  444. if err != nil {
  445. return execID, "", err
  446. }
  447. if w != nil {
  448. //Serverless: Get respond header type from the vm
  449. header, _ := vm.Get("HTTP_HEADER")
  450. headerString, _ := header.ToString()
  451. if headerString != "" {
  452. w.Header().Set("Content-Type", headerString)
  453. }
  454. }
  455. valueString, err := value.ToString()
  456. if err != nil {
  457. return execID, "", err
  458. }
  459. return execID, valueString, nil
  460. }
  461. /*
  462. Get user specific tmp filepath for buffering remote file. Return filepath and closer
  463. tempFilepath, closerFunction := g.getUserSpecificTempFilePath(u, "myfile.txt")
  464. //Do something with it, after done
  465. closerFunction();
  466. */
  467. func (g *Gateway) getUserSpecificTempFilePath(u *user.User, filename string) (string, func()) {
  468. uuid := uuid.NewV4().String()
  469. tmpFileLocation := filepath.Join(g.Option.TempFolderPath, "agiBuff", u.Username, uuid, filepath.Base(filename))
  470. os.MkdirAll(filepath.Dir(tmpFileLocation), 0775)
  471. return tmpFileLocation, func() {
  472. os.RemoveAll(filepath.Dir(tmpFileLocation))
  473. }
  474. }
  475. /*
  476. Buffer remote reosurces to local by fsh and rpath. Return buffer filepath on local device and its closer function
  477. */
  478. func (g *Gateway) bufferRemoteResourcesToLocal(fsh *filesystem.FileSystemHandler, u *user.User, rpath string) (string, func(), error) {
  479. buffFile, closerFunc := g.getUserSpecificTempFilePath(u, rpath)
  480. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  481. if err != nil {
  482. return "", nil, err
  483. }
  484. defer f.Close()
  485. dest, err := os.OpenFile(buffFile, os.O_CREATE|os.O_RDWR, 0775)
  486. if err != nil {
  487. return "", nil, err
  488. }
  489. io.Copy(dest, f)
  490. dest.Close()
  491. return buffFile, func() {
  492. closerFunc()
  493. }, nil
  494. }