From 94256181fdb65dd07c3f53ff0a8fd3b874c2ae69 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 00:29:57 +0900 Subject: [PATCH 1/2] =?UTF-8?q?test(fileserver):=20copy=C2=B7move=C2=B7del?= =?UTF-8?q?ete=EC=9D=98=20=EB=82=B4=EC=9A=A9=20=ED=95=B4=EC=8B=9C=20?= =?UTF-8?q?=EC=84=A0=EC=A1=B0=EA=B1=B4=20=EA=B1=B0=EC=A0=88=EC=9D=84=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=EA=B9=8C=EC=A7=80=20=EC=8B=9C=ED=97=98?= =?UTF-8?q?=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ContentPreconditions.requireDigestMatches는 delete·copy·move가 모두 지키는 내용 버전 선조건이다. 해시가 다르면 PRECONDITION_FAILED를 낸다. copy·move 시험에는 맞지 않는 해시로 도는 시험이 없어, 두 유스케이스의 선조건 호출 줄을 지워도 :application-fileserver:test가 통과한다. delete 시험은 예외 타입만 보아 거절 코드를 바꿔도 통과한다. FileLifecycleUseCasesTest에 시험 셋을 더하고 하나를 고친다. - copy: 맞지 않는 해시면 PRECONDITION_FAILED이고 대상 레코드·복사·쿼터 예약이 없다. 맞는 해시면 대상 namespace에 READY 파일을 만들고 그 크기를 쿼터에 확정한다. - move: 맞지 않는 해시면 PRECONDITION_FAILED이고 namespace와 출발·대상 사용량이 그대로다. 맞는 해시 쪽은 이미 있는 moveChangesOnlyTheNamespaceAndNeverTheContentKey(Optional.of(DIGEST))가 본다. - delete: 같은 시험이 거절 코드 PRECONDITION_FAILED도 단언한다. 오래된 값은 다른 내용의 SHA-256 꼴(STALE_DIGEST)로 둬 거절이 비교에서만 나올 수 있게 했다. delete 시험의 옛 값 "\"stale\""도 이것으로 바꿨다. 위험·한계: main 코드는 바꾸지 않았다. web-fileserver controller가 If-Match를 넘기는 경로는 이 항목 범위 밖이라 시험하지 않는다. 검증: desktop RED·GREEN은 PR 본문에 둔다. Refs: REV-BE-0035 --- .../lifecycle/FileLifecycleUseCasesTest.java | 109 +++++++++++++++++- 1 file changed, 103 insertions(+), 6 deletions(-) diff --git a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java index 5849351e..9273681e 100644 --- a/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java +++ b/src/application/fileserver/src/test/java/dev/caskeleton/application/fileserver/lifecycle/FileLifecycleUseCasesTest.java @@ -54,6 +54,15 @@ import org.junit.jupiter.api.Test; class FileLifecycleUseCasesTest { private static final String DIGEST = "f".repeat(64); + + /** + * A well-formed SHA-256 of some other content: what a client holds after the file changed. + * + *

Shaped like a real digest so a refusal can only come from the comparison, never from the + * value failing to parse. + */ + private static final String STALE_DIGEST = "0".repeat(64); + private static final long SIZE = 10; private static final long MAX_FILE = 1024; private static final StorageNamespace TARGET = StorageNamespace.of("tenant-b"); @@ -187,18 +196,26 @@ class FileLifecycleUseCasesTest { } @Test + @DisplayName("내용 해시가 맞지 않는 삭제는 PRECONDITION_FAILED로 거절되고 레코드는 READY로 남는다") void aStaleValidatorPreconditionIsRejectedBeforeAnyTransition() { + // given FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); - assertThatThrownBy( + // when + Throwable failure = + catchThrowable( () -> delete.handle( new DeleteFileCommand( - ready.fileId(), Optional.of("\"stale\""), FileserverFixtures.context()))) - .isInstanceOf(FileserverException.class); + ready.fileId(), Optional.of(STALE_DIGEST), FileserverFixtures.context()))); - assertThat(metadata.find(ready.fileId()).orElseThrow().state()).isEqualTo(FileState.READY); - assertThat(cleanup.queued()).isEmpty(); + // then + assertThat( + List.of( + codeOf(failure), + metadata.find(ready.fileId()).orElseThrow().state(), + cleanup.queued())) + .containsExactly(FileserverErrorCode.PRECONDITION_FAILED, FileState.READY, List.of()); } @Test @@ -274,6 +291,46 @@ class FileLifecycleUseCasesTest { assertThat(copyGateway.copies()).isEmpty(); } + @Test + @DisplayName("내용 해시가 맞지 않는 복사는 PRECONDITION_FAILED로 거절되고 레코드도 바이트도 쿼터도 만들지 않는다") + void copyWithAStaleDigestIsRefusedBeforeAnythingIsWritten() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + + // when + Throwable failure = + catchThrowable(() -> copy.handle(copyOf(source, Optional.of(STALE_DIGEST)))); + + // then + assertThat( + List.of( + codeOf(failure), + copyGateway.copies(), + metadata.find(nextCopyId()).isPresent(), + quota.reservationCount())) + .containsExactly(FileserverErrorCode.PRECONDITION_FAILED, List.of(), false, 0); + } + + @Test + @DisplayName("내용 해시가 맞는 복사는 진행되어 대상 namespace에 READY 파일을 만들고 그 크기를 쿼터에 확정한다") + void copyWithTheCurrentDigestProceeds() { + // given + FileRecord source = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + copyGateway.copiesContentOf(SIZE, DIGEST); + + // when + FileView copied = copy.handle(copyOf(source, Optional.of(DIGEST))); + + // then + assertThat( + List.of( + copied.state(), + copied.descriptor().namespace(), + quota.usedBytes(QuotaScope.ofNamespace(TARGET.value())))) + .containsExactly(FileState.READY, TARGET, SIZE); + } + @Test @DisplayName("저장소가 hard high-water를 넘으면 복사는 레코드도 바이트도 만들지 않고 STORAGE_FULL로 거절된다") void copyAtTheHardHighWaterMarkIsRefusedBeforeAnyRecordOrByteIsWritten() { @@ -462,6 +519,42 @@ class FileLifecycleUseCasesTest { .containsExactly(FileserverErrorCode.ACCESS_DENIED, ready.namespace()); } + /** + * A move under a digest the file no longer has is refused and changes nothing. + * + *

The matching side — a current digest lets the move through — is {@link + * #moveChangesOnlyTheNamespaceAndNeverTheContentKey}. + */ + @Test + @DisplayName("내용 해시가 맞지 않는 이동은 PRECONDITION_FAILED로 거절되고 파일과 사용량은 그대로다") + void moveWithAStaleDigestIsRefusedAndTheFileStays() { + // given + FileRecord ready = ReadyFileFixture.ready(metadata, SIZE, DIGEST); + QuotaScope source = QuotaScope.ofNamespace(ready.namespace().value()); + QuotaScope target = QuotaScope.ofNamespace(TARGET.value()); + quota.alreadyHolds(source, SIZE); + + // when + Throwable failure = + catchThrowable( + () -> + move.handle( + new MoveFileCommand( + ready.fileId(), + TARGET, + Optional.of(STALE_DIGEST), + FileserverFixtures.context()))); + + // then + assertThat( + List.of( + codeOf(failure), + metadata.find(ready.fileId()).orElseThrow().namespace(), + quota.usedBytes(source), + quota.usedBytes(target))) + .containsExactly(FileserverErrorCode.PRECONDITION_FAILED, ready.namespace(), SIZE, 0L); + } + @Test @DisplayName("이동은 파일의 바이트를 출발 namespace 사용량에서 대상 namespace 사용량으로 옮긴다") void moveTransfersTheFilesBytesFromTheSourceNamespaceToTheTarget() { @@ -520,8 +613,12 @@ class FileLifecycleUseCasesTest { } private static CopyFileCommand copyOf(FileRecord source) { + return copyOf(source, Optional.empty()); + } + + private static CopyFileCommand copyOf(FileRecord source, Optional expectedSha256) { return new CopyFileCommand( - source.fileId(), TARGET, Optional.empty(), Optional.empty(), FileserverFixtures.context()); + source.fileId(), TARGET, Optional.empty(), expectedSha256, FileserverFixtures.context()); } /** The id the copy would give its target: the identifier factory's first file id. */ -- 2.54.0 From 6af38df5403d7aee9f2baa8a506628c72bd23ae9 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 22 Nov 2026 00:30:41 +0900 Subject: [PATCH 2/2] =?UTF-8?q?test(fileserver):=20=EC=A1=B0=EB=A6=BD=20?= =?UTF-8?q?=EC=8B=9C=ED=97=98=EC=9D=98=20=EC=9D=BD=EA=B8=B0=20=EA=B1=B0?= =?UTF-8?q?=EC=A0=88=EC=9D=B4=20=EC=A3=BC=EC=9E=85=ED=95=9C=20fileserver?= =?UTF-8?q?=20=EC=A0=95=EC=B1=85=EC=97=90=EC=84=9C=20=EB=82=98=EC=98=A4?= =?UTF-8?q?=EB=8A=94=EC=A7=80=20=EB=B3=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit downloadWithoutTheReadRoleIsRefused의 Javadoc은 이 시험이 조립이 주입한 정책에 닿는다는 것을 증명한다고 적는다. 그러나 호출자 ROLE_UNRELATED에는 file:read 매핑이 없어, 다운로드 유스케이스의 @RequiresPermission ("file:read") gate가 정책보다 먼저 403을 낸다. 단언이 상태 코드뿐이라 read-roles 배선이 틀려도 이 클래스는 초록이다. 시험 환경에 ROLE_READ_ELSEWHERE=file:read 매핑을 더하고, 그 역할과 ROLE_FILE_WRITE를 든 호출자의 다운로드가 403·ACCESS_DENIED인지 보는 시험을 더한다. gate는 통과하고 호출자는 파일 소유자이니 거절은 fileserver 정책의 읽기 역할 검사에서만 나온다. 쓰기 역할을 함께 든 것은 일부러다. read-roles 자리에 write-roles를 넘기는 배선이면 이 호출자가 다운로드에 성공해 시험이 실패한다. 항목이 예로 든 ROLE_READ_ELSEWHERE 하나만으로는 그 배선에서도 거절돼 회귀를 잡지 못한다. 옛 시험은 downloadWithoutTheReadPermissionIsRefusedByThePermissionGate로 이름을 바꾸고 code AUTHZ_INSUFFICIENT_PERMISSION을 함께 단언한다. 버린 안: 옛 시험에 code 단언만 더하기. 그 호출자로는 gate code가 나와 배선을 증명하지 못한다. 위험·한계: main의 권한 설정과 정책 코드는 바꾸지 않았다. 이 클래스는 integration lane이라 PR run에서 돌지 않는다. desktop에서 그 lane을 돌린 결과를 PR 본문에 둔다. 검증: desktop RED·GREEN은 PR 본문에 둔다. Refs: REV-BE-0027 --- .../FileserverCompositionIntegrationTest.java | 74 +++++++++++++++++-- 1 file changed, 68 insertions(+), 6 deletions(-) diff --git a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java index 72ba437e..19742776 100644 --- a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java +++ b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java @@ -36,6 +36,7 @@ import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; @@ -58,6 +59,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.postgresql.PostgreSQLContainer; +import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @@ -124,7 +126,11 @@ import tools.jackson.databind.ObjectMapper; // The fileserver's tiers grant their permissions, as security.yml ships them. This // environment loads no configuration file, so the mapping is restated rather than read. "app.authz.role-permissions[ROLE_FILE_READ]=file:read", - "app.authz.role-permissions[ROLE_FILE_WRITE]=file:upload,file:delete,file:copy," + "file:move" + "app.authz.role-permissions[ROLE_FILE_WRITE]=file:upload,file:delete,file:copy," + + "file:move", + // A tier outside the fileserver's read roles that another mapping grants file:read: the + // permission gate lets it through, so a refusal can only come from the fileserver's policy. + "app.authz.role-permissions[ROLE_READ_ELSEWHERE]=file:read" }) @AutoConfigureMockMvc(addFilters = false) class FileserverCompositionIntegrationTest { @@ -253,19 +259,52 @@ class FileserverCompositionIntegrationTest { } /** - * A caller without the read role is refused. + * A caller no mapping grants {@code file:read} is refused by the permission gate. * - *

The authorization decision belongs to the injected policy, and this proves the wiring - * actually reaches it: the same request that succeeds above fails here on the roles alone. + *

The download use case's {@code @RequiresPermission("file:read")} answers before the + * fileserver's policy is consulted, so this pins the gate's code, not the policy's. That the + * wiring reaches the injected policy is {@link + * #downloadByAWriterWhoseReadPermissionComesFromAnotherTierIsRefusedByTheFileserverPolicy}. */ @Test - void downloadWithoutTheReadRoleIsRefused() throws Exception { + @DisplayName("file:read 권한이 없는 호출자의 다운로드는 권한 gate가 AUTHZ_INSUFFICIENT_PERMISSION으로 거절한다") + void downloadWithoutTheReadPermissionIsRefusedByThePermissionGate() throws Exception { + // given String fileId = knownFileId(); actAs(Set.of("ROLE_UNRELATED")); + // when MvcResult refused = mockMvc.perform(get("/v1/files/{fileId}/content", fileId)).andReturn(); - assertThat(refused.getResponse().getStatus()).isEqualTo(403); + // then + assertThat(List.of(refused.getResponse().getStatus(), errorCodeOf(refused))) + .containsExactly(403, "AUTHZ_INSUFFICIENT_PERMISSION"); + } + + /** + * A caller the permission gate admits is still refused by the fileserver's own read tier. + * + *

{@code ROLE_READ_ELSEWHERE} carries {@code file:read}, so the gate lets the request through, + * and the caller owns the file. What it lacks is a role from {@code security.read-roles}: the + * refusal, and its {@code ACCESS_DENIED} code, can only come from the policy the composition + * injected. The caller also holds a write tier on purpose — wiring that handed the policy the + * write roles as its read roles would let this caller download, and this test would fail. + */ + @Test + @DisplayName( + "file:read 권한은 있지만 fileserver 읽기 역할이 없는 작성자의 다운로드는 fileserver 정책이 ACCESS_DENIED로 거절한다") + void downloadByAWriterWhoseReadPermissionComesFromAnotherTierIsRefusedByTheFileserverPolicy() + throws Exception { + // given + String fileId = knownFileId(); + actAs(Set.of("ROLE_FILE_WRITE", "ROLE_READ_ELSEWHERE")); + + // when + MvcResult refused = mockMvc.perform(get("/v1/files/{fileId}/content", fileId)).andReturn(); + + // then + assertThat(List.of(refused.getResponse().getStatus(), errorCodeOf(refused))) + .containsExactly(403, "ACCESS_DENIED"); } /** @@ -311,6 +350,29 @@ class FileserverCompositionIntegrationTest { List.of())); } + /** + * The stable code the shared error envelope carries, or the raw body when it is not one. + * + *

A request that should have been refused may succeed, and then the body is the file's bytes. + * Returning them, rather than failing to parse them, lets the assertion print the status and body + * that came back instead. + */ + private String errorCodeOf(MvcResult result) throws Exception { + try { + JsonNode code = + objectMapper + .readTree(result.getResponse().getContentAsByteArray()) + .path("error") + .path("code"); + if (!code.isMissingNode()) { + return code.stringValue(); + } + } catch (JacksonException ignored) { + // Not JSON at all: the raw body below says what came back. + } + return result.getResponse().getContentAsString(); + } + /** Uploads one file over the raw streaming endpoint and returns the parsed answer. */ private JsonNode upload(byte[] content, String filename) throws Exception { MvcResult result = -- 2.54.0