A free open source IT asset/license management system
Added Google Workspace ChromeOS sync
snipe433bf8f2031f
diff --git a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.phpnew file mode 100644index 0000000000..0f6364112e--- /dev/null+++ b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapter.php@@ -0,0 +1,418 @@+<?php++namespace App\SyncAdapters\GoogleWorkspace;++use App\Models\Asset;+use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\PushableAdapter;+use App\SyncAdapters\SyncAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Log;++/**+ * Google Workspace (ChromeOS) adapter. Pulls Chrome device inventory+ * from the Google Admin SDK Directory API and normalizes it into+ * HostInventoryRecord objects. Also pushes annotatedAssetId and+ * composed notes back to Google Admin so ChromeOS devices stay+ * aligned with Snipe-IT ownership.+ *+ * Auth model: service account with domain-wide delegation. The admin+ * creates a service account in Google Cloud Console, downloads a JSON+ * key, and delegates the required OAuth scopes to it in Google Admin+ * Console. The adapter signs an RS256 JWT with the service account+ * key, exchanges it for a bearer, and impersonates a real admin user+ * on every call. The impersonation email must belong to a super+ * admin (or a delegated admin with Chrome device permissions).+ *+ * Group scoping: Google organizational units (OUs) map to Snipe-IT+ * companies. Every Chrome device carries an `orgUnitPath` (e.g.+ * "/Sales/USA" or "/Engineering"), and the adapter uses that path as+ * the vendorGroupId so admins can route devices to Snipe-IT companies+ * by OU. The vendor group refresh endpoint calls Admin SDK's+ * /customer/{cid}/orgunits and lists every OU under the root.+ *+ * URL is not configurable. The Admin SDK is a single Google-hosted+ * endpoint (admin.googleapis.com), and token exchange lives at+ * oauth2.googleapis.com. Neither has regional variants.+ */+class GoogleWorkspaceAdapter extends SyncAdapter implements PushableAdapter+{+ public static function typeLabel(): string+ {+ return 'Google Workspace (ChromeOS)';+ }++ public static function typeSlug(): string+ {+ return 'google_workspace';+ }++ public static function docsUrl(): ?string+ {+ return 'https://developers.google.com/admin-sdk/directory/reference/rest/v1/chromeosdevices';+ }++ /**+ * Google Admin SDK is a single fixed host. Admins never type a URL.+ */+ public function usesConfigurableUrl(): bool+ {+ return false;+ }++ public function settingsSchema(): array+ {+ return [+ [+ 'key' => 'service_account_email',+ 'label' => trans('admin/settings/sync_adapters.google_workspace_label_service_account_email'),+ 'help' => trans('admin/settings/sync_adapters.google_workspace_service_account_email_help'),+ 'placeholder' => '[email protected]',+ ],+ [+ 'key' => 'private_key',+ 'label' => trans('admin/settings/sync_adapters.google_workspace_label_private_key'),+ 'type' => 'textarea',+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.google_workspace_private_key_help'),+ 'placeholder' => "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",+ ],+ [+ 'key' => 'impersonate_email',+ 'label' => trans('admin/settings/sync_adapters.google_workspace_label_impersonate_email'),+ 'help' => trans('admin/settings/sync_adapters.google_workspace_impersonate_email_help'),+ 'placeholder' => '[email protected]',+ ],+ [+ 'key' => 'customer_id',+ 'label' => trans('admin/settings/sync_adapters.google_workspace_label_customer_id'),+ 'help' => trans('admin/settings/sync_adapters.google_workspace_customer_id_help'),+ 'default' => 'my_customer',+ 'required' => false,+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'google_workspace_annotated_location' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_annotated_location'],+ 'google_workspace_annotated_user' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_annotated_user'],+ 'google_workspace_boot_mode' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_boot_mode'],+ 'google_workspace_dev_mode' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_dev_mode'],+ 'google_workspace_platform_version' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_platform_version'],+ 'google_workspace_firmware_version' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_firmware_version'],+ 'google_workspace_ethernet_mac' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_ethernet_mac'],+ 'google_workspace_wifi_mac' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_wifi_mac'],+ 'google_workspace_enrollment_time' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_enrollment_time'],+ 'google_workspace_org_unit_path' => ['label_key' => 'admin/settings/sync_adapters.google_workspace_extra_org_unit_path'],+ ];+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return trans('admin/settings/sync_adapters.vendor_group_google_workspace_org_unit');+ }++ /**+ * Fetch every organizational unit under the customer root. Admin+ * SDK returns a flat list keyed on orgUnitPath ("/Sales", "/Sales/USA",+ * etc.). We use the path as the group id because it's stable across+ * OU renames of ancestors and it's what per-device records carry as+ * `orgUnitPath`. The root OU ("/") is included as an explicit option+ * so admins can route devices at the top level.+ */+ public function fetchGroups(): array+ {+ $client = $this->buildClient();++ $groups = [['id' => '/', 'label' => '/']];+ foreach ($client->orgUnits() as $unit) {+ $path = (string) ($unit['orgUnitPath'] ?? '');+ if ($path === '') {+ continue;+ }+ $groups[] = [+ 'id' => $path,+ 'label' => $path,+ ];+ }++ return $groups;+ }++ public function pull(): iterable+ {+ $client = $this->buildClient();++ foreach ($client->chromeosDevices() as $device) {+ yield $this->normalize($device);+ }+ }++ /**+ * Convert a Chrome device payload into the normalized record shape.+ *+ * Admin SDK's stable id is `deviceId` (a GUID). Serial is at+ * `serialNumber`. Model comes as a marketing string ("HP Chromebook+ * 14 G6"). Manufacturer is not exposed on the Chrome device+ * resource today so it stays null unless the admin maps something+ * from extras.+ *+ * hostname preference order: annotatedAssetId (admin-assigned+ * label if any), then the marketing model plus a serial suffix so+ * every device gets a distinct-looking hostname in Snipe-IT even+ * when the admin has not typed an asset ID on the vendor side.+ * Never falls back to just the serial because that reads as+ * duplicate serial data in the UI.+ *+ * @param array<string, mixed> $device+ */+ private function normalize(array $device): HostInventoryRecord+ {+ $serial = Arr::get($device, 'serialNumber');+ $model = Arr::get($device, 'model');+ $annotatedAssetId = Arr::get($device, 'annotatedAssetId');++ $hostname = null;+ if (is_string($annotatedAssetId) && $annotatedAssetId !== '') {+ $hostname = $annotatedAssetId;+ } elseif (is_string($model) && $model !== '' && is_string($serial) && $serial !== '') {+ $hostname = $model.' ('.$serial.')';+ }++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($device, 'deviceId'),+ hostname: $hostname,+ hardwareSerial: $serial,+ hardwareModel: $model,+ manufacturer: null,+ primaryMac: Arr::get($device, 'ethernetMacAddress') ?? Arr::get($device, 'macAddress'),+ primaryIp: $this->extractPrimaryIp($device),+ os: 'ChromeOS',+ osVersion: Arr::get($device, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastSync')),+ assetTag: is_string($annotatedAssetId) && $annotatedAssetId !== '' ? $annotatedAssetId : null,+ assignedUserEmail: $this->extractUserEmail($device),+ vendorGroupId: Arr::get($device, 'orgUnitPath'),+ extra: [+ 'google_workspace_annotated_location' => Arr::get($device, 'annotatedLocation'),+ 'google_workspace_annotated_user' => Arr::get($device, 'annotatedUser'),+ 'google_workspace_boot_mode' => Arr::get($device, 'bootMode'),+ 'google_workspace_dev_mode' => Arr::get($device, 'devMode'),+ 'google_workspace_platform_version' => Arr::get($device, 'platformVersion'),+ 'google_workspace_firmware_version' => Arr::get($device, 'firmwareVersion'),+ 'google_workspace_ethernet_mac' => Arr::get($device, 'ethernetMacAddress'),+ 'google_workspace_wifi_mac' => Arr::get($device, 'macAddress'),+ 'google_workspace_enrollment_time' => Arr::get($device, 'lastEnrollmentTime'),+ 'google_workspace_org_unit_path' => Arr::get($device, 'orgUnitPath'),+ ],+ );+ }++ /**+ * `recentUsers[0].email` is the most-recently-signed-in Google+ * account. Empty or "unknown" strings (Chrome returns these when a+ * device has never signed in with a managed account) collapse to+ * null so the sync path treats them as "no user".+ *+ * @param array<string, mixed> $device+ */+ private function extractUserEmail(array $device): ?string+ {+ $email = Arr::get($device, 'recentUsers.0.email');+ if (! is_string($email) || $email === '' || strcasecmp($email, 'UNKNOWN_USER') === 0) {+ return null;+ }++ return $email;+ }++ /**+ * Admin SDK returns an array of network history entries. The most+ * recent one carries the current IP. Falls back to the top-level+ * `lastKnownNetwork[0].ipAddress` shape Google's docs describe.+ *+ * @param array<string, mixed> $device+ */+ private function extractPrimaryIp(array $device): ?string+ {+ $ip = Arr::get($device, 'lastKnownNetwork.0.ipAddress');+ if (is_string($ip) && $ip !== '') {+ return $ip;+ }++ return null;+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if (! is_string($value) || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }++ /**+ * Push is always available for a configured Google Workspace+ * instance. The delegated OAuth scope needed to write is+ * https://www.googleapis.com/auth/admin.directory.device.chromeos+ * (no `.readonly` suffix). Runtime failure surfaces as a 403 from+ * Google when the admin only granted the readonly scope.+ */+ public function canPush(): bool+ {+ return true;+ }++ /**+ * Google Admin exposes a freeform `notes` field on every Chrome+ * device. It is the natural target for composed notes (asset tag,+ * category, user display name, whatever the admin templates in the+ * settings UI).+ */+ public function notesFieldTarget(): ?string+ {+ return 'notes';+ }++ /**+ * Push Snipe-IT-owned fields back to Google Admin. Today the+ * writable set is: annotatedAssetId (from asset_tag when mapped+ * push), annotatedLocation (from asset location if mapped push),+ * annotatedUser (from assigned user email if mapped push), and+ * notes (from the composed-notes template). Fields the admin has+ * not directed push stay untouched.+ *+ * @param array<int, string> $changedFields+ */+ public function push(Asset $asset, array $changedFields = []): bool+ {+ $externalSource = $this->pushPrologue($asset, $changedFields);+ if ($externalSource === null) {+ return false;+ }++ $payload = $this->buildPushPayload($asset);+ $this->applyComposedNotesToPayload($asset, $payload);++ if ($payload === []) {+ return false;+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PATCH Google Admin Chrome device %s with %s',+ $this->name(),+ $externalSource->external_id,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));++ return true;+ }++ $this->buildClient()->updateChromeosDevice($externalSource->external_id, $payload);++ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Google Admin Chrome device %s (%s)',+ $this->name(),+ $externalSource->external_id,+ implode(',', array_keys($payload)),+ ));++ return true;+ }++ /**+ * Map push-directed Snipe-IT fields onto Google Admin write keys.+ * Only the fields the admin has flagged push (or both) in the+ * direction UI appear here. This is the base payload before+ * composed notes are spliced in.+ *+ * @return array<string, mixed>+ */+ protected function buildPushPayload(Asset $asset): array+ {+ $payload = [];++ foreach ($this->pushDirectedFields() as $field) {+ $target = $this->pushTargetForField($field);+ if ($target === null) {+ continue;+ }+ $payload[$target] = $this->assetValueForSourceField($asset, $field);+ }++ return $payload;+ }++ /**+ * Snipe-IT source field -> Google Admin write key. Fields not in+ * this map do not have a Google-side counterpart and are skipped+ * on push even if the admin flagged them push-direction.+ *+ * `google_workspace_annotated_user` is one of the vendor-specific+ * extras exposed via extraFields(). Admins flag direction=push on+ * it in the mapping UI so Google's annotatedUser field mirrors+ * whoever the asset is currently checked out to on the Snipe-IT+ * side. Value resolution happens in assetValueForSourceField()+ * below, which reads asset->assignedTo->email at push time.+ */+ private function pushTargetForField(string $field): ?string+ {+ return match ($field) {+ 'asset_tag' => 'annotatedAssetId',+ 'google_workspace_annotated_user' => 'annotatedUser',+ default => null,+ };+ }++ /**+ * Resolve Snipe-IT source-field values for push. Standard fields+ * (asset_tag, hostname, serial, etc.) fall through to the parent+ * implementation. The vendor-specific extras this adapter can+ * push get resolved here.+ *+ * `google_workspace_annotated_user` returns the assigned user's+ * email address (Google's freeform annotatedUser field is a+ * string, and Google Admin convention is to store the primary+ * account there). Falls back to the user's display name when+ * no email is on file. Returns null when the asset is+ * unassigned or is checked out to a Location / another Asset+ * rather than a User. buildPushPayload includes the key in the+ * PATCH regardless, so a null value clears annotatedUser on+ * Google's side, which propagates check-in state through the+ * sync.+ */+ protected function assetValueForSourceField(Asset $asset, string $field): mixed+ {+ if ($field === 'google_workspace_annotated_user') {+ $assignee = $asset->assignedTo;+ if (! $assignee instanceof \App\Models\User) {+ return null;+ }++ return $assignee->email ?: $assignee->display_name;+ }++ return parent::assetValueForSourceField($asset, $field);+ }++ private function buildClient(): GoogleWorkspaceClient+ {+ return new GoogleWorkspaceClient(+ serviceAccountEmail: $this->credential('service_account_email'),+ privateKeyPem: $this->credential('private_key'),+ impersonateEmail: $this->credential('impersonate_email'),+ customerId: $this->credential('customer_id') ?: 'my_customer',+ );+ }+}diff --git a/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.phpnew file mode 100644index 0000000000..bf3baa6079--- /dev/null+++ b/app/SyncAdapters/GoogleWorkspace/GoogleWorkspaceClient.php@@ -0,0 +1,188 @@+<?php++namespace App\SyncAdapters\GoogleWorkspace;++use Firebase\JWT\JWT;+use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Google Admin SDK Directory API for Chrome+ * device management. Handles service-account JWT signing (RS256),+ * OAuth 2.0 token exchange with domain-wide delegation, and Admin+ * SDK's pageToken pagination.+ *+ * Auth model: the admin creates a service account in Google Cloud+ * Console, downloads its JSON key, and grants it domain-wide+ * delegation for the scopes below in Google Admin Console. On every+ * sync, the client signs a JWT that names the target admin user in+ * its `sub` claim, exchanges it at oauth2.googleapis.com for a short-+ * lived bearer, and caches that bearer for the life of the client.+ *+ * Scopes requested:+ * - admin.directory.device.chromeos (read + write per-device metadata)+ * - admin.directory.orgunit.readonly (list OUs for group scoping)+ *+ * If the admin only granted the .readonly counterpart of the first+ * scope during delegation, pull works but push fails with 403 at+ * PATCH time. Not something we can predict from client-side probing+ * so it surfaces as a normal push error.+ */+class GoogleWorkspaceClient+{+ private const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';++ private const ADMIN_SDK_BASE_URL = 'https://admin.googleapis.com/admin/directory/v1';++ private const REQUIRED_SCOPES = [+ 'https://www.googleapis.com/auth/admin.directory.device.chromeos',+ 'https://www.googleapis.com/auth/admin.directory.orgunit.readonly',+ ];++ private ?string $accessToken = null;++ public function __construct(+ private readonly string $serviceAccountEmail,+ private readonly string $privateKeyPem,+ private readonly string $impersonateEmail,+ private readonly string $customerId = 'my_customer',+ ) {}++ /**+ * Iterate every Chrome device visible to the impersonated admin.+ * Admin SDK caps the page size at 300 devices. Uses `nextPageToken`+ * for forward paging.+ *+ * projection=FULL returns every field the API exposes (recent+ * users, network history, dev mode, boot mode, etc.). BASIC omits+ * most of what the adapter maps into extras, so FULL is worth the+ * per-page cost.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function chromeosDevices(int $pageSize = 200): iterable+ {+ $pageToken = null;++ do {+ $params = [+ 'projection' => 'FULL',+ 'maxResults' => $pageSize,+ ];+ if (is_string($pageToken) && $pageToken !== '') {+ $params['pageToken'] = $pageToken;+ }++ $response = $this->request()+ ->get('/customer/'.$this->customerId.'/devices/chromeos', $params)+ ->throw()+ ->json();++ foreach (($response['chromeosdevices'] ?? []) as $device) {+ yield $device;+ }++ $pageToken = $response['nextPageToken'] ?? null;+ } while (is_string($pageToken) && $pageToken !== '');+ }++ /**+ * List every organizational unit under the customer root. Result+ * is a flat array of unit objects, each with orgUnitPath,+ * orgUnitId, name, description. The adapter uses orgUnitPath as+ * the vendor group id.+ *+ * @return array<int, array<string, mixed>>+ */+ public function orgUnits(): array+ {+ $response = $this->request()+ ->get('/customer/'.$this->customerId.'/orgunits', [+ 'type' => 'all',+ ])+ ->throw()+ ->json();++ return $response['organizationUnits'] ?? [];+ }++ /**+ * PATCH writable fields on a single Chrome device. Fields the+ * caller doesn't include stay untouched. Google accepts partial+ * updates on annotatedAssetId, annotatedLocation, annotatedUser,+ * notes, and orgUnitPath.+ *+ * @param array<string, mixed> $payload+ */+ public function updateChromeosDevice(string $deviceId, array $payload): void+ {+ Http::baseUrl(self::ADMIN_SDK_BASE_URL)+ ->withToken($this->bearer())+ ->withOptions(['allow_redirects' => false])+ ->asJson()+ ->acceptJson()+ ->timeout(30)+ ->patch('/customer/'.$this->customerId.'/devices/chromeos/'.$deviceId, $payload)+ ->throw();+ }++ /**+ * Sign an RS256 JWT and exchange it for an OAuth bearer via the+ * urn:ietf:params:oauth:grant-type:jwt-bearer flow. Token is+ * short-lived (~1 hour) and cached on this instance so a full+ * sync doesn't retrigger auth per request.+ */+ private function bearer(): string+ {+ if ($this->accessToken !== null) {+ return $this->accessToken;+ }++ $assertion = $this->buildJwtAssertion();++ $response = Http::asForm()+ ->withOptions(['allow_redirects' => false])+ ->timeout(30)+ ->post(self::TOKEN_ENDPOINT, [+ 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ 'assertion' => $assertion,+ ])+ ->throw()+ ->json();++ return $this->accessToken = (string) ($response['access_token'] ?? '');+ }++ /**+ * Sign an RS256 JWT with the service account private key. Google+ * requires a max 1-hour expiration. We use 55 minutes to give the+ * exchange enough slack, matching Google's own client-library+ * default. `sub` names the impersonated admin (domain-wide+ * delegation, without which the Directory API returns 401).+ */+ private function buildJwtAssertion(): string+ {+ $now = time();+ $payload = [+ 'iss' => $this->serviceAccountEmail,+ 'scope' => implode(' ', self::REQUIRED_SCOPES),+ 'aud' => self::TOKEN_ENDPOINT,+ 'iat' => $now,+ 'exp' => $now + 3300,+ 'sub' => $this->impersonateEmail,+ ];++ return JWT::encode($payload, $this->privateKeyPem, 'RS256');+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(self::ADMIN_SDK_BASE_URL)+ ->withToken($this->bearer())+ ->withOptions(['allow_redirects' => false])+ ->acceptJson()+ ->timeout(30)+ ->retry(3, 500, fn (\Exception $e) => $e instanceof \Illuminate\Http\Client\ConnectionException+ || ($e instanceof \Illuminate\Http\Client\RequestException && $e->response->status() === 429));+ }+}diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 390acf8838..c589547180 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -191,6 +191,26 @@ return ['jamf_platform_environment_id_help' => 'UUID of the Platform environment the integration is scoped to. Copy from Jamf Account under Environments, or from the URL of your environment console. Sent as the X-Environment-Id header on every request.','landscape_token_help' => 'Landscape does not have a UI for API tokens. Obtain one by POSTing your credentials to <code>/api/v2/login</code> on your Landscape instance and copying the <code>token</code> field from the JSON response. Pass an <code>expiry_minutes</code> value on that call to control how long the token stays valid (defaults to 24h). The account behind the token needs read access to computers.',+ // Google Workspace (ChromeOS) adapter+ 'google_workspace_label_service_account_email' => 'Service Account Email',+ 'google_workspace_label_private_key' => 'Service Account Private Key',+ 'google_workspace_label_impersonate_email' => 'Impersonate Admin Email',+ 'google_workspace_label_customer_id' => 'Customer ID',+ 'google_workspace_service_account_email_help' => 'Create a service account in Google Cloud Console under IAM & Admin -> Service Accounts. Enable the Admin SDK API on the project. Copy the service account email (ends with .iam.gserviceaccount.com) here.',+ 'google_workspace_private_key_help' => 'Download a JSON key for the service account and paste the <code>private_key</code> value here (including the BEGIN and END lines). Only the private key belongs in this field, not the whole JSON blob. Google only lets you download each key once, so create a new one rather than trying to re-download an existing key.',+ 'google_workspace_impersonate_email_help' => 'The service account cannot call the Directory API on its own. In Google Admin Console -> Security -> Access and data control -> API controls -> Domain-wide delegation, add the service account and grant it the <code>admin.directory.device.chromeos</code> and <code>admin.directory.orgunit.readonly</code> OAuth scopes. Then enter the email of a Google Workspace admin user the service account should impersonate here.',+ 'google_workspace_customer_id_help' => 'Leave as <code>my_customer</code> for a single-tenant setup. Multi-tenant resellers may set this to a specific customer ID from Google Admin Console.',+ 'google_workspace_extra_annotated_location' => 'Google Annotated Location',+ 'google_workspace_extra_annotated_user' => 'Google Annotated User',+ 'google_workspace_extra_boot_mode' => 'Google Boot Mode',+ 'google_workspace_extra_dev_mode' => 'Google Dev Mode',+ 'google_workspace_extra_platform_version' => 'Google Platform Version',+ 'google_workspace_extra_firmware_version' => 'Google Firmware Version',+ 'google_workspace_extra_ethernet_mac' => 'Google Ethernet MAC',+ 'google_workspace_extra_wifi_mac' => 'Google WiFi MAC',+ 'google_workspace_extra_enrollment_time' => 'Google Enrollment Time',+ 'google_workspace_extra_org_unit_path' => 'Google Org Unit Path',+// Custom HTTP adapter'custom_auth_method_help' => 'How the adapter authenticates against your API. <code>Bearer</code> sends a Bearer token in the <code>Authorization</code> header. <code>Basic</code> sends username + password. <code>API Key</code> sends the value in a custom header. <code>None</code> sends no auth headers.','custom_bearer_token_help' => 'Used when Authentication Method is set to <code>Bearer Token</code>. The value is sent as the <code>Authorization: Bearer <token></code> header.',@@ -355,6 +375,7 @@ return ['vendor_group_jamf_platform_blueprint' => 'Jamf Platform Blueprint','vendor_group_mosyle_location' => 'Mosyle Location','vendor_group_kaseya_organization' => 'Kaseya Organization',+ 'vendor_group_google_workspace_org_unit' => 'Google Organizational Unit',// Kaseya-specific label prefix for tenant-defined custom fields// captured by the "Refresh custom fields" button. Rendered in thediff --git a/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapterTest.php b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapterTest.phpnew file mode 100644index 0000000000..c5e202296d--- /dev/null+++ b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceAdapterTest.php@@ -0,0 +1,224 @@+<?php++namespace Tests\Feature\SyncAdapters\GoogleWorkspace;++use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\GoogleWorkspace\GoogleWorkspaceAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * End-to-end pull coverage for the Google Workspace (ChromeOS)+ * adapter. Fakes the OAuth token exchange at oauth2.googleapis.com+ * and the Admin SDK Directory API chromeosdevices endpoint. Verifies+ * the normalized record shape, sourceKey / sourceId routing, and OU+ * -> vendorGroupId mapping.+ */+class GoogleWorkspaceAdapterTest extends TestCase+{+ private string $privateKeyPem = '';++ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();++ $key = openssl_pkey_new([+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,+ 'private_key_bits' => 2048,+ ]);+ openssl_pkey_export($key, $pem);+ $this->privateKeyPem = $pem;+ }++ public function test_pulls_chromeos_devices_and_creates_assets(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3300]),+ '*/devices/chromeos*' => Http::response([+ 'chromeosdevices' => [+ $this->chromeDevice(deviceId: 'guid-42', serial: 'SN-42'),+ $this->chromeDevice(deviceId: 'guid-99', serial: 'SN-99'),+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 2);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'google_workspace', 'external_id' => 'guid-42']);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'google_workspace', 'external_id' => 'guid-99']);+ }++ public function test_normalized_record_carries_expected_fields(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3300]),+ '*/devices/chromeos*' => Http::response([+ 'chromeosdevices' => [+ [+ 'deviceId' => 'guid-7',+ 'serialNumber' => 'CHROM-7',+ 'model' => 'HP Chromebook 14 G6',+ 'annotatedAssetId' => 'ACME-042',+ 'annotatedLocation' => 'HQ / Row 3',+ 'annotatedUser' => '[email protected]',+ 'ethernetMacAddress' => 'aa:bb:cc:dd:ee:ff',+ 'macAddress' => '11:22:33:44:55:66',+ 'osVersion' => '119.0.6045.184',+ 'platformVersion' => '15633.69.0',+ 'firmwareVersion' => 'Google_Careena.13434.687.0',+ 'bootMode' => 'Verified',+ 'devMode' => false,+ 'lastSync' => '2026-01-15T10:00:00Z',+ 'lastEnrollmentTime' => '2024-08-10T09:15:00Z',+ 'orgUnitPath' => '/Sales/USA',+ 'recentUsers' => [+ ['email' => '[email protected]', 'type' => 'USER_TYPE_MANAGED'],+ ],+ 'lastKnownNetwork' => [+ ['ipAddress' => '10.0.4.42'],+ ],+ ],+ ],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);++ $record = $records[0];+ $this->assertSame('google_workspace', $record->sourceKey);+ $this->assertSame('guid-7', $record->sourceId);+ $this->assertSame('ACME-042', $record->hostname);+ $this->assertSame('CHROM-7', $record->hardwareSerial);+ $this->assertSame('HP Chromebook 14 G6', $record->hardwareModel);+ $this->assertSame('aa:bb:cc:dd:ee:ff', $record->primaryMac);+ $this->assertSame('10.0.4.42', $record->primaryIp);+ $this->assertSame('ChromeOS', $record->os);+ $this->assertSame('119.0.6045.184', $record->osVersion);+ $this->assertSame('ACME-042', $record->assetTag);+ $this->assertSame('[email protected]', $record->assignedUserEmail);+ $this->assertSame('/Sales/USA', $record->vendorGroupId);+ $this->assertNotNull($record->lastSeen);++ // Extras carry ChromeOS-specific data for the extra-field+ // mapping UI to route into custom fields.+ $this->assertSame('HQ / Row 3', $record->extra['google_workspace_annotated_location']);+ $this->assertSame('Verified', $record->extra['google_workspace_boot_mode']);+ $this->assertFalse($record->extra['google_workspace_dev_mode']);+ $this->assertSame('15633.69.0', $record->extra['google_workspace_platform_version']);+ $this->assertSame('/Sales/USA', $record->extra['google_workspace_org_unit_path']);+ }++ public function test_hostname_falls_back_to_model_plus_serial_when_annotated_asset_id_is_missing(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'stub', 'expires_in' => 3300]),+ '*/devices/chromeos*' => Http::response([+ 'chromeosdevices' => [+ [+ 'deviceId' => 'guid-none',+ 'serialNumber' => 'SN-NAKED',+ 'model' => 'Lenovo Chromebook Duet 5',+ ],+ ],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertSame('Lenovo Chromebook Duet 5 (SN-NAKED)', $records[0]->hostname);+ $this->assertNull($records[0]->assetTag);+ }++ public function test_unknown_user_recent_user_is_treated_as_no_user(): void+ {+ // Google Admin uses "UNKNOWN_USER" as the sentinel string when+ // a Chrome device is signed in with a personal account and the+ // domain policy is set to hide personal-account details. The+ // sync path must not try to match "UNKNOWN_USER" against a+ // Snipe-IT user.+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'stub', 'expires_in' => 3300]),+ '*/devices/chromeos*' => Http::response([+ 'chromeosdevices' => [+ [+ 'deviceId' => 'guid-anon',+ 'serialNumber' => 'SN-ANON',+ 'model' => 'Acer Chromebook',+ 'recentUsers' => [+ ['email' => 'UNKNOWN_USER', 'type' => 'USER_TYPE_UNMANAGED'],+ ],+ ],+ ],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertNull($records[0]->assignedUserEmail);+ }++ public function test_org_units_refresh_returns_flat_list_with_root(): void+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'https://oauth2.googleapis.com/token' => Http::response(['access_token' => 'stub', 'expires_in' => 3300]),+ '*/orgunits*' => Http::response([+ 'organizationUnits' => [+ ['orgUnitPath' => '/Sales', 'name' => 'Sales'],+ ['orgUnitPath' => '/Sales/USA', 'name' => 'USA'],+ ['orgUnitPath' => '/Engineering', 'name' => 'Engineering'],+ ],+ ]),+ ]);++ $groups = $adapter->fetchGroups();++ // Root OU is prepended so admins can route devices at the+ // customer-root level.+ $this->assertSame('/', $groups[0]['id']);+ $ids = array_column($groups, 'id');+ $this->assertContains('/Sales', $ids);+ $this->assertContains('/Sales/USA', $ids);+ $this->assertContains('/Engineering', $ids);+ }++ private function configuredAdapter(): GoogleWorkspaceAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'service_account_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'impersonate_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'customer_id', 'my_customer');+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));++ return new GoogleWorkspaceAdapter($instance->fresh());+ }++ /**+ * @return array<string, mixed>+ */+ private function chromeDevice(string $deviceId, string $serial): array+ {+ return [+ 'deviceId' => $deviceId,+ 'serialNumber' => $serial,+ 'model' => 'Chromebook Generic',+ 'orgUnitPath' => '/',+ ];+ }+}diff --git a/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspacePushTest.php b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspacePushTest.phpnew file mode 100644index 0000000000..95c364269d--- /dev/null+++ b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspacePushTest.php@@ -0,0 +1,322 @@+<?php++namespace Tests\Feature\SyncAdapters\GoogleWorkspace;++use App\Models\Asset;+use App\Models\AssetExternalSource;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\GoogleWorkspace\GoogleWorkspaceAdapter;+use App\SyncAdapters\PushableAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * End-to-end coverage for Google Workspace (ChromeOS) push. Google+ * Admin exposes annotatedAssetId (asset tag) and notes (composed) as+ * the two writable fields Snipe-IT populates. Both PATCH against the+ * same Chrome device endpoint. Tests verify the PATCH lands with the+ * right shape, dry-run behaves, and the composed-notes template is+ * spliced onto the payload.+ */+class GoogleWorkspacePushTest extends TestCase+{+ private string $privateKeyPem = '';++ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();++ $key = openssl_pkey_new([+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,+ 'private_key_bits' => 2048,+ ]);+ openssl_pkey_export($key, $pem);+ $this->privateKeyPem = $pem;+ }++ public function test_adapter_implements_pushable_interface(): void+ {+ $this->assertInstanceOf(PushableAdapter::class, $this->configuredAdapter());+ }++ public function test_composed_notes_template_patches_google_chrome_device(): void+ {+ $adapter = $this->configuredAdapter(template: 'Owned by Snipe-IT: {asset_tag}');+ $asset = Asset::factory()->create(['asset_tag' => 'ACME-042']);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => $adapter->name(),+ 'external_id' => 'chrome-device-guid-42',+ ]);++ Http::fake(function ($request) {+ if (str_contains($request->url(), '/oauth2.googleapis.com/token') || str_contains($request->url(), '/token')) {+ return Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3300]);+ }+ if ($request->method() === 'PATCH' && str_contains($request->url(), '/devices/chromeos/chrome-device-guid-42')) {+ return Http::response(['ok' => true]);+ }++ return Http::response(['unmatched' => true], 500);+ });++ $adapter->push($asset);++ Http::assertSent(function ($request) {+ if ($request->method() !== 'PATCH') {+ return false;+ }+ if (! str_contains($request->url(), '/devices/chromeos/chrome-device-guid-42')) {+ return false;+ }+ $notes = $request->data()['notes'] ?? '';++ return str_contains($notes, 'Owned by Snipe-IT: ACME-042');+ });+ }++ public function test_asset_tag_direction_push_writes_to_annotated_asset_id(): void+ {+ // Admin flags asset_tag with direction=push in the mapping UI.+ // buildPushPayload maps that to Google's annotatedAssetId key+ // on the Chrome device resource.+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.asset_tag', 'push');++ $asset = Asset::factory()->create(['asset_tag' => 'TAGGED-1']);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-tag-guid-1',+ ]);++ Http::fake(function () {+ return Http::response(['access_token' => 'stub', 'expires_in' => 3300]);+ });++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $freshAdapter->push($asset);++ Http::assertSent(function ($request) {+ if ($request->method() !== 'PATCH') {+ return false;+ }++ return ($request->data()['annotatedAssetId'] ?? null) === 'TAGGED-1';+ });+ }++ public function test_dry_run_skips_the_http_call_and_logs_payload(): void+ {+ $adapter = $this->configuredAdapter(template: 'Tag: {asset_tag}');+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'push_dry_run', '1');++ $asset = Asset::factory()->create(['asset_tag' => 'DRY-1']);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-dry-guid',+ ]);++ Http::fake();++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $result = $freshAdapter->push($asset);++ $this->assertTrue($result);+ // No HTTP call goes out in dry-run mode. Everything logs+ // through the sync-adapters channel so admins can inspect the+ // payload before flipping the toggle off.+ Http::assertNothingSent();+ }++ public function test_annotated_user_push_writes_assigned_users_email(): void+ {+ // Admin flags google_workspace_annotated_user with+ // direction=push. buildPushPayload maps that extras key to+ // Google's annotatedUser field on the Chrome device resource+ // and reads the value from asset->assignedTo->email.+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.google_workspace_annotated_user', 'push');++ $assignee = \App\Models\User::factory()->create([+ 'email' => '[email protected]',+ 'first_name' => 'Carol',+ 'last_name' => 'Danvers',+ ]);+ $asset = Asset::factory()->create();+ $asset->assigned_to = $assignee->id;+ $asset->assigned_type = \App\Models\User::class;+ $asset->save();++ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-user-guid-42',+ ]);++ Http::fake(function () {+ return Http::response(['access_token' => 'stub', 'expires_in' => 3300]);+ });++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $freshAdapter->push($asset);++ Http::assertSent(function ($request) {+ if ($request->method() !== 'PATCH') {+ return false;+ }++ return ($request->data()['annotatedUser'] ?? null) === '[email protected]';+ });+ }++ public function test_annotated_user_push_falls_back_to_display_name_when_email_is_blank(): void+ {+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.google_workspace_annotated_user', 'push');++ $assignee = \App\Models\User::factory()->create([+ 'email' => '',+ 'first_name' => 'No',+ 'last_name' => 'Email',+ ]);+ $asset = Asset::factory()->create();+ $asset->assigned_to = $assignee->id;+ $asset->assigned_type = \App\Models\User::class;+ $asset->save();++ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-noemail-guid',+ ]);++ Http::fake(fn () => Http::response(['access_token' => 'stub', 'expires_in' => 3300]));++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $freshAdapter->push($asset);++ Http::assertSent(function ($request) use ($assignee) {+ if ($request->method() !== 'PATCH') {+ return false;+ }++ // display_name accessor produces "No Email" for the+ // first_name / last_name pair above.+ return ($request->data()['annotatedUser'] ?? null) === $assignee->display_name;+ });+ }++ public function test_annotated_user_push_sends_null_when_asset_is_unassigned(): void+ {+ // A checkin on the Snipe-IT side should clear Google's+ // annotatedUser so both systems reflect that nobody currently+ // owns the device. Google's PATCH semantics treat a null value+ // as a clear, so we let it through unmodified.+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.google_workspace_annotated_user', 'push');++ $asset = Asset::factory()->create();+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-unassigned-guid',+ ]);++ Http::fake(fn () => Http::response(['access_token' => 'stub', 'expires_in' => 3300]));++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $freshAdapter->push($asset);++ Http::assertSent(function ($request) {+ if ($request->method() !== 'PATCH') {+ return false;+ }++ // Key IS present in payload (so Google clears its side)+ // and the value is null.+ return array_key_exists('annotatedUser', $request->data())+ && $request->data()['annotatedUser'] === null;+ });+ }++ public function test_annotated_user_push_skipped_when_asset_is_checked_out_to_a_location(): void+ {+ // assignedTo is polymorphic. Checkout to a Location, another+ // Asset, or anything other than a User has no email to write,+ // so the push skips the field. Key IS still present in the+ // PATCH so Google's side stays in sync with "no user owns+ // this right now".+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'direction.google_workspace_annotated_user', 'push');++ $location = \App\Models\Location::factory()->create();+ $asset = Asset::factory()->create();+ $asset->assigned_to = $location->id;+ $asset->assigned_type = \App\Models\Location::class;+ $asset->save();++ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-loc-guid',+ ]);++ Http::fake(fn () => Http::response(['access_token' => 'stub', 'expires_in' => 3300]));++ $freshAdapter = new GoogleWorkspaceAdapter($instance->fresh());+ $freshAdapter->push($asset);++ Http::assertSent(function ($request) {+ if ($request->method() !== 'PATCH') {+ return false;+ }++ return array_key_exists('annotatedUser', $request->data())+ && $request->data()['annotatedUser'] === null;+ });+ }++ public function test_blank_template_and_no_directed_fields_skips_push(): void+ {+ $adapter = $this->configuredAdapter(template: '');+ $asset = Asset::factory()->create(['asset_tag' => 'NOTPL']);+ AssetExternalSource::create([+ 'asset_id' => $asset->id,+ 'source' => 'google_workspace',+ 'external_id' => 'chrome-blank-guid',+ ]);++ Http::fake();++ $result = $adapter->push($asset);++ $this->assertFalse($result);+ Http::assertNothingSent();+ }++ private function configuredAdapter(?string $template = null): GoogleWorkspaceAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'service_account_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'impersonate_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'customer_id', 'my_customer');+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));+ if ($template !== null) {+ SyncAdapterConfig::put($instance->id, 'push_notes_template', $template);+ }++ return new GoogleWorkspaceAdapter($instance->fresh());+ }+}diff --git a/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceSettingsPageTest.php b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceSettingsPageTest.phpnew file mode 100644index 0000000000..2591baacb6--- /dev/null+++ b/tests/Feature/SyncAdapters/GoogleWorkspace/GoogleWorkspaceSettingsPageTest.php@@ -0,0 +1,96 @@+<?php++namespace Tests\Feature\SyncAdapters\GoogleWorkspace;++use App\Models\Category;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Models\User;+use Illuminate\Support\Facades\Crypt;+use Tests\TestCase;++/**+ * Smoke coverage for the Google Workspace (ChromeOS) adapter's+ * registration + settings-page presence. The schema mixes three+ * non-secret fields (service account email, impersonate admin email,+ * customer id) with one secret (the private key), so this test proves+ * the SyncAdapter base's per-schema encryption dispatch works:+ * secret gets encrypted at rest, plain-text fields stay plain.+ */+class GoogleWorkspaceSettingsPageTest extends TestCase+{+ public function test_google_workspace_tab_renders_on_the_adapters_page()+ {+ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('settings.adapters.index'))+ ->assertOk()+ ->assertSee('Google Workspace (ChromeOS)')+ ->assertSee('Service Account Email')+ ->assertSee('Service Account Private Key')+ ->assertSee('Impersonate Admin Email')+ ->assertSee('Customer ID');+ }++ public function test_saving_google_workspace_encrypts_only_the_private_key()+ {+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.adapters.save', $instance), [+ 'google_workspace_service_account_email' => '[email protected]',+ 'google_workspace_private_key' => "-----BEGIN PRIVATE KEY-----\nfake-key-material\n-----END PRIVATE KEY-----",+ 'google_workspace_impersonate_email' => '[email protected]',+ 'google_workspace_customer_id' => 'my_customer',+ 'google_workspace_default_category_id' => Category::factory()->create()->id,+ 'google_workspace_default_status_id' => Statuslabel::factory()->rtd()->create()->id,+ ])+ ->assertRedirect(route('settings.adapters.index', ['adapter' => $instance->slug]));++ // Non-secret fields land as plain text so admins can audit+ // which service account a Snipe-IT instance is talking to+ // without a decrypt step.+ $this->assertSame(+ '[email protected]',+ SyncAdapterConfig::get($instance->id, 'service_account_email'),+ );+ $this->assertSame('[email protected]', SyncAdapterConfig::get($instance->id, 'impersonate_email'));+ $this->assertSame('my_customer', SyncAdapterConfig::get($instance->id, 'customer_id'));++ // Secret field is Crypt-encrypted at rest. A regression that+ // stored the private key plain would surface here.+ $storedKey = SyncAdapterConfig::get($instance->id, 'private_key');+ $this->assertStringNotContainsString('fake-key-material', $storedKey);+ $this->assertStringContainsString('fake-key-material', Crypt::decrypt($storedKey));+ }++ public function test_blank_credentials_on_save_fail_validation()+ {+ $instance = SyncAdapterInstance::where('slug', 'google_workspace')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'service_account_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'impersonate_email', '[email protected]');+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt('existing-key-material'));++ $this->actingAs(User::factory()->superuser()->create())+ ->from(route('settings.adapters.index', ['adapter' => $instance->slug]))+ ->post(route('settings.adapters.save', $instance), [+ 'google_workspace_service_account_email' => '',+ 'google_workspace_private_key' => '',+ 'google_workspace_impersonate_email' => '',+ 'google_workspace_default_category_id' => Category::factory()->create()->id,+ 'google_workspace_default_status_id' => Statuslabel::factory()->rtd()->create()->id,+ ])+ ->assertRedirect()+ ->assertSessionHasErrors([+ 'google_workspace_service_account_email',+ 'google_workspace_private_key',+ 'google_workspace_impersonate_email',+ ]);++ // Nothing persisted since the save was rejected. Prior values+ // stay intact.+ $this->assertSame('[email protected]', SyncAdapterConfig::get($instance->id, 'service_account_email'));+ $this->assertSame('[email protected]', SyncAdapterConfig::get($instance->id, 'impersonate_email'));+ $this->assertSame('existing-key-material', Crypt::decrypt(SyncAdapterConfig::get($instance->id, 'private_key')));+ }+}