Harden API CORS and Docker build
This commit is contained in:
1 parent
ffcba26e64
commit
8476526dd7
6 files changed
+251
-1
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
.git
|
||||||
|
.pnpm-store
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
**/dist
|
||||||
|
**/coverage
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
# syntax=docker/dockerfile:1.7
|
||||||
|
|
||||||
|
FROM node:26-slim AS pnpm-base
|
||||||
|
|
||||||
|
ENV PNPM_HOME=/pnpm
|
||||||
|
ENV PATH="${PNPM_HOME}:${PATH}"
|
||||||
|
|
||||||
|
RUN corepack enable
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
FROM pnpm-base AS deps
|
||||||
|
|
||||||
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
|
COPY tsconfig.base.json ./
|
||||||
|
COPY apps/api/package.json apps/api/package.json
|
||||||
|
COPY apps/web/package.json apps/web/package.json
|
||||||
|
COPY packages/shared/package.json packages/shared/package.json
|
||||||
|
|
||||||
|
RUN pnpm install --frozen-lockfile --filter api...
|
||||||
|
|
||||||
|
FROM deps AS build
|
||||||
|
|
||||||
|
COPY apps/api apps/api
|
||||||
|
COPY packages/shared packages/shared
|
||||||
|
|
||||||
|
RUN pnpm -r --sort --filter api... run build
|
||||||
|
|
||||||
|
FROM pnpm-base AS prod-deps
|
||||||
|
|
||||||
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
|
COPY apps/api/package.json apps/api/package.json
|
||||||
|
COPY apps/web/package.json apps/web/package.json
|
||||||
|
COPY packages/shared/package.json packages/shared/package.json
|
||||||
|
|
||||||
|
RUN pnpm install --prod --frozen-lockfile --filter api...
|
||||||
|
|
||||||
|
FROM gcr.io/distroless/nodejs26-debian13:nonroot AS runtime
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=prod
|
||||||
|
|
||||||
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
|
||||||
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
|
||||||
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
|
||||||
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||||
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/packages/shared/package.json ./packages/shared/package.json
|
||||||
|
COPY --from=build --chown=nonroot:nonroot /app/packages/shared/dist ./packages/shared/dist
|
||||||
|
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||||
|
COPY --chown=nonroot:nonroot ./project.yaml ./project.yaml
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
CMD ["apps/api/dist/main.js"]
|
||||||
@@ -29,7 +29,8 @@ describe('bootstrap', () => {
|
|||||||
const mockListen = jest
|
const mockListen = jest
|
||||||
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
|
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
|
||||||
.mockResolvedValue(undefined);
|
.mockResolvedValue(undefined);
|
||||||
const mockApp = { listen: mockListen };
|
const mockEnableCors = jest.fn();
|
||||||
|
const mockApp = { enableCors: mockEnableCors, listen: mockListen };
|
||||||
const mockedNestFactory = NestFactory as unknown as {
|
const mockedNestFactory = NestFactory as unknown as {
|
||||||
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
|
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
|
||||||
};
|
};
|
||||||
@@ -37,6 +38,11 @@ describe('bootstrap', () => {
|
|||||||
|
|
||||||
await bootstrap();
|
await bootstrap();
|
||||||
|
|
||||||
|
expect(mockEnableCors).toHaveBeenCalledWith({
|
||||||
|
origin: expect.any(Function),
|
||||||
|
credentials: true,
|
||||||
|
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||||
|
});
|
||||||
expect(configureApp).toHaveBeenCalledWith(mockApp);
|
expect(configureApp).toHaveBeenCalledWith(mockApp);
|
||||||
expect(mockListen).toHaveBeenCalledWith('3123');
|
expect(mockListen).toHaveBeenCalledWith('3123');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
import { configureApp } from './app.setup';
|
import { configureApp } from './app.setup';
|
||||||
|
import { createCorsOrigin } from './cors-origin';
|
||||||
|
|
||||||
export async function bootstrap(): Promise<void> {
|
export async function bootstrap(): Promise<void> {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
|
const nodeEnv = process.env.NODE_ENV;
|
||||||
|
app.enableCors({
|
||||||
|
origin: createCorsOrigin(nodeEnv),
|
||||||
|
credentials: true,
|
||||||
|
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||||
|
});
|
||||||
configureApp(app);
|
configureApp(app);
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import {
|
||||||
|
createCorsOrigin,
|
||||||
|
isAllowedCorsOrigin,
|
||||||
|
resolveWebOrigins,
|
||||||
|
} from './cors-origin';
|
||||||
|
|
||||||
|
describe('CORS origin resolution', () => {
|
||||||
|
it('allows Cloudflare Pages preview origins in dev and staging', () => {
|
||||||
|
const origin = 'https://807e0ea6.persona-lenz.pages.dev';
|
||||||
|
|
||||||
|
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
|
||||||
|
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not allow Cloudflare Pages preview origins in prod', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://807e0ea6.persona-lenz.pages.dev', 'prod'),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects similar but unsafe Pages origins', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('http://807e0ea6.persona-lenz.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://persona-lenz.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://a.b.persona-lenz.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin(
|
||||||
|
'https://807e0ea6.persona-lenz.pages.dev.evil.com',
|
||||||
|
'staging',
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps configured web origins allowed', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://example.com', 'prod', [
|
||||||
|
'https://example.com',
|
||||||
|
]),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
|
||||||
|
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a Nest CORS callback from the same rules', (done) => {
|
||||||
|
const corsOrigin = createCorsOrigin('staging');
|
||||||
|
|
||||||
|
expect(corsOrigin).not.toBe(true);
|
||||||
|
if (corsOrigin === true) return;
|
||||||
|
|
||||||
|
corsOrigin('https://807e0ea6.persona-lenz.pages.dev', (error, allow) => {
|
||||||
|
expect(error).toBeNull();
|
||||||
|
expect(allow).toBe(true);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps dev CORS permissive for local development', () => {
|
||||||
|
expect(createCorsOrigin('dev')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
|
||||||
|
|
||||||
|
const DEFAULT_WEB_ORIGINS = [
|
||||||
|
'http://localhost:5173',
|
||||||
|
'http://126.dahyeon.us:5173',
|
||||||
|
'https://persona-lenz.dahyeon.us',
|
||||||
|
];
|
||||||
|
|
||||||
|
const PAGES_DEV_ORIGIN_HOST_PATTERN =
|
||||||
|
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.persona-lenz\.pages\.dev$/i;
|
||||||
|
|
||||||
|
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
|
||||||
|
|
||||||
|
function parseOrigin(origin: string, allowPath: boolean): URL | null {
|
||||||
|
const trimmedOrigin = origin.trim();
|
||||||
|
if (trimmedOrigin.length === 0) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = new URL(trimmedOrigin);
|
||||||
|
if (
|
||||||
|
!allowPath &&
|
||||||
|
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return url;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeOrigin(origin: string, allowPath = false): string | null {
|
||||||
|
const url = parseOrigin(origin, allowPath);
|
||||||
|
if (!url) return null;
|
||||||
|
|
||||||
|
return `${url.protocol}//${url.host}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWebOrigins(
|
||||||
|
webOrigin = process.env.WEB_ORIGIN,
|
||||||
|
): string[] {
|
||||||
|
const configuredOrigins = webOrigin
|
||||||
|
?.split(',')
|
||||||
|
.map((origin) => normalizeOrigin(origin, true))
|
||||||
|
.filter((origin): origin is string => origin !== null);
|
||||||
|
|
||||||
|
if (configuredOrigins && configuredOrigins.length > 0) {
|
||||||
|
return configuredOrigins;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...DEFAULT_WEB_ORIGINS];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isPersonaLenzPagesDevOrigin(origin: string): boolean {
|
||||||
|
const url = parseOrigin(origin, false);
|
||||||
|
if (!url) return false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
url.protocol === 'https:' &&
|
||||||
|
url.port === '' &&
|
||||||
|
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAllowedCorsOrigin(
|
||||||
|
requestOrigin: string | undefined,
|
||||||
|
nodeEnv = process.env.NODE_ENV,
|
||||||
|
webOrigins = resolveWebOrigins(),
|
||||||
|
): boolean {
|
||||||
|
if (!requestOrigin) return false;
|
||||||
|
|
||||||
|
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
|
||||||
|
if (!normalizedRequestOrigin) return false;
|
||||||
|
|
||||||
|
const normalizedWebOrigins = webOrigins
|
||||||
|
.map((origin) => normalizeOrigin(origin, true))
|
||||||
|
.filter((origin): origin is string => origin !== null);
|
||||||
|
|
||||||
|
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
|
||||||
|
isPersonaLenzPagesDevOrigin(requestOrigin)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCorsOrigin(
|
||||||
|
nodeEnv = process.env.NODE_ENV,
|
||||||
|
webOrigin = process.env.WEB_ORIGIN,
|
||||||
|
): true | CustomOrigin {
|
||||||
|
if (nodeEnv === 'dev') return true;
|
||||||
|
|
||||||
|
const webOrigins = resolveWebOrigins(webOrigin);
|
||||||
|
|
||||||
|
return (requestOrigin, callback) => {
|
||||||
|
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in new issue
Block a user