fix(http): Fileserver 202 REJECTED를 파일 거절로 읽고 빈 파일은 보내지 않는다
문제: 짝 백엔드(45d2a478)는 POST /v1/files를 요청 안에서 동기로 검증하고 READY가 아닌 state를 모두 202로 답한다(FileUploadController#created). 악성 코드가 아닌 이유로 검증기가 거절하면 예외 없이 202 REJECTED다 (FinalizeUploadApplicationUseCase#applyNonAcceptVerdict). 기본 검증기 사슬의 첫 검증기(LengthVerifier)가 빈 파일을 그렇게 거절하므로, 0바이트 파일 하나로 닿는다. client schema에는 REJECTED가 없어 이 답이 SCHEMA_MISMATCH, APPLIED_CONFIRMED, "응답 형식 오류" 문구로 끝난다. 사용자는 파일을 바꾸라는 안내 대신 지원 문의를 보게 된다. 테스트의 MSW는 202 VERIFYING만 적은 백엔드 문서에서 왔고, 매뉴얼도 202를 "아직 검사 중"으로 적어 QUARANTINED(동기 검증 202의 대부분)를 끝나지 않는 대기로 보이게 한다. 고른 방법(리뷰 01-01 최소 개선 방향 (가)): - schema가 REJECTED를 받는다. 202 REJECTED는 성공이 아니라 실패 VALIDATION_REJECTED, code FILE_REJECTED, NOT_APPLIED, httpStatus 202다. 413·415·422 파일 거절과 같은 규칙이다. 백엔드는 그 레코드를 공개하지 않고 바이트 정리를 예약하므로 쓸 수 있는 파일이 남지 않는다. 공개 타입 FileserverFileState와 FileserverUploadedFile은 바꾸지 않았다(REJECTED는 성공 값으로 나오지 않는다). - 빈 파일은 읽기 전(선언 크기 0) 또는 읽은 뒤(선언 없음, 0바이트) 보내지 않고 FILE_EMPTY, NOT_STARTED로 끝낸다. 서버의 202 REJECTED에는 이유가 없어 기능이 "빈 파일"이라고 말할 수 없기 때문이다. - 201⇔READY 검사, size 일치 검사, 모르는 필드 무시는 그대로다. 201 REJECTED는 여전히 SCHEMA_MISMATCH다. - MSW 설명을 백엔드 코드(45d2a478) 기준으로 고치고 202 QUARANTINED· REJECTED 행을 더했다(1103/01-01의 "MSW가 문서에서 왔다" 부분). - 매뉴얼 7절이 202 state 셋의 뜻(VERIFYING 재검사 대기, QUARANTINED 관리자 결정 전 내려받기 불가, REJECTED는 실패)과 FILE_EMPTY를 적는다. 버린 대안: - REJECTED를 성공 state로 넘긴다: 타입 변경은 작지만 기능마다 성공 값에서 거절을 다시 찾아야 하고, 공개 타입 FileserverFileState가 넓어진다. - 빈 파일 거절만 한다: 기본 사슬은 막지만 제품이 더한 검증기의 REJECT는 그대로 SCHEMA_MISMATCH다. 위험·한계: - upload() 결과가 바뀐다. 202 REJECTED가 SCHEMA_MISMATCH에서 VALIDATION_REJECTED/FILE_REJECTED로, 빈 파일이 서버 요청에서 FILE_EMPTY로 바뀐다. CHANGELOG [계약] 한 줄이 필요하다. - 빈 파일 거절은 짝 백엔드 기본 검증기 사슬을 가정한다. 제품이 사슬에서 LengthVerifier를 빼 빈 파일을 받게 하면 client 규칙도 바꿔야 한다. - 실제 짝 백엔드를 띄워 빈 파일을 올려 보지 않았다(미검증). 응답 모양은 백엔드 코드(UploadedFileResponse, FileRecord#toDescriptor)를 읽은 것이다. - 1103/01-01의 남은 부분은 이 커밋 밖이다: 백엔드 매뉴얼의 짝 경로 안내와 docs/fileserver/http-contract.md의 202 state 목록(백엔드로 넘김), 실제 업로드 검증(미검증). 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/integration/fileserver-upload.test.ts RED(이 커밋의 테스트 + 부모 src): "reads 202 REJECTED as a refused file, not as a broken answer"(SCHEMA_MISMATCH로 끝남), "an empty file", "an undeclared size that turns out empty"(fetch를 부름)가 실패한다. Refs: 1105/01-01, 1103/01-01
This commit is contained in:
@@ -286,7 +286,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
||||
→ FileContentPort.openSource(ref) → FileByteSource
|
||||
→ 기능 어댑터: upload({ source, filename, mediaType, idempotencyKey, signal })
|
||||
→ POST /v1/files (multipart, 파트 이름 file)
|
||||
→ 201 READY 또는 202 VERIFYING + 저장된 파일 정보(fileId, sha256 …)
|
||||
→ 201 READY 또는 202 VERIFYING·QUARANTINED + 저장된 파일 정보(fileId, sha256 …)
|
||||
202 REJECTED는 저장된 파일이 아니다 → 실패 FILE_REJECTED
|
||||
```
|
||||
|
||||
- `FileByteSource`: 고른 파일의 바이트를 조각으로 읽는 값이다. `File`·`Blob`은 파일 어댑터 밖으로 나오지 않는다.
|
||||
@@ -308,13 +309,17 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
||||
|
||||
**결과 읽기**: `upload()`는 `Result<FileserverUploadedFile, AppFailure>`를 돌려준다.
|
||||
|
||||
- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 그 밖(202 `VERIFYING` 등)은 서버가 아직 검사 중이다.
|
||||
- 성공 `state`가 `READY`(201)면 바로 내려받을 수 있다. 202는 아직 내려받을 수 없다. 짝 백엔드는 업로드 요청 안에서 검증을 끝내고, `READY`가 아닌 state는 모두 202로 답한다.
|
||||
- `VERIFYING`: 검증기가 나중에 다시 보자고 했다. 서버가 다시 검사하면 `READY`가 될 수 있다.
|
||||
- `QUARANTINED`: 격리됐다. 이름·타입 불일치, 스크립트 같은 이유다. 관리자가 정하기 전까지 내려받을 수 없다. "검사 중"으로 보이면 화면이 끝나지 않는 대기가 된다.
|
||||
- `REJECTED`: 검증기가 거절했다(악성 코드 말고 다른 이유). 저장된 파일이 아니므로 성공으로 돌려주지 않는다. 실패 `VALIDATION_REJECTED`, code `FILE_REJECTED`, `NOT_APPLIED`다. 사용자가 다른 파일을 골라야 한다.
|
||||
- 빈 파일은 보내지 않는다. 짝 백엔드 기본 검증기가 빈 파일을 거절하기 때문이다. `VALIDATION_REJECTED`, code `FILE_EMPTY`, `NOT_STARTED`다.
|
||||
- 실패 `effect`:
|
||||
- `NOT_STARTED`: 보내지 않았다. 입력, 크기, 자격 증명에서 거절했다.
|
||||
- `NOT_APPLIED`: 서버가 거절했고 파일은 없다. Fileserver는 모호하지 않은 실패에서 업로드를 취소한다. 아래 `MAYBE_APPLIED` 경우를 뺀 4xx와, 5xx 중 정한 code(`STORAGE_UNAVAILABLE` 등)다.
|
||||
- `MAYBE_APPLIED`: 올라갔을 수도 있다. 응답을 잃음, 시간 초과, `details.ambiguous: true`, 409 `IDEMPOTENT_IN_FLIGHT`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`, 그 밖의 5xx다. 다시 보낼 때는 같은 `idempotencyKey`를 쓴다.
|
||||
- `APPLIED_CONFIRMED`: 서버는 만들었다고 답했지만 응답을 읽지 못했다. 다시 올리지 않는다.
|
||||
- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 화면 문구는 기능이 code로 고른다.
|
||||
- `code`는 백엔드 code 그대로다(`FILE_TOO_LARGE`, `UNSUPPORTED_MEDIA_TYPE`, `MALWARE_DETECTED` …). 백엔드가 code를 주지 않는 거절은 client가 이름을 붙인다(`FILE_REJECTED`, `FILE_EMPTY`, `FILE_NOT_READABLE`). 화면 문구는 기능이 code로 고른다.
|
||||
- client는 스스로 다시 보내지 않는다. `retryable: true`이고 `retryAfterMs`가 있으면 그만큼 기다린 뒤 기능이 다시 부른다. 서버가 상한(`maxRetryAfterMs`, 기본 30초)보다 길게 기다리라고 하면 `retryable: false`다.
|
||||
|
||||
**주의 — 멱등 키**: 짝 백엔드(`bbe944bd`)의 `POST /v1/files`는 멱등 키를 읽지 않는다(업로드 use case가 `NOT_IDEMPOTENT`).
|
||||
@@ -390,6 +395,7 @@ export const createAttachmentFeatureInput = defineFeatureAdapterContribution({
|
||||
**틀리면**
|
||||
|
||||
- 프로필의 필수 헤더가 없으면 `fetch`를 부르지 않고 `MISSING_REQUIRED_CREDENTIAL_HEADER`로 끝난다.
|
||||
- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다.
|
||||
- 파일이 `maxFileBytes`보다 크면 읽기 전에 `FILE_TOO_LARGE`(`NOT_STARTED`)다. 비어 있으면 `FILE_EMPTY`(`NOT_STARTED`)다.
|
||||
- 202 응답을 모두 "검사 중"으로 보이면 `QUARANTINED` 파일의 화면이 끝나지 않는다. state마다 따로 보인다.
|
||||
- 백엔드가 Fileserver 응답 모양이나 code를 바꾸면 검사가 잡지 못한다. 실패 판정 표(`fileserver-upload.ts`의 `NOT_APPLIED_5XX_CODES`, `MAYBE_APPLIED_CODES`)는 백엔드 `bbe944bd` 기준이다. 백엔드 SHA가 바뀌면 같이 다시 본다.
|
||||
- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 계약대로 답하는 MSW).
|
||||
- 테스트 예: `tests/integration/fileserver-upload.test.ts`(백엔드 코드가 답하는 대로 답하는 MSW. 백엔드 문서는 202 `VERIFYING`만 적는다).
|
||||
|
||||
@@ -48,7 +48,8 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
|
||||
* gives (`FileserverByteSource` is its shape), so no `File` or `Blob` crosses
|
||||
* into this adapter. Its bytes are read
|
||||
* once into the multipart body, at most `maxFileBytes` of them; a file that
|
||||
* declares a larger size is refused before reading.
|
||||
* declares a larger size is refused before reading, and an empty file is
|
||||
* never sent.
|
||||
*
|
||||
* One request per call. The client never resends: the body is the whole
|
||||
* file, and only the caller knows whether to spend that again. It keeps the
|
||||
@@ -59,6 +60,19 @@ import type { AuthOperationContext } from "./http-execution-v3.ts";
|
||||
|
||||
export type FileserverFileState = "READY" | "UPLOADED" | "VERIFYING" | "QUARANTINED";
|
||||
|
||||
/**
|
||||
* 1105/01-01. The states the backend answers `POST /v1/files` with. It
|
||||
* verifies synchronously and answers 202 for every state but `READY`
|
||||
* (`FileUploadController#created`), so a file its verifiers refused, for a
|
||||
* reason other than malware, comes back as 202 `REJECTED`. That one is not a
|
||||
* stored file: the client returns it as a `FILE_REJECTED` failure.
|
||||
*/
|
||||
type FileserverAnswerState = FileserverFileState | "REJECTED";
|
||||
|
||||
type FileserverAnswer = Readonly<
|
||||
Omit<FileserverUploadedFile, "state"> & { state: FileserverAnswerState }
|
||||
>;
|
||||
|
||||
/**
|
||||
* The bytes to send: structurally the browser-file-storage port's
|
||||
* `FileByteSource`, which a product passes as it is. Written here instead of
|
||||
@@ -75,7 +89,12 @@ export type FileserverByteSource = Readonly<{
|
||||
/** The stored file, as the backend's `UploadedFileResponse` describes it. */
|
||||
export type FileserverUploadedFile = Readonly<{
|
||||
fileId: string;
|
||||
/** `READY` with 201. Anything else came with 202: not readable yet. */
|
||||
/**
|
||||
* `READY` with 201: readable now. With 202 the file is not readable:
|
||||
* `VERIFYING` means a verifier asked to check again later, and `QUARANTINED`
|
||||
* means it is held until an operator decides, so a screen must not wait for
|
||||
* it as for a check in progress.
|
||||
*/
|
||||
state: FileserverFileState;
|
||||
filename: string;
|
||||
mediaType: string;
|
||||
@@ -191,7 +210,7 @@ export function createFileserverUploadClient(
|
||||
const uploadedFileSchema = z
|
||||
.object({
|
||||
fileId: z.string().regex(UUID),
|
||||
state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED"]),
|
||||
state: z.enum(["READY", "UPLOADED", "VERIFYING", "QUARANTINED", "REJECTED"]),
|
||||
filename: z.string().min(1).max(1_024),
|
||||
mediaType: z.string().min(1).max(255),
|
||||
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
@@ -426,6 +445,11 @@ async function readMultipartBody(
|
||||
// The server's code for the same refusal, so a feature handles one code.
|
||||
return failure("VALIDATION_REJECTED", "FILE_TOO_LARGE", notSent);
|
||||
}
|
||||
// 1105/01-01. The backend's default verifier chain rejects empty content
|
||||
// first (`LengthVerifier`), and that answer is a 202 `REJECTED` with no
|
||||
// reason. Refused here instead, under a code that says why.
|
||||
const empty = () => failure("VALIDATION_REJECTED", "FILE_EMPTY", notSent);
|
||||
if (declared === 0) return empty();
|
||||
const random = new Uint8Array(16);
|
||||
crypto.getRandomValues(random);
|
||||
const boundary = `----FileserverUpload${[...random]
|
||||
@@ -485,6 +509,7 @@ async function readMultipartBody(
|
||||
return failure("REQUEST_ABORTED", "REQUEST_ABORTED", notSent);
|
||||
}
|
||||
if (declared !== null && fileBytes !== declared) return changed();
|
||||
if (fileBytes === 0) return empty();
|
||||
let bytes: Uint8Array<ArrayBuffer>;
|
||||
if (sized) {
|
||||
bytes = sized;
|
||||
@@ -564,7 +589,7 @@ async function readAnswer(
|
||||
response: Response,
|
||||
attempt: AbortableOperation,
|
||||
settings: Settings,
|
||||
uploadedFileSchema: z.ZodType<FileserverUploadedFile>,
|
||||
uploadedFileSchema: z.ZodType<FileserverAnswer>,
|
||||
sentBytes: number,
|
||||
): Promise<Result<FileserverUploadedFile, AppFailure>> {
|
||||
const status = response.status;
|
||||
@@ -629,9 +654,19 @@ async function readAnswer(
|
||||
) {
|
||||
return unreadable("SCHEMA_MISMATCH", "UPLOADED_FILE_INVALID");
|
||||
}
|
||||
const { state, ...file } = parsed.data;
|
||||
if (state === "REJECTED") {
|
||||
// 1105/01-01. The file is the user's to replace, as with a 413, 415 or
|
||||
// 422 refusal. The backend keeps the record unpublished and schedules
|
||||
// its bytes for removal, so nothing usable was stored.
|
||||
return failure("VALIDATION_REJECTED", "FILE_REJECTED", {
|
||||
httpStatus: status,
|
||||
effect: "NOT_APPLIED",
|
||||
});
|
||||
}
|
||||
return Object.freeze({
|
||||
ok: true as const,
|
||||
value: Object.freeze({ ...parsed.data }),
|
||||
value: Object.freeze({ ...file, state }),
|
||||
});
|
||||
}
|
||||
if (status < 400) return unreadable("ENVELOPE_MISMATCH", "STATUS_UNEXPECTED");
|
||||
|
||||
@@ -12,11 +12,22 @@ import type { RestAuthProfile } from "../../src/contracts/rest-profiles.ts";
|
||||
|
||||
/**
|
||||
* 2026-11-03 01-01. The paired backend Fileserver's `POST /v1/files`, answered
|
||||
* exactly as clean-architecture-backend-template `bbe944bd` documents it:
|
||||
* docs/fileserver/http-contract.md (201 READY / 202 VERIFYING, Envelope
|
||||
* failure body, `details.ambiguous`, `Retry-After`) and docs/web/http-contract.md
|
||||
* §1–§2 (Envelope keys, 409 IDEMPOTENT_IN_FLIGHT with `Retry-After: 2`).
|
||||
* The success body is `UploadedFileResponse` wrapped by `EnvelopeBodyAdvice`.
|
||||
* as clean-architecture-backend-template `45d2a478` (the pin) answers it in
|
||||
* code, not only as its docs/fileserver/http-contract.md lists it.
|
||||
*
|
||||
* 1105/01-01. The document lists 202 VERIFYING alone. The code verifies the
|
||||
* upload synchronously and answers 201 for `READY` and 202 for every other
|
||||
* state (`FileUploadController#created`): `VERIFYING` (a verifier asked to
|
||||
* retry), `QUARANTINED` and `REJECTED` (a refusal other than malware,
|
||||
* `FinalizeUploadApplicationUseCase#applyNonAcceptVerdict`). The default
|
||||
* verifier chain rejects an empty file that way (`LengthVerifier`). A record
|
||||
* not yet published reports `application/octet-stream` (`FileRecord#toDescriptor`).
|
||||
*
|
||||
* Failure bodies, `details.ambiguous` and `Retry-After` follow the Fileserver
|
||||
* handler; Envelope keys and the idempotency answers follow
|
||||
* docs/web/http-contract.md §1–§2 (409 IDEMPOTENT_IN_FLIGHT with
|
||||
* `Retry-After: 2`). The success body is `UploadedFileResponse` wrapped by
|
||||
* `EnvelopeBodyAdvice`.
|
||||
*/
|
||||
const BASE_URL = "https://api.test/api/";
|
||||
const UPLOAD_URL = "https://api.test/api/v1/files";
|
||||
@@ -188,6 +199,40 @@ describe("Fileserver multipart upload — success", () => {
|
||||
expect(result).toEqual({ ok: true, value: uploaded("VERIFYING") });
|
||||
});
|
||||
|
||||
it("reads 202 QUARANTINED as a stored file held until an operator decides", async () => {
|
||||
const held = uploaded("QUARANTINED", { mediaType: "application/octet-stream" });
|
||||
answer({ status: 202, body: successEnvelope(held) });
|
||||
|
||||
const result = await client().client.upload(upload());
|
||||
|
||||
expect(result).toEqual({ ok: true, value: held });
|
||||
});
|
||||
|
||||
it("reads 202 REJECTED as a refused file, not as a broken answer", async () => {
|
||||
// 1105/01-01. A verifier refused the file for a reason other than malware.
|
||||
answer({
|
||||
status: 202,
|
||||
body: successEnvelope(
|
||||
uploaded("REJECTED", { mediaType: "application/octet-stream" }),
|
||||
),
|
||||
});
|
||||
|
||||
const result = await client().client.upload(upload());
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: expect.objectContaining({
|
||||
kind: "VALIDATION_REJECTED",
|
||||
code: "FILE_REJECTED",
|
||||
httpStatus: 202,
|
||||
effect: "NOT_APPLIED",
|
||||
retryable: false,
|
||||
action: "none",
|
||||
operationId: "FILESERVER_UPLOAD",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a source whose size is not declared up front", async () => {
|
||||
const captured = answer({ status: 201, body: successEnvelope(uploaded("READY")) });
|
||||
|
||||
@@ -261,6 +306,7 @@ describe("Fileserver multipart upload — answers that do not match the contract
|
||||
it.each([
|
||||
["201 with a state that is not READY", 201, successEnvelope(uploaded("VERIFYING")), "SCHEMA_MISMATCH"],
|
||||
["202 with READY", 202, successEnvelope(uploaded("READY")), "SCHEMA_MISMATCH"],
|
||||
["201 with REJECTED", 201, successEnvelope(uploaded("REJECTED")), "SCHEMA_MISMATCH"],
|
||||
["a size other than the bytes sent", 201, successEnvelope(uploaded("READY", { size: 1 })), "SCHEMA_MISMATCH"],
|
||||
["the DTO without its Envelope", 201, uploaded("READY"), "ENVELOPE_MISMATCH"],
|
||||
] as const)("%s is a created file the client cannot read", async (_label, status, body, kind) => {
|
||||
@@ -497,6 +543,9 @@ describe("Fileserver multipart upload — refused before sending", () => {
|
||||
|
||||
it.each([
|
||||
["a declared size above maxFileBytes", { source: byteSource(new Uint8Array(2_000)) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"],
|
||||
// 1105/01-01. The backend's default verifier chain rejects these.
|
||||
["an empty file", { source: byteSource(new Uint8Array(0)) }, "VALIDATION_REJECTED", "FILE_EMPTY"],
|
||||
["an undeclared size that turns out empty", { source: byteSource(new Uint8Array(0), { byteLength: null }) }, "VALIDATION_REJECTED", "FILE_EMPTY"],
|
||||
["an undeclared size that grows past maxFileBytes", { source: byteSource(new Uint8Array(2_000), { byteLength: null, chunkBytes: 512 }) }, "VALIDATION_REJECTED", "FILE_TOO_LARGE"],
|
||||
["a file that shrank after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength + 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"],
|
||||
["a file that grew after selection", { source: byteSource(FILE_BYTES, { byteLength: FILE_BYTES.byteLength - 1 }) }, "VALIDATION_REJECTED", "FILE_NOT_READABLE"],
|
||||
|
||||
Reference in New Issue
Block a user