diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index e36381f1..95869c07 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -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`를 돌려준다. -- 성공 `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`만 적는다). diff --git a/src/adapters/http/fileserver-upload.ts b/src/adapters/http/fileserver-upload.ts index f3832d7e..4e833b0a 100644 --- a/src/adapters/http/fileserver-upload.ts +++ b/src/adapters/http/fileserver-upload.ts @@ -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 & { 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; if (sized) { bytes = sized; @@ -564,7 +589,7 @@ async function readAnswer( response: Response, attempt: AbortableOperation, settings: Settings, - uploadedFileSchema: z.ZodType, + uploadedFileSchema: z.ZodType, sentBytes: number, ): Promise> { 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"); diff --git a/tests/integration/fileserver-upload.test.ts b/tests/integration/fileserver-upload.test.ts index ec5bd27b..79b6bd4c 100644 --- a/tests/integration/fileserver-upload.test.ts +++ b/tests/integration/fileserver-upload.test.ts @@ -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"],