feat(auth): delegate CORM sessions and permissions to ERP
This commit is contained in:
+6
-11
@@ -36,24 +36,19 @@ APP_PORT=8002
|
|||||||
APP_ROOT_PATH=/corm
|
APP_ROOT_PATH=/corm
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# SSO (dbx-main 세션 공유)
|
# ERP 중앙 인증 (동일 도메인의 /corm/ 경로)
|
||||||
# ============================================
|
# ============================================
|
||||||
# dbx-main, OMS 와 반드시 같은 값으로 맞춰야 SSO 동작.
|
# ERP 쿠키 이름과 동일하게 설정. CORM은 서명 키를 보유하지 않고 쿠키를 ERP에 전달만 한다.
|
||||||
# 미설정 시 컨테이너 기동 실패 (fail-fast). openssl rand -hex 32 로 생성.
|
|
||||||
SESSION_SECRET_KEY=__paste-same-value-as-dbx-main__
|
|
||||||
SESSION_COOKIE_NAME=session
|
SESSION_COOKIE_NAME=session
|
||||||
SESSION_SAME_SITE=lax
|
|
||||||
SESSION_HTTPS_ONLY=1
|
|
||||||
SESSION_MAX_AGE=28800
|
|
||||||
|
|
||||||
# 세션에서 읽을 사용자 키. dbx-main 이 어느 키로 쓰는지에 맞춰라.
|
|
||||||
SESSION_USER_KEY=user_email
|
|
||||||
SESSION_NAME_KEY=user_name
|
|
||||||
|
|
||||||
# 미인증 시 보낼 dbx-main 로그인/로그아웃 URL
|
# 미인증 시 보낼 dbx-main 로그인/로그아웃 URL
|
||||||
MAIN_LOGIN_URL=https://dbx.no1king.freeddns.org/login
|
MAIN_LOGIN_URL=https://dbx.no1king.freeddns.org/login
|
||||||
MAIN_LOGOUT_URL=https://dbx.no1king.freeddns.org/logout
|
MAIN_LOGOUT_URL=https://dbx.no1king.freeddns.org/logout
|
||||||
|
|
||||||
|
# 사용자 접근은 매 요청 ERP의 현재 사용자/corm 권한으로 확인(실패 시 503 차단).
|
||||||
|
# dbx-main 과 공용 postgres_default 네트워크에서 통신. 외부 공개 주소보다 내부 주소 권장.
|
||||||
|
ERP_AUTH_URL=http://dbx-main:8000/api/auth/check
|
||||||
|
|
||||||
# ===== 서비스 간 호출 인증 =====
|
# ===== 서비스 간 호출 인증 =====
|
||||||
# OMS 가 반품 신청을 보낼 때 X-Service-Token 헤더로 이 값을 보낸다.
|
# OMS 가 반품 신청을 보낼 때 X-Service-Token 헤더로 이 값을 보낸다.
|
||||||
# CORM 의 AuthGuard 가 해당 헤더가 이 값과 일치하면 세션 검사 우회.
|
# CORM 의 AuthGuard 가 해당 헤더가 이 값과 일치하면 세션 검사 우회.
|
||||||
|
|||||||
@@ -3,6 +3,21 @@
|
|||||||
CS / 발주 / 반품 통합 관리 웹 애플리케이션.
|
CS / 발주 / 반품 통합 관리 웹 애플리케이션.
|
||||||
FastAPI + PostgreSQL 기반, Docker로 실행.
|
FastAPI + PostgreSQL 기반, Docker로 실행.
|
||||||
|
|
||||||
|
로그인·로그아웃·사용자·CORM 접근 권한은 ERP(main-app)가 관리한다.
|
||||||
|
`erp_auth.py`가 매 사용자 요청마다 ERP의 `GET /api/auth/check?module=corm`에 세션 쿠키를 전달해
|
||||||
|
현재 권한을 확인한다. ERP에서 권한을 끄거나 사용자를 삭제하면 다음 요청부터 차단된다.
|
||||||
|
ERP 연결 실패/타임아웃은 503으로 차단하며, CORM은 ERP 세션을 발급·갱신하지 않는다.
|
||||||
|
사용자 확인은 CORM의 세션 서명 키 없이 동작한다. `SESSION_COOKIE_NAME`은 ERP와 같아야 한다.
|
||||||
|
|
||||||
|
`ERP_AUTH_URL` 기본값은 `http://dbx-main:8000/api/auth/check`이다(공용 `postgres_default` 네트워크).
|
||||||
|
운영은 동일 도메인의 `/corm/` 프록시를 유지하고, **ERP 인증 API를 먼저 배포한 다음 CORM을 배포한다.**
|
||||||
|
새 CORM만 배포하면 기존 ERP의 404 응답으로 사용자 접근이 503이 된다.
|
||||||
|
실제 배포 전 양쪽 `git status --short`, `docker compose ps`, 공통 Docker 네트워크와 설정 백업 위치를 확인한다.
|
||||||
|
기존 `INTERNAL_SERVICE_TOKEN` 시스템 호출과 NPM의 외부 `X-Service-Token` 헤더 제거 설정은 유지한다.
|
||||||
|
|
||||||
|
검증: `python -m unittest discover -s tests -v`. 권한이 있는 직원으로 접속 후 ERP에서 `corm` 권한을 끄고,
|
||||||
|
같은 탭 새로고침 시 403인지 확인한다. 공개 헬스 체크 성공만으로 사용자 인증 성공을 판단하지 않는다.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 기술 스택
|
## 기술 스택
|
||||||
|
|||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
"""CORM 사용자 접근의 최종 판단을 ERP에 위임한다."""
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import Request
|
||||||
|
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
||||||
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
|
|
||||||
|
|
||||||
|
class AuthGuardMiddleware(BaseHTTPMiddleware):
|
||||||
|
def __init__(self, app):
|
||||||
|
super().__init__(app)
|
||||||
|
self.root = os.getenv("APP_ROOT_PATH", "").rstrip("/")
|
||||||
|
self.login_url = os.getenv(
|
||||||
|
"MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login"
|
||||||
|
)
|
||||||
|
self.auth_url = os.getenv(
|
||||||
|
"ERP_AUTH_URL", "http://dbx-main:8000/api/auth/check"
|
||||||
|
).strip()
|
||||||
|
self.cookie_name = os.getenv("SESSION_COOKIE_NAME", "session")
|
||||||
|
|
||||||
|
async def dispatch(self, request: Request, call_next):
|
||||||
|
raw = request.scope.get("path", "") or "/"
|
||||||
|
root = self.root or request.scope.get("root_path", "").rstrip("/")
|
||||||
|
path = raw
|
||||||
|
if root and (raw == root or raw.startswith(root + "/")):
|
||||||
|
path = raw[len(root):] or "/"
|
||||||
|
|
||||||
|
# 공개 경로는 정확히 일치할 때만 허용한다(정적 자원만 하위 경로 포함).
|
||||||
|
if path.startswith("/static/") or path in {
|
||||||
|
"/health", "/health/db", "/api/cafe24/callback",
|
||||||
|
"/admin/oauth/callback", "/login", "/logout", "/favicon.ico",
|
||||||
|
}:
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
# 기존 OMS 등의 시스템 호출 인증. 사용자 로그인/권한과 별개다.
|
||||||
|
service_token = os.getenv("INTERNAL_SERVICE_TOKEN", "")
|
||||||
|
incoming = request.headers.get("x-service-token", "")
|
||||||
|
if service_token and incoming and secrets.compare_digest(incoming, service_token):
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
wants_html = "text/html" in request.headers.get("accept", "") or not path.startswith("/api/")
|
||||||
|
|
||||||
|
def denied(status, message):
|
||||||
|
headers = {"Cache-Control": "no-store"}
|
||||||
|
if wants_html:
|
||||||
|
return HTMLResponse(
|
||||||
|
f'<!doctype html><html lang="ko"><meta charset="utf-8">'
|
||||||
|
f"<title>CORM 접근 안내</title><p>{message}</p></html>",
|
||||||
|
status_code=status, headers=headers,
|
||||||
|
)
|
||||||
|
return JSONResponse({"detail": message}, status_code=status, headers=headers)
|
||||||
|
|
||||||
|
def unauthenticated():
|
||||||
|
if not wants_html:
|
||||||
|
return denied(401, "로그인이 필요합니다.")
|
||||||
|
next_path = f"{root}{path}"
|
||||||
|
query = request.scope.get("query_string", b"")
|
||||||
|
if query:
|
||||||
|
next_path += "?" + query.decode("latin-1")
|
||||||
|
sep = "&" if "?" in self.login_url else "?"
|
||||||
|
return RedirectResponse(
|
||||||
|
f"{self.login_url}{sep}next={quote(next_path, safe='/')}",
|
||||||
|
status_code=302, headers={"Cache-Control": "no-store"},
|
||||||
|
)
|
||||||
|
|
||||||
|
cookie = request.cookies.get(self.cookie_name)
|
||||||
|
if not cookie:
|
||||||
|
return unauthenticated()
|
||||||
|
if not self.auth_url:
|
||||||
|
return denied(503, "ERP 인증 서버 설정을 확인해 주세요.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 사용자별 권한 캐시 없음. 쿠키·토큰·ERP 응답 본문은 로그에 남기지 않는다.
|
||||||
|
# 다른 쿠키/서비스 토큰은 전달하지 않으며 리디렉션도 따라가지 않는다.
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
timeout=3.0, follow_redirects=False, trust_env=False,
|
||||||
|
cookies={self.cookie_name: cookie},
|
||||||
|
) as client:
|
||||||
|
response = await client.get(
|
||||||
|
self.auth_url, params={"module": "corm"},
|
||||||
|
)
|
||||||
|
if response.status_code == 401:
|
||||||
|
return unauthenticated()
|
||||||
|
if response.status_code == 403:
|
||||||
|
return denied(403, "CORM 접근 권한이 없습니다. ERP 관리자에게 문의해 주세요.")
|
||||||
|
if response.status_code != 200:
|
||||||
|
return denied(503, "ERP에서 접근 권한을 확인할 수 없습니다. 잠시 후 다시 시도해 주세요.")
|
||||||
|
data = response.json()
|
||||||
|
user = data.get("user") if isinstance(data, dict) else None
|
||||||
|
if (
|
||||||
|
data.get("module") != "corm" or not isinstance(user, dict)
|
||||||
|
or not isinstance(user.get("email"), str) or not user["email"].strip()
|
||||||
|
):
|
||||||
|
raise ValueError("Invalid ERP authorization response")
|
||||||
|
except (httpx.HTTPError, ValueError, TypeError, AttributeError):
|
||||||
|
return denied(503, "ERP에서 접근 권한을 확인할 수 없습니다. 잠시 후 다시 시도해 주세요.")
|
||||||
|
|
||||||
|
request.state.erp_user = user
|
||||||
|
return await call_next(request)
|
||||||
@@ -19,8 +19,7 @@ from urllib.parse import quote
|
|||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks
|
from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, FileResponse, RedirectResponse
|
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, FileResponse, RedirectResponse
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from erp_auth import AuthGuardMiddleware
|
||||||
from starlette.middleware.sessions import SessionMiddleware
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
# Load local settings before application modules read environment values.
|
# Load local settings before application modules read environment values.
|
||||||
@@ -43,80 +42,6 @@ from google_runtime import (
|
|||||||
APP_ROOT_PATH = os.getenv("APP_ROOT_PATH", "").rstrip("/")
|
APP_ROOT_PATH = os.getenv("APP_ROOT_PATH", "").rstrip("/")
|
||||||
MAIN_LOGIN_URL = os.getenv("MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login")
|
MAIN_LOGIN_URL = os.getenv("MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login")
|
||||||
MAIN_LOGOUT_URL = os.getenv("MAIN_LOGOUT_URL", "https://dbx.no1king.freeddns.org/logout")
|
MAIN_LOGOUT_URL = os.getenv("MAIN_LOGOUT_URL", "https://dbx.no1king.freeddns.org/logout")
|
||||||
SESSION_USER_KEY = os.getenv("SESSION_USER_KEY", "user_email")
|
|
||||||
SESSION_NAME_KEY = os.getenv("SESSION_NAME_KEY", "user_name")
|
|
||||||
|
|
||||||
# 인증 우회 경로 — 정적 자원, 헬스, OAuth 콜백, 로그인/로그아웃 위임
|
|
||||||
# Starlette scope.path 는 root_path 가 제거된 형태로 들어오므로 prefix 없이 매칭.
|
|
||||||
_AUTH_EXEMPT_PREFIXES = (
|
|
||||||
"/static/",
|
|
||||||
"/health",
|
|
||||||
"/api/cafe24/callback",
|
|
||||||
"/admin/oauth/callback",
|
|
||||||
"/login",
|
|
||||||
"/logout",
|
|
||||||
"/favicon.ico",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _require_session_secret() -> str:
|
|
||||||
secret = os.getenv("SESSION_SECRET_KEY", "").strip()
|
|
||||||
if not secret:
|
|
||||||
raise RuntimeError(
|
|
||||||
"SESSION_SECRET_KEY 환경변수가 설정되지 않았습니다. "
|
|
||||||
"openssl rand -hex 32 로 새 값을 만들어 .env 에 넣고 컨테이너를 재기동하세요. "
|
|
||||||
"dbx-main 과 SSO 하려면 양쪽 .env 에 같은 값이어야 합니다."
|
|
||||||
)
|
|
||||||
return secret
|
|
||||||
|
|
||||||
|
|
||||||
class AuthGuardMiddleware(BaseHTTPMiddleware):
|
|
||||||
"""세션에 user_email 이 없으면 차단.
|
|
||||||
|
|
||||||
- HTML 요청 (Accept: text/html 또는 / 같은 페이지) → dbx-main /login?next=... 302
|
|
||||||
- 그 외 (API 등) → 401 JSON
|
|
||||||
- _AUTH_EXEMPT_PREFIXES 에 해당하는 경로는 통과
|
|
||||||
"""
|
|
||||||
|
|
||||||
async def dispatch(self, request: Request, call_next):
|
|
||||||
# 환경별로 scope.path 가 root_path 를 포함할 수도, 안 할 수도 있어
|
|
||||||
# 항상 root_path 제외된 형태로 정규화한다.
|
|
||||||
raw = request.scope.get("path", "") or "/"
|
|
||||||
if APP_ROOT_PATH and raw.startswith(APP_ROOT_PATH + "/"):
|
|
||||||
path = raw[len(APP_ROOT_PATH):]
|
|
||||||
elif APP_ROOT_PATH and raw == APP_ROOT_PATH:
|
|
||||||
path = "/"
|
|
||||||
else:
|
|
||||||
path = raw
|
|
||||||
|
|
||||||
for prefix in _AUTH_EXEMPT_PREFIXES:
|
|
||||||
if path == prefix or path.startswith(prefix):
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
# 서비스 간 호출 — X-Service-Token 헤더가 일치하면 세션 없이도 통과.
|
|
||||||
# NPM 은 외부에서 들어온 이 헤더를 빈 값으로 strip 해야 한다 (보안).
|
|
||||||
service_token = os.getenv("INTERNAL_SERVICE_TOKEN", "")
|
|
||||||
if service_token:
|
|
||||||
incoming_token = request.headers.get("x-service-token", "")
|
|
||||||
if incoming_token and incoming_token == service_token:
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
email = request.session.get(SESSION_USER_KEY)
|
|
||||||
if email:
|
|
||||||
return await call_next(request)
|
|
||||||
|
|
||||||
# 미인증
|
|
||||||
accept = request.headers.get("accept", "")
|
|
||||||
wants_html = "text/html" in accept or not path.startswith("/api/")
|
|
||||||
if wants_html:
|
|
||||||
next_path = f"{APP_ROOT_PATH}{path}" if APP_ROOT_PATH else path
|
|
||||||
if request.scope.get("query_string"):
|
|
||||||
next_path = f"{next_path}?{request.scope['query_string'].decode('latin-1')}"
|
|
||||||
sep = "&" if "?" in MAIN_LOGIN_URL else "?"
|
|
||||||
target = f"{MAIN_LOGIN_URL}{sep}next={quote(next_path, safe='/')}"
|
|
||||||
return RedirectResponse(url=target, status_code=302)
|
|
||||||
return JSONResponse({"detail": "Not authenticated"}, status_code=401)
|
|
||||||
|
|
||||||
# ==========================================
|
# ==========================================
|
||||||
# 데이터베이스 접속 설정 (환경변수 기반)
|
# 데이터베이스 접속 설정 (환경변수 기반)
|
||||||
# ==========================================
|
# ==========================================
|
||||||
@@ -163,21 +88,9 @@ except ImportError:
|
|||||||
|
|
||||||
app = FastAPI(title="CS Web Program")
|
app = FastAPI(title="CS Web Program")
|
||||||
|
|
||||||
# 미들웨어 등록 순서 주의:
|
# 세션 발급/검증/갱신은 ERP만 수행한다. CORM은 쿠키를 ERP에 전달할 뿐
|
||||||
# Starlette 은 add_middleware 를 "반대 순서로" 적용한다 (마지막에 추가한 것이 가장 바깥).
|
# 세션 서명 키를 갖거나 Set-Cookie로 ERP 세션을 갱신하지 않는다.
|
||||||
# AuthGuardMiddleware 가 request.session 을 읽으려면 SessionMiddleware 가
|
|
||||||
# 먼저 실행돼서 scope 에 session 을 주입해야 한다.
|
|
||||||
# 따라서 AuthGuard 를 먼저 추가 (내부) → Session 을 나중에 추가 (외부, 먼저 실행).
|
|
||||||
app.add_middleware(AuthGuardMiddleware)
|
app.add_middleware(AuthGuardMiddleware)
|
||||||
app.add_middleware(
|
|
||||||
SessionMiddleware,
|
|
||||||
secret_key=_require_session_secret(),
|
|
||||||
session_cookie=os.getenv("SESSION_COOKIE_NAME", "session"),
|
|
||||||
same_site=os.getenv("SESSION_SAME_SITE", "lax"),
|
|
||||||
https_only=os.getenv("SESSION_HTTPS_ONLY", "0") == "1",
|
|
||||||
max_age=int(os.getenv("SESSION_MAX_AGE", "28800")),
|
|
||||||
path="/",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health/db")
|
@app.get("/health/db")
|
||||||
@@ -378,8 +291,8 @@ async def index(request: Request):
|
|||||||
context={
|
context={
|
||||||
"version_history": version_history,
|
"version_history": version_history,
|
||||||
"root_path": APP_ROOT_PATH,
|
"root_path": APP_ROOT_PATH,
|
||||||
"user_email": request.session.get(SESSION_USER_KEY, ""),
|
"user_email": getattr(request.state, "erp_user", {}).get("email", ""),
|
||||||
"user_name": request.session.get(SESSION_NAME_KEY, ""),
|
"user_name": getattr(request.state, "erp_user", {}).get("name", ""),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
fastapi
|
fastapi
|
||||||
|
httpx>=0.28
|
||||||
uvicorn
|
uvicorn
|
||||||
pydantic
|
pydantic
|
||||||
gspread
|
gspread
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
"""ERP 권한 차단·장애·경로 우회를 DB/외부 네트워크 없이 검증한다."""
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from erp_auth import AuthGuardMiddleware
|
||||||
|
|
||||||
|
|
||||||
|
class ErpAuthTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.env = patch.dict(os.environ, {
|
||||||
|
"APP_ROOT_PATH": "/corm", "MAIN_LOGIN_URL": "https://erp.example/login",
|
||||||
|
"ERP_AUTH_URL": "http://erp.test/api/auth/check", "SESSION_COOKIE_NAME": "erp_session",
|
||||||
|
"INTERNAL_SERVICE_TOKEN": "system-only-test-token",
|
||||||
|
})
|
||||||
|
self.env.start()
|
||||||
|
self.addCleanup(self.env.stop)
|
||||||
|
self.calls = []
|
||||||
|
self.status = 200
|
||||||
|
self.payload = {"module": "corm", "user": {"email": "worker@example.test", "name": "Worker"}}
|
||||||
|
self.error = None
|
||||||
|
self.hits = []
|
||||||
|
self.real_client = httpx.AsyncClient
|
||||||
|
|
||||||
|
def handler(request):
|
||||||
|
self.calls.append(request)
|
||||||
|
if self.error:
|
||||||
|
raise self.error
|
||||||
|
return httpx.Response(self.status, json=self.payload)
|
||||||
|
|
||||||
|
def client_factory(**kwargs):
|
||||||
|
self.assertEqual(kwargs, {
|
||||||
|
"timeout": 3.0, "follow_redirects": False, "trust_env": False,
|
||||||
|
"cookies": {"erp_session": "browser-cookie"},
|
||||||
|
})
|
||||||
|
return self.real_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||||
|
|
||||||
|
self.mock_client = patch("erp_auth.httpx.AsyncClient", side_effect=client_factory)
|
||||||
|
self.mock_client.start()
|
||||||
|
self.addCleanup(self.mock_client.stop)
|
||||||
|
app = FastAPI()
|
||||||
|
app.add_middleware(AuthGuardMiddleware)
|
||||||
|
|
||||||
|
@app.api_route("/{path:path}", methods=["GET", "POST"])
|
||||||
|
async def protected(request: Request, path: str):
|
||||||
|
self.hits.append(path)
|
||||||
|
return JSONResponse({"user": getattr(request.state, "erp_user", None)})
|
||||||
|
|
||||||
|
self.client = TestClient(app, follow_redirects=False)
|
||||||
|
|
||||||
|
def get(self, path="/api/items", cookie=True, headers=None):
|
||||||
|
headers = dict(headers or {})
|
||||||
|
if cookie:
|
||||||
|
headers["Cookie"] = "erp_session=browser-cookie; unrelated=do-not-forward"
|
||||||
|
return self.client.get(path, headers=headers)
|
||||||
|
|
||||||
|
def test_authorized_identity_and_only_session_cookie_forwarded(self):
|
||||||
|
r = self.get()
|
||||||
|
self.assertEqual(r.status_code, 200)
|
||||||
|
self.assertEqual(r.json()["user"], self.payload["user"])
|
||||||
|
call = self.calls[0]
|
||||||
|
self.assertEqual(str(call.url), "http://erp.test/api/auth/check?module=corm")
|
||||||
|
self.assertEqual(call.headers["cookie"], "erp_session=browser-cookie")
|
||||||
|
self.assertNotIn("x-service-token", call.headers)
|
||||||
|
self.assertNotIn("set-cookie", r.headers)
|
||||||
|
|
||||||
|
def test_no_cookie_api_401_and_html_redirect_with_query(self):
|
||||||
|
self.assertEqual(self.get(cookie=False).status_code, 401)
|
||||||
|
r = self.get("/corm/returns?status=open&term=a%20b", cookie=False)
|
||||||
|
self.assertEqual(r.status_code, 302)
|
||||||
|
parts = urlsplit(r.headers["location"])
|
||||||
|
self.assertEqual(parts.netloc, "erp.example")
|
||||||
|
self.assertEqual(parse_qs(parts.query)["next"], ["/corm/returns?status=open&term=a%20b"])
|
||||||
|
self.assertFalse(self.calls)
|
||||||
|
self.assertFalse(self.hits)
|
||||||
|
|
||||||
|
def test_permission_removal_and_deleted_user_take_effect_next_request(self):
|
||||||
|
self.assertEqual(self.get().status_code, 200)
|
||||||
|
self.status = 403
|
||||||
|
self.assertEqual(self.get().status_code, 403)
|
||||||
|
self.assertEqual(self.get("/", headers={"Accept": "text/html"}).status_code, 403)
|
||||||
|
self.status = 401
|
||||||
|
self.assertEqual(self.get().status_code, 401)
|
||||||
|
self.assertEqual(self.get("/").status_code, 302)
|
||||||
|
self.assertEqual(len(self.hits), 1)
|
||||||
|
self.assertEqual(len(self.calls), 5)
|
||||||
|
|
||||||
|
def test_erp_failures_never_allow_access(self):
|
||||||
|
for status in (302, 404, 422, 500, 503):
|
||||||
|
with self.subTest(status=status):
|
||||||
|
self.status = status
|
||||||
|
self.assertEqual(self.get().status_code, 503)
|
||||||
|
self.error = httpx.ConnectError("offline")
|
||||||
|
self.assertEqual(self.get().status_code, 503)
|
||||||
|
self.error = httpx.ReadTimeout("timeout")
|
||||||
|
r = self.get("/")
|
||||||
|
self.assertEqual(r.status_code, 503)
|
||||||
|
self.assertEqual(r.headers["cache-control"], "no-store")
|
||||||
|
self.assertFalse(self.hits)
|
||||||
|
|
||||||
|
def test_malformed_or_wrong_module_responses_are_denied(self):
|
||||||
|
for payload in (None, [], {}, {"module": "order", "user": {"email": "a"}},
|
||||||
|
{"module": "corm", "user": {"email": ""}},
|
||||||
|
{"module": "corm", "user": {"email": 1}}):
|
||||||
|
with self.subTest(payload=payload):
|
||||||
|
self.payload = payload
|
||||||
|
self.assertEqual(self.get().status_code, 503)
|
||||||
|
self.assertFalse(self.hits)
|
||||||
|
|
||||||
|
def test_exempt_paths_are_exact_and_corm_prefix_is_handled(self):
|
||||||
|
for path in ("/login", "/logout", "/health/db", "/admin/oauth/callback?code=x",
|
||||||
|
"/static/app.js", "/corm/health/db", "/corm/static/app.js"):
|
||||||
|
with self.subTest(path=path):
|
||||||
|
self.assertEqual(self.get(path, cookie=False).status_code, 200)
|
||||||
|
for path in ("/login-bypass", "/health/secrets", "/admin/oauth/callback/secret"):
|
||||||
|
with self.subTest(path=path):
|
||||||
|
self.assertEqual(self.get(path, cookie=False).status_code, 302)
|
||||||
|
self.assertFalse(self.calls)
|
||||||
|
|
||||||
|
def test_existing_machine_auth_and_invalid_token(self):
|
||||||
|
self.assertEqual(self.get(cookie=False, headers={"X-Service-Token": "system-only-test-token"}).status_code, 200)
|
||||||
|
self.assertEqual(self.get(cookie=False, headers={"X-Service-Token": "wrong"}).status_code, 401)
|
||||||
|
self.assertEqual(len(self.hits), 1)
|
||||||
|
self.assertFalse(self.calls)
|
||||||
|
|
||||||
|
def test_real_application_page_and_login_logout_delegation(self):
|
||||||
|
import main
|
||||||
|
client = TestClient(main.app, follow_redirects=False)
|
||||||
|
page = client.get("/", headers={"Cookie": "erp_session=browser-cookie"})
|
||||||
|
self.assertEqual(page.status_code, 200)
|
||||||
|
self.assertNotIn("set-cookie", page.headers)
|
||||||
|
self.status = 403
|
||||||
|
self.assertEqual(client.get("/", headers={"Cookie": "erp_session=browser-cookie"}).status_code, 403)
|
||||||
|
self.assertEqual(client.get("/api/config").status_code, 401)
|
||||||
|
login = client.get("/login", params={"next": "/corm/?tab=returns"})
|
||||||
|
self.assertEqual(login.status_code, 302)
|
||||||
|
self.assertEqual(parse_qs(urlsplit(login.headers["location"]).query)["next"], ["/corm/?tab=returns"])
|
||||||
|
logout = client.get("/logout")
|
||||||
|
self.assertEqual(logout.status_code, 302)
|
||||||
|
self.assertEqual(logout.headers["location"], main.MAIN_LOGOUT_URL)
|
||||||
|
self.assertNotIn("set-cookie", logout.headers)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -16,9 +16,8 @@ import requests
|
|||||||
|
|
||||||
_import_cache_dir = tempfile.TemporaryDirectory()
|
_import_cache_dir = tempfile.TemporaryDirectory()
|
||||||
os.environ["SETTINGS_CACHE_FILE"] = str(Path(_import_cache_dir.name) / "settings.json")
|
os.environ["SETTINGS_CACHE_FILE"] = str(Path(_import_cache_dir.name) / "settings.json")
|
||||||
# 서버판(dbx-corm)은 SSO 미들웨어가 세션 비밀값을 요구하고, 로그인 안 된 요청을 401 로 막는다.
|
# 서버판(dbx-corm)은 ERP 중앙 인증으로 로그인 안 된 요청을 401 로 막는다.
|
||||||
# 테스트는 서비스 간 호출 토큰(X-Service-Token)으로 통과한다.
|
# 테스트는 서비스 간 호출 토큰(X-Service-Token)으로 통과한다.
|
||||||
os.environ.setdefault("SESSION_SECRET_KEY", "test-only-session-secret")
|
|
||||||
os.environ["INTERNAL_SERVICE_TOKEN"] = "test-service-token"
|
os.environ["INTERNAL_SERVICE_TOKEN"] = "test-service-token"
|
||||||
|
|
||||||
import main
|
import main
|
||||||
|
|||||||
Reference in New Issue
Block a user