A free open source IT asset/license management system
Added loss ratio safety net for *sort of* okay files
snipece670d654f78
diff --git a/app/Http/Controllers/Api/ImportController.php b/app/Http/Controllers/Api/ImportController.phpindex a9bfce9e8e..b432f06b76 100644--- a/app/Http/Controllers/Api/ImportController.php+++ b/app/Http/Controllers/Api/ImportController.php@@ -129,6 +129,33 @@ class ImportController extends Controller422);}+ // Loss-ratio safety net. iconv's //IGNORE flag lets a+ // mostly-valid file with a stray invalid byte still+ // import successfully, but a truly-corrupt file (random+ // binary, wrong-encoding guess) can silently //IGNORE+ // away most of its bytes and land a nearly-empty CSV+ // downstream. If more than half the source was dropped,+ // treat it the same as an iconv exception and 422 out+ // with the existing transliterate_failure message so+ // the caller sees a real error instead of an eerily-+ // empty import.+ if ($transliterated !== false && strlen($transliterated) < intdiv(strlen($file_contents), 2)) {+ \Log::warning(sprintf(+ 'CSV import: refusing lossy encoding conversion (%s -> UTF-8) that kept %d/%d bytes',+ $encoding,+ strlen($transliterated),+ strlen($file_contents),+ ));++ return response()->json(+ Helper::formatStandardApiResponse(+ 'error',+ null,+ trans('admin/hardware/message.import.transliterate_failure', ['encoding' => $encoding])+ ),+ 422+ );+ }if ($transliterated !== false) {$tmpname = tempnam(sys_get_temp_dir(), '');$tmpresults = file_put_contents($tmpname, $transliterated);diff --git a/app/Importer/Importer.php b/app/Importer/Importer.phpindex c647bd8058..ff817ca09a 100644--- a/app/Importer/Importer.php+++ b/app/Importer/Importer.php@@ -139,50 +139,125 @@ abstract class Importerini_set('auto_detect_line_endings', '1');}// By default the importer passes a url to the file.- // However, for testing we also support passing a string directly- $contents = null;+ // However, for testing we also support passing a string directly.+ //+ // Memory-conscious construction: this constructor runs once per JS-+ // chunked slice against the same file (see ItemImportRequest::import,+ // which builds a new Importer per POST from the Livewire importer's+ // chunk loop). Buffering the whole file into a string here would+ // multiply peak memory by the chunk count, which defeats the entire+ // point of the chunked-import rework. Common case: sample the head+ // of the file, if it's UTF-8 use Reader::createFromPath so the CSV+ // reader streams from disk. Only fall back to full-file buffering+ // when encoding conversion is actually needed.if (is_file($file)) {- $contents = file_get_contents($file);+ $sample = self::readSampleForEncodingProbe($file);+ if ($sample !== null && ! mb_check_encoding($sample, 'UTF-8')) {+ $contents = file_get_contents($file);+ if ($contents !== false) {+ $contents = self::convertToUtf8IfNeeded($contents);+ $this->csv = Reader::createFromString($contents);+ } else {+ $this->csv = Reader::createFromPath($file);+ }+ } else {+ $this->csv = Reader::createFromPath($file);+ }} else {- $contents = $file;+ // Raw string input (tests, callers that build a CSV string+ // in-process). Already in memory, so run the same encoding+ // guard directly on the string.+ $contents = mb_check_encoding($file, 'UTF-8') ? $file : self::convertToUtf8IfNeeded($file);+ $this->csv = Reader::createFromString($contents);}+ $this->tempPassword = '*** NO PASSWORD - IMPORTED VIA CSV ***';+ }- if ($contents !== false && ! mb_check_encoding($contents, 'UTF-8')) {- $encoding = null;- if (class_exists('\Onnov\DetectEncoding\EncodingDetector')) {- $detector = new \Onnov\DetectEncoding\EncodingDetector;- $encoding = $detector->getEncoding($contents);- }- // Only fall back to mb_detect_encoding if the Onnov detector gave- // us nothing useful. Overriding a confident Onnov result with a- // permissive mb_detect guess re-labels the file as one of the CJK- // encodings early in the fallback list and produces mojibake.- if (! $encoding || strcasecmp($encoding, 'UTF-8') === 0) {- $detected = mb_detect_encoding($contents, ['UTF-8', 'GBK', 'GB2312', 'GB18030', 'BIG5', 'SJIS', 'EUC-JP', 'EUC-KR', 'Windows-1252', 'Windows-1251', 'ISO-8859-1'], true);- if ($detected) {- $encoding = $detected;- }+ /**+ * Read a small head-of-file sample cheaply for encoding detection. 8KB+ * is enough to tell UTF-8 from GBK / Windows-1252 / Shift-JIS in+ * practice (CSVs have uniform encoding throughout), and reading a+ * sample this size stays in a single filesystem block on almost every+ * modern deployment.+ *+ * Returns null if the file can't be opened, which callers should+ * treat as "assume UTF-8 and let downstream errors surface".+ */+ private static function readSampleForEncodingProbe(string $path): ?string+ {+ $handle = @fopen($path, 'rb');+ if ($handle === false) {+ return null;+ }+ $sample = @fread($handle, 8192);+ fclose($handle);++ return $sample === false ? null : $sample;+ }++ /**+ * Detect the source encoding of a non-UTF-8 string and convert it to+ * UTF-8. Uses the Onnov detector first, falling back to mb_detect only+ * when Onnov abstains (Onnov is usually more reliable when it commits+ * to an answer, and overriding it with the CJK-leaning mb_detect list+ * produces mojibake on short Cyrillic input).+ *+ * The iconv //IGNORE flag lets real-world CSVs with a stray invalid+ * byte in an otherwise valid file import successfully. To keep that+ * from turning into "silently accept entirely-corrupt input", the+ * result is length-checked against the source: if the converted+ * output is less than half the source size (rough proxy for+ * "//IGNORE dropped most of the file"), we return the source+ * unchanged rather than a nearly-empty buffer, so downstream sees the+ * problem instead of an eerily-empty import.+ */+ private static function convertToUtf8IfNeeded(string $contents): string+ {+ if (mb_check_encoding($contents, 'UTF-8')) {+ return $contents;+ }++ $encoding = null;+ if (class_exists('\Onnov\DetectEncoding\EncodingDetector')) {+ $detector = new \Onnov\DetectEncoding\EncodingDetector;+ $encoding = $detector->getEncoding($contents);+ }+ if (! $encoding || strcasecmp($encoding, 'UTF-8') === 0) {+ $detected = mb_detect_encoding($contents, ['UTF-8', 'GBK', 'GB2312', 'GB18030', 'BIG5', 'SJIS', 'EUC-JP', 'EUC-KR', 'Windows-1252', 'Windows-1251', 'ISO-8859-1'], true);+ if ($detected) {+ $encoding = $detected;}- if ($encoding && strcasecmp($encoding, 'UTF-8') !== 0) {- if (function_exists('iconv')) {- $converted = @iconv(strtoupper($encoding), 'UTF-8//IGNORE', $contents);- if ($converted !== false) {- $contents = $converted;- }- } elseif (function_exists('mb_convert_encoding')) {- $contents = mb_convert_encoding($contents, 'UTF-8', $encoding);- }+ }+ if (! $encoding || strcasecmp($encoding, 'UTF-8') === 0) {+ return $contents;+ }++ $converted = null;+ if (function_exists('iconv')) {+ $converted = @iconv(strtoupper($encoding), 'UTF-8//IGNORE', $contents);+ if ($converted === false) {+ $converted = null;}+ } elseif (function_exists('mb_convert_encoding')) {+ $converted = @mb_convert_encoding($contents, 'UTF-8', $encoding);}- if ($contents !== null) {- $this->csv = Reader::createFromString($contents);- } elseif (is_file($file)) {- $this->csv = Reader::createFromPath($file);- } else {- $this->csv = Reader::createFromString($file);+ if ($converted === null || $converted === '') {+ return $contents;}- $this->tempPassword = '*** NO PASSWORD - IMPORTED VIA CSV ***';++ if (strlen($converted) < intdiv(strlen($contents), 2)) {+ Log::warning(sprintf(+ 'CSV import: refusing lossy encoding conversion (%s -> UTF-8) that kept %d/%d bytes',+ $encoding,+ strlen($converted),+ strlen($contents),+ ));++ return $contents;+ }++ return $converted;}// Cached Values for import lookupsdiff --git a/tests/Feature/Importing/Ui/ImportTest.php b/tests/Feature/Importing/Ui/ImportTest.phpindex be91799db1..1866a66b9a 100644--- a/tests/Feature/Importing/Ui/ImportTest.php+++ b/tests/Feature/Importing/Ui/ImportTest.php@@ -60,15 +60,14 @@ class ImportTest extends TestCase// 0xC0 makes it 'not unicode', and 0xFF makes it 'likely WINDOWS-1251', and 0x98 at the end makes it 'not-valid-Windows-1251'$evil_content = $evil_maker([0xC0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x98]);- // As of PR #19418 (CSV encoding hardening), the iconv call uses- // //IGNORE so truly-invalid byte runs are silently dropped instead- // of throwing back to the controller as transliterate_failure. That- // is deliberate: real-world CJK / Windows-1252 CSVs typically have- // mostly-valid content with a stray byte or two, and //IGNORE lets- // those imports succeed. The tradeoff is that fully-corrupt input- // like this test's evil_content is now accepted through the store- // path (the resulting rows will just be nearly empty). Verify the- // request no longer bounces with 422.+ // PR #19418 added the iconv //IGNORE flag so real-world CJK CSVs+ // with a stray invalid byte still import instead of aborting on+ // the first bad byte. That is the desired UX. As a result, this+ // specific 19-byte payload (18 valid Windows-1251 bytes plus one+ // invalid 0x98) is now accepted through the store path rather+ // than rejected with transliterate_failure. The loss-ratio safety+ // net added in the same PR only fires when //IGNORE drops more+ // than half the input, which does not apply to this shape.$this->actingAsForApi(User::factory()->superuser()->create());$this->post(route('api.imports.store'), ['files' => [UploadedFile::fake()->createWithContent('myname.csv', $evil_content)]])->assertOk();