|
| 1 | +package org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.impl; |
| 2 | + |
| 3 | +import jdk.nashorn.api.scripting.ScriptObjectMirror; |
| 4 | +import org.elasticsearch.common.Strings; |
| 5 | +import org.elasticsearch.common.logging.ESLogger; |
| 6 | +import org.elasticsearch.common.logging.Loggers; |
| 7 | +import org.elasticsearch.common.settings.Settings; |
| 8 | +import org.elasticsearch.plugin.readonlyrest.acl.RequestContext; |
| 9 | +import org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.Rule; |
| 10 | +import org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.RuleExitResult; |
| 11 | +import org.elasticsearch.plugin.readonlyrest.acl.blocks.rules.RuleNotConfiguredException; |
| 12 | + |
| 13 | +import javax.script.Invocable; |
| 14 | +import javax.script.ScriptEngine; |
| 15 | +import javax.script.ScriptEngineManager; |
| 16 | +import javax.script.ScriptException; |
| 17 | + |
| 18 | +/** |
| 19 | + * Created by sscarduzio on 14/02/2016. |
| 20 | + */ |
| 21 | +public class ScriptRule extends Rule { |
| 22 | + |
| 23 | + private final static ESLogger logger = Loggers.getLogger(ScriptRule.class); |
| 24 | + |
| 25 | + private Invocable inv = null; |
| 26 | + |
| 27 | + public ScriptRule(Settings s) throws RuleNotConfiguredException { |
| 28 | + super(s); |
| 29 | + String source = s.get(KEY); |
| 30 | + if(Strings.isNullOrEmpty(source)) { |
| 31 | + throw new RuleNotConfiguredException(); |
| 32 | + } |
| 33 | + ScriptEngineManager manager = new ScriptEngineManager(); |
| 34 | + ScriptEngine engine = manager.getEngineByName("nashorn"); |
| 35 | + try { |
| 36 | + // parse code |
| 37 | + ScriptObjectMirror som = (ScriptObjectMirror) engine.eval(source); |
| 38 | + if(!som.isFunction()) { |
| 39 | + logger.error("the javascript snippet should be a function. Found: " + source); |
| 40 | + throw new RuleNotConfiguredException(); |
| 41 | + } |
| 42 | + logger.info("Parsed script source: " + source + " " + som.isFunction() ); |
| 43 | + inv = (Invocable) engine; |
| 44 | + } catch (ScriptException e) { |
| 45 | + e.printStackTrace(); |
| 46 | + throw new RuleNotConfiguredException(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public RuleExitResult match(RequestContext rc) { |
| 52 | + String cause = "script returned false"; |
| 53 | + try { |
| 54 | + // call function from script file |
| 55 | + Boolean result = (Boolean) inv.invokeFunction("onRequest", rc); |
| 56 | + if (result) { |
| 57 | + return MATCH; |
| 58 | + } |
| 59 | + } catch (ScriptException e) { |
| 60 | + e.printStackTrace(); |
| 61 | + cause = e.getMessage(); |
| 62 | + } catch (NoSuchMethodException e) { |
| 63 | + e.printStackTrace(); |
| 64 | + cause = e.getMessage(); |
| 65 | + } |
| 66 | + logger.debug("OnRequest script did not match. Cause: " + cause); |
| 67 | + return NO_MATCH; |
| 68 | + } |
| 69 | +} |
0 commit comments