summaryrefslogtreecommitdiff
path: root/tests/test_20_assertion.py
blob: 88be13f6b03bd171ef4ab79421d9a0abdf3b88f6 (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
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
# coding=utf-8
from saml2.argtree import add_path
from saml2.authn_context import pword
from saml2.mdie import to_dict
from saml2 import md, assertion
from saml2.saml import Attribute
from saml2.saml import Issuer
from saml2.saml import NAMEID_FORMAT_ENTITY
from saml2.saml import NAME_FORMAT_URI
from saml2.saml import AttributeValue
from saml2.saml import NameID
from saml2.saml import NAMEID_FORMAT_TRANSIENT
from saml2.assertion import Policy
from saml2.assertion import Assertion
from saml2.assertion import filter_on_attributes
from saml2.assertion import filter_attribute_value_assertions
from saml2.assertion import from_local
from saml2.s_utils import MissingValue
from saml2 import attribute_converter
from saml2.attribute_converter import ac_factory, AttributeConverterNOOP

from pytest import raises

from saml2.extension import mdui
from saml2.extension import idpdisc
from saml2.extension import dri
from saml2.extension import mdattr
from saml2.extension import ui
from saml2 import saml
from saml2 import xmldsig
from saml2 import xmlenc

from pathutils import full_path

ONTS = [saml, mdui, mdattr, dri, ui, idpdisc, md, xmldsig, xmlenc]


def _eq(l1, l2):
    return set(l1) == set(l2)


gn = to_dict(md.RequestedAttribute(name="urn:oid:2.5.4.42",
                                   friendly_name="givenName",
                                   name_format=NAME_FORMAT_URI), ONTS)

sn = to_dict(md.RequestedAttribute(name="urn:oid:2.5.4.4",
                                   friendly_name="surName",
                                   name_format=NAME_FORMAT_URI), ONTS)

mail = to_dict(md.RequestedAttribute(name="urn:oid:0.9.2342.19200300.100.1.3",
                                     friendly_name="mail",
                                     name_format=NAME_FORMAT_URI), ONTS)


# ---------------------------------------------------------------------------


def test_filter_on_attributes_0():
    a = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                          friendly_name="serialNumber"), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]


def test_filter_on_attributes_1():
    a = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                          friendly_name="serialNumber"), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]


def test_filter_on_attributes_2():

    a = to_dict(Attribute(friendly_name="surName",name="urn:oid:2.5.4.4",
                          name_format=NAME_FORMAT_URI), ONTS)
    required = [a]
    ava = {"sn":["kakavas"]}

    ava = filter_on_attributes(ava,required,acs=ac_factory())
    assert list(ava.keys()) == ['sn']
    assert ava["sn"] == ["kakavas"]


def test_filter_on_attributes_without_friendly_name():
    ava = {"eduPersonTargetedID": "test@example.com",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
                  name_format=NAME_FORMAT_URI), ONTS)
    ep_affiliation = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1",
                  name_format=NAME_FORMAT_URI), ONTS)

    restricted_ava = filter_on_attributes(ava, required=[eptid],
                                          optional=[ep_affiliation],
                                          acs=ac_factory())
    assert restricted_ava == {"eduPersonTargetedID": "test@example.com",
                              "eduPersonAffiliation": "test"}


def test_filter_on_attributes_with_missing_required_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    with raises(MissingValue):
        filter_on_attributes(ava, required=[eptid], acs=ac_factory())


def test_filter_on_attributes_with_missing_optional_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    assert filter_on_attributes(ava, optional=[eptid], acs=ac_factory()) == {}


def test_filter_on_attributes_with_missing_name_format():
    ava = {"eduPersonTargetedID": "test@example.com",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(Attribute(friendly_name="eduPersonTargetedID",
                              name="urn:myown:eptid",
                              name_format=''), ONTS)
    ava = filter_on_attributes(ava, optional=[eptid], acs=ac_factory())
    assert ava['eduPersonTargetedID'] == "test@example.com"


# ----------------------------------------------------------------------

def test_lifetime_1():
    conf = {
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:umu.se:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "surName": None,
                "mail": [".*@.*\.umu\.se"],
            }
        }}

    r = Policy(conf)

    assert r is not None

    assert r.get_lifetime("urn:mace:umu.se:saml:roland:sp") == {"minutes": 5}
    assert r.get_lifetime("urn:mace:example.se:saml:sp") == {"minutes": 15}


def test_lifetime_2():
    conf = {
        "default": {
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:umu.se:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "surName": None,
                "mail": [".*@.*\.umu\.se"],
            }
        }}

    r = Policy(conf)
    assert r is not None

    assert r.get_lifetime("urn:mace:umu.se:saml:roland:sp") == {"minutes": 5}
    assert r.get_lifetime("urn:mace:example.se:saml:sp") == {"hours": 1}


def test_ava_filter_1():
    conf = {
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:umu.se:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "surName": None,
                "mail": [".*@.*\.umu\.se"],
            }
        }}

    r = Policy(conf)

    ava = {"givenName": "Derek",
           "surName": "Jeter",
           "mail": "derek@example.com"}

    ava = r.filter(ava, "urn:mace:umu.se:saml:roland:sp", None, None)
    assert _eq(list(ava.keys()), ["givenName", "surName"])

    ava = {"givenName": "Derek",
           "mail": "derek@nyy.umu.se"}

    assert _eq(sorted(list(ava.keys())), ["givenName", "mail"])


def test_ava_filter_2():
    conf = {
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:umu.se:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "sn": None,
                "mail": [".*@.*\.umu\.se"],
            }
        }}

    policy = Policy(conf)

    ava = {"givenName": "Derek", "sn": "Jeter", "mail": "derek@example.com"}

    # mail removed because it doesn't match the regular expression
    _ava = policy.filter(ava, 'urn:mace:umu.se:saml:roland:sp', None, [mail],
                         [gn, sn])

    assert _eq(sorted(list(_ava.keys())), ["givenName", 'sn'])

    ava = {"givenName": "Derek", "sn": "Jeter"}

    # it wasn't there to begin with
    try:
        policy.filter(ava, 'urn:mace:umu.se:saml:roland:sp', None,
                      [gn, sn, mail])
    except MissingValue:
        pass


def test_ava_filter_dont_fail():
    conf = {
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None,  # means all I have
            "fail_on_missing_requested": False
        },
        "urn:mace:umu.se:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "surName": None,
                "mail": [".*@.*\.umu\.se"],
            },
            "fail_on_missing_requested": False
        }}

    policy = Policy(conf)

    ava = {"givenName": "Derek",
           "surName": "Jeter",
           "mail": "derek@example.com"}

    # mail removed because it doesn't match the regular expression
    # So it should fail if the 'fail_on_ ...' flag wasn't set
    _ava = policy.filter(ava, 'urn:mace:umu.se:saml:roland:sp', None,
                         [mail], [gn, sn])

    assert _ava

    ava = {"givenName": "Derek",
           "surName": "Jeter"}

    # it wasn't there to begin with
    _ava = policy.filter(ava, 'urn:mace:umu.se:saml:roland:sp',
                         None, [gn, sn, mail])

    assert _ava


def test_filter_attribute_value_assertions_0(AVA):
    p = Policy({
        "default": {
            "attribute_restrictions": {
                "surName": [".*berg"],
            }
        }
    })

    ava = filter_attribute_value_assertions(AVA[3].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert list(ava.keys()) == ["surName"]
    assert ava["surName"] == ["Hedberg"]


def test_filter_attribute_value_assertions_1(AVA):
    p = Policy({
        "default": {
            "attribute_restrictions": {
                "surName": None,
                "givenName": [".*er.*"],
            }
        }
    })

    ava = filter_attribute_value_assertions(AVA[0].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert _eq(ava.keys(), ["givenName", "surName"])
    assert ava["surName"] == ["Jeter"]
    assert ava["givenName"] == ["Derek"]

    ava = filter_attribute_value_assertions(AVA[1].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert _eq(list(ava.keys()), ["surName"])
    assert ava["surName"] == ["Howard"]


def test_filter_attribute_value_assertions_2(AVA):
    p = Policy({
        "default": {
            "attribute_restrictions": {
                "givenName": ["^R.*"],
            }
        }
    })

    ava = filter_attribute_value_assertions(AVA[0].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert _eq(ava.keys(), [])

    ava = filter_attribute_value_assertions(AVA[1].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert _eq(list(ava.keys()), ["givenName"])
    assert ava["givenName"] == ["Ryan"]

    ava = filter_attribute_value_assertions(AVA[3].copy(),
                                            p.get_attribute_restrictions(""))

    print(ava)
    assert _eq(list(ava.keys()), ["givenName"])
    assert ava["givenName"] == ["Roland"]


# ----------------------------------------------------------------------------


def test_assertion_1(AVA):
    ava = Assertion(AVA[0])

    print(ava)
    print(ava.__dict__)

    policy = Policy({
        "default": {
            "attribute_restrictions": {
                "givenName": ["^R.*"],
            }
        }
    })

    ava = ava.apply_policy("", policy)

    print(ava)
    assert _eq(list(ava.keys()), [])

    ava = Assertion(AVA[1].copy())
    ava = ava.apply_policy("", policy)
    assert _eq(list(ava.keys()), ["givenName"])
    assert ava["givenName"] == ["Ryan"]

    ava = Assertion(AVA[3].copy())
    ava = ava.apply_policy("", policy)
    assert _eq(list(ava.keys()), ["givenName"])
    assert ava["givenName"] == ["Roland"]


def test_assertion_2():
    AVA = {'mail': u'roland.hedberg@adm.umu.se',
           'eduPersonTargetedID': 'http://lingon.ladok.umu'
                                  '.se:8090/idp!http://lingon.ladok.umu'
                                  '.se:8088/sp!95e9ae91dbe62d35198fbbd5e1fb0976',
           'displayName': u'Roland Hedberg',
           'uid': 'http://roland.hedberg.myopenid.com/'}

    ava = Assertion(AVA)

    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })

    ava = ava.apply_policy("", policy)
    acs = ac_factory(full_path("attributemaps"))
    attribute = from_local(acs, ava, policy.get_name_form(""))

    assert len(attribute) == 4
    names = [attr.name for attr in attribute]
    assert _eq(sorted(list(names)), [
        'urn:oid:0.9.2342.19200300.100.1.1',
        'urn:oid:0.9.2342.19200300.100.1.3',
        'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
        'urn:oid:2.16.840.1.113730.3.1.241'])


# ----------------------------------------------------------------------------


def test_filter_values_req_2():
    a1 = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                           friendly_name="serialNumber"), ONTS)
    a2 = to_dict(Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,
                           friendly_name="surName"), ONTS)

    required = [a1, a2]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    with raises(MissingValue):
        filter_on_attributes(ava, required, acs=ac_factory())


def test_filter_values_req_3():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]


def test_filter_values_req_4():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    with raises(MissingValue):
        filter_on_attributes(ava, required, acs=ac_factory())


def test_filter_values_req_5():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]


def test_filter_values_req_6():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["54321"]


def test_filter_values_req_opt_0():
    r = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)
    o = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, [r], [o], acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert _eq(ava["serialNumber"], ["12345", "54321"])


def test_filter_values_req_opt_1():
    r = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)
    o = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345"),
                                   AttributeValue(text="abcd0")]), ONTS)

    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, [r], [o], acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert _eq(ava["serialNumber"], ["12345", "54321"])


def test_filter_values_req_opt_2():
    r = [
        to_dict(
            Attribute(
                friendly_name="surName",
                name="urn:oid:2.5.4.4",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS),
        to_dict(
            Attribute(
                friendly_name="givenName",
                name="urn:oid:2.5.4.42",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS),
        to_dict(
            Attribute(
                friendly_name="mail",
                name="urn:oid:0.9.2342.19200300.100.1.3",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS)]
    o = [
        to_dict(
            Attribute(
                friendly_name="title",
                name="urn:oid:2.5.4.12",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS)]

    ava = {"surname": ["Hedberg"], "givenName": ["Roland"],
           "eduPersonAffiliation": ["staff"], "uid": ["rohe0002"]}

    with raises(MissingValue):
        filter_on_attributes(ava, r, o, acs=ac_factory())


# ---------------------------------------------------------------------------


def test_filter_values_req_opt_4():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    rava = attribute_converter.list_to_local(acs, r)
    oava = attribute_converter.list_to_local(acs, o)

    ava = {"sn": ["Hedberg"], "givenName": ["Roland"],
           "eduPersonAffiliation": ["staff"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_demands(ava, rava, oava)
    print(ava)
    assert _eq(sorted(list(ava.keys())), ['givenName', 'sn'])
    assert ava == {'givenName': ['Roland'], 'sn': ['Hedberg']}


# ---------------------------------------------------------------------------


def test_filter_ava_0():
    policy = Policy(
        {
            "default": {
                "lifetime": {"minutes": 15},
                "attribute_restrictions": None  # means all I have
            },
            "urn:mace:example.com:saml:roland:sp": {
                "lifetime": {"minutes": 5},
            }
        }
    )

    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
           "mail": ["derek@nyy.mlb.com"]}

    # No restrictions apply
    ava = policy.filter(ava, "urn:mace:example.com:saml:roland:sp", [], [])

    assert _eq(sorted(list(ava.keys())), ["givenName", "mail", "surName"])
    assert ava["givenName"] == ["Derek"]
    assert ava["surName"] == ["Jeter"]
    assert ava["mail"] == ["derek@nyy.mlb.com"]


def test_filter_ava_1():
    """ No mail address returned """
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:example.com:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "givenName": None,
                "surName": None,
            }
        }})

    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
           "mail": ["derek@nyy.mlb.com"]}

    # No restrictions apply
    ava = policy.filter(ava, "urn:mace:example.com:saml:roland:sp", [], [])

    assert _eq(sorted(list(ava.keys())), ["givenName", "surName"])
    assert ava["givenName"] == ["Derek"]
    assert ava["surName"] == ["Jeter"]


def test_filter_ava_2():
    """ Only mail returned """
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:example.com:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "mail": None,
            }
        }})

    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
           "mail": ["derek@nyy.mlb.com"]}

    # No restrictions apply
    ava = policy.filter(ava, "urn:mace:example.com:saml:roland:sp", [], [])

    assert _eq(list(ava.keys()), ["mail"])
    assert ava["mail"] == ["derek@nyy.mlb.com"]


def test_filter_ava_3():
    """ Only example.com mail addresses returned """
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:example.com:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "mail": [".*@example\.com$"],
            }
        }})

    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
           "mail": ["derek@nyy.mlb.com", "dj@example.com"]}

    # No restrictions apply
    ava = policy.filter(ava, "urn:mace:example.com:saml:roland:sp", [], [])

    assert _eq(list(ava.keys()), ["mail"])
    assert ava["mail"] == ["dj@example.com"]


def test_filter_ava_4():
    """ Return everything as default policy is used """
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 15},
            "attribute_restrictions": None  # means all I have
        },
        "urn:mace:example.com:saml:roland:sp": {
            "lifetime": {"minutes": 5},
            "attribute_restrictions": {
                "mail": [".*@example\.com$"],
            }
        }})

    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
           "mail": ["derek@nyy.mlb.com", "dj@example.com"]}

    # No restrictions apply
    ava = policy.filter(ava, "urn:mace:example.com:saml:curt:sp", [], [])

    assert _eq(sorted(list(ava.keys())), ['mail', 'givenName', 'surName'])
    assert _eq(ava["mail"], ["derek@nyy.mlb.com", "dj@example.com"])


def test_req_opt():
    req = [
        to_dict(
            md.RequestedAttribute(
                friendly_name="surname", name="urn:oid:2.5.4.4",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
                is_required="true"), ONTS),
        to_dict(
            md.RequestedAttribute(
                friendly_name="givenname",
                name="urn:oid:2.5.4.42",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
                is_required="true"), ONTS),
        to_dict(
            md.RequestedAttribute(
                friendly_name="edupersonaffiliation",
                name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
                is_required="true"), ONTS)]

    opt = [
        to_dict(
            md.RequestedAttribute(
                friendly_name="title",
                name="urn:oid:2.5.4.12",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
                is_required="false"), ONTS)]

    policy = Policy()
    ava = {'givenname': 'Roland', 'sn': 'Hedberg',
           'uid': 'rohe0002', 'edupersonaffiliation': 'staff'}

    sp_entity_id = "urn:mace:example.com:saml:curt:sp"
    fava = policy.filter(ava, sp_entity_id, None, req, opt)
    assert fava


def test_filter_on_wire_representation_1():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    ava = {"sn": ["Hedberg"], "givenname": ["Roland"],
           "edupersonaffiliation": ["staff"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_wire_representation(ava, acs, r, o)
    assert _eq(sorted(list(ava.keys())), ["givenname", "sn"])


def test_filter_on_wire_representation_2():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    ava = {"sn": ["Hedberg"], "givenname": ["Roland"],
           "title": ["Master"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_wire_representation(ava, acs, r, o)
    assert _eq(sorted(list(ava.keys())), ["givenname", "sn", "title"])


length = pword.Length(min="4")
restricted_password = pword.RestrictedPassword(length=length)
authenticator = pword.Authenticator(restricted_password=restricted_password)
authn_method = pword.AuthnMethod(authenticator=authenticator)
ACD = pword.AuthenticationContextDeclaration(authn_method=authn_method)


def test_assertion_with_noop_attribute_conv():
    ava = {"urn:oid:2.5.4.4": "Roland", "urn:oid:2.5.4.42": "Hedberg"}
    ast = Assertion(ava)
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })
    name_id = NameID(format=NAMEID_FORMAT_TRANSIENT, text="foobar")
    issuer = Issuer(text="entityid", format=NAMEID_FORMAT_ENTITY)

    farg = add_path(
        {},
        ['subject', 'subject_confirmation', 'method', saml.SCM_BEARER])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'in_response_to', 'in_response_to'])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'recipient', 'consumer_url'])

    msg = ast.construct(
        "sp_entity_id", [AttributeConverterNOOP(NAME_FORMAT_URI)], policy,
        issuer=issuer, farg=farg, authn_decl=ACD, name_id=name_id,
        authn_auth="authn_authn")

    print(msg)
    for attr in msg.attribute_statement[0].attribute:
        assert attr.name_format == NAME_FORMAT_URI
        assert len(attr.attribute_value) == 1
        if attr.name == "urn:oid:2.5.4.42":
            assert attr.attribute_value[0].text == "Hedberg"
        elif attr.name == "urn:oid:2.5.4.4":
            assert attr.attribute_value[0].text == "Roland"


# THis test doesn't work without a MetadataStore instance
# def test_filter_ava_5():
#    policy = Policy({
#        "default": {
#            "lifetime": {"minutes": 15},
#            #"attribute_restrictions": None  # means all I have
#            "entity_categories": ["swamid", "edugain"]
#        }
#    })
#
#    ava = {"givenName": ["Derek"], "surName": ["Jeter"],
#           "mail": ["derek@nyy.mlb.com", "dj@example.com"]}
#
#    ava = policy.filter(ava, "urn:mace:example.com:saml:curt:sp", None, [], [])
#
#    # using entity_categories means there *always* are restrictions
#    # in this case the only allowed attribute is eduPersonTargetedID
#    # which isn't available in the ava hence zip is returned.
#    assert ava == {}


def test_assertion_with_zero_attributes():
    ava = {}
    ast = Assertion(ava)
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })
    name_id = NameID(format=NAMEID_FORMAT_TRANSIENT, text="foobar")
    issuer = Issuer(text="entityid", format=NAMEID_FORMAT_ENTITY)
    farg = add_path(
        {},
        ['subject', 'subject_confirmation', 'method', saml.SCM_BEARER])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'in_response_to', 'in_response_to'])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'recipient', 'consumer_url'])

    msg = ast.construct(
        "sp_entity_id", [AttributeConverterNOOP(NAME_FORMAT_URI)], policy,
        issuer=issuer, authn_decl=ACD, authn_auth="authn_authn",
        name_id=name_id, farg=farg)

    print(msg)
    assert msg.attribute_statement == []


def test_assertion_with_authn_instant():
    ava = {}
    ast = Assertion(ava)
    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })
    name_id = NameID(format=NAMEID_FORMAT_TRANSIENT, text="foobar")
    issuer = Issuer(text="entityid", format=NAMEID_FORMAT_ENTITY)

    farg = add_path(
        {},
        ['subject', 'subject_confirmation', 'method', saml.SCM_BEARER])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'in_response_to', 'in_response_to'])
    add_path(
        farg['subject']['subject_confirmation'],
        ['subject_confirmation_data', 'recipient', 'consumer_url'])

    msg = ast.construct(
        "sp_entity_id", [AttributeConverterNOOP(NAME_FORMAT_URI)], policy,
        issuer=issuer, authn_decl=ACD, authn_auth="authn_authn",
        authn_instant=1234567890, name_id=name_id, farg=farg)

    print(msg)
    assert msg.authn_statement[0].authn_instant == "2009-02-13T23:31:30Z"


if __name__ == "__main__":
    test_assertion_2()