Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions backend/app/chat/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
get_qdrant_store,
get_runtime_settings,
)
from backend.app.documents.security import validate_document_security_levels
from backend.app.documents.security import (
DocumentSecurityPermissionError,
filter_document_security_levels_for_role,
)
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
Expand Down Expand Up @@ -77,11 +80,13 @@ async def answer_question(
chat_service: ChatService = Depends(get_chat_service),
) -> ChatResponse:
try:
security_levels = filter_document_security_levels_for_role(
role=workspace_context.role,
requested_security_levels=chat_request.security_levels,
)
validated_request = chat_request.model_copy(
update={
"security_levels": validate_document_security_levels(
chat_request.security_levels,
),
"security_levels": security_levels,
},
)
return chat_service.answer(
Expand All @@ -96,6 +101,8 @@ async def answer_question(
"message": str(exc),
},
) from exc
except DocumentSecurityPermissionError as exc:
raise _document_security_forbidden() from exc
except EmbeddingProviderError as exc:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
Expand All @@ -120,3 +127,13 @@ async def answer_question(
"message": str(exc),
},
) from exc


def _document_security_forbidden() -> HTTPException:
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"code": "DOCUMENT_SECURITY_FORBIDDEN",
"message": "Document security level is not allowed for this role.",
},
)
52 changes: 49 additions & 3 deletions backend/app/documents/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@
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.security import (
DocumentSecurityPermissionError,
ensure_document_security_level_allowed,
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
from backend.app.indexing.embedder import (
Expand Down Expand Up @@ -171,6 +178,10 @@ async def upload_document(
try:
data = await file.read()
validated_security_level = validate_document_security_level(security_level)
ensure_document_security_level_allowed(
workspace_context.role,
validated_security_level,
)
return document_service.upload_document(
workspace_context=workspace_context,
filename=file.filename or "document",
Expand All @@ -180,6 +191,8 @@ async def upload_document(
)
except DocumentProcessingError as exc:
raise _document_processing_error(exc) from exc
except DocumentSecurityPermissionError as exc:
raise _document_security_forbidden() from exc


@router.get("", response_model=DocumentListResponse)
Expand All @@ -192,7 +205,12 @@ async def list_documents(
workspace_id=workspace_context.workspace_id,
limit=limit,
)
return DocumentListResponse(documents=documents, total=len(documents))
visible_documents = [
document
for document in documents
if _is_document_visible(workspace_context, document)
]
return DocumentListResponse(documents=visible_documents, total=len(visible_documents))


@router.delete("/{document_id}", response_model=DocumentDeleteResponse)
Expand All @@ -208,6 +226,8 @@ async def delete_document(
)
except DocumentNotFoundError as exc:
raise _document_not_found(document_id) from exc
except DocumentSecurityPermissionError as exc:
raise _document_security_forbidden() from exc


@router.post("/{document_id}/reindex", response_model=DocumentRecord)
Expand All @@ -223,10 +243,26 @@ async def reindex_document(
)
except DocumentNotFoundError as exc:
raise _document_not_found(document_id) from exc
except DocumentSecurityPermissionError as exc:
raise _document_security_forbidden() from exc
except DocumentProcessingError as exc:
raise _document_processing_error(exc) from exc


def _is_document_visible(
workspace_context: WorkspaceContext,
document: DocumentRecord,
) -> bool:
try:
ensure_document_security_level_allowed(
workspace_context.role,
document.security_level,
)
except DocumentSecurityPermissionError:
return False
return True


def _document_not_found(document_id: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
Expand All @@ -237,6 +273,16 @@ def _document_not_found(document_id: str) -> HTTPException:
)


def _document_security_forbidden() -> HTTPException:
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"code": "DOCUMENT_SECURITY_FORBIDDEN",
"message": "Document security level is not allowed for this role.",
},
)


def _document_processing_error(exc: DocumentProcessingError) -> HTTPException:
status_code = (
status.HTTP_413_CONTENT_TOO_LARGE
Expand Down
56 changes: 56 additions & 0 deletions backend/app/documents/security.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
from fastapi import HTTPException, status

from backend.app.auth.models import ADMIN_ROLE, MEMBER_ROLE
from backend.app.documents.models import (
CONFIDENTIAL_SECURITY_LEVEL,
GENERAL_SECURITY_LEVEL,
INTERNAL_SECURITY_LEVEL,
RESTRICTED_SECURITY_LEVEL,
SUPPORTED_DOCUMENT_SECURITY_LEVELS,
)

_MEMBER_SECURITY_LEVELS = [GENERAL_SECURITY_LEVEL, INTERNAL_SECURITY_LEVEL]
_ADMIN_SECURITY_LEVELS = [
GENERAL_SECURITY_LEVEL,
INTERNAL_SECURITY_LEVEL,
CONFIDENTIAL_SECURITY_LEVEL,
RESTRICTED_SECURITY_LEVEL,
]


class DocumentSecurityPermissionError(ValueError):
pass


def validate_document_security_level(security_level: str) -> str:
normalized = security_level.strip() or INTERNAL_SECURITY_LEVEL
Expand Down Expand Up @@ -32,3 +48,43 @@ def validate_document_security_levels(security_levels: list[str] | None) -> list
if normalized not in validated:
validated.append(normalized)
return validated


def allowed_document_security_levels(role: str) -> list[str]:
if role == ADMIN_ROLE:
return _ADMIN_SECURITY_LEVELS.copy()
return _MEMBER_SECURITY_LEVELS.copy()


def ensure_document_security_level_allowed(role: str, security_level: str) -> None:
validated_security_level = validate_document_security_level(security_level)
if validated_security_level not in allowed_document_security_levels(role):
raise DocumentSecurityPermissionError(
f"Role {role} cannot access document security level: {validated_security_level}",
)


def filter_document_security_levels_for_role(
*,
role: str,
requested_security_levels: list[str] | None,
) -> list[str] | None:
validated_levels = validate_document_security_levels(requested_security_levels)
if role == ADMIN_ROLE and validated_levels is None:
return None

allowed_levels = allowed_document_security_levels(role)
if validated_levels is None:
return allowed_levels

disallowed_levels = [
security_level
for security_level in validated_levels
if security_level not in allowed_levels
]
if disallowed_levels:
raise DocumentSecurityPermissionError(
"Requested document security levels are not allowed for this role.",
)

return validated_levels
9 changes: 9 additions & 0 deletions backend/app/documents/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
DocumentRecord,
DocumentUploadResponse,
)
from backend.app.documents.security import ensure_document_security_level_allowed
from backend.app.documents.store import DocumentMetadataStore
from backend.app.jobs.base import IndexDocumentJob, JobQueue
from backend.app.parsers.base import DocumentTooLargeError, ParserRegistry
Expand Down Expand Up @@ -109,6 +110,10 @@ def delete_document(
)
if record is None:
raise DocumentNotFoundError(f"Document not found: {document_id}")
ensure_document_security_level_allowed(
workspace_context.role,
record.security_level,
)

self._vector_store.delete_document(
workspace_id=workspace_context.workspace_id,
Expand Down Expand Up @@ -138,6 +143,10 @@ def reindex_document(
)
if record is None:
raise DocumentNotFoundError(f"Document not found: {document_id}")
ensure_document_security_level_allowed(
workspace_context.role,
record.security_level,
)

data = self._storage_service.download_document(storage_key=record.storage_key)
self._validate_document_size(data)
Expand Down
27 changes: 23 additions & 4 deletions backend/app/search/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
get_qdrant_store,
get_runtime_settings,
)
from backend.app.documents.security import validate_document_security_levels
from backend.app.documents.security import (
DocumentSecurityPermissionError,
filter_document_security_levels_for_role,
)
from backend.app.indexing.embedder import EmbeddingProviderError
from backend.app.retrieval.filters import RetrievalFilter
from backend.app.retrieval.retriever import Retriever, build_retriever
Expand Down Expand Up @@ -36,15 +39,21 @@ async def search_documents(
workspace_context: WorkspaceContext = Depends(require_workspace_context),
retriever: Retriever = Depends(get_search_retriever),
) -> SearchResponse:
try:
security_levels = filter_document_security_levels_for_role(
role=workspace_context.role,
requested_security_levels=search_request.security_levels,
)
except DocumentSecurityPermissionError as exc:
raise _document_security_forbidden() from exc

try:
chunks = retriever.retrieve(
query_text=search_request.query,
filters=RetrievalFilter(
workspace_id=workspace_context.workspace_id,
document_ids=search_request.document_ids,
security_levels=validate_document_security_levels(
search_request.security_levels,
),
security_levels=security_levels,
),
limit=search_request.limit,
)
Expand Down Expand Up @@ -75,3 +84,13 @@ async def search_documents(
total=len(results),
results=results,
)


def _document_security_forbidden() -> HTTPException:
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"code": "DOCUMENT_SECURITY_FORBIDDEN",
"message": "Document security level is not allowed for this role.",
},
)
79 changes: 79 additions & 0 deletions backend/tests/chat/test_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,85 @@ def test_채팅_API가_워크스페이스_인증_후_답변을_반환한다(
}


def test_member_chat_without_security_filter_is_scoped_to_allowed_levels(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv(
"DOCSEARCH_API_KEYS",
"local-dev-key|workspace-alpha|Workspace Alpha|member",
)

from backend.app.chat.router import get_chat_service

fake_service = FakeChatService()
app = create_app()
app.dependency_overrides[get_chat_service] = lambda: fake_service
client = TestClient(app)

response = client.post(
"/v1/chat",
headers={"X-API-Key": "local-dev-key"},
json={"question": "정책 문서 요약해줘"},
)

assert response.status_code == 200
assert fake_service.chat_request is not None
assert fake_service.chat_request.security_levels == ["general", "internal"]


def test_member_chat_rejects_restricted_security_level(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv(
"DOCSEARCH_API_KEYS",
"local-dev-key|workspace-alpha|Workspace Alpha|member",
)

from backend.app.chat.router import get_chat_service

app = create_app()
app.dependency_overrides[get_chat_service] = lambda: FakeChatService()
client = TestClient(app)

response = client.post(
"/v1/chat",
headers={"X-API-Key": "local-dev-key"},
json={
"question": "정책 문서 요약해줘",
"security_levels": ["restricted"],
},
)

assert response.status_code == 403
assert response.json()["detail"]["code"] == "DOCUMENT_SECURITY_FORBIDDEN"


def test_admin_chat_without_security_filter_keeps_unrestricted_filter(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv(
"DOCSEARCH_API_KEYS",
"local-dev-key|workspace-alpha|Workspace Alpha|admin",
)

from backend.app.chat.router import get_chat_service

fake_service = FakeChatService()
app = create_app()
app.dependency_overrides[get_chat_service] = lambda: fake_service
client = TestClient(app)

response = client.post(
"/v1/chat",
headers={"X-API-Key": "local-dev-key"},
json={"question": "정책 문서 요약해줘"},
)

assert response.status_code == 200
assert fake_service.chat_request is not None
assert fake_service.chat_request.security_levels is None


def test_채팅_API는_API_Key가_없으면_거부한다() -> None:
app = create_app()
client = TestClient(app)
Expand Down
Loading
Loading