c5f900f3bd
- 体积守门改 UTF-8 字节数(原按字符数,"汉"*1500 约 4.5KB 可绕过 4096 上限)
- 字符串长度检查并入 _walk_props 递归,嵌套字符串同样受 MAX_STR_LEN 约束
(顺序:体积先行,故同一值既超长又超体积时报 properties_too_large)
- properties 传了但非 dict([]/""/0/None)不再被 or {} 静默放行,缺省键仍放行
Co-Authored-By: Claude Code <noreply@anthropic.com>
60 lines
2.5 KiB
Python
60 lines
2.5 KiB
Python
from datetime import datetime, timedelta
|
|
from django.utils import timezone
|
|
from tracker.services.validation import validate_event, sanitize_url
|
|
|
|
NOW = timezone.now()
|
|
|
|
def _ev(**kw):
|
|
base = dict(event_id="e1", event_name="page_view",
|
|
occurred_at=NOW, path="/p", title="t", properties={})
|
|
base.update(kw)
|
|
return base
|
|
|
|
def test_ok_event():
|
|
assert validate_event(_ev()) is None # None = 通过
|
|
|
|
def test_unknown_event_name():
|
|
assert validate_event(_ev(event_name="xxx")) == "event_name_not_allowed"
|
|
|
|
def test_sensitive_property_rejected():
|
|
r = validate_event(_ev(properties={"user_password": "1"}))
|
|
assert "sensitive" in r
|
|
|
|
def test_shape_type_and_whitelist():
|
|
assert validate_event(["x"]) == "event_invalid_shape"
|
|
assert validate_event(_ev(event_id=123)) == "invalid_event_id"
|
|
assert validate_event(_ev(properties={"foo": "bar"})) == "property_not_allowed"
|
|
|
|
def test_too_many_props_and_long_string():
|
|
r = validate_event(_ev(properties={f"k{i}": "v" for i in range(40)}))
|
|
assert "properties" in r
|
|
r = validate_event(_ev(properties={"referrer": "x" * 600}))
|
|
assert "properties" in r
|
|
|
|
def test_future_and_stale_time():
|
|
r = validate_event(_ev(occurred_at=NOW + timedelta(days=2)))
|
|
assert "occurred_at" in r # 超窗拒绝
|
|
assert validate_event(_ev(occurred_at=NOW - timedelta(hours=2))) is None # 窗内迟到可收
|
|
|
|
def test_sanitize_url_drops_sensitive_params():
|
|
u = sanitize_url("/p?email=a@b.com&token=x&id=3&utm_source=google&monkey=1")
|
|
assert "email=" not in u and "token=" not in u and "utm_source=google" in u
|
|
assert "monkey=1" in u # fullmatch:含 key 子串的正常参数不误伤
|
|
|
|
def test_nested_sensitive_key_rejected():
|
|
r = validate_event(_ev(properties={"utm": {"utm_a": 1, "user_password": "x"}}))
|
|
assert "sensitive" in r # utm 在 page_view 白名单内,嵌套敏感键仍须命中
|
|
|
|
def test_naive_datetime_rejected():
|
|
assert validate_event(_ev(occurred_at=NOW.replace(tzinfo=None))) == "invalid_occurred_at"
|
|
|
|
def test_prop_size_gate_counts_bytes():
|
|
r = validate_event(_ev(properties={"utm": {"a": "汉" * 1500}}))
|
|
assert r == "properties_too_large" # 字符数约 2K 未超,UTF-8 约 4.5KB 超 4096,须按字节算
|
|
|
|
def test_nested_string_length_capped():
|
|
assert validate_event(_ev(properties={"utm": {"a": "x" * 600}})) == "properties_too_long"
|
|
|
|
def test_falsy_non_dict_properties_rejected():
|
|
assert validate_event(_ev(properties=[])) == "properties_invalid"
|