diff --git a/README.md b/README.md index e70612d..2615200 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile | --- | --- | | APP_DB_URL / APP_DB_USERNAME / APP_DB_PASSWORD | MySQL 连接配置 | | SERVER_PORT | 后台端口,默认 8992 | +| APP_ADMIN_ALLOWED_ORIGINS | 管理端 `/admin-api/**` 跨域白名单;`test` 默认 `https://dev-cadworld-admin.robotquan.com`,`prod` 默认 `https://cadworld-admin.robotquan.com`;可用逗号分隔的完整 origin 覆盖,显式留空关闭跨域,禁止通配符 | | OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET | 阿里云 OSS 凭证,通过环境变量或被 Git 忽略的 `.env` 提供 | | OSS_REGION / OSS_BUCKET | 默认 `oss-cn-beijing / linkerbot`,签名地域使用 `cn-beijing` | | OSS_ROOT_PREFIX | 桶内环境根目录;`test` 默认 `cadworld_dev`,`prod` 默认 `cadworld` | diff --git a/cadworld-adminapi/docs/admin-api.md b/cadworld-adminapi/docs/admin-api.md index 2323ef9..52fce87 100644 --- a/cadworld-adminapi/docs/admin-api.md +++ b/cadworld-adminapi/docs/admin-api.md @@ -8,6 +8,8 @@ JSON 请求设置 `Content-Type: application/json`。当前没有登录认证,操作人来自 `APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME`,默认 `0 / TEST_OPERATOR`。上传令牌与该操作人绑定。 +`/admin-api/**` 跨域白名单按 profile 区分:`test` 允许 `https://dev-cadworld-admin.robotquan.com`,`prod` 允许 `https://cadworld-admin.robotquan.com`。可通过 `APP_ADMIN_ALLOWED_ORIGINS` 覆盖,多个完整 origin 用逗号分隔,禁止通配符;显式留空关闭跨域。允许 `GET / HEAD / POST / PUT / DELETE / OPTIONS`,请求头允许 `Content-Type / Authorization / X-Request-Id`,支持凭证,并向前端暴露 `X-Request-Id`;预检缓存 3600 秒。OSS 直传上传的 CORS 仍需在 OSS 单独配置。 + 成功返回 HTTP 200,包括新增和删除: ```json diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/AdminCorsProperties.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/AdminCorsProperties.java new file mode 100644 index 0000000..eaeaa7e --- /dev/null +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/AdminCorsProperties.java @@ -0,0 +1,8 @@ +package com.linkerbot.cadworld.config; + +import java.util.List; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "app.admin.cors") +public record AdminCorsProperties(List allowedOrigins) { +} diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/WebConfig.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/WebConfig.java index d0cd4e1..b370684 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/WebConfig.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/config/WebConfig.java @@ -1,15 +1,39 @@ package com.linkerbot.cadworld.config; import com.linkerbot.cadworld.audit.OperationAuditInterceptor; +import java.util.List; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +@Slf4j @Configuration @RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { private final OperationAuditInterceptor audit; + private final AdminCorsProperties cors; + + @Override + public void addCorsMappings(CorsRegistry registry) { + List origins = cors.allowedOrigins(); + if (origins == null || origins.isEmpty()) return; + String[] allowed = origins.stream().map(String::trim).filter((String origin) -> !origin.isBlank()).toArray(String[]::new); + if (allowed.length == 0) return; + for (String origin : allowed) { + if (origin.contains("*")) throw new IllegalArgumentException("管理接口凭证跨域必须配置具体前端域名"); + } + registry.addMapping("/admin-api/**") + .allowedOrigins(allowed) + .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") + .allowedHeaders("Content-Type", "Authorization", "X-Request-Id") + .exposedHeaders("X-Request-Id") + .allowCredentials(true) + .maxAge(3600); + log.info("管理接口跨域配置已启用 path=/admin-api/** allowedOrigins={}", List.of(allowed)); + } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(audit).addPathPatterns("/admin-api/**"); } diff --git a/cadworld-adminapi/src/main/resources/application-prod.yml b/cadworld-adminapi/src/main/resources/application-prod.yml index eb6c8b7..cfa31e0 100644 --- a/cadworld-adminapi/src/main/resources/application-prod.yml +++ b/cadworld-adminapi/src/main/resources/application-prod.yml @@ -8,6 +8,9 @@ spring: maximum-pool-size: 20 app: + admin: + cors: + allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://cadworld-admin.robotquan.com} storage: root-prefix: ${OSS_ROOT_PREFIX:cadworld} diff --git a/cadworld-adminapi/src/main/resources/application-test.yml b/cadworld-adminapi/src/main/resources/application-test.yml index 2676486..df8ca3f 100644 --- a/cadworld-adminapi/src/main/resources/application-test.yml +++ b/cadworld-adminapi/src/main/resources/application-test.yml @@ -11,6 +11,10 @@ spring: connection-timeout: 5000 app: + admin: + cors: + # Origin 必须包含协议;可用逗号分隔的完整来源覆盖。 + allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:https://dev-cadworld-admin.robotquan.com} storage: root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev} diff --git a/cadworld-adminapi/src/main/resources/application.yml b/cadworld-adminapi/src/main/resources/application.yml index e525b50..e4067f7 100644 --- a/cadworld-adminapi/src/main/resources/application.yml +++ b/cadworld-adminapi/src/main/resources/application.yml @@ -35,6 +35,8 @@ springdoc: app: admin: + cors: + allowed-origins: ${APP_ADMIN_ALLOWED_ORIGINS:} operator: id: ${APP_ADMIN_OPERATOR_ID:0} name: ${APP_ADMIN_OPERATOR_NAME:TEST_OPERATOR} diff --git a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/config/AdminCorsConfigurationTest.java b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/config/AdminCorsConfigurationTest.java new file mode 100644 index 0000000..3c30624 --- /dev/null +++ b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/config/AdminCorsConfigurationTest.java @@ -0,0 +1,116 @@ +package com.linkerbot.cadworld.config; + +import com.linkerbot.cadworld.audit.OperationAuditInterceptor; +import com.linkerbot.cadworld.common.web.RequestIdFilter; +import com.linkerbot.cadworld.service.AdminOperatorProvider; +import com.linkerbot.cadworld.service.OperationLogService; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.http.HttpHeaders; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class AdminCorsConfigurationTest { + private final WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withInitializer(context -> context.getEnvironment().getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) + .withInitializer(new ConfigDataApplicationContextInitializer()) + .withUserConfiguration(CorsTestConfiguration.class); + + @ParameterizedTest + @CsvSource({ + "test, https://dev-cadworld-admin.robotquan.com, https://cadworld-admin.robotquan.com", + "prod, https://cadworld-admin.robotquan.com, https://dev-cadworld-admin.robotquan.com" + }) + void profileAllowsItsFrontendAndRejectsOtherOrigins(String profile, String allowedOrigin, String otherOrigin) { + runner.withPropertyValues("spring.profiles.active=" + profile).run(context -> { + assertThat(context).hasNotFailed(); + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new RequestIdFilter()).build(); + for (String method : List.of("GET", "HEAD", "POST", "PUT", "DELETE")) { + mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "content-type,authorization,x-request-id")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin)) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600")); + } + mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin) + .header("X-Request-Id", "cors-test")) + .andExpect(status().isOk()).andExpect(content().string("ok")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin)) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "X-Request-Id")) + .andExpect(header().string("X-Request-Id", "cors-test")); + for (String origin : List.of(otherOrigin, allowedOrigin.replace("https://", "http://"), "https://untrusted.example")) { + mvc.perform(options("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT")) + .andExpect(status().isForbidden()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin)) + .andExpect(status().isForbidden()); + } + }); + } + + @Test + void environmentVariableCanOverrideWhitelistWithMultipleOrigins() { + runner.withPropertyValues("spring.profiles.active=test", + "APP_ADMIN_ALLOWED_ORIGINS=http://localhost:5173,https://custom.example").run(context -> { + assertThat(context).hasNotFailed(); + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); + for (String origin : List.of("http://localhost:5173", "https://custom.example")) { + mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, origin)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin)); + } + mvc.perform(get("/admin-api/cors-probe").header(HttpHeaders.ORIGIN, "https://dev-cadworld-admin.robotquan.com")) + .andExpect(status().isForbidden()); + }); + } + + @Test + void credentialedCorsRejectsWildcardAtStartup() { + runner.withPropertyValues("spring.profiles.active=test", "APP_ADMIN_ALLOWED_ORIGINS=*") + .run(context -> assertThat(context.getStartupFailure()).hasRootCauseInstanceOf(IllegalArgumentException.class)); + } + + @TestConfiguration(proxyBeanMethods = false) + @EnableWebMvc + @EnableConfigurationProperties(AdminCorsProperties.class) + @Import(WebConfig.class) + static class CorsTestConfiguration { + @Bean OperationAuditInterceptor audit() { + return new OperationAuditInterceptor(mock(OperationLogService.class), mock(AdminOperatorProvider.class)); + } + @Bean ProbeController probeController() { return new ProbeController(); } + } + + @RestController + static class ProbeController { + @RequestMapping(value = "/admin-api/cors-probe", method = { + RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE + }) + public String probe() { return "ok"; } + } +} diff --git a/cadworld-api/docs/demand-integration.md b/cadworld-api/docs/demand-integration.md index e099a7d..1df3962 100644 --- a/cadworld-api/docs/demand-integration.md +++ b/cadworld-api/docs/demand-integration.md @@ -34,9 +34,11 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar | `APP_DEMAND_ATTACHMENT_DIRECTORY` | `data/demand-attachments`,私有附件目录 | | `APP_DEMAND_RETENTION` | `P7D`,允许 1 小时至 30 天 | | `APP_DEMAND_CONCURRENT_ANALYSES` | `4`,允许 1–16;当前进程并发上限,无等待队列 | -| `APP_DEMAND_ALLOWED_ORIGINS` | 为空表示不额外开放跨域;逗号分隔的具体前端 origin,禁止通配符 | +| `APP_DEMAND_ALLOWED_ORIGINS` | `/api/**` 跨域白名单;`test` 默认 `https://dev-cadworld.robotquan.com`,`prod` 默认 `https://cadworld.robotquan.com`;可用逗号分隔的完整 origin 覆盖,显式留空关闭跨域,禁止通配符 | | `APP_DEMAND_ROOT_IS_MOUNTING_FRAME` | `false`;本项目尚未统一根节点安装约定,保持 false | +用户端跨域支持凭证,允许 `GET / POST / DELETE / OPTIONS`,请求头允许 `Content-Type / X-Request-Id`,向前端暴露 `X-Request-Id`,预检缓存 3600 秒。浏览器请求需要携带访客 Cookie 时,使用 `credentials: 'include'`(Axios 使用 `withCredentials: true`)。公开 OSS/CDN 资源的跨域需在对应资源服务单独配置。 + 模型调用使用严格 JSON Schema、深度思考、`stream:false`、`store:false`,不启用联网工具。SSE 为后端阶段和已校验业务结果,不透传模型推理内容。接收上游响应最多 2MiB,提取的中间 JSON 最多 150000 字符。 原始提示词、模型中间 Schema、类别目录放在 `cadworld-service/src/main/resources/robot-demand/`,不作为公开静态资源。Schema 拒绝缺少字段、未知字段、非法枚举、超长值和无效证据编号。来源文字必须是所属用户消息的原文子串;助手追问不能作为用户数值证据。每张上传图片都需出现在模型图片分析中,图片与观察归属需一致。 diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java index 092d4a3..4055924 100644 --- a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java +++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/config/DemandConfiguration.java @@ -19,6 +19,7 @@ import com.linkerbot.cadworld.service.matching.MatchTextService; import com.linkerbot.cadworld.service.matching.RobotMatchingService; import java.io.IOException; import java.util.List; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @@ -27,6 +28,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** 仅用户端启动时注册需求解析服务,管理端不会绑定模型或初始化会话业务。 */ +@Slf4j @Configuration(proxyBeanMethods = false) public class DemandConfiguration { @Bean DemandRules demandRules(ObjectMapper json) throws IOException { return new DemandRules(json); } @@ -56,6 +58,7 @@ public class DemandConfiguration { for (String origin : allowed) if (origin.contains("*")) throw new IllegalArgumentException("需求接口凭证跨域必须配置具体前端域名"); registry.addMapping("/api/**").allowedOrigins(allowed).allowedMethods("GET", "POST", "DELETE", "OPTIONS") .allowedHeaders("Content-Type", "X-Request-Id").exposedHeaders("X-Request-Id").allowCredentials(true).maxAge(3600); + log.info("用户接口跨域配置已启用 path=/api/** allowedOrigins={}", List.of(allowed)); } }; } diff --git a/cadworld-api/src/main/resources/application-prod.yml b/cadworld-api/src/main/resources/application-prod.yml index d4b2032..668da40 100644 --- a/cadworld-api/src/main/resources/application-prod.yml +++ b/cadworld-api/src/main/resources/application-prod.yml @@ -13,6 +13,7 @@ spring: app: demand: secure-cookie: true + allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:https://cadworld.robotquan.com} storage: root-prefix: ${OSS_ROOT_PREFIX:cadworld} # 生产环境必须配置公开 OSS/CDN 域名,供前端直接加载模型。 diff --git a/cadworld-api/src/main/resources/application-test.yml b/cadworld-api/src/main/resources/application-test.yml index 063ee2d..5a66acf 100644 --- a/cadworld-api/src/main/resources/application-test.yml +++ b/cadworld-api/src/main/resources/application-test.yml @@ -12,6 +12,9 @@ spring: connection-timeout: 5000 app: + demand: + # Origin 必须包含协议;可用逗号分隔的完整来源覆盖。 + allowed-origins: ${APP_DEMAND_ALLOWED_ORIGINS:https://dev-cadworld.robotquan.com} storage: root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev} diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/config/ApiCorsConfigurationTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/config/ApiCorsConfigurationTest.java new file mode 100644 index 0000000..2a49bcd --- /dev/null +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/config/ApiCorsConfigurationTest.java @@ -0,0 +1,102 @@ +package com.linkerbot.cadworld.api.config; + +import com.linkerbot.cadworld.common.web.RequestIdFilter; +import com.linkerbot.cadworld.config.DemandProperties; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.http.HttpHeaders; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class ApiCorsConfigurationTest { + private final WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withInitializer(context -> context.getEnvironment().getPropertySources() + .remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) + .withInitializer(new ConfigDataApplicationContextInitializer()) + .withUserConfiguration(CorsTestConfiguration.class); + + @ParameterizedTest + @CsvSource({ + "test, https://dev-cadworld.robotquan.com, https://cadworld.robotquan.com", + "prod, https://cadworld.robotquan.com, https://dev-cadworld.robotquan.com" + }) + void profileAllowsItsFrontendAndRejectsOtherOrigins(String profile, String allowedOrigin, String otherOrigin) { + runner.withPropertyValues("spring.profiles.active=" + profile).run(context -> { + assertThat(context).hasNotFailed(); + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).addFilters(new RequestIdFilter()).build(); + for (String method : List.of("GET", "POST", "DELETE")) { + mvc.perform(options("/api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, method) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "content-type,x-request-id")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin)) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600")); + } + mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, allowedOrigin) + .header("X-Request-Id", "cors-test")) + .andExpect(status().isOk()).andExpect(content().string("ok")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin)) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "X-Request-Id")) + .andExpect(header().string("X-Request-Id", "cors-test")); + for (String origin : List.of(otherOrigin, allowedOrigin.replace("https://", "http://"), "https://untrusted.example")) { + mvc.perform(options("/api/cors-probe").header(HttpHeaders.ORIGIN, origin) + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) + .andExpect(status().isForbidden()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, origin)) + .andExpect(status().isForbidden()); + } + }); + } + + @Test + void environmentVariableCanOverrideWhitelistWithMultipleOrigins() { + runner.withPropertyValues("spring.profiles.active=test", + "APP_DEMAND_ALLOWED_ORIGINS=http://localhost:5173,https://custom.example").run(context -> { + assertThat(context).hasNotFailed(); + MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); + for (String origin : List.of("http://localhost:5173", "https://custom.example")) { + mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, origin)) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin)); + } + mvc.perform(get("/api/cors-probe").header(HttpHeaders.ORIGIN, "https://dev-cadworld.robotquan.com")) + .andExpect(status().isForbidden()); + }); + } + + @TestConfiguration(proxyBeanMethods = false) + @EnableWebMvc + @EnableConfigurationProperties(DemandProperties.class) + static class CorsTestConfiguration { + @Bean WebMvcConfigurer cors(DemandProperties properties) { return new DemandConfiguration().demandCors(properties); } + @Bean ProbeController probeController() { return new ProbeController(); } + } + + @RestController + static class ProbeController { + @RequestMapping(value = "/api/cors-probe", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE}) + public String probe() { return "ok"; } + } +}