Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions python/descope_agent_auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@
PendingAuthorization,
VaultToken,
)

__version__ = "0.1.0"
from ._version import __version__ as __version__

__all__ = [
"AgentAuthClient",
Expand Down
13 changes: 12 additions & 1 deletion python/descope_agent_auth/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions python/descope_agent_auth/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""Single source of the SDK version (kept equal to pyproject.toml by a test)."""

__version__ = "0.1.0"
52 changes: 52 additions & 0 deletions python/tests/test_sdk_headers.py
Original file line number Diff line number Diff line change
@@ -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))
16 changes: 15 additions & 1 deletion typescript/src/httpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
'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([
Expand Down Expand Up @@ -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) {
Expand Down
36 changes: 36 additions & 0 deletions typescript/src/sdkHeaders.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {};
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);
});
});
2 changes: 2 additions & 0 deletions typescript/src/version.ts
Original file line number Diff line number Diff line change
@@ -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';
Loading