Skip to content

A free open source IT asset/license management system

Fixed #19737 - Jamf adapter token caching

snipe3e0695c5b0ab
diff --git a/app/SyncAdapters/Jamf/JamfAdapter.php b/app/SyncAdapters/Jamf/JamfAdapter.php
index 3ae69e1eb9..bc8ecdf7b0 100644
--- a/app/SyncAdapters/Jamf/JamfAdapter.php
+++ b/app/SyncAdapters/Jamf/JamfAdapter.php
@@ -11,10 +11,13 @@ use Illuminate\Support\Arr;
/**
* Jamf Pro adapter. Pulls computer inventory via the Jamf Pro API and
- * normalizes it into HostInventoryRecord objects. Uses a Jamf-generated
- * Personal Access Token as a bearer credential. Also pushes
- * Snipe-IT-authoritative fields (asset_tag today) back to Jamf via
- * the /api/v1/computers-inventory-detail/{id} PATCH endpoint.
+ * normalizes it into HostInventoryRecord objects. Authenticates via
+ * OAuth 2.0 client credentials against Jamf Pro's /api/oauth/token
+ * endpoint (Jamf Pro does not issue long-lived personal tokens, so
+ * this is the only workable flow). Also pushes Snipe-IT-authoritative
+ * fields (asset_tag today) back to Jamf via the
+ * /api/v1/computers-inventory-detail/{id} PATCH endpoint using the
+ * same exchanged bearer.
*/
class JamfAdapter extends SyncAdapter implements PushableAdapter
{
@@ -42,10 +45,15 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter
{
return [
[
- 'key' => 'token',
- 'label' => trans('admin/settings/sync_adapters.label_api_token'),
+ 'key' => 'client_id',
+ 'label' => trans('admin/settings/sync_adapters.label_client_id'),
+ 'help' => trans('admin/settings/sync_adapters.jamf_client_id_help'),
+ ],
+ [
+ 'key' => 'client_secret',
+ 'label' => trans('admin/settings/sync_adapters.label_client_secret'),
'secret' => true,
- 'help' => trans('admin/settings/sync_adapters.jamf_token_help'),
+ 'help' => trans('admin/settings/sync_adapters.jamf_client_secret_help'),
],
];
}
@@ -71,7 +79,11 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter
public function fetchGroups(): array
{
- $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));
+ $client = new JamfClient(
+ baseUrl: $this->url(),
+ clientId: $this->credential('client_id'),
+ clientSecret: $this->credential('client_secret'),
+ );
return array_map(
fn (array $site) => [
@@ -84,7 +96,11 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter
public function pull(): iterable
{
- $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));
+ $client = new JamfClient(
+ baseUrl: $this->url(),
+ clientId: $this->credential('client_id'),
+ clientSecret: $this->credential('client_secret'),
+ );
foreach ($client->computers() as $computer) {
yield $this->normalize($computer);
@@ -135,10 +151,10 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter
}
/**
- * Jamf Pro writes are gated by the PAT's API role scopes. Both
- * pull + push work with the same token when the role grants the
- * "Update Computers" privilege. No tier / license gate, so canPush
- * is always true for a configured instance.
+ * Jamf Pro writes are gated by the API Client's role privileges.
+ * Both pull + push work with the same OAuth client when the role
+ * grants the "Update Computers" privilege. No tier / license gate,
+ * so canPush is always true for a configured instance.
*/
public function canPush(): bool
{
@@ -200,7 +216,11 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter
*/
protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void
{
- $client = new JamfClient(baseUrl: $this->url(), token: $this->credential('token'));
+ $client = new JamfClient(
+ baseUrl: $this->url(),
+ clientId: $this->credential('client_id'),
+ clientSecret: $this->credential('client_secret'),
+ );
$client->updateComputerDetail($externalSource->external_id, $payload);
}
diff --git a/app/SyncAdapters/Jamf/JamfClient.php b/app/SyncAdapters/Jamf/JamfClient.php
index 91e4f6a017..a39fb5b9f4 100644
--- a/app/SyncAdapters/Jamf/JamfClient.php
+++ b/app/SyncAdapters/Jamf/JamfClient.php
@@ -10,19 +10,31 @@ use Illuminate\Support\Facades\Http;
* endpoints the sync adapter uses. Yields raw decoded JSON, no
* normalization (that's the adapter's job).
*
- * Auth model: a Jamf-generated Personal Access Token (create one under
- * Settings -> System -> API Roles and Clients -> API Roles) passed as
- * a bearer token. This skips the /api/v1/auth/token exchange dance and
- * keeps the credential storage shape identical to the other bearer-
- * token adapters (Fleet, Kandji, JumpCloud).
+ * Auth model: OAuth 2.0 client credentials. The admin creates an API
+ * Role granting Read on Computers (plus Read on Sites when
+ * group-to-company mapping is in play) and an API Client that uses
+ * that role, under Settings -> System -> API Roles and Clients in
+ * Jamf Pro. This client exchanges the Client ID + Client Secret for a
+ * bearer token via POST /api/oauth/token and caches it on the instance
+ * (with a small buffer before expiry so a slow sync run does not
+ * present a token that's about to be rejected). Jamf Pro's default
+ * token lifetime is 60 seconds, so any non-trivial sync will refresh
+ * at least once. Longer lifetimes are configurable per API Client in
+ * Jamf. Failures throw up to the sync runner and land in the
+ * sync-adapters log.
*
* Jamf Pro API reference: https://developer.jamf.com/jamf-pro/reference
*/
class JamfClient
{
+ private ?string $accessToken = null;
+
+ private ?int $expiresAt = null;
+
public function __construct(
private readonly string $baseUrl,
- private readonly string $token,
+ private readonly string $clientId,
+ private readonly string $clientSecret,
) {}
/**
@@ -102,8 +114,41 @@ class JamfClient
{
return Http::baseUrl(rtrim($this->baseUrl, '/'))
->withOptions(['allow_redirects' => false])
- ->withToken($this->token)
+ ->withToken($this->bearer())
->acceptJson()
->timeout(30);
}
+
+ /**
+ * Exchange client credentials for a bearer token via Jamf Pro's
+ * /api/oauth/token endpoint. Tokens are short-lived (60 seconds
+ * on default API Clients, up to 68 years if the admin configured
+ * a longer lifetime) so we cache the token on this instance and
+ * re-exchange when we're within a 30-second buffer of expiry.
+ * Response shape: {access_token, token_type: Bearer, expires_in}.
+ */
+ private function bearer(): string
+ {
+ $now = time();
+ if ($this->accessToken !== null && $this->expiresAt !== null && $now < $this->expiresAt - 30) {
+ return $this->accessToken;
+ }
+
+ $response = Http::asForm()
+ ->withOptions(['allow_redirects' => false])
+ ->timeout(30)
+ ->post(rtrim($this->baseUrl, '/') . '/api/oauth/token', [
+ 'grant_type' => 'client_credentials',
+ 'client_id' => $this->clientId,
+ 'client_secret' => $this->clientSecret,
+ ])
+ ->throw()
+ ->json();
+
+ $this->accessToken = (string) ($response['access_token'] ?? '');
+ $expiresIn = (int) ($response['expires_in'] ?? 0);
+ $this->expiresAt = $expiresIn > 0 ? $now + $expiresIn : null;
+
+ return $this->accessToken;
+ }
}
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index c589547180..188e66c77f 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -150,7 +150,8 @@ return [
'fleet_token_help' => 'Generate under My Account -> Get API token in your Fleet instance. Needs an admin or observer role with read access to hosts (and to teams if you use group-to-company mapping).',
'kandji_token_help' => 'Generate under Settings -> Access -> API Token in your Iru (Kandji) tenant. Needs the Device list read permission (and Blueprint list if you use group-to-company mapping).',
'kandji_base_url_help' => 'Your Iru (Kandji) API URL is listed on the Access page of your Iru (Kandji) admin console under the API Token section. It is not the same as the URL you use to sign into the admin console. Save the URL that ends with <code>.api.kandji.io</code>, not the dashboard URL.',
- 'jamf_token_help' => 'Generate a Personal Access Token under Settings -> System -> API Roles and Clients in Jamf Pro. The role needs Read on Computers (and Sites if you use group-to-company mapping).',
+ 'jamf_client_id_help' => 'Create an API Role granting Read on Computers (and Read on Sites if you use group-to-company mapping), then an API Client that uses that role, under Settings -> System -> API Roles and Clients in Jamf Pro. Copy the Client ID from the API Client detail page. Consider raising the token lifetime on the API Client above the 60-second default so long sync runs do not re-exchange constantly.',
+ 'jamf_client_secret_help' => 'Paired with the Client ID above. Jamf Pro shows the secret once at API Client creation time.',
'jamf_school_network_id_help' => 'Find your Network ID under Organization -> Settings -> API in the Jamf School admin console.',
'jamf_school_api_key_help' => 'Generate under Organization -> Settings -> API in Jamf School. Needs read access to Devices (and Locations if you use group-to-company mapping).',
'jumpcloud_token_help' => 'Copy from your JumpCloud admin user\'s profile page (top-right menu -> My API Key). API keys inherit the admin user\'s permissions, so use an account with read access to Systems.',
diff --git a/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php b/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php
index 59b9aac585..ca59bf428c 100644
--- a/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php
@@ -31,6 +31,7 @@ class JamfAdapterTest extends TestCase
$adapter = $this->configuredJamfAdapter();
Http::fake([
+ '*/api/oauth/token' => $this->jamfTokenResponse(),
'*/api/v1/computers-inventory*' => Http::response([
'totalCount' => 2,
'results' => [
@@ -55,6 +56,7 @@ class JamfAdapterTest extends TestCase
$adapter = $this->configuredJamfAdapter();
Http::fake([
+ '*/api/oauth/token' => $this->jamfTokenResponse(),
'*/api/v1/computers-inventory*' => Http::response([
'totalCount' => 1,
'results' => [
@@ -92,11 +94,28 @@ class JamfAdapterTest extends TestCase
{
$instance = SyncAdapterInstance::where('slug', 'jamf')->firstOrFail();
SyncAdapterConfig::put($instance->id, 'url', 'https://example.jamfcloud.com');
- SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-jamf-token'));
+ SyncAdapterConfig::put($instance->id, 'client_id', Crypt::encrypt('fake-jamf-client-id'));
+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-jamf-client-secret'));
return new JamfAdapter($instance->fresh());
}
+ /**
+ * Jamf Pro's /api/oauth/token response shape. expires_in is
+ * whatever the API Client is configured for. The client's bearer
+ * cache honors it with a 30-second buffer before re-exchanging.
+ * No return type hint because Http::response() inside a fake
+ * handler resolves to a promise, not a bare Response.
+ */
+ private function jamfTokenResponse()
+ {
+ return Http::response([
+ 'access_token' => 'fake-jamf-access-token',
+ 'token_type' => 'Bearer',
+ 'expires_in' => 3600,
+ ]);
+ }
+
/**
* @return array<string, mixed>
*/
diff --git a/tests/Feature/SyncAdapters/Jamf/JamfPushTest.php b/tests/Feature/SyncAdapters/Jamf/JamfPushTest.php
index 22bac28e82..40b5dd5ad9 100644
--- a/tests/Feature/SyncAdapters/Jamf/JamfPushTest.php
+++ b/tests/Feature/SyncAdapters/Jamf/JamfPushTest.php
@@ -48,6 +48,11 @@ class JamfPushTest extends TestCase
]);
Http::fake([
+ '*/api/oauth/token' => Http::response([
+ 'access_token' => 'fake-jamf-access-token',
+ 'token_type' => 'Bearer',
+ 'expires_in' => 3600,
+ ]),
'*/api/v1/computers-inventory-detail/*' => Http::response(['ok' => true]),
]);
@@ -100,7 +105,8 @@ class JamfPushTest extends TestCase
{
$instance = SyncAdapterInstance::where('slug', 'jamf')->firstOrFail();
SyncAdapterConfig::put($instance->id, 'url', 'https://example.com/jamf');
- SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-jamf-token'));
+ SyncAdapterConfig::put($instance->id, 'client_id', Crypt::encrypt('fake-jamf-client-id'));
+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-jamf-client-secret'));
return new JamfAdapter($instance->fresh());
}