diff --git a/python/descope_agent_auth/__init__.py b/python/descope_agent_auth/__init__.py index d2d8521..58bc664 100644 --- a/python/descope_agent_auth/__init__.py +++ b/python/descope_agent_auth/__init__.py @@ -33,8 +33,7 @@ PendingAuthorization, VaultToken, ) - -__version__ = "0.1.0" +from ._version import __version__ as __version__ __all__ = [ "AgentAuthClient", diff --git a/python/descope_agent_auth/_http.py b/python/descope_agent_auth/_http.py index 71ec894..acc936b 100644 --- a/python/descope_agent_auth/_http.py +++ b/python/descope_agent_auth/_http.py @@ -10,13 +10,24 @@ import asyncio import logging +import platform from dataclasses import dataclass from typing import Any, Dict, Mapping, Optional import httpx +from ._version import __version__ from .errors import AgentAuthError +# Identify the SDK on every Descope request, like Descope's python-sdk does, so usage +# can be told apart from the core SDK ("python") in Descope's analytics. +SDK_HEADERS = { + "User-Agent": f"descope-agent-auth-python/{__version__}", + "x-descope-sdk-name": "agent-auth-python", + "x-descope-sdk-version": __version__, + "x-descope-sdk-python-version": platform.python_version(), +} + _REDACTED = "***redacted***" _SENSITIVE_KEYS = { "authorization", @@ -87,7 +98,7 @@ def __init__( base_url=self._base_url, timeout=timeout, transport=_transport, - headers={"User-Agent": "descope-agent-auth-python/0.1.0"}, + headers=SDK_HEADERS, ) async def aclose(self) -> None: diff --git a/python/descope_agent_auth/_version.py b/python/descope_agent_auth/_version.py new file mode 100644 index 0000000..9744720 --- /dev/null +++ b/python/descope_agent_auth/_version.py @@ -0,0 +1,3 @@ +"""Single source of the SDK version (kept equal to pyproject.toml by a test).""" + +__version__ = "0.1.0" diff --git a/python/tests/test_sdk_headers.py b/python/tests/test_sdk_headers.py new file mode 100644 index 0000000..c0fb185 --- /dev/null +++ b/python/tests/test_sdk_headers.py @@ -0,0 +1,52 @@ +"""Every request identifies the SDK, like Descope's python-sdk and node-sdk do. + +Descope analytics groups traffic by ``x-descope-sdk-name`` + ``x-descope-sdk-version``, +so this SDK uses its own name rather than ``python`` (the core python-sdk). +""" + +from __future__ import annotations + +import asyncio +import platform +import re +import unittest +from pathlib import Path + +import httpx + +import descope_agent_auth +from descope_agent_auth._http import HttpClient + + +def _send_and_capture_headers() -> httpx.Headers: + seen = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["headers"] = request.headers + return httpx.Response(200, json={}) + + async def run() -> None: + client = HttpClient("https://api.descope.com", _transport=httpx.MockTransport(handler)) + await client.post_form("/oauth2/v1/apps/token", data={"grant_type": "x"}) + await client.aclose() + + asyncio.run(run()) + return seen["headers"] + + +class TestSdkHeaders(unittest.TestCase): + def test_requests_carry_descope_sdk_headers(self): + headers = _send_and_capture_headers() + + self.assertEqual(headers["x-descope-sdk-name"], "agent-auth-python") + self.assertEqual(headers["x-descope-sdk-version"], descope_agent_auth.__version__) + self.assertEqual(headers["x-descope-sdk-python-version"], platform.python_version()) + self.assertEqual( + headers["user-agent"], f"descope-agent-auth-python/{descope_agent_auth.__version__}" + ) + + def test_version_matches_pyproject(self): + pyproject = (Path(__file__).parents[1] / "pyproject.toml").read_text() + match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject, re.M) + assert match is not None + self.assertEqual(descope_agent_auth.__version__, match.group(1)) diff --git a/typescript/src/httpClient.ts b/typescript/src/httpClient.ts index 43df51b..55a9995 100644 --- a/typescript/src/httpClient.ts +++ b/typescript/src/httpClient.ts @@ -8,6 +8,20 @@ */ import { AgentAuthError } from './errors'; +import { SDK_VERSION } from './version'; + +/** + * Identify the SDK on every Descope request, like Descope's node-sdk and core-js-sdk + * do, so usage can be told apart from the core SDK (`nodejs`) in Descope's analytics. + * The runtime-version header is only sent on Node (not on Workers, Deno or browsers). + */ +const nodeVersion = (globalThis as { process?: { versions?: { node?: string } } }).process?.versions + ?.node; +export const SDK_HEADERS: Record = { + 'x-descope-sdk-name': 'agent-auth-js', + 'x-descope-sdk-version': SDK_VERSION, + ...(nodeVersion ? { 'x-descope-sdk-node-version': nodeVersion } : {}), +}; const REDACTED = '***redacted***'; const SENSITIVE_KEYS = new Set([ @@ -156,7 +170,7 @@ export class HttpClient { resp = await this.fetchImpl(url, { method, body: opts.body, - headers: opts.headers, + headers: { ...SDK_HEADERS, ...opts.headers }, signal: controller.signal, }); } catch (err) { diff --git a/typescript/src/sdkHeaders.test.ts b/typescript/src/sdkHeaders.test.ts new file mode 100644 index 0000000..da8fd68 --- /dev/null +++ b/typescript/src/sdkHeaders.test.ts @@ -0,0 +1,36 @@ +// Every request identifies the SDK, like Descope's node-sdk and core-js-sdk do. +// Descope analytics groups traffic by x-descope-sdk-name + x-descope-sdk-version, so +// this SDK uses its own name rather than `nodejs` (the core node-sdk). +import nock from 'nock'; +import pkg from '../package.json'; +import { BASE_URL, makeClient } from './testutils'; +import { ClientCredentialsProvider } from './providers'; +import { SDK_VERSION } from './version'; + +beforeAll(() => nock.disableNetConnect()); +afterEach(() => nock.cleanAll()); +afterAll(() => nock.enableNetConnect()); + +describe('SDK identification headers', () => { + it('sends x-descope-sdk-* headers on every Descope request', async () => { + let headers: Record = {}; + nock(BASE_URL) + .post(/.*/) + .reply(function reply() { + headers = this.req.headers; + return [200, { access_token: 'agent_at', expires_in: 3600 }]; + }); + + await makeClient( + new ClientCredentialsProvider({ clientId: 'cid', clientSecret: 's' }), + ).getCredential(); + + expect(headers['x-descope-sdk-name']).toBe('agent-auth-js'); + expect(headers['x-descope-sdk-version']).toBe(pkg.version); + expect(headers['x-descope-sdk-node-version']).toBe(process.versions.node); + }); + + it('keeps SDK_VERSION in sync with package.json', () => { + expect(SDK_VERSION).toBe(pkg.version); + }); +}); diff --git a/typescript/src/version.ts b/typescript/src/version.ts new file mode 100644 index 0000000..4eaf39b --- /dev/null +++ b/typescript/src/version.ts @@ -0,0 +1,2 @@ +/** Single source of the SDK version (kept equal to package.json by a test). */ +export const SDK_VERSION = '0.1.0';