You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tinkerpop.apache.org by sp...@apache.org on 2015/07/15 23:21:28 UTC

[20/46] incubator-tinkerpop git commit: Add a SandboxExtension.

Add a SandboxExtension.

Provide a way to use the ASTTransformer to validate incoming variables and types.


Project: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/commit/c47426dd
Tree: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/tree/c47426dd
Diff: http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/diff/c47426dd

Branch: refs/heads/master
Commit: c47426dd7c9c18b8aed2d2565cf046ad47ea9a43
Parents: 6252cfa
Author: Stephen Mallette <sp...@genoprime.com>
Authored: Thu Jul 9 15:18:13 2015 -0400
Committer: Stephen Mallette <sp...@genoprime.com>
Committed: Thu Jul 9 15:18:13 2015 -0400

----------------------------------------------------------------------
 .../GremlinGroovyScriptEngineOverGraphTest.java | 143 ++++++++++++++++++-
 .../groovy/jsr223/SandboxExtension.groovy       |  66 +++++++++
 .../jsr223/GremlinGroovyScriptEngine.java       |  28 ++++
 3 files changed, 236 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/c47426dd/gremlin-groovy-test/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngineOverGraphTest.java
----------------------------------------------------------------------
diff --git a/gremlin-groovy-test/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngineOverGraphTest.java b/gremlin-groovy-test/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngineOverGraphTest.java
index babcf1b..c72bfd5 100644
--- a/gremlin-groovy-test/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngineOverGraphTest.java
+++ b/gremlin-groovy-test/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngineOverGraphTest.java
@@ -23,12 +23,15 @@ import org.apache.commons.lang.exception.ExceptionUtils;
 import org.apache.tinkerpop.gremlin.AbstractGremlinTest;
 import org.apache.tinkerpop.gremlin.FeatureRequirementSet;
 import org.apache.tinkerpop.gremlin.LoadGraphWith;
+import org.apache.tinkerpop.gremlin.groovy.CompileStaticCustomizerProvider;
 import org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider;
 import org.apache.tinkerpop.gremlin.groovy.NoImportCustomizerProvider;
+import org.apache.tinkerpop.gremlin.groovy.TypeCheckedCustomizerProvider;
 import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
 import org.apache.tinkerpop.gremlin.structure.Direction;
 import org.apache.tinkerpop.gremlin.structure.Vertex;
 import org.apache.tinkerpop.gremlin.util.config.YamlConfiguration;
+import org.codehaus.groovy.control.MultipleCompilationErrorsException;
 import org.junit.Assert;
 import org.junit.Test;
 
@@ -43,10 +46,12 @@ import java.util.List;
 import java.util.Random;
 import java.util.concurrent.CountDownLatch;
 
+import static org.hamcrest.Matchers.containsString;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -145,7 +150,7 @@ public class GremlinGroovyScriptEngineOverGraphTest extends AbstractGremlinTest
     public void shouldClearBindingsBetweenEvals() throws Exception {
         final ScriptEngine engine = new GremlinGroovyScriptEngine();
         engine.put("g", g);
-        Assert.assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()"));
+        assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()"));
 
         final Bindings bindings = engine.createBindings();
         bindings.put("g", g);
@@ -234,6 +239,142 @@ public class GremlinGroovyScriptEngineOverGraphTest extends AbstractGremlinTest
 
     @Test
     @LoadGraphWith(LoadGraphWith.GraphData.MODERN)
+    public void shouldEvalGraphTraversalSourceWithTypeChecked() throws Exception {
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine()) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+
+        final TypeCheckedCustomizerProvider providerNoExtension = new TypeCheckedCustomizerProvider();
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerNoExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings);
+            fail("Type checking should have forced an error as 'g' is not defined");
+        } catch (Exception ex) {
+            assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
+            assertThat(ex.getMessage(), containsString("The variable [g] is undeclared."));
+        }
+
+        final TypeCheckedCustomizerProvider providerWithExtension = new TypeCheckedCustomizerProvider(
+                SandboxExtension.class.getName());
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerWithExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings));
+            assertEquals(g.V(convertToVertexId("marko")).out("created").count().next(), engine.eval("g.V(" + convertToVertexId("marko") + ").out(\"created\").count().next()", bindings));
+        }
+    }
+
+    @Test
+    @LoadGraphWith(LoadGraphWith.GraphData.MODERN)
+    public void shouldEvalGraphWithTypeChecked() throws Exception {
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine()) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+
+        final TypeCheckedCustomizerProvider providerNoExtension = new TypeCheckedCustomizerProvider();
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerNoExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+            fail("Type checking should have forced an error as 'graph' is not defined");
+        } catch (Exception ex) {
+            assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
+            assertThat(ex.getMessage(), containsString("The variable [graph] is undeclared."));
+        }
+
+        final TypeCheckedCustomizerProvider providerWithExtension = new TypeCheckedCustomizerProvider(
+                SandboxExtension.class.getName());
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerWithExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+    }
+
+    @Test
+    @LoadGraphWith(LoadGraphWith.GraphData.MODERN)
+    public void shouldEvalGraphTraversalSourceWithCompileStatic() throws Exception {
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine()) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+
+        final CompileStaticCustomizerProvider providerNoExtension = new CompileStaticCustomizerProvider();
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerNoExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings);
+            fail("Type checking should have forced an error as 'g' is not defined");
+        } catch (Exception ex) {
+            assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
+            assertThat(ex.getMessage(), containsString("The variable [g] is undeclared."));
+        }
+
+        final CompileStaticCustomizerProvider providerWithExtension = new CompileStaticCustomizerProvider(
+                SandboxExtension.class.getName());
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerWithExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("g", g);
+            assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(" + convertToVertexId("marko") + ").next()", bindings));
+            assertEquals(g.V(convertToVertexId("marko")).out("created").count().next(), engine.eval("g.V(" + convertToVertexId("marko") + ").out(\"created\").count().next()", bindings));
+        }
+    }
+
+    @Test
+    @LoadGraphWith(LoadGraphWith.GraphData.MODERN)
+    public void shouldEvalGraphWithCompileStatic() throws Exception {
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine()) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+
+        final CompileStaticCustomizerProvider providerNoExtension = new CompileStaticCustomizerProvider();
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerNoExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+            fail("Type checking should have forced an error as 'graph' is not defined");
+        } catch (Exception ex) {
+            assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
+            assertThat(ex.getMessage(), containsString("The variable [graph] is undeclared."));
+        }
+
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerNoExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            bindings.put("x", convertToVertexId("marko"));
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(x).next()", bindings));
+            fail("Type checking should have forced an error as 'graph' is not defined");
+        } catch (Exception ex) {
+            assertEquals(MultipleCompilationErrorsException.class, ex.getCause().getClass());
+            assertThat(ex.getMessage(), containsString("The variable [graph] is undeclared."));
+        }
+
+        final CompileStaticCustomizerProvider providerWithExtension = new CompileStaticCustomizerProvider(
+                SandboxExtension.class.getName());
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerWithExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(" + convertToVertexId("marko") + ").next()", bindings));
+        }
+
+        try (GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(providerWithExtension)) {
+            final Bindings bindings = engine.createBindings();
+            bindings.put("graph", graph);
+            bindings.put("x", convertToVertexId("marko"));
+            assertEquals(graph.vertices(convertToVertexId("marko")).next(), engine.eval("graph.vertices(x).next()", bindings));
+        }
+    }
+
+    @Test
+    @LoadGraphWith(LoadGraphWith.GraphData.MODERN)
     public void shouldEvalGlobalClosuresEvenAfterEvictionOfClass() throws ScriptException {
         final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
 

http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/c47426dd/gremlin-groovy/src/main/groovy/org/apache/tinkerpop/gremlin/groovy/jsr223/SandboxExtension.groovy
----------------------------------------------------------------------
diff --git a/gremlin-groovy/src/main/groovy/org/apache/tinkerpop/gremlin/groovy/jsr223/SandboxExtension.groovy b/gremlin-groovy/src/main/groovy/org/apache/tinkerpop/gremlin/groovy/jsr223/SandboxExtension.groovy
new file mode 100644
index 0000000..4888f8c
--- /dev/null
+++ b/gremlin-groovy/src/main/groovy/org/apache/tinkerpop/gremlin/groovy/jsr223/SandboxExtension.groovy
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.groovy.jsr223
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource
+import org.apache.tinkerpop.gremlin.structure.Graph
+import org.codehaus.groovy.ast.ClassNode
+import org.codehaus.groovy.ast.expr.VariableExpression
+import org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport
+
+import java.util.function.BiPredicate
+
+/**
+ * @author Stephen Mallette (http://stephen.genoprime.com)
+ */
+class SandboxExtension extends GroovyTypeCheckingExtensionSupport.TypeCheckingDSL {
+
+    protected boolean graphIsAlwaysGraphInstance = true
+    protected boolean gIsAlwaysGraphTraversalSource = true
+    protected BiPredicate<VariableExpression, Map<String,ClassNode>> filter = USE_ALL
+
+    public static final BiPredicate<VariableExpression, Map<String,ClassNode>> USE_ALL = { var, types -> true }
+
+    @Override
+    Object run() {
+        unresolvedVariable { var ->
+            if (var.name == "graph" && graphIsAlwaysGraphInstance) {
+                storeType(var, classNodeFor(Graph))
+                handled = true
+                return
+            }
+
+            if (var.name == "g" && gIsAlwaysGraphTraversalSource) {
+                storeType(var, classNodeFor(GraphTraversalSource))
+                handled = true
+                return
+            }
+
+            final Map<String,ClassNode> varTypes = (Map<String,ClassNode>) GremlinGroovyScriptEngine.COMPILE_OPTIONS.get()
+                    .get(GremlinGroovyScriptEngine.COMPILE_OPTIONS_VAR_TYPES)
+            if (varTypes.containsKey(var.name) && filter.test(var, varTypes)
+                || (var.name == "graph" && !graphIsAlwaysGraphInstance
+                     || var.name == "g" && !gIsAlwaysGraphTraversalSource)) {
+                storeType(var, varTypes.get(var.name))
+                handled = true
+                return
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-tinkerpop/blob/c47426dd/gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine.java
----------------------------------------------------------------------
diff --git a/gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine.java b/gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine.java
index 9042e6d..09af47f 100644
--- a/gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine.java
+++ b/gremlin-groovy/src/main/java/org/apache/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine.java
@@ -37,6 +37,8 @@ import groovy.lang.MissingMethodException;
 import groovy.lang.MissingPropertyException;
 import groovy.lang.Script;
 import groovy.lang.Tuple;
+import org.codehaus.groovy.ast.ClassHelper;
+import org.codehaus.groovy.ast.ClassNode;
 import org.codehaus.groovy.control.CompilationFailedException;
 import org.codehaus.groovy.control.CompilerConfiguration;
 import org.codehaus.groovy.jsr223.GroovyCompiledScript;
@@ -81,6 +83,7 @@ import java.util.stream.Collectors;
  */
 public class GremlinGroovyScriptEngine extends GroovyScriptEngineImpl implements DependencyManager, AutoCloseable {
 
+    public static final String COMPILE_OPTIONS_VAR_TYPES = "sandbox.bindings";
     public static final String KEY_REFERENCE_TYPE = "#jsr223.groovy.engine.keep.globals";
     public static final String REFERENCE_TYPE_PHANTOM = "phantom";
     public static final String REFERENCE_TYPE_WEAK = "weak";
@@ -96,6 +99,13 @@ public class GremlinGroovyScriptEngine extends GroovyScriptEngineImpl implements
         }
     };
 
+    public static final ThreadLocal<Map<String, Object>> COMPILE_OPTIONS = new ThreadLocal<Map<String, Object>>(){
+        @Override
+        protected Map<String, Object> initialValue() {
+            return new HashMap<>();
+        }
+    };
+
     /**
      * Script to generated Class map.
      */
@@ -287,6 +297,7 @@ public class GremlinGroovyScriptEngine extends GroovyScriptEngineImpl implements
         } catch (ClassCastException cce) { /*ignore.*/ }
 
         try {
+            registerBindingTypes(context);
             final Class clazz = getScriptClass(script);
             if (null == clazz) throw new ScriptException("Script class is null");
             return eval(clazz, context);
@@ -447,6 +458,23 @@ public class GremlinGroovyScriptEngine extends GroovyScriptEngineImpl implements
         }
     }
 
+    private void registerBindingTypes(final ScriptContext context) {
+        final Map<String,ClassNode> variableTypes = new HashMap<>();
+        clearVarTypes();
+        context.getBindings(ScriptContext.ENGINE_SCOPE).forEach((k, v) -> {
+            final Class clazz = v.getClass();
+            variableTypes.put(k, ClassHelper.make(clazz));
+        });
+
+        COMPILE_OPTIONS.get().put(COMPILE_OPTIONS_VAR_TYPES, variableTypes);
+    }
+
+    private static void clearVarTypes() {
+        final Map<String,Object> m = COMPILE_OPTIONS.get();
+        if (m.containsKey(COMPILE_OPTIONS_VAR_TYPES))
+            ((Map<String,ClassNode>) m.get(COMPILE_OPTIONS_VAR_TYPES)).clear();
+    }
+
     private void ensureSandbox() {
         if (securityProvider.isPresent() && !this.registeredSandbox.get()) {
             this.securityProvider.get().registerInterceptors();