Skip to content

Add support for string, binary, and base64 payload sanitization with tests#3

Merged
shaunluedeke merged 1 commit into
masterfrom
add-string-and-base64-support
Jun 2, 2026
Merged

Add support for string, binary, and base64 payload sanitization with tests#3
shaunluedeke merged 1 commit into
masterfrom
add-string-and-base64-support

Conversation

@shaunluedeke

@shaunluedeke shaunluedeke commented Jun 2, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Neue Features

    • Neue Methoden für die Verarbeitung von String-, Binär- und Base64-Eingabedaten
    • Automatische MIME-Typ-Erkennung mit Heuristiken
    • Unterstützung für Python-ähnliche Bytes-Literale und Data-URIs
  • Dokumentation

    • README erweitert mit Beispielen zur Eingabeverarbeitung
  • Tests

    • Tests für die neue Funktionalität hinzugefügt

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Die FileSanitizer-Klasse wird um drei neue öffentliche Methoden erweitert, um Roh-Payloads, Binärdaten und Base64-/Data-URI-Eingaben direkt zu verarbeiten. Ein interner Orchestrator normalisiert Eingaben, erstellt temporäre Dateien, erkennt MIME-Typen automatisch, delegiert an die bestehende Verarbeitung und räumt Ressourcen auf. Umfangreiche Tests validieren HTML-Sanitisierung, MIME-Erkennung und Base64-Handling.

Changes

Neue Eingabe-Verarbeitungs-Entry-Points

Layer / File(s) Summary
Öffentliche API-Entry-Points für Eingabeformate
src/FileSanitizer.php, README.md
Neue öffentliche Methoden processString(), processBinary() und processBase64() sowie Convenience-Wrapper sanitizeAlways() ermöglichen direkte Verarbeitung von String-Payloads, Binärdaten und Base64-Daten. Die process()-Methode delegiert direkt an processWithMimeType(). README dokumentiert die neuen APIs mit Beispielen für Verwendung mit optionalen filenameHint- und mimeType-Parametern.
Interne Datenverarbeitungs-Orchestrierung
src/FileSanitizer.php
processDataInput() orchestriert den zentralen Fluss: optionale Eingabe-Normalisierung, Erstellung temporärer Eingabedateien, Delegierung an processWithMimeType(), Auslesen sanitisierter Ausgabedaten und robustes Cleanup (Temp-Dateien, optionale Output-Dateien, leere Verzeichnisse) im finally-Block.
MIME-Typ-Erkennung und Eingabe-Vorbereitung
src/FileSanitizer.php
Helper-Funktionen detectMimeTypeFromData() (mit finfo_buffer und Heuristik-Matching für PDF/SVG/HTML/JSON), extractBase64Payload() (Data-URI-Präfix-Entfernung), extractDataUriMimeType() (Regex-basierte MIME-Extraktion), normalizeStringInput() (Python-ähnliche Bytes-Literal-Verarbeitung mit stripcslashes) und createTempInputPath() (sichere Generierung mit Endungs-Ableitung und zufälligen Temp-Verzeichnissen).
Datei- und Verzeichnis-Lifecycle-Helpers
src/FileSanitizer.php
readFileIfExists() liest Inhalte mit Fehlerbehandlung, safeUnlink() entfernt nur existente Dateien, cleanupEmptyDir() bereinigt leere Verzeichnisse – alle mit unterdrückten Fehlern für robuste Ressourcenbereinigung.
Integration in bestehende Verarbeitungs-Pipeline
src/FileSanitizer.php
Updates zu processWithMimeType() als zentraler Verarbeitungsweg, resolveSanitizer() zur Sanitizer-Auswahl, defaultOutputPath() zur Standard-Pfad-Ableitung mit .sanitized-Suffix, sowie Import von Exception für Dateisystem-Fehlerbehandlung.
Test-Suite für Eingabeverarbeitung
tests/Sanitizer/FileSanitizerInputStringTest.php
Neue PHPUnit-Testklasse mit 5 Tests: HTML-Sanitisierung bei String-Payloads, MIME-Typ-Erkennung aus Payload (doctype), Base64-Dekodierung mit Data-URI-Unterstützung und Konsistenz-Validierung zwischen sanitizedData/sanitizedBase64, Python-ähnliche Bytes-Literal-Verarbeitung und Binary-PNG-Verarbeitung mit Signatur-Validierung.

🎯 3 (Moderate) | ⏱️ ~25 minutes

🐰 Neue APIs hüpfen heran,
Strings, Binärdaten, Base64 im Plan,
MIME-Erkennung tanzt und spielt,
Temp-Dateien werden aufgeräumt zielgerichtet,
FileSanitizer macht's nun elegant!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Der PR-Titel beschreibt präzise die Hauptänderung: Hinzufügen von Support für String-, Binary- und Base64-Payload-Sanitisierung mit Tests. Dies entspricht exakt den Inhaltsänderungen in README, FileSanitizer.php und den neuen Testdateien.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-string-and-base64-support

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
tests/Sanitizer/FileSanitizerInputStringTest.php (1)

31-31: ⚡ Quick win

Optional: Explizite Base64-Validierung für klarere Fehlermeldungen.

Die aktuelle Assertion funktioniert korrekt, aber wenn sanitizedBase64 ungültiges Base64 enthielte, würde base64_decode(..., true) false zurückgeben und die Fehlermeldung wäre nicht optimal. Eine explizite Prüfung könnte das Debugging erleichtern.

💡 Optionale Verbesserung für klarere Assertions
-        self::assertSame($result['sanitizedData'], base64_decode($result['sanitizedBase64'], true));
+        $decoded = base64_decode($result['sanitizedBase64'], true);
+        self::assertNotFalse($decoded, 'sanitizedBase64 sollte gültiges Base64 enthalten');
+        self::assertSame($result['sanitizedData'], $decoded);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/Sanitizer/FileSanitizerInputStringTest.php` at line 31, The test
currently compares sanitizedData to base64_decode($result['sanitizedBase64'],
true) directly, which yields an unhelpful failure if sanitizedBase64 is invalid;
first assert the base64 is valid by calling
base64_decode($result['sanitizedBase64'], true) and using an explicit assertion
like assertNotFalse (or assertIsString) on that decoded value keyed by
'sanitizedBase64', then perform the assertSame between $result['sanitizedData']
and the decoded value so failures clearly indicate invalid Base64 versus content
mismatch.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/FileSanitizer.php`:
- Around line 188-195: The temporary working directory created in
FileSanitizer.php using $tempDirectory is currently created with mode 0755;
change the mkdir invocation to use 0700 to restrict access (so uploads and
artifacts are not world-readable) and, to be extra safe, after successful
creation call chmod($tempDirectory, 0700) to enforce the permission on systems
where umask may interfere; update the mkdir line and add the chmod fallback near
the existing creation/check block (the try/catch that sets $tempDirectory and
the if (!mkdir(...)) check).
- Around line 134-137: defaultOutputPath currently mishandles names without
extensions because it always uses substr with a negative length and produces
".sanitized" instead of appending to the original name; update the function
defaultOutputPath to check if $extension === '' and in that case return
$inputPath . '.sanitized', otherwise compute the base name (using
substr($inputPath, 0, -strlen($extension) - 1)) and return base . '.sanitized.'
. $extension so dateiendungslose und normale Dateien are treated correctly.
- Around line 199-214: Behandle Data-URIs flexibler: in
extractBase64Payload(string $base64Data) prüfe zunächst, ob der String ein
Data-URI ist, indem du bis zum ersten Komma splittest; falls im Header (Teil vor
dem Komma) case-insensitiv das Flag ";base64" vorkommt, gebe den Teil nach dem
Komma (ohne Whitespace) zurück, sonst behandle den gesamten Input als rohes
Base64 wie bisher; in extractDataUriMimeType(string $base64Data) parse ebenfalls
nur den Header bis zum ersten Komma, entferne das führende "data:" und
extrahiere den MIME-Type als Text vor dem ersten Semikolon (oder null, wenn leer
oder Header fehlt), normalisiere mit strtolower/trim und gib null zurück, wenn
kein Data-URI vorliegt oder kein MIME-Type angegeben wurde; referenziere die
Funktionen extractBase64Payload und extractDataUriMimeType beim Patch.

---

Nitpick comments:
In `@tests/Sanitizer/FileSanitizerInputStringTest.php`:
- Line 31: The test currently compares sanitizedData to
base64_decode($result['sanitizedBase64'], true) directly, which yields an
unhelpful failure if sanitizedBase64 is invalid; first assert the base64 is
valid by calling base64_decode($result['sanitizedBase64'], true) and using an
explicit assertion like assertNotFalse (or assertIsString) on that decoded value
keyed by 'sanitizedBase64', then perform the assertSame between
$result['sanitizedData'] and the decoded value so failures clearly indicate
invalid Base64 versus content mismatch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c0886b4a-e8aa-4d88-a492-b1b76073bc0d

📥 Commits

Reviewing files that changed from the base of the PR and between eb2dbe1 and 04110cd.

📒 Files selected for processing (3)
  • README.md
  • src/FileSanitizer.php
  • tests/Sanitizer/FileSanitizerInputStringTest.php

Comment thread src/FileSanitizer.php
Comment thread src/FileSanitizer.php
Comment thread src/FileSanitizer.php
@shaunluedeke shaunluedeke merged commit f539524 into master Jun 2, 2026
13 checks passed
@shaunluedeke shaunluedeke deleted the add-string-and-base64-support branch June 2, 2026 19:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant