HY-love-sleep commented on code in PR #7153:
URL: https://github.com/apache/shenyu/pull/7153#discussion_r4060127936


##########
shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-sensitive-word/src/main/java/org/apache/shenyu/plugin/ai/sensitive/word/SensitiveWordPlugin.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.ai.sensitive.word;
+
+import org.apache.shenyu.common.dto.RuleData;
+import org.apache.shenyu.common.dto.SelectorData;
+import org.apache.shenyu.common.dto.convert.rule.SensitiveWordHandle;
+import org.apache.shenyu.common.enums.PluginEnum;
+import org.apache.shenyu.plugin.api.ShenyuPluginChain;
+import org.apache.shenyu.plugin.api.exception.ResponsiveException;
+import org.apache.shenyu.plugin.api.utils.WebFluxResultUtils;
+import org.apache.shenyu.plugin.base.AbstractShenyuPlugin;
+import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
+import org.apache.shenyu.plugin.base.utils.ServerWebExchangeUtils;
+import org.apache.shenyu.plugin.ai.sensitive.word.ac.AhoCorasick;
+import 
org.apache.shenyu.plugin.ai.sensitive.word.handler.SensitiveWordPluginDataHandler;
+import 
org.apache.shenyu.plugin.ai.sensitive.word.handler.SensitiveWordPluginDataHandler.CachedDictionary;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.core.ReactiveRedisTemplate;
+import org.springframework.http.codec.HttpMessageReader;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * The sensitive word plugin, it rejects the request when its body contains a 
word of the dictionary
+ * configured for the matched rule.
+ *
+ * <p>The dictionary is read from a redis set, so it can be maintained outside 
of shenyu. A loaded
+ * dictionary is reused for the refresh interval of the rule handle, see 
{@link SensitiveWordHandle}.
+ */
+public class SensitiveWordPlugin extends AbstractShenyuPlugin {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SensitiveWordPlugin.class);
+
+    /**
+     * The error code returned to the client when the request contains 
sensitive words.
+     */
+    private static final int SENSITIVE_WORD_CODE = 1500;
+
+    private final List<HttpMessageReader<?>> readers;
+
+    public SensitiveWordPlugin(final List<HttpMessageReader<?>> readers) {
+        this.readers = readers;
+    }
+
+    @Override
+    protected Mono<Void> doExecute(final ServerWebExchange exchange,
+                                   final ShenyuPluginChain chain,
+                                   final SelectorData selector,
+                                   final RuleData rule) {
+        SensitiveWordHandle handle = 
SensitiveWordPluginDataHandler.CACHED_HANDLE.get()
+                .obtainHandle(CacheKeyUtils.INST.getKey(rule));
+        if (Objects.isNull(handle)) {
+            return chain.execute(exchange);
+        }
+        ReactiveRedisTemplate<String, String> redisTemplate = 
SensitiveWordPluginDataHandler.REDIS_TEMPLATES.get()
+                .obtainHandle(SensitiveWordPluginDataHandler.PLUGIN_NAME);
+        if (Objects.isNull(redisTemplate)) {
+            LOG.warn("sensitive word plugin: the redis template is not 
initialized, skip the sensitive word check");
+            return chain.execute(exchange);
+        }
+        return ServerWebExchangeUtils.rewriteRequestBody(exchange, readers,
+                        body -> check(exchange, redisTemplate, handle, body))
+                .flatMap(chain::execute)
+                .onErrorResume(error -> {
+                    if (error instanceof ResponsiveException) {
+                        return 
WebFluxResultUtils.failedResult((ResponsiveException) error);
+                    }
+                    return Mono.error(error);
+                });
+    }
+
+    private Mono<String> check(final ServerWebExchange exchange,
+                               final ReactiveRedisTemplate<String, String> 
redisTemplate,
+                               final SensitiveWordHandle handle,
+                               final String body) {
+        return dictionary(redisTemplate, handle)
+                .map(automaton -> automaton.search(body))

Review Comment:
   Fixed in `06f2b6109`. `dictionary()` now ends with 
`publishOn(Schedulers.boundedElastic())`, so the cached path and the redis path 
are both off the event loop before the scan. I also took the second half of 
your suggestion: `buildFailureLinks()` resolves the matches of every node once, 
so `search(...)` is linear instead of walking the failure chain per character. 
Thanks for catching it — only the very first request was off the loop before.



##########
shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-sensitive-word/src/main/java/org/apache/shenyu/plugin/ai/sensitive/word/SensitiveWordPlugin.java:
##########
@@ -0,0 +1,148 @@
+/*
+ * 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.ai.sensitive.word;
+
+import org.apache.shenyu.common.dto.RuleData;
+import org.apache.shenyu.common.dto.SelectorData;
+import org.apache.shenyu.common.dto.convert.rule.SensitiveWordHandle;
+import org.apache.shenyu.common.enums.PluginEnum;
+import org.apache.shenyu.plugin.api.ShenyuPluginChain;
+import org.apache.shenyu.plugin.api.exception.ResponsiveException;
+import org.apache.shenyu.plugin.api.utils.WebFluxResultUtils;
+import org.apache.shenyu.plugin.base.AbstractShenyuPlugin;
+import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
+import org.apache.shenyu.plugin.base.utils.ServerWebExchangeUtils;
+import org.apache.shenyu.plugin.ai.sensitive.word.ac.AhoCorasick;
+import 
org.apache.shenyu.plugin.ai.sensitive.word.handler.SensitiveWordPluginDataHandler;
+import 
org.apache.shenyu.plugin.ai.sensitive.word.handler.SensitiveWordPluginDataHandler.CachedDictionary;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.redis.core.ReactiveRedisTemplate;
+import org.springframework.http.codec.HttpMessageReader;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+import reactor.core.scheduler.Schedulers;
+
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * The sensitive word plugin, it rejects the request when its body contains a 
word of the dictionary
+ * configured for the matched rule.
+ *
+ * <p>The dictionary is read from a redis set, so it can be maintained outside 
of shenyu. A loaded
+ * dictionary is reused for the refresh interval of the rule handle, see 
{@link SensitiveWordHandle}.
+ */
+public class SensitiveWordPlugin extends AbstractShenyuPlugin {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SensitiveWordPlugin.class);
+
+    /**
+     * The error code returned to the client when the request contains 
sensitive words.
+     */
+    private static final int SENSITIVE_WORD_CODE = 1500;
+
+    private final List<HttpMessageReader<?>> readers;
+
+    public SensitiveWordPlugin(final List<HttpMessageReader<?>> readers) {
+        this.readers = readers;
+    }
+
+    @Override
+    protected Mono<Void> doExecute(final ServerWebExchange exchange,
+                                   final ShenyuPluginChain chain,
+                                   final SelectorData selector,
+                                   final RuleData rule) {
+        SensitiveWordHandle handle = 
SensitiveWordPluginDataHandler.CACHED_HANDLE.get()
+                .obtainHandle(CacheKeyUtils.INST.getKey(rule));
+        if (Objects.isNull(handle)) {
+            return chain.execute(exchange);
+        }
+        ReactiveRedisTemplate<String, String> redisTemplate = 
SensitiveWordPluginDataHandler.REDIS_TEMPLATES.get()
+                .obtainHandle(SensitiveWordPluginDataHandler.PLUGIN_NAME);
+        if (Objects.isNull(redisTemplate)) {
+            LOG.warn("sensitive word plugin: the redis template is not 
initialized, skip the sensitive word check");
+            return chain.execute(exchange);
+        }
+        return ServerWebExchangeUtils.rewriteRequestBody(exchange, readers,
+                        body -> check(exchange, redisTemplate, handle, body))
+                .flatMap(chain::execute)
+                .onErrorResume(error -> {
+                    if (error instanceof ResponsiveException) {
+                        return 
WebFluxResultUtils.failedResult((ResponsiveException) error);
+                    }
+                    return Mono.error(error);
+                });
+    }
+
+    private Mono<String> check(final ServerWebExchange exchange,
+                               final ReactiveRedisTemplate<String, String> 
redisTemplate,
+                               final SensitiveWordHandle handle,
+                               final String body) {
+        return dictionary(redisTemplate, handle)
+                .map(automaton -> automaton.search(body))
+                .flatMap(matches -> {
+                    if (matches.isEmpty()) {
+                        return Mono.just(body);
+                    }
+                    return Mono.error(new 
ResponsiveException(SENSITIVE_WORD_CODE,
+                            String.format("The request contains sensitive 
words: %s", matches), exchange));

Review Comment:
   Fixed in `06f2b6109`. The client now gets a generic message (`Request 
rejected: sensitive content detected`) and the matched words go to the plugin 
log only; the rejection code follows the `waf` plugin (403) instead of a 
plugin-invented code. The test now asserts the response body does **not** 
contain the matched word.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to