0
# Security Operations
1
2
User and role management, API key operations, token management, and security configuration for Elasticsearch clusters with security features enabled. These operations provide comprehensive security administration capabilities.
3
4
## Capabilities
5
6
### Authentication Operations
7
8
Authenticate users and validate credentials.
9
10
```python { .api }
11
def authenticate(
12
self,
13
**kwargs
14
) -> ObjectApiResponse:
15
"""
16
Authenticate the current user and return user information.
17
18
Returns:
19
ObjectApiResponse with authenticated user details including username, roles, and metadata
20
"""
21
22
def get_token(
23
self,
24
grant_type: str,
25
username: Optional[str] = None,
26
password: Optional[str] = None,
27
refresh_token: Optional[str] = None,
28
scope: Optional[str] = None,
29
**kwargs
30
) -> ObjectApiResponse:
31
"""
32
Get authentication token.
33
34
Parameters:
35
- grant_type: Grant type (password, refresh_token, client_credentials)
36
- username: Username for password grant
37
- password: Password for password grant
38
- refresh_token: Refresh token for token refresh
39
- scope: Requested access scope
40
41
Returns:
42
ObjectApiResponse with access token and refresh token
43
"""
44
45
def invalidate_token(
46
self,
47
token: Optional[str] = None,
48
refresh_token: Optional[str] = None,
49
realm_name: Optional[str] = None,
50
username: Optional[str] = None,
51
**kwargs
52
) -> ObjectApiResponse:
53
"""
54
Invalidate authentication tokens.
55
56
Parameters:
57
- token: Access token to invalidate
58
- refresh_token: Refresh token to invalidate
59
- realm_name: Realm name to invalidate tokens for
60
- username: Username to invalidate tokens for
61
62
Returns:
63
ObjectApiResponse with invalidation result
64
"""
65
```
66
67
### User Management
68
69
Create, update, and manage user accounts.
70
71
```python { .api }
72
def create_user(
73
self,
74
username: str,
75
password: Optional[str] = None,
76
password_hash: Optional[str] = None,
77
roles: Optional[List[str]] = None,
78
full_name: Optional[str] = None,
79
email: Optional[str] = None,
80
metadata: Optional[Dict[str, Any]] = None,
81
enabled: Optional[bool] = None,
82
refresh: Optional[str] = None,
83
**kwargs
84
) -> ObjectApiResponse:
85
"""
86
Create a new user.
87
88
Parameters:
89
- username: Username for the new user
90
- password: Password in plain text
91
- password_hash: Pre-hashed password
92
- roles: List of role names to assign
93
- full_name: Full display name
94
- email: Email address
95
- metadata: Additional user metadata
96
- enabled: Whether user is enabled
97
- refresh: Refresh policy for the request
98
99
Returns:
100
ObjectApiResponse with user creation result
101
"""
102
103
def put_user(
104
self,
105
username: str,
106
password: Optional[str] = None,
107
password_hash: Optional[str] = None,
108
roles: Optional[List[str]] = None,
109
full_name: Optional[str] = None,
110
email: Optional[str] = None,
111
metadata: Optional[Dict[str, Any]] = None,
112
enabled: Optional[bool] = None,
113
refresh: Optional[str] = None,
114
**kwargs
115
) -> ObjectApiResponse:
116
"""
117
Create or update a user.
118
119
Parameters: Same as create_user
120
121
Returns:
122
ObjectApiResponse with user creation or update result
123
"""
124
125
def get_user(
126
self,
127
username: Optional[Union[str, List[str]]] = None,
128
**kwargs
129
) -> ObjectApiResponse:
130
"""
131
Get user information.
132
133
Parameters:
134
- username: Username(s) to retrieve, or None for all users
135
136
Returns:
137
ObjectApiResponse with user information
138
"""
139
140
def delete_user(
141
self,
142
username: str,
143
refresh: Optional[str] = None,
144
**kwargs
145
) -> ObjectApiResponse:
146
"""
147
Delete a user.
148
149
Parameters:
150
- username: Username to delete
151
- refresh: Refresh policy for the request
152
153
Returns:
154
ObjectApiResponse with deletion result
155
"""
156
157
def enable_user(
158
self,
159
username: str,
160
refresh: Optional[str] = None,
161
**kwargs
162
) -> ObjectApiResponse:
163
"""
164
Enable a user account.
165
166
Parameters:
167
- username: Username to enable
168
- refresh: Refresh policy
169
170
Returns:
171
ObjectApiResponse with enable result
172
"""
173
174
def disable_user(
175
self,
176
username: str,
177
refresh: Optional[str] = None,
178
**kwargs
179
) -> ObjectApiResponse:
180
"""
181
Disable a user account.
182
183
Parameters:
184
- username: Username to disable
185
- refresh: Refresh policy
186
187
Returns:
188
ObjectApiResponse with disable result
189
"""
190
191
def change_password(
192
self,
193
username: str,
194
password: str,
195
password_hash: Optional[str] = None,
196
refresh: Optional[str] = None,
197
**kwargs
198
) -> ObjectApiResponse:
199
"""
200
Change user password.
201
202
Parameters:
203
- username: Username to change password for
204
- password: New password in plain text
205
- password_hash: New pre-hashed password
206
- refresh: Refresh policy
207
208
Returns:
209
ObjectApiResponse with password change result
210
"""
211
```
212
213
### Role Management
214
215
Define and manage user roles and permissions.
216
217
```python { .api }
218
def create_role(
219
self,
220
name: str,
221
cluster: Optional[List[str]] = None,
222
indices: Optional[List[Dict[str, Any]]] = None,
223
applications: Optional[List[Dict[str, Any]]] = None,
224
run_as: Optional[List[str]] = None,
225
metadata: Optional[Dict[str, Any]] = None,
226
transient_metadata: Optional[Dict[str, Any]] = None,
227
global_: Optional[Dict[str, Any]] = None,
228
refresh: Optional[str] = None,
229
**kwargs
230
) -> ObjectApiResponse:
231
"""
232
Create a role.
233
234
Parameters:
235
- name: Role name
236
- cluster: List of cluster privileges
237
- indices: List of index privilege specifications
238
- applications: List of application privilege specifications
239
- run_as: List of usernames this role can impersonate
240
- metadata: Role metadata
241
- transient_metadata: Transient metadata
242
- global_: Global privileges configuration
243
- refresh: Refresh policy
244
245
Returns:
246
ObjectApiResponse with role creation result
247
"""
248
249
def put_role(
250
self,
251
name: str,
252
cluster: Optional[List[str]] = None,
253
indices: Optional[List[Dict[str, Any]]] = None,
254
applications: Optional[List[Dict[str, Any]]] = None,
255
run_as: Optional[List[str]] = None,
256
metadata: Optional[Dict[str, Any]] = None,
257
transient_metadata: Optional[Dict[str, Any]] = None,
258
global_: Optional[Dict[str, Any]] = None,
259
refresh: Optional[str] = None,
260
**kwargs
261
) -> ObjectApiResponse:
262
"""
263
Create or update a role.
264
265
Parameters: Same as create_role
266
267
Returns:
268
ObjectApiResponse with role creation or update result
269
"""
270
271
def get_role(
272
self,
273
name: Optional[Union[str, List[str]]] = None,
274
**kwargs
275
) -> ObjectApiResponse:
276
"""
277
Get role information.
278
279
Parameters:
280
- name: Role name(s) to retrieve, or None for all roles
281
282
Returns:
283
ObjectApiResponse with role information
284
"""
285
286
def delete_role(
287
self,
288
name: str,
289
refresh: Optional[str] = None,
290
**kwargs
291
) -> ObjectApiResponse:
292
"""
293
Delete a role.
294
295
Parameters:
296
- name: Role name to delete
297
- refresh: Refresh policy
298
299
Returns:
300
ObjectApiResponse with deletion result
301
"""
302
```
303
304
### API Key Management
305
306
Generate and manage API keys for authentication.
307
308
```python { .api }
309
def create_api_key(
310
self,
311
name: str,
312
role_descriptors: Optional[Dict[str, Any]] = None,
313
expiration: Optional[str] = None,
314
metadata: Optional[Dict[str, Any]] = None,
315
refresh: Optional[str] = None,
316
**kwargs
317
) -> ObjectApiResponse:
318
"""
319
Create an API key.
320
321
Parameters:
322
- name: API key name
323
- role_descriptors: Role definitions for the API key
324
- expiration: Expiration time for the key
325
- metadata: API key metadata
326
- refresh: Refresh policy
327
328
Returns:
329
ObjectApiResponse with API key details including the key value
330
"""
331
332
def get_api_key(
333
self,
334
id: Optional[str] = None,
335
name: Optional[str] = None,
336
realm_name: Optional[str] = None,
337
username: Optional[str] = None,
338
owner: Optional[bool] = None,
339
**kwargs
340
) -> ObjectApiResponse:
341
"""
342
Get API key information.
343
344
Parameters:
345
- id: API key ID
346
- name: API key name
347
- realm_name: Realm name
348
- username: Username
349
- owner: Whether to return only keys owned by authenticated user
350
351
Returns:
352
ObjectApiResponse with API key information
353
"""
354
355
def invalidate_api_key(
356
self,
357
id: Optional[str] = None,
358
name: Optional[str] = None,
359
realm_name: Optional[str] = None,
360
username: Optional[str] = None,
361
owner: Optional[bool] = None,
362
**kwargs
363
) -> ObjectApiResponse:
364
"""
365
Invalidate API keys.
366
367
Parameters:
368
- id: API key ID to invalidate
369
- name: API key name to invalidate
370
- realm_name: Realm name to invalidate keys for
371
- username: Username to invalidate keys for
372
- owner: Whether to invalidate only keys owned by authenticated user
373
374
Returns:
375
ObjectApiResponse with invalidation result
376
"""
377
378
def grant_api_key(
379
self,
380
grant_type: str,
381
api_key: Dict[str, Any],
382
access_token: Optional[str] = None,
383
username: Optional[str] = None,
384
password: Optional[str] = None,
385
**kwargs
386
) -> ObjectApiResponse:
387
"""
388
Grant API key on behalf of another user.
389
390
Parameters:
391
- grant_type: Grant type (password, access_token)
392
- api_key: API key specification
393
- access_token: Access token for access_token grant
394
- username: Username for password grant
395
- password: Password for password grant
396
397
Returns:
398
ObjectApiResponse with granted API key
399
"""
400
```
401
402
### Privilege Management
403
404
Manage application privileges and check user permissions.
405
406
```python { .api }
407
def put_privileges(
408
self,
409
privileges: Dict[str, Any],
410
refresh: Optional[str] = None,
411
**kwargs
412
) -> ObjectApiResponse:
413
"""
414
Create or update application privileges.
415
416
Parameters:
417
- privileges: Privilege definitions by application
418
- refresh: Refresh policy
419
420
Returns:
421
ObjectApiResponse with privilege creation result
422
"""
423
424
def get_privileges(
425
self,
426
application: Optional[str] = None,
427
name: Optional[str] = None,
428
**kwargs
429
) -> ObjectApiResponse:
430
"""
431
Get application privileges.
432
433
Parameters:
434
- application: Application name
435
- name: Privilege name
436
437
Returns:
438
ObjectApiResponse with privilege information
439
"""
440
441
def delete_privileges(
442
self,
443
application: str,
444
name: str,
445
refresh: Optional[str] = None,
446
**kwargs
447
) -> ObjectApiResponse:
448
"""
449
Delete application privileges.
450
451
Parameters:
452
- application: Application name
453
- name: Privilege name
454
- refresh: Refresh policy
455
456
Returns:
457
ObjectApiResponse with deletion result
458
"""
459
460
def has_privileges(
461
self,
462
user: Optional[str] = None,
463
cluster: Optional[List[str]] = None,
464
index: Optional[List[Dict[str, Any]]] = None,
465
application: Optional[List[Dict[str, Any]]] = None,
466
**kwargs
467
) -> ObjectApiResponse:
468
"""
469
Check user privileges.
470
471
Parameters:
472
- user: Username to check privileges for
473
- cluster: Cluster privileges to check
474
- index: Index privileges to check
475
- application: Application privileges to check
476
477
Returns:
478
ObjectApiResponse with privilege check results
479
"""
480
```
481
482
### Certificate Management
483
484
Manage SSL certificates and certificate authorities.
485
486
```python { .api }
487
def get_builtin_privileges(
488
self,
489
**kwargs
490
) -> ObjectApiResponse:
491
"""
492
Get built-in cluster and index privileges.
493
494
Returns:
495
ObjectApiResponse with built-in privilege definitions
496
"""
497
498
def clear_cached_realms(
499
self,
500
realms: List[str],
501
**kwargs
502
) -> ObjectApiResponse:
503
"""
504
Clear cached realm information.
505
506
Parameters:
507
- realms: List of realm names to clear
508
509
Returns:
510
ObjectApiResponse with cache clearing result
511
"""
512
513
def clear_cached_roles(
514
self,
515
name: List[str],
516
**kwargs
517
) -> ObjectApiResponse:
518
"""
519
Clear cached role information.
520
521
Parameters:
522
- name: List of role names to clear from cache
523
524
Returns:
525
ObjectApiResponse with cache clearing result
526
"""
527
528
def clear_cached_privileges(
529
self,
530
application: List[str],
531
**kwargs
532
) -> ObjectApiResponse:
533
"""
534
Clear cached application privileges.
535
536
Parameters:
537
- application: List of application names to clear
538
539
Returns:
540
ObjectApiResponse with cache clearing result
541
"""
542
```
543
544
## Usage Examples
545
546
### User Management
547
548
```python
549
from elasticsearch import Elasticsearch
550
551
client = Elasticsearch(
552
hosts=['https://localhost:9200'],
553
http_auth=('admin', 'admin_password'),
554
verify_certs=True
555
)
556
557
# Create a new user
558
client.security.create_user(
559
username="analyst_user",
560
password="secure_password123",
561
roles=["data_analyst", "kibana_user"],
562
full_name="Data Analyst",
563
email="analyst@company.com",
564
metadata={
565
"department": "analytics",
566
"hire_date": "2024-01-01"
567
},
568
enabled=True
569
)
570
571
# Get user information
572
user_info = client.security.get_user(username="analyst_user")
573
print(f"User roles: {user_info.body['analyst_user']['roles']}")
574
575
# Update user roles
576
client.security.put_user(
577
username="analyst_user",
578
roles=["data_analyst", "kibana_user", "monitoring_user"]
579
)
580
581
# Change user password
582
client.security.change_password(
583
username="analyst_user",
584
password="new_secure_password456"
585
)
586
587
# Disable user temporarily
588
client.security.disable_user(username="analyst_user")
589
590
# Re-enable user
591
client.security.enable_user(username="analyst_user")
592
```
593
594
### Role Management
595
596
```python
597
# Create a custom role with specific privileges
598
client.security.create_role(
599
name="custom_data_analyst",
600
cluster=["monitor", "manage_index_templates"],
601
indices=[
602
{
603
"names": ["sales-*", "analytics-*"],
604
"privileges": ["read", "view_index_metadata"],
605
"field_security": {
606
"grant": ["*"],
607
"except": ["sensitive_field"]
608
},
609
"query": {
610
"term": {"department": "sales"}
611
}
612
},
613
{
614
"names": ["logs-*"],
615
"privileges": ["read"],
616
"query": {
617
"range": {
618
"@timestamp": {"gte": "now-30d"}
619
}
620
}
621
}
622
],
623
applications=[
624
{
625
"application": "kibana-.kibana",
626
"privileges": ["feature_dashboard.read", "feature_visualize.read"],
627
"resources": ["space:default"]
628
}
629
],
630
metadata={
631
"created_by": "admin",
632
"description": "Custom role for data analysts"
633
}
634
)
635
636
# Get role information
637
role_info = client.security.get_role(name="custom_data_analyst")
638
for role_name, role_def in role_info.body.items():
639
print(f"Role: {role_name}")
640
print(f"Cluster privileges: {role_def['cluster']}")
641
print(f"Index privileges: {len(role_def['indices'])} definitions")
642
643
# Update role to add run_as privilege
644
client.security.put_role(
645
name="custom_data_analyst",
646
cluster=["monitor", "manage_index_templates"],
647
indices=[
648
{
649
"names": ["sales-*", "analytics-*", "reports-*"],
650
"privileges": ["read", "view_index_metadata"]
651
}
652
],
653
run_as=["report_user"]
654
)
655
```
656
657
### API Key Management
658
659
```python
660
# Create API key for application access
661
api_key_response = client.security.create_api_key(
662
name="analytics_app_key",
663
role_descriptors={
664
"analytics_role": {
665
"cluster": ["monitor"],
666
"indices": [
667
{
668
"names": ["analytics-*"],
669
"privileges": ["read", "write"]
670
}
671
]
672
}
673
},
674
expiration="90d",
675
metadata={
676
"application": "analytics_dashboard",
677
"environment": "production"
678
}
679
)
680
681
api_key = api_key_response.body['api_key']
682
api_key_id = api_key_response.body['id']
683
print(f"API Key created: {api_key_id}")
684
685
# Use API key for authentication
686
api_client = Elasticsearch(
687
hosts=['https://localhost:9200'],
688
api_key=(api_key_id, api_key),
689
verify_certs=True
690
)
691
692
# List API keys
693
keys = client.security.get_api_key(owner=True)
694
for key in keys.body['api_keys']:
695
print(f"Key: {key['name']}, Created: {key['creation']}, Status: {'Valid' if not key['invalidated'] else 'Invalid'}")
696
697
# Invalidate API key when no longer needed
698
client.security.invalidate_api_key(id=api_key_id)
699
```
700
701
### Authentication and Authorization
702
703
```python
704
# Authenticate current user
705
auth_info = client.security.authenticate()
706
current_user = auth_info.body
707
print(f"Authenticated as: {current_user['username']}")
708
print(f"Roles: {current_user['roles']}")
709
print(f"Full name: {current_user['full_name']}")
710
711
# Check user privileges
712
privilege_check = client.security.has_privileges(
713
cluster=["monitor", "manage_index_templates"],
714
index=[
715
{
716
"names": ["sales-*"],
717
"privileges": ["read", "write"]
718
},
719
{
720
"names": ["logs-*"],
721
"privileges": ["read"]
722
}
723
]
724
)
725
726
print(f"Has cluster monitor privilege: {privilege_check.body['cluster']['monitor']}")
727
for index_check in privilege_check.body['index']:
728
index_name = list(index_check.keys())[0]
729
privileges = index_check[index_name]
730
print(f"Index {index_name} privileges: {privileges}")
731
732
# Get available built-in privileges
733
builtin_privileges = client.security.get_builtin_privileges()
734
print("Available cluster privileges:", builtin_privileges.body['cluster'])
735
print("Available index privileges:", builtin_privileges.body['index'])
736
```
737
738
### Token-Based Authentication
739
740
```python
741
# Get authentication token
742
token_response = client.security.get_token(
743
grant_type="password",
744
username="analyst_user",
745
password="secure_password123"
746
)
747
748
access_token = token_response.body['access_token']
749
refresh_token = token_response.body['refresh_token']
750
751
# Use token for authentication
752
token_client = Elasticsearch(
753
hosts=['https://localhost:9200'],
754
headers={"Authorization": f"Bearer {access_token}"},
755
verify_certs=True
756
)
757
758
# Refresh token when needed
759
new_token_response = client.security.get_token(
760
grant_type="refresh_token",
761
refresh_token=refresh_token
762
)
763
764
# Invalidate tokens when done
765
client.security.invalidate_token(
766
token=access_token,
767
refresh_token=refresh_token
768
)
769
```
770
771
### Advanced Security Configuration
772
773
```python
774
# Create application privileges
775
client.security.put_privileges(
776
privileges={
777
"myapp": {
778
"read": {
779
"application": "myapp",
780
"name": "read",
781
"actions": ["data:read/*", "action:login"],
782
"metadata": {
783
"description": "Read access to myapp"
784
}
785
},
786
"write": {
787
"application": "myapp",
788
"name": "write",
789
"actions": ["data:write/*", "data:read/*", "action:login"],
790
"metadata": {
791
"description": "Write access to myapp"
792
}
793
}
794
}
795
}
796
)
797
798
# Create role with application privileges
799
client.security.create_role(
800
name="myapp_user",
801
applications=[
802
{
803
"application": "myapp",
804
"privileges": ["read"],
805
"resources": ["resource1", "resource2"]
806
}
807
]
808
)
809
810
# Clear caches for performance
811
client.security.clear_cached_roles(name=["myapp_user"])
812
client.security.clear_cached_privileges(application=["myapp"])
813
```