[Security] Authenticate shared-memory multimodal cache handles (#59357)
Signed-off-by: Clinton Thomas <1033162+KernelClint@users.noreply.github.com> Co-authored-by: Lucas Bourtoule <35483370+dhalf@users.noreply.github.com> Co-authored-by: Cyrus Leung <tlleungac@connect.ust.hk>
This commit is contained in:
co-authored by
Lucas Bourtoule
Cyrus Leung
parent
72e7874fa6
commit
3d5625cc3c
@@ -108,10 +108,10 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
# Clear the buffer
|
||||
self.ring_buffer.clear()
|
||||
|
||||
# Check that metadata is empty and IDs reset
|
||||
# Check that metadata is empty and IDs keep increasing
|
||||
self.assertEqual(len(self.ring_buffer.metadata), 0)
|
||||
self.assertEqual(self.ring_buffer.monotonic_id_start, 0)
|
||||
self.assertEqual(self.ring_buffer.monotonic_id_end, 0)
|
||||
self.assertEqual(self.ring_buffer.monotonic_id_start, 3)
|
||||
self.assertEqual(self.ring_buffer.monotonic_id_end, 3)
|
||||
self.assertEqual(self.ring_buffer.data_buffer_start, 0)
|
||||
self.assertEqual(self.ring_buffer.data_buffer_end, 0)
|
||||
|
||||
|
||||
@@ -227,10 +227,68 @@ class TestSingleWriterShmObjectStorage(unittest.TestCase):
|
||||
self.assertEqual(len(self.storage.id_index), 0)
|
||||
self.assertEqual(len(self.storage.ring_buffer.metadata), 0)
|
||||
|
||||
# Verify that new items can be added after clearing
|
||||
# Verify that new items can be added after clearing. IDs keep
|
||||
# increasing so handles issued before the clear cannot alias new data.
|
||||
address, monotonic_id = self.storage.put("new_item", "new_value")
|
||||
self.assertIn("new_item", self.storage.key_index)
|
||||
self.assertEqual((address, monotonic_id), (0, 0))
|
||||
self.assertEqual((address, monotonic_id), (0, 5))
|
||||
|
||||
def _open_reader(self) -> SingleWriterShmObjectStorage:
|
||||
reader = SingleWriterShmObjectStorage.create_from_handle(self.storage.handle())
|
||||
self.addCleanup(reader.close)
|
||||
return reader
|
||||
|
||||
def test_reader_get_and_touch_each_require_valid_signature(self):
|
||||
address, monotonic_id = self.storage.put("key", "value")
|
||||
signature = self.storage.get_signature("key")
|
||||
reader = self._open_reader()
|
||||
|
||||
reader.touch("key", address, monotonic_id, signature)
|
||||
self.assertEqual(reader.get(address, monotonic_id, signature, "key"), "value")
|
||||
|
||||
flipped = [signature[0] ^ 1, *signature[1:]]
|
||||
for bad in (None, flipped, [signature], signature[:-1], [256] * 32):
|
||||
with self.assertRaisesRegex(ValueError, "SHM handle signature"):
|
||||
reader.get(address, monotonic_id, bad, "key")
|
||||
with self.assertRaisesRegex(ValueError, "SHM handle signature"):
|
||||
reader.touch("key", address, monotonic_id, bad)
|
||||
|
||||
def test_signature_is_bound_to_key_and_address(self):
|
||||
address, monotonic_id = self.storage.put("key", "value")
|
||||
signature = self.storage.get_signature("key")
|
||||
reader = self._open_reader()
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "SHM handle signature"):
|
||||
reader.get(address, monotonic_id, signature, "other_key")
|
||||
with self.assertRaisesRegex(ValueError, "SHM handle signature"):
|
||||
reader.get(address + 1, monotonic_id, signature, "key")
|
||||
|
||||
def test_writer_rejects_handle_no_longer_in_key_index(self):
|
||||
address, monotonic_id = self.storage.put("key", "value")
|
||||
signature = self.storage.get_signature("key")
|
||||
self.storage.verify_signature("key", address, monotonic_id, signature)
|
||||
|
||||
self.storage.clear()
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "SHM handle signature"):
|
||||
self.storage.verify_signature("key", address, monotonic_id, signature)
|
||||
|
||||
def test_handle_issued_before_clear_reads_own_data_until_reused(self):
|
||||
address, monotonic_id = self.storage.put("key", "value")
|
||||
signature = self.storage.get_signature("key")
|
||||
reader = self._open_reader()
|
||||
|
||||
self.storage.clear()
|
||||
|
||||
# Requests still draining after a clear keep reading their own data.
|
||||
self.assertEqual(reader.get(address, monotonic_id, signature, "key"), "value")
|
||||
|
||||
self.storage.put("key", "new_value")
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "modified or is invalid"):
|
||||
reader.get(address, monotonic_id, signature, "key")
|
||||
with self.assertRaisesRegex(ValueError, "modified or is invalid"):
|
||||
reader.touch("key", address, monotonic_id, signature)
|
||||
|
||||
|
||||
# Reader process function
|
||||
@@ -242,11 +300,11 @@ def reader_process(process_id, storage_handle, items_to_read):
|
||||
|
||||
errors = []
|
||||
|
||||
for key, original_value, address, monotonic_id in items_to_read:
|
||||
for key, original_value, address, monotonic_id, signature in items_to_read:
|
||||
time.sleep(random.random() / 100)
|
||||
try:
|
||||
# Read data from shared memory
|
||||
retrieved_value = reader_storage.get(address, monotonic_id)
|
||||
retrieved_value = reader_storage.get(address, monotonic_id, signature, key)
|
||||
|
||||
# Verify data integrity
|
||||
assert retrieved_value == original_value
|
||||
@@ -289,7 +347,8 @@ def run_multiprocess_example():
|
||||
for key, value in test_data:
|
||||
print(f"Storing {key}: {value}")
|
||||
address, monotonic_id = storage.put(key, value)
|
||||
stored_items.append((key, value, address, monotonic_id))
|
||||
signature = storage.get_signature(key)
|
||||
stored_items.append((key, value, address, monotonic_id, signature))
|
||||
print(f" -> Stored at address {address}, ID {monotonic_id}")
|
||||
|
||||
print("\n--- Retrieving Data ---")
|
||||
|
||||
@@ -15,14 +15,25 @@ from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_features import (
|
||||
placeholder_ranges_from_engine_input,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import (
|
||||
encode_mm_kwargs_item,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
MultiModalFeatures,
|
||||
PlaceholderRangeInfo,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.exceptions import GenerationError
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.multimodal.inputs import PlaceholderRange
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalBatchedField,
|
||||
MultiModalFieldElem,
|
||||
MultiModalKwargsItem,
|
||||
PlaceholderRange,
|
||||
)
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.renderers import renderer_from_config
|
||||
from vllm.renderers.online_renderer import OnlineRenderer
|
||||
@@ -285,6 +296,46 @@ async def test_non_stream_error():
|
||||
await serving.serve_tokens(request)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_serve_tokens_rejects_invalid_shm_handle_before_engine_handoff():
|
||||
engine = _mock_engine()
|
||||
engine.generate = MagicMock()
|
||||
serving = _build_serving_tokens(engine)
|
||||
cache = MagicMock()
|
||||
cache.validate_input_item.side_effect = ValueError(
|
||||
"Invalid SHM handle signature for cache key."
|
||||
)
|
||||
serving.online_renderer.renderer._mm_processor_cache = cache
|
||||
forged_item = MultiModalKwargsItem(
|
||||
{
|
||||
"address": MultiModalFieldElem(data=224, field=MultiModalBatchedField()),
|
||||
"monotonic_id": MultiModalFieldElem(
|
||||
data=4242,
|
||||
field=MultiModalBatchedField(),
|
||||
),
|
||||
}
|
||||
)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
features=MultiModalFeatures(
|
||||
mm_hashes={"image": ["image_A"]},
|
||||
mm_placeholders={"image": [PlaceholderRangeInfo(offset=0, length=1)]},
|
||||
kwargs_data={"image": [encode_mm_kwargs_item(forged_item)]},
|
||||
),
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
|
||||
assert isinstance(response, ErrorResponse)
|
||||
cache.validate_input_item.assert_called_once()
|
||||
validated_item, validated_hash = cache.validate_input_item.call_args.args
|
||||
assert validated_hash == "image_A"
|
||||
assert validated_item["address"].data == 224
|
||||
engine.generate.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_basic():
|
||||
"""Streaming returns SSE chunks with correct token_ids and ends with [DONE]."""
|
||||
|
||||
@@ -29,6 +29,7 @@ from vllm.multimodal.cache.base import (
|
||||
)
|
||||
from vllm.multimodal.hasher import MultiModalHasher
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalBatchedField,
|
||||
MultiModalFeatureSpec,
|
||||
MultiModalFieldElem,
|
||||
MultiModalKwargsItem,
|
||||
@@ -42,6 +43,7 @@ from vllm.utils.async_utils import make_async
|
||||
from vllm.utils.mem_constants import GiB_bytes, MiB_bytes
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.engine.llm_engine import LLMEngine
|
||||
from vllm.v1.serial_utils import MsgpackDecoder, MsgpackEncoder
|
||||
|
||||
from ..models.utils import build_model_context
|
||||
from ..utils import create_new_process_for_each_test
|
||||
@@ -778,6 +780,212 @@ def test_cache_eviction_shm_cache():
|
||||
_run_test_cache_eviction_shm(sender_cache, receiver_cache, base_item_size=MiB_bytes)
|
||||
|
||||
|
||||
def test_shm_receiver_requires_sender_handle_for_current_cache_key():
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(
|
||||
model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
|
||||
mm_processor_cache_type="shm",
|
||||
mm_shm_cache_max_object_size_mb=1,
|
||||
mm_processor_cache_gb=2 * MiB_bytes / GiB_bytes,
|
||||
),
|
||||
)
|
||||
sender_cache = ShmObjectStoreSenderCache(vllm_config)
|
||||
receiver_cache = ShmObjectStoreReceiverCache(vllm_config, mp.Lock())
|
||||
mm_hash = "image_A"
|
||||
item = MultiModalKwargsItem.dummy(1024)
|
||||
|
||||
try:
|
||||
sender_item, _ = sender_cache.get_and_update_item((item, []), mm_hash)
|
||||
|
||||
valid_feature = MultiModalFeatureSpec(
|
||||
data=sender_item,
|
||||
modality="image",
|
||||
identifier=mm_hash,
|
||||
mm_position=PlaceholderRange(offset=0, length=1),
|
||||
mm_hash=mm_hash,
|
||||
)
|
||||
receiver_cache.get_and_update_features([valid_feature])
|
||||
assert valid_feature.data == item
|
||||
|
||||
forged_item = MultiModalKwargsItem(
|
||||
{
|
||||
"address": sender_item["address"],
|
||||
"monotonic_id": sender_item["monotonic_id"],
|
||||
}
|
||||
)
|
||||
forged_feature = MultiModalFeatureSpec(
|
||||
data=forged_item,
|
||||
modality="image",
|
||||
identifier=mm_hash,
|
||||
mm_position=PlaceholderRange(offset=0, length=1),
|
||||
mm_hash=mm_hash,
|
||||
)
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
receiver_cache.get_and_update_features([forged_feature])
|
||||
|
||||
wrong_key = "image_B"
|
||||
wrong_key_feature = MultiModalFeatureSpec(
|
||||
data=sender_item,
|
||||
modality="image",
|
||||
identifier=wrong_key,
|
||||
mm_position=PlaceholderRange(offset=0, length=1),
|
||||
mm_hash=wrong_key,
|
||||
)
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
receiver_cache.get_and_update_features([wrong_key_feature])
|
||||
finally:
|
||||
receiver_cache._shm_cache.close()
|
||||
sender_cache.close()
|
||||
|
||||
|
||||
def test_shm_sender_handle_survives_engine_msgpack_round_trip():
|
||||
vllm_config = VllmConfig(
|
||||
model_config=ModelConfig(
|
||||
model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
|
||||
mm_processor_cache_type="shm",
|
||||
mm_shm_cache_max_object_size_mb=1,
|
||||
mm_processor_cache_gb=2 * MiB_bytes / GiB_bytes,
|
||||
),
|
||||
)
|
||||
sender_cache = ShmObjectStoreSenderCache(vllm_config)
|
||||
receiver_cache = ShmObjectStoreReceiverCache(vllm_config, mp.Lock())
|
||||
mm_hash = "image_A"
|
||||
item = MultiModalKwargsItem.dummy(1024)
|
||||
|
||||
try:
|
||||
sender_item, _ = sender_cache.get_and_update_item((item, []), mm_hash)
|
||||
encoded = MsgpackEncoder().encode(sender_item)
|
||||
decoded = MsgpackDecoder(MultiModalKwargsItem).decode(encoded)
|
||||
feature = MultiModalFeatureSpec(
|
||||
data=decoded,
|
||||
modality="image",
|
||||
identifier=mm_hash,
|
||||
mm_position=PlaceholderRange(offset=0, length=1),
|
||||
mm_hash=mm_hash,
|
||||
)
|
||||
|
||||
receiver_cache.get_and_update_features([feature])
|
||||
|
||||
assert feature.data == item
|
||||
finally:
|
||||
receiver_cache._shm_cache.close()
|
||||
sender_cache.close()
|
||||
|
||||
|
||||
def _small_shm_vllm_config() -> VllmConfig:
|
||||
return VllmConfig(
|
||||
model_config=ModelConfig(
|
||||
model="llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
|
||||
mm_processor_cache_type="shm",
|
||||
mm_shm_cache_max_object_size_mb=1,
|
||||
mm_processor_cache_gb=2 * MiB_bytes / GiB_bytes,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _with_elem(item: MultiModalKwargsItem, key: str, data) -> MultiModalKwargsItem:
|
||||
elems = dict(item)
|
||||
elems[key] = MultiModalFieldElem(data=data, field=MultiModalBatchedField())
|
||||
return MultiModalKwargsItem(elems)
|
||||
|
||||
|
||||
def test_shm_sender_validates_client_supplied_handles():
|
||||
sender_cache = ShmObjectStoreSenderCache(_small_shm_vllm_config())
|
||||
mm_hash = "image_A"
|
||||
|
||||
try:
|
||||
handle, _ = sender_cache.get_and_update_item(
|
||||
(MultiModalKwargsItem.dummy(1024), []), mm_hash
|
||||
)
|
||||
sender_cache.validate_input_item(handle, mm_hash)
|
||||
sender_cache.validate_input_item(MultiModalKwargsItem.dummy(16), mm_hash)
|
||||
|
||||
signature = handle["signature"].data
|
||||
forged = [
|
||||
_with_elem(handle, "signature", [signature[0] ^ 1, *signature[1:]]),
|
||||
_with_elem(handle, "signature", [signature]),
|
||||
_with_elem(handle, "address", True),
|
||||
_with_elem(handle, "address", -1),
|
||||
_with_elem(handle, "monotonic_id", 2**32),
|
||||
MultiModalKwargsItem(
|
||||
{"address": handle["address"], "monotonic_id": handle["monotonic_id"]}
|
||||
),
|
||||
]
|
||||
for item in forged:
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
sender_cache.validate_input_item(item, mm_hash)
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
sender_cache.validate_input_item(handle, "image_B")
|
||||
|
||||
sender_cache.clear_cache()
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
sender_cache.validate_input_item(handle, mm_hash)
|
||||
finally:
|
||||
sender_cache.close()
|
||||
|
||||
|
||||
def test_shm_receiver_rejects_out_of_range_handle_fields():
|
||||
vllm_config = _small_shm_vllm_config()
|
||||
sender_cache = ShmObjectStoreSenderCache(vllm_config)
|
||||
receiver_cache = ShmObjectStoreReceiverCache(vllm_config, mp.Lock())
|
||||
mm_hash = "image_A"
|
||||
|
||||
try:
|
||||
handle, _ = sender_cache.get_and_update_item(
|
||||
(MultiModalKwargsItem.dummy(1024), []), mm_hash
|
||||
)
|
||||
for key, value in [
|
||||
("address", -1),
|
||||
("address", 2**64),
|
||||
("monotonic_id", -1),
|
||||
("monotonic_id", 2**32),
|
||||
]:
|
||||
with pytest.raises(ValueError, match="SHM handle signature"):
|
||||
receiver_cache.get_and_update_item(
|
||||
_with_elem(handle, key, value), mm_hash
|
||||
)
|
||||
finally:
|
||||
receiver_cache._shm_cache.close()
|
||||
sender_cache.close()
|
||||
|
||||
|
||||
def test_shm_handle_issued_before_cache_clear():
|
||||
vllm_config = _small_shm_vllm_config()
|
||||
sender_cache = ShmObjectStoreSenderCache(vllm_config)
|
||||
receiver_cache = ShmObjectStoreReceiverCache(vllm_config, mp.Lock())
|
||||
mm_hash = "image_A"
|
||||
item = MultiModalKwargsItem.dummy(1024)
|
||||
|
||||
def feature(data: MultiModalKwargsItem) -> MultiModalFeatureSpec:
|
||||
return MultiModalFeatureSpec(
|
||||
data=data,
|
||||
modality="image",
|
||||
identifier=mm_hash,
|
||||
mm_position=PlaceholderRange(offset=0, length=1),
|
||||
mm_hash=mm_hash,
|
||||
)
|
||||
|
||||
try:
|
||||
stale_item, _ = sender_cache.get_and_update_item((item, []), mm_hash)
|
||||
sender_cache.clear_cache()
|
||||
|
||||
# A request still draining after the clear resolves to its own data.
|
||||
draining = feature(stale_item)
|
||||
receiver_cache.get_and_update_features([draining])
|
||||
assert draining.data == item
|
||||
|
||||
sender_cache.get_and_update_item(
|
||||
(MultiModalKwargsItem.dummy(2048), []),
|
||||
mm_hash,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="modified or is invalid"):
|
||||
receiver_cache.get_and_update_features([feature(stale_item)])
|
||||
finally:
|
||||
receiver_cache._shm_cache.close()
|
||||
sender_cache.close()
|
||||
|
||||
|
||||
def test_processor_cache_shared_across_loras():
|
||||
"""Test that processor cache uses mm_hash to share data across LoRAs."""
|
||||
model_config = ModelConfig(
|
||||
|
||||
Reference in New Issue
Block a user