From c1ea06ac2193ffb0b7cb3a6d05eddc19643c88f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Molakvo=C3=A6?= <14975046+skjnldsv@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:19 +0100 Subject: [PATCH] fix(export): quote every CSV field and neutralise formulas after spaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CSV export only looked at the first character of a field for a formula trigger, and quoted a field only when it had to. A value with leading spaces or quotes before `=` was written unchanged. Every field is now quoted, and a text cell that starts with `=`, `+`, `-`, `@`, a tab or a carriage return, also after leading spaces or quotes, gets a leading apostrophe. Numbers stay numbers. Assisted-by: ClaudeCode:claude-opus-5-5 Signed-off-by: John Molakvoæ <14975046+skjnldsv@users.noreply.github.com> --- SPECIFICATION.md | 3 ++ lib/Service/ExportService.php | 25 +++++++------ tests/Unit/Service/ExportServiceTest.php | 46 ++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 13 deletions(-) diff --git a/SPECIFICATION.md b/SPECIFICATION.md index 1ffcd736..053cd26f 100644 --- a/SPECIFICATION.md +++ b/SPECIFICATION.md @@ -1394,6 +1394,9 @@ The HR area (visible only to HR-group members) provides: (columns `Employee`, `Account ID`, `Email`, in that order), so two people with the same name can be told apart and payroll can match rows to its own records. The e-mail cell is empty when the account has none or was deleted; the account id stays. + Every CSV field is quoted. A text cell that starts with `=`, `+`, `-`, `@`, a tab + or a carriage return, also after leading spaces or quotes, gets a leading `'` so + spreadsheets show it as text instead of running it; numbers stay numbers. Managers get a scoped version (their reports only) of the who's-off calendar — the Team timeline — and, below it, a **scoped balances table** of their direct reports diff --git a/lib/Service/ExportService.php b/lib/Service/ExportService.php index 18ebf94f..5cf0fb49 100644 --- a/lib/Service/ExportService.php +++ b/lib/Service/ExportService.php @@ -114,25 +114,24 @@ private function groupSuffix(?string $group): string { * @param list> $rows */ private function toCsv(array $rows): string { - $handle = fopen('php://temp', 'r+'); // BOM so Excel opens UTF-8 correctly. - fwrite($handle, "\xEF\xBB\xBF"); + $csv = "\xEF\xBB\xBF"; foreach ($rows as $row) { - // escape: '' disables PHP's legacy backslash escaping in favour of pure - // RFC-4180 quoting (and silences the 8.4 deprecation of the default). - fputcsv($handle, array_map([$this, 'sanitizeCell'], $row), ',', '"', ''); + // Every field is quoted (RFC 4180), so no value is ever read as more than one cell. + $csv .= implode(',', array_map( + fn (string $value): string => '"' . str_replace('"', '""', $this->sanitizeCell($value)) . '"', + $row, + )) . "\n"; } - rewind($handle); - $content = stream_get_contents($handle); - fclose($handle); - return $content === false ? '' : $content; + return $csv; } /** * Neutralize spreadsheet formula injection: a cell that begins with a formula - * trigger (=, +, -, @, tab or CR) is evaluated by Excel/LibreOffice/Sheets when - * the export is opened. Employee display names, account ids, e-mail addresses - * and leave-type labels are attacker-influenced free text, so prefix any such value with an apostrophe, + * trigger (=, +, -, @, tab or CR), also after leading spaces or quotes, is + * evaluated by Excel/LibreOffice/Sheets when the export is opened. Employee + * display names, account ids, e-mail addresses and leave-type labels are + * attacker-influenced free text, so prefix any such value with an apostrophe, * which forces the client to treat the whole cell as literal text. */ private function sanitizeCell(string $value): string { @@ -141,7 +140,7 @@ private function sanitizeCell(string $value): string { if (is_numeric($value)) { return $value; } - if ($value !== '' && in_array($value[0], ['=', '+', '-', '@', "\t", "\r"], true)) { + if (preg_match('/^[ "\']*[=+\-@\t\r]/', $value) === 1) { return "'" . $value; } return $value; diff --git a/tests/Unit/Service/ExportServiceTest.php b/tests/Unit/Service/ExportServiceTest.php index 423e5097..b2c1d275 100644 --- a/tests/Unit/Service/ExportServiceTest.php +++ b/tests/Unit/Service/ExportServiceTest.php @@ -18,6 +18,7 @@ use OCA\Absence\Tests\Unit\L10nMockTrait; use OCP\IUser; use OCP\IUserManager; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -71,6 +72,51 @@ public function testRequestsCsvNeutralizesFormulaInjection(): void { self::assertStringNotContainsString(',=HYPERLINK', $csv); } + /** @return array display name => the cell the export writes */ + public static function formulaCells(): array { + return [ + 'equals' => ['=1+2', '"\'=1+2"'], + 'plus' => ['+1+2', '"\'+1+2"'], + 'minus' => ['-1+2', '"\'-1+2"'], + 'at' => ['@SUM(A1)', '"\'@SUM(A1)"'], + 'tab' => ["\t=1+2", "\"'\t=1+2\""], + 'carriage return' => ["\r=1+2", "\"'\r=1+2\""], + 'after spaces' => [' =1+2', '"\' =1+2"'], + 'after a quote' => ['"=1+2', '"\'""=1+2"'], + 'after a single quote' => ["'=1+2", "\"''=1+2\""], + 'after a separator' => ['Sam,=1+2', '"Sam,=1+2"'], + 'plain text' => ['Alex Sample', '"Alex Sample"'], + 'a hyphen inside' => ['Anne-Marie Sample', '"Anne-Marie Sample"'], + ]; + } + + /** + * A cell that a spreadsheet would read as a formula, also after leading + * spaces or quotes, is made text, and every field is quoted so no value + * spills into the next cell. + */ + #[DataProvider('formulaCells')] + public function testRequestsCsvWritesEveryCellAsText(string $displayName, string $cell): void { + $this->leaveTypeMapper->method('findAll')->willReturn([]); + $this->requestMapper->method('findAllInRange')->willReturn([$this->approvedRequest(1, 'sam')]); + $this->userManager->method('get')->willReturn($this->user($displayName, null)); + + $lines = explode("\n", $this->service->requestsCsv('2026-01-01', '2026-01-31')['content']); + + self::assertStringStartsWith('"ID","Employee","Account ID",', substr($lines[0], 3)); + self::assertStringStartsWith('"1",' . $cell . ',"sam",""', $lines[1]); + } + + public function testBalancesCsvKeepsNegativeNumbersNumeric(): void { + $row = $this->balanceRow('sam', 'Sam Okoro', 'Vacation'); + $row['manualAdjustment'] = -2.0; + $this->reportService->method('balancesReport')->willReturn([$row]); + + $lines = explode("\n", $this->service->balancesCsv(2026)['content']); + + self::assertStringContainsString(',"-2",', $lines[1]); + } + public function testRequestsCsvRejectsInvalidDate(): void { $this->expectException(ValidationException::class); $this->service->requestsCsv('not-a-date', '2026-01-31');