From 434dfe0a2fbc6a4f8f16adf9dda32be1d89d2038 Mon Sep 17 00:00:00 2001 From: burnern <200775118+dev-burnern@users.noreply.github.com> Date: Sun, 17 May 2026 01:18:33 +0900 Subject: [PATCH 1/4] =?UTF-8?q?feat(auth):=20=EC=82=AC=EB=B2=88=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=EA=B3=BC=20=ED=9A=8C=EC=9B=90?= =?UTF-8?q?=EA=B0=80=EC=9E=85=20=EC=A0=80=EC=9E=A5=EC=86=8C=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/auth/dependencies.py | 79 +++++-- backend/app/auth/models.py | 28 +++ backend/app/auth/postgres_store.py | 137 ++++++++++++ backend/app/auth/router.py | 80 +++++++ backend/app/auth/service.py | 197 +++++++++++++++++- backend/app/auth/store.py | 116 +++++++++++ backend/app/core/config.py | 30 +++ backend/app/main.py | 12 +- backend/app/middleware/rate_limit.py | 6 + backend/tests/auth/test_api_key_auth.py | 6 +- backend/tests/auth/test_login_auth.py | 76 +++++++ .../auth/test_postgres_auth_user_store.py | 110 ++++++++++ backend/tests/middleware/test_rate_limit.py | 31 +++ infra/compose/docker-compose.yml | 1 + 14 files changed, 878 insertions(+), 31 deletions(-) create mode 100644 backend/app/auth/postgres_store.py create mode 100644 backend/app/auth/router.py create mode 100644 backend/app/auth/store.py create mode 100644 backend/tests/auth/test_login_auth.py create mode 100644 backend/tests/auth/test_postgres_auth_user_store.py diff --git a/backend/app/auth/dependencies.py b/backend/app/auth/dependencies.py index 6863984..fee6856 100644 --- a/backend/app/auth/dependencies.py +++ b/backend/app/auth/dependencies.py @@ -1,12 +1,11 @@ from fastapi import Depends, HTTPException, Request, status -from backend.app.auth.models import ADMIN_ROLE, WorkspaceContext +from backend.app.auth.models import ADMIN_ROLE, ApiKeyRecord, UserRecord, WorkspaceContext from backend.app.auth.service import AuthService -from backend.app.core.config import get_settings -def get_auth_service() -> AuthService: - return AuthService(get_settings()) +def get_auth_service(request: Request) -> AuthService: + return request.app.state.auth_service def require_workspace_context( @@ -14,34 +13,50 @@ def require_workspace_context( auth_service: AuthService = Depends(get_auth_service), ) -> WorkspaceContext: api_key = request.headers.get("X-API-Key") - if not api_key: + if api_key: + record = auth_service.validate_api_key(api_key) + if record is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail={ + "code": "AUTH_INVALID_API_KEY", + "message": "API key is invalid.", + }, + ) + return _context_from_api_key(request, record) + + authorization = request.headers.get("Authorization") + if not authorization: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail={ - "code": "AUTH_MISSING_API_KEY", - "message": "API key is required.", + "code": "AUTH_MISSING_CREDENTIALS", + "message": "Authentication credential is required.", }, ) - record = auth_service.validate_api_key(api_key) - if record is None: + scheme, _, token = authorization.partition(" ") + if scheme.lower() != "bearer" or not token: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail={ - "code": "AUTH_INVALID_API_KEY", - "message": "API key is invalid.", + "code": "AUTH_INVALID_TOKEN", + "message": "Bearer token is required.", }, ) - request.state.request_context.workspace_id = record.workspace_id - request.state.request_context.workspace_name = record.workspace_name + try: + record = auth_service.validate_access_token(token) + except Exception as exc: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail={ + "code": "AUTH_INVALID_TOKEN", + "message": str(exc), + }, + ) from exc - return WorkspaceContext( - request_id=request.state.request_context.request_id, - workspace_id=record.workspace_id, - workspace_name=record.workspace_name, - role=record.role, - ) + return _context_from_user(request, record) def require_admin_workspace_context( @@ -57,3 +72,29 @@ def require_admin_workspace_context( ) return workspace_context + + +def _context_from_api_key(request: Request, record: ApiKeyRecord) -> WorkspaceContext: + request.state.request_context.workspace_id = record.workspace_id + request.state.request_context.workspace_name = record.workspace_name + + return WorkspaceContext( + request_id=request.state.request_context.request_id, + workspace_id=record.workspace_id, + workspace_name=record.workspace_name, + role=record.role, + ) + + +def _context_from_user(request: Request, record: UserRecord) -> WorkspaceContext: + request.state.request_context.workspace_id = record.workspace_id + request.state.request_context.workspace_name = record.workspace_name + + return WorkspaceContext( + request_id=request.state.request_context.request_id, + workspace_id=record.workspace_id, + workspace_name=record.workspace_name, + role=record.role, + employee_id=record.employee_id, + display_name=record.display_name, + ) diff --git a/backend/app/auth/models.py b/backend/app/auth/models.py index c95596d..7f0a9eb 100644 --- a/backend/app/auth/models.py +++ b/backend/app/auth/models.py @@ -14,8 +14,36 @@ class ApiKeyRecord(BaseModel): role: UserRole = MEMBER_ROLE +class UserRecord(BaseModel): + employee_id: str + password_hash: str + workspace_id: str + workspace_name: str + role: UserRole = MEMBER_ROLE + display_name: str | None = None + + class WorkspaceContext(BaseModel): request_id: str workspace_id: str workspace_name: str role: UserRole = MEMBER_ROLE + employee_id: str | None = None + display_name: str | None = None + + +class LoginRequest(BaseModel): + employee_id: str + password: str + + +class SignupRequest(BaseModel): + employee_id: str + password: str + display_name: str | None = None + + +class AuthResponse(BaseModel): + access_token: str + token_type: str = "bearer" + workspace: WorkspaceContext diff --git a/backend/app/auth/postgres_store.py b/backend/app/auth/postgres_store.py new file mode 100644 index 0000000..0dc86cb --- /dev/null +++ b/backend/app/auth/postgres_store.py @@ -0,0 +1,137 @@ +from __future__ import annotations + +from typing import Callable, Iterable + +from backend.app.auth.models import UserRecord + + +class PostgresAuthUserStore: + def __init__( + self, + *, + database_url: str, + seed_users: Iterable[UserRecord], + connection_factory: Callable[[], object] | None = None, + ) -> None: + self._database_url = database_url + self._seed_users = list(seed_users) + self._connection_factory = connection_factory or self._create_connection + self._ensure_schema() + self._seed_default_users() + + def get_user(self, employee_id: str) -> UserRecord | None: + with self._connection_factory() as connection: + cursor = connection.execute( + f""" + SELECT + {_user_columns()} + FROM auth_users + WHERE employee_id = %(employee_id)s + """, + {"employee_id": employee_id}, + ) + rows = cursor.fetchall() + + if not rows: + return None + return UserRecord.model_validate(rows[0]) + + def create_user(self, record: UserRecord) -> bool: + with self._connection_factory() as connection: + cursor = connection.execute( + """ + INSERT INTO auth_users ( + employee_id, + password_hash, + workspace_id, + workspace_name, + role, + display_name + ) + VALUES ( + %(employee_id)s, + %(password_hash)s, + %(workspace_id)s, + %(workspace_name)s, + %(role)s, + %(display_name)s + ) + ON CONFLICT (employee_id) DO NOTHING + RETURNING employee_id + """, + record.model_dump(mode="python"), + ) + rows = cursor.fetchall() + connection.commit() + + return bool(rows) + + def _ensure_schema(self) -> None: + with self._connection_factory() as connection: + connection.execute( + """ + CREATE TABLE IF NOT EXISTS auth_users ( + employee_id TEXT PRIMARY KEY, + password_hash TEXT NOT NULL, + workspace_id TEXT NOT NULL, + workspace_name TEXT NOT NULL, + role TEXT NOT NULL, + display_name TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """, + ) + connection.execute( + """ + CREATE INDEX IF NOT EXISTS idx_auth_users_workspace + ON auth_users (workspace_id) + """, + ) + connection.commit() + + def _seed_default_users(self) -> None: + if not self._seed_users: + return + + with self._connection_factory() as connection: + for record in self._seed_users: + connection.execute( + """ + INSERT INTO auth_users ( + employee_id, + password_hash, + workspace_id, + workspace_name, + role, + display_name + ) + VALUES ( + %(employee_id)s, + %(password_hash)s, + %(workspace_id)s, + %(workspace_name)s, + %(role)s, + %(display_name)s + ) + ON CONFLICT (employee_id) DO NOTHING + """, + record.model_dump(mode="python"), + ) + connection.commit() + + def _create_connection(self) -> object: + from psycopg import connect + from psycopg.rows import dict_row + + return connect(self._database_url, row_factory=dict_row) + + +def _user_columns() -> str: + return """ + employee_id, + password_hash, + workspace_id, + workspace_name, + role, + display_name + """ diff --git a/backend/app/auth/router.py b/backend/app/auth/router.py new file mode 100644 index 0000000..e8946bc --- /dev/null +++ b/backend/app/auth/router.py @@ -0,0 +1,80 @@ +from fastapi import APIRouter, Depends, HTTPException, Request, status + +from backend.app.auth.dependencies import get_auth_service, require_workspace_context +from backend.app.auth.models import AuthResponse, LoginRequest, SignupRequest, WorkspaceContext +from backend.app.auth.service import ( + AuthError, + AuthService, + DuplicateUserError, + InvalidCredentialsError, +) + +router = APIRouter(prefix="/v1/auth", tags=["auth"]) + + +@router.post("/signup", response_model=AuthResponse, status_code=status.HTTP_201_CREATED) +async def signup( + request_body: SignupRequest, + request: Request, + auth_service: AuthService = Depends(get_auth_service), +) -> AuthResponse: + try: + user = auth_service.register_user( + employee_id=request_body.employee_id, + password=request_body.password, + display_name=request_body.display_name, + ) + except DuplicateUserError as exc: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail={"code": "AUTH_DUPLICATE_EMPLOYEE_ID", "message": str(exc)}, + ) from exc + except AuthError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={"code": "AUTH_INVALID_SIGNUP", "message": str(exc)}, + ) from exc + + return _build_auth_response(request, auth_service, user) + + +@router.post("/login", response_model=AuthResponse) +async def login( + request_body: LoginRequest, + request: Request, + auth_service: AuthService = Depends(get_auth_service), +) -> AuthResponse: + try: + user = auth_service.authenticate_user( + employee_id=request_body.employee_id, + password=request_body.password, + ) + except InvalidCredentialsError as exc: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail={"code": "AUTH_INVALID_CREDENTIALS", "message": str(exc)}, + ) from exc + + return _build_auth_response(request, auth_service, user) + + +@router.get("/me", response_model=WorkspaceContext) +async def me( + workspace_context: WorkspaceContext = Depends(require_workspace_context), +) -> WorkspaceContext: + return workspace_context + + +def _build_auth_response(request: Request, auth_service: AuthService, user) -> AuthResponse: + workspace = WorkspaceContext( + request_id=request.state.request_context.request_id, + workspace_id=user.workspace_id, + workspace_name=user.workspace_name, + role=user.role, + employee_id=user.employee_id, + display_name=user.display_name, + ) + return AuthResponse( + access_token=auth_service.create_access_token(user), + workspace=workspace, + ) diff --git a/backend/app/auth/service.py b/backend/app/auth/service.py index 8aa51ae..f57a340 100644 --- a/backend/app/auth/service.py +++ b/backend/app/auth/service.py @@ -1,19 +1,149 @@ +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +import base64 +import hashlib +import hmac +import json import secrets -from backend.app.auth.models import MEMBER_ROLE, SUPPORTED_ROLES, ApiKeyRecord +from backend.app.auth.models import ( + MEMBER_ROLE, + SUPPORTED_ROLES, + ApiKeyRecord, + UserRecord, +) +from backend.app.auth.store import ( + AuthUserStore, + InMemoryAuthUserStore, + build_member_user_record, + parse_auth_users, +) from backend.app.core.config import Settings +class AuthError(ValueError): + pass + + +class DuplicateUserError(AuthError): + pass + + +class InvalidCredentialsError(AuthError): + pass + + +class InvalidTokenError(AuthError): + pass + + class AuthService: - def __init__(self, settings: Settings): - self._api_keys = self._parse_api_keys(settings.api_keys) + def __init__( + self, + settings: Settings, + user_store: AuthUserStore | None = None, + ) -> None: + self._settings = settings + self._api_keys: list[ApiKeyRecord] | None = None + self._user_store = user_store or InMemoryAuthUserStore( + parse_auth_users(settings.auth_users), + ) def validate_api_key(self, api_key: str) -> ApiKeyRecord | None: - for record in self._api_keys: + for record in self._get_api_keys(): if secrets.compare_digest(record.api_key, api_key): return record return None + def register_user( + self, + *, + employee_id: str, + password: str, + display_name: str | None = None, + ) -> UserRecord: + normalized_employee_id = _normalize_employee_id(employee_id) + _validate_password(password) + if self._user_store.get_user(normalized_employee_id) is not None: + raise DuplicateUserError("이미 가입된 사번입니다.") + + record = build_member_user_record( + employee_id=normalized_employee_id, + password_hash=hash_password(password), + workspace_id=self._settings.signup_default_workspace_id, + workspace_name=self._settings.signup_default_workspace_name, + display_name=_normalize_optional(display_name), + ) + if not self._user_store.create_user(record): + raise DuplicateUserError("이미 가입된 사번입니다.") + return record + + def authenticate_user(self, *, employee_id: str, password: str) -> UserRecord: + record = self._user_store.get_user(_normalize_employee_id(employee_id)) + if record is None or not _verify_password(password, record.password_hash): + raise InvalidCredentialsError("사번 또는 비밀번호가 올바르지 않습니다.") + return record + + def create_access_token(self, record: UserRecord) -> str: + expires_at = datetime.now(UTC) + timedelta( + seconds=self._settings.auth_token_ttl_seconds, + ) + payload = { + "employee_id": record.employee_id, + "workspace_id": record.workspace_id, + "workspace_name": record.workspace_name, + "role": record.role, + "display_name": record.display_name, + "exp": int(expires_at.timestamp()), + } + encoded_payload = _base64url_encode( + json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode(), + ) + signature = self._sign(encoded_payload) + return f"{encoded_payload}.{signature}" + + def validate_access_token(self, token: str) -> UserRecord: + try: + encoded_payload, signature = token.split(".", 1) + except ValueError as exc: + raise InvalidTokenError("로그인 토큰이 올바르지 않습니다.") from exc + + if not hmac.compare_digest(signature, self._sign(encoded_payload)): + raise InvalidTokenError("로그인 토큰이 올바르지 않습니다.") + + try: + payload = json.loads(_base64url_decode(encoded_payload)) + except (ValueError, json.JSONDecodeError) as exc: + raise InvalidTokenError("로그인 토큰이 올바르지 않습니다.") from exc + + expires_at = int(payload.get("exp", 0)) + if expires_at < int(datetime.now(UTC).timestamp()): + raise InvalidTokenError("로그인이 만료되었습니다.") + + return UserRecord( + employee_id=str(payload["employee_id"]), + password_hash="", + workspace_id=str(payload["workspace_id"]), + workspace_name=str(payload["workspace_name"]), + role=str(payload.get("role", MEMBER_ROLE)), + display_name=payload.get("display_name"), + ) + + def _get_api_keys(self) -> list[ApiKeyRecord]: + if self._api_keys is None: + self._api_keys = self._parse_api_keys(self._settings.api_keys) + return self._api_keys + + def _sign(self, encoded_payload: str) -> str: + return _base64url_encode( + hmac.new( + self._settings.auth_token_secret.encode(), + encoded_payload.encode(), + hashlib.sha256, + ).digest(), + ) + @staticmethod def _parse_api_keys(raw_value: str) -> list[ApiKeyRecord]: records: list[ApiKeyRecord] = [] @@ -30,9 +160,7 @@ def _parse_api_keys(raw_value: str) -> list[ApiKeyRecord]: ) role = parts[3] if len(parts) == 4 else MEMBER_ROLE if role not in SUPPORTED_ROLES: - raise ValueError( - "DOCSEARCH_API_KEYS role must be one of: admin, member.", - ) + raise ValueError("DOCSEARCH_API_KEYS role must be one of: admin, member.") records.append( ApiKeyRecord( @@ -44,3 +172,58 @@ def _parse_api_keys(raw_value: str) -> list[ApiKeyRecord]: ) return records + + +def _normalize_employee_id(employee_id: str) -> str: + normalized = employee_id.strip() + if not normalized: + raise AuthError("사번을 입력하세요.") + return normalized + + +def _normalize_optional(value: str | None) -> str | None: + if value is None: + return None + normalized = value.strip() + return normalized or None + + +def _validate_password(password: str) -> None: + if len(password) < 4: + raise AuthError("비밀번호는 4자 이상이어야 합니다.") + + +def hash_password(password: str) -> str: + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", + password.encode(), + salt.encode(), + 120_000, + ).hex() + return f"pbkdf2_sha256${salt}${digest}" + + +def _verify_password(password: str, password_hash: str) -> bool: + try: + algorithm, salt, expected_digest = password_hash.split("$", 2) + except ValueError: + return False + if algorithm != "pbkdf2_sha256": + return False + digest = hashlib.pbkdf2_hmac( + "sha256", + password.encode(), + salt.encode(), + 120_000, + ).hex() + return hmac.compare_digest(digest, expected_digest) + + +def _base64url_encode(value: bytes) -> str: + return base64.urlsafe_b64encode(value).decode().rstrip("=") + + +def _base64url_decode(value: str) -> bytes: + padding = "=" * (-len(value) % 4) + return base64.urlsafe_b64decode(value + padding) diff --git a/backend/app/auth/store.py b/backend/app/auth/store.py new file mode 100644 index 0000000..22b40da --- /dev/null +++ b/backend/app/auth/store.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import hashlib +import secrets +from threading import Lock +from typing import Iterable, Protocol + +from backend.app.auth.models import MEMBER_ROLE, SUPPORTED_ROLES, UserRecord + + +class AuthUserStore(Protocol): + def get_user(self, employee_id: str) -> UserRecord | None: + raise NotImplementedError + + def create_user(self, record: UserRecord) -> bool: + raise NotImplementedError + + +class InMemoryAuthUserStore: + def __init__(self, seed_users: Iterable[UserRecord]) -> None: + self._records = {record.employee_id: record for record in seed_users} + self._lock = Lock() + + def get_user(self, employee_id: str) -> UserRecord | None: + with self._lock: + return self._records.get(employee_id) + + def create_user(self, record: UserRecord) -> bool: + with self._lock: + if record.employee_id in self._records: + return False + self._records[record.employee_id] = record + return True + + +def parse_auth_users(raw_value: str) -> list[UserRecord]: + records: list[UserRecord] = [] + + for entry in raw_value.split(";"): + normalized_entry = entry.strip() + if not normalized_entry: + continue + + parts = [part.strip() for part in normalized_entry.split("|")] + if len(parts) not in {5, 6}: + raise ValueError( + "DOCSEARCH_AUTH_USERS entries must use employee_id|password|workspace_id|workspace_name|role(|display_name) format.", + ) + role = parts[4] + if role not in SUPPORTED_ROLES: + raise ValueError("DOCSEARCH_AUTH_USERS role must be one of: admin, member.") + + employee_id = parts[0].strip() + if not employee_id: + raise ValueError("DOCSEARCH_AUTH_USERS employee_id must not be empty.") + records.append( + UserRecord( + employee_id=employee_id, + password_hash=_hash_password(parts[1]), + workspace_id=parts[2], + workspace_name=parts[3], + role=role, + display_name=_normalize_optional(parts[5] if len(parts) == 6 else None), + ), + ) + + return records + + +def create_auth_user_store(settings) -> AuthUserStore: + seed_users = parse_auth_users(settings.auth_users) + if settings.auth_user_backend == "postgres": + from backend.app.auth.postgres_store import PostgresAuthUserStore + + return PostgresAuthUserStore( + database_url=settings.database_url, + seed_users=seed_users, + ) + + return InMemoryAuthUserStore(seed_users) + + +def build_member_user_record( + *, + employee_id: str, + password_hash: str, + workspace_id: str, + workspace_name: str, + display_name: str | None = None, +) -> UserRecord: + return UserRecord( + employee_id=employee_id, + password_hash=password_hash, + workspace_id=workspace_id, + workspace_name=workspace_name, + role=MEMBER_ROLE, + display_name=display_name, + ) + + +def _normalize_optional(value: str | None) -> str | None: + if value is None: + return None + normalized = value.strip() + return normalized or None + + +def _hash_password(password: str) -> str: + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", + password.encode(), + salt.encode(), + 120_000, + ).hex() + return f"pbkdf2_sha256${salt}${digest}" diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 3f772af..13d665e 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -7,6 +7,11 @@ DEFAULT_API_KEY = "local-dev-key" DEFAULT_API_KEYS = f"{DEFAULT_API_KEY}|local-workspace|Local Workspace" +DEFAULT_AUTH_USERS = ( + "1001|password|local-workspace|Local Workspace|admin|관리자;" + "2301029|password|local-workspace|Local Workspace|admin|관리자;" + "1002|password|local-workspace|Local Workspace|member|사용자" +) def _bool_env(name: str, default: bool) -> bool: @@ -40,6 +45,31 @@ class Settings(BaseModel): DEFAULT_API_KEYS, ), ) + auth_users: str = Field( + default_factory=lambda: os.getenv("DOCSEARCH_AUTH_USERS", DEFAULT_AUTH_USERS), + ) + auth_user_backend: Literal["inmemory", "postgres"] = Field( + default_factory=lambda: os.getenv("AUTH_USER_BACKEND", "inmemory"), + ) + auth_token_secret: str = Field( + default_factory=lambda: os.getenv("DOCSEARCH_AUTH_TOKEN_SECRET", "local-dev-secret"), + ) + auth_token_ttl_seconds: int = Field( + default_factory=lambda: int(os.getenv("DOCSEARCH_AUTH_TOKEN_TTL_SECONDS", "86400")), + gt=0, + ) + signup_default_workspace_id: str = Field( + default_factory=lambda: os.getenv( + "DOCSEARCH_SIGNUP_WORKSPACE_ID", + "local-workspace", + ), + ) + signup_default_workspace_name: str = Field( + default_factory=lambda: os.getenv( + "DOCSEARCH_SIGNUP_WORKSPACE_NAME", + "Local Workspace", + ), + ) database_url: str = Field( default_factory=lambda: os.getenv( "DATABASE_URL", diff --git a/backend/app/main.py b/backend/app/main.py index c5580af..3b5a9c4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -4,6 +4,9 @@ from backend.app.audit.router import router as audit_router from backend.app.auth.dependencies import require_workspace_context from backend.app.auth.models import WorkspaceContext +from backend.app.auth.router import router as auth_router +from backend.app.auth.service import AuthService +from backend.app.auth.store import create_auth_user_store from backend.app.chat.router import router as chat_router from backend.app.core.dependency_health import DependencyHealthChecker from backend.app.core.operation_events import InMemoryOperationEventStore @@ -30,6 +33,10 @@ def create_app() -> FastAPI: app.add_middleware(RateLimitMiddleware, settings=settings) app.add_middleware(SecurityHeadersMiddleware) app.add_middleware(RequestContextMiddleware) + app.state.auth_service = AuthService( + settings, + user_store=create_auth_user_store(settings), + ) app.state.dependency_health_checker = DependencyHealthChecker() app.state.operation_event_store = InMemoryOperationEventStore() @@ -59,9 +66,10 @@ async def ready() -> JSONResponse: @app.get("/v1/workspace") async def workspace( workspace_context: WorkspaceContext = Depends(require_workspace_context), - ) -> dict[str, str]: - return workspace_context.model_dump() + ) -> WorkspaceContext: + return workspace_context + app.include_router(auth_router) app.include_router(documents_router) app.include_router(search_router) app.include_router(chat_router) diff --git a/backend/app/middleware/rate_limit.py b/backend/app/middleware/rate_limit.py index ecd1e28..957df36 100644 --- a/backend/app/middleware/rate_limit.py +++ b/backend/app/middleware/rate_limit.py @@ -249,6 +249,12 @@ async def dispatch( return response def _bucket_key(self, request: Request) -> str: + authorization = request.headers.get("Authorization") + if authorization and authorization.lower().startswith("bearer "): + token = authorization[7:].strip() + if token: + return f"auth_token:{token}" + api_key = request.headers.get("X-API-Key") if api_key and api_key.strip(): return f"api_key:{api_key.strip()}" diff --git a/backend/tests/auth/test_api_key_auth.py b/backend/tests/auth/test_api_key_auth.py index d2e2758..0085e7c 100644 --- a/backend/tests/auth/test_api_key_auth.py +++ b/backend/tests/auth/test_api_key_auth.py @@ -12,7 +12,7 @@ def clear_settings_cache() -> None: get_settings.cache_clear() -def test_workspace_route_requires_api_key() -> None: +def test_workspace_route_requires_credentials() -> None: client = TestClient(create_app()) response = client.get("/v1/workspace") @@ -20,8 +20,8 @@ def test_workspace_route_requires_api_key() -> None: assert response.status_code == 401 assert response.json() == { "detail": { - "code": "AUTH_MISSING_API_KEY", - "message": "API key is required.", + "code": "AUTH_MISSING_CREDENTIALS", + "message": "Authentication credential is required.", } } diff --git a/backend/tests/auth/test_login_auth.py b/backend/tests/auth/test_login_auth.py new file mode 100644 index 0000000..1abc940 --- /dev/null +++ b/backend/tests/auth/test_login_auth.py @@ -0,0 +1,76 @@ +from fastapi.testclient import TestClient +import pytest + +from backend.app.core.config import get_settings +from backend.app.main import create_app + + +@pytest.fixture(autouse=True) +def clear_settings_cache() -> None: + get_settings.cache_clear() + yield + get_settings.cache_clear() + + +def test_login_returns_token_and_workspace_context() -> None: + client = TestClient(create_app()) + + response = client.post( + "/v1/auth/login", + json={"employee_id": "2301029", "password": "password"}, + ) + + assert response.status_code == 200 + body = response.json() + assert body["access_token"] + assert body["workspace"]["employee_id"] == "2301029" + assert body["workspace"]["role"] == "admin" + + me = client.get( + "/v1/auth/me", + headers={"Authorization": f"Bearer {body['access_token']}"}, + ) + + assert me.status_code == 200 + assert me.json()["employee_id"] == "2301029" + assert me.json()["role"] == "admin" + + +def test_signup_registers_member_user_and_rejects_duplicates() -> None: + client = TestClient(create_app()) + + response = client.post( + "/v1/auth/signup", + json={ + "employee_id": "2001", + "password": "pass1234", + "display_name": "Portfolio User", + }, + ) + + assert response.status_code == 201 + body = response.json() + assert body["access_token"] + assert body["workspace"]["employee_id"] == "2001" + assert body["workspace"]["display_name"] == "Portfolio User" + assert body["workspace"]["role"] == "member" + + duplicate = client.post( + "/v1/auth/signup", + json={"employee_id": "2001", "password": "pass1234"}, + ) + + assert duplicate.status_code == 409 + assert duplicate.json()["detail"]["code"] == "AUTH_DUPLICATE_EMPLOYEE_ID" + + +def test_login_rejects_wrong_password() -> None: + client = TestClient(create_app()) + + response = client.post( + "/v1/auth/login", + json={"employee_id": "1001", "password": "wrong-password"}, + ) + + assert response.status_code == 401 + assert response.json()["detail"]["code"] == "AUTH_INVALID_CREDENTIALS" diff --git a/backend/tests/auth/test_postgres_auth_user_store.py b/backend/tests/auth/test_postgres_auth_user_store.py new file mode 100644 index 0000000..7a2225e --- /dev/null +++ b/backend/tests/auth/test_postgres_auth_user_store.py @@ -0,0 +1,110 @@ +from backend.app.auth.models import UserRecord +from backend.app.auth.postgres_store import PostgresAuthUserStore +from backend.app.auth.store import parse_auth_users + + +class FakeCursor: + def __init__(self, rows: list[dict[str, object]]) -> None: + self._rows = rows + + def fetchall(self) -> list[dict[str, object]]: + return self._rows + + +class FakeConnection: + def __init__(self, rows: list[dict[str, object]] | None = None) -> None: + self.rows = rows or [] + self.statements: list[tuple[str, dict[str, object] | None]] = [] + self.commit_count = 0 + + def __enter__(self) -> "FakeConnection": + return self + + def __exit__(self, exc_type, exc, traceback) -> None: + return None + + def execute( + self, + sql: str, + params: dict[str, object] | None = None, + ) -> FakeCursor: + self.statements.append((sql, params)) + return FakeCursor(self.rows) + + def commit(self) -> None: + self.commit_count += 1 + + +def test_PostgresAuthUserStore는_스키마를_보장하고_기본_계정을_시드한다() -> None: + connection = FakeConnection() + store = PostgresAuthUserStore( + database_url="postgresql://docsearch:docsearch@postgres:5432/docsearch", + seed_users=parse_auth_users( + "2301029|password|local-workspace|Local Workspace|admin|관리자", + ), + connection_factory=lambda: connection, + ) + + assert store is not None + assert "CREATE TABLE IF NOT EXISTS auth_users" in connection.statements[0][0] + seed_sql, seed_params = connection.statements[-1] + assert "INSERT INTO auth_users" in seed_sql + assert "ON CONFLICT (employee_id) DO NOTHING" in seed_sql + assert seed_params is not None + assert seed_params["employee_id"] == "2301029" + assert seed_params["role"] == "admin" + assert seed_params["display_name"] == "관리자" + assert connection.commit_count == 2 + + +def test_PostgresAuthUserStore는_회원가입_계정을_저장한다() -> None: + connection = FakeConnection(rows=[{"employee_id": "2001"}]) + store = PostgresAuthUserStore( + database_url="postgresql://docsearch:docsearch@postgres:5432/docsearch", + seed_users=[], + connection_factory=lambda: connection, + ) + + created = store.create_user( + UserRecord( + employee_id="2001", + password_hash="pbkdf2_sha256$salt$digest", + workspace_id="local-workspace", + workspace_name="Local Workspace", + role="member", + display_name="사용자", + ), + ) + + assert created is True + insert_sql, insert_params = connection.statements[-1] + assert "RETURNING employee_id" in insert_sql + assert insert_params is not None + assert insert_params["employee_id"] == "2001" + assert insert_params["role"] == "member" + assert connection.commit_count == 2 + + +def test_PostgresAuthUserStore는_사번으로_계정을_조회한다() -> None: + row = { + "employee_id": "2301029", + "password_hash": "pbkdf2_sha256$salt$digest", + "workspace_id": "local-workspace", + "workspace_name": "Local Workspace", + "role": "admin", + "display_name": "관리자", + } + connection = FakeConnection(rows=[row]) + store = PostgresAuthUserStore( + database_url="postgresql://docsearch:docsearch@postgres:5432/docsearch", + seed_users=[], + connection_factory=lambda: connection, + ) + + record = store.get_user("2301029") + + assert record == UserRecord(**row) + select_sql, select_params = connection.statements[-1] + assert "FROM auth_users" in select_sql + assert "WHERE employee_id = %(employee_id)s" in select_sql + assert select_params == {"employee_id": "2301029"} diff --git a/backend/tests/middleware/test_rate_limit.py b/backend/tests/middleware/test_rate_limit.py index abf7f2c..50ad4a0 100644 --- a/backend/tests/middleware/test_rate_limit.py +++ b/backend/tests/middleware/test_rate_limit.py @@ -203,6 +203,27 @@ def test_v1_routes_are_limited_by_api_key(monkeypatch: pytest.MonkeyPatch) -> No assert other_key.headers["X-RateLimit-Remaining"] == "1" +def test_v1_routes_are_limited_by_bearer_token() -> None: + from fastapi import FastAPI + + app = FastAPI() + app.add_middleware(RateLimitMiddleware, settings=LimitByOneSettings()) + + @app.get("/v1/ping") + async def ping() -> dict[str, str]: + return {"status": "ok"} + + client = TestClient(app) + + first = client.get("/v1/ping", headers={"Authorization": "Bearer alpha-token"}) + blocked = client.get("/v1/ping", headers={"Authorization": "Bearer alpha-token"}) + other_token = client.get("/v1/ping", headers={"Authorization": "Bearer beta-token"}) + + assert first.status_code == 200 + assert blocked.status_code == 429 + assert other_token.status_code == 200 + + def test_v1_routes_are_limited_by_ip_when_api_key_is_missing( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -270,3 +291,13 @@ class FailOpenSettings: rate_limit_redis_prefix = "docsearch:test" rate_limit_fail_open = True redis_url = "redis://redis:6379/0" + + +class LimitByOneSettings: + rate_limit_enabled = True + rate_limit_backend = "memory" + rate_limit_requests = 1 + rate_limit_window_seconds = 60 + rate_limit_redis_prefix = "docsearch:test" + rate_limit_fail_open = True + redis_url = "redis://redis:6379/0" diff --git a/infra/compose/docker-compose.yml b/infra/compose/docker-compose.yml index 9196039..6c2531f 100644 --- a/infra/compose/docker-compose.yml +++ b/infra/compose/docker-compose.yml @@ -25,6 +25,7 @@ services: APP_ENV: development DEBUG: "false" DOCSEARCH_API_KEYS: "local-dev-key|local-workspace|Local Workspace|admin;local-member-key|local-workspace|Local Workspace|member" + AUTH_USER_BACKEND: postgres DATABASE_URL: postgresql://docsearch:docsearch@postgres:5432/docsearch AUDIT_LOG_BACKEND: postgres DOCUMENT_METADATA_BACKEND: postgres From 0dfb0c820b451208db08856108f9ffa55a889857 Mon Sep 17 00:00:00 2001 From: burnern <200775118+dev-burnern@users.noreply.github.com> Date: Sun, 17 May 2026 01:19:05 +0900 Subject: [PATCH 2/4] =?UTF-8?q?feat(documents):=20=EB=AC=B8=EC=84=9C=20?= =?UTF-8?q?=EB=B3=B4=EC=95=88=EB=93=B1=EA=B8=89=20=EA=B2=80=EC=83=89=20?= =?UTF-8?q?=ED=95=84=ED=84=B0=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/chat/models.py | 4 ++ backend/app/chat/router.py | 10 +++- backend/app/chat/service.py | 2 + backend/app/documents/models.py | 15 ++++++ backend/app/documents/postgres_store.py | 24 +++++++++ backend/app/documents/router.py | 5 ++ backend/app/documents/security.py | 34 +++++++++++++ backend/app/documents/service.py | 7 +++ backend/app/jobs/base.py | 2 + backend/app/retrieval/filters.py | 14 ++++++ backend/app/retrieval/qdrant_store.py | 5 ++ backend/app/search/models.py | 4 ++ backend/app/search/router.py | 5 ++ backend/tests/chat/test_router.py | 6 ++- backend/tests/chat/test_service.py | 3 ++ .../documents/test_postgres_document_store.py | 8 ++- backend/tests/documents/test_upload_api.py | 50 +++++++++++++++++++ backend/tests/retrieval/test_filters.py | 7 ++- backend/tests/retrieval/test_qdrant_store.py | 2 + backend/tests/search/test_search_router.py | 7 ++- 20 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 backend/app/documents/security.py diff --git a/backend/app/chat/models.py b/backend/app/chat/models.py index f26691a..e30ce39 100644 --- a/backend/app/chat/models.py +++ b/backend/app/chat/models.py @@ -1,9 +1,12 @@ from pydantic import BaseModel, Field +from backend.app.documents.models import DocumentSecurityLevel + class ChatRequest(BaseModel): question: str = Field(min_length=1, max_length=4000) document_ids: list[str] | None = None + security_levels: list[DocumentSecurityLevel] | None = None top_k: int | None = Field(default=None, ge=1, le=20) @@ -11,6 +14,7 @@ class ChatCitation(BaseModel): citation_id: int document_id: str filename: str + security_level: DocumentSecurityLevel chunk_index: int score: float rerank_score: float | None = None diff --git a/backend/app/chat/router.py b/backend/app/chat/router.py index 525cba1..4a0f8be 100644 --- a/backend/app/chat/router.py +++ b/backend/app/chat/router.py @@ -12,6 +12,7 @@ get_qdrant_store, get_runtime_settings, ) +from backend.app.documents.security import validate_document_security_levels from backend.app.indexing.embedder import EmbeddingProviderError from backend.app.llm.base import LLMClient, LLMProviderError from backend.app.llm.profiles import get_default_llm_profile @@ -76,9 +77,16 @@ async def answer_question( chat_service: ChatService = Depends(get_chat_service), ) -> ChatResponse: try: + validated_request = chat_request.model_copy( + update={ + "security_levels": validate_document_security_levels( + chat_request.security_levels, + ), + }, + ) return chat_service.answer( workspace_context=workspace_context, - chat_request=chat_request, + chat_request=validated_request, ) except ChatContextNotFoundError as exc: raise HTTPException( diff --git a/backend/app/chat/service.py b/backend/app/chat/service.py index 1e9085a..61d596d 100644 --- a/backend/app/chat/service.py +++ b/backend/app/chat/service.py @@ -72,6 +72,7 @@ def answer( filters=RetrievalFilter( workspace_id=workspace_context.workspace_id, document_ids=chat_request.document_ids, + security_levels=chat_request.security_levels, ), limit=retrieval_limit, ) @@ -248,6 +249,7 @@ def _build_citations( citation_id=citation_id, document_id=item.chunk.document_id, filename=item.chunk.filename, + security_level=item.chunk.security_level, chunk_index=item.chunk.chunk_index, score=item.chunk.score, rerank_score=item.rerank_score, diff --git a/backend/app/documents/models.py b/backend/app/documents/models.py index 3ed63f6..5d71031 100644 --- a/backend/app/documents/models.py +++ b/backend/app/documents/models.py @@ -3,10 +3,25 @@ from pydantic import BaseModel, Field +DocumentSecurityLevel = str +GENERAL_SECURITY_LEVEL = "general" +INTERNAL_SECURITY_LEVEL = "internal" +CONFIDENTIAL_SECURITY_LEVEL = "confidential" +RESTRICTED_SECURITY_LEVEL = "restricted" +SUPPORTED_DOCUMENT_SECURITY_LEVELS = { + GENERAL_SECURITY_LEVEL, + INTERNAL_SECURITY_LEVEL, + CONFIDENTIAL_SECURITY_LEVEL, + RESTRICTED_SECURITY_LEVEL, +} + + class DocumentMetadata(BaseModel): document_id: str workspace_id: str workspace_name: str + uploaded_by_employee_id: str | None = None + security_level: DocumentSecurityLevel = INTERNAL_SECURITY_LEVEL filename: str parser: str character_count: int diff --git a/backend/app/documents/postgres_store.py b/backend/app/documents/postgres_store.py index 3095115..b538440 100644 --- a/backend/app/documents/postgres_store.py +++ b/backend/app/documents/postgres_store.py @@ -23,6 +23,8 @@ def record_document(self, record: DocumentRecord) -> None: document_id, workspace_id, workspace_name, + uploaded_by_employee_id, + security_level, filename, parser, character_count, @@ -38,6 +40,8 @@ def record_document(self, record: DocumentRecord) -> None: %(document_id)s, %(workspace_id)s, %(workspace_name)s, + %(uploaded_by_employee_id)s, + %(security_level)s, %(filename)s, %(parser)s, %(character_count)s, @@ -51,6 +55,8 @@ def record_document(self, record: DocumentRecord) -> None: ) ON CONFLICT (document_id) DO UPDATE SET workspace_name = EXCLUDED.workspace_name, + uploaded_by_employee_id = EXCLUDED.uploaded_by_employee_id, + security_level = EXCLUDED.security_level, filename = EXCLUDED.filename, parser = EXCLUDED.parser, character_count = EXCLUDED.character_count, @@ -79,6 +85,8 @@ def list_documents( document_id, workspace_id, workspace_name, + uploaded_by_employee_id, + security_level, filename, parser, character_count, @@ -161,6 +169,8 @@ def _ensure_schema(self) -> None: document_id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL, workspace_name TEXT NOT NULL, + uploaded_by_employee_id TEXT, + security_level TEXT NOT NULL DEFAULT 'internal', filename TEXT NOT NULL, parser TEXT NOT NULL, character_count INTEGER NOT NULL, @@ -180,6 +190,18 @@ def _ensure_schema(self) -> None: ADD COLUMN IF NOT EXISTS indexing_error TEXT """ ) + connection.execute( + """ + ALTER TABLE document_metadata + ADD COLUMN IF NOT EXISTS uploaded_by_employee_id TEXT + """ + ) + connection.execute( + """ + ALTER TABLE document_metadata + ADD COLUMN IF NOT EXISTS security_level TEXT NOT NULL DEFAULT 'internal' + """ + ) connection.execute( """ CREATE INDEX IF NOT EXISTS idx_document_metadata_workspace_uploaded_at @@ -200,6 +222,8 @@ def _document_columns() -> str: document_id, workspace_id, workspace_name, + uploaded_by_employee_id, + security_level, filename, parser, character_count, diff --git a/backend/app/documents/router.py b/backend/app/documents/router.py index ecc77ea..92e02c2 100644 --- a/backend/app/documents/router.py +++ b/backend/app/documents/router.py @@ -5,6 +5,7 @@ APIRouter, Depends, File, + Form, HTTPException, Query, Request, @@ -22,6 +23,7 @@ DocumentUploadResponse, ) from backend.app.documents.postgres_store import PostgresDocumentMetadataStore +from backend.app.documents.security import validate_document_security_level from backend.app.documents.service import DocumentNotFoundError, DocumentService from backend.app.documents.store import DocumentMetadataStore, InMemoryDocumentMetadataStore from backend.app.indexing.chunker import CharacterChunker @@ -162,16 +164,19 @@ def get_document_service( @router.post("", response_model=DocumentUploadResponse, status_code=status.HTTP_201_CREATED) async def upload_document( file: UploadFile = File(...), + security_level: str = Form(default="internal"), workspace_context: WorkspaceContext = Depends(require_workspace_context), document_service: DocumentService = Depends(get_document_service), ) -> DocumentUploadResponse: try: data = await file.read() + validated_security_level = validate_document_security_level(security_level) return document_service.upload_document( workspace_context=workspace_context, filename=file.filename or "document", content_type=file.content_type or "application/octet-stream", data=data, + security_level=validated_security_level, ) except DocumentProcessingError as exc: raise _document_processing_error(exc) from exc diff --git a/backend/app/documents/security.py b/backend/app/documents/security.py new file mode 100644 index 0000000..7050220 --- /dev/null +++ b/backend/app/documents/security.py @@ -0,0 +1,34 @@ +from fastapi import HTTPException, status + +from backend.app.documents.models import ( + INTERNAL_SECURITY_LEVEL, + SUPPORTED_DOCUMENT_SECURITY_LEVELS, +) + + +def validate_document_security_level(security_level: str) -> str: + normalized = security_level.strip() or INTERNAL_SECURITY_LEVEL + if normalized not in SUPPORTED_DOCUMENT_SECURITY_LEVELS: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={ + "code": "DOCUMENT_INVALID_SECURITY_LEVEL", + "message": ( + "Document security level must be general, internal, " + "confidential, or restricted." + ), + }, + ) + return normalized + + +def validate_document_security_levels(security_levels: list[str] | None) -> list[str] | None: + if not security_levels: + return None + + validated: list[str] = [] + for security_level in security_levels: + normalized = validate_document_security_level(security_level) + if normalized not in validated: + validated.append(normalized) + return validated diff --git a/backend/app/documents/service.py b/backend/app/documents/service.py index c70270a..a141050 100644 --- a/backend/app/documents/service.py +++ b/backend/app/documents/service.py @@ -43,6 +43,7 @@ def upload_document( filename: str, content_type: str, data: bytes, + security_level: str = "internal", ) -> DocumentUploadResponse: document_id = uuid4().hex indexing_job_id = uuid4().hex @@ -66,6 +67,8 @@ def upload_document( filename=filename, content_type=content_type, storage_key=storage_key, + uploaded_by_employee_id=workspace_context.employee_id, + security_level=security_level, ), ) @@ -73,6 +76,8 @@ def upload_document( document_id=document_id, workspace_id=workspace_context.workspace_id, workspace_name=workspace_context.workspace_name, + uploaded_by_employee_id=workspace_context.employee_id, + security_level=security_level, filename=filename, parser=parsed.parser_name, character_count=parsed.character_count, @@ -151,6 +156,8 @@ def reindex_document( filename=record.filename, content_type=_guess_content_type(record.filename), storage_key=record.storage_key, + uploaded_by_employee_id=record.uploaded_by_employee_id, + security_level=record.security_level, ), ) updated = record.model_copy( diff --git a/backend/app/jobs/base.py b/backend/app/jobs/base.py index 149dc2c..64ceb0d 100644 --- a/backend/app/jobs/base.py +++ b/backend/app/jobs/base.py @@ -14,6 +14,8 @@ class IndexDocumentJob: filename: str content_type: str storage_key: str + uploaded_by_employee_id: str | None = None + security_level: str = "internal" attempt: int = 1 max_attempts: int = 3 diff --git a/backend/app/retrieval/filters.py b/backend/app/retrieval/filters.py index 13e6500..6cbc6a7 100644 --- a/backend/app/retrieval/filters.py +++ b/backend/app/retrieval/filters.py @@ -7,6 +7,7 @@ class RetrievalFilter: workspace_id: str document_ids: list[str] | None = None + security_levels: list[str] | None = None def build_qdrant_filter(filters: RetrievalFilter) -> models.Filter: @@ -27,4 +28,17 @@ def build_qdrant_filter(filters: RetrievalFilter) -> models.Filter: for document_id in filters.document_ids ] + if filters.security_levels: + must.append( + models.Filter( + should=[ + models.FieldCondition( + key="security_level", + match=models.MatchValue(value=security_level), + ) + for security_level in filters.security_levels + ], + ), + ) + return models.Filter(must=must, should=should) diff --git a/backend/app/retrieval/qdrant_store.py b/backend/app/retrieval/qdrant_store.py index 0629d03..14eeece 100644 --- a/backend/app/retrieval/qdrant_store.py +++ b/backend/app/retrieval/qdrant_store.py @@ -16,6 +16,7 @@ class RetrievedChunk: chunk_index: int chunk_text: str score: float + security_level: str = "internal" class QdrantVectorStore: @@ -52,6 +53,8 @@ def upsert_chunks( "workspace_id": job.workspace_id, "workspace_name": job.workspace_name, "document_id": job.document_id, + "uploaded_by_employee_id": job.uploaded_by_employee_id, + "security_level": job.security_level, "filename": job.filename, "parser": parser_name, "chunk_index": index, @@ -89,6 +92,7 @@ def search( document_id=str(point.payload["document_id"]), filename=str(point.payload["filename"]), parser=str(point.payload["parser"]), + security_level=str(point.payload.get("security_level", "internal")), chunk_index=int(point.payload["chunk_index"]), chunk_text=str(point.payload["chunk_text"]), score=float(point.score), @@ -116,6 +120,7 @@ def list_chunks( document_id=str(record.payload["document_id"]), filename=str(record.payload["filename"]), parser=str(record.payload["parser"]), + security_level=str(record.payload.get("security_level", "internal")), chunk_index=int(record.payload["chunk_index"]), chunk_text=str(record.payload["chunk_text"]), score=0.0, diff --git a/backend/app/search/models.py b/backend/app/search/models.py index 4921d62..484969d 100644 --- a/backend/app/search/models.py +++ b/backend/app/search/models.py @@ -1,9 +1,12 @@ from pydantic import BaseModel, Field +from backend.app.documents.models import DocumentSecurityLevel + class SearchRequest(BaseModel): query: str = Field(min_length=1, max_length=4000) document_ids: list[str] | None = None + security_levels: list[DocumentSecurityLevel] | None = None limit: int = Field(default=5, ge=1, le=20) @@ -11,6 +14,7 @@ class SearchResultChunk(BaseModel): document_id: str filename: str parser: str + security_level: DocumentSecurityLevel chunk_index: int score: float snippet: str diff --git a/backend/app/search/router.py b/backend/app/search/router.py index 14e6271..cede536 100644 --- a/backend/app/search/router.py +++ b/backend/app/search/router.py @@ -8,6 +8,7 @@ get_qdrant_store, get_runtime_settings, ) +from backend.app.documents.security import validate_document_security_levels from backend.app.indexing.embedder import EmbeddingProviderError from backend.app.retrieval.filters import RetrievalFilter from backend.app.retrieval.retriever import Retriever, build_retriever @@ -41,6 +42,9 @@ async def search_documents( filters=RetrievalFilter( workspace_id=workspace_context.workspace_id, document_ids=search_request.document_ids, + security_levels=validate_document_security_levels( + search_request.security_levels, + ), ), limit=search_request.limit, ) @@ -58,6 +62,7 @@ async def search_documents( document_id=chunk.document_id, filename=chunk.filename, parser=chunk.parser, + security_level=chunk.security_level, chunk_index=chunk.chunk_index, score=chunk.score, snippet=chunk.chunk_text, diff --git a/backend/tests/chat/test_router.py b/backend/tests/chat/test_router.py index ab977f7..c596ab1 100644 --- a/backend/tests/chat/test_router.py +++ b/backend/tests/chat/test_router.py @@ -23,6 +23,7 @@ def answer(self, *, workspace_context, chat_request: ChatRequest) -> ChatRespons citation_id=1, document_id="doc-1", filename="policy.md", + security_level="internal", chunk_index=0, score=0.88, snippet="문서 일부", @@ -70,6 +71,7 @@ def test_채팅_API가_워크스페이스_인증_후_답변을_반환한다( json={ "question": "정책 문서 요약해줘", "document_ids": ["doc-1"], + "security_levels": ["internal"], }, ) @@ -78,6 +80,7 @@ def test_채팅_API가_워크스페이스_인증_후_답변을_반환한다( assert fake_service.chat_request is not None assert fake_service.chat_request.question == "정책 문서 요약해줘" assert fake_service.chat_request.document_ids == ["doc-1"] + assert fake_service.chat_request.security_levels == ["internal"] assert response.json() == { "answer": "권한이 확인된 문서 기준 답변입니다. [1]", "model": "google/gemma-4-E4B-it", @@ -86,6 +89,7 @@ def test_채팅_API가_워크스페이스_인증_후_답변을_반환한다( "citation_id": 1, "document_id": "doc-1", "filename": "policy.md", + "security_level": "internal", "chunk_index": 0, "score": 0.88, "snippet": "문서 일부", @@ -110,7 +114,7 @@ def test_채팅_API는_API_Key가_없으면_거부한다() -> None: ) assert response.status_code == 401 - assert response.json()["detail"]["code"] == "AUTH_MISSING_API_KEY" + assert response.json()["detail"]["code"] == "AUTH_MISSING_CREDENTIALS" def test_chat_api_returns_502_when_embedding_backend_fails( diff --git a/backend/tests/chat/test_service.py b/backend/tests/chat/test_service.py index 669610a..f3cdfb8 100644 --- a/backend/tests/chat/test_service.py +++ b/backend/tests/chat/test_service.py @@ -109,6 +109,7 @@ def test_chat_service_answers_with_reranked_citations() -> None: chat_request=ChatRequest( question="보안 정책 요약해줘", document_ids=["doc-1"], + security_levels=["internal"], ), ) @@ -116,6 +117,7 @@ def test_chat_service_answers_with_reranked_citations() -> None: assert retriever.filters == RetrievalFilter( workspace_id="workspace-alpha", document_ids=["doc-1"], + security_levels=["internal"], ) assert retriever.limit == 3 assert reranker.request is not None @@ -135,6 +137,7 @@ def test_chat_service_answers_with_reranked_citations() -> None: assert response.citations[0].citation_id == 1 assert response.citations[0].document_id == "doc-1" assert response.citations[0].filename == "policy.md" + assert response.citations[0].security_level == "internal" assert response.citations[0].chunk_index == 2 assert response.citations[0].score == 0.91 assert response.citations[0].rerank_score == 1.0 diff --git a/backend/tests/documents/test_postgres_document_store.py b/backend/tests/documents/test_postgres_document_store.py index 21591ec..ae53183 100644 --- a/backend/tests/documents/test_postgres_document_store.py +++ b/backend/tests/documents/test_postgres_document_store.py @@ -64,11 +64,17 @@ def test_PostgresDocumentMetadataStore는_스키마를_보장하고_문서를_ assert "CREATE TABLE IF NOT EXISTS document_metadata" in connection.statements[0][0] assert "ADD COLUMN IF NOT EXISTS indexing_error" in connection.statements[1][0] - insert_sql, insert_params = connection.statements[3] + insert_sql, insert_params = next( + statement + for statement in connection.statements + if "INSERT INTO document_metadata" in statement[0] + ) assert "INSERT INTO document_metadata" in insert_sql assert insert_params is not None assert insert_params["document_id"] == "doc-1" assert insert_params["workspace_id"] == "workspace-alpha" + assert insert_params["uploaded_by_employee_id"] is None + assert insert_params["security_level"] == "internal" assert insert_params["indexing_error"] is None assert insert_params["uploaded_at"] == datetime(2026, 5, 15, 9, 0, tzinfo=UTC) assert connection.commit_count == 2 diff --git a/backend/tests/documents/test_upload_api.py b/backend/tests/documents/test_upload_api.py index fb4ede4..a4ed38f 100644 --- a/backend/tests/documents/test_upload_api.py +++ b/backend/tests/documents/test_upload_api.py @@ -197,6 +197,42 @@ def test_upload_normalizes_filename_and_content_type( assert storage.saved[0]["content_type"] == "text/plain" +def test_upload_with_login_token_records_uploader_and_security_level( + client: TestClient, + document_store: InMemoryDocumentMetadataStore, +) -> None: + token = _login_token(client, employee_id="1002") + + response = client.post( + "/v1/documents", + headers={"Authorization": f"Bearer {token}"}, + data={"security_level": "confidential"}, + files={"file": ("memo.txt", b"hello docsearch", "text/plain")}, + ) + + assert response.status_code == 201 + assert response.json()["uploaded_by_employee_id"] == "1002" + assert response.json()["security_level"] == "confidential" + + records = document_store.list_documents(workspace_id="local-workspace") + assert records[0].uploaded_by_employee_id == "1002" + assert records[0].security_level == "confidential" + + +def test_upload_rejects_unknown_security_level(client: TestClient) -> None: + token = _login_token(client, employee_id="1002") + + response = client.post( + "/v1/documents", + headers={"Authorization": f"Bearer {token}"}, + data={"security_level": "top_secret"}, + files={"file": ("memo.txt", b"hello docsearch", "text/plain")}, + ) + + assert response.status_code == 400 + assert response.json()["detail"]["code"] == "DOCUMENT_INVALID_SECURITY_LEVEL" + + def test_upload_rejects_empty_documents(client: TestClient) -> None: response = client.post( "/v1/documents", @@ -281,3 +317,17 @@ def enqueue(self, job) -> JobDispatchResult: chunk_count=0, failure_reason="parser failed", ) + + +def _login_token( + client: TestClient, + *, + employee_id: str, + password: str = "password", +) -> str: + response = client.post( + "/v1/auth/login", + json={"employee_id": employee_id, "password": password}, + ) + assert response.status_code == 200 + return response.json()["access_token"] diff --git a/backend/tests/retrieval/test_filters.py b/backend/tests/retrieval/test_filters.py index a9185ef..e5d96b7 100644 --- a/backend/tests/retrieval/test_filters.py +++ b/backend/tests/retrieval/test_filters.py @@ -5,12 +5,17 @@ def test_메타데이터_필터가_워크스페이스와_문서조건을_만든 RetrievalFilter( workspace_id="workspace-alpha", document_ids=["doc-1", "doc-2"], + security_levels=["internal", "restricted"], ), ) - assert len(qdrant_filter.must) == 1 + assert len(qdrant_filter.must) == 2 assert qdrant_filter.must[0].key == "workspace_id" assert qdrant_filter.must[0].match.value == "workspace-alpha" + assert len(qdrant_filter.must[1].should) == 2 + assert qdrant_filter.must[1].should[0].key == "security_level" + assert qdrant_filter.must[1].should[0].match.value == "internal" + assert qdrant_filter.must[1].should[1].match.value == "restricted" assert len(qdrant_filter.should) == 2 assert qdrant_filter.should[0].key == "document_id" assert qdrant_filter.should[0].match.value == "doc-1" diff --git a/backend/tests/retrieval/test_qdrant_store.py b/backend/tests/retrieval/test_qdrant_store.py index 8a2641f..84c249a 100644 --- a/backend/tests/retrieval/test_qdrant_store.py +++ b/backend/tests/retrieval/test_qdrant_store.py @@ -40,6 +40,7 @@ def test_Qdrant_저장소가_청크를_저장하고_검색한다() -> None: assert len(results) == 2 assert results[0].document_id == "doc-1" assert results[0].filename == "memo.txt" + assert results[0].security_level == "internal" assert results[0].chunk_index == 0 assert results[0].chunk_text == "alpha budget" @@ -50,6 +51,7 @@ def test_Qdrant_저장소가_청크를_저장하고_검색한다() -> None: assert [chunk.chunk_text for chunk in listed] == ["alpha budget", "beta note"] assert [chunk.score for chunk in listed] == [0.0, 0.0] + assert [chunk.security_level for chunk in listed] == ["internal", "internal"] def test_Qdrant_저장소가_문서_단위로_청크를_삭제한다() -> None: diff --git a/backend/tests/search/test_search_router.py b/backend/tests/search/test_search_router.py index a1b33a6..9ca9e3f 100644 --- a/backend/tests/search/test_search_router.py +++ b/backend/tests/search/test_search_router.py @@ -12,12 +12,14 @@ def __init__(self) -> None: self.query_text: str | None = None self.workspace_id: str | None = None self.document_ids: list[str] | None = None + self.security_levels: list[str] | None = None self.limit: int | None = None def retrieve(self, *, query_text, filters, limit): self.query_text = query_text self.workspace_id = filters.workspace_id self.document_ids = filters.document_ids + self.security_levels = filters.security_levels self.limit = limit return [ RetrievedChunk( @@ -65,6 +67,7 @@ def test_검색_API가_워크스페이스_필터로_청크를_반환한다( json={ "query": "권한 정책", "document_ids": ["doc-1"], + "security_levels": ["internal"], "limit": 5, }, ) @@ -73,6 +76,7 @@ def test_검색_API가_워크스페이스_필터로_청크를_반환한다( assert fake_retriever.query_text == "권한 정책" assert fake_retriever.workspace_id == "workspace-alpha" assert fake_retriever.document_ids == ["doc-1"] + assert fake_retriever.security_levels == ["internal"] assert fake_retriever.limit == 5 assert response.json() == { "query": "권한 정책", @@ -82,6 +86,7 @@ def test_검색_API가_워크스페이스_필터로_청크를_반환한다( "document_id": "doc-1", "filename": "policy.md", "parser": "markdown", + "security_level": "internal", "chunk_index": 2, "score": 0.87, "snippet": "권한 정책 문서 일부", @@ -100,7 +105,7 @@ def test_검색_API는_API_Key가_없으면_거부한다() -> None: ) assert response.status_code == 401 - assert response.json()["detail"]["code"] == "AUTH_MISSING_API_KEY" + assert response.json()["detail"]["code"] == "AUTH_MISSING_CREDENTIALS" def test_search_api_returns_502_when_embedding_backend_fails( From 0da621ea239c5a0887b9abb57b18f849ca7bca78 Mon Sep 17 00:00:00 2001 From: burnern <200775118+dev-burnern@users.noreply.github.com> Date: Sun, 17 May 2026 01:19:41 +0900 Subject: [PATCH 3/4] =?UTF-8?q?feat(frontend):=20=EC=82=AC=EB=B2=88=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=EA=B3=BC=20=EB=B3=B4=EC=95=88?= =?UTF-8?q?=EB=93=B1=EA=B8=89=20UI=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/app/App.test.tsx | 225 +++++------ frontend/src/app/App.tsx | 375 ++++++++++++------ .../features/audit/AuditLogWorkspace.test.tsx | 120 ++---- .../src/features/audit/AuditLogWorkspace.tsx | 24 +- .../src/features/chat/ChatWorkspace.test.tsx | 7 +- frontend/src/features/chat/ChatWorkspace.tsx | 65 ++- .../documents/DocumentWorkspace.test.tsx | 297 ++------------ .../features/documents/DocumentWorkspace.tsx | 99 +++-- .../OperationsStatusWorkspace.test.tsx | 122 +----- .../operations/OperationsStatusWorkspace.tsx | 26 +- frontend/src/lib/audit-log-api.test.ts | 99 +---- frontend/src/lib/audit-log-api.ts | 12 +- frontend/src/lib/auth-api.ts | 117 ++++++ frontend/src/lib/chat-api.test.ts | 40 +- frontend/src/lib/chat-api.ts | 10 +- frontend/src/lib/document-api.test.ts | 186 +++------ frontend/src/lib/document-api.ts | 34 +- frontend/src/lib/operations-api.test.ts | 98 +---- frontend/src/lib/operations-api.ts | 8 +- frontend/src/lib/search-api.test.ts | 68 ++-- frontend/src/lib/search-api.ts | 10 +- frontend/src/lib/workspace-api.test.ts | 90 ++--- frontend/src/lib/workspace-api.ts | 10 +- frontend/src/styles.css | 78 ++-- 24 files changed, 975 insertions(+), 1245 deletions(-) create mode 100644 frontend/src/lib/auth-api.ts diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx index 84fd996..e7d5724 100644 --- a/frontend/src/app/App.test.tsx +++ b/frontend/src/app/App.test.tsx @@ -2,167 +2,152 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it } from "vitest"; +import { AuthClient, AuthResponse } from "../lib/auth-api"; import App from "./App"; -import { WorkspaceClient, WorkspaceContext } from "../lib/workspace-api"; describe("App", () => { - it("채팅 작업 화면을 기본 화면으로 보여준다", () => { + it("로그인 전에는 사번 로그인 화면을 보여준다", () => { render(); - expect( - screen.getByRole("heading", { name: "DocSearch AI" }), - ).toBeInTheDocument(); - expect(screen.getByLabelText("API Key")).toBeInTheDocument(); - expect(screen.getByLabelText("질문")).toBeInTheDocument(); - expect( - screen.getByRole("button", { name: /질문 보내기/ }), - ).toBeDisabled(); - expect(screen.queryByRole("tab", { name: "감사 로그" })).not.toBeInTheDocument(); + expect(screen.getByText("DocSearch AI")).toBeInTheDocument(); + expect(screen.getByRole("heading", { name: "로그인" })).toBeInTheDocument(); + expect(screen.getByLabelText("사번")).toBeInTheDocument(); + expect(screen.getByLabelText("비밀번호")).toBeInTheDocument(); + expect(screen.getByRole("menuitem", { name: /AI 채팅/ })).toHaveAttribute( + "aria-disabled", + "true", + ); + expect(screen.queryByLabelText("API Key")).not.toBeInTheDocument(); }); - it("관리자 API Key를 확인하면 감사 로그 탭을 보여준다", async () => { + it("관리자로 로그인하면 운영 상태와 감사 로그 메뉴를 사용할 수 있다", async () => { const user = userEvent.setup(); - const workspaceClient = createWorkspaceClient({ - request_id: "req_1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "admin", - }); + const authClient = createAuthClient( + buildAuthResponse({ role: "admin", employee_id: "1001" }), + ); - render(); + render(); - await user.type(screen.getByLabelText("공통 API Key"), "admin-key"); - await user.click(screen.getByRole("button", { name: /키 확인/ })); + await user.type(screen.getByLabelText("사번"), "1001"); + await user.type(screen.getByLabelText("비밀번호"), "password"); + await user.click(screen.getByRole("button", { name: "로그인" })); - expect(await screen.findByText("Workspace Alpha")).toBeInTheDocument(); + expect(await screen.findByText("Local Workspace")).toBeInTheDocument(); expect(screen.getByText("admin")).toBeInTheDocument(); - await user.click(screen.getByRole("tab", { name: "운영 상태" })); - - expect( - screen.getByRole("heading", { name: "운영 상태" }), - ).toBeInTheDocument(); - await user.click(screen.getByRole("tab", { name: "감사 로그" })); - - expect( - screen.getByRole("heading", { name: "채팅 감사 로그" }), - ).toBeInTheDocument(); - expect( - screen.getByRole("button", { name: /로그 조회/ }), - ).toBeEnabled(); - expect(workspaceClient.requests).toEqual(["admin-key"]); + expect(screen.getByText("1001")).toBeInTheDocument(); + expect(screen.getByRole("menuitem", { name: /운영 상태/ })).not.toHaveAttribute( + "aria-disabled", + "true", + ); + expect(screen.getByRole("menuitem", { name: /감사 로그/ })).not.toHaveAttribute( + "aria-disabled", + "true", + ); + expect(authClient.loginRequests).toEqual([ + { employeeId: "1001", password: "password", displayName: undefined }, + ]); }); - it("일반 사용자 API Key를 확인하면 감사 로그 탭을 숨긴다", async () => { + it("일반 사용자로 로그인하면 관리자 메뉴는 비활성화한다", async () => { const user = userEvent.setup(); - const workspaceClient = createWorkspaceClient({ - request_id: "req_1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "member", - }); - - render(); - - await user.type(screen.getByLabelText("공통 API Key"), "member-key"); - await user.click(screen.getByRole("button", { name: /키 확인/ })); - - expect(await screen.findByText("Workspace Alpha")).toBeInTheDocument(); - expect(screen.getByText("member")).toBeInTheDocument(); - expect(screen.queryByRole("tab", { name: "운영 상태" })).not.toBeInTheDocument(); - expect(screen.queryByRole("tab", { name: "감사 로그" })).not.toBeInTheDocument(); + const authClient = createAuthClient( + buildAuthResponse({ role: "member", employee_id: "1002" }), + ); + + render(); + + await user.type(screen.getByLabelText("사번"), "1002"); + await user.type(screen.getByLabelText("비밀번호"), "password"); + await user.click(screen.getByRole("button", { name: "로그인" })); + + expect(await screen.findByText("member")).toBeInTheDocument(); + expect(screen.getByRole("menuitem", { name: /운영 상태/ })).toHaveAttribute( + "aria-disabled", + "true", + ); + expect(screen.getByRole("menuitem", { name: /감사 로그/ })).toHaveAttribute( + "aria-disabled", + "true", + ); }); - it("감사 로그 탭에서 일반 사용자로 재확인하면 채팅 탭으로 이동한다", async () => { + it("회원가입 화면에서 이름과 사번, 비밀번호를 전송한다", async () => { const user = userEvent.setup(); - const workspaceClient = createSequenceWorkspaceClient([ - { - request_id: "req_1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "admin", - }, - { - request_id: "req_2", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "member", - }, - ]); - - render(); + const authClient = createAuthClient( + buildAuthResponse({ role: "member", employee_id: "2001" }), + ); - const apiKeyInput = screen.getByLabelText("공통 API Key"); - await user.type(apiKeyInput, "admin-key"); - await user.click(screen.getByRole("button", { name: /키 확인/ })); - await user.click(await screen.findByRole("tab", { name: "운영 상태" })); - expect( - screen.getByRole("heading", { name: "운영 상태" }), - ).toBeInTheDocument(); + render(); - await user.clear(apiKeyInput); - await user.type(apiKeyInput, "member-key"); - await user.click(screen.getByRole("button", { name: /키 확인/ })); + await user.click(screen.getByRole("button", { name: /회원가입/ })); + await user.type(screen.getByLabelText("사번"), "2001"); + await user.type(screen.getByLabelText("이름"), "홍길동"); + await user.type(screen.getByLabelText("비밀번호"), "pass1234"); + await user.click(screen.getByRole("button", { name: "회원가입" })); - expect(screen.queryByRole("tab", { name: "운영 상태" })).not.toBeInTheDocument(); - expect(screen.queryByRole("tab", { name: "감사 로그" })).not.toBeInTheDocument(); - expect(screen.getByRole("tabpanel", { name: "채팅" })).toBeInTheDocument(); + expect(await screen.findByText("2001")).toBeInTheDocument(); + expect(authClient.signupRequests).toEqual([ + { employeeId: "2001", password: "pass1234", displayName: "홍길동" }, + ]); }); - it("API Key 확인 실패 메시지를 보여준다", async () => { + it("로그인 실패 메시지를 보여준다", async () => { const user = userEvent.setup(); - const workspaceClient: WorkspaceClient = { - async getWorkspace() { - throw new Error("API key is invalid."); + const authClient: AuthClient = { + async login() { + throw new Error("사번 또는 비밀번호가 올바르지 않습니다."); + }, + async signup() { + throw new Error("not used"); }, }; - render(); - - await user.type(screen.getByLabelText("공통 API Key"), "bad-key"); - await user.click(screen.getByRole("button", { name: /키 확인/ })); - - expect(await screen.findByText("API key is invalid.")).toBeInTheDocument(); - expect(screen.queryByRole("tab", { name: "감사 로그" })).not.toBeInTheDocument(); - }); - - it("문서 탭으로 전환한다", async () => { - const user = userEvent.setup(); - - render(); + render(); - await user.click(screen.getByRole("tab", { name: "문서" })); + await user.type(screen.getByLabelText("사번"), "9999"); + await user.type(screen.getByLabelText("비밀번호"), "wrong"); + await user.click(screen.getByRole("button", { name: "로그인" })); expect( - screen.getByRole("heading", { name: "문서 업로드" }), + await screen.findByText("사번 또는 비밀번호가 올바르지 않습니다."), ).toBeInTheDocument(); - expect( - screen.getByRole("button", { name: /문서 업로드/ }), - ).toBeDisabled(); }); }); -function createWorkspaceClient(context: WorkspaceContext): WorkspaceClient & { - requests: string[]; +function createAuthClient(response: AuthResponse): AuthClient & { + loginRequests: unknown[]; + signupRequests: unknown[]; } { - const requests: string[] = []; + const loginRequests: unknown[] = []; + const signupRequests: unknown[] = []; return { - requests, - async getWorkspace(payload) { - requests.push(payload.apiKey); - return context; + loginRequests, + signupRequests, + async login(payload) { + loginRequests.push(payload); + return response; + }, + async signup(payload) { + signupRequests.push(payload); + return response; }, }; } -function createSequenceWorkspaceClient( - contexts: WorkspaceContext[], -): WorkspaceClient { - let index = 0; +function buildAuthResponse( + overrides: Partial = {}, +): AuthResponse { return { - async getWorkspace() { - const context = contexts[index] ?? contexts[contexts.length - 1]; - index += 1; - return context; + access_token: "auth-token", + token_type: "bearer", + workspace: { + request_id: "req_1", + workspace_id: "local-workspace", + workspace_name: "Local Workspace", + role: "member", + employee_id: "1002", + display_name: "사용자", + ...overrides, }, }; } diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx index 0ae6921..f3788d8 100644 --- a/frontend/src/app/App.tsx +++ b/frontend/src/app/App.tsx @@ -1,163 +1,306 @@ -import { Alert, Button, Input, Layout, Space, Tabs, Tag, Typography } from "antd"; +import { + AuditOutlined, + FileOutlined, + MenuFoldOutlined, + MenuUnfoldOutlined, + MessageOutlined, + SettingOutlined, +} from "@ant-design/icons"; +import { Alert, Button, Card, Input, Layout, Menu, Space, Tag, Typography } from "antd"; import { useMemo, useState } from "react"; -import { ChatWorkspace } from "../features/chat/ChatWorkspace"; import { AuditLogWorkspace } from "../features/audit/AuditLogWorkspace"; +import { ChatWorkspace } from "../features/chat/ChatWorkspace"; import { DocumentWorkspace } from "../features/documents/DocumentWorkspace"; import { OperationsStatusWorkspace } from "../features/operations/OperationsStatusWorkspace"; import { - WorkspaceClient, - WorkspaceContext, - createWorkspaceApiClient, -} from "../lib/workspace-api"; + AuthClient, + AuthWorkspace, + createAuthApiClient, +} from "../lib/auth-api"; -const { Content, Header } = Layout; -const { Paragraph, Title } = Typography; +const { Content, Header, Sider } = Layout; +const { Paragraph, Text, Title } = Typography; interface AppProps { - workspaceClient?: WorkspaceClient; + authClient?: AuthClient; } -export default function App({ workspaceClient }: AppProps) { - const resolvedWorkspaceClient = useMemo( - () => workspaceClient ?? createWorkspaceApiClient(), - [workspaceClient], +type ActiveView = "chat" | "documents" | "operations" | "audit"; +type AuthMode = "login" | "signup"; + +export default function App({ authClient }: AppProps) { + const resolvedAuthClient = useMemo( + () => authClient ?? createAuthApiClient(), + [authClient], + ); + const [authMode, setAuthMode] = useState("login"); + const [employeeId, setEmployeeId] = useState(""); + const [password, setPassword] = useState(""); + const [displayName, setDisplayName] = useState(""); + const [authToken, setAuthToken] = useState(null); + const [workspaceContext, setWorkspaceContext] = useState( + null, ); - const [apiKey, setApiKey] = useState(""); - const [confirmedApiKey, setConfirmedApiKey] = useState(null); - const [workspaceContext, setWorkspaceContext] = - useState(null); - const [workspaceError, setWorkspaceError] = useState(null); - const [isCheckingWorkspace, setIsCheckingWorkspace] = useState(false); - const [activeTab, setActiveTab] = useState("chat"); - - const canCheckWorkspace = apiKey.trim().length > 0 && !isCheckingWorkspace; + const [authError, setAuthError] = useState(null); + const [isAuthenticating, setIsAuthenticating] = useState(false); + const [activeView, setActiveView] = useState("chat"); + const [collapsed, setCollapsed] = useState(false); + + const isAuthenticated = authToken !== null && workspaceContext !== null; const isAdmin = workspaceContext?.role === "admin"; - const sharedApiKey = confirmedApiKey ?? undefined; + const canSubmitAuth = + employeeId.trim().length > 0 && password.length > 0 && !isAuthenticating; - async function checkWorkspace() { - if (!canCheckWorkspace) { + async function submitAuth() { + if (!canSubmitAuth) { return; } - setIsCheckingWorkspace(true); - setWorkspaceError(null); + setIsAuthenticating(true); + setAuthError(null); try { - const nextContext = await resolvedWorkspaceClient.getWorkspace({ - apiKey: apiKey.trim(), - }); - setWorkspaceContext(nextContext); - setConfirmedApiKey(apiKey.trim()); - if ( - nextContext.role !== "admin" && - (activeTab === "audit" || activeTab === "operations") - ) { - setActiveTab("chat"); - } + const payload = { + employeeId: employeeId.trim(), + password, + displayName: displayName.trim() || undefined, + }; + const response = + authMode === "login" + ? await resolvedAuthClient.login(payload) + : await resolvedAuthClient.signup(payload); + setAuthToken(response.access_token); + setWorkspaceContext(response.workspace); + setActiveView("chat"); } catch (error) { + setAuthToken(null); setWorkspaceContext(null); - setConfirmedApiKey(null); - if (activeTab === "audit" || activeTab === "operations") { - setActiveTab("chat"); - } - setWorkspaceError( - error instanceof Error ? error.message : "API Key 확인에 실패했습니다.", + setAuthError( + error instanceof Error ? error.message : "로그인 요청에 실패했습니다.", ); } finally { - setIsCheckingWorkspace(false); + setIsAuthenticating(false); } } - const tabItems = [ + function logout() { + setAuthToken(null); + setWorkspaceContext(null); + setPassword(""); + setActiveView("chat"); + } + + const menuItems = [ { key: "chat", - label: "채팅", - children: , + icon: , + label: "AI 채팅", + disabled: !isAuthenticated, }, { key: "documents", - label: "문서", - children: , + icon: , + label: "문서 관리", + disabled: !isAuthenticated, }, - ]; - - if (isAdmin) { - tabItems.push({ + { key: "operations", + icon: , label: "운영 상태", - children: , - }); - tabItems.push({ + disabled: !isAdmin, + }, + { key: "audit", + icon: , label: "감사 로그", - children: , - }); - } + disabled: !isAdmin, + }, + ]; return ( - - - - DocSearch AI + + + + {collapsed ? "DS" : "DocSearch AI"} + + + setActiveView(key as ActiveView)} + className="app-menu" + /> + + + + + : } + onClick={() => setCollapsed((value) => !value)} + aria-label={collapsed ? "사이드바 펼치기" : "사이드바 접기"} + /> + + {workspaceContext ? ( + + {workspaceContext.workspace_name} + + {workspaceContext.role} + + {workspaceContext.employee_id} + + 로그아웃 + + + ) : ( + 사번으로 로그인하세요 + )} + + + + {!isAuthenticated ? ( + void submitAuth()} + /> + ) : null} + {isAuthenticated && activeView === "chat" ? ( + + ) : null} + {isAuthenticated && activeView === "documents" ? ( + + ) : null} + {isAuthenticated && activeView === "operations" && isAdmin ? ( + + ) : null} + {isAuthenticated && activeView === "audit" && isAdmin ? ( + + ) : null} + + + + ); +} + +interface AuthCardProps { + authMode: AuthMode; + employeeId: string; + password: string; + displayName: string; + errorMessage: string | null; + isSubmitting: boolean; + canSubmit: boolean; + onAuthModeChange(value: AuthMode): void; + onEmployeeIdChange(value: string): void; + onPasswordChange(value: string): void; + onDisplayNameChange(value: string): void; + onSubmit(): void; +} + +function AuthCard({ + authMode, + employeeId, + password, + displayName, + errorMessage, + isSubmitting, + canSubmit, + onAuthModeChange, + onEmployeeIdChange, + onPasswordChange, + onDisplayNameChange, + onSubmit, +}: AuthCardProps) { + const isSignup = authMode === "signup"; + + return ( + + { + event.preventDefault(); + onSubmit(); + }} + > + + + {isSignup ? "회원가입" : "로그인"} - - 온프레미스 RAG 문서 질의응답 + + 사번과 비밀번호로 DocSearch AI에 접속합니다. - - React - FastAPI - vLLM - Qdrant - - - - - { - event.preventDefault(); - void checkWorkspace(); - }} - > - - 공통 API Key + + + 사번 + + onEmployeeIdChange(event.target.value)} + /> + + {isSignup ? ( + <> + + 이름 - setApiKey(event.target.value)} + onDisplayNameChange(event.target.value)} /> - - 키 확인 - - {workspaceContext ? ( - - {workspaceContext.workspace_name} - - {workspaceContext.role} - - - ) : null} - - {workspaceError ? ( - - ) : null} - - + ) : null} + + + 비밀번호 + + onPasswordChange(event.target.value)} /> - - + + {errorMessage ? : null} + + + {isSignup ? "회원가입" : "로그인"} + + onAuthModeChange(isSignup ? "login" : "signup")} + > + {isSignup ? "이미 계정이 있나요? 로그인" : "계정이 없나요? 회원가입"} + + + ); } diff --git a/frontend/src/features/audit/AuditLogWorkspace.test.tsx b/frontend/src/features/audit/AuditLogWorkspace.test.tsx index ddd5761..6652752 100644 --- a/frontend/src/features/audit/AuditLogWorkspace.test.tsx +++ b/frontend/src/features/audit/AuditLogWorkspace.test.tsx @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { AuditLogWorkspace } from "./AuditLogWorkspace"; describe("AuditLogWorkspace", () => { - it("API Key로 채팅 감사 로그를 조회하고 이벤트를 표시한다", async () => { + it("채팅 감사 로그를 조회하고 이벤트를 표시한다", async () => { const user = userEvent.setup(); const client = { exportChatEvents: vi.fn(), @@ -24,9 +24,9 @@ describe("AuditLogWorkspace", () => { retrieval_limit: 5, rerank_top_k: 5, retrieved_chunk_count: 1, - model: "google/gemma-4-E4B-it", - answer_preview: "권한이 허용된 문서 기준으로 답변합니다.", - answer_character_count: 23, + model: "local-model", + answer_preview: "문서 기반 답변입니다.", + answer_character_count: 12, prompt_tokens: 10, completion_tokens: 6, total_tokens: 16, @@ -45,126 +45,68 @@ describe("AuditLogWorkspace", () => { }), }; - render(); + render(); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - const submit = screen.getByRole("button", { name: /로그 조회/ }); - - expect(submit).toBeEnabled(); - await user.click(submit); + await user.click(screen.getByRole("button", { name: /로그 조회/ })); await waitFor(() => { expect(client.listChatEvents).toHaveBeenCalledWith({ - apiKey: "local-dev-key", + authToken: "auth-token", }); }); - expect(await screen.findByText("정책 문서 요약해줘")).toBeInTheDocument(); - expect( - screen.getByText("권한이 허용된 문서 기준으로 답변합니다."), - ).toBeInTheDocument(); expect(screen.getByText("policy.md")).toBeInTheDocument(); - expect(screen.getByText("Workspace Alpha")).toBeInTheDocument(); expect(screen.getByText("tokens 16")).toBeInTheDocument(); }); - it("조회 결과가 비어 있으면 빈 상태를 보여준다", async () => { - const user = userEvent.setup(); - const client = { - exportChatEvents: vi.fn(), - listChatEvents: vi.fn().mockResolvedValue({ total: 0, events: [] }), - }; - - render(); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.click(screen.getByRole("button", { name: /로그 조회/ })); - - expect(await screen.findByText("아직 감사 로그가 없습니다.")).toBeInTheDocument(); - }); - - it("조회 실패 메시지를 보여준다", async () => { - const user = userEvent.setup(); - const client = { - exportChatEvents: vi.fn(), - listChatEvents: vi.fn().mockRejectedValue(new Error("API key is invalid.")), - }; - - render(); - - await user.type(screen.getByLabelText("API Key"), "bad-key"); - await user.click(screen.getByRole("button", { name: /로그 조회/ })); - - expect(await screen.findByText("API key is invalid.")).toBeInTheDocument(); - }); - - it("입력한 조회 필터를 감사 로그 API에 전달한다", async () => { + it("필터와 CSV 내보내기 요청을 전송한다", async () => { const user = userEvent.setup(); + const downloadFile = vi.fn(); const client = { - exportChatEvents: vi.fn(), listChatEvents: vi.fn().mockResolvedValue({ total: 0, events: [] }), + exportChatEvents: vi.fn().mockResolvedValue({ + filename: "chat-audit-logs.csv", + content: "event_id\n1\n", + contentType: "text/csv; charset=utf-8", + }), }; - render(); + render( + , + ); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); await user.type(screen.getByLabelText("검색어"), "정책"); await user.type(screen.getByLabelText("문서 ID"), "doc-1"); - await user.type(screen.getByLabelText("요청 ID"), "request-1"); - await user.type(screen.getByLabelText("시작 시각"), "2026-05-15T09:00"); - await user.type(screen.getByLabelText("종료 시각"), "2026-05-15T10:00"); await user.clear(screen.getByLabelText("조회 개수")); await user.type(screen.getByLabelText("조회 개수"), "20"); - - await user.click(screen.getByRole("button", { name: /로그 조회/ })); + await user.click(screen.getByRole("button", { name: /CSV 내보내기/ })); await waitFor(() => { - expect(client.listChatEvents).toHaveBeenCalledWith({ - apiKey: "local-dev-key", + expect(client.exportChatEvents).toHaveBeenCalledWith({ + authToken: "auth-token", query: "정책", documentId: "doc-1", - requestId: "request-1", - occurredFrom: "2026-05-15T09:00", - occurredTo: "2026-05-15T10:00", limit: 20, }); }); + expect(downloadFile).toHaveBeenCalled(); }); - it("현재 필터로 감사 로그 CSV를 내보낸다", async () => { + it("조회 실패 메시지를 보여준다", async () => { const user = userEvent.setup(); - const downloadFile = vi.fn(); const client = { - listChatEvents: vi.fn().mockResolvedValue({ total: 0, events: [] }), - exportChatEvents: vi.fn().mockResolvedValue({ - filename: "chat-audit-logs-20260515.csv", - content: "이벤트 ID,질문\r\nevent-1,정책 질문\r\n", - contentType: "text/csv; charset=utf-8", - }), + exportChatEvents: vi.fn(), + listChatEvents: vi.fn().mockRejectedValue(new Error("로그 조회 실패")), }; - render(); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.type(screen.getByLabelText("검색어"), "정책"); - await user.type(screen.getByLabelText("문서 ID"), "doc-1"); - await user.clear(screen.getByLabelText("조회 개수")); - await user.type(screen.getByLabelText("조회 개수"), "20"); + render(); - await user.click(screen.getByRole("button", { name: /CSV 내보내기/ })); + await user.click(screen.getByRole("button", { name: /로그 조회/ })); - await waitFor(() => { - expect(client.exportChatEvents).toHaveBeenCalledWith({ - apiKey: "local-dev-key", - query: "정책", - documentId: "doc-1", - limit: 20, - }); - }); - expect(downloadFile).toHaveBeenCalledWith({ - filename: "chat-audit-logs-20260515.csv", - content: "이벤트 ID,질문\r\nevent-1,정책 질문\r\n", - contentType: "text/csv; charset=utf-8", - }); + expect(await screen.findByText("로그 조회 실패")).toBeInTheDocument(); }); }); diff --git a/frontend/src/features/audit/AuditLogWorkspace.tsx b/frontend/src/features/audit/AuditLogWorkspace.tsx index c7192e0..d9c2723 100644 --- a/frontend/src/features/audit/AuditLogWorkspace.tsx +++ b/frontend/src/features/audit/AuditLogWorkspace.tsx @@ -26,19 +26,18 @@ const { Paragraph, Text, Title } = Typography; interface AuditLogWorkspaceProps { client?: AuditLogClient; downloadFile?: (file: AuditLogExportResponse) => void; - apiKey?: string; + authToken: string; } export function AuditLogWorkspace({ client, downloadFile = downloadTextFile, - apiKey: confirmedApiKey, + authToken, }: AuditLogWorkspaceProps) { const auditLogClient = useMemo( () => client ?? createAuditLogApiClient(), [client], ); - const [apiKey, setApiKey] = useState(""); const [response, setResponse] = useState( null, ); @@ -53,8 +52,7 @@ export function AuditLogWorkspace({ const [occurredTo, setOccurredTo] = useState(""); const [limit, setLimit] = useState(100); - const resolvedApiKey = confirmedApiKey ?? apiKey.trim(); - const hasApiKey = resolvedApiKey.length > 0; + const hasApiKey = authToken.length > 0; const canSubmit = hasApiKey && !isLoading; const canExport = hasApiKey && !isExporting; @@ -107,7 +105,7 @@ export function AuditLogWorkspace({ function buildAuditLogRequest() { return { - apiKey: resolvedApiKey, + authToken, query: normalizeOptionalText(query), documentId: normalizeOptionalText(documentId), requestId: normalizeOptionalText(requestId), @@ -129,20 +127,6 @@ export function AuditLogWorkspace({ void loadAuditLogs(); }} > - {confirmedApiKey ? null : ( - <> - - API Key - - setApiKey(event.target.value)} - /> - > - )} - 검색어 diff --git a/frontend/src/features/chat/ChatWorkspace.test.tsx b/frontend/src/features/chat/ChatWorkspace.test.tsx index 5a54437..e0be71c 100644 --- a/frontend/src/features/chat/ChatWorkspace.test.tsx +++ b/frontend/src/features/chat/ChatWorkspace.test.tsx @@ -16,6 +16,7 @@ describe("ChatWorkspace", () => { citation_id: 1, document_id: "doc-1", filename: "policy.md", + security_level: "internal", chunk_index: 0, score: 0.88, rerank_score: 0.94, @@ -31,9 +32,8 @@ describe("ChatWorkspace", () => { }), }; - render(); + render(); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); await user.type(screen.getByLabelText("문서 ID"), "doc-1, doc-2"); await user.type(screen.getByLabelText("질문"), "정책 문서 요약해줘"); @@ -44,9 +44,10 @@ describe("ChatWorkspace", () => { await waitFor(() => { expect(client.ask).toHaveBeenCalledWith({ - apiKey: "local-dev-key", + authToken: "auth-token", question: "정책 문서 요약해줘", documentIds: ["doc-1", "doc-2"], + securityLevels: [], topK: 5, }); }); diff --git a/frontend/src/features/chat/ChatWorkspace.tsx b/frontend/src/features/chat/ChatWorkspace.tsx index 9321f83..9b5404a 100644 --- a/frontend/src/features/chat/ChatWorkspace.tsx +++ b/frontend/src/features/chat/ChatWorkspace.tsx @@ -7,6 +7,7 @@ import { Input, InputNumber, List, + Select, Space, Tag, Typography, @@ -18,28 +19,30 @@ import { ChatResponse, createChatApiClient, } from "../../lib/chat-api"; +import { DocumentSecurityLevel } from "../../lib/document-api"; const { TextArea } = Input; const { Paragraph, Text, Title } = Typography; interface ChatWorkspaceProps { client?: ChatClient; - apiKey?: string; + authToken: string; } -export function ChatWorkspace({ client, apiKey: confirmedApiKey }: ChatWorkspaceProps) { +export function ChatWorkspace({ client, authToken }: ChatWorkspaceProps) { const chatClient = useMemo(() => client ?? createChatApiClient(), [client]); - const [apiKey, setApiKey] = useState(""); const [documentIds, setDocumentIds] = useState(""); + const [securityLevels, setSecurityLevels] = useState( + [], + ); const [topK, setTopK] = useState(5); const [question, setQuestion] = useState(""); const [response, setResponse] = useState(null); const [errorMessage, setErrorMessage] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); - const resolvedApiKey = confirmedApiKey ?? apiKey.trim(); const canSubmit = - resolvedApiKey.length > 0 && question.trim().length > 0 && !isSubmitting; + authToken.length > 0 && question.trim().length > 0 && !isSubmitting; async function submitQuestion() { if (!canSubmit) { @@ -51,9 +54,10 @@ export function ChatWorkspace({ client, apiKey: confirmedApiKey }: ChatWorkspace try { const nextResponse = await chatClient.ask({ - apiKey: resolvedApiKey, + authToken, question: question.trim(), documentIds: parseDocumentIds(documentIds), + securityLevels, topK, }); setResponse(nextResponse); @@ -71,20 +75,6 @@ export function ChatWorkspace({ client, apiKey: confirmedApiKey }: ChatWorkspace event.preventDefault()}> - {confirmedApiKey ? null : ( - <> - - API Key - - setApiKey(event.target.value)} - /> - > - )} - 문서 ID @@ -94,6 +84,25 @@ export function ChatWorkspace({ client, apiKey: confirmedApiKey }: ChatWorkspace onChange={(event) => setDocumentIds(event.target.value)} /> + + 보안 등급 + + + setSecurityLevels(nextLevels as DocumentSecurityLevel[]) + } + placeholder="전체 등급 검색" + options={[ + { value: "general", label: "일반" }, + { value: "internal", label: "사내" }, + { value: "confidential", label: "대외비" }, + { value: "restricted", label: "기밀" }, + ]} + /> + 검색 개수 @@ -170,6 +179,9 @@ function AnswerResult({ response }: { response: ChatResponse }) { {citation.citation_id} {citation.filename} + + {formatSecurityLevel(citation.security_level)} + score {citation.score.toFixed(2)} {citation.rerank_score ? ( @@ -193,3 +205,16 @@ function parseDocumentIds(value: string): string[] { .map((documentId) => documentId.trim()) .filter(Boolean); } + +function formatSecurityLevel(value?: DocumentSecurityLevel): string { + if (value === "general") { + return "일반"; + } + if (value === "confidential") { + return "대외비"; + } + if (value === "restricted") { + return "기밀"; + } + return "사내"; +} diff --git a/frontend/src/features/documents/DocumentWorkspace.test.tsx b/frontend/src/features/documents/DocumentWorkspace.test.tsx index a293552..9882844 100644 --- a/frontend/src/features/documents/DocumentWorkspace.test.tsx +++ b/frontend/src/features/documents/DocumentWorkspace.test.tsx @@ -5,104 +5,42 @@ import { describe, expect, it, vi } from "vitest"; import { DocumentWorkspace } from "./DocumentWorkspace"; describe("DocumentWorkspace", () => { - it("문서를 업로드하고 인덱싱 결과를 표시한다", async () => { + it("문서를 업로드하고 선택한 권한을 함께 전송한다", async () => { const user = userEvent.setup(); const documentClient = { - uploadDocument: vi.fn().mockResolvedValue({ - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "completed", - chunk_count: 1, - }), + uploadDocument: vi.fn().mockResolvedValue(buildDocumentRecord()), listDocuments: vi.fn(), deleteDocument: vi.fn(), reindexDocument: vi.fn(), }; - const searchClient = { - searchDocuments: vi.fn(), - }; + const searchClient = { searchDocuments: vi.fn() }; const file = new File(["hello docsearch"], "memo.txt", { type: "text/plain", }); render( , ); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); await user.upload(screen.getByLabelText("문서 파일"), file); - - const submit = screen.getByRole("button", { name: /문서 업로드/ }); - expect(submit).toBeEnabled(); - await user.click(submit); + await user.click(screen.getByRole("button", { name: /문서 업로드/ })); await waitFor(() => { expect(documentClient.uploadDocument).toHaveBeenCalledWith({ - apiKey: "local-dev-key", + authToken: "auth-token", file, + securityLevel: "internal", }); }); expect(await screen.findByText("memo.txt")).toBeInTheDocument(); - expect(screen.getByText("doc-1")).toBeInTheDocument(); - expect(screen.getByText("completed")).toBeInTheDocument(); - expect(screen.getByText("chunks 1")).toBeInTheDocument(); - expect(screen.getByText("hello docsearch")).toBeInTheDocument(); - }); - - it("업로드 결과의 인덱싱 실패 사유를 표시한다", async () => { - const user = userEvent.setup(); - const documentClient = { - uploadDocument: vi.fn().mockResolvedValue({ - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "failed", - indexing_error: "parser failed", - chunk_count: 0, - }), - listDocuments: vi.fn(), - deleteDocument: vi.fn(), - reindexDocument: vi.fn(), - }; - const searchClient = { - searchDocuments: vi.fn(), - }; - const file = new File(["hello docsearch"], "memo.txt", { - type: "text/plain", - }); - - render( - , - ); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.upload(screen.getByLabelText("문서 파일"), file); - await user.click(screen.getByRole("button", { name: /문서 업로드/ })); - - expect(await screen.findByText("failed")).toBeInTheDocument(); - expect(screen.getByText("parser failed")).toBeInTheDocument(); + expect(screen.getAllByText("사내")).toHaveLength(2); }); - it("문서 검색 결과를 표시한다", async () => { + it("문서 검색 요청에 토큰과 검색 조건을 전송한다", async () => { const user = userEvent.setup(); const documentClient = { uploadDocument: vi.fn(), @@ -112,13 +50,14 @@ describe("DocumentWorkspace", () => { }; const searchClient = { searchDocuments: vi.fn().mockResolvedValue({ - query: "권한 정책", + query: "권한", total: 1, results: [ { document_id: "doc-1", filename: "policy.md", parser: "markdown", + security_level: "internal", chunk_index: 2, score: 0.87, snippet: "권한 정책 문서 일부", @@ -129,139 +68,35 @@ describe("DocumentWorkspace", () => { render( , ); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.type(screen.getByLabelText("검색어"), "권한 정책"); + await user.type(screen.getByLabelText("검색어"), "권한"); await user.type(screen.getByLabelText("검색 문서 ID"), "doc-1"); - - const submit = screen.getByRole("button", { name: /문서 검색/ }); - expect(submit).toBeEnabled(); - await user.click(submit); + await user.click(screen.getByRole("button", { name: /문서 검색/ })); await waitFor(() => { expect(searchClient.searchDocuments).toHaveBeenCalledWith({ - apiKey: "local-dev-key", - query: "권한 정책", + authToken: "auth-token", + query: "권한", documentIds: ["doc-1"], + securityLevels: [], limit: 5, }); }); expect(await screen.findByText("policy.md")).toBeInTheDocument(); - expect(screen.getByText("권한 정책 문서 일부")).toBeInTheDocument(); - expect(screen.getByText("score 0.87")).toBeInTheDocument(); }); - it("검색 결과가 비어 있으면 빈 상태를 보여준다", async () => { - const user = userEvent.setup(); - const documentClient = { - uploadDocument: vi.fn(), - listDocuments: vi.fn(), - deleteDocument: vi.fn(), - reindexDocument: vi.fn(), - }; - const searchClient = { - searchDocuments: vi.fn().mockResolvedValue({ - query: "없는 문서", - total: 0, - results: [], - }), - }; - - render( - , - ); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.type(screen.getByLabelText("검색어"), "없는 문서"); - await user.click(screen.getByRole("button", { name: /문서 검색/ })); - - expect(await screen.findByText("검색 결과가 없습니다.")).toBeInTheDocument(); - }); - - it("업로드된 문서 목록을 조회하고 표시한다", async () => { + it("문서 목록 조회와 삭제 요청을 처리한다", async () => { const user = userEvent.setup(); const documentClient = { uploadDocument: vi.fn(), listDocuments: vi.fn().mockResolvedValue({ total: 1, - documents: [ - { - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "completed", - chunk_count: 1, - uploaded_at: "2026-05-15T09:00:00Z", - }, - ], - }), - deleteDocument: vi.fn(), - reindexDocument: vi.fn(), - }; - const searchClient = { - searchDocuments: vi.fn(), - }; - - render( - , - ); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - - const submit = screen.getByRole("button", { name: /문서 목록 조회/ }); - expect(submit).toBeEnabled(); - await user.click(submit); - - await waitFor(() => { - expect(documentClient.listDocuments).toHaveBeenCalledWith({ - apiKey: "local-dev-key", - }); - }); - expect(await screen.findByText("memo.txt")).toBeInTheDocument(); - expect(screen.getByText("doc-1")).toBeInTheDocument(); - expect(screen.getByText("completed")).toBeInTheDocument(); - expect(screen.getByText("chunks 1")).toBeInTheDocument(); - expect(screen.getByText("hello docsearch")).toBeInTheDocument(); - }); - - it("문서 목록에서 문서를 삭제하고 목록에서 제거한다", async () => { - const user = userEvent.setup(); - const documentClient = { - uploadDocument: vi.fn(), - listDocuments: vi.fn().mockResolvedValue({ - total: 1, - documents: [ - { - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "completed", - chunk_count: 1, - uploaded_at: "2026-05-15T09:00:00Z", - }, - ], + documents: [buildDocumentRecord()], }), deleteDocument: vi.fn().mockResolvedValue({ document_id: "doc-1", @@ -270,18 +105,16 @@ describe("DocumentWorkspace", () => { }), reindexDocument: vi.fn(), }; - const searchClient = { - searchDocuments: vi.fn(), - }; + const searchClient = { searchDocuments: vi.fn() }; render( , ); - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); await user.click(screen.getByRole("button", { name: /문서 목록 조회/ })); expect(await screen.findByText("memo.txt")).toBeInTheDocument(); @@ -289,76 +122,28 @@ describe("DocumentWorkspace", () => { await waitFor(() => { expect(documentClient.deleteDocument).toHaveBeenCalledWith({ - apiKey: "local-dev-key", + authToken: "auth-token", documentId: "doc-1", }); }); - expect(screen.queryByText("memo.txt")).not.toBeInTheDocument(); - expect(screen.getByText("업로드된 문서가 없습니다.")).toBeInTheDocument(); - }); - - it("문서 목록에서 문서를 재인덱싱하고 갱신된 상태를 표시한다", async () => { - const user = userEvent.setup(); - const documentClient = { - uploadDocument: vi.fn(), - listDocuments: vi.fn().mockResolvedValue({ - total: 1, - documents: [ - { - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "completed", - chunk_count: 1, - uploaded_at: "2026-05-15T09:00:00Z", - }, - ], - }), - deleteDocument: vi.fn(), - reindexDocument: vi.fn().mockResolvedValue({ - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-2", - indexing_status: "completed", - chunk_count: 2, - uploaded_at: "2026-05-15T09:00:00Z", - }), - }; - const searchClient = { - searchDocuments: vi.fn(), - }; - - render( - , - ); - - await user.type(screen.getByLabelText("API Key"), "local-dev-key"); - await user.click(screen.getByRole("button", { name: /문서 목록 조회/ })); - expect(await screen.findByText("chunks 1")).toBeInTheDocument(); - - await user.click(screen.getByRole("button", { name: /재인덱싱/ })); - - await waitFor(() => { - expect(documentClient.reindexDocument).toHaveBeenCalledWith({ - apiKey: "local-dev-key", - documentId: "doc-1", - }); - }); - expect(await screen.findByText("chunks 2")).toBeInTheDocument(); }); }); + +function buildDocumentRecord() { + return { + document_id: "doc-1", + workspace_id: "workspace-alpha", + workspace_name: "Workspace Alpha", + uploaded_by_employee_id: "1002", + security_level: "internal" as const, + filename: "memo.txt", + parser: "text", + character_count: 15, + text_preview: "hello docsearch", + storage_key: "workspace-alpha/doc-1/memo.txt", + indexing_job_id: "job-1", + indexing_status: "completed", + chunk_count: 1, + uploaded_at: "2026-05-15T09:00:00Z", + }; +} diff --git a/frontend/src/features/documents/DocumentWorkspace.tsx b/frontend/src/features/documents/DocumentWorkspace.tsx index b5d4fee..452fb2b 100644 --- a/frontend/src/features/documents/DocumentWorkspace.tsx +++ b/frontend/src/features/documents/DocumentWorkspace.tsx @@ -13,6 +13,7 @@ import { Input, InputNumber, List, + Select, Space, Tag, Typography, @@ -23,6 +24,7 @@ import { DocumentClient, DocumentListResponse, DocumentRecord, + DocumentSecurityLevel, DocumentUploadResponse, createDocumentApiClient, } from "../../lib/document-api"; @@ -38,13 +40,13 @@ const { Paragraph, Text, Title } = Typography; interface DocumentWorkspaceProps { documentClient?: DocumentClient; searchClient?: SearchClient; - apiKey?: string; + authToken: string; } export function DocumentWorkspace({ documentClient, searchClient, - apiKey: confirmedApiKey, + authToken, }: DocumentWorkspaceProps) { const resolvedDocumentClient = useMemo( () => documentClient ?? createDocumentApiClient(), @@ -54,14 +56,18 @@ export function DocumentWorkspace({ () => searchClient ?? createSearchApiClient(), [searchClient], ); - const [apiKey, setApiKey] = useState(""); const [file, setFile] = useState(null); + const [securityLevel, setSecurityLevel] = + useState("internal"); const [uploadResult, setUploadResult] = useState(null); const [uploadError, setUploadError] = useState(null); const [isUploading, setIsUploading] = useState(false); const [query, setQuery] = useState(""); const [documentIds, setDocumentIds] = useState(""); + const [searchSecurityLevels, setSearchSecurityLevels] = useState< + DocumentSecurityLevel[] + >([]); const [limit, setLimit] = useState(5); const [searchResult, setSearchResult] = useState(null); const [searchError, setSearchError] = useState(null); @@ -78,11 +84,10 @@ export function DocumentWorkspace({ null, ); - const trimmedApiKey = confirmedApiKey ?? apiKey.trim(); - const canUpload = trimmedApiKey.length > 0 && file !== null && !isUploading; + const canUpload = authToken.length > 0 && file !== null && !isUploading; const canSearch = - trimmedApiKey.length > 0 && query.trim().length > 0 && !isSearching; - const canList = trimmedApiKey.length > 0 && !isListing; + authToken.length > 0 && query.trim().length > 0 && !isSearching; + const canList = authToken.length > 0 && !isListing; async function uploadDocument() { if (!canUpload || file === null) { @@ -94,8 +99,9 @@ export function DocumentWorkspace({ try { const nextResult = await resolvedDocumentClient.uploadDocument({ - apiKey: trimmedApiKey, + authToken, file, + securityLevel, }); setUploadResult(nextResult); setDocumentIds((current) => current || nextResult.document_id); @@ -119,9 +125,10 @@ export function DocumentWorkspace({ try { const nextResult = await resolvedSearchClient.searchDocuments({ - apiKey: trimmedApiKey, + authToken, query: query.trim(), documentIds: parseDocumentIds(documentIds), + securityLevels: searchSecurityLevels, limit, }); setSearchResult(nextResult); @@ -145,7 +152,7 @@ export function DocumentWorkspace({ try { const nextList = await resolvedDocumentClient.listDocuments({ - apiKey: trimmedApiKey, + authToken, }); setDocumentList(nextList); setActionError(null); @@ -160,7 +167,7 @@ export function DocumentWorkspace({ } async function deleteDocument(record: DocumentRecord) { - if (!trimmedApiKey) { + if (!authToken) { return; } @@ -169,7 +176,7 @@ export function DocumentWorkspace({ try { await resolvedDocumentClient.deleteDocument({ - apiKey: trimmedApiKey, + authToken, documentId: record.document_id, }); setDocumentList((current) => removeDocument(current, record.document_id)); @@ -184,7 +191,7 @@ export function DocumentWorkspace({ } async function reindexDocument(record: DocumentRecord) { - if (!trimmedApiKey) { + if (!authToken) { return; } @@ -193,7 +200,7 @@ export function DocumentWorkspace({ try { const updatedRecord = await resolvedDocumentClient.reindexDocument({ - apiKey: trimmedApiKey, + authToken, documentId: record.document_id, }); setDocumentList((current) => upsertDocument(current, updatedRecord)); @@ -219,20 +226,6 @@ export function DocumentWorkspace({ 문서 업로드 - {confirmedApiKey ? null : ( - <> - - API Key - - setApiKey(event.target.value)} - /> - > - )} - 문서 파일 @@ -242,6 +235,21 @@ export function DocumentWorkspace({ onChange={(event) => setFile(event.target.files?.[0] ?? null)} /> + + 보안 등급 + + + setDocumentIds(event.target.value)} /> + + 보안 등급 필터 + + + setSearchSecurityLevels(nextLevels as DocumentSecurityLevel[]) + } + placeholder="전체 등급 검색" + options={[ + { value: "general", label: "일반" }, + { value: "internal", label: "사내" }, + { value: "confidential", label: "대외비" }, + { value: "restricted", label: "기밀" }, + ]} + /> + 검색 개수 @@ -377,6 +404,7 @@ function UploadResult({ result }: { result: DocumentUploadResponse }) { {result.indexing_status} + {formatSecurityLevel(result.security_level)} chunks {result.chunk_count} {result.parser} @@ -450,6 +478,7 @@ function DocumentListItem({ {record.filename} {record.indexing_status} + {formatSecurityLevel(record.security_level)} chunks {record.chunk_count} {record.parser} {formatUploadedAt(record.uploaded_at)} @@ -509,6 +538,7 @@ function SearchResultItem({ chunk }: { chunk: SearchResultChunk }) { {chunk.filename} {chunk.document_id} {chunk.parser} + {formatSecurityLevel(chunk.security_level)} chunk {chunk.chunk_index} score {chunk.score.toFixed(2)} @@ -531,6 +561,19 @@ function formatUploadedAt(value: string): string { }); } +function formatSecurityLevel(value?: DocumentSecurityLevel): string { + if (value === "general") { + return "일반"; + } + if (value === "confidential") { + return "대외비"; + } + if (value === "restricted") { + return "기밀"; + } + return "사내"; +} + function parseDocumentIds(value: string): string[] { return value .split(",") diff --git a/frontend/src/features/operations/OperationsStatusWorkspace.test.tsx b/frontend/src/features/operations/OperationsStatusWorkspace.test.tsx index a059fec..4ed6428 100644 --- a/frontend/src/features/operations/OperationsStatusWorkspace.test.tsx +++ b/frontend/src/features/operations/OperationsStatusWorkspace.test.tsx @@ -2,8 +2,8 @@ import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; -import { OperationsStatusWorkspace } from "./OperationsStatusWorkspace"; import type { OperationsStatusResponse } from "../../lib/operations-api"; +import { OperationsStatusWorkspace } from "./OperationsStatusWorkspace"; describe("OperationsStatusWorkspace", () => { it("운영 상태를 조회하고 요약 정보를 표시한다", async () => { @@ -12,85 +12,18 @@ describe("OperationsStatusWorkspace", () => { getOperationsStatus: vi.fn().mockResolvedValue(buildOperationsResponse()), }; - render(); + render(); - await user.type(screen.getByLabelText("API Key"), "admin-key"); await user.click(screen.getByRole("button", { name: /상태 새로고침/ })); await waitFor(() => { expect(client.getOperationsStatus).toHaveBeenCalledWith({ - apiKey: "admin-key", + authToken: "auth-token", }); }); - expect(await screen.findAllByText("ready")).toHaveLength(3); - expect(screen.getByText("Workspace Alpha")).toBeInTheDocument(); - expect(screen.getByText("development")).toBeInTheDocument(); + expect(await screen.findByText("Workspace Alpha")).toBeInTheDocument(); expect(screen.getByText("rate limit 120/60s")).toBeInTheDocument(); - expect(screen.getByText("rate backend redis")).toBeInTheDocument(); - expect(screen.getByText("fail-open on")).toBeInTheDocument(); - expect(screen.getByText("retrieval hybrid")).toBeInTheDocument(); - expect(screen.getByText("hybrid 0.7/0.3")).toBeInTheDocument(); expect(screen.getByText("indexing queue ready")).toBeInTheDocument(); - expect(screen.getByText("pending 3")).toBeInTheDocument(); - expect(screen.getByText("max attempts 5")).toBeInTheDocument(); - expect(screen.getByText("docsearch:indexing:queue")).toBeInTheDocument(); - expect(screen.getByText("qdrant")).toBeInTheDocument(); - expect(screen.getByText("Qdrant 연결이 정상입니다.")).toBeInTheDocument(); - expect(screen.getByText("기록된 운영 이벤트가 없습니다.")).toBeInTheDocument(); - expect(screen.getByText("google/gemma-4-E4B-it")).toBeInTheDocument(); - expect(screen.getByText("embedding backend deterministic")).toBeInTheDocument(); - expect(screen.getByText("BAAI/bge-m3")).toBeInTheDocument(); - expect( - screen.getByText("Redis 인덱싱 큐 대기건수 조회에 성공했습니다."), - ).toBeInTheDocument(); - }); - - it("운영 이벤트를 표시한다", async () => { - const user = userEvent.setup(); - const client = { - getOperationsStatus: vi.fn().mockResolvedValue( - buildOperationsResponse({ - events: [ - { - event_id: "event-1", - event_type: "dependency.health_failed", - severity: "error" as const, - source: "qdrant", - message: "Qdrant 연결에 실패했습니다.", - occurred_at: "2026-05-16T00:00:00Z", - details: { check: "qdrant" }, - }, - ], - }), - ), - }; - - render(); - - await user.type(screen.getByLabelText("API Key"), "admin-key"); - await user.click(screen.getByRole("button", { name: /상태 새로고침/ })); - - expect(await screen.findByText("운영 이벤트")).toBeInTheDocument(); - expect(screen.getByText("dependency.health_failed")).toBeInTheDocument(); - expect(screen.getByText("Qdrant 연결에 실패했습니다.")).toBeInTheDocument(); - }); - - it("공통 API Key를 받으면 내부 API Key 입력을 숨기고 그대로 사용한다", async () => { - const user = userEvent.setup(); - const client = { - getOperationsStatus: vi.fn().mockResolvedValue(buildOperationsResponse()), - }; - - render(); - - expect(screen.queryByLabelText("API Key")).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: /상태 새로고침/ })); - - await waitFor(() => { - expect(client.getOperationsStatus).toHaveBeenCalledWith({ - apiKey: "admin-key", - }); - }); }); it("조회 실패 메시지를 보여준다", async () => { @@ -101,54 +34,31 @@ describe("OperationsStatusWorkspace", () => { .mockRejectedValue(new Error("Admin role is required.")), }; - render(); + render(); - await user.type(screen.getByLabelText("API Key"), "member-key"); await user.click(screen.getByRole("button", { name: /상태 새로고침/ })); expect(await screen.findByText("Admin role is required.")).toBeInTheDocument(); }); }); -function buildOperationsResponse( - overrides: Partial = {}, -): OperationsStatusResponse { - return { - ...buildBaseOperationsResponse(), - ...overrides, - }; -} - -function buildBaseOperationsResponse(): OperationsStatusResponse { +function buildOperationsResponse(): OperationsStatusResponse { return { - status: "ready" as const, + status: "ready", service: "docsearch-ai", workspace: { workspace_id: "workspace-alpha", workspace_name: "Workspace Alpha", - role: "admin" as const, + role: "admin", }, checks: [ - { - name: "configuration", - status: "ready" as const, - message: "운영 설정 기준을 통과했습니다.", - }, { name: "qdrant", - status: "ready" as const, + status: "ready", message: "Qdrant 연결이 정상입니다.", }, ], events: [], - indexing_queue: { - backend: "redis", - status: "ready" as const, - queue_key: "docsearch:indexing:queue", - pending_jobs: 3, - max_attempts: 5, - message: "Redis 인덱싱 큐 대기건수 조회에 성공했습니다.", - }, settings: { environment: "development", debug: false, @@ -160,20 +70,20 @@ function buildBaseOperationsResponse(): OperationsStatusResponse { hybrid_candidate_limit: 50, rate_limit: { enabled: true, + backend: "redis", requests: 120, window_seconds: 60, - backend: "redis", fail_open: true, }, backends: { audit_log: "postgres", document_metadata: "postgres", - indexing_queue: "inprocess", + indexing_queue: "redis", embedding: "deterministic", reranker: "score", }, models: { - llm: "google/gemma-4-E4B-it", + llm: "local-model", llm_timeout_seconds: 30, llm_max_tokens: 1024, llm_temperature: 0.2, @@ -184,5 +94,13 @@ function buildBaseOperationsResponse(): OperationsStatusResponse { embedding_vector_size: 8, }, }, + indexing_queue: { + backend: "redis", + status: "ready", + queue_key: "docsearch:indexing:queue", + pending_jobs: 3, + max_attempts: 5, + message: "Redis 인덱싱 큐 대기건수 조회에 성공했습니다.", + }, }; } diff --git a/frontend/src/features/operations/OperationsStatusWorkspace.tsx b/frontend/src/features/operations/OperationsStatusWorkspace.tsx index 0c6e0c5..c13c892 100644 --- a/frontend/src/features/operations/OperationsStatusWorkspace.tsx +++ b/frontend/src/features/operations/OperationsStatusWorkspace.tsx @@ -1,5 +1,5 @@ import { ReloadOutlined } from "@ant-design/icons"; -import { Alert, Button, Card, Empty, Input, List, Space, Tag, Typography } from "antd"; +import { Alert, Button, Card, Empty, List, Space, Tag, Typography } from "antd"; import { useMemo, useState } from "react"; import { @@ -14,26 +14,24 @@ const { Paragraph, Text, Title } = Typography; interface OperationsStatusWorkspaceProps { client?: OperationsClient; - apiKey?: string; + authToken: string; } export function OperationsStatusWorkspace({ client, - apiKey: confirmedApiKey, + authToken, }: OperationsStatusWorkspaceProps) { const operationsClient = useMemo( () => client ?? createOperationsApiClient(), [client], ); - const [apiKey, setApiKey] = useState(""); const [response, setResponse] = useState( null, ); const [errorMessage, setErrorMessage] = useState(null); const [isLoading, setIsLoading] = useState(false); - const resolvedApiKey = confirmedApiKey ?? apiKey.trim(); - const canSubmit = resolvedApiKey.length > 0 && !isLoading; + const canSubmit = authToken.length > 0 && !isLoading; async function loadOperationsStatus() { if (!canSubmit) { @@ -45,7 +43,7 @@ export function OperationsStatusWorkspace({ try { const nextResponse = await operationsClient.getOperationsStatus({ - apiKey: resolvedApiKey, + authToken, }); setResponse(nextResponse); } catch (error) { @@ -68,20 +66,6 @@ export function OperationsStatusWorkspace({ void loadOperationsStatus(); }} > - {confirmedApiKey ? null : ( - <> - - API Key - - setApiKey(event.target.value)} - /> - > - )} - { - it("채팅 감사 로그 API에 API Key를 전송한다", async () => { + it("감사 로그 조회에 Bearer 토큰과 필터를 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response(JSON.stringify({ total: 0, events: [] }), { + new Response(JSON.stringify({ events: [], total: 0 }), { status: 200, headers: { "Content-Type": "application/json" }, }), @@ -15,83 +15,31 @@ describe("createAuditLogApiClient", () => { fetcher, }); - const response = await client.listChatEvents({ - apiKey: "local-dev-key", - }); - - expect(fetcher).toHaveBeenCalledWith("http://api.local/v1/audit-logs/chat", { - method: "GET", - headers: { - "X-API-Key": "local-dev-key", - }, - }); - expect(response.total).toBe(0); - }); - - it("API 오류 메시지를 사용자에게 전달할 수 있는 오류로 변환한다", async () => { - const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - detail: { - code: "AUTH_INVALID_API_KEY", - message: "API key is invalid.", - }, - }), - { status: 401, headers: { "Content-Type": "application/json" } }, - ), - ); - const client = createAuditLogApiClient({ - baseUrl: "", - fetcher, - }); - - await expect( - client.listChatEvents({ apiKey: "bad-key" }), - ).rejects.toThrow("API key is invalid."); - }); - - it("선택한 감사 로그 필터를 쿼리 문자열로 전송한다", async () => { - const fetcher = vi.fn().mockResolvedValue( - new Response(JSON.stringify({ total: 0, events: [] }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }), - ); - const client = createAuditLogApiClient({ - baseUrl: "http://api.local/", - fetcher, - }); - await client.listChatEvents({ - apiKey: "local-dev-key", + authToken: "auth-token", query: "정책", documentId: "doc-1", - requestId: "request-1", - occurredFrom: "2026-05-15T09:00", - occurredTo: "2026-05-15T10:00", + requestId: "req-1", limit: 20, }); const requestedUrl = new URL(fetcher.mock.calls[0][0]); - expect(requestedUrl.origin + requestedUrl.pathname).toBe( - "http://api.local/v1/audit-logs/chat", - ); + expect(requestedUrl.pathname).toBe("/v1/audit-logs/chat"); expect(requestedUrl.searchParams.get("query")).toBe("정책"); expect(requestedUrl.searchParams.get("document_id")).toBe("doc-1"); - expect(requestedUrl.searchParams.get("request_id")).toBe("request-1"); - expect(requestedUrl.searchParams.get("from")).toBe("2026-05-15T09:00"); - expect(requestedUrl.searchParams.get("to")).toBe("2026-05-15T10:00"); - expect(requestedUrl.searchParams.get("limit")).toBe("20"); + expect(fetcher.mock.calls[0][1]).toEqual({ + method: "GET", + headers: { Authorization: "Bearer auth-token" }, + }); }); - it("채팅 감사 로그 CSV 내보내기 API를 호출하고 파일 정보를 반환한다", async () => { + it("감사 로그 CSV 내보내기 결과를 파일 정보로 반환한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response("이벤트 ID,질문\r\nevent-1,정책 질문\r\n", { + new Response("event_id\n1\n", { status: 200, headers: { "Content-Type": "text/csv; charset=utf-8", - "Content-Disposition": - 'attachment; filename="chat-audit-logs-20260515.csv"', + "Content-Disposition": 'attachment; filename="chat.csv"', }, }), ); @@ -100,29 +48,18 @@ describe("createAuditLogApiClient", () => { fetcher, }); - const response = await client.exportChatEvents({ - apiKey: "local-dev-key", - query: "정책", + const file = await client.exportChatEvents({ + authToken: "auth-token", documentId: "doc-1", - limit: 20, }); - const requestedUrl = new URL(fetcher.mock.calls[0][0]); - expect(requestedUrl.origin + requestedUrl.pathname).toBe( - "http://api.local/v1/audit-logs/chat/export", - ); - expect(requestedUrl.searchParams.get("query")).toBe("정책"); - expect(requestedUrl.searchParams.get("document_id")).toBe("doc-1"); - expect(requestedUrl.searchParams.get("limit")).toBe("20"); expect(fetcher.mock.calls[0][1]).toEqual({ method: "GET", - headers: { - "X-API-Key": "local-dev-key", - }, + headers: { Authorization: "Bearer auth-token" }, }); - expect(response).toEqual({ - filename: "chat-audit-logs-20260515.csv", - content: "이벤트 ID,질문\r\nevent-1,정책 질문\r\n", + expect(file).toEqual({ + filename: "chat.csv", + content: "event_id\n1\n", contentType: "text/csv; charset=utf-8", }); }); diff --git a/frontend/src/lib/audit-log-api.ts b/frontend/src/lib/audit-log-api.ts index 8a73c19..7698994 100644 --- a/frontend/src/lib/audit-log-api.ts +++ b/frontend/src/lib/audit-log-api.ts @@ -1,5 +1,7 @@ +import { buildAuthHeaders } from "./auth-api"; + export interface AuditLogRequest { - apiKey: string; + authToken: string; query?: string; documentId?: string; requestId?: string; @@ -86,9 +88,7 @@ export function createAuditLogApiClient( `${baseUrl}/v1/audit-logs/chat${buildQueryString(payload)}`, { method: "GET", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }, ); @@ -105,9 +105,7 @@ export function createAuditLogApiClient( `${baseUrl}/v1/audit-logs/chat/export${buildQueryString(payload)}`, { method: "GET", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }, ); diff --git a/frontend/src/lib/auth-api.ts b/frontend/src/lib/auth-api.ts new file mode 100644 index 0000000..d888607 --- /dev/null +++ b/frontend/src/lib/auth-api.ts @@ -0,0 +1,117 @@ +export type WorkspaceRole = "member" | "admin"; + +export interface AuthRequest { + employeeId: string; + password: string; + displayName?: string; +} + +export interface AuthWorkspace { + request_id: string; + workspace_id: string; + workspace_name: string; + role: WorkspaceRole; + employee_id: string; + display_name?: string | null; +} + +export interface AuthResponse { + access_token: string; + token_type: "bearer"; + workspace: AuthWorkspace; +} + +export interface AuthClient { + login(payload: AuthRequest): Promise; + signup(payload: AuthRequest): Promise; +} + +type Fetcher = (input: string, init: RequestInit) => Promise; + +interface AuthApiClientOptions { + baseUrl?: string; + fetcher?: Fetcher; +} + +export class AuthApiError extends Error { + constructor(message: string) { + super(message); + this.name = "AuthApiError"; + } +} + +export function createAuthApiClient( + options: AuthApiClientOptions = {}, +): AuthClient { + const baseUrl = normalizeBaseUrl( + options.baseUrl ?? import.meta.env.VITE_API_BASE_URL ?? "/api", + ); + const fetcher = + options.fetcher ?? + ((input: string, init: RequestInit) => globalThis.fetch(input, init)); + + return { + async login(payload: AuthRequest): Promise { + return submitAuthRequest(fetcher, `${baseUrl}/v1/auth/login`, payload); + }, + async signup(payload: AuthRequest): Promise { + return submitAuthRequest(fetcher, `${baseUrl}/v1/auth/signup`, payload); + }, + }; +} + +export function buildAuthHeaders(authToken: string): Record { + return { + Authorization: `Bearer ${authToken}`, + }; +} + +async function submitAuthRequest( + fetcher: Fetcher, + url: string, + payload: AuthRequest, +): Promise { + const response = await fetcher(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + employee_id: payload.employeeId, + password: payload.password, + display_name: payload.displayName, + }), + }); + + if (!response.ok) { + throw new AuthApiError(await readErrorMessage(response)); + } + + return (await response.json()) as AuthResponse; +} + +function normalizeBaseUrl(baseUrl: string): string { + return baseUrl.replace(/\/$/, ""); +} + +async function readErrorMessage(response: Response): Promise { + const fallback = `인증 요청에 실패했습니다. (${response.status})`; + + try { + const payload = (await response.json()) as { + detail?: string | { message?: string }; + }; + + if (typeof payload.detail === "string") { + return payload.detail; + } + + if (payload.detail?.message) { + return payload.detail.message; + } + } catch { + return fallback; + } + + return fallback; +} diff --git a/frontend/src/lib/chat-api.test.ts b/frontend/src/lib/chat-api.test.ts index b0e9d21..1ccfe44 100644 --- a/frontend/src/lib/chat-api.test.ts +++ b/frontend/src/lib/chat-api.test.ts @@ -3,12 +3,12 @@ import { describe, expect, it, vi } from "vitest"; import { createChatApiClient } from "./chat-api"; describe("createChatApiClient", () => { - it("채팅 API에 API Key와 질문 요청을 전송한다", async () => { + it("Bearer 토큰과 질문 요청을 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( new Response( JSON.stringify({ - answer: "문서 기준 답변입니다. [1]", - model: "google/gemma-4-E4B-it", + answer: "문서 기반 답변입니다. [1]", + model: "local-model", citations: [], usage: {}, retrieved_chunk_count: 0, @@ -16,15 +16,13 @@ describe("createChatApiClient", () => { { status: 200, headers: { "Content-Type": "application/json" } }, ), ); - const client = createChatApiClient({ - baseUrl: "http://api.local", - fetcher, - }); + const client = createChatApiClient({ baseUrl: "http://api.local", fetcher }); const response = await client.ask({ - apiKey: "local-dev-key", - question: "정책 문서 요약해줘", + authToken: "auth-token", + question: "정책 요약해줘", documentIds: ["doc-1"], + securityLevels: ["restricted"], topK: 5, }); @@ -32,41 +30,37 @@ describe("createChatApiClient", () => { method: "POST", headers: { "Content-Type": "application/json", - "X-API-Key": "local-dev-key", + Authorization: "Bearer auth-token", }, body: JSON.stringify({ - question: "정책 문서 요약해줘", + question: "정책 요약해줘", document_ids: ["doc-1"], + security_levels: ["restricted"], top_k: 5, }), }); - expect(response.answer).toBe("문서 기준 답변입니다. [1]"); + expect(response.answer).toBe("문서 기반 답변입니다. [1]"); }); - it("API 오류 메시지를 사용자에게 전달할 수 있는 오류로 변환한다", async () => { + it("API 오류 메시지를 예외로 변환한다", async () => { const fetcher = vi.fn().mockResolvedValue( new Response( JSON.stringify({ - detail: { - code: "AUTH_INVALID_API_KEY", - message: "API key is invalid.", - }, + detail: { code: "AUTH_INVALID_TOKEN", message: "토큰이 올바르지 않습니다." }, }), { status: 401, headers: { "Content-Type": "application/json" } }, ), ); - const client = createChatApiClient({ - baseUrl: "", - fetcher, - }); + const client = createChatApiClient({ baseUrl: "", fetcher }); await expect( client.ask({ - apiKey: "bad-key", + authToken: "bad-token", question: "질문", documentIds: [], + securityLevels: [], topK: 5, }), - ).rejects.toThrow("API key is invalid."); + ).rejects.toThrow("토큰이 올바르지 않습니다."); }); }); diff --git a/frontend/src/lib/chat-api.ts b/frontend/src/lib/chat-api.ts index aa566d4..f2a980a 100644 --- a/frontend/src/lib/chat-api.ts +++ b/frontend/src/lib/chat-api.ts @@ -1,7 +1,11 @@ +import { buildAuthHeaders } from "./auth-api"; +import { DocumentSecurityLevel } from "./document-api"; + export interface ChatSubmitPayload { - apiKey: string; + authToken: string; question: string; documentIds: string[]; + securityLevels: DocumentSecurityLevel[]; topK: number; } @@ -9,6 +13,7 @@ export interface ChatCitation { citation_id: number; document_id: string; filename: string; + security_level: DocumentSecurityLevel; chunk_index: number; score: number; rerank_score?: number | null; @@ -63,7 +68,7 @@ export function createChatApiClient( method: "POST", headers: { "Content-Type": "application/json", - "X-API-Key": payload.apiKey, + ...buildAuthHeaders(payload.authToken), }, body: JSON.stringify(toChatRequestBody(payload)), }); @@ -81,6 +86,7 @@ function toChatRequestBody(payload: ChatSubmitPayload) { return { question: payload.question, document_ids: payload.documentIds, + security_levels: payload.securityLevels, top_k: payload.topK, }; } diff --git a/frontend/src/lib/document-api.test.ts b/frontend/src/lib/document-api.test.ts index 8c632dc..5c0755d 100644 --- a/frontend/src/lib/document-api.test.ts +++ b/frontend/src/lib/document-api.test.ts @@ -3,13 +3,14 @@ import { describe, expect, it, vi } from "vitest"; import { createDocumentApiClient } from "./document-api"; describe("createDocumentApiClient", () => { - it("문서 업로드 API에 API Key와 파일 FormData를 전송한다", async () => { + it("문서 업로드 요청에 토큰, 파일, 보안 등급을 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( new Response( JSON.stringify({ document_id: "doc-1", workspace_id: "workspace-alpha", workspace_name: "Workspace Alpha", + security_level: "confidential", filename: "memo.txt", parser: "text", character_count: 15, @@ -25,175 +26,104 @@ describe("createDocumentApiClient", () => { const file = new File(["hello docsearch"], "memo.txt", { type: "text/plain", }); - const client = createDocumentApiClient({ - baseUrl: "http://api.local", - fetcher, - }); + const client = createDocumentApiClient({ baseUrl: "http://api.local", fetcher }); const response = await client.uploadDocument({ - apiKey: "local-dev-key", + authToken: "auth-token", file, + securityLevel: "confidential", }); expect(fetcher).toHaveBeenCalledWith( "http://api.local/v1/documents", expect.objectContaining({ method: "POST", - headers: { - "X-API-Key": "local-dev-key", - }, + headers: { Authorization: "Bearer auth-token" }, }), ); const body = fetcher.mock.calls[0][1].body as FormData; expect(body.get("file")).toBe(file); + expect(body.get("security_level")).toBe("confidential"); expect(response.document_id).toBe("doc-1"); }); - it("업로드 API 오류 메시지를 사용자에게 전달할 수 있는 오류로 변환한다", async () => { + it("문서 목록 조회에 토큰을 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - detail: { - code: "DOCUMENT_UNSUPPORTED_TYPE", - message: "Unsupported document type: .csv", - }, - }), - { status: 400, headers: { "Content-Type": "application/json" } }, - ), - ); - const client = createDocumentApiClient({ - baseUrl: "", - fetcher, - }); - - await expect( - client.uploadDocument({ - apiKey: "local-dev-key", - file: new File(["a,b"], "table.csv", { type: "text/csv" }), + new Response(JSON.stringify({ documents: [], total: 0 }), { + status: 200, + headers: { "Content-Type": "application/json" }, }), - ).rejects.toThrow("Unsupported document type: .csv"); - }); - - it("문서 목록 API에 API Key를 포함해 조회 요청을 보낸다", async () => { - const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - documents: [ - { - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-1", - indexing_status: "completed", - chunk_count: 1, - uploaded_at: "2026-05-15T09:00:00Z", - }, - ], - total: 1, - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), ); - const client = createDocumentApiClient({ - baseUrl: "http://api.local/", - fetcher, - }); + const client = createDocumentApiClient({ baseUrl: "http://api.local/", fetcher }); - const response = await client.listDocuments({ - apiKey: "local-dev-key", - }); + const response = await client.listDocuments({ authToken: "auth-token" }); expect(fetcher).toHaveBeenCalledWith( "http://api.local/v1/documents", expect.objectContaining({ method: "GET", - headers: { - "X-API-Key": "local-dev-key", - }, + headers: { Authorization: "Bearer auth-token" }, }), ); - expect(response.total).toBe(1); - expect(response.documents[0].filename).toBe("memo.txt"); + expect(response.total).toBe(0); }); - it("문서 삭제 API에 API Key와 문서 ID를 전송한다", async () => { - const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - document_id: "doc-1", - workspace_id: "workspace-alpha", - deleted: true, - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - ); - const client = createDocumentApiClient({ - baseUrl: "http://api.local", - fetcher, - }); + it("문서 삭제와 재인덱싱에 토큰과 문서 ID를 전송한다", async () => { + const fetcher = vi + .fn() + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + document_id: "doc-1", + workspace_id: "workspace-alpha", + deleted: true, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + document_id: "doc-1", + workspace_id: "workspace-alpha", + workspace_name: "Workspace Alpha", + filename: "memo.txt", + parser: "text", + character_count: 15, + text_preview: "hello docsearch", + storage_key: "workspace-alpha/doc-1/memo.txt", + indexing_job_id: "job-2", + indexing_status: "completed", + chunk_count: 2, + uploaded_at: "2026-05-15T09:00:00Z", + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); + const client = createDocumentApiClient({ baseUrl: "http://api.local", fetcher }); - const response = await client.deleteDocument({ - apiKey: "local-dev-key", + await client.deleteDocument({ authToken: "auth-token", documentId: "doc-1" }); + const record = await client.reindexDocument({ + authToken: "auth-token", documentId: "doc-1", }); - expect(fetcher).toHaveBeenCalledWith( + expect(fetcher).toHaveBeenNthCalledWith( + 1, "http://api.local/v1/documents/doc-1", expect.objectContaining({ method: "DELETE", - headers: { - "X-API-Key": "local-dev-key", - }, + headers: { Authorization: "Bearer auth-token" }, }), ); - expect(response.deleted).toBe(true); - }); - - it("문서 재인덱싱 API에 API Key와 문서 ID를 전송한다", async () => { - const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - document_id: "doc-1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - filename: "memo.txt", - parser: "text", - character_count: 15, - text_preview: "hello docsearch", - storage_key: "workspace-alpha/doc-1/memo.txt", - indexing_job_id: "job-2", - indexing_status: "completed", - chunk_count: 2, - uploaded_at: "2026-05-15T09:00:00Z", - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), - ); - const client = createDocumentApiClient({ - baseUrl: "http://api.local", - fetcher, - }); - - const response = await client.reindexDocument({ - apiKey: "local-dev-key", - documentId: "doc-1", - }); - - expect(fetcher).toHaveBeenCalledWith( + expect(fetcher).toHaveBeenNthCalledWith( + 2, "http://api.local/v1/documents/doc-1/reindex", expect.objectContaining({ method: "POST", - headers: { - "X-API-Key": "local-dev-key", - }, + headers: { Authorization: "Bearer auth-token" }, }), ); - expect(response.indexing_job_id).toBe("job-2"); - expect(response.chunk_count).toBe(2); + expect(record.chunk_count).toBe(2); }); }); diff --git a/frontend/src/lib/document-api.ts b/frontend/src/lib/document-api.ts index 28e545f..d1e9f1d 100644 --- a/frontend/src/lib/document-api.ts +++ b/frontend/src/lib/document-api.ts @@ -1,21 +1,32 @@ +import { buildAuthHeaders } from "./auth-api"; + export interface DocumentUploadPayload { - apiKey: string; + authToken: string; file: File; + securityLevel: DocumentSecurityLevel; } export interface DocumentListPayload { - apiKey: string; + authToken: string; } export interface DocumentActionPayload { - apiKey: string; + authToken: string; documentId: string; } +export type DocumentSecurityLevel = + | "general" + | "internal" + | "confidential" + | "restricted"; + export interface DocumentUploadResponse { document_id: string; workspace_id: string; workspace_name: string; + uploaded_by_employee_id?: string | null; + security_level?: DocumentSecurityLevel; filename: string; parser: string; character_count: number; @@ -79,12 +90,11 @@ export function createDocumentApiClient( ): Promise { const formData = new FormData(); formData.append("file", payload.file); + formData.append("security_level", payload.securityLevel); const response = await fetcher(`${baseUrl}/v1/documents`, { method: "POST", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), body: formData, }); @@ -100,9 +110,7 @@ export function createDocumentApiClient( ): Promise { const response = await fetcher(`${baseUrl}/v1/documents`, { method: "GET", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }); if (!response.ok) { @@ -119,9 +127,7 @@ export function createDocumentApiClient( `${baseUrl}/v1/documents/${encodeURIComponent(payload.documentId)}`, { method: "DELETE", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }, ); @@ -137,9 +143,7 @@ export function createDocumentApiClient( `${baseUrl}/v1/documents/${encodeURIComponent(payload.documentId)}/reindex`, { method: "POST", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }, ); diff --git a/frontend/src/lib/operations-api.test.ts b/frontend/src/lib/operations-api.test.ts index c6e5a85..9e1ef95 100644 --- a/frontend/src/lib/operations-api.test.ts +++ b/frontend/src/lib/operations-api.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { createOperationsApiClient } from "./operations-api"; describe("createOperationsApiClient", () => { - it("운영 상태 API를 공통 API Key 헤더로 호출한다", async () => { + it("운영 상태 API에 Bearer 토큰을 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( new Response( JSON.stringify({ @@ -14,100 +14,38 @@ describe("createOperationsApiClient", () => { workspace_name: "Workspace Alpha", role: "admin", }, - checks: [ - { - name: "configuration", - status: "ready", - message: "운영 설정 기준을 통과했습니다.", - }, - ], + checks: [], events: [], - indexing_queue: { - backend: "redis", - status: "ready", - queue_key: "docsearch:indexing:queue", - pending_jobs: 2, - max_attempts: 5, - message: "Redis 인덱싱 큐 대기건수 조회에 성공했습니다.", - }, - settings: { - environment: "development", - debug: false, - dependency_health_checks_enabled: true, - dependency_health_timeout_seconds: 2, - retrieval_mode: "hybrid", - hybrid_dense_weight: 0.7, - hybrid_lexical_weight: 0.3, - hybrid_candidate_limit: 50, - rate_limit: { - enabled: true, - requests: 120, - window_seconds: 60, - backend: "redis", - fail_open: true, - }, - backends: { - audit_log: "postgres", - document_metadata: "postgres", - indexing_queue: "inprocess", - embedding: "deterministic", - reranker: "score", - }, - models: { - llm: "google/gemma-4-E4B-it", - llm_timeout_seconds: 30, - llm_max_tokens: 1024, - llm_temperature: 0.2, - llm_max_retries: 2, - llm_retry_backoff_seconds: 0.5, - embedding: "BAAI/bge-m3", - reranker: "BAAI/bge-reranker-v2-m3", - embedding_vector_size: 8, - }, - }, + settings: {}, + indexing_queue: {}, }), - { status: 200 }, + { status: 200, headers: { "Content-Type": "application/json" } }, ), ); const client = createOperationsApiClient({ - baseUrl: "http://localhost:8000", + baseUrl: "http://api.local", fetcher, }); - const response = await client.getOperationsStatus({ apiKey: "admin-key" }); + await client.getOperationsStatus({ authToken: "auth-token" }); - expect(fetcher).toHaveBeenCalledWith( - "http://localhost:8000/v1/admin/operations", - { - method: "GET", - headers: { - "X-API-Key": "admin-key", - }, - }, - ); - expect(response.status).toBe("ready"); - expect(response.settings.rate_limit.requests).toBe(120); - expect(response.settings.rate_limit.backend).toBe("redis"); - expect(response.settings.rate_limit.fail_open).toBe(true); - expect(response.indexing_queue.pending_jobs).toBe(2); + expect(fetcher).toHaveBeenCalledWith("http://api.local/v1/admin/operations", { + method: "GET", + headers: { Authorization: "Bearer auth-token" }, + }); }); - it("오류 응답의 메시지를 예외로 변환한다", async () => { + it("API 오류 메시지를 예외로 변환한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - detail: { - code: "AUTH_FORBIDDEN_ROLE", - message: "Admin role is required.", - }, - }), - { status: 403 }, - ), + new Response(JSON.stringify({ detail: { message: "Admin role is required." } }), { + status: 403, + headers: { "Content-Type": "application/json" }, + }), ); - const client = createOperationsApiClient({ fetcher }); + const client = createOperationsApiClient({ baseUrl: "", fetcher }); await expect( - client.getOperationsStatus({ apiKey: "member-key" }), + client.getOperationsStatus({ authToken: "member-token" }), ).rejects.toThrow("Admin role is required."); }); }); diff --git a/frontend/src/lib/operations-api.ts b/frontend/src/lib/operations-api.ts index 4b97cae..27978db 100644 --- a/frontend/src/lib/operations-api.ts +++ b/frontend/src/lib/operations-api.ts @@ -1,7 +1,9 @@ +import { buildAuthHeaders } from "./auth-api"; + export type OperationsStatus = "ready" | "not_ready"; export interface OperationsStatusRequest { - apiKey: string; + authToken: string; } export interface OperationsWorkspaceSummary { @@ -117,9 +119,7 @@ export function createOperationsApiClient( ): Promise { const response = await fetcher(`${baseUrl}/v1/admin/operations`, { method: "GET", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }); if (!response.ok) { diff --git a/frontend/src/lib/search-api.test.ts b/frontend/src/lib/search-api.test.ts index 6a93886..59fe1d7 100644 --- a/frontend/src/lib/search-api.test.ts +++ b/frontend/src/lib/search-api.test.ts @@ -3,35 +3,20 @@ import { describe, expect, it, vi } from "vitest"; import { createSearchApiClient } from "./search-api"; describe("createSearchApiClient", () => { - it("검색 API에 API Key와 검색 조건을 전송한다", async () => { + it("Bearer 토큰과 검색 조건을 전송한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - query: "권한 정책", - total: 1, - results: [ - { - document_id: "doc-1", - filename: "policy.md", - parser: "markdown", - chunk_index: 2, - score: 0.87, - snippet: "권한 정책 문서 일부", - }, - ], - }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), + new Response(JSON.stringify({ query: "권한", total: 0, results: [] }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), ); - const client = createSearchApiClient({ - baseUrl: "http://api.local", - fetcher, - }); + const client = createSearchApiClient({ baseUrl: "http://api.local", fetcher }); - const response = await client.searchDocuments({ - apiKey: "local-dev-key", - query: "권한 정책", + await client.searchDocuments({ + authToken: "auth-token", + query: "권한", documentIds: ["doc-1"], + securityLevels: ["internal"], limit: 5, }); @@ -39,41 +24,34 @@ describe("createSearchApiClient", () => { method: "POST", headers: { "Content-Type": "application/json", - "X-API-Key": "local-dev-key", + Authorization: "Bearer auth-token", }, body: JSON.stringify({ - query: "권한 정책", + query: "권한", document_ids: ["doc-1"], + security_levels: ["internal"], limit: 5, }), }); - expect(response.total).toBe(1); }); - it("검색 API 오류 메시지를 사용자에게 전달할 수 있는 오류로 변환한다", async () => { + it("API 오류 메시지를 예외로 변환한다", async () => { const fetcher = vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - detail: { - code: "AUTH_INVALID_API_KEY", - message: "API key is invalid.", - }, - }), - { status: 401, headers: { "Content-Type": "application/json" } }, - ), + new Response(JSON.stringify({ detail: { message: "검색 실패" } }), { + status: 500, + headers: { "Content-Type": "application/json" }, + }), ); - const client = createSearchApiClient({ - baseUrl: "", - fetcher, - }); + const client = createSearchApiClient({ baseUrl: "", fetcher }); await expect( client.searchDocuments({ - apiKey: "bad-key", - query: "권한 정책", + authToken: "bad-token", + query: "권한", documentIds: [], + securityLevels: [], limit: 5, }), - ).rejects.toThrow("API key is invalid."); + ).rejects.toThrow("검색 실패"); }); }); diff --git a/frontend/src/lib/search-api.ts b/frontend/src/lib/search-api.ts index 591e524..faf4d73 100644 --- a/frontend/src/lib/search-api.ts +++ b/frontend/src/lib/search-api.ts @@ -1,7 +1,11 @@ +import { buildAuthHeaders } from "./auth-api"; +import { DocumentSecurityLevel } from "./document-api"; + export interface SearchSubmitPayload { - apiKey: string; + authToken: string; query: string; documentIds: string[]; + securityLevels: DocumentSecurityLevel[]; limit: number; } @@ -9,6 +13,7 @@ export interface SearchResultChunk { document_id: string; filename: string; parser: string; + security_level: DocumentSecurityLevel; chunk_index: number; score: number; snippet: string; @@ -56,11 +61,12 @@ export function createSearchApiClient( method: "POST", headers: { "Content-Type": "application/json", - "X-API-Key": payload.apiKey, + ...buildAuthHeaders(payload.authToken), }, body: JSON.stringify({ query: payload.query, document_ids: payload.documentIds, + security_levels: payload.securityLevels, limit: payload.limit, }), }); diff --git a/frontend/src/lib/workspace-api.test.ts b/frontend/src/lib/workspace-api.test.ts index bd499bc..f931864 100644 --- a/frontend/src/lib/workspace-api.test.ts +++ b/frontend/src/lib/workspace-api.test.ts @@ -1,68 +1,46 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; -import { WorkspaceApiError, createWorkspaceApiClient } from "./workspace-api"; +import { createWorkspaceApiClient } from "./workspace-api"; -describe("workspace-api", () => { - it("API Key로 워크스페이스 컨텍스트를 조회한다", async () => { - const calls: Array<{ input: string; init: RequestInit }> = []; +describe("createWorkspaceApiClient", () => { + it("Bearer 토큰으로 워크스페이스 컨텍스트를 조회한다", async () => { + const fetcher = vi.fn().mockResolvedValue( + new Response( + JSON.stringify({ + request_id: "req-1", + workspace_id: "workspace-alpha", + workspace_name: "Workspace Alpha", + role: "admin", + employee_id: "1001", + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ); const client = createWorkspaceApiClient({ - baseUrl: "/api", - fetcher: async (input, init) => { - calls.push({ input, init }); - return new Response( - JSON.stringify({ - request_id: "req_1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "admin", - }), - { - status: 200, - headers: { "Content-Type": "application/json" }, - }, - ); - }, + baseUrl: "http://api.local", + fetcher, }); - const result = await client.getWorkspace({ apiKey: "admin-key" }); + const result = await client.getWorkspace({ authToken: "auth-token" }); - expect(result).toEqual({ - request_id: "req_1", - workspace_id: "workspace-alpha", - workspace_name: "Workspace Alpha", - role: "admin", - }); - expect(calls).toHaveLength(1); - expect(calls[0]).toMatchObject({ - input: "/api/v1/workspace", - init: { - method: "GET", - headers: { - "X-API-Key": "admin-key", - }, - }, + expect(fetcher).toHaveBeenCalledWith("http://api.local/v1/workspace", { + method: "GET", + headers: { Authorization: "Bearer auth-token" }, }); + expect(result.employee_id).toBe("1001"); }); - it("오류 응답 메시지를 예외로 변환한다", async () => { - const client = createWorkspaceApiClient({ - fetcher: async () => - new Response( - JSON.stringify({ - detail: { - code: "AUTH_INVALID_API_KEY", - message: "API key is invalid.", - }, - }), - { - status: 401, - headers: { "Content-Type": "application/json" }, - }, - ), - }); - - await expect(client.getWorkspace({ apiKey: "bad-key" })).rejects.toThrow( - new WorkspaceApiError("API key is invalid."), + it("API 오류 메시지를 예외로 변환한다", async () => { + const fetcher = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ detail: { message: "로그인이 필요합니다." } }), { + status: 401, + headers: { "Content-Type": "application/json" }, + }), ); + const client = createWorkspaceApiClient({ baseUrl: "", fetcher }); + + await expect( + client.getWorkspace({ authToken: "bad-token" }), + ).rejects.toThrow("로그인이 필요합니다."); }); }); diff --git a/frontend/src/lib/workspace-api.ts b/frontend/src/lib/workspace-api.ts index ce949c1..c3a4546 100644 --- a/frontend/src/lib/workspace-api.ts +++ b/frontend/src/lib/workspace-api.ts @@ -1,7 +1,9 @@ +import { buildAuthHeaders } from "./auth-api"; + export type WorkspaceRole = "member" | "admin"; export interface WorkspaceRequest { - apiKey: string; + authToken: string; } export interface WorkspaceContext { @@ -9,6 +11,8 @@ export interface WorkspaceContext { workspace_id: string; workspace_name: string; role: WorkspaceRole; + employee_id?: string | null; + display_name?: string | null; } export interface WorkspaceClient { @@ -43,9 +47,7 @@ export function createWorkspaceApiClient( async getWorkspace(payload: WorkspaceRequest): Promise { const response = await fetcher(`${baseUrl}/v1/workspace`, { method: "GET", - headers: { - "X-API-Key": payload.apiKey, - }, + headers: buildAuthHeaders(payload.authToken), }); if (!response.ok) { diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 04c841e..bddbf93 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -14,15 +14,40 @@ body { .app-shell { min-height: 100vh; - background: #f7f8fb; + background: #f5f5f5; +} + +.app-sider { + min-height: 100vh; + border-right: 1px solid #f0f0f0; +} + +.app-logo { + height: 64px; + display: flex; + align-items: center; + justify-content: center; + border-bottom: 1px solid #f0f0f0; + background: #ffffff; +} + +.app-logo-text { + font-size: 18px; +} + +.app-menu { + border-right: 0; +} + +.app-main-layout { + min-width: 0; } .app-header { - height: auto; - min-height: 72px; - padding: 14px 32px; + height: 64px; + padding: 0 24px; background: #ffffff; - border-bottom: 1px solid #e5e7eb; + border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; justify-content: space-between; @@ -44,25 +69,28 @@ body { } .app-content { - padding: 28px 32px 40px; + min-height: calc(100vh - 64px); + padding: 24px; + background: #f5f5f5; + overflow: auto; } -.workspace-auth { - margin-bottom: 20px; - display: flex; - flex-direction: column; - gap: 10px; +.auth-card { + max-width: 440px; + margin: 72px auto 0; + border: 1px solid #f0f0f0; + border-radius: 8px; } -.workspace-auth-form { - display: grid; - grid-template-columns: minmax(180px, 320px) auto minmax(0, 1fr); - gap: 10px 12px; - align-items: end; +.auth-form { + display: flex; + flex-direction: column; + gap: 14px; } -.workspace-auth-form .field-label { - grid-column: 1 / -1; +.auth-copy.ant-typography { + margin: 0; + color: #64748b; } .chat-workspace { @@ -202,13 +230,16 @@ body { @media (max-width: 860px) { .app-header { - align-items: flex-start; + height: auto; + min-height: 64px; + align-items: stretch; flex-direction: column; - padding: 14px 20px; + padding: 12px 16px; } .app-content { - padding: 20px; + min-height: auto; + padding: 16px; } .chat-workspace, @@ -218,7 +249,8 @@ body { grid-template-columns: 1fr; } - .workspace-auth-form { - grid-template-columns: 1fr; + .auth-form { + align-items: stretch; + flex-direction: column; } } From 1656d11d46234d80c6841f4fbb51db8e9c8b9b6e Mon Sep 17 00:00:00 2001 From: burnern <200775118+dev-burnern@users.noreply.github.com> Date: Sun, 17 May 2026 01:20:03 +0900 Subject: [PATCH 4/4] =?UTF-8?q?docs(infra):=20=EB=A1=9C=EC=BB=AC=20LLM=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8=20=EA=B5=AC=EC=84=B1=20=EC=A0=95?= =?UTF-8?q?=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/notebook-local-test.md | 29 +++++++++++++++++++++++ infra/compose/docker-compose.host-llm.yml | 11 +++++++++ infra/nginx/default.conf | 3 +++ 3 files changed, 43 insertions(+) create mode 100644 infra/compose/docker-compose.host-llm.yml diff --git a/docs/notebook-local-test.md b/docs/notebook-local-test.md index a454ef3..137661c 100644 --- a/docs/notebook-local-test.md +++ b/docs/notebook-local-test.md @@ -46,6 +46,35 @@ EMBEDDING_TIMEOUT_SECONDS=10.0 `EMBEDDING_VECTOR_SIZE`는 Qdrant collection 크기와 맞아야 합니다. deterministic 8차원으로 만든 collection을 BGE-M3 1024차원으로 재사용하면 upsert나 검색이 실패할 수 있으므로, 모델을 바꿀 때는 collection을 비우거나 새 collection 이름을 사용합니다. +## 포트폴리오 화면용 host LLM 연결 + +Ollama 또는 LM Studio처럼 Windows 호스트에서 OpenAI compatible local server를 실행하면, Docker 안의 API만 해당 서버를 바라보게 바꿀 수 있습니다. 이 구성은 embedding stub은 그대로 두고 채팅 LLM만 실제 모델로 바꾸므로 기존 Qdrant collection을 다시 만들 필요가 없습니다. + +Ollama 기본 서버를 사용할 때: + +```powershell +$env:LOCAL_LLM_BASE_URL = "http://host.docker.internal:11434/v1" +$env:LOCAL_LLM_MODEL = "gemma3:4b" +$env:LOCAL_LLM_TIMEOUT_SECONDS = "180.0" +$env:LOCAL_LLM_MAX_TOKENS = "384" +$env:LOCAL_LLM_TEMPERATURE = "0.0" +$env:LOCAL_CHAT_RETRIEVAL_LIMIT = "3" +$env:LOCAL_CHAT_RERANK_TOP_K = "1" +docker compose -f infra/compose/docker-compose.yml -f infra/compose/docker-compose.notebook.yml -f infra/compose/docker-compose.host-llm.yml up --build -d api gateway +docker compose -f infra/compose/docker-compose.yml -f infra/compose/docker-compose.notebook.yml -f infra/compose/docker-compose.host-llm.yml restart gateway +``` + +포트폴리오 화면을 빠르게 확인할 때는 채팅 화면의 `검색 개수`를 `1`로 낮춰 테스트합니다. `gemma3:4b` CPU 모드는 `검색 개수 1`에서는 짧은 답변 확인이 가능하지만, `검색 개수 5`는 컨텍스트가 길어져 응답이 1분 이상 걸릴 수 있습니다. + +LM Studio 기본 서버를 사용할 때: + +```powershell +$env:LOCAL_LLM_BASE_URL = "http://host.docker.internal:1234/v1" +$env:LOCAL_LLM_MODEL = "" +docker compose -f infra/compose/docker-compose.yml -f infra/compose/docker-compose.notebook.yml -f infra/compose/docker-compose.host-llm.yml up --build -d api gateway +docker compose -f infra/compose/docker-compose.yml -f infra/compose/docker-compose.notebook.yml -f infra/compose/docker-compose.host-llm.yml restart gateway +``` + ## 빠른 확인 순서 1. `http://localhost:8080`에서 `local-dev-key`를 입력합니다. diff --git a/infra/compose/docker-compose.host-llm.yml b/infra/compose/docker-compose.host-llm.yml new file mode 100644 index 0000000..f82842d --- /dev/null +++ b/infra/compose/docker-compose.host-llm.yml @@ -0,0 +1,11 @@ +services: + api: + environment: + LLM_BASE_URL: ${LOCAL_LLM_BASE_URL:-http://host.docker.internal:11434/v1} + LLM_MODEL: ${LOCAL_LLM_MODEL:-gemma3:4b} + LLM_API_KEY: ${LOCAL_LLM_API_KEY:-ollama} + LLM_TIMEOUT_SECONDS: ${LOCAL_LLM_TIMEOUT_SECONDS:-180.0} + LLM_MAX_TOKENS: ${LOCAL_LLM_MAX_TOKENS:-384} + LLM_TEMPERATURE: ${LOCAL_LLM_TEMPERATURE:-0.0} + CHAT_RETRIEVAL_LIMIT: ${LOCAL_CHAT_RETRIEVAL_LIMIT:-3} + CHAT_RERANK_TOP_K: ${LOCAL_CHAT_RERANK_TOP_K:-1} diff --git a/infra/nginx/default.conf b/infra/nginx/default.conf index 0984b28..0478acf 100644 --- a/infra/nginx/default.conf +++ b/infra/nginx/default.conf @@ -15,6 +15,9 @@ http { location /api/ { proxy_pass http://backend_api/; proxy_http_version 1.1; + proxy_connect_timeout 180s; + proxy_send_timeout 180s; + proxy_read_timeout 180s; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;