summaryrefslogtreecommitdiffstats
path: root/src/tests/intg/test_infopipe.py
blob: f1f6c83f17a5a4fab4c3e5d4d9506df204668132 (plain)
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
#
# Infopipe integration test
#
# Copyright (c) 2017 Red Hat, Inc.
# Author: Lukas Slebodnik <lslebodn@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from __future__ import print_function

import os
import stat
import pwd
import signal
import subprocess
import errno
import time
import ldap
import ldap.modlist
import pytest
import dbus
import shutil

import config
import ds_openldap
import ldap_ent
from util import unindent, get_call_output

LDAP_BASE_DN = "dc=example,dc=com"
INTERACTIVE_TIMEOUT = 4


class DbusDaemon(object):
    def __init__(self):
        self.pid = 0

    def start(self):
        """Start the SSSD process"""
        assert self.pid == 0

        dbus_config_path = config.SYSCONFDIR + "/dbus-1/cwrap-dbus-system.conf"
        dbus_commands = [
            ["dbus-daemon", "--config-file", dbus_config_path,
             "--nosyslog", "--fork"],
            ["dbus-daemon", "--config-file", dbus_config_path, "--fork"],
        ]
        dbus_started = False
        for dbus_command in dbus_commands:
            try:
                if subprocess.call(dbus_command) == 0:
                    dbus_started = True
                    break
                else:
                    print("start failed for %s" % " ".join(dbus_command))
            except OSError as ex:
                if ex.errno == errno.ENOENT:
                    print("%s does not exist" % (dbus_command[0]))
                    pass

        if not dbus_started:
            raise Exception("dbus-daemon start failed")
        dbus_pid_path = config.RUNSTATEDIR + "/dbus/messagebus.pid"
        # wait 10 seconds for pidfile
        wait_time = 10
        for _ in range(wait_time * 10):
            if os.path.isfile(dbus_pid_path):
                break
            time.sleep(.1)

        assert os.path.isfile(dbus_pid_path)
        with open(dbus_pid_path, "r") as pid_file:
            self.pid = int(pid_file.read())

    def stop(self):
        """Stop the SSSD process and remove its state"""

        # stop process only if running
        if self.pid != 0:
            try:
                os.kill(self.pid, signal.SIGTERM)
                while True:
                    try:
                        os.kill(self.pid, signal.SIGCONT)
                    except OSError:
                        break
                    time.sleep(.1)
            except OSError:
                pass

        # clean pid so we can start service one more time
        self.pid = 0

        # dbus-daemon 1.2.24 does not clean pid file after itself
        try:
            os.unlink(config.RUNSTATEDIR + "/dbus/messagebus.pid")
        except OSError as ex:
            if ex.errno != errno.ENOENT:
                raise


@pytest.fixture(scope="module")
def dbus_system_bus(request):
    dbus_daemon = DbusDaemon()
    dbus_daemon.start()

    def cleanup_dbus_process():
        dbus_daemon.stop()
    request.addfinalizer(cleanup_dbus_process)

    return dbus.SystemBus()


@pytest.fixture(scope="module")
def ds_inst(request):
    """LDAP server instance fixture"""
    ds_inst = ds_openldap.DSOpenLDAP(
        config.PREFIX, 10389, LDAP_BASE_DN,
        "cn=admin", "Secret123"
    )

    try:
        ds_inst.setup()
    except Exception:
        ds_inst.teardown()
        raise
    request.addfinalizer(ds_inst.teardown)

    return ds_inst


@pytest.fixture(scope="module")
def ldap_conn(request, ds_inst):
    """LDAP server connection fixture"""
    ldap_conn = ds_inst.bind()
    ldap_conn.ds_inst = ds_inst
    request.addfinalizer(ldap_conn.unbind_s)
    return ldap_conn


def create_ldap_entries(ldap_conn, ent_list=None):
    """Add LDAP entries from ent_list"""
    if ent_list is not None:
        for entry in ent_list:
            ldap_conn.add_s(entry[0], entry[1])


def cleanup_ldap_entries(ldap_conn, ent_list=None):
    """Remove LDAP entries added by create_ldap_entries"""
    if ent_list is None:
        for ou in ("Users", "Groups", "Netgroups", "Services", "Policies"):
            for entry in ldap_conn.search_s(f"ou={ou},"
                                            f"{ldap_conn.ds_inst.base_dn}",
                                            ldap.SCOPE_ONELEVEL,
                                            attrlist=[]):
                ldap_conn.delete_s(entry[0])
    else:
        for entry in ent_list:
            ldap_conn.delete_s(entry[0])


def create_ldap_cleanup(request, ldap_conn, ent_list=None):
    """Add teardown for removing all user/group LDAP entries"""
    request.addfinalizer(lambda: cleanup_ldap_entries(ldap_conn, ent_list))


def create_ldap_fixture(request, ldap_conn, ent_list=None):
    """Add LDAP entries and add teardown for removing them"""
    create_ldap_entries(ldap_conn, ent_list)
    create_ldap_cleanup(request, ldap_conn, ent_list)


SCHEMA_RFC2307 = "rfc2307"
SCHEMA_RFC2307_BIS = "rfc2307bis"


def format_basic_conf(ldap_conn, schema, config):
    """Format a basic SSSD configuration"""
    schema_conf = "ldap_schema         = " + schema + "\n"
    if schema == SCHEMA_RFC2307_BIS:
        schema_conf += "ldap_group_object_class = groupOfNames\n"

    return unindent("""\
        [sssd]
        debug_level         = 0xffff
        domains             = LDAP, app
        services            = nss, ifp
        enable_files_domain = false

        [nss]
        memcache_timeout    = 0

        [ifp]
        debug_level         = 0xffff
        user_attributes = +extraName
        ca_db               = {config.PAM_CERT_DB_PATH}

        [domain/LDAP]
        {schema_conf}
        id_provider         = ldap
        ldap_uri            = {ldap_conn.ds_inst.ldap_url}
        ldap_search_base    = {ldap_conn.ds_inst.base_dn}
        ldap_user_extra_attrs = extraName:uid
        ldap_user_certificate = userCert

        [application/app]
        inherit_from = LDAP
    """).format(**locals())


def format_certificate_conf(ldap_conn, schema, config):
    """Format an SSSD configuration with all caches refreshing in 4 seconds"""
    return \
        format_basic_conf(ldap_conn, schema, config) + \
        unindent("""
            [certmap/LDAP/user1]
            matchrule = <SUBJECT>.*CN = SSSD test cert 0001.*
        """).format(**locals())


def create_conf_file(contents):
    """Create sssd.conf with specified contents"""
    with open(config.CONF_PATH, "w") as conf:
        conf.write(contents)
    os.chmod(config.CONF_PATH, stat.S_IRUSR | stat.S_IWUSR)


def cleanup_conf_file():
    """Remove sssd.conf, if it exists"""
    if os.path.lexists(config.CONF_PATH):
        os.unlink(config.CONF_PATH)


def create_conf_cleanup(request):
    """Add teardown for removing sssd.conf"""
    request.addfinalizer(cleanup_conf_file)


def create_conf_fixture(request, contents):
    """
    Create sssd.conf with specified contents and add teardown for removing it
    """
    create_conf_file(contents)
    create_conf_cleanup(request)


def create_sssd_process():
    """Start the SSSD process"""
    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
        raise Exception("sssd start failed")


def cleanup_sssd_process():
    """Stop the SSSD process and remove its state"""
    try:
        with open(config.PIDFILE_PATH, "r") as pid_file:
            pid = int(pid_file.read())
        os.kill(pid, signal.SIGTERM)
        while True:
            try:
                os.kill(pid, signal.SIGCONT)
            except OSError:
                break
            time.sleep(1)
    except OSError:
        pass
    for path in os.listdir(config.DB_PATH):
        os.unlink(config.DB_PATH + "/" + path)
    for path in os.listdir(config.MCACHE_PATH):
        os.unlink(config.MCACHE_PATH + "/" + path)


def create_sssd_cleanup(request):
    """Add teardown for stopping SSSD and removing its state"""
    request.addfinalizer(cleanup_sssd_process)


def create_sssd_fixture(request):
    """Start SSSD and add teardown for stopping it and removing its state"""
    create_sssd_process()
    create_sssd_cleanup(request)


def backup_ca_db():
    """Create backup file for ca db"""
    src = os.path.dirname(config.PAM_CERT_DB_PATH) + "/SSSD_test_CA.pem"
    dst = os.path.dirname(config.PAM_CERT_DB_PATH) + "/SSSD_test_CA.pem.bp"
    shutil.copyfile(src, dst)


def restore_ca_db():
    """Restore backup file for ca db"""
    src = os.path.dirname(config.PAM_CERT_DB_PATH) + "/SSSD_test_CA.pem.bp"
    dst = os.path.dirname(config.PAM_CERT_DB_PATH) + "/SSSD_test_CA.pem"
    shutil.copyfile(src, dst)
    os.remove(src)


def create_restore_ca_db(request):
    """Add teardown for restoring ca_db"""
    request.addfinalizer(restore_ca_db)


def create_ca_db_fixture(request):
    """
    Create backup for ca_db and add teardown for restoring it
    """
    backup_ca_db()
    create_restore_ca_db(request)


@pytest.fixture
def sanity_rfc2307(request, ldap_conn):
    ent_list = ldap_ent.List(ldap_conn.ds_inst.base_dn)
    ent_list.add_user("user1", 1001, 2001)
    ent_list.add_user("user2", 1002, 2002)
    ent_list.add_user("user3", 1003, 2003)

    ent_list.add_group("group1", 2001)
    ent_list.add_group("group2", 2002)
    ent_list.add_group("group3", 2003)

    ent_list.add_group("empty_group", 2010)

    ent_list.add_group("single_user_group", 2011, ["user1"])
    ent_list.add_group("two_user_group", 2012, ["user1", "user2"])

    create_ldap_fixture(request, ldap_conn, ent_list)

    config.PAM_CERT_DB_PATH = os.environ['PAM_CERT_DB_PATH']
    conf = format_basic_conf(ldap_conn, SCHEMA_RFC2307, config)
    create_conf_fixture(request, conf)
    create_sssd_fixture(request)
    create_ca_db_fixture(request)
    return None


@pytest.fixture
def simple_rfc2307(request, ldap_conn):
    ent_list = ldap_ent.List(ldap_conn.ds_inst.base_dn)
    ent_list.add_user('usr\\\\001', 181818, 181818)
    ent_list.add_group("group1", 181818)
    create_ldap_fixture(request, ldap_conn, ent_list)
    config.PAM_CERT_DB_PATH = os.environ['PAM_CERT_DB_PATH']
    conf = format_basic_conf(ldap_conn, SCHEMA_RFC2307, config)
    create_conf_fixture(request, conf)
    create_sssd_fixture(request)
    create_ca_db_fixture(request)
    return None


@pytest.fixture
def auto_private_groups_rfc2307(request, ldap_conn):
    ent_list = ldap_ent.List(ldap_conn.ds_inst.base_dn)
    ent_list.add_user("user1", 1001, 2001)

    ent_list.add_group("group1", 2001)
    ent_list.add_group("single_user_group", 2011, ["user1"])
    ent_list.add_group("two_user_group", 2012, ["user1"])

    create_ldap_fixture(request, ldap_conn, ent_list)

    config.PAM_CERT_DB_PATH = os.environ['PAM_CERT_DB_PATH']
    conf = \
        format_basic_conf(ldap_conn, SCHEMA_RFC2307, config) + \
        unindent("""
            [domain/LDAP]
            auto_private_groups = True
        """).format(**locals())
    create_conf_fixture(request, conf)
    create_sssd_fixture(request)
    create_ca_db_fixture(request)
    return None


@pytest.fixture
def add_user_with_cert(request, ldap_conn):
    config.PAM_CERT_DB_PATH = os.environ['PAM_CERT_DB_PATH']

    ent_list = ldap_ent.List(ldap_conn.ds_inst.base_dn)
    ent_list.add_user("user1", 1001, 2001)

    create_ldap_fixture(request, ldap_conn, ent_list)

    der_path = os.path.dirname(config.PAM_CERT_DB_PATH)
    der_path += "/SSSD_test_cert_x509_0001.der"
    with open(der_path, 'rb') as f:
        val = f.read()
    dn = "uid=user1,ou=Users," + LDAP_BASE_DN
    '''
    Using 'userCert' instead of 'userCertificate' to hold the user certificate
    because the default OpenLDAP has syntax and matching rules which are not
    used in other LDAP servers.
    '''
    ldap_conn.modify_s(dn, [(ldap.MOD_ADD, 'userCert', val)])

    conf = format_certificate_conf(ldap_conn, SCHEMA_RFC2307_BIS, config)
    create_conf_fixture(request, conf)
    create_sssd_fixture(request)
    create_ca_db_fixture(request)

    return None


def test_ping_raw(dbus_system_bus, ldap_conn, simple_rfc2307):
    # test with disabled introspection
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe',
                                          introspect=False)
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    # test missing parameter
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.Ping()
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'sbus.Error.Errno'
    assert 'Unexpected argument type provided' in ex.get_dbus_message()

    # test wrong parameter type
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.Ping(1)
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'sbus.Error.Errno'
    assert 'Unexpected argument type provided' in ex.get_dbus_message()

    # test wrong parameter value
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.Ping('test')
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'org.freedesktop.DBus.Error.InvalidArgs'
    assert ex.get_dbus_message() == 'Invalid argument'

    # positive test
    ret = sssd_interface.Ping('ping')
    assert ret == "PONG"

    # test case insensitive input
    ret = sssd_interface.Ping('PinG')
    assert ret == "PONG"

    ret = sssd_interface.Ping('PING')
    assert ret == "PONG"


def test_ping_introspection(dbus_system_bus, ldap_conn, simple_rfc2307):
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe')
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    # test missing parameter
    with pytest.raises(TypeError) as exc_info:
        sssd_interface.Ping()
    assert exc_info.errisinstance(TypeError)

    ex = exc_info.value
    assert str(ex) == 'More items found in D-Bus signature than in Python ' \
                      'arguments'

    # test wrong parameter type
    with pytest.raises(TypeError) as exc_info:
        sssd_interface.Ping(1)
    assert exc_info.errisinstance(TypeError)

    ex = exc_info.value
    assert str(ex) == 'Expected a string or unicode object'

    # test wrong parameter value
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.Ping('test')
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'org.freedesktop.DBus.Error.InvalidArgs'
    assert ex.get_dbus_message() == 'Invalid argument'

    # positive test
    ret = sssd_interface.Ping('ping')
    assert ret == "PONG"

    # test case insensitive input
    ret = sssd_interface.Ping('PinG')
    assert ret == "PONG"

    ret = sssd_interface.Ping('PING')
    assert ret == "PONG"


def test_special_characters(dbus_system_bus, ldap_conn, simple_rfc2307):
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe')
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    attributes = ['name', 'uidNumber', 'gidNumber', 'gecos', 'homeDirectory',
                  'loginShell']
    expected = dict(name='usr\\001', uidNumber='181818', gidNumber='181818',
                    gecos='181818', homeDirectory='/home/usr\\\\001',
                    loginShell='/bin/bash')

    user_attrs = sssd_interface.GetUserAttr('usr\\001', attributes)
    assert user_attrs.signature == 'sv'
    assert user_attrs.variant_level == 0

    assert len(attributes) == len(user_attrs)
    assert sorted(attributes) == sorted(user_attrs.keys())

    # check values of attributes
    for attr in user_attrs:
        assert user_attrs[attr].signature == 's'
        assert user_attrs[attr].variant_level == 1
        assert user_attrs[attr][0] == expected[attr]


def test_get_user_attr(dbus_system_bus, ldap_conn, sanity_rfc2307):
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe')
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    # negative test
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.GetUserAttr('non_existent_user', ['name'])
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'sbus.Error.NotFound'
    assert ex.get_dbus_message() == 'No such file or directory'

    # test 0 attributes
    user_attrs = sssd_interface.GetUserAttr('user1', [])

    assert user_attrs.signature == 'sv'
    assert user_attrs.variant_level == 0

    # expect empty sequence; len(user_attrs) == 0
    assert not user_attrs

    # positive test
    attributes = ['name', 'uidNumber', 'gidNumber', 'gecos', 'homeDirectory',
                  'loginShell']
    expected = dict(name='user1', uidNumber='1001', gidNumber='2001',
                    gecos='1001', homeDirectory='/home/user1',
                    loginShell='/bin/bash')
    user_attrs = sssd_interface.GetUserAttr('user1', attributes)

    assert user_attrs.signature == 'sv'
    assert user_attrs.variant_level == 0

    assert len(attributes) == len(user_attrs)
    assert sorted(attributes) == sorted(user_attrs.keys())

    # check values of attributes
    for attr in user_attrs:
        assert user_attrs[attr].signature == 's'
        assert user_attrs[attr].variant_level == 1
        assert user_attrs[attr][0] == expected[attr]


def test_get_user_groups(dbus_system_bus, ldap_conn, sanity_rfc2307):
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe')
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    # negative test
    with pytest.raises(dbus.exceptions.DBusException) as exc_info:
        sssd_interface.GetUserGroups('non_existent_user')
    assert exc_info.errisinstance(dbus.exceptions.DBusException)

    ex = exc_info.value
    assert ex.get_dbus_name() == 'sbus.Error.NotFound'
    assert ex.get_dbus_message() == 'No such file or directory'

    # the same test via nss responder
    with pytest.raises(KeyError):
        pwd.getpwnam("non_existent_user")

    # 0 groups
    res = sssd_interface.GetUserGroups('user3')
    assert res.signature == 's'
    assert res.variant_level == 0

    # expect empty sequence; len(res) == 0
    assert not res

    # single group
    res = sssd_interface.GetUserGroups('user2')
    assert res.signature == 's'
    assert res.variant_level == 0

    assert len(res) == 1
    assert res[0] == 'two_user_group'

    # more groups
    res = sssd_interface.GetUserGroups('user1')
    assert res.signature == 's'
    assert res.variant_level == 0

    assert len(res) == 2
    assert sorted(res) == ['single_user_group', 'two_user_group']


'''
Given auto_private_groups is enabled
When GetUserGroups is called
Then the origPrimaryGroupGidNumber is returned as part of the group memberships
'''


def test_get_user_groups_given_auto_private_groups_enabled(
        dbus_system_bus,
        ldap_conn, auto_private_groups_rfc2307):
    sssd_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                          '/org/freedesktop/sssd/infopipe')
    sssd_interface = dbus.Interface(sssd_obj, 'org.freedesktop.sssd.infopipe')

    res = sssd_interface.GetUserGroups('user1')

    assert sorted(res) == ['group1', 'single_user_group', 'two_user_group']


def get_user_property(dbus_system_bus, username, prop_name):
    users_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                           '/org/freedesktop/sssd/infopipe/Users')

    users_iface = dbus.Interface(users_obj,
                                 "org.freedesktop.sssd.infopipe.Users")

    user_path = users_iface.FindByName(username)
    user_object = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                             user_path)

    prop_iface = dbus.Interface(user_object, 'org.freedesktop.DBus.Properties')
    return prop_iface.Get('org.freedesktop.sssd.infopipe.Users.User',
                          prop_name)


def get_user_by_attr(dbus_system_bus, attribute, filter):
    users_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                           '/org/freedesktop/sssd/infopipe/Users')

    users_iface = dbus.Interface(users_obj,
                                 "org.freedesktop.sssd.infopipe.Users")

    return users_iface.ListByAttr(attribute, filter, 0)


def get_user_by_name(dbus_system_bus, filter):
    users_obj = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                           '/org/freedesktop/sssd/infopipe/Users')

    users_iface = dbus.Interface(users_obj,
                                 "org.freedesktop.sssd.infopipe.Users")

    return users_iface.ListByName(filter, 0)


def test_get_extra_attributes_empty(dbus_system_bus,
                                    ldap_conn,
                                    sanity_rfc2307):
    """
    Make sure the extraAttributes property can be retrieved
    """
    extra_attrs = get_user_property(dbus_system_bus,
                                    'user1',
                                    'extraAttributes')
    assert extra_attrs['extraName'][0] == 'user1'


def test_sssctl_domain_list_app_domain(dbus_system_bus,
                                       ldap_conn,
                                       sanity_rfc2307):
    output = get_call_output(["sssctl", "domain-list"], subprocess.STDOUT)

    assert "Error" not in output
    assert output.find("LDAP") != -1
    assert output.find("app") != -1


def test_update_member_list_and_get_all(dbus_system_bus,
                                        ldap_conn,
                                        sanity_rfc2307):
    '''
    Test that UpdateMemberList() and GetAll() return the correct users that are
    members of a group
    '''
    sssd_obj = dbus_system_bus.get_object(
        'org.freedesktop.sssd.infopipe',
        '/org/freedesktop/sssd/infopipe/Groups')
    groups_iface = dbus.Interface(sssd_obj,
                                  'org.freedesktop.sssd.infopipe.Groups')
    group_id = 2011
    expected_user_result = "/org/freedesktop/sssd/infopipe/Users/LDAP/1001"

    group_path = groups_iface.FindByName('single_user_group')

    group_object = dbus_system_bus.get_object('org.freedesktop.sssd.infopipe',
                                              group_path)
    group_iface = dbus.Interface(group_object,
                                 'org.freedesktop.sssd.infopipe.Groups.Group')

    # update local cache for group
    try:
        group_iface.UpdateMemberList(group_id)
    except dbus.exceptions.DBusException as ex:
        assert False, "Unexpected DBusException raised: " + ex

    # check members of group
    prop_iface = dbus.Interface(group_object,
                                'org.freedesktop.DBus.Properties')
    res = prop_iface.GetAll('org.freedesktop.sssd.infopipe.Groups.Group')
    assert str(res.get("users")[0]) == expected_user_result

    # delete group (there's no other way of removing a user from a group) and
    # wait change to propagate
    ldap_conn.delete("cn=single_user_group,ou=Groups,dc=example,dc=com")
    time.sleep(INTERACTIVE_TIMEOUT)

    # add group back but this time without any member
    ldap_group = ldap_ent.group("dc=example,dc=com", "single_user_group", 2011)
    ldap_conn.add_s(ldap_group[0], ldap_group[1])

    # invalidate cache
    subprocess.call(["sss_cache", "-E"])

    # check that group has no members
    group_iface.UpdateMemberList(group_id)
    prop_interface = dbus.Interface(group_object,
                                    'org.freedesktop.DBus.Properties')
    res = prop_interface.GetAll('org.freedesktop.sssd.infopipe.Groups.Group')
    assert not res.get("users")


def test_find_by_valid_certificate(dbus_system_bus,
                                   ldap_conn,
                                   add_user_with_cert):
    """test_find_by_valid_certificate

    :id: 3f212e6e-00ce-44ac-95d4-59925cb5a14a
    :title: SSSD-TC: Infopipe: Find by valid certificate
    :casecomponent: sssd
    :subsystemteam: sst_idm_sssd
    """
    users_obj = dbus_system_bus.get_object(
        'org.freedesktop.sssd.infopipe',
        '/org/freedesktop/sssd/infopipe/Users')
    users_iface = dbus.Interface(users_obj,
                                 'org.freedesktop.sssd.infopipe.Users')
    cert_path = os.path.dirname(config.PAM_CERT_DB_PATH)

    # Valid certificate with user
    cert_file = cert_path + "/SSSD_test_cert_x509_0001.pem"
    with open(cert_file, "r") as f:
        cert = f.read()
    res = users_iface.FindByValidCertificate(cert)
    assert res == "/org/freedesktop/sssd/infopipe/Users/app/user1_40app"

    # Valid certificate without user
    cert_file = cert_path + "/SSSD_test_cert_x509_0002.pem"
    with open(cert_file, "r") as f:
        cert = f.read()
    try:
        res = users_iface.FindByValidCertificate(cert)
        assert False, "Previous call should raise an exception"
    except dbus.exceptions.DBusException as ex:
        assert str(ex) == "sbus.Error.NotFound: No such file or directory"

    # Valid certificate from another CA
    cert_file = os.environ['ABS_SRCDIR'] + \
        "/../test_ECC_CA/SSSD_test_ECC_cert_key_0001.pem"
    with open(cert_file, "r") as f:
        cert = f.read()
    try:
        res = users_iface.FindByValidCertificate(cert)
        assert False, "Previous call should raise an exception"
    except dbus.exceptions.DBusException as ex:
        assert str(ex) == \
            "org.freedesktop.DBus.Error.IOError: Input/output error"

    # Invalid certificate
    cert = "Invalid cert"
    try:
        res = users_iface.FindByValidCertificate(cert)
        assert False, "Previous call should raise an exception"
    except dbus.exceptions.DBusException as ex:
        error = "org.freedesktop.DBus.Error.IOError: Input/output error"
        assert str(ex) == error

    # Remove certificate db
    cert_db = cert_path + "/SSSD_test_CA.pem"
    os.remove(cert_db)
    cert_file = cert_path + "/SSSD_test_cert_x509_0002.pem"
    with open(cert_file, "r") as f:
        cert = f.read()
    try:
        res = users_iface.FindByValidCertificate(cert)
        assert False, "Previous call should raise an exception"
    except dbus.exceptions.DBusException as ex:
        assert str(ex) == \
            "sbus.Error.NoCA: Certificate authority file not found"


def test_list_by_attr(dbus_system_bus, ldap_conn, sanity_rfc2307):
    users = get_user_by_attr(dbus_system_bus, "extraName", "user2")
    assert len(users) == 2
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1002' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user2_40app' in users

    users = get_user_by_attr(dbus_system_bus, "extraName", "user*")
    assert len(users) == 6
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1001' in users
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1002' in users
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1003' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user1_40app' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user2_40app' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user3_40app' in users

    users = get_user_by_attr(dbus_system_bus, "extraName", "nouser*")
    assert len(users) == 0

    users = get_user_by_attr(dbus_system_bus, "noattr", "*")
    assert len(users) == 0


def test_list_by_name(dbus_system_bus, ldap_conn, sanity_rfc2307):
    users = get_user_by_name(dbus_system_bus, "user2")
    assert len(users) == 2
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1002' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user2_40app' in users

    users = get_user_by_name(dbus_system_bus, "user*")
    assert len(users) == 6
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1001' in users
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1002' in users
    assert '/org/freedesktop/sssd/infopipe/Users/LDAP/1003' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user1_40app' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user2_40app' in users
    assert '/org/freedesktop/sssd/infopipe/Users/app/user3_40app' in users

    users = get_user_by_name(dbus_system_bus, "nouser*")
    assert len(users) == 0