Skip to content

Enforce explicit names for global scripts and refine script id handling #3691

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

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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.logging.log4j.core.config;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.apache.logging.log4j.core.script.AbstractScript;
import org.junit.jupiter.api.Test;

class ScriptsPluginTest {

@Test
void testCreateScriptsNullInput() {
assertThrows(NullPointerException.class, () -> ScriptsPlugin.createScripts(null));
}

@Test
void testCreateScriptsEmptyInput() {
AbstractScript[] emptyArray = new AbstractScript[0];
assertSame(emptyArray, ScriptsPlugin.createScripts(emptyArray), "Should return empty array");
}

@Test
void testCreateScriptsAllExplicitNames() {
AbstractScript script1 = new MockScript("script1", "JavaScript", "text");
AbstractScript script2 = new MockScript("script2", "Groovy", "text");
AbstractScript[] input = {script1, script2};
AbstractScript[] result = ScriptsPlugin.createScripts(input);
assertEquals(2, result.length, "Should return 2 scripts");
assertArrayEquals(input, result, "Should contain all valid scripts");
}

@Test
void testCreateScriptsImplicitName() {
AbstractScript script = new MockScript(null, "JavaScript", "text");
AbstractScript[] input = {script};
assertThrows(ConfigurationException.class, () -> ScriptsPlugin.createScripts(input));
}

@Test
void testCreateScriptsBlankName() {
AbstractScript script = new MockScript(" ", "JavaScript", "text");
AbstractScript[] input = {script};
assertThrows(ConfigurationException.class, () -> ScriptsPlugin.createScripts(input));
}

@Test
void testCreateScriptsMixedExplicitAndImplicitNames() {
AbstractScript explicitScript = new MockScript("script", "Python", "text");
AbstractScript implicitScript = new MockScript(null, "JavaScript", "text");
AbstractScript[] input = {explicitScript, implicitScript};
assertThrows(ConfigurationException.class, () -> ScriptsPlugin.createScripts(input));
}

private class MockScript extends AbstractScript {

public MockScript(String name, String language, String scriptText) {
super(name, language, scriptText);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* 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.logging.log4j.core.script;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import org.junit.jupiter.api.Test;

class AbstractScriptTest {

@Test
void testConstructorAndGettersWithExplicitName() {
final String lang = "JavaScript";
final String text = "text";
final String name = "script";
final AbstractScript script = new MockScript(name, lang, text);

assertEquals(lang, script.getLanguage(), "Language should match");
assertEquals(text, script.getScriptText(), "Script text should match");
assertEquals(name, script.getName(), "Name should match the provided name");
assertEquals(name, script.getId(), "Id should match the provided name");
}

@Test
void testConstructorAndGettersWithImplicitName() {
final String lang = "JavaScript";
final String text = "text";
final AbstractScript script = new MockScript(null, lang, text);

assertEquals(lang, script.getLanguage(), "Language should match");
assertEquals(text, script.getScriptText(), "Script text should match");
assertNull(script.getName(), "Name should be null");
assertNotNull(script.getId(), "Id should not be null");
}

@Test
void testConstructorAndGettersWithBlankName() {
final String lang = "JavaScript";
final String text = "text";
final String name = " ";
final AbstractScript script = new MockScript(name, lang, text);

assertEquals(lang, script.getLanguage(), "Language should match");
assertEquals(text, script.getScriptText(), "Script text should match");
assertEquals(name, script.getName(), "Name should be blank");
assertNotNull(script.getId(), "Id should not be null");
}

private class MockScript extends AbstractScript {

public MockScript(String name, String language, String scriptText) {
super(name, language, scriptText);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ public Appender build() {
"ScriptAppenderSelector '{}' executing {} '{}': {}",
name,
script.getLanguage(),
script.getName(),
script.getId(),
script.getScriptText());
final Object object = scriptManager.execute(script.getName(), bindings);
final Object object = scriptManager.execute(script.getId(), bindings);
final String actualAppenderName = Objects.toString(object, null);
LOGGER.debug("ScriptAppenderSelector '{}' selected '{}'", name, actualAppenderName);
return appenderSet.createAppender(actualAppenderName, name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public List<PathWithAttributes> selectFilesToDelete(
bindings.put("configuration", configuration);
bindings.put("substitutor", configuration.getStrSubstitutor());
bindings.put("statusLogger", LOGGER);
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return (List<PathWithAttributes>) object;
}

Expand Down Expand Up @@ -110,8 +110,8 @@ public static ScriptCondition createCondition(
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
LOGGER.error("ScriptCondition: No script with name {} has been declared.", script.getName());
if (configuration.getScriptManager().getScript(script.getId()) == null) {
LOGGER.error("ScriptCondition: No script with name {} has been declared.", script.getId());
return null;
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public String getPattern(final LogEvent event, final ConcurrentMap<Object, Objec
final Bindings bindings = scriptManager.createBindings(patternScript);
bindings.put(STATIC_VARIABLES_KEY, scriptStaticVariables);
bindings.put(LOG_EVENT_KEY, event);
final Object object = scriptManager.execute(patternScript.getName(), bindings);
final Object object = scriptManager.execute(patternScript.getId(), bindings);
bindings.remove(LOG_EVENT_KEY);
return Objects.toString(object, null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public void start() {
final ScriptManager scriptManager = configuration.getScriptManager();
final Bindings bindings = scriptManager.createBindings(defaultRouteScript);
bindings.put(STATIC_VARIABLES_KEY, scriptStaticVariables);
final Object object = scriptManager.execute(defaultRouteScript.getName(), bindings);
final Object object = scriptManager.execute(defaultRouteScript.getId(), bindings);
final Route route = routes.getRoute(Objects.toString(object, null));
if (route != null) {
defaultRoute = route;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,21 @@
*/
package org.apache.logging.log4j.core.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.logging.log4j.core.Core;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.script.AbstractScript;
import org.apache.logging.log4j.util.Strings;
import org.jspecify.annotations.NullMarked;

/**
* A container of Scripts.
*/
@NullMarked
@Plugin(name = "Scripts", category = Core.CATEGORY_NAME)
public final class ScriptsPlugin {

Expand All @@ -37,7 +43,19 @@ private ScriptsPlugin() {}
*/
@PluginFactory
public static AbstractScript[] createScripts(@PluginElement("Scripts") final AbstractScript[] scripts) {
Objects.requireNonNull(scripts, "Scripts array cannot be null");
if (scripts.length == 0) {
return scripts;
}

return scripts;
final List<AbstractScript> validScripts = new ArrayList<>(scripts.length);
for (final AbstractScript script : scripts) {
if (Strings.isBlank(script.getName())) {
throw new ConfigurationException("A script defined in <Scripts> lacks an explicit 'name' attribute");
} else {
validScripts.add(script);
}
}
return validScripts.toArray(new AbstractScript[0]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public boolean isCondition() {
final SimpleBindings bindings = new SimpleBindings();
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return Boolean.parseBoolean(object.toString());
}

Expand Down Expand Up @@ -114,8 +114,8 @@ public ScriptArbiter build() {
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
LOGGER.error("No script with name {} has been declared.", script.getName());
if (configuration.getScriptManager().getScript(script.getId()) == null) {
LOGGER.error("No script with name {} has been declared.", script.getId());
return null;
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public Result filter(
bindings.put("throwable", null);
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}

Expand All @@ -85,7 +85,7 @@ public Result filter(
bindings.put("throwable", t);
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}

Expand All @@ -101,7 +101,7 @@ public Result filter(
bindings.put("throwable", t);
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}

Expand All @@ -111,13 +111,13 @@ public Result filter(final LogEvent event) {
bindings.put("logEvent", event);
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}

@Override
public String toString() {
return script.getName();
return script.getId();
}

/**
Expand Down Expand Up @@ -146,8 +146,8 @@ public static ScriptFilter createFilter(
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
logger.error("No script with name {} has been declared.", script.getName());
if (configuration.getScriptManager().getScript(script.getId()) == null) {
logger.error("No script with name {} has been declared.", script.getId());
return null;
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ public ScriptPatternSelector build() {
return null;
}
if (script instanceof ScriptRef) {
if (configuration.getScriptManager().getScript(script.getName()) == null) {
LOGGER.error("No script with name {} has been declared.", script.getName());
if (configuration.getScriptManager().getScript(script.getId()) == null) {
LOGGER.error("No script with name {} has been declared.", script.getId());
return null;
}
} else {
Expand Down Expand Up @@ -262,7 +262,7 @@ public PatternFormatter[] getFormatters(final LogEvent event) {
bindings.putAll(configuration.getProperties());
bindings.put("substitutor", configuration.getStrSubstitutor());
bindings.put("logEvent", event);
final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
final Object object = configuration.getScriptManager().execute(script.getId(), bindings);
if (object == null) {
return defaultFormatters;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
*/
package org.apache.logging.log4j.core.script;

import java.util.Objects;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.Strings;

/**
* Container for the language and body of a script.
Expand All @@ -30,11 +32,13 @@ public abstract class AbstractScript {
private final String language;
private final String scriptText;
private final String name;
private final String id;

public AbstractScript(final String name, final String language, final String scriptText) {
this.language = language;
this.scriptText = scriptText;
this.name = name == null ? this.toString() : name;
this.name = name;
this.id = Strings.isBlank(name) ? Integer.toHexString(Objects.hashCode(this)) : name;
}

public String getLanguage() {
Expand All @@ -48,4 +52,8 @@ public String getScriptText() {
public String getName() {
return this.name;
}

public String getId() {
return this.id;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ public static ScriptFile createScript(
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (!(getName().equals(filePath.toString()))) {
sb.append("name=").append(getName()).append(", ");
if (!(getId().equals(filePath.toString()))) {
sb.append("name=").append(getId()).append(", ");
}
sb.append("path=").append(filePath);
if (getLanguage() != null) {
Expand Down
Loading