You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by as...@apache.org on 2026/05/02 14:57:00 UTC

(tooling-agents) branch main updated: ASVS audit: 5.2.2.md (redacted)

This is an automated email from the ASF dual-hosted git repository.

asf-tooling pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-agents.git


The following commit(s) were added to refs/heads/main by this push:
     new c333ddc  ASVS audit: 5.2.2.md (redacted)
c333ddc is described below

commit c333ddcc4cb133adc6aec5e4b4bcbd9ab05e348a
Author: ASF Tooling Team <ro...@apache.org>
AuthorDate: Sat May 2 16:56:16 2026 +0200

    ASVS audit: 5.2.2.md (redacted)
---
 ASVS/reports/mahout/245aad3/ch05_general/5.2.2.md | 424 ++++++++++++++++++++++
 1 file changed, 424 insertions(+)

diff --git a/ASVS/reports/mahout/245aad3/ch05_general/5.2.2.md b/ASVS/reports/mahout/245aad3/ch05_general/5.2.2.md
new file mode 100644
index 0000000..ff02392
--- /dev/null
+++ b/ASVS/reports/mahout/245aad3/ch05_general/5.2.2.md
@@ -0,0 +1,424 @@
+# ASVS 5.2.2 Security Audit Report
+
+## Executive Summary
+
+- **Repository:** apache/mahout
+- **Audit Date:** May 02, 2026
+- **Auditor:** Tooling Agents
+- **ASVS Requirement:** 5.2.2 — Verify that when the application accepts a file, either on its own or within an archive such as a zip file, it checks if the file extension matches an expected file extension and validates that the contents correspond to the type represented by the extension. This includes, but is not limited to, checking the initial 'magic bytes', performing image re-writing, and using specialized libraries for file content validation. For L1, this can focus just on files [...]
+- **Files Analyzed:** 21 relevant out of 393 total, 35 skipped
+
+### Finding Summary
+
+| Severity | Count | Description |
+|----------|-------|-------------|
+| Critical | 0 | No critical findings |
+| High | 0 | No high severity findings |
+| Medium | 2 | Missing extension validation in loader APIs; No magic byte validation |
+| Low | 1 | Python fallback path lacks content validation |
+| **Total** | **3** | **All findings relate to missing content validation controls** |
+
+---
+
+## Security Controls Inventory
+
+| Control | Location | Description | Coverage |
+|---------|----------|-------------|----------|
+| Extension allowlist | `engine.rs:encode_from_file()` L445-495 | Checks extension before dispatching | `encode()` path only |
+| Extension allowlist (Python fallback) | `loader.py:_pytorch_file_iter()` L310-320 | Checks against `_FALLBACK_FILE_EXTS` | PyTorch fallback path |
+| Streaming format restriction | `loader.py:source_file()` L192-196 | Streaming restricted to `.parquet` | Builder validation |
+| Remote URL sanitization | `loader.py:source_file()` L185-188 | Rejects query/fragment in remote URLs | Builder validation |
+| TensorFlow dtype validation | `tensorflow_io.rs` tests | Reader validates DT_DOUBLE, rejects DT_FLOAT | Core library level |
+| TensorFlow shape validation | `tensorflow_io.rs` tests | Reader rejects unsupported ranks | Core library level |
+| TensorFlow size validation | `tensorflow_io.rs` tests | Reader detects size mismatches | Core library level |
+| Pickle safety | `loader.py:_pytorch_file_iter()` L324 | `torch.load(weights_only=True)` | PyTorch fallback path |
+| Unsupported format rejection | `engine.rs` L491-495 | Returns error for unknown extensions | `encode()` path only |
+| **Magic byte / content validation** | **NONE** | **No pre-parse content-type verification** | **None** |
+
+### Coverage Analysis: Extension Validation
+
+| Entry Point | Extension Check | Content Validation | Gap Type |
+|-------------|-----------------|-------------------|----------|
+| `QdpEngine.encode(path_string)` | ✅ `encode_from_file()` | ❌ No magic bytes | Standard |
+| `QdpEngine.encode(pathlib.Path)` | ✅ `encode_from_file()` | ❌ No magic bytes | Standard |
+| `QdpEngine.create_file_loader()` | ❌ **No check** | ❌ No magic bytes | **Type A** |
+| `QdpEngine.create_streaming_file_loader()` | ❌ **No check** | ❌ No magic bytes | **Type A** |
+| `QuantumDataLoader.source_file()` (Rust) | ❌ Only streaming restriction | ❌ No magic bytes | **Type A** |
+| `QuantumDataLoader._pytorch_file_iter()` | ✅ `_FALLBACK_FILE_EXTS` | ❌ No magic bytes | Standard |
+
+---
+
+## Critical File Review
+
+| File | Role | Extension Check | Magic Bytes | Content Validation | Risk |
+|------|------|-----------------|-------------|-------------------|------|
+| `engine.rs` | Main file routing | ✅ `encode_from_file` | ❌ | ⚠️ Via parsing libraries | MEDIUM |
+| `engine.rs` | Loader factory | ❌ | ❌ | ⚠️ Via core library | MEDIUM |
+| `loader.py` | Python file iter | ✅ `_FALLBACK_FILE_EXTS` | ❌ | ⚠️ Via torch/numpy | LOW |
+| `loader.rs` | Path extraction | N/A (utility) | N/A | N/A | LOW |
+
+---
+
+## Findings
+
+### Medium Severity
+
+#### ASVS-522-MED-001: Missing Extension Validation in Loader Factory Methods
+
+**Severity:** MEDIUM  
+**Gap Type:** Type A — Entry points with no extension validation
+
+**Location:**
+- **File:** `qdp/qdp-python/src/engine.rs`
+- **Functions:** `create_file_loader_impl` (L543-578), `create_streaming_file_loader_impl` (L580-620)
+
+**Related Functions Checked:**
+- `path_from_py()` — String extraction only, no validation
+- `PipelineIterator::new_from_file()` — Core library call
+
+**Description:**
+
+The loader factory methods (`create_file_loader_impl` and `create_streaming_file_loader_impl`) accept file paths but perform no extension validation before passing them to the core pipeline iterator. This creates an inconsistency with the `encode_from_file()` method, which does validate extensions against an allowlist.
+
+**Vulnerable Code:**
+
+```rust
+fn create_file_loader_impl(
+    &self,
+    py: Python<'_>,
+    path: &Bound<'_, PyAny>,
+    batch_size: usize,
+    num_qubits: u32,
+    encoding_method: &str,
+    batch_limit: Option<usize>,
+    null_handling: Option<&str>,
+) -> PyResult<PyQuantumLoader> {
+    let path_str = path_from_py(path)?;  // <-- no extension validation
+    // ... path goes directly to PipelineIterator::new_from_file
+    let iter = py
+        .detach(|| {
+            qdp_core::PipelineIterator::new_from_file(
+                engine,
+                path_str.as_str(),  // <-- raw path passed to core
+                config,
+                batch_limit,
+            )
+        })
+```
+
+**Data Flow:**
+
+```
+Python user path → path_from_py() (string extraction only) → PipelineIterator::new_from_file() (no extension check at binding layer)
+```
+
+**Proof of Concept:**
+
+```python
+engine = QdpEngine(device_id=0)
+# Passes a .csv or .html file directly to the pipeline reader
+# No extension validation at the binding layer
+loader = engine.create_file_loader(
+    path="/tmp/malicious.csv",  # or any unsupported extension
+    batch_size=64,
+    num_qubits=16,
+    encoding_method="amplitude"
+)
+```
+
+**Impact:**
+
+Files with unsupported or misleading extensions bypass the extension validation present in `encode_from_file()`. While the core library likely performs its own format detection, this inconsistency means the loader API has weaker validation than the `encode()` API, creating a defense-in-depth gap. If the core library's format detection relies on the same extension-based routing without magic byte checks, a misnamed file would be routed to the wrong parser.
+
+**Remediation:**
+
+```rust
+fn create_file_loader_impl(
+    &self,
+    py: Python<'_>,
+    path: &Bound<'_, PyAny>,
+    // ...
+) -> PyResult<PyQuantumLoader> {
+    let path_str = path_from_py(path)?;
+    
+    // Validate extension before passing to core
+    let supported = [".parquet", ".arrow", ".feather", ".ipc", ".npy", ".pt", ".pth", ".pb"];
+    let path_lower = path_str.to_ascii_lowercase();
+    if !supported.iter().any(|ext| path_lower.ends_with(ext)) {
+        return Err(PyRuntimeError::new_err(format!(
+            "Unsupported file format for loader. Expected one of {:?}, got: {}",
+            supported, path_str
+        )));
+    }
+    // ... continue with existing logic
+```
+
+---
+
+#### ASVS-522-MED-002: No Magic Byte Validation in Main File Routing
+
+**Severity:** MEDIUM  
+**Gap Type:** Type B — Extension control exists but no content validation control
+
+**Location:**
+- **File:** `qdp/qdp-python/src/engine.rs`
+- **Function:** `encode_from_file()` (L445-495)
+
+**Related Functions Checked:**
+- `encode_from_parquet()` — Format-specific parser
+- `encode_from_tensorflow()` — Format-specific parser
+- `encode_from_numpy()` — Format-specific parser
+- `encode_from_pytorch()` — Format-specific parser
+
+**Description:**
+
+The `encode_from_file()` method validates file extensions against an allowlist but does not verify that file contents match the expected format before dispatching to format-specific parsers. This allows files with valid extensions but mismatched content to be processed by the wrong parser.
+
+**Vulnerable Code:**
+
+```rust
+fn encode_from_file(
+    &self,
+    path: &str,
+    num_qubits: usize,
+    encoding_method: &str,
+) -> PyResult<QuantumTensor> {
+    // Extension check exists (positive)
+    let ptr = if path.ends_with(".parquet") {
+        self.core_engine()?
+            .encode_from_parquet(path, num_qubits, encoding_method)  // no magic byte check before this
+    // ... other extensions ...
+    } else if path.ends_with(".pb") {
+        self.core_engine()?
+            .encode_from_tensorflow(path, num_qubits, encoding_method)  // no magic byte check
+    } else {
+        return Err(PyRuntimeError::new_err(format!(
+            "Unsupported file format..."
+        )));
+    };
+```
+
+**Data Flow:**
+
+```
+User file path → extension check (allowlist) → [MISSING: magic byte verification] → format-specific parser
+```
+
+**Proof of Concept:**
+
+```python
+import struct
+engine = QdpEngine(device_id=0)
+
+# Create a file with .npy extension but Parquet content
+# (or any mismatched content)
+with open("/tmp/disguised.npy", "wb") as f:
+    f.write(b"PAR1...")  # Parquet magic bytes in a .npy file
+
+# This passes extension validation but routes to NumPy reader
+# instead of Parquet reader
+engine.encode("/tmp/disguised.npy", num_qubits=4)
+```
+
+**Impact:**
+
+A file with a valid extension but mismatched content is routed to the wrong format parser. While format-specific parsing libraries (arrow-rs, ndarray-npy, prost) generally reject structurally invalid input, the error messages will be confusing, and the parser processes potentially adversarial data under incorrect assumptions about its structure. With `remote-io` enabled, files from S3/GCS increase the attack surface. This is particularly relevant for `.pb` (protobuf) files where the pars [...]
+
+**Remediation:**
+
+```rust
+use std::fs::File;
+use std::io::Read;
+
+/// Check file magic bytes match expected format
+fn validate_magic_bytes(path: &str, expected_ext: &str) -> PyResult<()> {
+    let mut file = File::open(path)
+        .map_err(|e| PyRuntimeError::new_err(format!("Cannot open file: {}", e)))?;
+    let mut header = [0u8; 8];
+    let n = file.read(&mut header)
+        .map_err(|e| PyRuntimeError::new_err(format!("Cannot read file header: {}", e)))?;
+    
+    match expected_ext {
+        ".parquet" if n >= 4 => {
+            if &header[..4] != b"PAR1" {
+                return Err(PyRuntimeError::new_err(
+                    "File has .parquet extension but does not start with Parquet magic bytes"
+                ));
+            }
+        }
+        ".npy" if n >= 6 => {
+            if header[0] != 0x93 || &header[1..6] != b"NUMPY" {
+                return Err(PyRuntimeError::new_err(
+                    "File has .npy extension but does not start with NumPy magic bytes"
+                ));
+            }
+        }
+        ".arrow" | ".feather" if n >= 6 => {
+            if &header[..6] != b"ARROW1" {
+                return Err(PyRuntimeError::new_err(
+                    "File has Arrow extension but does not start with Arrow magic bytes"
+                ));
+            }
+        }
+        // .pt/.pth (pickle/zip) and .pb (protobuf) have less distinctive magic bytes
+        // but basic structural checks can still be applied
+        _ => {} // Other formats: rely on parser validation
+    }
+    Ok(())
+}
+```
+
+---
+
+### Low Severity
+
+#### ASVS-522-LOW-003: Python Fallback Path Lacks Content Validation
+
+**Severity:** LOW  
+**Gap Type:** Standard — Extension validated, content not validated
+
+**Location:**
+- **File:** `qdp/qdp-python/qumat_qdp/loader.py`
+- **Function:** `_pytorch_file_iter()` (L300-340)
+
+**Related Functions Checked:**
+- `torch.load()` — PyTorch deserialization
+- `np.load()` — NumPy format loading
+
+**Description:**
+
+The Python fallback path for PyTorch file iteration validates file extensions against an allowlist but does not verify magic bytes before loading files with `torch.load()` or `np.load()`.
+
+**Vulnerable Code:**
+
+```python
+def _pytorch_file_iter(self, torch, encode_fn, device: str) -> Iterator[object]:
+    ext = os.path.splitext(path)[1].lower()
+
+    if ext not in _FALLBACK_FILE_EXTS:
+        raise RuntimeError(...)
+
+    # Load all data into memory — no magic byte check
+    if ext in _TORCH_FILE_EXTS:
+        raw = torch.load(path, weights_only=True)  # pickle deserialization
+    else:
+        arr = np.load(path)  # NumPy format loading
+```
+
+**Data Flow:**
+
+```
+User file path → extension check (allowlist) → [MISSING: magic byte check] → torch.load() or np.load()
+```
+
+**Impact:**
+
+Lower severity because: (1) `torch.load(weights_only=True)` prevents arbitrary code execution from pickle, (2) `np.load()` validates NumPy format headers internally, (3) this is an explicit fallback path when the Rust extension is unavailable. The main risk is processing mismatched content under incorrect format assumptions.
+
+**Remediation:**
+
+Add magic byte checks before calling `torch.load()` and `np.load()`, similar to the Rust remediation above:
+
+```python
+def _validate_magic_bytes(path: str, expected_ext: str) -> None:
+    """Validate file magic bytes match expected format."""
+    with open(path, 'rb') as f:
+        header = f.read(8)
+    
+    if expected_ext == '.npy':
+        if len(header) < 6 or header[0] != 0x93 or header[1:6] != b'NUMPY':
+            raise RuntimeError(
+                f"File has .npy extension but does not start with NumPy magic bytes"
+            )
+    elif expected_ext in ('.pt', '.pth'):
+        # Check for pickle or zip magic bytes
+        if len(header) >= 2:
+            if header[:2] not in (b'PK', b'\x80\x02', b'\x80\x03', b'\x80\x04'):
+                raise RuntimeError(
+                    f"File has PyTorch extension but does not have expected magic bytes"
+                )
+```
+
+---
+
+## Positive Security Patterns
+
+| Pattern | Location | Description |
+|---------|----------|-------------|
+| Extension allowlist | `engine.rs:encode_from_file()` | Comprehensive allowlist with explicit rejection of unknown extensions |
+| `weights_only=True` | `loader.py:_pytorch_file_iter()` L324 | Prevents pickle deserialization attacks for `.pt`/`.pth` files |
+| TensorFlow content validation | Core library (evidenced by tests) | Validates dtype (DT_DOUBLE required), tensor rank (rejects 3D+), and size consistency |
+| Remote URL sanitization | `loader.py:source_file()` L185-188 | Rejects query parameters and fragments in remote URLs |
+| Streaming restriction | `loader.py:source_file()` L192-196 | Streaming limited to `.parquet` only |
+| Error propagation | `engine.rs` throughout | Format-specific parse errors are propagated as `PyRuntimeError` with descriptive messages |
+| Input type auto-detection | `engine.rs:encode_with_core()` | Uses duck-typing (`__array_interface__`, `__fspath__`, PyTorch checks) to safely route inputs |
+| Encoding method validation | `engine.rs` constructor | Precision and backend validated against strict allowlists |
+| Seed range validation | `loader.py:_validate_loader_args()` | Seed checked against Rust u64 range to prevent overflow |
+| Mutual exclusion enforcement | `loader.py:_create_iterator()` | Prevents conflicting synthetic + file source configuration |
+
+---
+
+## Architecture Observations
+
+1. **Two distinct file handling paths:** The `encode()` API and the loader factory APIs (`create_file_loader`/`create_streaming_file_loader`) take different code paths. Only `encode()` has extension validation at the binding layer. This inconsistency increases maintenance risk.
+
+2. **Defense-in-depth through parsing libraries:** While no explicit magic byte checks exist, the format-specific libraries (arrow-rs, ndarray-npy, prost, tch) perform structural validation during parsing. This provides a safety net that prevents silent misinterpretation, though error messages for mismatched content will be confusing rather than descriptive.
+
+3. **Remote I/O extends trust boundary:** When the `remote-io` feature is enabled, files from S3/GCS pass through the same validation (or lack thereof). The `resolve_path` function downloads to a temp file which is then processed identically to local files. This makes magic byte validation more important since remote files have a wider threat model than local user files.
+
+4. **Known false positive acknowledgment:** The acceptance of multiple untrusted file formats is intentional. The findings above focus specifically on the gap between extension validation (which exists) and content validation (which is absent at the pre-parse stage).
+
+---
+
+## Recommendations Summary
+
+### Immediate Actions (High Priority)
+
+| Priority | Recommendation | Effort | Impact |
+|----------|---------------|--------|--------|
+| 1 | Add extension validation to `create_file_loader_impl` and `create_streaming_file_loader_impl` to match `encode_from_file()` coverage | Low | Eliminates inconsistency between API surfaces |
+| 2 | Add magic byte validation for formats with well-known signatures (`.parquet` → `PAR1`, `.npy` → `\x93NUMPY`, `.arrow` → `ARROW1`) in `encode_from_file()` | Medium | Defense-in-depth; early rejection of mismatched files |
+
+### Short-term Actions
+
+| Priority | Recommendation | Effort | Impact |
+|----------|---------------|--------|--------|
+| 3 | Extract extension validation into a shared helper function used by both `encode_from_file()` and loader factory methods | Low | Prevents future divergence |
+| 4 | Add magic byte validation to the Python fallback path (`_pytorch_file_iter`) for `.npy` files | Low | Consistent validation across all code paths |
+
+### Long-term Actions
+
+| Priority | Recommendation | Effort | Impact |
+|----------|---------------|--------|--------|
+| 5 | For `remote-io` paths specifically, consider mandatory magic byte validation since files cross a trust boundary | Medium | Reduces risk from external file sources |
+
+---
+
+## Appendix: Files Analyzed
+
+<details>
+<summary>Click to expand list of 21 files analyzed</summary>
+
+- `qdp/qdp-python/src/engine.rs` (relevance: 7)
+- `qdp/qdp-python/qumat_qdp/loader.py` (relevance: 6)
+- `website/versioned_docs/version-0.4/qdp/readers.md` (relevance: 6)
+- `qdp/qdp-core/tests/parquet_io.rs` (relevance: 5)
+- `qdp/qdp-core/tests/tensorflow_io.rs` (relevance: 5)
+- `qdp/qdp-core/tests/torch_io.rs` (relevance: 5)
+- `testing/qdp/test_numpy.py` (relevance: 5)
+- `docs/qdp/api.md` (relevance: 4)
+- `docs/qdp/python-api.md` (relevance: 4)
+- `qdp/qdp-core/tests/numpy.rs` (relevance: 4)
+- `qdp/qdp-python/benchmark/benchmark_numpy_io.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/cpu_baseline/svhn_kernel_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/pennylane_baseline/iris_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/pennylane_baseline/mnist_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/pennylane_baseline/svhn_iqp.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/qdp_pipeline/iris_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/qdp_pipeline/mnist_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/qdp_pipeline/svhn_iqp.py` (relevance: 4)
+- `qdp/qdp-python/benchmark/encoding_benchmarks/qdp_pipeline/svhn_kernel_amplitude.py` (relevance: 4)
+- `qdp/qdp-python/src/loader.rs` (relevance: 4)
+- `testing/qdp_python/test_quantum_data_loader.py` (relevance: 4)
+
+</details>
\ No newline at end of file


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org