Skip to content
Merged
5 changes: 5 additions & 0 deletions docs/changelog.d/851-gtheory-numpy-scalar-trust.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# G-theory NumPy scalar trust hardening

## Fixed

- Require exact package-supported NumPy integer and floating scalar classes for G-theory public numeric controls, rejecting caller-defined subclasses even when they spoof NumPy module metadata before any conversion callback can execute.
38 changes: 38 additions & 0 deletions docs/doctoring/gtheory_numpy_scalar_trust.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# G-theory NumPy scalar trust boundary

## Scope

`fast_mlsirm.gtheory` uses Python only to validate and marshal public controls before the compiled Rust G-theory kernels run. Protected-main validation distinguished supposedly trusted NumPy numeric scalars by checking both `isinstance(...)` and whether `type(value).__module__` started with `numpy`. Class metadata is caller-controlled for user-defined subclasses, so a subclass of a NumPy scalar could spoof that string and reach `int(...)` or `float(...)` with an overridden conversion method.

The correction replaces metadata-based trust with exact package-supported NumPy scalar type identities. Built-in Python controls retain their existing exact-type handling. Genuine NumPy integer and floating scalar classes remain accepted. User-defined subclasses are rejected before conversion or representation callbacks can execute, including subclasses that claim a `numpy` module name.

## Scientific boundary

This change does not alter generalizability-theory arithmetic. ANOVA sums of squares and mean squares, variance-component estimation, the repository's documented negative-component clamping policy for D-study quantities, generalizability/dependability coefficients, Phi(lambda), denominator handling, and all result-affecting numerical work remain Rust-owned. The worked Huebner and Lucht (2019) G-study/D-study reference cases remain the scientific oracle for the existing formulas; callback-safety tests only exercise Python control marshalling.

## Security and reliability interpretation

The defect is improper validation of a specified input type: caller-controlled metadata was used as evidence that conversion behavior belonged to NumPy. MITRE CWE-1287 recommends an accept-known-good validation strategy for expected input types. Exact scalar-class allowlists make that trust decision independent of caller-modifiable module metadata.

NIST SP 800-218, SSDF Version 1.1, remains the final secure-development baseline recorded here. NIST SP 800-218 Rev. 1 / SSDF Version 1.2 is an Initial Public Draft and is tracked as draft guidance rather than represented as final. OWASP ASVS 5.0.0 is the current stable ASVS release; its positive input-validation guidance is informative to this boundary without implying package certification or ASVS conformance.

## Verification contract

- a caller-defined `np.integer` subclass with spoofed NumPy module metadata must fail without executing `__int__` or `__repr__`;
- a caller-defined `np.floating` subclass with spoofed NumPy module metadata must fail without executing `__float__` or `__repr__`;
- accepted Python and genuine NumPy integer D-study sizes preserve their ordinary marshalled integer values;
- accepted Python and genuine NumPy real Phi(lambda) cuts preserve their ordinary finite values;
- booleans, non-positive D-study sizes, non-real controls, and non-finite cuts retain the existing stable validation errors;
- rejected controls never reach result-affecting Rust G-theory calls.

## References

Huebner, A., & Lucht, M. (2019). Generalizability theory in R. *Practical Assessment, Research, and Evaluation, 24*, Article 5. https://doi.org/10.7275/5065-gc10

MITRE. (2026). *CWE-1287: Improper validation of specified type of input (Version 4.20).* Common Weakness Enumeration. https://cwe.mitre.org/data/definitions/1287.html

National Institute of Standards and Technology. (2022). *Secure software development framework (SSDF) version 1.1: Recommendations for mitigating the risk of software vulnerabilities* (NIST Special Publication 800-218). https://doi.org/10.6028/NIST.SP.800-218

National Institute of Standards and Technology. (2025). *Secure software development framework (SSDF) version 1.2: Recommendations for mitigating the risk of software vulnerabilities* (NIST Special Publication 800-218 Rev. 1, Initial Public Draft). https://doi.org/10.6028/NIST.SP.800-218r1.ipd

OWASP Foundation. (n.d.). *OWASP Application Security Verification Standard 5.0.0.* https://owasp.org/www-project-application-security-verification-standard/
53 changes: 40 additions & 13 deletions python/fast_mlsirm/gtheory.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,45 @@
A primer*. Sage. (As cited in Huebner & Lucht, 2019; not read.)
"""

_NUMPY_INTEGER_SCALAR_TYPES = (
np.int8,
np.int16,
np.int32,
np.int64,
np.intp,
np.longlong,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
np.uintp,
np.ulonglong,
)
_NUMPY_FLOAT_SCALAR_TYPES = (
np.float16,
np.float32,
np.float64,
np.longdouble,
)

def _trusted_numpy_scalar(value: object, scalar_type: type[np.generic]) -> bool:
"""Return whether ``value`` is a package-trusted NumPy scalar family.

Validation must not execute arbitrary caller conversion hooks. Restricting
NumPy acceptance to scalar classes defined by NumPy keeps later ``int`` or
``float`` conversion inside a known implementation instead of accepting an
unrelated user subclass that only imitates the numeric protocol.
"""
def _has_exact_type(value: object, trusted_types: tuple[type, ...]) -> bool:
"""Return whether ``value`` has one exact trusted type without callbacks."""

value_type = type(value)
return any(value_type is trusted_type for trusted_type in trusted_types)


def _trusted_numpy_integer(value: object) -> bool:
"""Return whether ``value`` has an exact package-trusted NumPy integer type."""

return _has_exact_type(value, _NUMPY_INTEGER_SCALAR_TYPES)


def _trusted_numpy_float(value: object) -> bool:
"""Return whether ``value`` has an exact package-trusted NumPy float type."""

return isinstance(value, scalar_type) and type(value).__module__.startswith("numpy")
return _has_exact_type(value, _NUMPY_FLOAT_SCALAR_TYPES)


def _positive_integer_control(value: object, message: str) -> int:
Expand All @@ -48,7 +76,7 @@ def _positive_integer_control(value: object, message: str) -> int:
raise ValueError(message)
if type(value) is int:
parsed = value
elif _trusted_numpy_scalar(value, np.integer):
elif _trusted_numpy_integer(value):
parsed = int(value)
else:
raise ValueError(message)
Expand All @@ -62,11 +90,10 @@ def _finite_real_control(value: object, message: str) -> float:

if isinstance(value, (bool, np.bool_)):
raise ValueError(message)
if type(value) in (int, float):
value_type = type(value)
if value_type is int or value_type is float:
parsed = float(value)
elif _trusted_numpy_scalar(value, np.integer) or _trusted_numpy_scalar(
value, np.floating
):
elif _trusted_numpy_integer(value) or _trusted_numpy_float(value):
parsed = float(value)
else:
raise ValueError(message)
Expand Down
143 changes: 143 additions & 0 deletions tests/test_gtheory_numpy_scalar_subclass_trust.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Regression contracts for caller-defined NumPy scalar subclasses."""

from __future__ import annotations

import numpy as np
import pytest

import fast_mlsirm.gtheory as gtheory


class _NoNumericCore:
"""Core stub proving rejected controls never reach numerical dispatch."""

def gtheory_pi(self, *args, **kwargs):
raise AssertionError("invalid G-theory control reached Rust")

def phi_lambda(self, *args, **kwargs):
raise AssertionError("invalid Phi(lambda) control reached Rust")


def _pi_data() -> np.ndarray:
"""Return a minimal one-facet score matrix for marshalling tests."""

return np.array([[0.0, 1.0], [1.0, 0.0]], dtype=np.float64)


def test_pi_rejects_spoofed_numpy_integer_subclass_before_callbacks(monkeypatch) -> None:
"""NumPy-looking subclass metadata must not authorize integer coercion."""

calls: list[str] = []

class SpoofedNumpyInt(np.int64):
__module__ = "numpy"

def __int__(self) -> int:
calls.append("__int__")
raise AssertionError("caller integer conversion executed")

def __repr__(self) -> str:
calls.append("__repr__")
raise AssertionError("caller representation executed")

monkeypatch.setattr(gtheory, "_core_or_raise", lambda name: _NoNumericCore())

with pytest.raises(ValueError, match=r"n_i_prime entries must be positive integers"):
gtheory.gtheory_pi(_pi_data(), n_i_prime=[SpoofedNumpyInt(2)])

assert calls == []


def test_pi_rejects_hostile_scalar_metaclass_hash_before_callback(monkeypatch) -> None:
"""Integer type admission must not hash a caller-controlled metaclass."""

calls: list[str] = []

class HostileMeta(type):
def __hash__(cls) -> int:
calls.append("type-__hash__")
raise AssertionError("type hash callback executed")

class HostileNumpyInt(np.int64, metaclass=HostileMeta):
pass

monkeypatch.setattr(gtheory, "_core_or_raise", lambda name: _NoNumericCore())

with pytest.raises(ValueError, match=r"n_i_prime entries must be positive integers"):
gtheory.gtheory_pi(_pi_data(), n_i_prime=[HostileNumpyInt(2)])

assert calls == []


def test_phi_lambda_rejects_spoofed_numpy_float_subclass_before_callbacks(
monkeypatch,
) -> None:
"""NumPy-looking subclass metadata must not authorize float coercion."""

calls: list[str] = []

class SpoofedNumpyFloat(np.float64):
__module__ = "numpy"

def __float__(self) -> float:
calls.append("__float__")
raise AssertionError("caller float conversion executed")

def __repr__(self) -> str:
calls.append("__repr__")
raise AssertionError("caller representation executed")

monkeypatch.setattr(gtheory, "_core_or_raise", lambda name: _NoNumericCore())

with pytest.raises(ValueError, match=r"cut must be a finite real scalar"):
gtheory.phi_lambda(_pi_data(), SpoofedNumpyFloat(0.5), n_i_prime=[2])

assert calls == []


def test_phi_lambda_rejects_hostile_scalar_metaclass_hash_before_callback(
monkeypatch,
) -> None:
"""Float type admission must not hash a caller-controlled metaclass."""

calls: list[str] = []

class HostileMeta(type):
def __hash__(cls) -> int:
calls.append("type-__hash__")
raise AssertionError("type hash callback executed")

class HostileNumpyFloat(np.float64, metaclass=HostileMeta):
pass

monkeypatch.setattr(gtheory, "_core_or_raise", lambda name: _NoNumericCore())

with pytest.raises(ValueError, match=r"cut must be a finite real scalar"):
gtheory.phi_lambda(_pi_data(), HostileNumpyFloat(0.5), n_i_prime=[2])

assert calls == []


def test_phi_lambda_rejects_hostile_scalar_metaclass_equality_before_callback(
monkeypatch,
) -> None:
"""Float admission must not compare a caller-controlled metaclass for equality."""

calls: list[str] = []

class HostileMeta(type):
__hash__ = type.__hash__

def __eq__(cls, other: object) -> bool:
calls.append("type-__eq__")
raise AssertionError("type equality callback executed")

class HostileNumpyFloat(np.float64, metaclass=HostileMeta):
pass

monkeypatch.setattr(gtheory, "_core_or_raise", lambda name: _NoNumericCore())

with pytest.raises(ValueError, match=r"cut must be a finite real scalar"):
gtheory.phi_lambda(_pi_data(), HostileNumpyFloat(0.5), n_i_prime=[2])

assert calls == []
Loading