mirror of
https://github.com/FOSSBilling/FOSSBilling.git
synced 2026-12-02 21:30:16 +09:00
Add invoice hash self-healing and patch backfill (#3807)
* Add invoice hash self-healing and patch backfill * Simplify invoice-hash comments and update test * Update last_patch to 74 * Fix invoice hash backfill case matching
This commit is contained in:
1 parent
cf547d76b1
commit
0f29d0794e
4 files changed
+269
-20
No files matched your search
@@ -303,7 +303,7 @@ LOCK TABLES `setting` WRITE;
|
||||
|
||||
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
|
||||
VALUES
|
||||
(1,'last_patch','73',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'),
|
||||
(1,'last_patch','74',0,NULL,NULL,'2024-12-30 12:00:00','2024-12-30 12:00:00'),
|
||||
(2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
|
||||
(3,'company_email','support@yourcompany.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
|
||||
(4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
|
||||
|
||||
@@ -280,6 +280,17 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
);
|
||||
}
|
||||
|
||||
private function computeInvoiceHashExpiration(): ?string
|
||||
{
|
||||
$value = $this->fetchOne("SELECT value FROM setting WHERE param = 'invoice_hash_lifetime_days'");
|
||||
$days = is_string($value) && $value !== '' ? (int) $value : 90;
|
||||
if ($days <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return date('Y-m-d H:i:s', strtotime("+{$days} days"));
|
||||
}
|
||||
|
||||
private function getTableColumns(string $table): array
|
||||
{
|
||||
$columns = $this->fetchAll(sprintf('SHOW COLUMNS FROM `%s`', $this->quoteIdentifier($table)));
|
||||
@@ -468,6 +479,7 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
71 => 'patch71',
|
||||
72 => 'patch72',
|
||||
73 => 'patch73',
|
||||
74 => 'patch74',
|
||||
];
|
||||
ksort($patches, SORT_NATURAL);
|
||||
|
||||
@@ -1484,23 +1496,26 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
]
|
||||
);
|
||||
|
||||
// Destructive migration: NULL legacy invoice hashes that fall outside the
|
||||
// modern 30-60 lowercase hex format enforced by the new guest API regex
|
||||
// validation. Hashes that fall within the 30-60 char range (including
|
||||
// 32-char MD5 and 40-char SHA-1) are preserved. Affected rows:
|
||||
// - 2022-era SHA-256 (64 hex, just over the upper bound)
|
||||
// - 2023-era 200-254 hex
|
||||
// - Any hash containing non-lowercase-hex characters
|
||||
// These links would be rejected by the new API anyway, so leaving them
|
||||
// in place creates dead links in customer email archives. The
|
||||
// extendInvoiceHashLifetime() helper regenerates a valid modern hash
|
||||
// automatically when an admin re-sends the invoice, restoring magic-link
|
||||
// access without manual intervention.
|
||||
$this->executeSql(
|
||||
"UPDATE invoice SET hash = NULL
|
||||
WHERE hash IS NOT NULL
|
||||
AND (LENGTH(hash) < 30 OR LENGTH(hash) > 60 OR hash NOT REGEXP '^[a-f0-9]+$')"
|
||||
// Regenerate invoice hashes that fall outside the modern 30-60 lowercase
|
||||
// hex format enforced by the new guest API regex validation. The client
|
||||
// area, gateway return URLs, and email links all build URLs from the
|
||||
// hash, so NULLing it (as an earlier revision did) broke those URLs —
|
||||
// see https://github.com/FOSSBilling/FOSSBilling/issues/3791.
|
||||
$expires = $this->computeInvoiceHashExpiration();
|
||||
$rows = $this->fetchAll(
|
||||
"SELECT id FROM invoice WHERE hash IS NOT NULL
|
||||
AND (LENGTH(hash) < 30 OR LENGTH(hash) > 60 OR BINARY hash NOT REGEXP '^[a-f0-9]+$')"
|
||||
);
|
||||
foreach ($rows as $row) {
|
||||
$this->executeSql(
|
||||
'UPDATE invoice SET hash = :hash, hash_expires_at = :expires WHERE id = :id',
|
||||
[
|
||||
'hash' => bin2hex(random_bytes(random_int(15, 30))),
|
||||
'expires' => $expires,
|
||||
'id' => $row['id'],
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function patch68(): void
|
||||
@@ -1859,6 +1874,25 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
$this->executeSql('DROP TABLE `support_p_ticket`;');
|
||||
}
|
||||
|
||||
private function patch74(): void
|
||||
{
|
||||
// Backfill hashes NULLed by the original revision of patch67.
|
||||
$expires = $this->computeInvoiceHashExpiration();
|
||||
$rows = $this->fetchAll(
|
||||
"SELECT id FROM invoice WHERE hash IS NULL OR LENGTH(hash) < 30 OR LENGTH(hash) > 60 OR BINARY hash NOT REGEXP '^[a-f0-9]+$'"
|
||||
);
|
||||
foreach ($rows as $row) {
|
||||
$this->executeSql(
|
||||
'UPDATE invoice SET hash = :hash, hash_expires_at = :expires WHERE id = :id',
|
||||
[
|
||||
'hash' => bin2hex(random_bytes(random_int(15, 30))),
|
||||
'expires' => $expires,
|
||||
'id' => $row['id'],
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function generateDownloadableStoredFilename(): string
|
||||
{
|
||||
do {
|
||||
|
||||
@@ -188,6 +188,7 @@ class Service implements InjectionAwareInterface
|
||||
|
||||
public function toApiArray(\Model_Invoice $invoice, $deep = true, $identity = null): array
|
||||
{
|
||||
$this->ensureValidHash($invoice);
|
||||
$row = $this->di['db']->toArray($invoice);
|
||||
|
||||
$items = $this->di['db']->find('InvoiceItem', 'invoice_id = :iid', ['iid' => $row['id']]);
|
||||
@@ -1850,8 +1851,8 @@ class Service implements InjectionAwareInterface
|
||||
/**
|
||||
* Re-stamps hash_expires_at on an existing invoice using the current
|
||||
* invoice_hash_lifetime_days setting. Also self-heals invoices whose
|
||||
* hash is empty or in a legacy format (patch67 NULLs those) by
|
||||
* generating a fresh modern hash.
|
||||
* hash is empty or in a legacy format by generating a fresh modern
|
||||
* hash. Called when an admin re-sends an invoice or payment reminder.
|
||||
*/
|
||||
public function extendInvoiceHashLifetime(\Model_Invoice $invoice): void
|
||||
{
|
||||
@@ -1864,6 +1865,23 @@ class Service implements InjectionAwareInterface
|
||||
$this->di['db']->store($invoice);
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerates the hash if it is missing or in a legacy format. No-op
|
||||
* for valid hashes, making it safe to call from read paths.
|
||||
*/
|
||||
public function ensureValidHash(\Model_Invoice $invoice): void
|
||||
{
|
||||
$hash = $invoice->hash ?? null;
|
||||
$isModern = is_string($hash) && preg_match('/^[a-f0-9]{30,60}$/', $hash) === 1;
|
||||
if ($isModern) {
|
||||
return;
|
||||
}
|
||||
|
||||
$invoice->hash = bin2hex(random_bytes(random_int(15, 30)));
|
||||
$invoice->hash_expires_at = $this->computeHashExpiration();
|
||||
$this->di['db']->store($invoice);
|
||||
}
|
||||
|
||||
private function isHashExpired(\Model_Invoice $invoice): bool
|
||||
{
|
||||
$expires = $invoice->hash_expires_at ?? null;
|
||||
|
||||
@@ -148,6 +148,7 @@ test('converts to api array', function (): void {
|
||||
$service = new Service();
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceModel->hash = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4';
|
||||
|
||||
$invoiceItemModel = new Model_InvoiceItem();
|
||||
$invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
@@ -170,7 +171,7 @@ test('converts to api array', function (): void {
|
||||
'serie' => 'BB',
|
||||
'nr' => '0001',
|
||||
'serie_nr' => 'BB0001',
|
||||
'hash' => 'hashedValue',
|
||||
'hash' => 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4',
|
||||
'gateway_id' => '',
|
||||
'taxname' => '',
|
||||
'taxrate' => '',
|
||||
@@ -243,6 +244,202 @@ test('converts to api array', function (): void {
|
||||
expect($result['buyer']['phone_cc'])->toBe('');
|
||||
});
|
||||
|
||||
test('ensure valid hash is a no-op for modern hashes', function (): void {
|
||||
$service = new Service();
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceModel->hash = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4';
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldNotReceive('store');
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
|
||||
$service->setDi($di);
|
||||
$service->ensureValidHash($invoiceModel);
|
||||
|
||||
expect($invoiceModel->hash)->toBe('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4');
|
||||
});
|
||||
|
||||
test('ensure valid hash regenerates a missing hash', function (): void {
|
||||
$service = new Service();
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->with('invoice_hash_lifetime_days', '90')
|
||||
->andReturn('90');
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('store')
|
||||
->once()
|
||||
->with($invoiceModel);
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(function ($serviceName) use ($systemService) {
|
||||
if ($serviceName === 'system') {
|
||||
return $systemService;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
$service->setDi($di);
|
||||
$service->ensureValidHash($invoiceModel);
|
||||
|
||||
expect($invoiceModel->hash)->toBeString();
|
||||
expect(strlen($invoiceModel->hash))->toBeGreaterThanOrEqual(30);
|
||||
expect(strlen($invoiceModel->hash))->toBeLessThanOrEqual(60);
|
||||
expect($invoiceModel->hash)->toMatch('/^[a-f0-9]+$/');
|
||||
expect($invoiceModel->hash_expires_at)->toBeString();
|
||||
});
|
||||
|
||||
test('ensure valid hash regenerates a legacy format hash', function (): void {
|
||||
$service = new Service();
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
$invoiceModel->hash = 'AAAAAAAAC4C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8C8';
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->with('invoice_hash_lifetime_days', '90')
|
||||
->andReturn('90');
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('store')
|
||||
->once()
|
||||
->with($invoiceModel);
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(function ($serviceName) use ($systemService) {
|
||||
if ($serviceName === 'system') {
|
||||
return $systemService;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
$service->setDi($di);
|
||||
$service->ensureValidHash($invoiceModel);
|
||||
|
||||
expect(strlen($invoiceModel->hash))->toBeGreaterThanOrEqual(30);
|
||||
expect(strlen($invoiceModel->hash))->toBeLessThanOrEqual(60);
|
||||
expect($invoiceModel->hash)->toMatch('/^[a-f0-9]+$/');
|
||||
});
|
||||
|
||||
test('to api array self-heals invoice with missing hash', function (): void {
|
||||
$service = new Service();
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$invoiceItemModel = new Model_InvoiceItem();
|
||||
$invoiceItemModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getCompany')->atLeast()->once();
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->atLeast()->once()
|
||||
->andReturnUsing(function (string $param, string $default = '') {
|
||||
if ($param === 'invoice_hash_lifetime_days') {
|
||||
return '90';
|
||||
}
|
||||
|
||||
return $default;
|
||||
});
|
||||
|
||||
$subscriptionServiceMock = Mockery::mock(ServiceSubscription::class);
|
||||
$subscriptionServiceMock->shouldReceive('getSubscriptionPeriod')
|
||||
->byDefault()
|
||||
->andReturn('1W');
|
||||
$invoiceItemServiceMock = Mockery::mock(ServiceInvoiceItem::class);
|
||||
|
||||
$modelToArrayResult = [
|
||||
'id' => 1,
|
||||
'serie' => 'BB',
|
||||
'nr' => '0001',
|
||||
'serie_nr' => 'BB0001',
|
||||
'hash' => null,
|
||||
'gateway_id' => '',
|
||||
'taxname' => '',
|
||||
'taxrate' => '',
|
||||
'currency' => '',
|
||||
'status' => '',
|
||||
'notes' => '',
|
||||
'text_1' => '',
|
||||
'text_2' => '',
|
||||
'due_at' => '',
|
||||
'created_at' => '',
|
||||
'updated_at' => '',
|
||||
'buyer_first_name' => '',
|
||||
'buyer_last_name' => '',
|
||||
'buyer_company' => '',
|
||||
'buyer_company_vat' => '',
|
||||
'buyer_company_number' => '',
|
||||
'buyer_address' => '',
|
||||
'buyer_city' => '',
|
||||
'buyer_state' => '',
|
||||
'buyer_country' => '',
|
||||
'buyer_phone' => '',
|
||||
'buyer_email' => '',
|
||||
'buyer_zip' => '',
|
||||
'seller_company_vat' => '',
|
||||
'seller_company_number' => '',
|
||||
];
|
||||
|
||||
$dbMock = Mockery::mock('\Box_Database');
|
||||
$dbMock->shouldReceive('toArray')
|
||||
->atLeast()->once()
|
||||
->andReturnUsing(function () use ($invoiceModel, $modelToArrayResult): array {
|
||||
$modelToArrayResult['hash'] = $invoiceModel->hash;
|
||||
|
||||
return $modelToArrayResult;
|
||||
});
|
||||
$dbMock->shouldReceive('find')
|
||||
->atLeast()->once()
|
||||
->andReturn([$invoiceItemModel]);
|
||||
$dbMock->shouldReceive('getCell')
|
||||
->byDefault()
|
||||
->andReturn('1W');
|
||||
$dbMock->shouldReceive('store')
|
||||
->once()
|
||||
->with($invoiceModel);
|
||||
|
||||
$periodMock = Mockery::mock('\Box_Period');
|
||||
$periodMock->shouldReceive('getUnit');
|
||||
$periodMock->shouldReceive('getQty');
|
||||
|
||||
$di = container();
|
||||
$di['db'] = $dbMock;
|
||||
$di['mod_service'] = $di->protect(function ($serviceName, $sub = '') use ($systemService, $subscriptionServiceMock, $invoiceItemServiceMock) {
|
||||
$service = null;
|
||||
if ($sub == 'InvoiceItem') {
|
||||
$service = $invoiceItemServiceMock;
|
||||
}
|
||||
if ($serviceName == 'system' || $serviceName == 'System') {
|
||||
$service = $systemService;
|
||||
}
|
||||
if ($sub == 'Subscription') {
|
||||
$service = $subscriptionServiceMock;
|
||||
}
|
||||
|
||||
return $service;
|
||||
});
|
||||
$di['period'] = $di->protect(fn (): Mockery\MockInterface => $periodMock);
|
||||
|
||||
$service->setDi($di);
|
||||
|
||||
$result = $service->toApiArray($invoiceModel);
|
||||
|
||||
expect($result)->toBeArray();
|
||||
expect($result['hash'])->toBeString();
|
||||
expect(strlen($result['hash']))->toBeGreaterThanOrEqual(30);
|
||||
expect(strlen($result['hash']))->toBeLessThanOrEqual(60);
|
||||
});
|
||||
|
||||
test('handles after admin invoice payment received event', function (): void {
|
||||
$service = new Service();
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
Reference in new issue
Block a user