-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathipa.py
More file actions
3975 lines (3325 loc) · 134 KB
/
ipa.py
File metadata and controls
3975 lines (3325 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""IPA multihost role."""
from __future__ import annotations
import os
import re
import shlex
import time
import uuid
from itertools import groupby
from textwrap import dedent
from typing import Any, Literal, Optional
from pytest_mh import MultihostHost
from pytest_mh.cli import CLIBuilder, CLIBuilderArgs
from pytest_mh.conn import ProcessError, ProcessResult
from pytest_mh.utils.fs import LinuxFileSystem
from ..hosts.ipa import IPAHost
from ..misc import (
attrs_include_value,
attrs_parse,
delimiter_parse,
get_attr,
ip_version,
to_list,
to_list_of_strings,
to_list_without_none,
)
from ..misc.globals import test_venv_bin
from ..roles.client import Client
from ..utils.sssctl import SSSCTLUtils
from ..utils.sssd import SSSDUtils
from .base import BaseLinuxRole, BaseObject
from .generic import GenericNetgroupMember, GenericPasswordPolicy
from .nfs import NFSExport
__all__ = [
"IPA",
"IPAObject",
"IPAPasswordPolicy",
"IPAUser",
"IPAGroup",
"IPASudoRule",
"IPAAutomount",
"IPAAutomountLocation",
"IPAAutomountMap",
"IPAAutomountKey",
"IPADNSServer",
"IPADNSZone",
"IPACertificateAuthority",
"IPAHBACService",
"IPAHBACServiceGroup",
"IPAHostGroup",
"IPAHBAC",
]
RevocationReason = Literal[
"unspecified",
"key_compromise",
"ca_compromise",
"affiliation_changed",
"superseded",
"cessation_of_operation",
"certificate_hold",
"remove_from_crl",
"privilege_withdrawn",
"aa_compromise",
]
class IPA(BaseLinuxRole[IPAHost]):
"""
IPA role.
Provides unified Python API for managing objects in the IPA server.
.. code-block:: python
:caption: Creating user and group
@pytest.mark.topology(KnownTopology.IPA)
def test_example(ipa: IPA):
u = ipa.user('tuser').add()
g = ipa.group('tgroup').add()
g.add_member(u)
.. note::
The role object is instantiated automatically as a dynamic pytest
fixture by the multihost plugin. You should not create the object
manually.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.domain: str = self.host.domain
"""
IPA domain name.
"""
self.realm: str = self.host.realm
"""
Kerberos realm.
"""
self.name: str = "ipa"
"""
Generic provider name.
"""
self.server: str = self.host.hostname
"""
Generic server name.
"""
self.sssd: SSSDUtils = SSSDUtils(self.host, self.fs, self.svc, self.authselect, load_config=True)
"""
Managing and configuring SSSD.
"""
self.sssctl: SSSCTLUtils = SSSCTLUtils(self.host, self.fs)
"""
Call commands from sssctl.
"""
self._password_policy: IPAPasswordPolicy = IPAPasswordPolicy(self)
"""
Manage password policy.
"""
self.automount: IPAAutomount = IPAAutomount(self)
"""
Manage automount locations, maps and keys.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(client: Client, ipa: IPA, nfs: NFS):
nfs_export1 = nfs.export('export1').add()
nfs_export2 = nfs.export('export2').add()
nfs_export3 = nfs.export('sub/export3').add()
# Create automout location
loc = ipa.automount.location('boston').add()
# Create automount maps
auto_master = loc.map('auto.master').add()
auto_home = loc.map('auto.home').add()
auto_sub = loc.map('auto.sub').add()
# Create mount points
auto_master.key('/ehome').add(info=auto_home)
auto_master.key('/esub/sub1/sub2').add(info=auto_sub)
# Create mount keys
key1 = auto_home.key('export1').add(info=nfs_export1)
key2 = auto_home.key('export2').add(info=nfs_export2)
key3 = auto_sub.key('export3').add(info=nfs_export3)
# Start SSSD
client.sssd.common.autofs()
client.sssd.domain['ipa_automount_location'] = 'boston'
client.sssd.start()
# Reload automounter in order to fetch updated maps
client.automount.reload()
# Check that we can mount all directories on correct locations
assert client.automount.mount('/ehome/export1', nfs_export1)
assert client.automount.mount('/ehome/export2', nfs_export2)
assert client.automount.mount('/esub/sub1/sub2/export3', nfs_export3)
# Check that the maps are correctly fetched
assert client.automount.dumpmaps() == {
'/ehome': {
'map': 'auto.home',
'keys': [str(key1), str(key2)]
},
'/esub/sub1/sub2': {
'map': 'auto.sub',
'keys': [str(key3)]
},
}
"""
self.ca = IPACertificateAuthority(self.host, self.fs)
"""
IPA Certificate Authority management.
Provides certificate operations:
- Request certificates for services/users
- Revoke certificates with configurable reasons
- Manage certificate holds
- Retrieve certificate details
Example:
cert, key, csr = ipa.ca.request(principal="HTTP/client.ipa.test")
ipa.ca.revoke_hold(cert)
ipa.ca.revoke(cert, reason="key_compromise")
"""
@property
def password_policy(self) -> IPAPasswordPolicy:
"""
Domain password policy management.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(client: Client, ipa: IPA):
# Enable password complexity
ipa.password_policy.complexity(enable=True)
# Set 3 login attempts and 30 lockout duration
ipa.password_policy.lockout(attempts=3, duration=30)
"""
return self._password_policy
@property
def naming_context(self) -> str:
"""
Naming context.
"""
ipa_default = self.fs.read("/etc/ipa/default.conf")
_ipa_default = ipa_default.strip().splitlines()
for i in _ipa_default:
if "basedn" in i:
return str(i.split("=", 1)[1])
raise ValueError("basedn not found in /etc/ipa/default.conf!")
def setup(self) -> None:
"""
Obtain IPA admin Kerberos TGT.
"""
super().setup()
# Restart SSSD so it is opened with new database files.
self.sssd.stop()
self.sssd.clear(db=True, memcache=True, logs=True, config=False)
self.sssd.start()
# Obtain admin TGT
self.host.kinit()
def fqn(self, name: str) -> str:
"""
Return fully qualified name in form name@domain.
:param name: Username.
:type name: str
:return: Fully qualified name.
:rtype: str
"""
return f"{name}@{self.domain}"
@staticmethod
def ipa_search(
role: IPA,
command: str,
criteria: str | None = None,
attr: str = "cn",
all: bool = False,
) -> list[str]:
"""
Perform a generic IPA search command and extract attribute values.
:param role: IPA role object.
:type role: IPA
:param command: IPA command to run (e.g., 'hostgroup-find').
:type command: str
:param criteria: Optional search filter string.
:type criteria: str or None, optional
:param attr: Attribute name to extract from each entry.
:type attr: str, optional
:param all: Prints all attributes, default is False.
:type all: bool, optional
:return: List of extracted attribute values.
:rtype: list[str]
"""
cmd = ["ipa", command]
if all:
cmd.append("--all")
if criteria:
cmd.append(criteria)
result = role.host.conn.exec(cmd)
names: list[str] = []
blocks = (
list(group) for key, group in groupby(result.stdout_lines, key=lambda line: line.strip() == "") if not key
)
for block in blocks:
attrs = attrs_parse(block)
values = attrs.get(attr, [])
for value in values:
if isinstance(value, list):
names.extend(value)
else:
names.append(value)
return names
def user(self, name: str) -> IPAUser:
"""
Get user object.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(client: Client, ipa: IPA):
# Create user
ipa.user('user-1').add()
# Start SSSD
client.sssd.start()
# Call `id user-1` and assert the result
result = client.tools.id('user-1')
assert result is not None
assert result.user.name == 'user-1'
assert result.group.name == 'user-1'
:param name: Username.
:type name: str
:return: New user object.
:rtype: IPAUser
"""
return IPAUser(self, name)
def group(self, name: str) -> IPAGroup:
"""
Get group object.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example_group(client: Client, ipa: IPA):
# Create user
user = ipa.user('user-1').add()
# Create secondary group and add user as a member
ipa.group('group-1').add().add_member(user)
# Start SSSD
client.sssd.start()
# Call `id user-1` and assert the result
result = client.tools.id('user-1')
assert result is not None
assert result.user.name == 'user-1'
assert result.group.name == 'user-1'
assert result.memberof('group-1')
:param name: Group name.
:type name: str
:return: New group object.
:rtype: IPAGroup
"""
return IPAGroup(self, name)
def netgroup(self, name: str) -> IPANetgroup:
"""
Get netgroup object.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example_netgroup(client: Client, ipa: IPA):
# Create user
user = ipa.user("user-1").add()
# Create two netgroups
ng1 = ipa.netgroup("ng-1").add()
ng2 = ipa.netgroup("ng-2").add()
# Add user and ng2 as members to ng1
ng1.add_member(user=user)
ng1.add_member(ng=ng2)
# Add host as member to ng2
ng2.add_member(host="client")
# Start SSSD
client.sssd.start()
# Call `getent netgroup ng-1` and assert the results
result = client.tools.getent.netgroup("ng-1")
assert result is not None
assert result.name == "ng-1"
assert len(result.members) == 2
assert "(-,user-1,ipa.test)" in result.members
assert "(client.test,-,ipa.test)" in result.members
:param name: Netgroup name.
:type name: str
:return: New netgroup object.
:rtype: IPANetgroup
"""
return IPANetgroup(self, name)
def host_account(self, name: str) -> IPAHostAccount:
"""
Get host object.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(client: Client, ipa: IPA):
# Create host
ipa.host_account(f'myhost.{ipa.domain}').add(ip="10.255.251.10")
:param name: Hostname.
:type name: str
:return: New host account object.
:rtype: IPAHostAccount
"""
return IPAHostAccount(self, name)
def sudorule(self, name: str) -> IPASudoRule:
"""
Get sudo rule object.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(client: Client, ipa: IPA):
user = ipa.user('user-1').add(password="Secret123")
ipa.sudorule('testrule').add(user=user, host='ALL', command='/bin/ls')
client.sssd.common.sudo()
client.sssd.start()
# Test that user can run /bin/ls
assert client.auth.sudo.run('user-1', 'Secret123', command='/bin/ls')
:param name: Sudo rule name.
:type name: str
:return: New sudo rule object.
:rtype: IPASudoRule
"""
return IPASudoRule(self, name)
def idview(self, name: str) -> IPAIDView:
"""
IPA ID View object.
Here, we only add the IPA ID view, that can be used
while creating a new User ID override.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_example(ipa: IPA):
ipa.idview("newview").add(description="This is a new view")
ipa.idview("newview").apply(hosts="client.test")
ipa.idview("newview").delete()
:param name: ID View name.
:type name: str
:return: New ID View object.
"""
return IPAIDView(self, name)
def dns(self) -> IPADNSServer:
"""
Get DNS server object.
Get methods use dig and is parsed by jc. The data from jc contains several nested dict,
but two are returned as a tuple, ``answer, authority``.
.. code-block:: python
:caption: Example usage
# Create forward zone and add forward record
zone = ipa.dns().zone("example.test").create()
zone.add_record("client", "172.16.200.15")
# Create reverse zone and add reverse record
zone = ipa.dns().zone("10.0.10.in-addr.arpa").create()
zone.add_ptr_record("client.example.test", 15)
# Add forward record to default domain
ipa.dns().zone(ipa.domain).add_record("client", "1.2.3.4")
# Add a global forwarder
ipa.dns().add_forwarder("1.1.1.1")
# Remove a global forwarder
ipa.dns().remove_forwarder("1.1.1.1")
# Clear all forwarders
ipa.dns().clear_forwarders()
"""
return IPADNSServer(self)
def hbac(self, name: str) -> IPAHBAC:
"""
IPA HBAC object.
Provides access to manage HBAC (Host-Based Access Control) rules in IPA.
This allows creating rules and setting access controls for particular hosts and services.
.. rubric:: Example usage
.. code-block:: python
@pytest.mark.topology(KnownTopology.IPA)
def test_ipa__validate_hbac_rule_check_access_sshd_service(client: Client, ipa: IPA):
# Disable all users to access all services on all hosts.
ipa.hbac("allow_all").disable()
ssh_access_rule = ipa.hbac("ssh_access_user1").create(
description="SSH access rule for user1",
users="user1",
hosts="client.test",
services="sshd"
)
hbactest_out1 = ssh_access_rule.test(user="user1", host="client.test",
service="sshd", rule="ssh_access_user1")
assert hbactest_out1["access_granted"], "Access was not granted as expected"
assert "ssh_access_user1" in hbactest_out1["matched_rules"], \
"Matched rule ssh_access_user1 was not found as expected"
hbactest_out2 = ssh_access_rule.test(user="user2", host="client.test",
service="sshd", rule="ssh_access_user1")
assert not hbactest_out2["access_granted"], "Access was granted which is not expected"
assert "ssh_access_user1" in hbactest_out2["not_matched_rules"], \
"Rule should not match for user2"
hbactest_out3 = ssh_access_rule.test(user="user1", host="client.test",
service="sshd", rule="nonexistent_rule")
assert "nonexistent_rule" in hbactest_out3["invalid_rules"], \
"Non-existent rule nonexistent_rule should be reported as invalid"
hbactest_out4 = ssh_access_rule.test(user="user2", host="client.test",
service="sshd", rule="nonexistent_rule")
assert "nonexistent_rule" in hbactest_out4["invalid_rules"], \
"Non-existent rule nonexistent_rule should be reported as invalid"
client.sssd.restart()
assert client.auth.ssh.password("user1", "Secret123"), "user1 should be able to SSH"
assert not client.auth.ssh.password("user2", "Secret123"), "user2 should be denied SSH"
assert not client.auth.ssh.password("user3", "Secret123"), "user3 should be denied SSH"
ssh_access_rule.delete()
client.sssd.restart()
assert not client.auth.ssh.password("user1", "Secret123"), "user1 should be denied after rule deletion"
assert not client.auth.ssh.password("user2", "Secret123"), "user2 should be denied after rule deletion"
assert not client.auth.ssh.password("user3", "Secret123"), "user3 should be denied after rule deletion"
:param name: IPA HBAC rule name.
:type name: str
:return: New HBAC object.
:rtype: IPAHBAC
"""
return IPAHBAC(self, name)
def hostgroup(self, name: str) -> IPAHostGroup:
"""
IPA Host Group object.
Here, we can create and manage IPA host groups, which are collections
of hosts that can be used in HBAC rules for simplified host management.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_ipa__validate_hbac_rule_host_group_access(client: Client, ipa: IPA):
# Create users for testing
users = ["user1", "user2"]
for user in users:
ipa.user(user).add()
# Create host groups
web_group = ipa.hostgroup("webservers").add(description="Web servers group")
db_group = ipa.hostgroup("dbservers").add(description="Database servers group")
# Add hosts to webservers group
web_group.add_member(host=["client.test"])
# Disable default allow_all rule
ipa.hbac("allow_all").disable()
# Create HBAC rule using host group
webservers_ssh_rule = ipa.hbac("webservers_ssh_access").create(
description="SSH access for webservers host group",
users="user1",
hostgroups="webservers",
services="sshd"
)
# Test access via host group
hbactest_result = webservers_ssh_rule.test(user="user1", host="client.test", service="sshd")
assert hbactest_result["access_granted"], "user1 should have access via host group"
# Remove host from group and test access is denied
web_group.remove_member(host=["client.test"])
client.sssd.restart()
assert not client.auth.ssh.password("user1", "Secret123"), "user1 should be denied after host removal"
:param name: IPA host group name.
:type name: str
:return: New host group object.
:rtype: IPAHostGroup
"""
return IPAHostGroup(self, name)
def hbacsvc(self, name: str) -> IPAHBACService:
"""
IPA HBAC Service object.
This method creates and returns an IPA HBAC service object, which represents
individual services that can be used in HBAC rules to control access at the service level.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_ipa__validate_hbac_rule_service_access(client: Client, ipa: IPA):
# Create users for testing
users = ["user1", "user2"]
for user in users:
ipa.user(user).add()
# Create HBAC service
ssh_service = ipa.hbacsvc("sshd").add(description="SSH service")
# Disable default allow_all rule
ipa.hbac("allow_all").disable()
# Create HBAC rule using the service
remote_services_rule = ipa.hbac("remote_services_access").create(
description="Remote access via specific services",
users="user1",
hosts="client.test",
services="sshd"
)
# Test access to the sshd service
hbactest_ssh = remote_services_rule.test(user="user1", host="client.test", service="sshd")
assert hbactest_ssh["access_granted"], "user1 should have sshd access"
# Test access to a service not authorized
hbactest_http = remote_services_rule.test(user="user1", host="client.test", service="httpd")
assert not hbactest_http["access_granted"], "user1 should be denied httpd access"
# Remove service from the HBAC rule and test access is denied
ipa.hbacsvc("sshd").remove_member()
client.sssd.restart()
assert not client.auth.ssh.password("user1", "Secret123"), "user1 denied after service removal"
:param name: IPA HBAC service name.
:type name: str
:return: New HBAC service object.
:rtype: IPAHBACService
"""
return IPAHBACService(self, name)
def hbacsvcgroup(self, name: str) -> IPAHBACServiceGroup:
"""
IPA HBAC Service Group object.
In this we can create and manage IPA HBAC service groups, which are collections
of services that can be used in HBAC rules for simplified service management.
.. code-block:: python
:caption: Example usage
@pytest.mark.topology(KnownTopology.IPA)
def test_ipa__validate_hbac_rule_service_group_access(client: Client, ipa: IPA):
# Create users for testing
users = ["user1", "user2"]
for user in users:
ipa.user(user).add()
# Create service group and add services
remote_svc_group = ipa.hbacsvcgroup("remote_access").add(description="Remote access services")
remote_svc_group.add_member(hbacsvc=["sshd"])
# Disable default allow_all rule
ipa.hbac("allow_all").disable()
# Create HBAC rule using service group
remote_services_rule = ipa.hbac("remote_services_access").create(
description="Remote access via service groups",
users="user1",
hosts="client.test",
servicegroups="remote_access"
)
# Test access to services in the group
hbactest_ssh = remote_services_rule.test(user="user1", host="client.test", service="sshd")
assert hbactest_ssh["access_granted"], "user1 should have sshd access via service group"
# Test access to service not in group
hbactest_http = remote_services_rule.test(user="user1", host="client.test", service="httpd")
assert not hbactest_http["access_granted"], "user1 should be denied httpd access"
# Remove service from group and test access is denied
remote_svc_group.remove_member(hbacsvc=["sshd"])
client.sssd.restart()
assert not client.auth.ssh.password("user1", "Secret123"), "user1 denied after service removal"
:param name: IPA HBAC service group name.
:type name: str
:return: New HBAC service group object.
:rtype: IPAHBACServiceGroup
"""
return IPAHBACServiceGroup(self, name)
class IPAObject(BaseObject[IPAHost, IPA]):
"""
Base class for IPA object management.
Provides shortcuts for command execution and implementation of :meth:`get`
and :meth:`delete` methods.
"""
def __init__(self, role: IPA, name: str, command_group: str) -> None:
"""
:param role: IPA role object.
:type role: IPA
:param name: Object name.
:type name: str
:param command_group: IPA command group.
:type command_group: str
"""
super().__init__(role)
self.command_group: str = command_group
"""IPA cli command group."""
self.name: str = name
"""Object name."""
def _exec(
self, op: str, args: list[str] | None = None, ipaargs: list[str] | None = None, **kwargs
) -> ProcessResult:
"""
Execute IPA command.
.. code-block:: console
$ ipa $ipaargs $command_group-$op $name $args
for example >>> ipa user-add tuser
:param op: Command group operation (usually add, mod, del, show)
:type op: str
:param args: List of additional command arguments, defaults to None
:type args: list[str] | None, optional
:param ipaargs: List of additional command arguments to the ipa main command, defaults to None
:type ipaargs: list[str] | None, optional
:return: SSH process result.
:rtype: ProcessResult
"""
if args is None:
args = []
if ipaargs is None:
ipaargs = []
return self.role.host.conn.exec(["ipa", *ipaargs, f"{self.command_group}-{op}", self.name, *args], **kwargs)
def _add(self, attrs: CLIBuilderArgs | None = None, input: str | None = None):
"""
Add IPA object.
:param attrs: Object attributes in :class:`pytest_mh.cli.CLIBuilder` format, defaults to None
:type attrs: pytest_mh.cli.CLIBuilderArgs | None, optional
:param input: Contents of standard input given to the executed command, defaults to None
:type input: str | None, optional
"""
if attrs is None:
attrs = {}
self._exec("add", self.cli.args(attrs), input=input)
def _modify(self, attrs: CLIBuilderArgs, input: str | None = None):
"""
Modify IPA object.
:param attrs: Object attributes in :class:`pytest_mh.cli.CLIBuilder` format, defaults to dict()
:type attrs: pytest_mh.cli.CLIBuilderArgs, optional
:param input: Contents of standard input given to the executed command, defaults to None
:type input: str | None, optional
"""
self._exec("mod", self.cli.args(attrs), input=input)
def delete(self) -> None:
"""
Delete IPA object.
"""
self._exec("del")
def get(self, attrs: list[str] | None = None) -> dict[str, list[str]] | None:
"""
Get IPA object attributes.
:param attrs: If set, only requested attributes are returned, defaults to None
:type attrs: list[str] | None, optional
:return: Dictionary with attribute name as a key or None if no such attribute is found.
:rtype: dict[str, list[str]] | None
"""
cmd = self._exec("show", ["--all", "--raw"], raise_on_error=False)
# ipa output starts with space
lines = dedent(cmd.stdout).splitlines()
if lines is None or len(lines) == 0:
return None
# Remove first line that contains the object name and not attribute
return attrs_parse(lines[1:], attrs)
class IPAUser(IPAObject):
"""
IPA user management.
"""
def __init__(self, role: IPA, name: str) -> None:
"""
:param role: IPA role object.
:type role: IPA
:param name: Username.
:type name: str
"""
super().__init__(role, name, command_group="user")
def add(
self,
*,
uid: int | None = None,
gid: int | None = None,
password: str | None = "Secret123",
home: str | None = None,
gecos: str | None = None,
shell: str | None = None,
require_password_reset: bool = False,
user_auth_type: str | list[str] | None = None,
sshpubkey: str | list[str] | None = None,
email: str | None = None,
) -> IPAUser:
"""
Create new IPA user.
Parameters that are not set are ignored.
:param uid: User id, defaults to None
:type uid: int | None, optional
:param gid: Primary group id, defaults to None
:type gid: int | None, optional
:param password: Password, defaults to 'Secret123'
:type password: str | None, optional
:param home: Home directory, defaults to None
:type home: str | None, optional
:param gecos: GECOS, defaults to None
:type gecos: str | None, optional
:param shell: Login shell, defaults to None
:type shell: str | None, optional
:param require_password_reset: Require password reset on first login, defaults to False
:type require_password_reset: bool, optional
:param user_auth_type: Types of supported user authentication, defaults to None
:type user_auth_type: str | list[str] | None, optional
:param sshpubkey: SSH public key, defaults to None
:type sshpubkey: str | list[str] | None, optional
:param email: email attribute, defaults to None
:type email: str | None, optional
:return: Self.
:rtype: IPAUser
"""
attrs = {
"first": (self.cli.option.VALUE, self.name),
"last": (self.cli.option.VALUE, self.name),
"uid": (self.cli.option.VALUE, uid),
"gidnumber": (self.cli.option.VALUE, gid),
"homedir": (self.cli.option.VALUE, home),
"gecos": (self.cli.option.VALUE, gecos),
"shell": (self.cli.option.VALUE, shell),
"password": (self.cli.option.SWITCH, True) if password is not None else None,
"user-auth-type": (self.cli.option.VALUE, user_auth_type),
"sshpubkey": (self.cli.option.VALUE, sshpubkey),
"email": (self.cli.option.VALUE, email),
}
if not require_password_reset:
attrs["password-expiration"] = (self.cli.option.VALUE, "20380101120000Z")
self._add(attrs, input=password)
return self
def modify(
self,
*,
first: str | None = None,
last: str | None = None,
uid: int | None = None,
gid: int | None = None,
password: str | None = None,
home: str | None = None,
gecos: str | None = None,
shell: str | None = None,
user_auth_type: str | list[str] | None = None,
idp: str | None = None,
idp_user_id: str | None = None,
password_expiration: str | None = None,
sshpubkey: str | list[str] | None = None,
email: str | None = None,
) -> IPAUser:
"""
Modify existing IPA user.
:param first: First name of user.
:type first: str | None, optional
:param last: Last name of user.
:type last: str | None, optional
:param uid: User id, defaults to None
:type uid: int | None, optional
:param gid: Primary group id, defaults to None
:type gid: int | None, optional
:param password: Password, defaults to 'Secret123'
:type password: str | None, optional
:param home: Home directory, defaults to None
:type home: str | None, optional
:param gecos: GECOS, defaults to None
:type gecos: str | None, optional
:param shell: Login shell, defaults to None
:type shell: str | None, optional
:param user_auth_type: Types of supported user authentication, defaults to None
:type user_auth_type: str | list[str] | None, optional
:param idp: Name of external IdP configured in IPA for user.
:type idp: str | None, optional
:param idp_user_id: User ID used to map IPA user to external IdP user.
:type idp_user_id: str | None, optional
:param password_expiration: Date and time stamp for password expiration.
:type password_expiration: str | None, optional
:param sshpubkey: SSH public key, defaults to None
:type sshpubkey: str | list[str] | None, optional
:param email: email attribute, defaults to None
:type email: str | None, optional
:return: Self.
:rtype: IPAUser
"""
attrs = {
"first": (self.cli.option.VALUE, first),
"last": (self.cli.option.VALUE, last),
"uid": (self.cli.option.VALUE, uid),
"gidnumber": (self.cli.option.VALUE, gid),
"homedir": (self.cli.option.VALUE, home),
"gecos": (self.cli.option.VALUE, gecos),
"shell": (self.cli.option.VALUE, shell),
"password": (self.cli.option.SWITCH, True) if password is not None else None,
"user-auth-type": (self.cli.option.VALUE, user_auth_type),
"idp": (self.cli.option.VALUE, idp),
"idp-user-id": (self.cli.option.VALUE, idp_user_id),
"password-expiration": (self.cli.option.VALUE, password_expiration),
"sshpubkey": (self.cli.option.VALUE, sshpubkey),
"email": (self.cli.option.VALUE, email),
}
self._modify(attrs, input=password)
return self
def reset(self, password: str | None = "Secret123") -> IPAUser:
"""
Reset user password.
:param password: Password, defaults to 'Secret123'
:type password: str, optional
:return: Self.
:rtype: IPAUser
"""
pwinput = f"{password}\n{password}"
self.role.host.conn.run(f"ipa passwd {self.name}", input=pwinput)
self.expire("20380101120000Z")
return self
def expire(self, expiration: str | None = "19700101000000Z") -> IPAUser:
"""
Set user password expiration date and time.