mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-04 21:06:03 +00:00
Compare commits
1 Commits
fix/rag-ru
...
fix/api-ap
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31f4bc1ad6 |
@@ -52,6 +52,9 @@ class ApiKeyService:
|
|||||||
|
|
||||||
async def verify_api_key(self, key: str) -> bool:
|
async def verify_api_key(self, key: str) -> bool:
|
||||||
"""Verify if an API key is valid"""
|
"""Verify if an API key is valid"""
|
||||||
|
if not isinstance(key, str) or not key.startswith('lbk_'):
|
||||||
|
return False
|
||||||
|
|
||||||
result = await self.ap.persistence_mgr.execute_async(
|
result = await self.ap.persistence_mgr.execute_async(
|
||||||
sqlalchemy.select(apikey.ApiKey).where(apikey.ApiKey.key == key)
|
sqlalchemy.select(apikey.ApiKey).where(apikey.ApiKey.key == key)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import posixpath
|
import posixpath
|
||||||
import re
|
from typing import Any
|
||||||
from typing import TYPE_CHECKING, Any
|
from langbot.pkg.core import app
|
||||||
from urllib.parse import unquote
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from langbot.pkg.core import app
|
|
||||||
|
|
||||||
|
|
||||||
class RAGRuntimeService:
|
class RAGRuntimeService:
|
||||||
@@ -113,17 +109,8 @@ class RAGRuntimeService:
|
|||||||
regardless of the underlying storage provider.
|
regardless of the underlying storage provider.
|
||||||
"""
|
"""
|
||||||
# Validate storage_path to prevent path traversal
|
# Validate storage_path to prevent path traversal
|
||||||
decoded_path = unquote(storage_path).replace('\\', '/')
|
normalized = posixpath.normpath(storage_path)
|
||||||
decoded_segments = decoded_path.split('/')
|
if normalized.startswith('/') or '..' in normalized.split('/'):
|
||||||
normalized = posixpath.normpath(decoded_path)
|
|
||||||
if (
|
|
||||||
not storage_path
|
|
||||||
or '\x00' in decoded_path
|
|
||||||
or normalized.startswith('/')
|
|
||||||
or '..' in decoded_segments
|
|
||||||
or '..' in normalized.split('/')
|
|
||||||
or re.match(r'^[A-Za-z]:/', normalized)
|
|
||||||
):
|
|
||||||
raise ValueError('Invalid storage path')
|
raise ValueError('Invalid storage path')
|
||||||
content_bytes = await self.ap.storage_mgr.storage_provider.load(normalized)
|
content_bytes = await self.ap.storage_mgr.storage_provider.load(normalized)
|
||||||
return content_bytes if content_bytes else b''
|
return content_bytes if content_bytes else b''
|
||||||
|
|||||||
40
tests/unit_tests/api/test_apikey_service.py
Normal file
40
tests/unit_tests/api/test_apikey_service.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import AsyncMock, Mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from langbot.pkg.api.http.service.apikey import ApiKeyService
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize('api_key', [None, 123, b'lbk_bytes', '', 'plain_key', ' LBK_bad', 'sk-lbk_fake'])
|
||||||
|
async def test_verify_api_key_rejects_non_lbk_keys_without_db_query(api_key):
|
||||||
|
persistence_mgr = SimpleNamespace(execute_async=AsyncMock())
|
||||||
|
service = ApiKeyService(SimpleNamespace(persistence_mgr=persistence_mgr))
|
||||||
|
|
||||||
|
result = await service.verify_api_key(api_key)
|
||||||
|
|
||||||
|
assert result is False
|
||||||
|
persistence_mgr.execute_async.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
('db_row', 'expected'),
|
||||||
|
[
|
||||||
|
(object(), True),
|
||||||
|
(None, False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_verify_api_key_keeps_db_validation_for_lbk_keys(db_row, expected):
|
||||||
|
query_result = Mock()
|
||||||
|
query_result.first.return_value = db_row
|
||||||
|
persistence_mgr = SimpleNamespace(execute_async=AsyncMock(return_value=query_result))
|
||||||
|
service = ApiKeyService(SimpleNamespace(persistence_mgr=persistence_mgr))
|
||||||
|
|
||||||
|
result = await service.verify_api_key('lbk_valid_format')
|
||||||
|
|
||||||
|
assert result is expected
|
||||||
|
persistence_mgr.execute_async.assert_awaited_once()
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from langbot.pkg.rag.service.runtime import RAGRuntimeService
|
|
||||||
|
|
||||||
|
|
||||||
class DummyStorageProvider:
|
|
||||||
def __init__(self, content: bytes | None = b'data'):
|
|
||||||
self.content = content
|
|
||||||
self.loaded_paths: list[str] = []
|
|
||||||
|
|
||||||
async def load(self, path: str):
|
|
||||||
self.loaded_paths.append(path)
|
|
||||||
return self.content
|
|
||||||
|
|
||||||
|
|
||||||
def make_service(storage_provider: DummyStorageProvider) -> RAGRuntimeService:
|
|
||||||
return RAGRuntimeService(SimpleNamespace(storage_mgr=SimpleNamespace(storage_provider=storage_provider)))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_get_file_stream_normalizes_safe_path():
|
|
||||||
storage_provider = DummyStorageProvider()
|
|
||||||
service = make_service(storage_provider)
|
|
||||||
|
|
||||||
content = await service.get_file_stream('safe/./nested/file.pdf')
|
|
||||||
|
|
||||||
assert content == b'data'
|
|
||||||
assert storage_provider.loaded_paths == ['safe/nested/file.pdf']
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
'storage_path',
|
|
||||||
[
|
|
||||||
'',
|
|
||||||
'../secret.txt',
|
|
||||||
'/absolute/path.txt',
|
|
||||||
'..\\secret.txt',
|
|
||||||
'nested\\..\\secret.txt',
|
|
||||||
'%2e%2e/secret.txt',
|
|
||||||
'nested/%2e%2e/secret.txt',
|
|
||||||
'C:\\secret.txt',
|
|
||||||
'safe/\x00file.txt',
|
|
||||||
],
|
|
||||||
)
|
|
||||||
async def test_get_file_stream_rejects_unsafe_paths(storage_path: str):
|
|
||||||
storage_provider = DummyStorageProvider()
|
|
||||||
service = make_service(storage_provider)
|
|
||||||
|
|
||||||
with pytest.raises(ValueError, match='Invalid storage path'):
|
|
||||||
await service.get_file_stream(storage_path)
|
|
||||||
|
|
||||||
assert storage_provider.loaded_paths == []
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_get_file_stream_returns_empty_bytes_for_missing_content():
|
|
||||||
storage_provider = DummyStorageProvider(content=None)
|
|
||||||
service = make_service(storage_provider)
|
|
||||||
|
|
||||||
content = await service.get_file_stream('safe/file.pdf')
|
|
||||||
|
|
||||||
assert content == b''
|
|
||||||
assert storage_provider.loaded_paths == ['safe/file.pdf']
|
|
||||||
Reference in New Issue
Block a user