0
# Authentication and Credentials
1
2
Complete authentication system supporting anonymous access, static tokens, OAuth2 token exchange, JWT authentication, service account credentials, and Yandex Cloud IAM integration.
3
4
## Capabilities
5
6
### Base Credentials Classes
7
8
Abstract base classes that define the credential interface.
9
10
```python { .api }
11
class AbstractCredentials:
12
"""Abstract base class for auth metadata providers."""
13
14
class Credentials:
15
def __init__(self, tracer=None):
16
"""
17
Base credentials class.
18
19
Args:
20
tracer: Optional tracer for debugging
21
"""
22
23
def auth_metadata(self):
24
"""
25
Get authentication metadata.
26
27
Returns:
28
Iterable of (header, value) tuples for gRPC metadata
29
"""
30
31
def get_auth_token(self) -> str:
32
"""
33
Extract auth token from metadata.
34
35
Returns:
36
str: Authentication token or empty string
37
"""
38
```
39
40
### Anonymous Credentials
41
42
No authentication - for local development and testing.
43
44
```python { .api }
45
class AnonymousCredentials(Credentials):
46
"""Credentials for anonymous access (no authentication)."""
47
48
def __init__(self):
49
"""Create anonymous credentials."""
50
```
51
52
### Static Token Credentials
53
54
Fixed token authentication for simple authentication scenarios.
55
56
```python { .api }
57
class StaticCredentials(Credentials):
58
def __init__(self, token: str):
59
"""
60
Static token credentials.
61
62
Args:
63
token (str): Authentication token
64
"""
65
```
66
67
### OAuth2 Token Exchange Credentials
68
69
OAuth2 token exchange authentication for secure token-based access.
70
71
```python { .api }
72
class OAuth2TokenExchangeCredentials(Credentials):
73
def __init__(
74
self,
75
token_endpoint: str,
76
resource: str = None,
77
audience: str = None,
78
scope: str = None,
79
requested_token_type: str = None,
80
subject_token: str = None,
81
subject_token_type: str = None,
82
actor_token: str = None,
83
actor_token_type: str = None,
84
**kwargs
85
):
86
"""
87
OAuth2 token exchange credentials.
88
89
Args:
90
token_endpoint (str): OAuth2 token endpoint URL
91
resource (str, optional): Target resource
92
audience (str, optional): Token audience
93
scope (str, optional): Requested scope
94
requested_token_type (str, optional): Type of requested token
95
subject_token (str, optional): Subject token for exchange
96
subject_token_type (str, optional): Subject token type
97
actor_token (str, optional): Actor token
98
actor_token_type (str, optional): Actor token type
99
"""
100
```
101
102
### JWT Credentials
103
104
JSON Web Token authentication for service-to-service communication.
105
106
```python { .api }
107
class JWTCredentials(Credentials):
108
def __init__(
109
self,
110
jwt_token: str,
111
refresh_token: str = None,
112
token_endpoint: str = None
113
):
114
"""
115
JWT token credentials.
116
117
Args:
118
jwt_token (str): JWT token
119
refresh_token (str, optional): Refresh token for renewal
120
token_endpoint (str, optional): Token refresh endpoint
121
"""
122
```
123
124
### Service Account Credentials
125
126
Direct service account authentication using key files or metadata.
127
128
```python { .api }
129
class DirectServiceAccountCredentials(Credentials):
130
def __init__(
131
self,
132
service_account_id: str,
133
key_id: str,
134
private_key: str,
135
token_endpoint: str = None
136
):
137
"""
138
Direct service account credentials.
139
140
Args:
141
service_account_id (str): Service account identifier
142
key_id (str): Private key identifier
143
private_key (str): RSA private key in PEM format
144
token_endpoint (str, optional): Token endpoint URL
145
"""
146
```
147
148
### Refreshable Credentials
149
150
Auto-refreshing credentials wrapper for long-running applications.
151
152
```python { .api }
153
class RefreshableCredentials(Credentials):
154
def __init__(
155
self,
156
credentials_factory: callable,
157
refresh_threshold: float = 300
158
):
159
"""
160
Auto-refreshing credentials wrapper.
161
162
Args:
163
credentials_factory (callable): Function returning fresh credentials
164
refresh_threshold (float): Refresh before expiry (seconds)
165
"""
166
```
167
168
### Credential Factory Functions
169
170
Convenience functions for creating credentials from various sources.
171
172
```python { .api }
173
def default_credentials(credentials: Credentials = None, tracer=None) -> Credentials:
174
"""
175
Get default credentials or return anonymous if none provided.
176
177
Args:
178
credentials (Credentials, optional): Explicit credentials
179
tracer: Optional tracer
180
181
Returns:
182
Credentials: Default or provided credentials
183
"""
184
185
def credentials_from_env_variables(tracer=None) -> Credentials:
186
"""
187
Create credentials from environment variables.
188
189
Environment variables checked:
190
- YDB_SERVICE_ACCOUNT_KEY_FILE_CREDENTIALS: Path to service account key file
191
- YDB_ANONYMOUS_CREDENTIALS: "1" for anonymous access
192
- YDB_METADATA_CREDENTIALS: "1" for metadata service
193
- YDB_ACCESS_TOKEN_CREDENTIALS: Direct access token
194
195
Args:
196
tracer: Optional tracer
197
198
Returns:
199
Credentials: Credentials based on environment variables
200
"""
201
202
def construct_credentials_from_string(credentials_string: str) -> Credentials:
203
"""
204
Parse credentials from connection string format.
205
206
Args:
207
credentials_string (str): Credentials specification
208
209
Returns:
210
Credentials: Parsed credentials object
211
"""
212
```
213
214
### Yandex Cloud IAM Integration
215
216
```python { .api }
217
import ydb.iam
218
219
class ServiceAccountCredentials(Credentials):
220
@classmethod
221
def from_file(cls, key_file: str, **kwargs) -> 'ServiceAccountCredentials':
222
"""
223
Create credentials from service account key file.
224
225
Args:
226
key_file (str): Path to JSON key file
227
228
Returns:
229
ServiceAccountCredentials: Configured credentials
230
"""
231
232
class MetadataCredentials(Credentials):
233
def __init__(self, metadata_url: str = None):
234
"""
235
Credentials from Yandex Cloud metadata service.
236
237
Args:
238
metadata_url (str, optional): Custom metadata service URL
239
"""
240
```
241
242
### OAuth2 Token Exchange Module
243
244
```python { .api }
245
import ydb.oauth2_token_exchange
246
247
class TokenExchangeCredentials(Credentials):
248
def __init__(
249
self,
250
token_endpoint: str,
251
client_id: str,
252
client_secret: str,
253
**kwargs
254
):
255
"""
256
Token exchange credentials with client authentication.
257
258
Args:
259
token_endpoint (str): OAuth2 token endpoint
260
client_id (str): OAuth2 client ID
261
client_secret (str): OAuth2 client secret
262
"""
263
```
264
265
## Usage Examples
266
267
### Anonymous Access (Development)
268
269
```python
270
import ydb
271
272
# No authentication - for local development
273
credentials = ydb.AnonymousCredentials()
274
275
driver = ydb.Driver(
276
endpoint="grpc://localhost:2136",
277
database="/local",
278
credentials=credentials
279
)
280
```
281
282
### Static Token Authentication
283
284
```python
285
import ydb
286
287
# Using static token
288
credentials = ydb.StaticCredentials("your-access-token")
289
290
driver = ydb.Driver(
291
endpoint="grpcs://ydb.example.com:2135",
292
database="/production/db",
293
credentials=credentials
294
)
295
```
296
297
### Environment-Based Credentials
298
299
```python
300
import os
301
import ydb
302
303
# Set environment variable
304
os.environ["YDB_ACCESS_TOKEN_CREDENTIALS"] = "your-token"
305
306
# Automatically detect credentials from environment
307
credentials = ydb.credentials_from_env_variables()
308
309
driver = ydb.Driver(
310
endpoint="grpcs://ydb.example.com:2135",
311
database="/production/db",
312
credentials=credentials
313
)
314
```
315
316
### Yandex Cloud Service Account
317
318
```python
319
import ydb
320
import ydb.iam
321
322
# From service account key file
323
credentials = ydb.iam.ServiceAccountCredentials.from_file(
324
"service-account-key.json"
325
)
326
327
driver = ydb.Driver(
328
endpoint="grpcs://ydb.serverless.yandexcloud.net:2135",
329
database="/ru-central1/b1g..../etn....",
330
credentials=credentials
331
)
332
```
333
334
### Metadata Service Credentials
335
336
```python
337
import ydb
338
import ydb.iam
339
340
# From Yandex Cloud metadata service (inside YC VM)
341
credentials = ydb.iam.MetadataCredentials()
342
343
driver = ydb.Driver(
344
endpoint="grpcs://ydb.serverless.yandexcloud.net:2135",
345
database="/ru-central1/b1g..../etn....",
346
credentials=credentials
347
)
348
```
349
350
### OAuth2 Token Exchange
351
352
```python
353
import ydb
354
355
# OAuth2 token exchange
356
credentials = ydb.OAuth2TokenExchangeCredentials(
357
token_endpoint="https://oauth.example.com/token",
358
resource="https://ydb.example.com",
359
audience="ydb-api",
360
subject_token="initial-token",
361
subject_token_type="urn:ietf:params:oauth:token-type:access_token"
362
)
363
364
driver = ydb.Driver(
365
endpoint="grpcs://ydb.example.com:2135",
366
database="/production/db",
367
credentials=credentials
368
)
369
```
370
371
### Auto-Refreshing Credentials
372
373
```python
374
import ydb
375
376
def create_fresh_credentials():
377
# Fetch new token from your auth system
378
token = fetch_token_from_auth_system()
379
return ydb.StaticCredentials(token)
380
381
# Auto-refresh 5 minutes before expiry
382
credentials = ydb.RefreshableCredentials(
383
credentials_factory=create_fresh_credentials,
384
refresh_threshold=300
385
)
386
387
driver = ydb.Driver(
388
endpoint="grpcs://ydb.example.com:2135",
389
database="/production/db",
390
credentials=credentials
391
)
392
```
393
394
## Types
395
396
```python { .api }
397
# Exception types for credential operations
398
class CredentialsTimeout(Exception):
399
"""Raised when credential operation times out."""
400
401
# Type aliases
402
Token = str
403
Endpoint = str
404
KeyFile = str
405
```