test(authoring): security regression coverage and smoke guards

- ConfiguredAuthoringSecurityPolicyTest: public/private classification
  per surface, always-blocked ranges, unresolvable hosts, no-host URIs.
- AuthoringStartupGuardTest: inline mode only boots with a
  non-production profile; docker mode always passes.
- McpClientFactoryTest: rejected endpoints never connect, disabled
  stdio refuses, envRefs are filtered by the allowlist, docker-wrapped
  commands carry the full hardening argument set.
- HttpMcpClientTest/StdioMcpClientTest: redirects to the cloud metadata
  range are not followed, 3 MiB bodies and unterminated 5 MiB lines are
  rejected (the latter with the process killed), teardown commands run
  on close.
- AuthoringFlowIntegrationTest: metadata endpoints and envRefs outside
  the allowlist are rejected at save time with actionable reasons.
- Smoke case 5 asserts the same three rejections over HTTP.

Signed-off-by: zjncs <18910855655@163.com>
This commit is contained in:
zjncs 2026-09-21 10:29:09 +08:00
parent ef1fac4a37
commit 51ad2d94c3
11 changed files with 636 additions and 3 deletions

View file

@ -13,6 +13,8 @@ set -euo pipefail
# case 4 — MCP probe: dead MCP endpoint → MCP_CONNECT_FAILED finding; a local
# fake MCP server → tools discovered in the event log; unknown
# toolFilters → warning without failing the run
# case 5 — security guards: cloud-metadata endpoints and envRefs outside the
# allowlist are rejected at binding save time
#
# Requires the local dev profile (mock auth enabled). Usage:
# scripts/authoring-smoke-test.sh [base-url]
@ -444,8 +446,60 @@ print(match["ruleCode"] if match else "none")')"
assert_equals "MCP_TOOL_FILTER_UNKNOWN warning reported" "MCP_TOOL_FILTER_UNKNOWN" "$FILTERED_RULE"
kill "$FAKE_MCP_PID" 2>/dev/null || true
wait "$FAKE_MCP_PID" 2>/dev/null || true
FAKE_MCP_PID=""
# ---------------------------------------------------------------- case 5: security guards
echo
echo "--- Case 5: binding security guards reject at save time ---"
SEC_NAME="security-skill-$RUN_ID"
SEC_RESPONSE="$(api POST /api/web/authoring/drafts \
"{\"namespaceSlug\":\"$SLUG\",\"name\":\"$SEC_NAME\"}")"
assert_code "Security guard draft created" "$SEC_RESPONSE" "0"
SEC_DRAFT_ID="$(json_field "$SEC_RESPONSE" "data.id")"
SEC_MD="---
name: $SEC_NAME
description: exercises the binding security policy
---
# Security guard skill
"
api PUT "/api/web/authoring/drafts/$SEC_DRAFT_ID/files" \
"{\"path\":\"SKILL.md\",\"content\":$(python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))' <<< "$SEC_MD"),\"contentType\":\"text/markdown\"}" >/dev/null
# Cloud metadata endpoints are always blocked — even on the local profile where
# loopback/RFC1918 endpoints are deliberately allowed. Reason text assertions
# live in AuthoringFlowIntegrationTest; here we pin the save-time rejection.
METADATA_BINDING="$(api PUT "/api/web/authoring/drafts/$SEC_DRAFT_ID/runtime" \
'{"agentType":"local-script","config":{"interpreter":"sh"},"toolAllowlist":[],"mcpServers":[{"name":"metadata-thief","transport":"http","endpoint":"http://169.254.169.254/latest/meta-data/"}]}')"
if [[ "$(json_field "$METADATA_BINDING" "code")" != "0" ]]; then
pass "Cloud metadata MCP endpoint rejected at save"
else
fail "Cloud metadata MCP endpoint must be rejected at save"
fi
# envRefs outside the (empty) allowlist are rejected: bindings must not read
# arbitrary server environment variables.
ENVREF_BINDING="$(api PUT "/api/web/authoring/drafts/$SEC_DRAFT_ID/runtime" \
'{"agentType":"local-script","config":{"interpreter":"sh"},"toolAllowlist":[],"mcpServers":[{"name":"env-hog","transport":"http","endpoint":"http://127.0.0.1:9/mcp","envRefs":["HOME"]}]}')"
if [[ "$(json_field "$ENVREF_BINDING" "code")" != "0" ]]; then
pass "envRefs outside the allowlist rejected at save"
else
fail "envRefs outside the allowlist must be rejected at save"
fi
# The LLM surface is guarded too — those requests would carry the server API key.
LLM_BINDING="$(api PUT "/api/web/authoring/drafts/$SEC_DRAFT_ID/runtime" \
'{"agentType":"openai-compatible","config":{"endpoint":"http://169.254.169.254/v1","model":"test-model"},"toolAllowlist":[],"mcpServers":[]}')"
if [[ "$(json_field "$LLM_BINDING" "code")" != "0" ]]; then
pass "Cloud metadata LLM endpoint rejected at save"
else
fail "Cloud metadata LLM endpoint must be rejected at save"
fi
# ---------------------------------------------------------------- summary
echo

View file

@ -297,8 +297,54 @@ class AuthoringFlowIntegrationTest {
.contains("SPEC_MISSING", "MCP_CONNECT_FAILED");
}
@Test
void securityPolicyRejectsUnsafeBindingsAtSaveTime() {
SkillDraft draft = draftService.createDraft(NS_SLUG, USER, "security-flow",
"exercises the binding security policy", null);
draftService.saveFile(draft.getId(), USER, "SKILL.md", validSkillMd(), "text/markdown", null, null);
// cloud metadata endpoints are always blocked — even under the test
// profile where loopback/RFC1918 endpoints are deliberately allowed
assertBindingRejected(() -> bindingService.saveBinding(draft.getId(), USER, "local-script",
Map.of("interpreter", "sh"), null,
List.of(Map.of("name", "metadata", "transport", "http",
"endpoint", "http://169.254.169.254/latest/meta-data/")), null),
"link-local");
// envRefs outside the configured allowlist are rejected: bindings must
// not be able to read arbitrary server environment variables
assertBindingRejected(() -> bindingService.saveBinding(draft.getId(), USER, "local-script",
Map.of("interpreter", "sh"), null,
List.of(Map.of("name", "env-hog", "transport", "http",
"endpoint", "http://127.0.0.1:9/mcp",
"envRefs", List.of("HOME"))), null),
"env-allowlist");
// the LLM surface is guarded too — those requests carry the server API key
assertBindingRejected(() -> bindingService.saveBinding(draft.getId(), USER, "openai-compatible",
Map.of("endpoint", "http://169.254.169.254/v1", "model", "test-model"), null, null, null),
"link-local");
// the allowlisted env ref saves fine (loopback is allowed under the test profile)
bindingService.saveBinding(draft.getId(), USER, "local-script",
Map.of("interpreter", "sh"), null,
List.of(Map.of("name", "env-ok", "transport", "http",
"endpoint", "http://127.0.0.1:9/mcp",
"envRefs", List.of("TEST_ALLOWED_MCP_VAR"))), null);
}
// ---------------------------------------------------------------- helpers
/** Save-time rejection: a 400 whose first message arg explains the reason. */
private static void assertBindingRejected(Runnable save, String reasonFragment) {
try {
save.run();
fail("binding save should have been rejected: " + reasonFragment);
} catch (com.iflytek.skillhub.domain.shared.exception.DomainBadRequestException exception) {
assertThat(String.valueOf(exception.messageArgs()[0])).contains(reasonFragment);
}
}
private ValidationRun awaitTerminal(Long runId) {
long deadline = System.currentTimeMillis() + 60_000;
while (System.currentTimeMillis() < deadline) {

View file

@ -0,0 +1,70 @@
package com.iflytek.skillhub.config;
import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* The startup guard makes host-side script execution impossible to configure
* by accident in production: inline mode outside local/dev/test fails fast.
*/
class AuthoringStartupGuardTest {
private final AuthoringProperties properties = new AuthoringProperties();
private AuthoringStartupGuard guard(MockEnvironment environment) {
return new AuthoringStartupGuard(properties, environment);
}
@Test
void inlineModeWithoutDevProfileFailsStartup() {
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.INLINE);
assertThatThrownBy(() -> guard(new MockEnvironment()).run(null))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("execution-mode=inline")
.hasMessageContaining("docker");
}
@Test
void inlineModeWithProdLikeProfileStillFails() {
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.INLINE);
MockEnvironment environment = new MockEnvironment();
environment.setActiveProfiles("redis-sentinel");
assertThatThrownBy(() -> guard(environment).run(null))
.isInstanceOf(IllegalStateException.class);
}
@Test
void inlineModeIsAllowedInLocalDevAndTestProfiles() {
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.INLINE);
for (String profile : new String[]{"local", "dev", "test"}) {
MockEnvironment environment = new MockEnvironment();
environment.setActiveProfiles(profile);
assertThatCode(() -> guard(environment).run(null))
.as("profile " + profile)
.doesNotThrowAnyException();
}
}
@Test
void dockerModePassesEverywhere() {
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.DOCKER);
assertThatCode(() -> guard(new MockEnvironment()).run(null))
.doesNotThrowAnyException();
}
@Test
void disabledLocalScriptPassesEverywhere() {
properties.getLocalScript().setEnabled(false);
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.INLINE);
assertThatCode(() -> guard(new MockEnvironment()).run(null))
.doesNotThrowAnyException();
}
}

View file

@ -0,0 +1,128 @@
package com.iflytek.skillhub.config;
import com.iflytek.skillhub.domain.authoring.service.AuthoringSecurityPolicy;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Pins the SSRF classification of user-supplied endpoints: link-local (cloud
* metadata) is always blocked, private/loopback ranges follow the per-surface
* flags, and public addresses pass.
*/
class ConfiguredAuthoringSecurityPolicyTest {
private final AuthoringProperties properties = new AuthoringProperties();
private final ConfiguredAuthoringSecurityPolicy policy =
new ConfiguredAuthoringSecurityPolicy(properties);
@Test
void publicHttpAndHttpsEndpointsAreAllowed() {
// literal public IPs keep the test hermetic: hostname resolution varies
// with the local network (VPNs and DNS64 may answer with private ranges)
assertThat(policy.endpointRejection("https://1.1.1.1/v1",
AuthoringSecurityPolicy.EndpointUse.LLM_API)).isNull();
assertThat(policy.endpointRejection("http://8.8.8.8/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNull();
}
@Test
void nonHttpSchemesAndHostlessUrlsAreRejected() {
assertThat(policy.endpointRejection("file:///etc/passwd",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("http(s)");
assertThat(policy.endpointRejection("ftp://example.com/x",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("http(s)");
assertThat(policy.endpointRejection("http://",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
assertThat(policy.endpointRejection("http:///no-host-here",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("no host");
assertThat(policy.endpointRejection("not a url at all",
AuthoringSecurityPolicy.EndpointUse.LLM_API)).isNotNull();
}
@Test
void cloudMetadataAndLinkLocalAreAlwaysBlockedEvenWhenPrivateIsAllowed() {
properties.getMcp().setAllowPrivateEndpoints(true);
properties.getOpenAiCompatible().setAllowPrivateEndpoints(true);
assertThat(policy.endpointRejection("http://169.254.169.254/latest/meta-data/",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("link-local");
assertThat(policy.endpointRejection("http://169.254.0.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("link-local");
assertThat(policy.endpointRejection("http://[fe80::1]/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
// the LLM surface carries the server API key — same absolute block
assertThat(policy.endpointRejection("http://169.254.169.254/v1",
AuthoringSecurityPolicy.EndpointUse.LLM_API)).contains("link-local");
}
@Test
void unspecifiedAndMulticastAreAlwaysBlocked() {
assertThat(policy.endpointRejection("http://0.0.0.0/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
assertThat(policy.endpointRejection("http://224.0.0.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
}
@Test
void loopbackIsBlockedByDefaultAndAllowedWithTheFlag() {
assertThat(policy.endpointRejection("http://127.0.0.1:8080/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).contains("private/loopback");
assertThat(policy.endpointRejection("http://localhost:8080/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
assertThat(policy.endpointRejection("http://[::1]/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
properties.getMcp().setAllowPrivateEndpoints(true);
assertThat(policy.endpointRejection("http://127.0.0.1:8080/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNull();
// the LLM surface has its own flag and stays blocked
assertThat(policy.endpointRejection("http://127.0.0.1:8080/v1",
AuthoringSecurityPolicy.EndpointUse.LLM_API)).isNotNull();
properties.getOpenAiCompatible().setAllowPrivateEndpoints(true);
assertThat(policy.endpointRejection("http://127.0.0.1:8080/v1",
AuthoringSecurityPolicy.EndpointUse.LLM_API)).isNull();
}
@Test
void privateV4V6AndCgnatRangesAreBlockedByDefault() {
assertThat(policy.endpointRejection("http://10.1.2.3/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
assertThat(policy.endpointRejection("http://172.16.0.9/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
assertThat(policy.endpointRejection("http://192.168.1.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
// 172.32.x.x is public (just outside the RFC1918 block)
assertThat(policy.endpointRejection("http://172.32.0.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNull();
assertThat(policy.endpointRejection("http://100.64.0.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
// 100.128.x.x is public (just outside CGNAT)
assertThat(policy.endpointRejection("http://100.128.0.1/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNull();
assertThat(policy.endpointRejection("http://[fd12::1]/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER)).isNotNull();
}
@Test
void unresolvableOrSyntheticHostsNeverPassSilently() {
// a hostname that resolves nowhere is rejected for that reason; on
// networks whose DNS answers every query with a synthetic private
// range (some VPNs), the address classification rejects it instead —
// either way the endpoint must not pass silently
String rejection = policy.endpointRejection("http://this-host-does-not-exist.invalid/mcp",
AuthoringSecurityPolicy.EndpointUse.MCP_SERVER);
assertThat(rejection).isNotNull();
}
@Test
void stdioAndEnvRefsFollowConfiguration() {
assertThat(policy.stdioTransportAllowed()).isFalse();
properties.getMcp().setStdioEnabled(true);
assertThat(policy.stdioTransportAllowed()).isTrue();
assertThat(policy.envRefAllowed("ANY_VAR")).isFalse();
properties.getMcp().setEnvAllowlist(java.util.List.of("WEATHER_API_KEY"));
assertThat(policy.envRefAllowed("WEATHER_API_KEY")).isTrue();
assertThat(policy.envRefAllowed("PATH")).isFalse();
}
}

View file

@ -0,0 +1,53 @@
package com.iflytek.skillhub.service.authoring;
import com.iflytek.skillhub.domain.authoring.service.AuthoringSecurityPolicy;
/**
* Ready-made policies for unit tests that build components by hand instead of
* through the Spring context.
*/
public final class TestingAuthoringSecurityPolicy {
private TestingAuthoringSecurityPolicy() {
}
/** Allows every endpoint, stdio, and env ref — for tests focused elsewhere. */
public static AuthoringSecurityPolicy permissive() {
return new AuthoringSecurityPolicy() {
@Override
public String endpointRejection(String url, EndpointUse use) {
return null;
}
@Override
public boolean stdioTransportAllowed() {
return true;
}
@Override
public boolean envRefAllowed(String name) {
return true;
}
};
}
/** Production posture: rejects every endpoint, stdio, and env ref. */
public static AuthoringSecurityPolicy denyAll() {
return new AuthoringSecurityPolicy() {
@Override
public String endpointRejection(String url, EndpointUse use) {
return "blocked by test policy";
}
@Override
public boolean stdioTransportAllowed() {
return false;
}
@Override
public boolean envRefAllowed(String name) {
return false;
}
};
}
}

View file

@ -10,6 +10,7 @@ import com.iflytek.skillhub.domain.authoring.runtime.RuntimeExecutionContext;
import com.iflytek.skillhub.domain.authoring.runtime.TaskResult;
import com.iflytek.skillhub.domain.authoring.spec.TaskType;
import com.iflytek.skillhub.domain.authoring.spec.ValidationTaskSpec;
import com.iflytek.skillhub.service.authoring.TestingAuthoringSecurityPolicy;
import com.iflytek.skillhub.service.authoring.mcp.McpClientFactory;
import com.iflytek.skillhub.service.authoring.mcp.TestingMcpHttpServer;
import com.sun.net.httpserver.HttpExchange;
@ -82,7 +83,9 @@ class OpenAiCompatibleRuntimeAdapterToolLoopTest {
openAi = new FakeOpenAiEndpoint();
properties = new AuthoringProperties();
properties.getOpenAiCompatible().setEnabled(true);
adapter = new OpenAiCompatibleRuntimeAdapter(properties, MAPPER, new McpClientFactory(MAPPER));
adapter = new OpenAiCompatibleRuntimeAdapter(properties, MAPPER,
new McpClientFactory(MAPPER, properties, TestingAuthoringSecurityPolicy.permissive()),
TestingAuthoringSecurityPolicy.permissive());
Files.writeString(workspace.resolve("SKILL.md"), "---\nname: test\n---\nUse the weather tools.\n");
trace.clear();
}

View file

@ -1,10 +1,16 @@
package com.iflytek.skillhub.service.authoring.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -98,4 +104,69 @@ class HttpMcpClientTest {
.hasMessageContaining("dead");
}
}
@Test
void redirectsAreNeverFollowed() throws Exception {
// a public URL answering 302 towards a link-local target is the classic
// SSRF bypass: the client must surface the redirect as an error, not follow it
AtomicInteger requests = new AtomicInteger();
HttpServer redirector = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
redirector.createContext("/", exchange -> {
requests.incrementAndGet();
exchange.getResponseHeaders().set("Location", "http://169.254.169.254/mcp");
exchange.sendResponseHeaders(302, -1);
exchange.close();
});
redirector.start();
try (HttpMcpClient client = new HttpMcpClient("redirector",
"http://127.0.0.1:" + redirector.getAddress().getPort() + "/mcp",
httpClient, objectMapper, Map.of())) {
assertThatThrownBy(() -> client.listTools(Duration.ofSeconds(5)))
.isInstanceOf(Exception.class)
.hasMessageContaining("302");
} finally {
redirector.stop(0);
}
assertThat(requests.get())
.as("the redirect target must never be requested")
.isEqualTo(1);
}
@Test
void oversizedResponseBodyIsRejected() throws Exception {
// 3 MiB body against a 2 MiB cap: a hostile endpoint must not be able to
// buffer an unbounded response in server memory
HttpServer flood = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
flood.createContext("/", exchange -> {
byte[] bytes = new byte[3 * 1024 * 1024];
java.util.Arrays.fill(bytes, (byte) 'x');
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream output = exchange.getResponseBody()) {
output.write(bytes);
}
exchange.close();
});
flood.start();
try (HttpMcpClient client = new HttpMcpClient("flood",
"http://127.0.0.1:" + flood.getAddress().getPort() + "/mcp",
httpClient, objectMapper, Map.of())) {
assertThatThrownBy(() -> client.listTools(Duration.ofSeconds(10)))
.isInstanceOf(Exception.class)
.hasMessageContaining("exceeds");
} finally {
flood.stop(0);
}
}
@Test
void readBodyCappedAllowsBodiesUnderTheLimit() throws Exception {
byte[] small = "hello".getBytes(StandardCharsets.UTF_8);
assertThat(HttpMcpClient.readBodyCapped(new ByteArrayInputStream(small), 10))
.isEqualTo("hello");
assertThatThrownBy(() -> HttpMcpClient.readBodyCapped(
new ByteArrayInputStream(small), 3))
.isInstanceOf(java.io.IOException.class)
.hasMessageContaining("exceeds");
}
}

View file

@ -0,0 +1,148 @@
package com.iflytek.skillhub.service.authoring.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iflytek.skillhub.config.AuthoringProperties;
import com.iflytek.skillhub.domain.authoring.service.AuthoringSecurityPolicy;
import com.iflytek.skillhub.service.authoring.TestingAuthoringSecurityPolicy;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Connect-time enforcement in McpClientFactory: blocked endpoints and the
* disabled stdio transport fail before any connection or process is created,
* envRefs are filtered through the policy, and docker execution mode wraps
* stdio commands in the hardened container profile.
*/
class McpClientFactoryTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final AuthoringProperties properties = new AuthoringProperties();
private McpClientFactory factory(AuthoringSecurityPolicy policy) {
return new McpClientFactory(MAPPER, properties, policy);
}
/** Allows everything except env refs (for the envRefs filter test). */
private final AuthoringSecurityPolicy pathOnlyEnvRefs = new AuthoringSecurityPolicy() {
@Override
public String endpointRejection(String url, EndpointUse use) {
return null;
}
@Override
public boolean stdioTransportAllowed() {
return true;
}
@Override
public boolean envRefAllowed(String name) {
return "PATH".equals(name);
}
};
@Test
void httpEndpointRejectedByPolicyNeverConnects() {
AuthoringSecurityPolicy blocking = new AuthoringSecurityPolicy() {
@Override
public String endpointRejection(String url, EndpointUse use) {
return "blocked by test policy";
}
@Override
public boolean stdioTransportAllowed() {
return true;
}
@Override
public boolean envRefAllowed(String name) {
return true;
}
};
assertThatThrownBy(() -> factory(blocking).create(Map.of(
"name", "evil", "transport", "http", "endpoint", "http://169.254.169.254/mcp")))
.isInstanceOf(IOException.class)
.hasMessageContaining("endpoint rejected");
}
@Test
void stdioIsRefusedWhenDisabled() {
AuthoringSecurityPolicy stdioDisabled = new AuthoringSecurityPolicy() {
@Override
public String endpointRejection(String url, EndpointUse use) {
return null;
}
@Override
public boolean stdioTransportAllowed() {
return false;
}
@Override
public boolean envRefAllowed(String name) {
return true;
}
};
assertThatThrownBy(() -> factory(stdioDisabled).create(
Map.of("name", "local", "transport", "stdio", "command", "sleep 30")))
.isInstanceOf(IOException.class)
.hasMessageContaining("stdio transport is disabled");
}
@Test
void envRefsNotInAllowlistNeverReachTheSpawnedProcess() {
// HOME exists in every environment, so dropping it is observable: only
// the allowlisted PATH survives the filter
Map<String, Object> server = Map.of(
"name", "envtest", "transport", "stdio", "command", "sleep 30",
"envRefs", List.of("PATH", "HOME"));
Map<String, String> environment = factory(pathOnlyEnvRefs).environmentOf(server);
assertThat(environment).containsKey("PATH");
assertThat(environment).doesNotContainKey("HOME");
}
@Test
void dockerModeWrapsStdioCommandInHardenedContainer() {
properties.getMcp().setStdioEnabled(true);
properties.getLocalScript().setExecutionMode(
AuthoringProperties.ScriptExecutionMode.DOCKER);
properties.getMcp().getDocker().setImage("alpine:3.20");
List<String> wrapped = factory(TestingAuthoringSecurityPolicy.permissive())
.dockerWrappedCommand("skillhub-mcp-test-abcd1234",
List.of("python3", "-m", "fake_server"),
Map.of("WEATHER_API_KEY", "secret-value"));
assertThat(wrapped.get(0)).isEqualTo("docker");
assertThat(wrapped).containsSubsequence("run", "--rm", "--name",
"skillhub-mcp-test-abcd1234");
assertThat(wrapped).containsSubsequence("--network", "none");
assertThat(wrapped).containsSubsequence("--memory", "256m");
assertThat(wrapped).containsSubsequence("--cpus", "1.0");
assertThat(wrapped).containsSubsequence("--pids-limit", "128");
assertThat(wrapped).contains("--read-only");
assertThat(wrapped).containsSubsequence("--cap-drop", "ALL");
assertThat(wrapped).contains("no-new-privileges");
// environment travels as -e flags, not through the parent environment
assertThat(wrapped).containsSubsequence("-e", "WEATHER_API_KEY=secret-value");
// the image runs the declared command
int image = wrapped.indexOf("alpine:3.20");
assertThat(image).isPositive();
assertThat(wrapped.subList(image + 1, wrapped.size()))
.containsExactly("python3", "-m", "fake_server");
}
@Test
void containerNamesAreSanitizedAndUnique() {
String first = McpClientFactory.containerName("my server!");
String second = McpClientFactory.containerName("my server!");
assertThat(first).startsWith("skillhub-mcp-my-server-");
assertThat(first).isNotEqualTo(second);
assertThat(McpClientFactory.containerName(null)).startsWith("skillhub-mcp-unknown-");
}
}

View file

@ -1,8 +1,10 @@
package com.iflytek.skillhub.service.authoring.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iflytek.skillhub.config.AuthoringProperties;
import com.iflytek.skillhub.domain.authoring.validation.FindingDraft;
import com.iflytek.skillhub.domain.authoring.validation.FindingSeverity;
import com.iflytek.skillhub.service.authoring.TestingAuthoringSecurityPolicy;
import java.time.Duration;
import java.util.List;
import java.util.Map;
@ -19,8 +21,9 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class McpProbeServiceTest {
private final McpProbeService probeService =
new McpProbeService(new McpClientFactory(new ObjectMapper()));
private final McpProbeService probeService = new McpProbeService(new McpClientFactory(
new ObjectMapper(), new AuthoringProperties(),
TestingAuthoringSecurityPolicy.permissive()));
private TestingMcpHttpServer mcpServer;

View file

@ -1,6 +1,8 @@
package com.iflytek.skillhub.service.authoring.mcp;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
@ -86,4 +88,46 @@ class StdioMcpClientTest {
.listTools(Duration.ofSeconds(10)))
.isInstanceOf(Exception.class);
}
@Test
void unterminatedHugeLineIsRejectedAndTheProcessKilled() {
// a hostile stdio server streaming one endless line must not exhaust
// memory: the capped reader destroys the process past the limit
String floodServer = """
import sys, time
sys.stdout.write('x' * (5 * 1024 * 1024))
sys.stdout.flush()
time.sleep(60)
""";
StdioMcpClient client;
try {
client = new StdioMcpClient("flood", List.of("python3", "-c", floodServer),
Map.of(), new ObjectMapper());
} catch (Exception exception) {
// python3 disappeared between the class check and here
org.junit.jupiter.api.Assumptions.assumeTrue(false, exception.getMessage());
return;
}
assertThatThrownBy(() -> client.listTools(Duration.ofSeconds(30)))
.isInstanceOf(Exception.class)
.hasMessageContaining("longer than");
client.close();
}
@Test
void teardownCommandRunsOnClose() throws Exception {
// docker-wrapped stdio servers rely on this: a killed docker client can
// leave its container behind, so close() must run the cleanup command
Path marker = Files.createTempFile("skillhub-stdio-teardown", ".marker");
Files.deleteIfExists(marker);
StdioMcpClient client = new StdioMcpClient("cleaned",
List.of("python3", "-c", FAKE_SERVER), Map.of(), new ObjectMapper(),
List.of("touch", marker.toString()), false);
client.listTools(Duration.ofSeconds(10));
client.close();
assertThat(Files.exists(marker))
.as("the teardown command must have run after process destruction")
.isTrue();
Files.deleteIfExists(marker);
}
}

View file

@ -47,6 +47,19 @@ skillhub:
security:
scanner:
enabled: false
authoring:
local-script:
# tests exercise the inline script runtime directly; no docker needed
execution-mode: inline
openai-compatible:
# fake LLM endpoints in tests bind to loopback
allow-private-endpoints: true
mcp:
# fake MCP servers in tests bind to loopback; link-local stays blocked
allow-private-endpoints: true
stdio-enabled: true
# the one variable bindings may reference in tests; everything else is rejected
env-allowlist: TEST_ALLOWED_MCP_VAR
logging:
level: