cad项目OSS共用配置

This commit is contained in:
lxp
2026-11-03 17:50:46 +08:00
parent 46496e0ab9
commit 57502588aa
9 changed files with 137 additions and 64 deletions
+22 -9
View File
@@ -98,23 +98,36 @@ interface CadDocument {
## 部署配置
先手工执行 [CAD 建表 SQL](cad-database.md),再部署后端。CAD 业务接口随应用部署可用,文件存储默认关闭;配置以下变量后开启。
先手工执行 [CAD 建表 SQL](cad-database.md),再部署后端。CAD 与现有资源共用 `vibemake.oss` 的 Bucket、地域、Endpoint、AccessKey 和各环境根目录;`vibemake.cad.oss` 仅保留独立的 `enabled` 开关,文件存储默认关闭。
| 变量 | 默认值 / 要求 |
```yaml
vibemake:
cad:
oss:
enabled: ${CAD_OSS_ENABLED:false}
```
| 配置项 | 默认值 / 要求 |
| --- | --- |
| `CAD_OSS_ENABLED` | false,配置齐全后设为 true |
| `CAD_OSS_REGION` | cn-beijing |
| `CAD_OSS_ENDPOINT` | 可选,HTTPS OSS Endpoint;不填写时按地域生成 |
| `CAD_OSS_BUCKET` | 必填,必须独立于现有公开资源 Bucket |
| `CAD_OSS_ACCESS_KEY_ID` / `CAD_OSS_ACCESS_KEY_SECRET` | 专用 RAM 凭据,通过部署环境注入 |
| `CAD_OSS_ROOT_DIRECTORY` | 沿用本环境资源根目录(test 为 vibemake_dev,prod 为 vibemake) |
| `OSS_REGION` | 与现有 OSS 共用,默认 cn-beijing |
| `OSS_ENDPOINT` | 与现有 OSS 共用,可选 HTTPS Endpoint;不填写时按地域生成 |
| `OSS_BUCKET` | 与现有资源共用同一个 Bucket |
| `OSS_ACCESS_KEY_ID` / `OSS_ACCESS_KEY_SECRET` | 与现有 OSS 共用,通过部署环境注入 |
| `vibemake.oss.root-directory` | CAD 直接使用各环境根目录:test 为 vibemake_dev,prod 为 vibemake |
| `CAD_MAX_FILE_BYTES` | 268435456;配置范围为 1 字节至 OSS 表单上限 5 GiB,需同时兼容编辑器读取上限 |
| `CAD_UPLOAD_VALIDITY` / `CAD_DOWNLOAD_VALIDITY` | 15m / 5m;范围 1 秒至 7 天 |
| `RATE_CAD_CREATE_PER_MINUTE` / `RATE_CAD_SIGN_PER_MINUTE` | 5 / 20,按当前用户独立限流 |
| `RATE_CAD_SAVE_PER_MINUTE` / `RATE_CAD_READ_PER_MINUTE` | 30 / 60,保存确认和下载签名尝试次数 |
Bucket ACL 必须 private,不能存在公共读取策略,建议开启阻止公共访问;必须从未开启版本控制(Off,Suspended 也不允许)。RAM 需要根目录 `cad-projects/*` 的 `oss:PutObject`、`oss:PutObjectAcl`、`oss:GetObject`,以及 Bucket 的 `oss:GetBucketAcl`、`oss:GetBucketPolicyStatus`、`oss:GetBucketVersioning`。后端只读取这些配置,不修改 Bucket。不要给前端 RAM 密钥。
CAD 独立开关与 `OSS_ENABLED` 分开控制:公共资源上传关闭时,只要共用连接参数完整,CAD 仍可独立开启。只有 `CAD_OSS_ENABLED` 继续生效;旧的 `CAD_OSS_BUCKET`、`CAD_OSS_REGION`、`CAD_OSS_ENDPOINT`、`CAD_OSS_ACCESS_KEY_ID`、`CAD_OSS_ACCESS_KEY_SECRET` 和 `CAD_OSS_ROOT_DIRECTORY` 均不再读取,可从 `.env` 移除。
上传策略精确绑定对象键、大小、MIME、Content-Disposition、private ACL 和禁止覆盖;后端在签发上传/下载时检查 Bucket ACL、策略及版本控制。相关行为依据 [OSS PostObject 官方文档](https://www.alibabacloud.com/help/en/oss/developer-reference/postobject);版本控制开启或暂停时,OSS 会忽略禁止覆盖参数,因此部署要求 Off。
共用 Bucket 可以是 private 或 public-read,CAD 对象必须显式为 private,不能继承 Bucket 权限;不允许 public-read-write Bucket 或公共 Bucket Policy。当前对公共 Policy 采用保守检查,任何公共 Policy 都会使 CAD 返回 `CAD_STORAGE_UNSAFE`,包括仅用于其他资源目录的公共 Policy。若现有公开资源依赖此类 Policy,需在部署时调整访问方案,应用不会自动修改整个 Bucket 的 ACL 或 Policy。
Bucket 必须从未开启版本控制(Off,Suspended 也不允许)。共用 RAM 凭据需要根目录 `cad-projects/*` 的 `oss:PutObject`、`oss:PutObjectAcl`、`oss:GetObject`、`oss:GetObjectAcl`,以及 Bucket 的 `oss:GetBucketAcl`、`oss:GetBucketPolicyStatus`、`oss:GetBucketVersioning`。后端只读取这些配置,不修改 Bucket。不要给前端 RAM 密钥。
上传策略精确绑定对象键、大小、MIME、Content-Disposition、private ACL 和禁止覆盖;后端签发凭据时检查 Bucket ACL、策略及版本控制,确认保存和签发下载时额外核验对象 ACL 必须为 private。对象 ACL 优先于 Bucket ACL,依据 [OSS 权限控制说明](https://help.aliyun.com/en/oss/user-guide/permissions-and-access-control-overview)。[OSS PostObject 官方文档](https://www.alibabacloud.com/help/en/oss/developer-reference/postobject)说明版本控制开启或暂停时会忽略禁止覆盖参数,因此部署要求 Off。
若此前已经使用独立 CAD Bucket 保存过文件,切换前需将文件按原对象键复制到 `OSS_BUCKET` 并设置 private ACL;应用只保存对象键,不记录历史 Bucket,不会自动迁移旧对象。
OSS CORS 允许真实编辑器来源的 POST、GET,允许 Content-Type;需要时暴露 Content-Length 和 Content-Disposition。直传和文件下载不携带平台 Token。生产联调须验证:匿名 GET 原对象被拒绝、有效签名能读取、过期签名不能读取、同对象二次上传被拒绝,以及完整原生设计保存后能恢复编辑。API 自动化使用存储替身,不能替代真实 Bucket 的这些验证。
@@ -73,6 +73,7 @@ vibemake:
oss:
enabled: ${OSS_ENABLED:true}
region: ${OSS_REGION:cn-beijing}
endpoint: ${OSS_ENDPOINT:}
bucket: ${OSS_BUCKET:linkerbot}
access-key-id: ${OSS_ACCESS_KEY_ID:}
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
@@ -88,12 +89,6 @@ vibemake:
download-validity: ${CAD_DOWNLOAD_VALIDITY:5m}
oss:
enabled: ${CAD_OSS_ENABLED:false}
region: ${CAD_OSS_REGION:cn-beijing}
endpoint: ${CAD_OSS_ENDPOINT:}
bucket: ${CAD_OSS_BUCKET:}
access-key-id: ${CAD_OSS_ACCESS_KEY_ID:}
access-key-secret: ${CAD_OSS_ACCESS_KEY_SECRET:}
root-directory: ${CAD_OSS_ROOT_DIRECTORY:${vibemake.oss.root-directory}}
ai:
enabled: ${AI_ENABLED:true}
api-key: ${ARK_API_KEY:}
@@ -14,6 +14,7 @@ import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.cad.CadObjectStore;
import com.linkerbot.vibemake.service.cad.CadProjectService;
import com.linkerbot.vibemake.service.config.CadProperties;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.oss.OssPostSigner;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import java.time.Duration;
@@ -38,8 +39,8 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.repository-write.worker-enabled=false", "vibemake.oss.enabled=false",
"vibemake.cad.oss.enabled=true", "vibemake.cad.oss.bucket=private-cad-tests",
"vibemake.cad.oss.access-key-id=TestCadKey", "vibemake.cad.oss.access-key-secret=test-secret",
"vibemake.cad.oss.enabled=true", "vibemake.oss.bucket=shared-oss-tests",
"vibemake.oss.access-key-id=TestCadKey", "vibemake.oss.access-key-secret=test-secret",
"vibemake.ai.enabled=false", "vibemake.git.enabled=false", "logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@@ -51,23 +52,25 @@ class CadWorkspaceTest {
@TestConfiguration
static class Config {
@Bean @Primary
FakeCadStore fakeCad(CadProperties properties, ObjectMapper json) {
return new FakeCadStore(properties, json);
FakeCadStore fakeCad(CadProperties properties, OssProperties oss, ObjectMapper json) {
return new FakeCadStore(properties, oss, json);
}
}
static class FakeCadStore implements CadObjectStore {
final Map<String, byte[]> objects = new ConcurrentHashMap<>();
final CadProperties properties;
final OssProperties oss;
final OssPostSigner signer;
boolean unavailable;
Runnable afterSign;
Runnable afterSize;
CyclicBarrier sizeBarrier;
FakeCadStore(CadProperties properties, ObjectMapper json) {
FakeCadStore(CadProperties properties, OssProperties oss, ObjectMapper json) {
this.properties = properties;
this.signer = new OssPostSigner(properties.getOss(), json);
this.oss = oss;
this.signer = new OssPostSigner(oss, json);
}
private void available() {
@@ -84,7 +87,7 @@ class CadWorkspaceTest {
afterSign = null;
action.run();
}
return new SignedUpload(properties.getOss().uploadUrl(), post.formFields(), post.expiresAt());
return new SignedUpload(oss.uploadUrl(), post.formFields(), post.expiresAt());
}
@Override
@@ -110,7 +113,7 @@ class CadWorkspaceTest {
@Override
public SignedDownload signDownload(String key, String name, Duration validity) {
available();
return new SignedDownload("https://private-cad-tests.example/" + key + "?signature=test",
return new SignedDownload(oss.uploadUrl() + "/" + key + "?signature=test",
ProjectSupport.now().plus(validity));
}
}
@@ -121,6 +124,7 @@ class CadWorkspaceTest {
@Autowired UserService users;
@Autowired TokenService tokens;
@Autowired CadProperties properties;
@Autowired OssProperties oss;
@Autowired CadProjectService service;
@Autowired FakeCadStore store;
private String token;
@@ -191,6 +195,11 @@ class CadWorkspaceTest {
assertThat(perform(auth(get(BASE + "/" + code + "/document")), 404).path("code").asText()).isEqualTo("CAD_DOCUMENT_NOT_FOUND");
JsonNode first = upload(code, 0, new byte[] {80, 75, 3, 4, 1});
assertThat(first.path("uploadUrl").asText()).isEqualTo(oss.uploadUrl());
assertThat(first.path("formFields").path("key").asText())
.startsWith(oss.getRootDirectory() + "/cad-projects/" + code + "/");
assertThat(first.path("formFields").path("x-oss-credential").asText())
.startsWith(oss.getAccessKeyId() + "/");
assertThat(confirm(code, first, 200).path("data").path("version").asLong()).isEqualTo(1);
JsonNode opened = perform(auth(get(BASE + "/" + code + "/document")), 200).path("data");
assertThat(opened.path("version").asLong()).isEqualTo(1);
@@ -25,26 +25,25 @@ import org.springframework.stereotype.Component;
public class AliyunCadObjectStore implements CadObjectStore {
private static final Logger log = LoggerFactory.getLogger(AliyunCadObjectStore.class);
private final CadProperties properties;
private final OssProperties publicOss;
private final OssProperties oss;
private final OssPostSigner signer;
private OSS client;
@Autowired
public AliyunCadObjectStore(CadProperties properties, OssProperties publicOss, ObjectMapper json) {
this(properties, publicOss, json, null);
public AliyunCadObjectStore(CadProperties properties, OssProperties oss, ObjectMapper json) {
this(properties, oss, json, null);
}
AliyunCadObjectStore(CadProperties properties, OssProperties publicOss, ObjectMapper json, OSS client) {
AliyunCadObjectStore(CadProperties properties, OssProperties oss, ObjectMapper json, OSS client) {
this.properties = properties;
this.publicOss = publicOss;
this.signer = new OssPostSigner(properties.getOss(), json);
this.oss = oss;
this.signer = new OssPostSigner(oss, json);
this.client = client;
}
private synchronized OSS client() {
OssProperties oss = properties.getOss();
if (!oss.isEnabled()) throw new BusinessException(503, "CAD_STORAGE_UNAVAILABLE", "CAD 文件存储暂未开启");
if (oss.getBucket().equals(publicOss.getBucket())) throw unsafe();
if (!properties.getOss().isEnabled()) throw new BusinessException(503, "CAD_STORAGE_UNAVAILABLE", "CAD 文件存储暂未开启");
if (!oss.hasValidStorageConfiguration()) throw unsafe("OSS_CONFIG_INVALID", null);
if (client == null) {
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
@@ -58,21 +57,27 @@ public class AliyunCadObjectStore implements CadObjectStore {
return client;
}
/** 每次签发上传/读取凭据均检查,防止部署误用公开 Bucket 或启用可覆盖的版本控制。 */
/** 允许共用 public-read Bucket,CAD 文件使用独立的 private 对象 ACL。 */
private OSS privateClient() {
OSS storage = client();
String bucket = properties.getOss().getBucket();
if (storage.getBucketAcl(bucket).getCannedACL() != CannedAccessControlList.Private
|| storage.getBucketPolicyStatus(bucket).isPublic()
|| !BucketVersioningConfiguration.OFF.equals(storage.getBucketVersioning(bucket).getStatus())) {
throw unsafe();
}
String bucket = oss.getBucket();
CannedAccessControlList acl = storage.getBucketAcl(bucket).getCannedACL();
if (acl != CannedAccessControlList.Private && acl != CannedAccessControlList.PublicRead)
throw unsafe("BUCKET_ACL_UNSAFE", null);
// 公共 Policy 可能绕过对象 ACL;不能仅因对象为 private 就忽略 Policy。
if (storage.getBucketPolicyStatus(bucket).isPublic()) throw unsafe("BUCKET_POLICY_PUBLIC", null);
if (!BucketVersioningConfiguration.OFF.equals(storage.getBucketVersioning(bucket).getStatus()))
throw unsafe("BUCKET_VERSIONING_ENABLED", null);
return storage;
}
private BusinessException unsafe() {
log.error("CAD 存储配置不安全 bucket={},需独立私有 Bucket、无公共策略且未开启版本控制",
properties.getOss().getBucket());
private void requirePrivateObject(OSS storage, String objectKey) {
if (storage.getObjectAcl(oss.getBucket(), objectKey).getPermission() != ObjectPermission.Private)
throw unsafe("OBJECT_ACL_NOT_PRIVATE", objectKey);
}
private BusinessException unsafe(String reason, String objectKey) {
log.error("CAD 存储配置或对象权限异常 bucket={} reason={} objectKey={}", oss.getBucket(), reason, objectKey);
return new BusinessException(503, "CAD_STORAGE_UNSAFE", "CAD 私有存储配置异常,请联系管理员");
}
@@ -82,7 +87,7 @@ public class AliyunCadObjectStore implements CadObjectStore {
privateClient();
OssPostSigner.SignedPost post = signer.signPrivateObject(objectKey, "application/octet-stream",
sizeBytes, validity, disposition(fileName));
return new SignedUpload(properties.getOss().uploadUrl(), post.formFields(), post.expiresAt());
return new SignedUpload(oss.uploadUrl(), post.formFields(), post.expiresAt());
} catch (OSSException error) {
throw failure("sign-upload", objectKey, error);
} catch (ClientException error) {
@@ -93,7 +98,9 @@ public class AliyunCadObjectStore implements CadObjectStore {
@Override
public long size(String objectKey) {
try {
return privateClient().getObjectMetadata(properties.getOss().getBucket(), objectKey).getContentLength();
OSS storage = privateClient();
requirePrivateObject(storage, objectKey);
return storage.getObjectMetadata(oss.getBucket(), objectKey).getContentLength();
} catch (OSSException error) {
if ("NoSuchKey".equals(error.getErrorCode())) {
log.warn("CAD 上传对象尚不存在 objectKey={} ossRequestId={}", objectKey, error.getRequestId());
@@ -109,9 +116,10 @@ public class AliyunCadObjectStore implements CadObjectStore {
public SignedDownload signDownload(String objectKey, String fileName, Duration validity) {
try {
OSS storage = privateClient();
requirePrivateObject(storage, objectKey);
Instant expiresAt = Instant.now().plus(validity);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
properties.getOss().getBucket(), objectKey, HttpMethod.GET);
oss.getBucket(), objectKey, HttpMethod.GET);
request.setExpiration(Date.from(expiresAt));
ResponseHeaderOverrides headers = new ResponseHeaderOverrides();
headers.setContentDisposition(disposition(fileName));
@@ -4,7 +4,7 @@ import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
/** CAD 专用私有存储边界,不复用公开资源的访问地址。 */
/** CAD 与公开资源共用 OSS 连接配置,设计文件使用对象级私有权限和授权下载地址。 */
public interface CadObjectStore {
record SignedUpload(String uploadUrl, Map<String, String> formFields, LocalDateTime expiresAt) {}
record SignedDownload(String downloadUrl, LocalDateTime expiresAt) {}
@@ -11,6 +11,7 @@ import com.linkerbot.vibemake.bean.entity.CadProject;
import com.linkerbot.vibemake.bean.entity.CadProjectUpload;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.config.CadProperties;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.mapper.CadProjectMapper;
import com.linkerbot.vibemake.service.mapper.CadProjectUploadMapper;
import com.linkerbot.vibemake.service.state.RateLimits;
@@ -31,6 +32,7 @@ public class CadProjectService {
private final CadProjectMapper projects;
private final CadProjectUploadMapper uploads;
private final CadProperties properties;
private final OssProperties oss;
private final CadObjectStore storage;
private final TransactionTemplate transactions;
private final RateLimits limits;
@@ -107,7 +109,7 @@ public class CadProjectService {
checkFile(input);
checkVersion(project, input.expectedVersion());
String uploadCode = Codes.next();
String key = properties.getOss().getRootDirectory() + "/cad-projects/" + code + "/" + uploadCode + "/design.sc";
String key = oss.getRootDirectory() + "/cad-projects/" + code + "/" + uploadCode + "/design.sc";
CadObjectStore.SignedUpload signature = storage.signUpload(key, input.fileName(), input.sizeBytes(), properties.getUploadValidity());
transactions.executeWithoutResult(status -> {
CadProject current = lockedOwner(userId, code);
@@ -16,7 +16,7 @@ import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "vibemake.cad")
public class CadProperties {
@Valid @NotNull
private OssProperties oss = new OssProperties();
private OssSettings oss = new OssSettings();
@Positive @Max(5368709120L)
private long maxFileBytes = 256L * 1024 * 1024;
@NotNull
@@ -24,6 +24,13 @@ public class CadProperties {
@NotNull
private Duration downloadValidity = Duration.ofMinutes(5);
/** 仅保留 CAD 独立开关,连接参数统一使用 vibemake.oss。 */
@Getter
@Setter
public static class OssSettings {
private boolean enabled;
}
@AssertTrue(message = "CAD 上传和下载签名有效期必须在 1 秒至 7 天之间")
public boolean isValidityValid() {
return valid(uploadValidity) && valid(downloadValidity);
@@ -34,7 +34,11 @@ public class OssProperties {
@AssertTrue(message = "开启 OSS 时必须配置合法的地域 ID(如 cn-beijing)、Bucket、凭据及根目录;Endpoint 为可选 HTTPS 地址")
public boolean isConfigurationValid() {
if (!enabled) return true;
return !enabled || hasValidStorageConfiguration();
}
/** CAD 独立开关开启时,即使公共资源上传关闭,仍需校验共用连接配置。 */
public boolean hasValidStorageConfiguration() {
return region != null && region.matches("[a-z0-9]+(?:-[a-z0-9]+)+")
&& !region.startsWith("oss-")
&& bucket != null && bucket.matches("[a-z0-9][a-z0-9-]{1,61}[a-z0-9]")
@@ -24,30 +24,33 @@ import java.util.Base64;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.params.provider.EnumSource;
class AliyunCadObjectStoreTest {
private final ObjectMapper json = new ObjectMapper();
private final CadProperties properties = new CadProperties();
private final OssProperties publicOss = new OssProperties();
private final OssProperties oss = new OssProperties();
private final OSS sdk = mock(OSS.class);
private AliyunCadObjectStore storage;
@BeforeEach
void setup() {
OssProperties oss = properties.getOss();
oss.setEnabled(true);
properties.getOss().setEnabled(true);
oss.setEnabled(false);
oss.setRegion("cn-beijing");
oss.setBucket("cad-private-test");
oss.setAccessKeyId("TestKey");
oss.setAccessKeySecret("test-secret");
oss.setRootDirectory("vibemake_dev");
publicOss.setBucket("public-resources");
AccessControlList acl = new AccessControlList();
acl.setCannedACL(CannedAccessControlList.Private);
when(sdk.getBucketAcl("cad-private-test")).thenReturn(acl);
when(sdk.getBucketPolicyStatus("cad-private-test")).thenReturn(new GetBucketPolicyStatusResult());
when(sdk.getBucketVersioning("cad-private-test")).thenReturn(new BucketVersioningConfiguration());
storage = new AliyunCadObjectStore(properties, publicOss, json, sdk);
ObjectAcl objectAcl = new ObjectAcl();
objectAcl.setPermission(ObjectPermission.Private);
when(sdk.getObjectAcl(eq("cad-private-test"), anyString())).thenReturn(objectAcl);
storage = new AliyunCadObjectStore(properties, oss, json, sdk);
}
@Test
@@ -72,7 +75,7 @@ class AliyunCadObjectStoreTest {
void downloadUsesRealSdkV4SignerWithPrivateCacheAndOriginalFileName() throws Exception {
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
OSS realSigner = OSSClientBuilder.create().endpoint(properties.getOss().resolvedEndpoint())
OSS realSigner = OSSClientBuilder.create().endpoint(oss.resolvedEndpoint())
.region("cn-beijing").credentialsProvider(new DefaultCredentialProvider("TestKey", "test-secret"))
.clientConfiguration(configuration).build();
try {
@@ -94,10 +97,26 @@ class AliyunCadObjectStoreTest {
}
@Test
void rejectsPublicAclAndPublicPolicyInsteadOfReturningCredentials() {
void publicReadBucketCanStorePrivateCadObjectsUsingSharedSettings() throws Exception {
AccessControlList acl = new AccessControlList();
acl.setCannedACL(CannedAccessControlList.PublicRead);
when(sdk.getBucketAcl("cad-private-test")).thenReturn(acl);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(1234);
when(sdk.getObjectMetadata("cad-private-test", "key")).thenReturn(metadata);
when(sdk.generatePresignedUrl(any(GeneratePresignedUrlRequest.class)))
.thenReturn(URI.create("https://cad-private-test.oss-cn-beijing.aliyuncs.com/key?signature=test").toURL());
assertThat(storage.signUpload("key", "x.sc", 1234, Duration.ofMinutes(15)).uploadUrl()).isEqualTo(oss.uploadUrl());
assertThat(storage.size("key")).isEqualTo(1234);
assertThat(storage.signDownload("key", "x.sc", Duration.ofMinutes(5)).downloadUrl()).contains("signature=test");
verify(sdk, never()).setBucketAcl(anyString(), any(CannedAccessControlList.class));
}
@Test
void rejectsPublicReadWriteBucketAndPublicPolicyInsteadOfReturningCredentials() {
AccessControlList acl = new AccessControlList();
acl.setCannedACL(CannedAccessControlList.PublicReadWrite);
when(sdk.getBucketAcl("cad-private-test")).thenReturn(acl);
assertUnsafe(() -> storage.signUpload("key", "x.sc", 1, Duration.ofMinutes(15)));
acl.setCannedACL(CannedAccessControlList.Private);
GetBucketPolicyStatusResult policy = new GetBucketPolicyStatusResult();
@@ -107,6 +126,18 @@ class AliyunCadObjectStoreTest {
verify(sdk, never()).generatePresignedUrl(any(GeneratePresignedUrlRequest.class));
}
@ParameterizedTest
@EnumSource(value = ObjectPermission.class, mode = EnumSource.Mode.EXCLUDE, names = "Private")
void refusesConfirmingOrSigningObjectsWithoutExplicitPrivateAcl(ObjectPermission permission) {
ObjectAcl acl = new ObjectAcl();
acl.setPermission(permission);
when(sdk.getObjectAcl("cad-private-test", "key")).thenReturn(acl);
assertUnsafe(() -> storage.size("key"));
assertUnsafe(() -> storage.signDownload("key", "x.sc", Duration.ofMinutes(5)));
verify(sdk, never()).getObjectMetadata(anyString(), anyString());
verify(sdk, never()).generatePresignedUrl(any(GeneratePresignedUrlRequest.class));
}
@ParameterizedTest
@ValueSource(strings = {"Enabled", "Suspended"})
void rejectsVersioningThatWouldAllowOverwritingAlreadySavedObjects(String status) {
@@ -116,15 +147,20 @@ class AliyunCadObjectStoreTest {
}
@Test
void requiresDistinctBucketAndExplicitlyEnabledStorage() {
publicOss.setBucket("cad-private-test");
assertUnsafe(() -> storage.signUpload("key", "x.sc", 1, Duration.ofMinutes(15)));
void cadSwitchDisablesOperationsEvenWithValidSharedSettings() {
properties.getOss().setEnabled(false);
assertThatThrownBy(() -> storage.signDownload("key", "x.sc", Duration.ofMinutes(5)))
.isInstanceOfSatisfying(BusinessException.class, error -> assertThat(error.code()).isEqualTo("CAD_STORAGE_UNAVAILABLE"));
verifyNoInteractions(sdk);
}
@Test
void rejectsIncompleteSharedCredentialsEvenWhenPublicUploadsDisabled() {
oss.setAccessKeySecret("");
assertUnsafe(() -> storage.signUpload("key", "x.sc", 1, Duration.ofMinutes(15)));
verifyNoInteractions(sdk);
}
@Test
void missingObjectAndTransportErrorsHaveStableCodes() {
OSSException missing = new OSSException("not found", "NoSuchKey", "request-test", "host", null, null, null);
@@ -140,13 +176,12 @@ class AliyunCadObjectStoreTest {
}
@Test
void validatesNestedCredentialsSizeAndSignatureValidity() {
void validatesSharedCredentialsSizeAndSignatureValidity() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
assertThat(factory.getValidator().validate(properties)).isEmpty();
properties.getOss().setAccessKeySecret("");
assertThat(factory.getValidator().validate(properties)).isNotEmpty();
properties.getOss().setEnabled(false);
assertThat(factory.getValidator().validate(properties)).isEmpty();
assertThat(oss.hasValidStorageConfiguration()).isTrue();
oss.setAccessKeySecret("");
assertThat(oss.hasValidStorageConfiguration()).isFalse();
properties.setUploadValidity(Duration.ZERO);
assertThat(factory.getValidator().validate(properties)).isNotEmpty();
properties.setUploadValidity(Duration.ofMinutes(15));