Skip to content
Merged
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
14 changes: 8 additions & 6 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ sudo mkdir -p /opt/tail-client
sudo chown deploy:deploy /opt/tail-client
```

방화벽에서 3001 포트를 연다. (서버의 3000은 tail-server의 그라파나가 127.0.0.1에서 쓰고 있어 웹은 3001로 연다.)
웹은 서버(tail-server)의 caddy가 HTTPS로 받아 3001로 넘긴다(tail-server `docs/deploy.md` 1-6). 방화벽에서 3001은 열지 않는다. (서버의 3000은 tail-server의 그라파나가 127.0.0.1에서 쓰고 있어 웹은 3001로 연다.)

웹의 origin을 서버의 CORS에 추가한다. `/opt/tail-server/.env`의 `CORS_ALLOWED_ORIGINS`에 `http://<서버 주소>:3001`을 쉼표로 이어 넣고 서버를 다시 띄운다.
도메인은 API와 웹을 같은 상위 도메인 아래에 둔다(`api.<도메인>`, `admin.<도메인>`). 서버가 리프레시 토큰을 `SameSite=Lax` httpOnly 쿠키로 주고, 로그인 표시 쿠키(`signedIn`)로 페이지를 보호하므로 서로 다른 사이트면 로그인이 되지 않는다.

웹의 origin을 서버의 CORS에 추가한다. `/opt/tail-server/.env`의 `CORS_ALLOWED_ORIGINS`에 `https://<ADMIN_DOMAIN>`을 넣고 서버를 다시 띄운다. 쿠키를 쓰므로 `*`는 안 된다.

```bash
sudo -u deploy nano /opt/tail-server/.env # CORS_ALLOWED_ORIGINS=기존값,http://<서버 주소>:3001
sudo -u deploy nano /opt/tail-server/.env # CORS_ALLOWED_ORIGINS=https://<ADMIN_DOMAIN>
cd /opt/tail-server && sudo -u deploy env IMAGE_TAG="$(cat current_tag)" docker compose up -d app
```

Expand All @@ -42,11 +44,11 @@ Settings → Secrets and variables → Actions → **Variables** → New reposit

| 이름 | 값 |
| ------------------------------ | ------------------------------------------------------------ |
| `NEXT_PUBLIC_API_URL` | 운영 서버 API 주소. 예: `http://<서버 주소>:8080/api/v1` |
| `NEXT_PUBLIC_API_URL` | 운영 서버 API 주소. 예: `https://<API_DOMAIN>/api/v1` |
| `NEXT_PUBLIC_KAKAO_CLIENT_ID` | 카카오 REST API 키 (서버 `KAKAO_CLIENT_ID`와 같은 값) |
| `NEXT_PUBLIC_GOOGLE_CLIENT_ID` | 구글 OAuth 클라이언트 ID (서버 `GOOGLE_CLIENT_ID`와 같은 값) |

카카오 디벨로퍼스와 구글 클라우드 콘솔의 Redirect URI에 `<웹 주소>/login`을 등록한다.
카카오 디벨로퍼스와 구글 클라우드 콘솔의 Redirect URI에 `https://<ADMIN_DOMAIN>/login`을 등록한다.

### prod environment

Expand All @@ -68,7 +70,7 @@ GHCR 로그인은 워크플로의 `GITHUB_TOKEN`으로 하므로 따로 등록
## 3. 첫 배포

1. `develop`을 `main`으로 PR해서 머지한다. CI가 성공하면 Deploy가 자동으로 시작된다.
2. 로그에 `OK: sha-xxxxxxx 배포 완료`가 나오면 `http://<서버 주소>:3001`에서 확인한다.
2. 로그에 `OK: sha-xxxxxxx 배포 완료`가 나오면 `https://<ADMIN_DOMAIN>`에서 로그인까지 확인한다.

첫 배포는 `current_tag`가 없어서 실패해도 롤백할 이전 버전이 없다.

Expand Down
4 changes: 1 addition & 3 deletions src/features/auth/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ const assign = vi.fn();
const ORIGIN = "http://admin.test";

beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
vi.stubGlobal("location", {
assign,
Expand All @@ -30,7 +29,7 @@ afterEach(() => {
function serverWithRole(role: "ADMIN" | "KEEPER" | "ME_FAILS") {
setServer((config) => {
if (config.url === "/auth/oauth/callback")
return [200, { data: { accessToken: "a1", refreshToken: "r1" } }];
return [200, { data: { accessToken: "a1" } }];
if (config.url === "/auth/me")
return role === "ME_FAILS"
? [500, {}]
Expand Down Expand Up @@ -93,7 +92,6 @@ test("내 정보를 못 불러오면 토큰을 지우고 실패한다", async ()
await expect(finishLogin("code-1", state)).rejects.toThrow();

expect(tokens.access).toBeNull();
expect(tokens.refresh).toBeNull();
});

test("state가 다르면 서버에 보내지 않고 실패한다", async () => {
Expand Down
10 changes: 4 additions & 6 deletions src/features/auth/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { api, loginHref, tokens } from "@/lib/api";
import { api, loginHref, signIn, signOut } from "@/lib/api";

export type Me = { id: number; nickname: string; role: "KEEPER" | "ADMIN" };

Expand Down Expand Up @@ -69,7 +69,7 @@ export async function finishLogin(code: string | undefined, state: string) {
code,
redirectUri: redirectUri(),
});
tokens.save(data.data);
signIn(data.data.accessToken);

let me: Me;
try {
Expand All @@ -91,8 +91,6 @@ export async function getMe() {

// 서버 폐기에 실패해도 이 브라우저에서는 로그아웃한다
export async function logout() {
await api
.post("/auth/logout", { refreshToken: tokens.refresh })
.catch(() => {});
tokens.clear();
await api.post("/auth/logout").catch(() => {});
signOut();
}
86 changes: 57 additions & 29 deletions src/lib/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ const reissues = () => requests.filter((r) => r.url?.endsWith("/reissue"));
const authOf = (url: string) => sent(url).map((r) => r.headers.Authorization);

beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
vi.stubGlobal("location", { assign, pathname: "/species", search: "" });
tokens.save({ accessToken: "old", refreshToken: "r1" });
tokens.access = "old";
});

afterEach(() => {
Expand All @@ -29,7 +28,7 @@ const okWithNewToken = (

const reissueOk = (config: InternalAxiosRequestConfig): [number, unknown] =>
config.url?.endsWith("/reissue")
? [200, { data: { accessToken: "new", refreshToken: "r2" } }]
? [200, { data: { accessToken: "new" } }]
: okWithNewToken(config);

test("401이면 한 번 재발급하고 새 토큰으로 다시 보낸다", async () => {
Expand All @@ -40,8 +39,8 @@ test("401이면 한 번 재발급하고 새 토큰으로 다시 보낸다", asyn
expect(res.data).toEqual({ data: "ok" });
expect(authOf("/animals")).toEqual(["Bearer old", "Bearer new"]);
expect(reissues()).toHaveLength(1);
expect(JSON.parse(reissues()[0].data)).toEqual({ refreshToken: "r1" });
expect(tokens.refresh).toBe("r2");
expect(reissues()[0].withCredentials).toBe(true);
expect(tokens.access).toBe("new");
});

test("401이 동시에 여러 개 와도 재발급은 한 번만 한다", async () => {
Expand All @@ -61,52 +60,81 @@ test("재발급이 401이면 토큰을 지우고 만료 화면으로 보내며
expect(assign).toHaveBeenCalledWith("/login?error=expired"),
);
expect(tokens.access).toBeNull();
expect(tokens.refresh).toBeNull();
expect(sessionStorage.getItem("returnTo")).toBe("/species");
});

test("재발급이 서버 오류면 토큰을 남기고 원래 에러를 던진다", async () => {
test("재발급이 서버 오류면 로그인 화면으로 보내지 않고 원래 에러를 던진다", async () => {
setServer((config) =>
config.url?.endsWith("/reissue") ? [500, {}] : [401, {}],
);

await expect(api.get("/animals")).rejects.toMatchObject({
response: { status: 401 },
});
expect(tokens.refresh).toBe("r1");
expect(assign).not.toHaveBeenCalled();
});

test("다른 탭이 먼저 재발급했으면 그 토큰으로 다시 보낸다", async () => {
setServer((config) => {
if (!config.url?.endsWith("/reissue")) return okWithNewToken(config);
// 다른 탭이 r1을 먼저 써서 새 토큰을 저장한 상황
tokens.save({ accessToken: "new", refreshToken: "r2" });
return [401, {}];
});

const res = await api.get("/animals");

expect(res.data).toEqual({ data: "ok" });
expect(assign).not.toHaveBeenCalled();
});

test("소셜 로그인과 로그아웃의 401은 재발급하지 않는다", async () => {
test("소셜 로그인의 401은 재발급하지 않는다", async () => {
setServer(() => [401, {}]);

await expect(api.post("/auth/oauth/callback")).rejects.toBeInstanceOf(
AxiosError,
);
await expect(api.post("/auth/logout")).rejects.toBeInstanceOf(AxiosError);
expect(reissues()).toHaveLength(0);
});

test("리프레시 토큰이 없으면 재발급 없이 로그인 화면으로 보낸다", async () => {
tokens.clear();
test("액세스 토큰이 만료돼 로그아웃이 401이면 재발급한 뒤 다시 보낸다", async () => {
setServer((config) =>
config.url === "/auth/logout" &&
config.headers.Authorization === "Bearer new"
? [204, null]
: reissueOk(config),
);

await api.post("/auth/logout");

expect(authOf("/auth/logout")).toEqual(["Bearer old", "Bearer new"]);
});

test("로그아웃 중 재발급까지 401이면 만료 화면으로 보내지 않고 에러를 던진다", async () => {
setServer(() => [401, {}]);

void api.get("/animals");
await expect(api.post("/auth/logout")).rejects.toBeInstanceOf(AxiosError);

await vi.waitFor(() => expect(assign).toHaveBeenCalledWith("/login"));
expect(reissues()).toHaveLength(0);
expect(assign).not.toHaveBeenCalled();
expect(tokens.access).toBeNull();
});

test("새로고침해 액세스 토큰이 없어도 첫 401에서 쿠키로 재발급해 복구한다", async () => {
tokens.access = null;
setServer(reissueOk);

const res = await api.get("/animals");

expect(res.data).toEqual({ data: "ok" });
expect(authOf("/animals")).toEqual([undefined, "Bearer new"]);
});

test("모든 요청과 재발급에 웹 표시 헤더와 쿠키 전송을 붙인다", async () => {
setServer(reissueOk);

await api.get("/animals");

for (const r of requests) {
expect(r.withCredentials).toBe(true);
expect(r.headers["X-Client-Type"]).toBe("WEB");
}
expect(reissues()).toHaveLength(1);
});

test("로그인 표시 쿠키는 재발급 성공 때 남고 만료되면 지운다", async () => {
setServer(reissueOk);
await api.get("/animals");
expect(document.cookie).toContain("signedIn=1");

setServer(() => [401, {}]);
tokens.access = null;
void api.get("/animals");
await vi.waitFor(() => expect(assign).toHaveBeenCalled());
expect(document.cookie).not.toContain("signedIn");
});
65 changes: 32 additions & 33 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,48 @@
import axios, { type InternalAxiosRequestConfig } from "axios";
import { markSignedIn, markSignedOut } from "./session";

// 서버는 X-Client-Type: WEB이면 리프레시 토큰을 응답 본문 대신 httpOnly 쿠키로 주고받는다
const webRequest = {
withCredentials: true,
headers: { "X-Client-Type": "WEB" },
};

export const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
...webRequest,
});

// 로그인 화면 주소. error는 login/page.tsx가 보여 주는 화면 종류
export type LoginError = "forbidden" | "failed" | "expired";
export const loginHref = (error?: LoginError) =>
error ? `/login?error=${error}` : "/login";

type Tokens = { accessToken: string; refreshToken: string };
const ACCESS = "accessToken";
const REFRESH = "refreshToken";

// shortcut: 토큰을 localStorage에 둬서 XSS에 노출되고 서버에서 로그인 여부를 볼 수 없다. 서버가 httpOnly 쿠키를 주면 옮긴다
// 액세스 토큰은 메모리에만 둔다. 새로고침으로 사라지면 첫 401에서 쿠키로 재발급해 복구한다.
// 리프레시 토큰은 서버가 준 httpOnly 쿠키라 JS는 보지 못한다
export const tokens = {
get access() {
return localStorage.getItem(ACCESS);
},
get refresh() {
return localStorage.getItem(REFRESH);
},
save({ accessToken, refreshToken }: Tokens) {
localStorage.setItem(ACCESS, accessToken);
localStorage.setItem(REFRESH, refreshToken);
},
clear() {
localStorage.removeItem(ACCESS);
localStorage.removeItem(REFRESH);
},
access: null as string | null,
};

export function signIn(accessToken: string) {
tokens.access = accessToken;
markSignedIn();
}

export function signOut() {
tokens.access = null;
markSignedOut();
}

api.interceptors.request.use((config) => {
const token = tokens.access;
if (token) config.headers.Authorization = `Bearer ${token}`;
if (tokens.access) config.headers.Authorization = `Bearer ${tokens.access}`;
return config;
});

// 소셜 로그인 실패(OAUTH_FAILED)도 401이고, 로그아웃은 실패해도 로그인 화면으로 가면 되므로 재발급하지 않는다
const noReissue = ["/auth/oauth/callback", "/auth/logout"];
// 소셜 로그인 실패(OAUTH_FAILED)도 401이라 재발급하지 않는다. 로그아웃은 인증이 필요해서,
// 액세스 토큰이 만료됐으면 서버 요구대로 재발급한 뒤 다시 보낸다
const noReissue = ["/auth/oauth/callback"];

// 동시에 401이 여러 개 나도 재발급은 한 번만 한다 (쓴 리프레시 토큰은 서버가 지운다)
// 동시에 401이 여러 개 나도 재발급은 한 번만 한다 (쓴 리프레시 토큰은 서버가 바꾼다)
let reissuing: Promise<void> | null = null;

api.interceptors.response.use(undefined, async (error) => {
Expand All @@ -53,26 +55,23 @@ api.interceptors.response.use(undefined, async (error) => {
) {
throw error;
}
const used = tokens.refresh;
if (!used) return leave(loginHref());

config.retried = true;
reissuing ??= axios
.put(`${api.defaults.baseURL}/auth/reissue`, { refreshToken: used })
.then((res) => tokens.save(res.data.data))
.put(`${api.defaults.baseURL}/auth/reissue`, undefined, webRequest)
.then((res) => signIn(res.data.data.accessToken))
.finally(() => (reissuing = null));
try {
await reissuing;
} catch (reissueError) {
// 다른 탭이 먼저 재발급했으면 그 토큰으로 다시 보낸다
if (tokens.refresh && tokens.refresh !== used) return api(config);
// 서버·네트워크 장애는 만료가 아니므로 토큰을 남긴다
// 서버·네트워크 장애는 만료가 아니므로 원래 에러를 던진다
if (
!axios.isAxiosError(reissueError) ||
reissueError.response?.status !== 401
)
throw error;
tokens.clear();
signOut();
// 로그아웃은 만료 화면 없이 호출한 쪽이 마무리한다 (사용자가 직접 나간 것이고, 관리자 아님 안내를 덮지 않는다)
if (config.url === "/auth/logout") throw error;
return leave(loginHref("expired"));
}
return api(config);
Expand Down
15 changes: 15 additions & 0 deletions src/lib/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// 서버의 리프레시 쿠키(refresh_token)는 Path=/api/v1/auth라 페이지 요청에는 오지 않아 proxy가 읽지 못한다.
// 그래서 로그인했다는 표시를 따로 남겨 proxy가 페이지를 그리기 전에 /login으로 보낸다.
// 화면 이동용 힌트일 뿐이고 진짜 인증은 API가 한다. 만료됐으면 첫 API 401에서 재발급 실패로 정리된다
export const SESSION_COOKIE = "signedIn";

// shortcut: 서버 리프레시 토큰 만료(JWT_REFRESH_TOKEN_EXPIRATION 기본 14d)를 따로 적어 둔다. 서버 값을 바꾸면 같이 바꾼다
const MAX_AGE = 60 * 60 * 24 * 14;

export const markSignedIn = () => {
document.cookie = `${SESSION_COOKIE}=1; Path=/; Max-Age=${MAX_AGE}; SameSite=Lax`;
};

export const markSignedOut = () => {
document.cookie = `${SESSION_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax`;
};
32 changes: 32 additions & 0 deletions src/proxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NextRequest } from "next/server";
import { expect, test } from "vitest";
import { config, proxy } from "./proxy";

const call = (cookie?: string) =>
proxy(
new NextRequest("http://admin.test/species", {
headers: cookie ? { cookie } : {},
}),
);

test("로그인 표시 쿠키가 없으면 로그인으로 보낸다", () => {
const res = call();
expect(res.headers.get("location")).toBe("http://admin.test/login");
});

test("로그인 표시 쿠키가 있으면 통과시킨다", () => {
expect(call("signedIn=1").headers.get("location")).toBeNull();
});

test("로그인·정적 파일은 보호하지 않고 나머지 페이지는 보호한다", () => {
const re = new RegExp(`^${config.matcher[0]}$`);
for (const path of ["/", "/species", "/guides/1", "/login-help"])
expect(re.test(path), path).toBe(true);
for (const path of [
"/login",
"/_next/static/a.js",
"/favicon.ico",
"/robots.txt",
])
expect(re.test(path), path).toBe(false);
});
14 changes: 14 additions & 0 deletions src/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE } from "@/lib/session";

// 로그인 표시 쿠키(lib/session.ts)가 없으면 페이지를 그리기 전에 로그인으로 보낸다.
// 유효한지는 보지 않는다(만료는 첫 API 401에서 처리)
export function proxy(request: NextRequest) {
if (request.cookies.has(SESSION_COOKIE)) return NextResponse.next();
return NextResponse.redirect(new URL("/login", request.url));
}

// /login, _next, 점이 든 정적 파일(favicon.ico, robots.txt, public/ 이미지)은 제외한다
export const config = {
matcher: ["/((?!login$|_next/|.*\\.).*)"],
};