Repository navigation
[GLB-264] fix(image-metadata): 기존 사진 자르기 시 S3 CORS와 관계없이 원본 화질 사진 사용 #366
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
youngju6143
wants to merge
2
commits into
develop
Choose a base branch
from
bug/GLB-264
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { afterEach, beforeEach, expect, it, vi } from "vitest"; | ||
|
|
||
| import { GET } from "./route"; | ||
|
|
||
| const { access } = vi.hoisted(() => ({ access: { denied: null as NextResponse | null } })); | ||
|
|
||
| vi.mock("@/config/env", () => ({ env: { S3_BASE_URL: "https://globber-dev.s3.ap-northeast-2.amazonaws.com/" } })); | ||
| vi.mock("../_lib/mapsAccess", () => ({ checkMapsAccess: async () => access.denied })); | ||
|
|
||
| const PHOTO_URL = "https://globber-prod.s3.ap-northeast-2.amazonaws.com/photo.jpg"; | ||
| const request = (url?: string) => | ||
| new NextRequest(`https://globber.world/api/image-proxy${url ? `?url=${encodeURIComponent(url)}` : ""}`); | ||
|
|
||
| const fetchMock = vi.fn(); | ||
|
|
||
| beforeEach(() => { | ||
| access.denied = null; | ||
| fetchMock.mockReset(); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| }); | ||
|
|
||
| it("로그인 확인에서 막히면 S3를 호출하지 않고 그 응답을 돌려준다", async () => { | ||
| access.denied = NextResponse.json({ error: "Unauthorized" }, { status: 401 }); | ||
|
|
||
| const response = await GET(request(PHOTO_URL)); | ||
|
|
||
| expect(response.status).toBe(401); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["url이 없으면", undefined, 400], | ||
| ["url 형식이 아니면", "not a url", 400], | ||
| ["허용하지 않은 호스트면", "https://evil.example/photo.jpg", 403], | ||
| ["https가 아니면", "http://globber-prod.s3.ap-northeast-2.amazonaws.com/photo.jpg", 403], | ||
| ])("%s S3를 호출하지 않는다", async (_, url, status) => { | ||
| const response = await GET(request(url)); | ||
|
|
||
| expect(response.status).toBe(status); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("허용한 S3 사진은 원본 그대로 전달하고, 리다이렉트는 따라가지 않는다", async () => { | ||
| fetchMock.mockResolvedValue(new Response("image-bytes", { headers: { "content-type": "image/jpeg" } })); | ||
|
|
||
| const response = await GET(request(PHOTO_URL)); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(response.headers.get("content-type")).toBe("image/jpeg"); | ||
| expect(response.headers.get("x-content-type-options")).toBe("nosniff"); | ||
| expect(await response.text()).toBe("image-bytes"); | ||
| expect(fetchMock).toHaveBeenCalledWith(new URL(PHOTO_URL), expect.objectContaining({ redirect: "error" })); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ["이미지가 아니면", "text/html"], | ||
| ["SVG면", "image/svg+xml"], | ||
| ["대문자로 적힌 SVG여도", "image/SVG+xml"], | ||
| ])("%s 전달하지 않고 S3 본문을 취소한다", async (_, contentType) => { | ||
| const s3Response = new Response("<svg/>", { headers: { "content-type": contentType } }); | ||
| const cancel = vi.spyOn(s3Response.body!, "cancel"); | ||
| fetchMock.mockResolvedValue(s3Response); | ||
|
|
||
| const response = await GET(request(PHOTO_URL)); | ||
|
|
||
| expect(response.status).toBe(502); | ||
| expect(cancel).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("업로드 최대 크기보다 큰 사진은 전달하지 않고 S3 본문을 취소한다", async () => { | ||
| const s3Response = new Response("x", { | ||
| headers: { "content-type": "image/jpeg", "content-length": String(11 * 1024 * 1024) }, | ||
| }); | ||
| const cancel = vi.spyOn(s3Response.body!, "cancel"); | ||
| fetchMock.mockResolvedValue(s3Response); | ||
|
|
||
| const response = await GET(request(PHOTO_URL)); | ||
|
|
||
| expect(response.status).toBe(413); | ||
| expect(cancel).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("S3 응답이 실패하거나 요청이 끊기면 502를 돌려준다", async () => { | ||
| fetchMock.mockResolvedValueOnce(new Response(null, { status: 404 })); | ||
| expect((await GET(request(PHOTO_URL))).status).toBe(502); | ||
|
|
||
| fetchMock.mockRejectedValueOnce(new TypeError("redirect")); | ||
| expect((await GET(request(PHOTO_URL))).status).toBe(502); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import { type NextRequest, NextResponse } from "next/server"; | ||
|
|
||
| import { env } from "@/config/env"; | ||
| import { UPLOAD_IMAGE_MAX_SIZE_BYTES } from "@/constants/image"; | ||
|
|
||
| import { checkMapsAccess } from "../_lib/mapsAccess"; | ||
|
|
||
| const getHostname = (value?: string) => { | ||
| if (!value) return null; | ||
| try { | ||
| return new URL(value).hostname; | ||
| } catch { | ||
| return null; | ||
| } | ||
| }; | ||
|
|
||
| // 열린 프록시가 되지 않도록 사진을 저장하는 S3 버킷만 허용한다 | ||
| const ALLOWED_HOSTS = new Set( | ||
| [ | ||
| "globber-dev.s3.ap-northeast-2.amazonaws.com", | ||
| "globber-prod.s3.ap-northeast-2.amazonaws.com", | ||
| getHostname(env.S3_BASE_URL), | ||
| ].filter((host): host is string => Boolean(host)) | ||
| ); | ||
|
|
||
| /** | ||
| * S3에 저장된 사진 원본을 같은 출처로 그대로 전달합니다 (GLB-264). | ||
| * S3 CORS 설정과 관계없이 자르기 화면이 원본 화질 사진을 canvas에서 쓸 수 있게 합니다. | ||
| * 기록 편집 화면에서만 쓰므로 로그인한 사용자만 호출할 수 있습니다. | ||
| * | ||
| * @example GET /api/image-proxy?url=https://globber-prod.s3.ap-northeast-2.amazonaws.com/photo.jpg | ||
| */ | ||
| export async function GET(request: NextRequest) { | ||
| const denied = await checkMapsAccess(request); | ||
| if (denied) return denied; | ||
|
|
||
| const url = request.nextUrl.searchParams.get("url"); | ||
| if (!url) return NextResponse.json({ error: "url required" }, { status: 400 }); | ||
|
|
||
| let target: URL; | ||
| try { | ||
| target = new URL(url); | ||
| } catch { | ||
| return NextResponse.json({ error: "invalid url" }, { status: 400 }); | ||
| } | ||
|
|
||
| if (target.protocol !== "https:" || !ALLOWED_HOSTS.has(target.hostname)) { | ||
| return NextResponse.json({ error: "host not allowed" }, { status: 403 }); | ||
| } | ||
|
|
||
| try { | ||
| // 리다이렉트를 따라가면 허용하지 않은 호스트로 나갈 수 있어 막는다 | ||
| const response = await fetch(target, { cache: "no-store", redirect: "error" }); | ||
| // MIME 타입은 대소문자를 구분하지 않으므로 소문자로 맞춰 검사한다 | ||
| const contentType = (response.headers.get("content-type") ?? "").toLowerCase(); | ||
| const contentLength = Number(response.headers.get("content-length") ?? 0); | ||
|
|
||
| // 거절한 응답의 본문을 읽지 않고 두면 S3 연결이 바로 반납되지 않으므로 취소한다 | ||
| const reject = async (error: string, status: number) => { | ||
| await response.body?.cancel().catch(() => {}); | ||
| return NextResponse.json({ error }, { status }); | ||
| }; | ||
|
|
||
| // SVG는 스크립트를 담을 수 있어 같은 출처로 내보내지 않는다 | ||
| if (!response.ok || !response.body || !contentType.startsWith("image/") || contentType.includes("svg")) { | ||
| return reject("failed to fetch image", 502); | ||
| } | ||
| if (contentLength > UPLOAD_IMAGE_MAX_SIZE_BYTES) { | ||
| return reject("image too large", 413); | ||
| } | ||
|
|
||
| return new NextResponse(response.body, { | ||
| headers: { | ||
| "Content-Type": contentType, | ||
| "Cache-Control": "private, max-age=300", | ||
| "X-Content-Type-Options": "nosniff", | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| console.error("[image-proxy] fetch failed:", error); | ||
| return NextResponse.json({ error: "failed to fetch image" }, { status: 502 }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.