Skip to content

Commit 4178629

Browse files
authored
fix(plugin-ai-proxy): validate defaults before activation. (#8294)
1 parent 1224745 commit 4178629

15 files changed

Lines changed: 1107 additions & 30 deletions

File tree

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/README.md‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,40 @@ Plugin updates replace the defaults rather than retaining omitted fields.
8686
Blank, `null` or `{}` configuration clears the previous connection/model values;
8787
disabling or deleting the plugin also clears its defaults. Each request receives
8888
a copy, so request-specific proxy credentials do not alter later requests.
89-
Malformed plugin configuration clears the defaults and logs a warning without
90-
interrupting configuration synchronization. A later valid update restores them.
89+
Malformed or invalid plugin configuration is rejected without replacing the
90+
last valid defaults. The handler logs known rejections at WARN with a fixed
91+
reason and plugin/namespace IDs. Unexpected runtime failures during candidate
92+
validation are rejected at ERROR with a fixed reason and the exception class,
93+
without logging the configuration, exception message or stack trace. This also
94+
applies during initial synchronization: these validation failures are handled
95+
locally and do not fail the synchronization callback.
96+
97+
Optional maxTokens must be positive and temperature must be finite and non-negative.
98+
A nonblank baseUrl must be a syntactically valid HTTP(S) URI with a host, without
99+
userinfo, query or fragment, and with either no port or a port from 1 to 65535.
100+
This common address constraint also applies to custom providers. Blank or omitted
101+
defaults are still allowed; required fields are checked when preparing requests
102+
after merging defaults and selector configuration. Provider profile query
103+
parameters and authentication are assembled separately and remain supported.
104+
105+
Rejecting defaults does not roll back the Admin configuration or stop the shared
106+
`BaseDataCache` from receiving the raw plugin data. The saved configuration, raw
107+
cache and handler's accepted defaults may therefore differ after a rejection.
108+
Use the handler's `action=rejected` log and IDs to diagnose this difference;
109+
there is no Admin rejection acknowledgement in this change. The log guarantees
110+
above cover the handler's rejection logs, not other subscribers' existing logs.
111+
91112
Defaults belong to the handler/resolver instance wired by the starter; separate
92113
application contexts do not share plugin configuration through a process-wide
93114
`Singleton`. Programmatic construction must pass the same `AiProxyPluginHandler`
94115
to `new AiProxyConfigService(handler)` and the plugin.
116+
The starter passes the runtime Provider and Protocol factories to the handler,
117+
so unregistered nonblank names are also rejected before publishing defaults.
118+
The no-argument constructor remains available for programmatic compatibility.
119+
It logs one WARN per instance to indicate that runtime registries are unavailable:
120+
it validates parsing and the common field constraints, while names are checked
121+
when requests are prepared. Programmatic callers can pass both runtime factories
122+
to enable name validation at update time as well.
95123

96124
## Exact response caching
97125

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/handler/AiProxyPluginHandler.java‎

Lines changed: 87 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,21 @@
2424
import org.apache.shenyu.common.dto.SelectorData;
2525
import org.apache.shenyu.common.dto.convert.rule.AiProxyHandle;
2626
import org.apache.shenyu.common.enums.PluginEnum;
27+
import org.apache.shenyu.common.exception.ShenyuException;
2728
import org.apache.shenyu.common.utils.GsonUtils;
2829
import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig;
2930
import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.AiProxyApiKeyCache;
31+
import org.apache.shenyu.plugin.ai.proxy.enhanced.protocol.AiProxyProtocolFactory;
32+
import org.apache.shenyu.plugin.ai.proxy.enhanced.provider.AiProxyProviderFactory;
33+
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyConfigValidator;
3034
import org.apache.shenyu.plugin.base.cache.CommonHandleCache;
3135
import org.apache.shenyu.plugin.base.handler.PluginDataHandler;
3236
import org.apache.shenyu.plugin.base.utils.CacheKeyUtils;
3337
import org.slf4j.Logger;
3438
import org.slf4j.LoggerFactory;
3539

3640
import java.util.Objects;
41+
import java.util.Set;
3742

3843
/**
3944
* this is ai proxy plugin handler.
@@ -42,30 +47,109 @@ public class AiProxyPluginHandler implements PluginDataHandler {
4247

4348
private static final Logger LOG = LoggerFactory.getLogger(AiProxyPluginHandler.class);
4449

50+
private static final Set<String> VALIDATION_REASONS = Set.of("maxTokens.nonPositive", "temperature.notFinite", "temperature.negative",
51+
"baseUrl.invalidSyntax", "baseUrl.invalidEndpoint", "provider.unregistered", "protocol.unregistered");
52+
4553
private final CommonHandleCache<String, AiProxyHandle> selectorCachedHandle = new CommonHandleCache<>();
4654

55+
private final AiProxyProviderFactory providerFactory;
56+
57+
private final AiProxyProtocolFactory protocolFactory;
58+
4759
private volatile AiCommonConfig globalConfig;
4860

61+
/**
62+
* Create a handler without registries for programmatic compatibility.
63+
* Provider and protocol names are checked when requests are prepared.
64+
* Logs one warning per instance about the missing update-time name checks.
65+
* Use the registry constructor to also check names before publishing defaults.
66+
*/
4967
public AiProxyPluginHandler() {
68+
providerFactory = null;
69+
protocolFactory = null;
70+
LOG.warn("AI proxy defaults validationMode=withoutRegistries; provider and protocol names are checked only when preparing requests");
71+
}
72+
73+
/**
74+
* Create a handler that validates names against the runtime registries.
75+
*
76+
* @param providerFactory registered providers
77+
* @param protocolFactory registered protocols
78+
*/
79+
public AiProxyPluginHandler(final AiProxyProviderFactory providerFactory, final AiProxyProtocolFactory protocolFactory) {
80+
this.providerFactory = Objects.requireNonNull(providerFactory, "providerFactory");
81+
this.protocolFactory = Objects.requireNonNull(protocolFactory, "protocolFactory");
5082
}
5183

5284
@Override
5385
public void handlerPlugin(final PluginData pluginData) {
5486
if (Objects.isNull(pluginData)) {
5587
return;
5688
}
89+
if (Boolean.FALSE.equals(pluginData.getEnabled())) {
90+
globalConfig = null;
91+
LOG.info("AI proxy defaults action=disabled pluginId={} namespaceId={}", pluginData.getId(), pluginData.getNamespaceId());
92+
return;
93+
}
94+
if (StringUtils.isBlank(pluginData.getConfig())) {
95+
globalConfig = null;
96+
LOG.info("AI proxy defaults action=cleared reason=blankConfig pluginId={} namespaceId={}", pluginData.getId(), pluginData.getNamespaceId());
97+
return;
98+
}
99+
final AiCommonConfig candidate;
57100
try {
58-
globalConfig = Boolean.FALSE.equals(pluginData.getEnabled()) || StringUtils.isBlank(pluginData.getConfig())
59-
? null : GsonUtils.getInstance().fromJson(pluginData.getConfig(), AiCommonConfig.class);
101+
candidate = GsonUtils.getInstance().fromJson(pluginData.getConfig(), AiCommonConfig.class);
60102
} catch (JsonParseException e) {
103+
LOG.warn("AI proxy defaults action=rejected reason=malformedConfig pluginId={} namespaceId={}", pluginData.getId(), pluginData.getNamespaceId());
104+
return;
105+
}
106+
if (Objects.isNull(candidate)) {
61107
globalConfig = null;
62-
LOG.warn("Invalid configuration for plugin {}; cleared global defaults", pluginData.getName());
108+
LOG.info("AI proxy defaults action=cleared reason=jsonNull pluginId={} namespaceId={}", pluginData.getId(), pluginData.getNamespaceId());
109+
return;
110+
}
111+
try {
112+
validateConfig(candidate);
113+
} catch (RuntimeException e) {
114+
logRejectedConfig(e, pluginData);
115+
return;
116+
}
117+
globalConfig = candidate;
118+
}
119+
120+
private void logRejectedConfig(final RuntimeException error, final PluginData pluginData) {
121+
String reason = error.getMessage();
122+
if (error instanceof IllegalArgumentException && Objects.nonNull(reason) && VALIDATION_REASONS.contains(reason)) {
123+
LOG.warn("AI proxy defaults action=rejected reason={} pluginId={} namespaceId={}", reason, pluginData.getId(), pluginData.getNamespaceId());
124+
return;
125+
}
126+
LOG.error("AI proxy defaults action=rejected reason=unexpectedValidationFailure exceptionType={} pluginId={} namespaceId={}",
127+
error.getClass().getSimpleName(), pluginData.getId(), pluginData.getNamespaceId());
128+
}
129+
130+
private void validateConfig(final AiCommonConfig candidate) {
131+
AiProxyConfigValidator.validate(candidate);
132+
if (Objects.nonNull(providerFactory) && StringUtils.isNotBlank(candidate.getProvider())) {
133+
try {
134+
providerFactory.getProvider(candidate.getProvider());
135+
} catch (ShenyuException e) {
136+
throw new IllegalArgumentException("provider.unregistered");
137+
}
138+
}
139+
if (Objects.nonNull(protocolFactory) && StringUtils.isNotBlank(candidate.getProtocol())) {
140+
try {
141+
protocolFactory.getProtocol(candidate.getProtocol());
142+
} catch (ShenyuException e) {
143+
throw new IllegalArgumentException("protocol.unregistered");
144+
}
63145
}
64146
}
65147

66148
@Override
67149
public void removePlugin(final PluginData pluginData) {
68150
globalConfig = null;
151+
LOG.info("AI proxy defaults action=removed pluginId={} namespaceId={}",
152+
Objects.isNull(pluginData) ? null : pluginData.getId(), Objects.isNull(pluginData) ? null : pluginData.getNamespaceId());
69153
}
70154

71155
/**

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAi.java‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamRequest;
2727
import org.apache.shenyu.plugin.ai.proxy.enhanced.model.PreparedAiRequest;
2828
import org.apache.shenyu.plugin.ai.proxy.enhanced.model.ShenyuAiRequest;
29+
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyConfigValidator;
2930
import org.springframework.http.HttpHeaders;
3031
import org.springframework.http.HttpMethod;
3132
import org.springframework.http.MediaType;
@@ -171,11 +172,7 @@ private void validateConfig(final AiCommonConfig config) {
171172
}
172173

173174
private URI resolveEndpoint(final AiCommonConfig config, final String configuredPath) {
174-
URI base = URI.create(config.getBaseUrl());
175-
if (!("http".equalsIgnoreCase(base.getScheme()) || "https".equalsIgnoreCase(base.getScheme()))
176-
|| Objects.isNull(base.getHost()) || Objects.nonNull(base.getRawQuery()) || Objects.nonNull(base.getRawFragment()) || Objects.nonNull(base.getRawUserInfo())) {
177-
throw new IllegalArgumentException("AI baseUrl must be an HTTP(S) endpoint without credentials, query or fragment");
178-
}
175+
URI base = AiProxyConfigValidator.parseBaseUrl(config.getBaseUrl());
179176
String path = configuredPath.startsWith("/") ? configuredPath.substring(1) : configuredPath;
180177
String basePath = base.getPath().endsWith("/") ? base.getPath().substring(0, base.getPath().length() - 1) : base.getPath();
181178
URI endpoint;

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyConfigService.java‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,15 +180,10 @@ private UpstreamIdentity identity(final AiCommonConfig config) {
180180
}
181181
final URI uri;
182182
try {
183-
uri = URI.create(config.getBaseUrl());
183+
uri = AiProxyConfigValidator.parseBaseUrl(config.getBaseUrl());
184184
} catch (IllegalArgumentException e) {
185185
throw new ShenyuException("AI fallback requires a valid HTTP(S) endpoint");
186186
}
187-
if (!("https".equalsIgnoreCase(uri.getScheme()) || "http".equalsIgnoreCase(uri.getScheme()))
188-
|| Objects.isNull(uri.getHost()) || Objects.nonNull(uri.getRawUserInfo())
189-
|| Objects.nonNull(uri.getRawQuery()) || Objects.nonNull(uri.getRawFragment()) || uri.getPort() == 0 || uri.getPort() > 65535) {
190-
throw new ShenyuException("AI fallback requires a valid HTTP(S) endpoint");
191-
}
192187
int port = uri.getPort() < 0 ? ("https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80) : uri.getPort();
193188
return new UpstreamIdentity(config.getProvider(), uri.getScheme().toLowerCase(Locale.ROOT), uri.getHost().toLowerCase(Locale.ROOT), port, uri.getRawPath());
194189
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.plugin.ai.proxy.enhanced.service;
19+
20+
import org.apache.commons.lang3.StringUtils;
21+
import org.apache.shenyu.plugin.ai.common.config.AiCommonConfig;
22+
23+
import java.net.URI;
24+
import java.util.Objects;
25+
26+
/**
27+
* Field constraints shared by partial defaults and resolved request configuration.
28+
*/
29+
public final class AiProxyConfigValidator {
30+
31+
private AiProxyConfigValidator() {
32+
}
33+
34+
/**
35+
* Validate optional fields without changing their values or requiring a complete configuration.
36+
*
37+
* @param config configuration to validate
38+
* @throws IllegalArgumentException with a fixed, input-free reason when a field is invalid
39+
*/
40+
public static void validate(final AiCommonConfig config) {
41+
if (Objects.nonNull(config.getMaxTokens()) && config.getMaxTokens() <= 0) {
42+
throw new IllegalArgumentException("maxTokens.nonPositive");
43+
}
44+
if (Objects.nonNull(config.getTemperature())) {
45+
if (!Double.isFinite(config.getTemperature())) {
46+
throw new IllegalArgumentException("temperature.notFinite");
47+
}
48+
if (config.getTemperature() < 0) {
49+
throw new IllegalArgumentException("temperature.negative");
50+
}
51+
}
52+
if (StringUtils.isNotBlank(config.getBaseUrl())) {
53+
parseBaseUrl(config.getBaseUrl());
54+
}
55+
}
56+
57+
/**
58+
* Parse an HTTP(S) base endpoint without credentials, query or fragment.
59+
*
60+
* @param baseUrl required base endpoint
61+
* @return parsed endpoint without changing its value
62+
* @throws IllegalArgumentException with a fixed, input-free reason if the endpoint is invalid
63+
*/
64+
public static URI parseBaseUrl(final String baseUrl) {
65+
if (StringUtils.isBlank(baseUrl)) {
66+
throw new IllegalArgumentException("baseUrl.invalidEndpoint");
67+
}
68+
final URI uri;
69+
try {
70+
uri = URI.create(baseUrl);
71+
} catch (IllegalArgumentException e) {
72+
throw new IllegalArgumentException("baseUrl.invalidSyntax");
73+
}
74+
if (!("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))
75+
|| Objects.isNull(uri.getHost()) || Objects.nonNull(uri.getRawUserInfo())
76+
|| Objects.nonNull(uri.getRawQuery()) || Objects.nonNull(uri.getRawFragment()) || uri.getPort() == 0 || uri.getPort() > 65535) {
77+
throw new IllegalArgumentException("baseUrl.invalidEndpoint");
78+
}
79+
return uri;
80+
}
81+
}

‎shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,11 @@ private PreparedExchange prepare(final String requestBody, final AiCommonConfig
765765
+ providerRequest.getProtocol() + " -> " + provider.name());
766766
}
767767
provider.capabilities().validate(providerRequest, stream);
768+
try {
769+
AiProxyConfigValidator.validate(config);
770+
} catch (IllegalArgumentException error) {
771+
throw new AiProxyException(AiProxyException.Kind.PROVIDER, "Invalid AI provider configuration", error);
772+
}
768773
AiProxyProtocol targetProtocol = aiProxyProtocolFactory.getProtocol(route.targetProtocol());
769774
AiProtocolRequestOverrides requestOverrides = new AiProtocolRequestOverrides(
770775
config.getTemperature(), config.getMaxTokens(), provider.capabilities().features().contains(

0 commit comments

Comments
 (0)