Browse Source

Support configuring whether dynamic (eval) JavaScript code is allowed (#1416)

Marko Lahma 2 years ago
parent
commit
ba6e1a5478
3 changed files with 28 additions and 0 deletions
  1. 15 0
      Jint.Tests/Runtime/EngineTests.cs
  2. 9 0
      Jint/Options.cs
  3. 4 0
      Jint/Runtime/Host.cs

+ 15 - 0
Jint.Tests/Runtime/EngineTests.cs

@@ -2882,6 +2882,21 @@ x.test = {
             Assert.True(array[1].IsUndefined());
         }
 
+        [Fact]
+        public void CanDisableCompilation()
+        {
+            var engine = new Engine(options =>
+            {
+                options.StringCompilationAllowed = false;
+            });
+
+            var ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("eval('1+1');"));
+            Assert.Equal("String compilation is not allowed", ex.Message);
+
+            ex = Assert.Throws<JavaScriptException>(() => engine.Evaluate("new Function('1+1');"));
+            Assert.Equal("String compilation is not allowed", ex.Message);
+        }
+
         [Fact]
         public void ExecuteShouldTriggerBeforeEvaluateEvent()
         {

+ 9 - 0
Jint/Options.cs

@@ -69,6 +69,15 @@ namespace Jint
         /// </summary>
         public IReferenceResolver ReferenceResolver { get; set; } = DefaultReferenceResolver.Instance;
 
+        /// <summary>
+        /// Whether calling 'eval' with custom code and function constructors taking function code as string is allowed.
+        /// Defaults to true.
+        /// </summary>
+        /// <remarks>
+        /// https://tc39.es/ecma262/#sec-hostensurecancompilestrings
+        /// </remarks>
+        public bool StringCompilationAllowed { get; set; } = true;
+
         /// <summary>
         /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
         /// once it is loaded.

+ 4 - 0
Jint/Runtime/Host.cs

@@ -108,6 +108,10 @@ namespace Jint.Runtime
         /// </summary>
         public virtual void EnsureCanCompileStrings(Realm callerRealm, Realm evalRealm)
         {
+            if (!Engine.Options.StringCompilationAllowed)
+            {
+                ExceptionHelper.ThrowJavaScriptException(callerRealm.Intrinsics.TypeError, "String compilation is not allowed");
+            }
         }
 
         /// <summary>