Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/web/src/app/api/_lib/mapsAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ const isRateLimited = (token: string, now: number) => {

/**
* Google Maps 프록시(/api/places, /api/geocode)를 로그인한 사용자만, 정해진 횟수 안에서 쓸 수 있게 막습니다 (GLB-129).
* 두 API는 기록 작성 화면에서만 쓰여 비로그인 화면에는 영향이 없습니다.
* 사진 자르기용 원본 이미지 프록시(/api/image-proxy, GLB-264)도 같은 기준을 씁니다.
* 세 API 모두 기록 작성·편집 화면에서만 쓰여 비로그인 화면에는 영향이 없습니다.
* 통과하면 null, 막아야 하면 바로 돌려줄 응답을 반환합니다.
*/
export const checkMapsAccess = async (request: NextRequest): Promise<NextResponse | null> => {
Expand Down
95 changes: 95 additions & 0 deletions apps/web/src/app/api/image-proxy/route.test.ts
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);
});
83 changes: 83 additions & 0 deletions apps/web/src/app/api/image-proxy/route.ts
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")) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 });
}
}
32 changes: 17 additions & 15 deletions apps/web/src/components/imageMetadata/ImageCropModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,40 +213,42 @@ export const ImageCropModal = ({ image, onClose, onSave, photoIndex = 0 }: Image
};

/**
* S3 이미지를 Blob URL로 변환합니다 (CORS 우회).
* 원본 화질 그대로 이미지를 Blob URL로 변환합니다 (CORS 우회).
* S3 직접 요청이 CORS로 실패하면 같은 출처 프록시(/api/image-proxy)로 원본을 받아옵니다.
*
* @param {string} url - 원본 이미지 URL
* @returns {Promise<string>} Blob URL
*/
const fetchImageAsBlob = async (url: string): Promise<string> => {
// 새로 고른 사진(blob:)은 CORS와 상관없고, 파라미터를 붙이면 주소가 깨지므로 그대로 읽는다
const isRemote = url.startsWith("http://") || url.startsWith("https://");
if (!isRemote) {
const response = await fetch(url);
return URL.createObjectURL(await response.blob());
}

try {
// S3 등 외부 요소를 fetch할 때 브라우저 디스크 캐시(<img> 태그가 로드한 CORS 헤더 없는 캐시)를
// 사용할 경우 CORS 에러가 발생할 수 있으므로, 캐시 우회를 위해 파라미터를 추가합니다.
// 단, URL이 이미 브라우저 내부의 blob: 형태인 경우 파라미터를 추가하면 깨지므로 분기 처리합니다.
let fetchUrl = url;
if (url.startsWith("http://") || url.startsWith("https://")) {
const cacheUrl = new URL(url);
cacheUrl.searchParams.set("t", Date.now().toString());
fetchUrl = cacheUrl.toString();
}
const cacheUrl = new URL(url);
cacheUrl.searchParams.set("t", Date.now().toString());

const response = await fetch(fetchUrl, {
// S3 공개 객체는 쿠키가 필요 없고, 쿠키를 같이 보내면 Allow-Origin: * 응답이 CORS 에러가 되므로 빼고 보낸다
const response = await fetch(cacheUrl.toString(), {
mode: "cors",
credentials: "include",
credentials: "omit",
});

if (response.ok) {
const blob = await response.blob();
return URL.createObjectURL(blob);
}
} catch (error) {
// CORS 또는 네트워크 에러 발생 시 Next.js Image Proxy로 fallback
logger.warn("Direct S3 fetch failed, falling back to Next.js proxy:", error);
logger.warn("Direct S3 fetch failed, falling back to same-origin proxy:", error);
}

// Fallback: Next.js Image Proxy 사용 (3840은 부하가 커 1920으로 낮춤)
const proxyUrl = `/_next/image?url=${encodeURIComponent(url)}&w=1920&q=95`;
const proxyResponse = await fetch(proxyUrl);
// Fallback: /_next/image는 1920px로 줄이고 다시 압축해 화질이 떨어지므로, 원본 그대로 전달하는 프록시를 쓴다
const proxyResponse = await fetch(`/api/image-proxy?url=${encodeURIComponent(url)}`);

if (!proxyResponse.ok) {
throw new Error("Failed to fetch image via proxy");
Expand Down
Loading