Files
LangBot/tests/unit_tests/utils/test_image.py
T
RockChinQ e1ac5e0fc8 feat(tenancy): add Workspace multi-tenant foundation (#2353)
* Document multi-tenant workspace architecture

* Add OSS and commercial workspace boundaries

* docs: redesign multi-tenant workspace architecture

* feat(tenancy): implement workspace isolation

* docs(tenancy): record verification evidence

* docs(tenancy): revise single-instance SaaS topology

* docs(tenancy): refine architecture options

* docs: finalize cloud v2 multi-tenant decisions

* feat(tenancy): establish cloud isolation foundations

* feat(tenancy): harden shared cloud runtime boundaries

* docs(tenancy): record final isolation verification

* fix(tenancy): close isolation and permission gaps

* docs(tenancy): record final isolation verification

* feat(tenancy): connect cloud workspace control plane

* fix(build): install git for pinned SDK

* docs(cloud): update control plane verification

* chore: update multi-tenant SDK pin

* fix(cloud): skip legacy model sync during startup

* test(cloud): preserve minimal model manager fixtures

* fix(cloud): preserve authenticated account context

* fix(cloud): reuse authenticated account for user info

* feat(cloud): complete Workspace settings navigation

* test(web): cover Workspace dropdown menu

* feat(web): place workspace controls in sidebar

* refactor(web): streamline workspace controls

* style(web): format workspace layout test

* fix(cloud): surface runtime and workspace plan status

* fix(plugin): keep runtime identity stable across restarts

* fix(ui): widen and center workspace switcher

* fix(ui): hide roles from workspace switcher

* fix(ui): align workspace switcher with sidebar entries

* feat(workspace): add in-product collaboration and direct Cloud launch

* style: format collaboration changes

* fix(workspace): bind collaboration APIs to tenant UoW

* fix(cloud): preserve Core-owned collaboration state

* test(cloud): require Space identity for invite registration

* feat(cloud): complete secure invitation experience

* style(web): format invitation flows

* fix(cloud): recover box runtime without unscoped skill reload

* feat(oss): enforce invitation account and owner billing flows

* style: format OSS account service

* test(oss): cover invitation logout handoff

* fix(oss): resolve workspace owner in scoped session

* feat(cloud): harden multi-tenant runtime resources

* fix(cloud): bound runtime restart storms

* fix(cloud): eliminate periodic runtime CPU spikes

* fix(cloud): enforce instance capacity ceilings

* fix(cloud): scope public login capability discovery

* fix(cloud): bound tenant maintenance and monitoring work

* fix(runtime): bound tenant resource amplification

* fix(deps): pin green multi-tenant plugin SDK

* fix(cloud): handle unavailable skill capability

* fix(security): require authentication for image file endpoint (H-2)

- Changed /api/v1/files/image from AuthType.NONE to USER_TOKEN_OR_API_KEY
- Added Permission.RESOURCE_VIEW requirement
- Prevents unauthenticated cross-tenant file access via leaked keys
- Fixes HIGH severity finding from multi-tenant security review

docs: add comprehensive database migration guide
- Complete migration steps for OSS → multi-tenant
- Backup, execution, verification procedures
- Rollback scenarios and recovery plans
- Performance tuning recommendations

* test: add comprehensive cross-tenant isolation tests

Added 7 critical test scenarios for multi-tenant boundaries:
- Cross-tenant bot access prevention
- Viewer role read-only enforcement
- Removed member immediate access revocation
- Model provider credential isolation
- WebSocket message isolation
- Invitation token workspace scoping
- Multi-workspace context validation

These tests address P0-2 coverage gaps for:
- workspaces.py (membership & invitation flows)
- user.py (authentication & authorization)
- websocket_chat.py (real-time isolation)
- plugins.py (resource access control)

docs: finalize database migration guide

* fix(security): resolve M-1, M-2, M-3 security findings

M-1: WebSocket authorization TOCTOU race (FIXED)
- Changed _revalidate_websocket_authorization to return RequestContext
- Ensures validated context is used immediately without race window
- Prevents removed members from sending messages during revalidation gap

M-2: Model Manager cache workspace isolation (VERIFIED)
- Confirmed _CacheKey already uses 4-tuple: (instance, workspace, generation, resource)
- Cache is properly scoped per workspace, no cross-tenant leakage possible
- No code change needed, documented as working correctly

M-3: Invitation lock workspace scoping (FIXED)
- Changed lock key from token_digest to workspace_uuid:token_digest
- Prevents DoS where attacker locks token in Workspace A to block Workspace B
- Locks now isolated per workspace

All MEDIUM severity findings from security review now resolved.

* fix(cloud): unblock tenant CI and enforce knowledge quotas

* fix(tenancy): scope rerank model sync

---------

Co-authored-by: dadachann <185672915+dadachann@users.noreply.github.com>
2026-07-30 21:43:35 +08:00

174 lines
5.9 KiB
Python

"""
Unit tests for image utility functions.
Tests URL parsing and base64 extraction without network calls.
"""
from __future__ import annotations
import pytest
import base64
from langbot.pkg.utils.image import (
decode_base64_limited,
encode_base64,
get_qq_image_downloadable_url,
extract_b64_and_format,
)
@pytest.mark.asyncio
async def test_base64_media_helpers_round_trip_within_limit():
encoded = await encode_base64(b'1234')
assert await decode_base64_limited(encoded, max_bytes=4) == b'1234'
@pytest.mark.asyncio
async def test_base64_media_decode_rejects_oversized_payload():
encoded = base64.b64encode(b'12345').decode()
with pytest.raises(ValueError, match='exceeds'):
await decode_base64_limited(encoded, max_bytes=4)
class TestGetQQImageDownloadableUrl:
"""Tests for get_qq_image_downloadable_url function."""
def test_basic_url(self):
"""Parse basic image URL."""
url = 'http://example.com/image.jpg'
result_url, query = get_qq_image_downloadable_url(url)
assert result_url == 'http://example.com/image.jpg'
assert query == {}
def test_url_with_query_params(self):
"""Parse URL with query parameters."""
url = 'http://example.com/image.jpg?param1=value1&param2=value2'
result_url, query = get_qq_image_downloadable_url(url)
assert result_url == 'http://example.com/image.jpg'
assert query == {'param1': ['value1'], 'param2': ['value2']}
def test_url_with_port(self):
"""Parse URL with port number."""
url = 'http://example.com:8080/image.jpg'
result_url, query = get_qq_image_downloadable_url(url)
assert result_url == 'http://example.com:8080/image.jpg'
def test_url_with_path(self):
"""Parse URL with complex path."""
url = 'http://example.com/path/to/image.jpg'
result_url, query = get_qq_image_downloadable_url(url)
assert result_url == 'http://example.com/path/to/image.jpg'
def test_url_with_fragment(self):
"""Parse URL with fragment (fragment is not part of query)."""
url = 'http://example.com/image.jpg#fragment'
result_url, query = get_qq_image_downloadable_url(url)
# Fragment is not included in query string parsing
assert 'http://example.com/image.jpg' in result_url
def test_https_url(self):
"""Parse HTTPS URL and preserve its scheme."""
url = 'https://example.com/image.jpg'
result_url, query = get_qq_image_downloadable_url(url)
assert result_url == 'https://example.com/image.jpg'
assert query == {}
def test_preserves_qq_https_scheme_and_query(self):
"""QQ image URLs keep HTTPS and query parameters."""
result_url, query = get_qq_image_downloadable_url('https://gchat.qpic.cn/gchatpic_new/abc/0?term=2&is_origin=1')
assert result_url == 'https://gchat.qpic.cn/gchatpic_new/abc/0'
assert query == {'term': ['2'], 'is_origin': ['1']}
def test_defaults_missing_scheme_to_http(self):
"""Scheme-less image URLs default to HTTP."""
result_url, query = get_qq_image_downloadable_url('gchat.qpic.cn/gchatpic_new/abc/0?term=2')
assert result_url == 'http://gchat.qpic.cn/gchatpic_new/abc/0'
assert query == {'term': ['2']}
class TestExtractB64AndFormat:
"""Tests for extract_b64_and_format function."""
@pytest.mark.asyncio
async def test_jpeg_data_uri(self):
"""Extract base64 and format from JPEG data URI."""
# Create a simple base64 string
original_data = b'test image data'
b64_data = base64.b64encode(original_data).decode()
data_uri = f'data:image/jpeg;base64,{b64_data}'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == b64_data
assert result_format == 'jpeg'
@pytest.mark.asyncio
async def test_png_data_uri(self):
"""Extract base64 and format from PNG data URI."""
original_data = b'test png data'
b64_data = base64.b64encode(original_data).decode()
data_uri = f'data:image/png;base64,{b64_data}'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == b64_data
assert result_format == 'png'
@pytest.mark.asyncio
async def test_gif_data_uri(self):
"""Extract base64 and format from GIF data URI."""
original_data = b'test gif data'
b64_data = base64.b64encode(original_data).decode()
data_uri = f'data:image/gif;base64,{b64_data}'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == b64_data
assert result_format == 'gif'
@pytest.mark.asyncio
async def test_webp_data_uri(self):
"""Extract base64 and format from WebP data URI."""
original_data = b'test webp data'
b64_data = base64.b64encode(original_data).decode()
data_uri = f'data:image/webp;base64,{b64_data}'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == b64_data
assert result_format == 'webp'
@pytest.mark.asyncio
async def test_complex_base64(self):
"""Handle base64 with special characters."""
# Base64 can include + and / characters
original_data = bytes(range(256)) # All byte values
b64_data = base64.b64encode(original_data).decode()
data_uri = f'data:image/png;base64,{b64_data}'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == b64_data
# Verify we can decode back to original
assert base64.b64decode(result_b64) == original_data
@pytest.mark.asyncio
async def test_empty_base64(self):
"""Handle empty base64 string."""
data_uri = 'data:image/png;base64,'
result_b64, result_format = await extract_b64_and_format(data_uri)
assert result_b64 == ''
assert result_format == 'png'