diff --git a/app/Support/Integrations/Tailscale/TailscaleDevices.php b/app/Support/Integrations/Tailscale/TailscaleDevices.php index 20095c7f..5ef065e7 100644 --- a/app/Support/Integrations/Tailscale/TailscaleDevices.php +++ b/app/Support/Integrations/Tailscale/TailscaleDevices.php @@ -93,6 +93,17 @@ public function link(Integration $integration): void $taken = $rows->pluck('machine_id')->filter()->all(); $free = $machines->reject(fn (Machine $machine) => in_array($machine->id, $taken, true))->values(); + // Count hostname candidates before linking rows, so row order can't + // turn multiple possible devices into an apparently unique match. + $hostnameMatches = []; + foreach ($rows->filter(fn (TailscaleDevice $candidate) => $candidate->machine_id === null && ! $candidate->external) as $candidate) { + foreach ($machines as $machine) { + if (self::byHostname($candidate, $machine)) { + $hostnameMatches[$machine->id] = ($hostnameMatches[$machine->id] ?? 0) + 1; + } + } + } + foreach ($rows->whereNull('machine_id') as $row) { if ($row->external) { continue; @@ -102,6 +113,9 @@ public function link(Integration $integration): void foreach ($tests as $test) { $found = $free->filter(fn (Machine $machine) => $test($row, $machine))->values(); if ($found->count() === 1) { + if ($how === TailscaleDevice::HOSTNAME && ($hostnameMatches[$found->first()->id] ?? 0) !== 1) { + continue; + } $match = $found->first(); break; } diff --git a/tests/Feature/Integrations/TailscaleTest.php b/tests/Feature/Integrations/TailscaleTest.php index 3e5eec06..42550a5d 100644 --- a/tests/Feature/Integrations/TailscaleTest.php +++ b/tests/Feature/Integrations/TailscaleTest.php @@ -195,6 +195,19 @@ function tsAccountProps(Workspace $workspace, Integration $integration): array expect(TailscaleDevice::query()->where('machine_id', $db->id)->exists())->toBeFalse(); }); +test('duplicate Tailscale hostnames do not link an arbitrary device to one machine', function () { + $workspace = Workspace::factory()->create(); + $integration = tsAccount($workspace); + $machine = tsMachine($workspace, 'web-1'); + $this->tailscale->device('web-1', '100.64.0.7'); + $this->tailscale->device('web-1', '100.64.0.8'); + + $props = tsAccountProps($workspace, $integration); + + expect(collect($props['devices'])->pluck('machine')->filter()->all())->toBe([]) + ->and(collect($props['machines'])->pluck('id')->all())->toContain($machine->id); +}); + test('add to tailnet makes a one-off key, deploys Tailscale with it, and links the device that turns up', function () { $workspace = Workspace::factory()->create(); $integration = tsAccount($workspace);