Skip to content
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
### Unreleased

#### Improvements
* Add JWT authentication for ClickHouse Cloud (http driver only): `access_token` takes a static token, and `access_token_provider` names a Python callable that dbt calls for the initial token and again whenever the server rejects it. Both replace `user`/`password` and cannot be combined with them. Requires `clickhouse-connect>=1.2.0` ([#747](https://github.com/ClickHouse/dbt-clickhouse/pull/747)).


### Release [1.10.4], 2026-11-24

Expand Down
62 changes: 60 additions & 2 deletions dbt/adapters/clickhouse/credentials.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import importlib
from dataclasses import dataclass
from typing import Any, Dict, Optional, Union
from typing import Any, Callable, Dict, Optional, Union

from dbt.adapters.contracts.connection import Credentials
from dbt_common.exceptions import DbtRuntimeError
from dbt_common.exceptions import DbtConfigError, DbtRuntimeError


@dataclass
Expand All @@ -19,6 +20,12 @@ class ClickHouseCredentials(Credentials):
database: Optional[str] = ''
schema: Optional[str] = 'default'
password: str = ''
# JWT access token (ClickHouse Cloud, http driver only). Replaces user/password.
access_token: Optional[str] = None
# Dotted path ('pkg.module:function' or 'pkg.module.function') to a zero-argument
# callable returning a JWT. Passed to clickhouse-connect as token_provider, which
# calls it on connect and again whenever the server rejects the current token.
access_token_provider: Optional[str] = None
cluster: Optional[str] = None
database_engine: Optional[str] = None
cluster_mode: bool = False
Expand Down Expand Up @@ -62,12 +69,63 @@ def __post_init__(self):
)
self.database = ''

if not self.driver:
if self.port in (9000, 9440):
self.driver = 'native'
else:
self.driver = 'http'

if self.driver == 'http':
if not self.port:
self.port = 8443 if self.secure else 8123
elif self.driver == 'native':
if not self.port:
self.port = 9440 if self.secure else 9000
else:
raise DbtConfigError(f'Unrecognized ClickHouse driver {self.driver}')

if self.access_token and self.access_token_provider:
raise DbtConfigError('access_token and access_token_provider cannot both be set.')
if self.uses_token_auth and (self.password or self.user not in (None, 'default')):
raise DbtConfigError(
'JWT authentication (access_token or access_token_provider) cannot be combined '
'with user/password authentication; remove user and password from the profile.'
)
if self.uses_token_auth and self.driver == 'native':
raise DbtConfigError(
'JWT authentication (access_token / access_token_provider) is only supported by the '
'http driver; set driver: http (and an http port) in the profile'
)

@property
def uses_token_auth(self) -> bool:
return bool(self.access_token or self.access_token_provider)

def resolve_token_provider(self) -> Optional[Callable[[], str]]:
"""Import the callable named by access_token_provider, or None if not configured."""
path = self.access_token_provider
if not path:
return None
module_name, _, attr = path.rpartition(':' if ':' in path else '.')
if not module_name or not attr:
raise DbtConfigError(
f'access_token_provider must be "module:function" or "module.function", got {path!r}'
)
try:
provider = getattr(importlib.import_module(module_name), attr)
except (ImportError, AttributeError) as ex:
raise DbtConfigError(f'Could not import access_token_provider {path!r}: {ex}') from ex
if not callable(provider):
raise DbtConfigError(f'access_token_provider {path!r} is not callable')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you might also want to check whether the function is allowed to be called with zero arguments (as stated by the contract). but it's not that critical, as a wrong signature will probably raise when clickhouse-connect tries to first call it.

return provider

def _connection_keys(self):
return (
'driver',
'host',
'port',
'user',
'access_token_provider',
'schema',
'retries',
'cluster',
Expand Down
20 changes: 1 addition & 19 deletions dbt/adapters/clickhouse/dbclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,25 +41,7 @@


def get_db_client(credentials: ClickHouseCredentials):
driver = credentials.driver
port = credentials.port
if not driver:
if port in (9000, 9440):
driver = 'native'
else:
driver = 'http'
if driver == 'http':
if not port:
port = 8443 if credentials.secure else 8123
elif driver == 'native':
if not port:
port = 9440 if credentials.secure else 9000
else:
raise FailedToConnectError(f'Unrecognized ClickHouse driver {driver}')

credentials.driver = driver
credentials.port = port
if driver == 'native':
if credentials.driver == 'native':
try:
import clickhouse_driver # noqa
from dbt.adapters.clickhouse.nativeclient import ChNativeClient
Expand Down
12 changes: 11 additions & 1 deletion dbt/adapters/clickhouse/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ def _create_client(self, credentials):
# standard path clients share a process-wide pool singleton that
# keeps sockets alive across close().
server_host_name = credentials.server_host_name
token_provider = credentials.resolve_token_provider()
kwargs = {}
if not credentials.reuse_connections:
if credentials.secure:
Expand All @@ -117,8 +118,12 @@ def _create_client(self, credentials):
return clickhouse_connect.get_client(
host=credentials.host,
port=credentials.port,
username=credentials.user,
# clickhouse-connect rejects a username alongside a token; the server
# derives the user from the token's claims.
username=None if credentials.uses_token_auth else credentials.user,
password=credentials.password,
access_token=credentials.access_token,
token_provider=token_provider,
interface='https' if credentials.secure else 'http',
compress=False if credentials.compression == '' else bool(credentials.compression),
connect_timeout=credentials.connect_timeout,
Expand All @@ -136,6 +141,11 @@ def _create_client(self, credentials):
except OperationalError as ex:
self._discard_dedicated_pool()
raise ChRetryableException(str(ex)) from ex
except Exception:
# e.g. authentication failures or a token provider error: not retryable,
# but the pool must still be released.
self._discard_dedicated_pool()
raise

def _set_client_database(self):
self._client.database = self.database
Expand Down
12 changes: 11 additions & 1 deletion dbt/adapters/clickhouse/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
from dbt.adapters.sql import SQLAdapter
from dbt_common.contracts.constraints import ConstraintType, ModelLevelConstraint
from dbt_common.events.functions import warn_or_error
from dbt_common.exceptions import DbtInternalError, DbtRuntimeError, NotImplementedError
from dbt_common.exceptions import (
DbtConfigError,
DbtInternalError,
DbtRuntimeError,
NotImplementedError,
)
from dbt_common.utils import filter_null_values

if TYPE_CHECKING:
Expand Down Expand Up @@ -630,6 +635,11 @@ def get_credentials(self, connection_overrides) -> Dict:
conn = self.connections.get_if_exists()
if conn is None or conn.credentials is None:
return dict()
if conn.credentials.uses_token_auth and 'user' not in connection_overrides:
raise DbtConfigError(
'Dictionary sources cannot authenticate with a JWT; set user/password for the '
'dictionary via the connection_overrides config.'
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dictionary JWT guard allows empty user

Medium Severity

The new dictionary JWT check only tests whether user is present in connection_overrides, not whether a usable user (and password) is actually provided. A falsy user still passes, then the existing loop drops empty override values, so a JWT profile can create a ClickHouse dictionary with no credentials — the failure mode this guard was meant to block.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 96228a5. Configure here.

credentials = {
'user': conn.credentials.user,
'password': conn.credentials.password,
Expand Down
1 change: 1 addition & 0 deletions docs/dbt-core-v2-fusion-and-platform.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ The tables below compare the features available in `dbt-clickhouse` (v1) with th
|---------|--------------|--------|-------|
| Protocol | How dbt talks to ClickHouse. | <Badge color="green">Supported</Badge> | ADBC (Arrow over HTTP) on v2; HTTP and native on v1. |
| Username and password, TLS | Standard auth. | <Badge color="green">Supported</Badge> | |
| JWT `access_token_provider` | Profile-level Python callable that supplies and refreshes a ClickHouse Cloud JWT. | <Badge color="red">Not yet</Badge> | Requires Python, so it applies to dbt Core 1.x only. |
| mTLS client certificates | `client_cert`, `client_cert_key`. | <Badge color="red">Not yet</Badge> | Driver work; the keys are accepted but ignored ([ClickHouse/dbt-clickhouse#794](https://github.com/ClickHouse/dbt-clickhouse/issues/794)). |
| HTTP client options | `connect_timeout`, `send_receive_timeout`, `server_host_name`. | <Badge color="red">Not yet</Badge> | Driver work; the keys are accepted but ignored ([ClickHouse/dbt-clickhouse#795](https://github.com/ClickHouse/dbt-clickhouse/issues/795)). |
| Connection reuse | `reuse_connections: false` opens a new connection per model. | <Badge color="red">Not yet</Badge> | The key is accepted but ignored ([ClickHouse/dbt-clickhouse#815](https://github.com/ClickHouse/dbt-clickhouse/issues/815)). |
Expand Down
54 changes: 54 additions & 0 deletions docs/features-and-configurations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ your_profile_name:
port: [8123] # If not set, defaults to 8123, 8443, 9000, 9440 depending on the secure and driver settings
user: [default] # User for all database operations
password: [<empty string>] # Password for the user
access_token: [null] # JWT access token (ClickHouse Cloud, http driver only). See the JWT authentication section below.
access_token_provider: [null] # Python function that supplies and refreshes a JWT. See the JWT authentication section below.
cluster: [<empty string>] # If set, certain DDL/table operations will be executed with the `ON CLUSTER` clause using this cluster. Distributed materializations require this setting to work. See the following ClickHouse Cluster section for more details.
verify: [True] # Validate TLS certificate if using TLS/SSL
secure: [False] # Use TLS (native protocol) or HTTPS (http protocol)
Expand All @@ -57,6 +59,58 @@ your_profile_name:
sync_request_timeout: [5] # Timeout for server ping
compress_block_size: [1048576] # Compression block size if compression is enabled
```

### JWT authentication {#jwt-authentication}

On ClickHouse Cloud, dbt can authenticate with a JWT instead of `user` and `password`.
See [JWT authentication setup](https://clickhouse.com/docs/products/cloud/guides/security/cloud-access-management/jwt-authentication-setup) to configure an identity provider for your service, and the [JWT authentication reference](https://clickhouse.com/docs/concepts/features/security/external-authenticators/jwt) for how ClickHouse validates tokens and derives permissions from them.

JWT authentication requires the `http` driver.
Set either `access_token` or `access_token_provider`, and leave out `user` and `password`:

```yaml
your_profile_name:
target: dev
outputs:
dev:
type: clickhouse
driver: http
host: <your-service>.clickhouse.cloud
port: 8443
secure: True
access_token_provider: my_dbt_auth:get_token
# or a static token:
# access_token: "{{ env_var('DBT_ENV_SECRET_CLICKHOUSE_TOKEN') }}"
```

A static `access_token` is never refreshed, so a run fails once the token expires.
Use `access_token_provider` for runs that can outlive a token.

#### Token provider function {#jwt-token-provider}

`access_token_provider` is the path to a Python function, as `module:function` or `module.function`.
The function takes no arguments and returns a JWT as a string:

```python
# my_dbt_auth.py
def get_token() -> str:
... # fetch a token from your identity provider
```

dbt calls it when it connects, and again whenever ClickHouse rejects the current token, for example after it expires.
An expired or otherwise unverifiable token triggers a refresh, but a value that is not a JWT fails the run.

The module must be importable from the Python environment that runs dbt.
The `dbt` command does not search the dbt project directory, so either install the module as a package in that environment or add its directory to `PYTHONPATH`, for example `PYTHONPATH=. dbt run`.

`access_token_provider` is not available on dbt v2, see [v1 vs v2 parity](/integrations/connectors/data-ingestion/etl-tools/dbt/dbt-core-v2-fusion-and-platform#parity-connectivity-and-auth).

#### Dictionaries {#jwt-dictionaries}

Dictionaries with a `clickhouse` source cannot use the token, because ClickHouse connects to the source with a user and password.
Set them with the dictionary's [`connection_overrides`](/integrations/connectors/data-ingestion/etl-tools/dbt/materializations#dictionary-configurations) config.
These values end up in dbt artifacts such as `manifest.json` and in the dictionary's DDL, so use a dedicated user that can only read the source table.

### Schema vs Database {#schema-vs-database}

The dbt model relation identifier `database.schema.table` isn't compatible with ClickHouse because ClickHouse doesn't
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ dependencies = [
"agate>=1.0,<2.0",

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@canbekley, what is this used for?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are unrelated changes, not introduced with this PR but with #776. we've set them because there are direct imports from those packages

# add dbt-core to ensure backwards compatibility of installation, this is not a functional dependency
"dbt-core>=1.9,<2.0",
"clickhouse-connect>=0.10.0",
"clickhouse-connect>=1.2.0",
"clickhouse-driver>=0.2.10"
]

Expand Down
95 changes: 95 additions & 0 deletions tests/integration/adapter/clickhouse/test_access_token_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""JWT authentication via `access_token` and `access_token_provider`.

ClickHouse only validates JWTs in ClickHouse Cloud, so the end-to-end runs need
`DBT_CH_TEST_CLOUD=true` and a valid token in `DBT_CH_TEST_ACCESS_TOKEN`. Against OSS
ClickHouse we can still verify the wiring: the server must see a `Bearer` header
(rather than a Basic auth fallback) and reject it as an unsupported scheme, and the
provider must be called a second time after that rejection.
"""

import os

import pytest
from dbt.adapters.clickhouse.credentials import ClickHouseCredentials
from dbt.adapters.clickhouse.httpclient import ChHttpClient
from dbt.tests.util import run_dbt

from tests.integration.adapter.clickhouse import token_provider_stub

_CLOUD = os.environ.get('DBT_CH_TEST_CLOUD', '').lower() in ('1', 'true', 'yes')
_TOKEN = os.environ.get('DBT_CH_TEST_ACCESS_TOKEN')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't set DBT_CH_TEST_ACCESS_TOKEN anywhere, so CI wouldn't run the tests that require the token. should we add them through test_cloud.yml?

_PROVIDER = f'{token_provider_stub.__name__}:rejected_then_real'


def _credentials(test_config, **auth):
return ClickHouseCredentials(
driver='http',
host=test_config['host'],
port=test_config['port'],
secure=test_config['secure'],
schema='default',
**auth,
)


@pytest.mark.skipif(_CLOUD, reason='OSS ClickHouse only; Cloud validates JWTs')
class TestAccessTokenRejectedByOSS:
@pytest.fixture(autouse=True)
def _http_only(self, test_config):
if test_config['driver'] != 'http':
pytest.skip('JWT authentication is only supported by the http driver')

def test_token_sent_as_bearer(self, test_config):
with pytest.raises(Exception, match='(?i)bearer'):
ChHttpClient(_credentials(test_config, access_token='not-a-real-jwt'))

def test_provider_called_again_after_rejection(self, test_config):
token_provider_stub.calls.clear()
with pytest.raises(Exception, match='(?i)bearer'):
ChHttpClient(_credentials(test_config, access_token_provider=_PROVIDER))
# initial token, then one refresh after the server rejected it
assert len(token_provider_stub.calls) == 2


def _jwt_target(dbt_profile_target, **auth):
if not (_CLOUD and _TOKEN):
pytest.skip('requires DBT_CH_TEST_CLOUD=true and DBT_CH_TEST_ACCESS_TOKEN')
if dbt_profile_target['driver'] != 'http':
pytest.skip('JWT authentication is only supported by the http driver')
target = {k: v for k, v in dbt_profile_target.items() if k not in ('user', 'password')}
target.update(auth)
return target


class TestAccessTokenCloud:
@pytest.fixture(scope="class")
def dbt_profile_target(self, dbt_profile_target):
return _jwt_target(dbt_profile_target, access_token=_TOKEN)

@pytest.fixture(scope="class")
def models(self):
return {'jwt_model.sql': 'select 1 as id'}

def test_run_with_access_token(self, project):
run_dbt(['debug'])
run_dbt(['run'])
assert project.run_sql('select id from jwt_model', fetch='one')[0] == 1
assert project.run_sql('select currentUser()', fetch='one')[0].startswith('JWT::')


class TestAccessTokenProviderCloud:
@pytest.fixture(scope="class")
def dbt_profile_target(self, dbt_profile_target):
token_provider_stub.calls.clear()
return _jwt_target(dbt_profile_target, access_token_provider=_PROVIDER)

@pytest.fixture(scope="class")
def models(self):
return {'jwt_model.sql': 'select 1 as id'}

def test_run_with_refreshed_token(self, project):
run_dbt(['run'])
assert project.run_sql('select id from jwt_model', fetch='one')[0] == 1
assert project.run_sql('select currentUser()', fetch='one')[0].startswith('JWT::')
# The first token was rejected, so the provider must have been asked again.
assert len(token_provider_stub.calls) >= 2
Loading
Loading