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:
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user