260806_03_ENH: mutipart 한글 꺠짐 개선

This commit is contained in:
2026-08-06 13:57:18 +09:00
parent e8888794c3
commit f08ecf4da0
4 changed files with 23 additions and 108 deletions

View File

@@ -23,8 +23,8 @@
- Redis and scheduling are opt-in through their `kri.*.enabled` settings and matching runtime dependencies.
- HTTP bypass targets are server-configured. Never accept an arbitrary full target URL from a frontend; retain allowed-path checks and do not forward hop-by-hop headers.
- The external API client returns response bodies as documented, while bypass responses preserve raw bytes and target `Content-Type`.
- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart boundaries and part headers use US-ASCII, `formField` values use UTF-8, and file bodies preserve the supplied bytes.
- ASCII multipart filenames are sent unchanged in `filename`. Non-ASCII filenames use a collision-free ASCII `filename` fallback plus the original name in UTF-8 percent-encoded `filename*`; spaces are encoded as `%20`, not `+`.
- `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes.
- Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply.
- `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics.
### Upgrade and Verification

View File

@@ -186,15 +186,12 @@ ExternalApiResponse res = client.postMultipart(url, headers, parts);
multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하고, 필요한 boundary를 포함한
`Content-Type: multipart/form-data; boundary=...` 값을 자동 생성합니다.
boundary와 multipart 파트 헤더는 US-ASCII로 생성하고, 텍스트 필드 내용은
UTF-8, 파일 내용은 원본 `byte[]`로 전송합니다. ASCII 파일명은 기존 `filename`을
그대로 사용합니다. non-ASCII 파일명은 서버 호환성을 위해 충돌하지 않는 ASCII
fallback을 `filename`에 넣고, UTF-8 퍼센트 인코딩한 원본 파일명을 `filename*`에
함께 전송합니다. 공백은 `+`가 아닌 `%20`으로 인코딩됩니다.
multipart 파트 헤더와 텍스트 필드는 UTF-8로 인코딩하고, 파일 내용은 원본
`byte[]`로 전송합니다. ASCII와 non-ASCII 파일명 모두 원본 값을 quoted `filename`에
UTF-8 바이트로 전송하며, ASCII fallback이나 `filename*`는 추가하지 않습니다.
```http
Content-Disposition: form-data; name="file"; filename="attachment.txt";
filename*=UTF-8''%ED%95%9C%EA%B8%80-%ED%8C%8C%EC%9D%BC.txt
Content-Disposition: form-data; name="file"; filename="한글-파일.txt"
```
지원 메서드:
@@ -773,5 +770,8 @@ Endpoint:
## 변경 이력
- 2026-08-06: non-ASCII multipart 파일명을 ASCII `filename` fallback과 UTF-8 `filename*`로 함께 전송하도록 개선했습니다.
- 2026-08-06: `beta.1.6.3`에서 non-ASCII multipart 파일명을 ASCII fallback/
`filename*` 없이 원본 `filename`의 UTF-8 바이트로 전송하도록 복원했습니다.
- 2026-08-06: `beta.1.6.2`에서 non-ASCII multipart 파일명에 ASCII `filename`
fallback과 UTF-8 `filename*`를 추가했습니다.
- 2026-08-04: `kri.auth.apikey.allowed-paths`와 `kri.auth.apikey.excluded-paths`를 추가했습니다. 미설정·`null`·빈 목록은 기존 전역 API Key 인증 동작을 유지하며, 제외 패턴은 허용 패턴보다 우선합니다.

View File

@@ -4,7 +4,7 @@ plugins {
}
// 버전 변경은 여기서
def commonVer = "beta.1.6.2"
def commonVer = "beta.1.6.3"
group = 'com.kri.common'
version = commonVer

View File

@@ -10,8 +10,6 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
/**
@@ -133,33 +131,25 @@ public class ExternalApiClient {
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
Set<String> usedAsciiFilenames = collectAsciiFilenames(parts);
for (ExternalApiMultipartPart part : parts) {
if (part == null) {
throw new IllegalArgumentException("parts must not contain null");
}
writeAscii(out, "--" + boundary + CRLF);
writeAscii(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\"");
writeUtf8(out, "--" + boundary + CRLF);
writeUtf8(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\"");
if (part.getFilename() != null) {
String filename = safeHeader(part.getFilename());
if (isAscii(filename)) {
writeAscii(out, "; filename=\"" + headerValue(filename) + "\"");
} else {
String fallbackFilename = uniqueAsciiFallback(filename, usedAsciiFilenames);
writeAscii(out, "; filename=\"" + headerValue(fallbackFilename) + "\"");
writeAscii(out, "; filename*=UTF-8''" + percentEncodeUtf8(filename));
}
writeUtf8(out, "; filename=\"" + headerValue(part.getFilename()) + "\"");
}
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
if (part.getContentType() != null && !part.getContentType().isBlank()) {
writeAscii(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF);
writeUtf8(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF);
}
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
out.write(part.content());
writeAscii(out, CRLF);
writeUtf8(out, CRLF);
}
writeAscii(out, "--" + boundary + "--" + CRLF);
writeUtf8(out, "--" + boundary + "--" + CRLF);
return out.toByteArray();
}
@@ -175,85 +165,10 @@ public class ExternalApiClient {
});
}
private static void writeAscii(ByteArrayOutputStream out, String value) throws IOException {
out.write(value.getBytes(StandardCharsets.US_ASCII));
}
private static Set<String> collectAsciiFilenames(List<ExternalApiMultipartPart> parts) {
Set<String> filenames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (ExternalApiMultipartPart part : parts) {
if (part != null && part.getFilename() != null) {
String filename = safeHeader(part.getFilename());
if (isAscii(filename)) {
filenames.add(filename);
}
}
}
return filenames;
}
private static String uniqueAsciiFallback(String filename, Set<String> usedFilenames) {
String extension = asciiExtension(filename);
String candidate = "attachment" + extension;
int sequence = 2;
while (!usedFilenames.add(candidate)) {
candidate = "attachment-" + sequence++ + extension;
}
return candidate;
}
private static String asciiExtension(String filename) {
int lastSeparator = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
int lastDot = filename.lastIndexOf('.');
if (lastDot <= lastSeparator || lastDot == filename.length() - 1) {
return "";
}
String extension = filename.substring(lastDot + 1);
if (extension.length() > 16 || !extension.chars().allMatch(Character::isLetterOrDigit)
|| !isAscii(extension)) {
return "";
}
return "." + extension;
}
private static boolean isAscii(String value) {
return value.chars().allMatch(ch -> ch <= 0x7F);
}
private static String percentEncodeUtf8(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
StringBuilder encoded = new StringBuilder(bytes.length * 3);
char[] hex = "0123456789ABCDEF".toCharArray();
for (byte current : bytes) {
int unsigned = current & 0xFF;
if (isRfc5987AttrChar(unsigned)) {
encoded.append((char) unsigned);
} else {
encoded.append('%')
.append(hex[unsigned >>> 4])
.append(hex[unsigned & 0x0F]);
}
}
return encoded.toString();
}
private static boolean isRfc5987AttrChar(int value) {
return value >= 'A' && value <= 'Z'
|| value >= 'a' && value <= 'z'
|| value >= '0' && value <= '9'
|| value == '!'
|| value == '#'
|| value == '$'
|| value == '&'
|| value == '+'
|| value == '-'
|| value == '.'
|| value == '^'
|| value == '_'
|| value == '`'
|| value == '|'
|| value == '~';
private static void writeUtf8(ByteArrayOutputStream out, String value) throws IOException {
// Multipart delimiters remain byte-identical because UTF-8 is ASCII-compatible, while
// user-visible field names and filenames retain non-ASCII characters.
out.write(value.getBytes(StandardCharsets.UTF_8));
}
private static String headerValue(String value) {