Skip to content
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

【Type:feature 】The SPEL in the mock plugin is secure by default #4606

Merged
merged 11 commits into from
May 3, 2023
Original file line number Diff line number Diff line change
Expand Up @@ -42,49 +42,53 @@
* MockPlugin.
*/
public class MockPlugin extends AbstractShenyuPlugin {

@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain,
final SelectorData selector, final RuleData rule) {

MockHandle mockHandle = MockPluginHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule));
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
exchange.getResponse().setStatusCode(HttpStatus.valueOf(mockHandle.getHttpStatusCode()));

return DataBufferUtils.join(exchange.getRequest().getBody())
.switchIfEmpty(Mono.just(DefaultDataBufferFactory.sharedInstance.allocateBuffer(0)))
.map(dataBuffer -> dealRule(dataBuffer, mockHandle.getResponseContent(), exchange.getRequest()))
.flatMap(bytes -> exchange.getResponse().writeWith(Mono.just(exchange.getResponse()
.bufferFactory().wrap(bytes))
.doOnNext(data -> exchange.getResponse().getHeaders()
.setContentLength(data.readableByteCount()))));
.flatMap(bytes -> exchange.getResponse()
.writeWith(Mono.just(exchange.getResponse()
.bufferFactory()
.wrap(bytes))
.doOnNext(data -> exchange.getResponse()
.getHeaders()
.setContentLength(data.readableByteCount()))));
}

@Override
public int getOrder() {
return PluginEnum.MOCK.getCode();
}

@Override
public String named() {
return PluginEnum.MOCK.getName();
}

private byte[] dealRule(final DataBuffer requestBodyBuffer, final String response, final ServerHttpRequest serverHttpRequest) {
byte[] originalBody = new byte[requestBodyBuffer.readableByteCount()];
requestBodyBuffer.read(originalBody);
DataBufferUtils.release(requestBodyBuffer);
MockRequest mockRequest = buildMockRequest(originalBody, serverHttpRequest);
return GeneratorFactory.dealRule(response, mockRequest).getBytes(StandardCharsets.UTF_8);
}

private MockRequest buildMockRequest(final byte[] originalBody, final ServerHttpRequest serverHttpRequest) {

return MockRequest.Builder.builder()
.headers(serverHttpRequest.getHeaders().toSingleValueMap())
.method(serverHttpRequest.getMethodValue())
.queries(serverHttpRequest.getQueryParams().toSingleValueMap())
.uri(serverHttpRequest.getURI().toString())
.body(originalBody).build();
.body(originalBody)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,91 +19,63 @@

import org.apache.shenyu.common.utils.JsonUtils;
import org.apache.shenyu.plugin.mock.api.MockRequest;
import org.apache.shenyu.plugin.mock.util.MockUtil;
import org.apache.shenyu.plugin.mock.util.EvaluationContextUtil;
import org.apache.shenyu.spi.Join;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.DataBindingPropertyAccessor;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.util.List;

/**
* The simplified version of the SEPL parsing implementation does not support write function execution.
*
* @see SimpleEvaluationContext
* @see DataBindingPropertyAccessor#forReadOnlyAccess()
*/
@Join
public class ExpressionGenerator implements Generator<String> {

private static final Logger LOG = LoggerFactory.getLogger(ExpressionGenerator.class);


private static final ExpressionParser PARSER = new SpelExpressionParser();

private static final EvaluationContext CONTEXT = initContext();

@Override
public String getName() {
return "expression";
}

@Override
public String doGenerate(final List<String> params, final String rule, final MockRequest mockRequest) {

String expression = params.get(0);

CONTEXT.setVariable("req", mockRequest);

Object val = PARSER.parseExpression(expression).getValue(CONTEXT);
return JsonUtils.toJson(val);
}

@Override
public int getParamSize() {
return 1;
}

@Override
public boolean match(final String rule) {
return rule.matches("^expression\\|.+");
return rule.matches("^" + getName() + "\\|.+");
}

private static EvaluationContext initContext() {

StandardEvaluationContext context = new StandardEvaluationContext();

try {
registerMockFunction(context, "double", "randomDouble", double.class, double.class, String[].class);

registerMockFunction(context, "bool", "bool");

registerMockFunction(context, "int", "randomInt", int.class, int.class);

registerMockFunction(context, "email", "email");

registerMockFunction(context, "phone", "phone");

registerMockFunction(context, "zh", "zh", int.class, int.class);

registerMockFunction(context, "en", "en", int.class, int.class);

registerMockFunction(context, "oneOf", "oneOf", Object[].class);

registerMockFunction(context, "current", "current", String[].class);

registerMockFunction(context, "array", "array", Object.class, int.class);

context.addPropertyAccessor(new MapAccessor());

} catch (NoSuchMethodException e) {
// It will never happen
LOG.error(e.getMessage(), e);
}

EvaluationContext context = SimpleEvaluationContext
.forPropertyAccessors(DataBindingPropertyAccessor.forReadOnlyAccess(), new MapAccessor())
.build();

EvaluationContextUtil.init(context);
return context;
}

private static void registerMockFunction(final StandardEvaluationContext context,
final String name,
final String methodName,
final Class<?>... parameterTypes) throws NoSuchMethodException {
context.registerFunction(name,
MockUtil.class.getDeclaredMethod(methodName, parameterTypes));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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.shenyu.plugin.mock.generator;

import org.apache.shenyu.common.utils.JsonUtils;
import org.apache.shenyu.plugin.mock.api.MockRequest;
import org.apache.shenyu.plugin.mock.util.EvaluationContextUtil;
import org.apache.shenyu.spi.Join;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.List;

/**
* Insecure support for SPEL parsed implementations.
*
* @see StandardEvaluationContext
* @see SpelExpressionParser
*/
@Join
public class StandardExpressionGenerator implements Generator<String> {

private static final ExpressionParser PARSER = new SpelExpressionParser();

private static final EvaluationContext CONTEXT = initContext();

@Override
public String getName() {
return "standardSPELExpression";
}

@Override
public String doGenerate(final List<String> params, final String rule, final MockRequest mockRequest) {

String expression = params.get(0);

CONTEXT.setVariable("req", mockRequest);

Object val = PARSER.parseExpression(expression).getValue(CONTEXT);
return JsonUtils.toJson(val);
}

@Override
public int getParamSize() {
return 1;
}

@Override
public boolean match(final String rule) {
return rule.matches("^" + getName() + "\\|.+");
}

private static EvaluationContext initContext() {

// org.springframework.security.access.expression.method.MethodSecurityEvaluationContext

StandardEvaluationContext context = new StandardEvaluationContext();

context.addPropertyAccessor(new MapAccessor());

EvaluationContextUtil.init(context);
return context;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,24 @@
* The type mock plugin data subscriber.
*/
public class MockPluginHandler implements PluginDataHandler {

public static final Supplier<CommonHandleCache<String, MockHandle>> CACHED_HANDLE = new BeanHolder<>(CommonHandleCache::new);

@Override
public void handlerRule(final RuleData ruleData) {
Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> {
MockHandle mockHandle = GsonUtils.getInstance().fromJson(s, MockHandle.class);
CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), mockHandle);
});
Optional.ofNullable(ruleData.getHandle())
.ifPresent(s -> {
MockHandle mockHandle = GsonUtils.getInstance().fromJson(s, MockHandle.class);
CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), mockHandle);
});
}

@Override
public void removeRule(final RuleData ruleData) {
Optional.ofNullable(ruleData).ifPresent(s ->
CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData)));
Optional.ofNullable(ruleData)
.ifPresent(s -> CACHED_HANDLE.get().removeHandle(CacheKeyUtils.INST.getKey(ruleData)));
}

@Override
public String pluginNamed() {
return PluginEnum.MOCK.getName();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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.shenyu.plugin.mock.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;

/**
* EvaluationContextUtil.
*/
public final class EvaluationContextUtil {

private static final Logger LOG = LoggerFactory.getLogger(EvaluationContextUtil.class);

private EvaluationContextUtil() {

}

/**
* init EvaluationContext.
*
* @param context context
*/
public static void init(final EvaluationContext context) {

try {
registerMockFunction(context, "double", "randomDouble", double.class, double.class, String[].class);

registerMockFunction(context, "bool", "bool");

registerMockFunction(context, "int", "randomInt", int.class, int.class);

registerMockFunction(context, "email", "email");

registerMockFunction(context, "phone", "phone");

registerMockFunction(context, "zh", "zh", int.class, int.class);

registerMockFunction(context, "en", "en", int.class, int.class);

registerMockFunction(context, "oneOf", "oneOf", Object[].class);

registerMockFunction(context, "current", "current", String[].class);

registerMockFunction(context, "array", "array", Object.class, int.class);

registerMockFunction(context, "nowDate", "nowDate");

registerMockFunction(context, "nowTime", "nowTime");

} catch (NoSuchMethodException e) {
// It will never happen
LOG.error(e.getMessage(), e);
}
}

private static void registerMockFunction(final EvaluationContext context,
final String name,
final String methodName,
final Class<?>... parameterTypes) throws NoSuchMethodException {
context.setVariable(name, MockUtil.class.getDeclaredMethod(methodName, parameterTypes));
}
}
Loading