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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ client = Client(
)
```

`access_token` accepts both personal access tokens (`ldpat_…`) and service
account tokens (`ldsvc_…`); the SDK selects the correct authentication scheme
automatically.

## Development

### Prerequisites
Expand Down
3 changes: 2 additions & 1 deletion lightdash/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def __init__(self, instance_url: str, access_token: str, project_uuid: str, conf
self.instance_url = instance_url.rstrip('/')
self.access_token = access_token
self.project_uuid = project_uuid
self.auth_header = "Bearer" if access_token.startswith("ldsvc_") else "ApiKey"

# Extract config values with defaults
config = config or {}
Expand Down Expand Up @@ -88,7 +89,7 @@ def _make_request(

with httpx.Client(
headers={
"Authorization": f"ApiKey {self.access_token}",
"Authorization": f"{self.auth_header} {self.access_token}",
"Accept": "application/json",
},
timeout=self.timeout
Expand Down
38 changes: 38 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Unit tests for Client construction.

Covers the Authorization scheme selection: service account tokens (``ldsvc_``)
authenticate with ``Bearer`` while personal access tokens and anything else use
``ApiKey`` — matching the Lightdash backend auth middleware (issue #17).
"""

import pytest
from lightdash import Client


def _client(token: str) -> Client:
# Construction makes no network call, so a dummy URL/project is fine.
return Client(
instance_url="https://example.lightdash.cloud",
access_token=token,
project_uuid="00000000-0000-0000-0000-000000000000",
)


class TestAuthHeaderScheme:
def test_service_account_token_uses_bearer(self):
"""ldsvc_ tokens must use the Bearer scheme."""
assert _client("ldsvc_abc123").auth_header == "Bearer"

def test_personal_access_token_uses_apikey(self):
"""ldpat_ tokens keep the ApiKey scheme (unchanged behaviour)."""
assert _client("ldpat_abc123").auth_header == "ApiKey"

def test_unprefixed_token_defaults_to_apikey(self):
"""Any other token defaults to ApiKey, preserving backwards compatibility."""
assert _client("legacy-token").auth_header == "ApiKey"

def test_authorization_header_value(self):
"""The composed Authorization header uses the selected scheme."""
c = _client("ldsvc_abc123")
assert f"{c.auth_header} {c.access_token}" == "Bearer ldsvc_abc123"