From d5c2c2010288f68b7d511882bd5527bee7a5ac59 Mon Sep 17 00:00:00 2001 From: Tilumca Date: Wed, 14 Oct 2026 05:05:11 +0200 Subject: [PATCH] API+Front: Host z portem i normalizacja same-origin (przegladarkowy Origin na srodowisku po IP dawal 403 CORS) --- admin/nginx.conf.template | 7 ++-- api/src/app.ts | 5 +-- api/src/lib/sameOrigin.ts | 26 ++++++++++++++ api/test/integration/cors-same-origin.test.ts | 11 ++++++ api/test/unit/sameOrigin.test.ts | 36 +++++++++++++++++++ app/nginx.conf.template | 7 ++-- 6 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 api/src/lib/sameOrigin.ts create mode 100644 api/test/unit/sameOrigin.test.ts diff --git a/admin/nginx.conf.template b/admin/nginx.conf.template index 1c1ea6d..e33f81a 100644 --- a/admin/nginx.conf.template +++ b/admin/nginx.conf.template @@ -21,7 +21,10 @@ server { # upload zdjec do 5 MB + zapas client_max_body_size 10m; proxy_pass http://${API_UPSTREAM}; - proxy_set_header Host $host; + # $http_host (nie $host!) — zachowuje port: Express porownuje Origin z Host + # i inaczej requesty na srodowisku z jawnych portem (staging 13xxx, dev 9xxx) + # wygladalyby na cross-origin + proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; @@ -29,7 +32,7 @@ server { location = /health { proxy_pass http://${API_UPSTREAM}; - proxy_set_header Host $host; + proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } diff --git a/api/src/app.ts b/api/src/app.ts index 048d9a7..94a7e17 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -8,6 +8,7 @@ import type { AppDeps } from './deps.js'; import { config } from './config.js'; import { logger } from './lib/logger.js'; import { forbidden } from './lib/errors.js'; +import { isSameOrigin } from './lib/sameOrigin.js'; import { apiLimiter } from './middleware/rateLimit.js'; import { errorHandler, notFoundHandler } from './middleware/errorHandler.js'; import { openapi } from './swagger.js'; @@ -42,8 +43,8 @@ export function createApp(deps: AppDeps): express.Express { // Zgadzający się z bieżącym originem nagłówek usuwamy, przez co middleware `cors` // traktuje request jak bez-origin (pełna semantyka RFC). app.use((req, _res, next) => { - const own = `${req.protocol}://${req.headers.host ?? ''}`; - if (req.headers.origin && req.headers.origin === own) { + const origin = req.headers.origin; + if (origin && isSameOrigin(origin, req.protocol, req.headers.host)) { delete req.headers.origin; } next(); diff --git a/api/src/lib/sameOrigin.ts b/api/src/lib/sameOrigin.ts new file mode 100644 index 0000000..9b2f4d8 --- /dev/null +++ b/api/src/lib/sameOrigin.ts @@ -0,0 +1,26 @@ +/** + * Czy nagłówek Origin to dokładnie origin bieżącego requesta (scheme + host + port). + * Notacja originów normalizuje domyślne porty (http:80, https:443) i wielkość liter; + * inne protokoły (albo inny port = inna instancja) to już cross-origin — bez wyjątku. + * Chodzi wyłącznie o requesty same-origin: przeglądarka i tak wysyła Origin dla metod + * niebezpiecznych, a wzorce CORS dotyczą tylko realnych przekroczeń originu. + */ +export function isSameOrigin(originHeader: string, proto: string, hostHeader?: string): boolean { + const normalize = (scheme: string, hostPort: string): string | null => { + const hp = hostPort.trim().toLowerCase(); + if (!hp) return null; + const defaultPort = scheme === 'http' ? ':80' : scheme === 'https' ? ':443' : ''; + if (defaultPort && hp.endsWith(defaultPort)) return hp.slice(0, -defaultPort.length); + return hp; + }; + try { + const url = new URL(originHeader); + const originProto = url.protocol.replace(':', ''); + if (originProto !== proto) return false; + const originHost = normalize(originProto, url.host); + const requestHost = normalize(proto, hostHeader ?? ''); + return originHost !== null && requestHost !== null && originHost === requestHost; + } catch { + return false; + } +} diff --git a/api/test/integration/cors-same-origin.test.ts b/api/test/integration/cors-same-origin.test.ts index c8da504..a3b6413 100644 --- a/api/test/integration/cors-same-origin.test.ts +++ b/api/test/integration/cors-same-origin.test.ts @@ -20,6 +20,17 @@ describe('CORS — ten sam origin poza listą wzorców', () => { expect(res.headers['access-control-allow-origin']).toBeUndefined(); }); + it('srodowisko z jawnym portem (staging po IP:13001) tez jest same-origin', async () => { + const app = buildApp(); + const res = await app + .post('/api/v1/auth/login') + .set('Host', '192.168.50.127:13001') + .set('Origin', 'http://192.168.50.127:13001') + .send({ email: 'cors@example.test', password: 'nie-ma-znaczenia' }); + expect(res.status).toBe(401); + expect(res.headers['access-control-allow-origin']).toBeUndefined(); + }); + it('POST z obcym Origin dostaje 403', async () => { const app = buildApp(); const res = await app diff --git a/api/test/unit/sameOrigin.test.ts b/api/test/unit/sameOrigin.test.ts new file mode 100644 index 0000000..4209aee --- /dev/null +++ b/api/test/unit/sameOrigin.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from 'vitest'; +import { isSameOrigin } from '../../src/lib/sameOrigin.js'; + +describe('isSameOrigin — origin requesta vs nagłówek Origin', () => { + it('ten sam scheme+host+port to same-origin', () => { + expect(isSameOrigin('http://192.168.50.127:13001', 'http', '192.168.50.127:13001')).toBe(true); + expect(isSameOrigin('https://tisachi.ddns.net', 'https', 'tisachi.ddns.net')).toBe(true); + }); + + it('domyślny port jest niewidoczny po jednej stronie', () => { + expect(isSameOrigin('http://api.example.test:80', 'http', 'api.example.test')).toBe(true); + expect(isSameOrigin('http://api.example.test', 'http', 'api.example.test:80')).toBe(true); + expect(isSameOrigin('https://api.example.test:443', 'https', 'api.example.test')).toBe(true); + }); + + it('wielkość liter hosta nie ma znaczenia', () => { + expect(isSameOrigin('http://Api.Example.Test:13001', 'http', 'api.example.test:13001')).toBe( + true, + ); + }); + + it('inny port / inny scheme / inny host to cross-origin', () => { + expect(isSameOrigin('http://192.168.50.127:13001', 'http', '192.168.50.127:13000')).toBe(false); + expect(isSameOrigin('http://192.168.50.127:13001', 'https', '192.168.50.127:13001')).toBe( + false, + ); + expect(isSameOrigin('http://obcy.example.test', 'http', 'api.example.test')).toBe(false); + // https:80 nie jest "domyślnym portem" — inny origin + expect(isSameOrigin('https://api.example.test:80', 'https', 'api.example.test')).toBe(false); + }); + + it('wartość nieparująca originu to zawsze false', () => { + expect(isSameOrigin('null', 'http', 'api.example.test')).toBe(false); + expect(isSameOrigin('http://', 'http', 'api.example.test')).toBe(false); + }); +}); diff --git a/app/nginx.conf.template b/app/nginx.conf.template index 80e8e14..aebdc0f 100644 --- a/app/nginx.conf.template +++ b/app/nginx.conf.template @@ -27,7 +27,10 @@ server { # upload zdjec do 5 MB + zapas client_max_body_size 10m; proxy_pass http://${API_UPSTREAM}; - proxy_set_header Host $host; + # $http_host (nie $host!) — zachowuje port: Express porownuje Origin z Host + # i inaczej requesty na srodowisku z jawnych portem (staging 13xxx, dev 9xxx) + # wygladalyby na cross-origin + proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; @@ -35,7 +38,7 @@ server { location = /health { proxy_pass http://${API_UPSTREAM}; - proxy_set_header Host $host; + proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }