| 1 |
"""Tests for the masking tools.""" |
| 2 |
|
| 3 |
import hashlib |
| 4 |
import hmac |
| 5 |
import importlib |
| 6 |
import sys |
| 7 |
import threading |
| 8 |
from types import ModuleType |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from asusrouter.tools.identifiers import MacAddress |
| 13 |
from asusrouter.tools.masking import _read_key_from_string |
| 14 |
|
| 15 |
MODULE = "asusrouter.tools.masking" |
| 16 |
ENV_KEY_NAME = "ASUSROUTER_MASK_KEY" |
| 17 |
|
| 18 |
TEST_KEY = "0f" * 32 |
| 19 |
TEST_MAC = "aa:bb:cc:11:22:33" |
| 20 |
|
| 21 |
|
| 22 |
def _reload_masking_with_env( |
| 23 |
monkeypatch: pytest.MonkeyPatch, env_value: str |
| 24 |
) -> ModuleType: |
| 25 |
"""Set up environment for testing masking.""" |
| 26 |
|
| 27 |
monkeypatch.setenv(ENV_KEY_NAME, env_value) |
| 28 |
|
| 29 |
# remove possibly cached module so env var is read at import time |
| 30 |
sys.modules.pop(MODULE, None) |
| 31 |
return importlib.import_module(MODULE) |
| 32 |
|
| 33 |
|
| 34 |
def _reload_masking(monkeypatch: pytest.MonkeyPatch) -> ModuleType: |
| 35 |
"""Reload the masking module without any environment variables.""" |
| 36 |
|
| 37 |
return _reload_masking_with_env(monkeypatch, TEST_KEY) |
| 38 |
|
| 39 |
|
| 40 |
@pytest.mark.parametrize( |
| 41 |
("key_str", "key"), |
| 42 |
[ |
| 43 |
# even-length valid hex (lowercase) |
| 44 |
("0f" * 32, bytes.fromhex("0f" * 32)), |
| 45 |
# even-length valid hex (uppercase) |
| 46 |
("0F" * 32, bytes.fromhex("0F" * 32)), |
| 47 |
# empty string -> fromhex('') -> b'' |
| 48 |
("", bytes.fromhex("")), |
| 49 |
# plain non-hex string -> fallback to UTF-8 encoding |
| 50 |
("my-secret-key", b"my-secret-key"), |
| 51 |
# invalid-hex characters (even length) -> fallback to encoding |
| 52 |
("zz" * 16, ("zz" * 16).encode()), |
| 53 |
# odd-length string -> fromhex would raise -> fallback to encoding |
| 54 |
("abc", b"abc"), |
| 55 |
], |
| 56 |
) |
| 57 |
def test_read_key_from_string(key_str: str, key: bytes) -> None: |
| 58 |
"""Test _read_key_from_string method.""" |
| 59 |
|
| 60 |
assert _read_key_from_string(key_str) == key |
| 61 |
|
| 62 |
|
| 63 |
@pytest.mark.parametrize("key", [TEST_KEY, "1234567890"]) |
| 64 |
def test_env_load(key: str, monkeypatch: pytest.MonkeyPatch) -> None: |
| 65 |
"""Test if environment variables are loaded correctly.""" |
| 66 |
|
| 67 |
# Set environment variable |
| 68 |
mod = _reload_masking_with_env(monkeypatch, key) |
| 69 |
|
| 70 |
# Check via the public API call |
| 71 |
assert mod.get_key_hex().lower() == key.lower() |
| 72 |
assert bytes.fromhex(mod.get_key_hex()) == bytes.fromhex(key) |
| 73 |
|
| 74 |
|
| 75 |
def test_configure_key_bytes( |
| 76 |
monkeypatch: pytest.MonkeyPatch, |
| 77 |
) -> None: |
| 78 |
"""Test configuring key with bytes sets the exact key.""" |
| 79 |
|
| 80 |
mod = _reload_masking(monkeypatch) |
| 81 |
|
| 82 |
# Set key |
| 83 |
key = b"13" * 32 |
| 84 |
mod.configure_key(key) |
| 85 |
|
| 86 |
# Test that the key is set correctly |
| 87 |
assert mod.get_key_hex() == key.hex() |
| 88 |
|
| 89 |
|
| 90 |
def test_configure_key_hex_string( |
| 91 |
monkeypatch: pytest.MonkeyPatch, |
| 92 |
) -> None: |
| 93 |
"""Test configuring key with hex string sets the expected key.""" |
| 94 |
|
| 95 |
mod = _reload_masking(monkeypatch) |
| 96 |
|
| 97 |
# Set key as hex string |
| 98 |
key_hex = "13" * 32 |
| 99 |
mod.configure_key(key_hex) |
| 100 |
|
| 101 |
# Test that the key is set correctly |
| 102 |
assert mod.get_key_hex() == key_hex.lower() |
| 103 |
|
| 104 |
|
| 105 |
def test_configure_key_any_string( |
| 106 |
monkeypatch: pytest.MonkeyPatch, |
| 107 |
) -> None: |
| 108 |
"""Test configuring key with plain string uses UTF-8 encoding.""" |
| 109 |
|
| 110 |
mod = _reload_masking(monkeypatch) |
| 111 |
|
| 112 |
# Set key as plain string |
| 113 |
s = "my-secret-key" |
| 114 |
mod.configure_key(s) |
| 115 |
|
| 116 |
# Test that the key is set correctly |
| 117 |
assert mod.get_key_hex() == s.encode().hex() |
| 118 |
|
| 119 |
|
| 120 |
def test_configure_key_none( |
| 121 |
monkeypatch: pytest.MonkeyPatch, |
| 122 |
) -> None: |
| 123 |
"""Test configuring key with None generates a new key.""" |
| 124 |
|
| 125 |
mod = _reload_masking(monkeypatch) |
| 126 |
|
| 127 |
# Set a defined key |
| 128 |
mod.configure_key(b"\x00" * 32) |
| 129 |
k1 = mod.get_key_hex() |
| 130 |
|
| 131 |
# Set key to None |
| 132 |
mod.configure_key(None) |
| 133 |
k2 = mod.get_key_hex() |
| 134 |
|
| 135 |
# Test that the key is set |
| 136 |
assert isinstance(k2, str) |
| 137 |
|
| 138 |
# Test that the key is different |
| 139 |
assert k1 != k2 |
| 140 |
|
| 141 |
|
| 142 |
def test_configure_key_affects_output( |
| 143 |
monkeypatch: pytest.MonkeyPatch, |
| 144 |
) -> None: |
| 145 |
"""Test that configuring the key affects the output.""" |
| 146 |
|
| 147 |
mod = _reload_masking(monkeypatch) |
| 148 |
|
| 149 |
mac = MacAddress.from_value(TEST_MAC) |
| 150 |
|
| 151 |
# Set key A |
| 152 |
mod.configure_key(b"A" * 32) |
| 153 |
m1 = mod.mask_mac(mac) |
| 154 |
|
| 155 |
# Set key B |
| 156 |
mod.configure_key(b"B" * 32) |
| 157 |
m2 = mod.mask_mac(mac) |
| 158 |
|
| 159 |
# Check that results are different |
| 160 |
assert m1 != m2 |
| 161 |
|
| 162 |
# Set again key A and check that the result is the same as the first |
| 163 |
mod.configure_key(b"A" * 32) |
| 164 |
m1b = mod.mask_mac(mac) |
| 165 |
assert m1 == m1b |
| 166 |
|
| 167 |
|
| 168 |
def test_masking_with_env(monkeypatch: pytest.MonkeyPatch) -> None: |
| 169 |
"""Test masking behavior with different environment configurations.""" |
| 170 |
|
| 171 |
mod = _reload_masking(monkeypatch) |
| 172 |
|
| 173 |
orig = TEST_MAC |
| 174 |
m1 = mod.mask_mac(orig) |
| 175 |
m2 = mod.mask_mac(orig) |
| 176 |
|
| 177 |
assert isinstance(m1, MacAddress) |
| 178 |
assert isinstance(m2, MacAddress) |
| 179 |
|
| 180 |
# Check that masking is deterministic |
| 181 |
assert m1 == m2 |
| 182 |
|
| 183 |
# Check that it differs from the original |
| 184 |
assert m1 != MacAddress.from_value(orig) |
| 185 |
|
| 186 |
|
| 187 |
def test_masked_mac_locally_administered( |
| 188 |
monkeypatch: pytest.MonkeyPatch, |
| 189 |
) -> None: |
| 190 |
"""Test that masked MAC is locally-administered.""" |
| 191 |
|
| 192 |
mod = _reload_masking(monkeypatch) |
| 193 |
|
| 194 |
masked = mod.mask_mac(TEST_MAC) |
| 195 |
|
| 196 |
# Get the first byte |
| 197 |
b0 = masked.to_bytes()[0] |
| 198 |
|
| 199 |
# Locally-administered bit set |
| 200 |
assert (b0 & 0x02) != 0 |
| 201 |
# Multicast bit cleared |
| 202 |
assert (b0 & 0x01) == 0 |
| 203 |
|
| 204 |
|
| 205 |
def test_mask_mac_invalid_input_raises( |
| 206 |
monkeypatch: pytest.MonkeyPatch, |
| 207 |
) -> None: |
| 208 |
"""Invalid MAC input should raise ValueError via MacAddress.from_value.""" |
| 209 |
|
| 210 |
mod = _reload_masking(monkeypatch) |
| 211 |
|
| 212 |
with pytest.raises(ValueError, match="MAC"): |
| 213 |
mod.mask_mac("not-a-mac") |
| 214 |
|
| 215 |
|
| 216 |
def test_configure_key_thread_safe(monkeypatch: pytest.MonkeyPatch) -> None: |
| 217 |
"""Test concurrent configure_key + mask_mac behavior.""" |
| 218 |
|
| 219 |
mod = _reload_masking(monkeypatch) |
| 220 |
|
| 221 |
# Writer changes the key repeatedly |
| 222 |
def writer(i: int) -> None: |
| 223 |
k = bytes([i % 256]) * 32 |
| 224 |
for _ in range(50): |
| 225 |
mod.configure_key(k) |
| 226 |
|
| 227 |
# Reader calls mask_mac repeatedly and records success/failure |
| 228 |
results: list[bytes | tuple[str, str]] = [] |
| 229 |
|
| 230 |
def reader() -> None: |
| 231 |
for _ in range(50): |
| 232 |
try: |
| 233 |
m = mod.mask_mac(TEST_MAC) |
| 234 |
results.append(m.to_bytes()) |
| 235 |
except Exception as ex: # noqa: BLE001 |
| 236 |
results.append(("err", str(ex))) |
| 237 |
|
| 238 |
writers = [threading.Thread(target=writer, args=(i,)) for i in range(4)] |
| 239 |
readers = [threading.Thread(target=reader) for _ in range(4)] |
| 240 |
|
| 241 |
for t in writers + readers: |
| 242 |
t.start() |
| 243 |
for t in writers + readers: |
| 244 |
t.join() |
| 245 |
|
| 246 |
# Ensure no reader observed exceptions |
| 247 |
assert all(not (isinstance(r, tuple) and r[0] == "err") for r in results) |
| 248 |
# And at least some successful reads happened |
| 249 |
assert len(results) > 0 |
| 250 |
|
| 251 |
|
| 252 |
def test_hmac_digest_thread_safe(monkeypatch: pytest.MonkeyPatch) -> None: |
| 253 |
"""_hmac_digest must produce the same result when invoked concurrently.""" |
| 254 |
|
| 255 |
mod = _reload_masking(monkeypatch) |
| 256 |
|
| 257 |
key_bytes = bytes.fromhex(TEST_KEY) |
| 258 |
data = b"concurrent-payload" |
| 259 |
expected = hmac.new(key_bytes, data, hashlib.sha256).digest() |
| 260 |
|
| 261 |
threads_count = 16 |
| 262 |
results: list[bytes | None] = [None] * threads_count |
| 263 |
|
| 264 |
def worker(idx: int) -> None: |
| 265 |
"""Call the module-level helper without passing explicit key.""" |
| 266 |
|
| 267 |
results[idx] = mod._hmac_digest(data, None) |
| 268 |
|
| 269 |
threads = [ |
| 270 |
threading.Thread(target=worker, args=(i,)) |
| 271 |
for i in range(threads_count) |
| 272 |
] |
| 273 |
for t in threads: |
| 274 |
t.start() |
| 275 |
for t in threads: |
| 276 |
t.join() |
| 277 |
|
| 278 |
assert all(r == expected for r in results) |
| 279 |
|
| 280 |
|
| 281 |
def test_hmac_digest_with_key(monkeypatch: pytest.MonkeyPatch) -> None: |
| 282 |
"""Test _hmac_digest with a specific key.""" |
| 283 |
|
| 284 |
mod = _reload_masking(monkeypatch) |
| 285 |
|
| 286 |
key = bytes.fromhex(TEST_KEY) |
| 287 |
data = b"payload" |
| 288 |
expected = hmac.new(key, data, hashlib.sha256).digest() |
| 289 |
|
| 290 |
result = mod._hmac_digest(data, key) |
| 291 |
assert result == expected |