-
Notifications
You must be signed in to change notification settings - Fork 5
Use the VM loader for loading plugin modules as well resource modules #209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
66f0dc5
Create an ApplicationScope that holds the top level context for the a…
kriszyp efd52b7
Fix root handling and unit tests
kriszyp d15dfcf
Respect verifyPath if it is already set
kriszyp 59ef091
Update components/ApplicationScope.ts
kriszyp 23c0505
Remove unused import
kriszyp 0e4f4dc
Apply suggestions from code review
kriszyp 9f04538
Updates for optional verifyPath and assignment of config
kriszyp 592d314
Merge remote-tracking branch 'origin/main' into vm-load-plugins
kriszyp 6588350
Merge remote-tracking branch 'origin/main' into vm-load-plugins
kriszyp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { Resources } from '../resources/Resources.ts'; | ||
| import { type Server } from '../server/Server.ts'; | ||
| import { loggerWithTag } from '../utility/logging/harper_logger.js'; | ||
| import { scopedImport } from '../security/jsLoader.ts'; | ||
| import * as env from '../utility/environment/environmentManager.js'; | ||
| import { CONFIG_PARAMS } from '../utility/hdbTerms.ts'; | ||
|
|
||
| export class MissingDefaultFilesOptionError extends Error { | ||
| constructor() { | ||
| super('No default files option exists. Ensure `files` is specified in config.yaml'); | ||
| this.name = 'MissingDefaultFilesOptionError'; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * This class is used to represent the application scope for the VM context used for loading modules within an application | ||
| */ | ||
| export class ApplicationScope { | ||
| logger: any; | ||
| resources: Resources; | ||
| server: Server; | ||
| mode?: 'none' | 'vm' | 'compartment'; // option to set this from the scope | ||
| dependencyContainment?: boolean; // option to set this from the scope | ||
| verifyPath?: string; | ||
| config: any; | ||
| constructor(name: string, resources: Resources, server: Server) { | ||
| this.logger = loggerWithTag(name); | ||
|
|
||
| this.resources = resources; | ||
| this.server = server; | ||
|
|
||
| this.mode = env.get(CONFIG_PARAMS.APPLICATIONS_CONTAINMENT) ?? 'vm'; | ||
| this.dependencyContainment = Boolean(env.get(CONFIG_PARAMS.APPLICATIONS_DEPENDENCYCONTAINMENT)); | ||
| } | ||
|
|
||
| /** | ||
| * The compartment that is used for this scope and any imports that it makes | ||
| */ | ||
| compartment?: Promise<any>; | ||
| /** | ||
| * Import a file into the scope's sandbox. | ||
| * @param filePath - The path of the file to import. | ||
| * @returns A promise that resolves with the imported module or value. | ||
| */ | ||
| async import(filePath: string): Promise<unknown> { | ||
| return scopedImport(filePath, this); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,7 @@ import { readFileSync } from 'node:fs'; | |
| import { dirname, isAbsolute } from 'node:path'; | ||
| import { pathToFileURL, fileURLToPath } from 'node:url'; | ||
| import { SourceTextModule, SyntheticModule, createContext, runInContext } from 'node:vm'; | ||
| import { Scope } from '../components/Scope.ts'; | ||
| import { ApplicationScope } from '../components/ApplicationScope.ts'; | ||
| import logger from '../utility/logging/harper_logger.js'; | ||
| import { createRequire } from 'node:module'; | ||
| import * as env from '../utility/environment/environmentManager'; | ||
|
|
@@ -25,7 +25,7 @@ let lockedDown = false; | |
| * @param moduleUrl | ||
| * @param scope | ||
| */ | ||
| export async function scopedImport(filePath: string | URL, scope?: Scope) { | ||
| export async function scopedImport(filePath: string | URL, scope?: ApplicationScope) { | ||
| if (!lockedDown && APPLICATIONS_LOCKDOWN && APPLICATIONS_LOCKDOWN !== 'none') { | ||
| lockedDown = true; | ||
| if (APPLICATIONS_LOCKDOWN === 'ses') { | ||
|
|
@@ -76,7 +76,7 @@ export async function scopedImport(filePath: string | URL, scope?: Scope) { | |
| } | ||
| const moduleUrl = (filePath instanceof URL ? filePath : pathToFileURL(filePath)).toString(); | ||
| try { | ||
| const containmentMode = scope?.applicationContainment.mode; | ||
| const containmentMode = scope?.mode; | ||
| if (scope && containmentMode !== 'none') { | ||
| if (containmentMode === 'compartment') { | ||
| // use SES Compartments | ||
|
|
@@ -110,7 +110,7 @@ export async function scopedImport(filePath: string | URL, scope?: Scope) { | |
| /** | ||
| * Load a module using Node's vm.Module API with (not really secure) sandboxing | ||
| */ | ||
| async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | ||
| async function loadModuleWithVM(moduleUrl: string, scope: ApplicationScope) { | ||
| const moduleCache = new Map<string, Promise<SourceTextModule | SyntheticModule>>(); | ||
|
|
||
| // Create a secure context with limited globals | ||
|
|
@@ -167,7 +167,7 @@ async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | |
| filename: url, | ||
| async importModuleDynamically(specifier: string, script) { | ||
| const resolvedUrl = resolveModule(specifier, script.sourceURL); | ||
| const useContainment = specifier.startsWith('.') || scope.applicationContainment.dependencyContainment; | ||
| const useContainment = specifier.startsWith('.') || scope.dependencyContainment; | ||
| const dynamicModule = await loadModuleWithCache(resolvedUrl, useContainment); | ||
| return dynamicModule; | ||
| }, | ||
|
|
@@ -213,7 +213,7 @@ async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | |
| return moduleCache.get(resolvedUrl)!; | ||
| } | ||
|
|
||
| const useContainment = specifier.startsWith('.') || scope.applicationContainment.dependencyContainment; | ||
| const useContainment = specifier.startsWith('.') || scope.dependencyContainment; | ||
| // Load the module | ||
| return await loadModuleWithCache(resolvedUrl, useContainment); | ||
| } | ||
|
|
@@ -246,7 +246,7 @@ async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | |
| { identifier: url, context } | ||
| ); | ||
| } else if (usePrivateGlobal && url.startsWith('file://')) { | ||
| checkAllowedModulePath(url, scope.applicationContainment.verifyPath); | ||
| checkAllowedModulePath(url, scope.verifyPath); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What if |
||
| // Load source text from file | ||
| const source = await readFile(new URL(url), { encoding: 'utf-8' }); | ||
|
|
||
|
|
@@ -286,7 +286,7 @@ async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | |
| } | ||
| } | ||
| } else { | ||
| checkAllowedModulePath(url, scope.applicationContainment.verifyPath); | ||
| checkAllowedModulePath(url, scope.verifyPath); | ||
| // For Node.js built-in modules (node:) and npm packages, use dynamic import | ||
| const importedModule = await import(url); | ||
| const exportNames = Object.keys(importedModule); | ||
|
|
@@ -318,7 +318,7 @@ async function loadModuleWithVM(moduleUrl: string, scope: Scope) { | |
| return entryModule.namespace; | ||
| } | ||
|
|
||
| async function getCompartment(scope: Scope, globals) { | ||
| async function getCompartment(scope: ApplicationScope, globals) { | ||
| const { StaticModuleRecord } = await import('@endo/static-module-record'); | ||
| require('ses'); | ||
| const compartment: CompartmentOptions = new (Compartment as typeof CompartmentOptions)( | ||
|
|
@@ -351,7 +351,7 @@ async function getCompartment(scope: Scope, globals) { | |
| const moduleText = await readFile(new URL(moduleSpecifier), { encoding: 'utf-8' }); | ||
| return new StaticModuleRecord(moduleText, moduleSpecifier); | ||
| } else { | ||
| checkAllowedModulePath(moduleSpecifier, scope.applicationContainment.verifyPath); | ||
| checkAllowedModulePath(moduleSpecifier, scope.verifyPath); | ||
| const moduleExports = await import(moduleSpecifier); | ||
| return { | ||
| imports: [], | ||
|
|
@@ -398,7 +398,7 @@ function getDefaultJSGlobalNames() { | |
| /** | ||
| * Get the set of global variables that should be available to modules that run in scoped compartments/contexts. | ||
| */ | ||
| function getGlobalObject(scope: Scope) { | ||
| function getGlobalObject(scope: ApplicationScope) { | ||
| const appGlobal = {}; | ||
| // create the new global object, assigning all the global variables from this global | ||
| // except those that will be natural intrinsics of the new VM | ||
|
|
@@ -411,20 +411,20 @@ function getGlobalObject(scope: Scope) { | |
| server: scope.server ?? server, | ||
| logger: scope.logger ?? logger, | ||
| resources: scope.resources, | ||
| config: scope.options.getRoot() ?? {}, | ||
| config: scope.config ?? {}, | ||
| fetch: APPLICATIONS_LOCKDOWN === 'ses' ? secureOnlyFetch : fetch, | ||
| console, | ||
| global: appGlobal, | ||
| harper: getHarperExports(scope), | ||
| }); | ||
| return appGlobal; | ||
| } | ||
| function getHarperExports(scope: Scope) { | ||
| function getHarperExports(scope: ApplicationScope) { | ||
| return { | ||
| server: scope.server ?? server, | ||
| logger: scope.logger ?? logger, | ||
| resources: scope.resources, | ||
| config: scope.options.getRoot() ?? {}, | ||
| config: scope.config ?? {}, | ||
| Resource, | ||
| tables, | ||
| databases, | ||
|
|
@@ -468,7 +468,7 @@ function checkAllowedModulePath(moduleUrl: string, containingFolder: string): bo | |
| if (path.startsWith(containingFolder)) { | ||
| return true; | ||
| } | ||
| throw new Error(`Can not load module outside of application folder`); | ||
| throw new Error(`Can not load module outside of application folder ${containingFolder}`); | ||
| } | ||
| let simpleName = moduleUrl.startsWith('node:') ? moduleUrl.slice(5) : moduleUrl; | ||
| simpleName = simpleName.split('/')[0]; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.