summaryrefslogtreecommitdiffstats
path: root/base/common/python/pki/profile.py
blob: d553df4468cc88301482ae66009d0d9a1e7d878b (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
#!/usr/bin/python
# 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; version 2 of the License.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2014 Red Hat, Inc.
# All rights reserved.
#
# @author: Abhishek Koneru <akoneru@redhat.com>

from __future__ import absolute_import
import json
import os
import types


import pki
import pki.client as client
import pki.account as account
import pki.encoder as encoder


class ProfileDataInfo(object):
    """Stores information about a profile"""

    json_attribute_names = {
        'profileId': 'profile_id', 'profileName': 'profile_name',
        'profileDescription': 'profile_description', 'profileURL': 'profile_url'
    }

    def __init__(self):
        self.profile_id = None
        self.profile_name = None
        self.profile_description = None
        self.profile_url = None

    def __repr__(self):
        attributes = {
            "ProfileDataInfo": {
                'profile_id': self.profile_id,
                'name': self.profile_name,
                'description': self.profile_description,
                'url': self.profile_url
            }
        }
        return str(attributes)

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        profile_data_info = cls()
        for k, v in attr_list.items():
            if k in ProfileDataInfo.json_attribute_names:
                setattr(profile_data_info,
                        ProfileDataInfo.json_attribute_names[k], v)
            else:
                setattr(profile_data_info, k, v)

        return profile_data_info


class ProfileDataInfoCollection(object):
    """
    Represents a collection of ProfileDataInfo objects.
    Also encapsulates the links for the list of the objects stored.
    """

    def __init__(self):
        self.profile_data_list = []
        self.links = []

    def __iter__(self):
        return iter(self.profile_data_list)

    @classmethod
    def from_json(cls, attr_list):
        ret = cls()
        profile_data_infos = attr_list['entries']
        if not isinstance(profile_data_infos, types.ListType):
            ret.profile_data_list.append(
                ProfileDataInfo.from_json(profile_data_infos))
        else:
            for profile_info in profile_data_infos:
                ret.profile_data_list.append(
                    ProfileDataInfo.from_json(profile_info))

        links = attr_list['Link']
        if not isinstance(links, types.ListType):
            ret.links.append(pki.Link.from_json(links))
        else:
            for link in links:
                ret.links.append(pki.Link.from_json(link))

        return ret


class Descriptor(object):
    """
    This class represents the description of a ProfileAttribute.
    It stores information such as the syntax, constraint and default value of
    a profile attribute.
    """

    json_attribute_names = {
        'Syntax': 'syntax', 'Description': 'description',
        'Constraint': 'constraint', 'DefaultValue': 'default_value'
    }

    def __init__(self, syntax=None, constraint=None, description=None,
                 default_value=None):
        self.syntax = syntax
        self.constraint = constraint
        self.description = description
        self.default_value = default_value

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        descriptor = cls()
        for k, v in attr_list.items():
            if k in Descriptor.json_attribute_names:
                setattr(descriptor,
                        Descriptor.json_attribute_names[k], v)
            else:
                setattr(descriptor, k, v)

        return descriptor


class ProfileAttribute(object):
    """
    Represents a profile attribute of a ProfileInput.
    """
    json_attribute_names = {
        'Value': 'value', 'Descriptor': 'descriptor'
    }

    def __init__(self, name=None, value=None, descriptor=None):
        self.name = name
        self.value = value
        self.descriptor = descriptor

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        attribute = cls()
        attribute.name = attr_list['name']
        if 'Value' in attr_list:
            attribute.value = attr_list['Value']
        if 'Descriptor' in attr_list:
            attribute.descriptor = Descriptor.from_json(attr_list['Descriptor'])

        return attribute


class ProfileInput(object):
    """
    This class encapsulates all the attributes of a profile to generate a
    specific property of a certificate.
    Ex. Subject name, Requestor Information etc.
    """

    json_attribute_names = {
        'id': 'profile_input_id', 'ClassID': 'class_id', 'Name': 'name',
        'Text': 'text', 'Attribute': 'attributes',
        'ConfigAttribute': 'config_attributes'
    }

    def __init__(self, profile_input_id=None, class_id=None, name=None,
                 text=None, attributes=None, config_attributes=None):

        self.profile_input_id = profile_input_id
        self.class_id = class_id
        self.name = name
        self.text = text
        if attributes is None:
            self.attributes = []
        else:
            self.attributes = attributes
        if config_attributes is None:
            self.config_attributes = []
        else:
            self.config_attributes = config_attributes

    def add_attribute(self, profile_attribute):
        """
        Add a ProfileAttribute object to the attributes list.
        """
        if not isinstance(profile_attribute, ProfileAttribute):
            raise ValueError("Object passed is not a ProfileAttribute.")
        self.attributes.append(profile_attribute)

    def remove_attribute(self, profile_attribute_name):
        """
        Remove a ProfileAttribute object with the given name from the attributes
        list.
        """
        for attr in self.attributes:
            if attr.name == profile_attribute_name:
                self.attributes.remove(attr)
                break

    def get_attribute(self, profile_attribute_name):
        """
        Returns a ProfileAttribute object for the given name.
        None, if no match.
        """
        for attr in self.attributes:
            if attr.name == profile_attribute_name:
                return attr

        return None

    def add_config_attribute(self, profile_attribute):
        """
        Add a ProfileAttribute object to the config_attributes list.
        """
        if not isinstance(profile_attribute, ProfileAttribute):
            raise ValueError("Object passed is not a ProfileAttribute.")
        self.config_attributes.append(profile_attribute)

    def remove_config_attribute(self, config_attribute_name):
        """
        Remove a ProfileAttribute object with the given name from the
        config_attributes list.
        """
        for attr in self.config_attributes:
            if attr.name == config_attribute_name:
                self.config_attributes.remove(attr)
                break

    def get_config_attribute(self, config_attribute_name):
        """
        Returns a ProfileAttribute object with the given name.
        None, if there is no match in the config_attributes list.
        """
        for attr in self.config_attributes:
            if attr.name == config_attribute_name:
                return attr

        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None
        profile_input = cls()

        for k, v in attr_list.items():
            if k not in ['Attribute', 'ConfigAttribute']:
                if k in ProfileInput.json_attribute_names:
                    setattr(profile_input,
                            ProfileInput.json_attribute_names[k], v)
                else:
                    setattr(profile_input, k, v)

        attributes = attr_list['Attribute']
        if not isinstance(attributes, types.ListType):
            profile_input.attributes.append(
                ProfileAttribute.from_json(attributes))
        else:
            for profile_info in attributes:
                profile_input.attributes.append(
                    ProfileAttribute.from_json(profile_info))

        config_attributes = attr_list['ConfigAttribute']
        if not isinstance(config_attributes, types.ListType):
            profile_input.config_attributes.append(
                ProfileAttribute.from_json(config_attributes))
        else:
            for config_attribute in config_attributes:
                profile_input.config_attributes.append(
                    ProfileAttribute.from_json(config_attribute))

        return profile_input


class ProfileOutput(object):
    """
    This class defines the output of a certificate enrollment request
    using a profile.
    """

    json_attribute_names = {
        'id': 'profile_output_id', 'classId': 'class_id'
    }

    def __init__(self, profile_output_id=None, name=None, text=None,
                 class_id=None, attributes=None):
        self.profile_output_id = profile_output_id
        self.name = name
        self.text = text
        self.class_id = class_id
        if attributes is None:
            self.attributes = []
        else:
            self.attributes = attributes

    def add_attribute(self, profile_attribute):
        """
        Add a ProfileAttribute object to the attributes list.
        """
        if not isinstance(profile_attribute, ProfileAttribute):
            raise ValueError("Object passed is not a ProfileAttribute.")
        self.attributes.append(profile_attribute)

    def remove_attribute(self, profile_attribute_name):
        """
        Remove a ProfileAttribute object with the given name from the attributes
        list.
        """
        for attr in self.attributes:
            if attr.name == profile_attribute_name:
                self.attributes.remove(attr)
                break

    def get_attribute(self, profile_attribute_name):
        """
        Returns a ProfileAttribute object for the given name.
        None, if no match.
        """
        for attr in self.attributes:
            if attr.name == profile_attribute_name:
                return attr

        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        profile_output = cls()
        for k, v in attr_list.items():
            if k not in ['attributes']:
                if k in ProfileOutput.json_attribute_names:
                    setattr(profile_output,
                            ProfileOutput.json_attribute_names[k], v)
                else:
                    setattr(profile_output, k, v)

        attributes = attr_list['attributes']
        if not isinstance(attributes, types.ListType):
            profile_output.attributes.append(
                ProfileAttribute.from_json(attributes))
        else:
            for profile_info in attributes:
                profile_output.attributes.append(
                    ProfileAttribute.from_json(profile_info))
        return profile_output


class ProfileParameter(object):
    def __init__(self, name=None, value=None):
        self.name = name
        self.value = value

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        param = cls()
        for attr in attr_list:
            setattr(param, attr, attr_list[attr])
        return param


class PolicyDefault(object):
    """
    An object of this class contains information of the default usage of a
    specific ProfileInput.
    """

    json_attribute_names = {
        'id': 'name', 'classId': 'class_id',
        'policyAttribute': 'policy_attributes', 'params': 'policy_params'
    }

    def __init__(self, name=None, class_id=None, description=None,
                 policy_attributes=None, policy_params=None):
        self.name = name
        self.class_id = class_id
        self.description = description
        if policy_attributes is None:
            self.policy_attributes = []
        else:
            self.policy_attributes = policy_attributes
        if policy_params is None:
            self.policy_params = []
        else:
            self.policy_params = policy_params

    def add_attribute(self, policy_attribute):
        """
        Add a policy attribute to the attribute list.
        @param policy_attribute - A ProfileAttribute object
        """
        if not isinstance(policy_attribute, ProfileAttribute):
            raise ValueError("Object passed is not a ProfileAttribute.")
        self.policy_attributes.append(policy_attribute)

    def remove_attribute(self, policy_attribute_name):
        """
        Remove a policy attribute with the given name from the attributes list.
        """
        for attr in self.policy_attributes:
            if attr.name == policy_attribute_name:
                self.policy_attributes.remove(attr)
                break

    def get_attribute(self, policy_attribute_name):
        """
        Fetch the policy attribute with the given name from the attributes list.
        """
        for attr in self.policy_attributes:
            if attr.name == policy_attribute_name:
                return attr

        return None

    def add_parameter(self, policy_parameter):
        """
        Add a profile parameter to the parameters list.
        @param policy_parameter - A ProfileParameter object.
        """
        if not isinstance(policy_parameter, ProfileParameter):
            raise ValueError("Object passed is not a ProfileParameter.")
        self.policy_params.append(policy_parameter)

    def remove_parameter(self, profile_parameter_name):
        """
        Remove a profile parameter with the given name from the parameters list.
        """
        for param in self.policy_params:
            if param.name == profile_parameter_name:
                self.policy_params.remove(param)
                break

    def get_parameter(self, profile_parameter_name):
        """
        Fetch a profile parameter with the given name from the parameters list.
        """
        for param in self.policy_params:
            if param.name == profile_parameter_name:
                return param

        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        policy_def = cls()
        for k, v in attr_list.items():
            if k not in ['policyAttribute', 'params']:
                if k in PolicyDefault.json_attribute_names:
                    setattr(policy_def,
                            PolicyDefault.json_attribute_names[k], v)
                else:
                    setattr(policy_def, k, v)

        if 'policyAttribute' in attr_list:
            attributes = attr_list['policyAttribute']
            if not isinstance(attributes, types.ListType):
                policy_def.policy_attributes.append(
                    ProfileAttribute.from_json(attributes))
            else:
                for attr in attributes:
                    policy_def.policy_attributes.append(
                        ProfileAttribute.from_json(attr))

        if 'params' in attr_list:
            params = attr_list['params']
            if not isinstance(params, types.ListType):
                policy_def.policy_params.append(
                    ProfileParameter.from_json(params))
            else:
                for param in params:
                    policy_def.policy_params.append(
                        ProfileParameter.from_json(param))

        return policy_def


class PolicyConstraintValue(object):
    """
    Represents a PolicyConstraintValue
    """
    def __init__(self, name=None, value=None, descriptor=None):
        self.name = name
        self.value = value
        self.descriptor = descriptor

    @property
    def name(self):
        return getattr(self, 'id')

    @name.setter
    def name(self, value):
        setattr(self, 'id', value)

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        ret = cls()
        ret.name = attr_list['id']
        ret.value = attr_list['value']
        if 'descriptor' in attr_list:
            ret.descriptor = Descriptor.from_json(attr_list['descriptor'])

        return ret


class PolicyConstraint(object):
    """
    An object of this class contains the policy constraints applied to a
    ProfileInput used by a certificate enrollment request.
    """

    json_attribute_names = {
        'id': 'name', 'classId': 'class_id',
        'constraint': 'policy_constraint_values'
    }

    def __init__(self, name=None, description=None, class_id=None,
                 policy_constraint_values=None):
        self.name = name
        self.description = description
        self.class_id = class_id
        if policy_constraint_values is None:
            self.policy_constraint_values = []
        else:
            self.policy_constraint_values = policy_constraint_values

    def add_constraint_value(self, policy_constraint_value):
        """
        Add a PolicyConstraintValue to the policy_constraint_values list.
        """
        if not isinstance(policy_constraint_value, PolicyConstraintValue):
            raise ValueError("Object passed not of type PolicyConstraintValue")
        self.policy_constraint_values.append(policy_constraint_value)

    def remove_constraint_value(self, policy_constraint_value_name):
        """
        Removes a PolicyConstraintValue with the given name form the
        policy_constraint_values list.
        """
        for attr in self.policy_constraint_values:
            if attr.name == policy_constraint_value_name:
                self.policy_constraint_values.remove(attr)
                break

    def get_constraint_value(self, policy_constraint_value_name):
        """
        Returns a PolicyConstraintValue object with the given name.
        None, if there is no match.
        """
        for constraint in self.policy_constraint_values:
            if constraint.name == policy_constraint_value_name:
                return constraint

        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        policy_constraint = cls()
        for k, v in attr_list.items():
            if k not in ['constraint']:
                if k in PolicyConstraint.json_attribute_names:
                    setattr(policy_constraint,
                            PolicyConstraint.json_attribute_names[k], v)
                else:
                    setattr(policy_constraint, k, v)

        if 'constraint' in attr_list:
            constraints = attr_list['constraint']
            if not isinstance(constraints, types.ListType):
                policy_constraint.add_constraint_value(
                    PolicyConstraintValue.from_json(constraints))
            else:
                for constraint in constraints:
                    policy_constraint.add_constraint_value(
                        PolicyConstraintValue.from_json(constraint))

        return policy_constraint


class ProfilePolicy(object):
    """
    This class represents the policy a profile adheres to.
    An object of this class stores the default values for profile and the
    constraints present on the values of the attributes of the profile submitted
    for an enrollment request.
    """

    json_attribute_names = {
        'id': 'policy_id', 'def': 'policy_default',
        'constraint': 'policy_constraint'
    }

    def __init__(self, policy_id=None, policy_default=None,
                 policy_constraint=None):
        self.policy_id = policy_id
        self.policy_default = policy_default
        self.policy_constraint = policy_constraint

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None
        policy = cls()

        policy.policy_id = attr_list['id']
        if 'def' in attr_list:
            policy.policy_default = PolicyDefault.from_json(attr_list['def'])
        if 'constraint' in attr_list:
            policy.policy_constraint = \
                PolicyConstraint.from_json(attr_list['constraint'])

        return policy


class ProfilePolicySet(object):
    """
    Stores a list of ProfilePolicy objects.
    """

    def __init__(self):
        self.policies = []

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        policy_set = cls()

        policies = attr_list['policies']
        if not isinstance(policies, types.ListType):
            policy_set.policies.append(ProfilePolicy.from_json(policies))
        else:
            for policy in policies:
                policy_set.policies.append(ProfilePolicy.from_json(policy))

        return policy_set


class PolicySet(object):
    """
    An object of this class contains a name value pair of the
    policy name and the ProfilePolicy object.
    """

    json_attribute_names = {
        'id': 'name', 'value': 'policy_list'
    }

    def __init__(self, name=None, policy_list=None):
        self.name = name
        if policy_list is None:
            self.policy_list = []
        else:
            self.policy_list = policy_list

    def add_policy(self, profile_policy):
        """
        Add a ProfilePolicy object to the policy_list
        """
        if not isinstance(profile_policy, ProfilePolicy):
            raise ValueError("Object passed is not a ProfilePolicy.")
        self.policy_list.append(profile_policy)

    def remove_policy(self, policy_id):
        """
        Removes a ProfilePolicy with the given ID from the PolicySet.
        """
        for policy in self.policy_list:
            if policy.policy_id == policy_id:
                self.policy_list.remove(policy)
                break

    def get_policy(self, policy_id):
        """
        Returns a ProfilePolicy object with the given profile id.
        """
        for policy in self.policy_list:
            if policy.policy_id == policy_id:
                return policy
        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        policy_set = cls()

        policy_set.name = attr_list['id']
        policies = attr_list['value']
        if not isinstance(policies, types.ListType):
            policy_set.policy_list.append(ProfilePolicy.from_json(policies))
        else:
            for policy in policies:
                policy_set.policy_list.append(ProfilePolicy.from_json(policy))

        return policy_set


class PolicySetList(object):
    """
    An object of this class stores a list of ProfileSet objects.
    """

    def __init__(self, policy_sets=None):
        if policy_sets is None:
            self.policy_sets = []
        else:
            self.policy_sets = policy_sets

    def __iter__(self):
        return iter(self.policy_sets)

    @property
    def policy_sets(self):
        return getattr(self, 'PolicySet')

    @policy_sets.setter
    def policy_sets(self, value):
        setattr(self, 'PolicySet', value)

    def add_policy_set(self, policy_set):
        """
        Add a PolicySet object to the policy_sets list.
        """
        if not isinstance(policy_set, PolicySet):
            raise ValueError("Object passed is not a PolicySet.")
        self.policy_sets.append(policy_set)

    def remove_policy_set(self, policy_set_name):
        """
        Remove a PolicySet object with the given name from the policy_sets list.
        """
        for policy_set in self.policy_sets:
            if policy_set.name == policy_set_name:
                self.policy_sets.remove(policy_set)
                break

    def get_policy_set(self, policy_set_name):
        """
        Fetch the PolicySet object for the given name.
        Returns None, if not found.
        """
        for policy_set in self.policy_sets:
            if policy_set.name == policy_set_name:
                return policy_set
        return None

    @classmethod
    def from_json(cls, attr_list):
        if attr_list is None:
            return None

        policy_set_list = cls()
        policy_sets = attr_list['PolicySet']
        if not isinstance(policy_sets, types.ListType):
            policy_set_list.policy_sets.append(PolicySet.from_json(policy_sets))
        else:
            for policy_set in policy_sets:
                policy_set_list.policy_sets.append(
                    PolicySet.from_json(policy_set))

        return policy_set_list


class Profile(object):
    """
    This class represents an enrollment profile.
    """

    json_attribute_names = {
        'id': 'profile_id', 'classId': 'class_id', 'enabledBy': 'enabled_by',
        'authenticatorId': 'authenticator_id', 'authzAcl': 'authorization_acl',
        'xmlOutput': 'xml_output', 'Input': 'inputs', 'Output': 'outputs',
        'PolicySets': 'policy_set_list'
    }

    def __init__(self, profile_id=None, class_id=None, name=None,
                 description=None, enabled=None, visible=None, enabled_by=None,
                 authenticator_id=None, authorization_acl=None, renewal=None,
                 xml_output=None, inputs=None, outputs=None,
                 policy_set_list=None, link=None):

        self.profile_id = profile_id
        self.name = name
        self.class_id = class_id
        self.description = description
        self.enabled = enabled
        self.visible = visible
        self.enabled_by = enabled_by
        self.authenticator_id = authenticator_id
        self.authorization_acl = authorization_acl
        self.renewal = renewal
        self.xml_output = xml_output
        if inputs is None:
            self.inputs = []
        else:
            self.inputs = inputs
        if outputs is None:
            self.outputs = []
        else:
            self.outputs = outputs
        if policy_set_list is None:
            self.policy_set_list = PolicySetList()
        else:
            self.policy_set_list = policy_set_list
        self.link = link

    def add_input(self, profile_input):
        """
        Add a ProfileInput object to the inputs list of the Profile.
        """
        if not isinstance(profile_input, ProfileInput):
            raise ValueError("Object passed is not a PolicyInput.")
        if profile_input is None:
            raise ValueError("No ProfileInput object provided.")
        self.inputs.append(profile_input)

    def remove_input(self, profile_input_id):
        """
        Remove a ProfileInput from the inputs list of the Profile.
        """
        for profile_input in self.inputs:
            if profile_input_id == profile_input.profile_input_id:
                self.inputs.remove(profile_input)
                break

    def get_input(self, profile_input_id):
        """
        Fetches a ProfileInput with the given ProfileInput id.
        Returns None, if there is no matching input.
        """
        for profile_input in self.inputs:
            if profile_input_id == profile_input.profile_input_id:
                return profile_input
        return None

    def add_output(self, profile_output):
        """
        Add a ProfileOutput object to the outputs list of the Profile.
        """
        if not isinstance(profile_output, ProfileOutput):
            raise ValueError("Object passed is not a PolicyOutput.")
        if profile_output is None:
            raise ValueError("No ProfileOutput object provided.")
        self.outputs.append(profile_output)

    def remove_output(self, profile_output_id):
        """
        Remove a ProfileOutput from the outputs list of the Profile.
        """
        for profile_output in self.outputs:
            if profile_output_id == profile_output.profile_output_id:
                self.inputs.remove(profile_output)

    def get_output(self, profile_output_id):
        """
        Fetches a ProfileOutput with the given ProfileOutput id.
        Returns None, if there is no matching output.
        """
        for profile_input in self.inputs:
            if profile_output_id == profile_input.profile_input_id:
                return profile_input
        return None

    def add_policy_set(self, policy_set):
        """
        Add a PolicySet object to the policy_sets list of the Profile.
        """
        if policy_set is None:
            raise ValueError("No PolicySet object provided.")
        self.policy_set_list.add_policy_set(policy_set)

    def remove_policy_set(self, policy_set_name):
        """
        Remove a PolicySet from the policy_sets list of the Profile.
        """
        self.policy_set_list.remove_policy_set(policy_set_name)

    def get_policy_set(self, policy_set_name):
        """
        Fetches a ProfileInput with the given ProfileInput id.
        Returns None, if there is no matching input.
        """
        return self.policy_set_list.get_policy_set(policy_set_name)

    @classmethod
    def from_json(cls, attr_list):
        profile_data = cls()
        for k, v in attr_list.items():
            if k not in ['Input', 'Output', 'PolicySets']:
                if k in Profile.json_attribute_names:
                    setattr(profile_data,
                            Profile.json_attribute_names[k], v)
                else:
                    setattr(profile_data, k, v)

        profile_inputs = attr_list['Input']
        if not isinstance(profile_inputs, types.ListType):
            profile_data.inputs.append(ProfileInput.from_json(profile_inputs))
        else:
            for profile_input in profile_inputs:
                profile_data.inputs.append(
                    ProfileInput.from_json(profile_input))

        profile_outputs = attr_list['Output']
        if not isinstance(profile_outputs, types.ListType):
            profile_data.outputs.append(
                ProfileOutput.from_json(profile_outputs))
        else:
            for profile_output in profile_outputs:
                profile_data.outputs.append(
                    ProfileOutput.from_json(profile_output))

        profile_data.policy_set_list = \
            PolicySetList.from_json(attr_list['PolicySets'])

        profile_data.link = pki.Link.from_json(attr_list['link'])

        return profile_data

    def __repr__(self):
        attributes = {
            "ProfileData": {
                'profile_id': self.profile_id,
                'name': self.name,
                'description': self.description,
                'status': ('enabled' if self.enabled else 'disabled'),
                'visible': self.visible
            }
        }
        return str(attributes)

    @staticmethod
    def get_profile_data_from_file(path_to_file):
        """
        Reads the file for the serialized Profile object.
        Currently supports only data format in json.
        """
        if path_to_file is None:
            raise ValueError("File path must be specified.")
        with open(path_to_file) as input_file:
            data = input_file.read()
            if data is not None:
                return Profile.from_json(json.loads(data))
        return None


class ProfileClient(object):
    """
    This class consists of methods for accessing the ProfileResource.
    """

    def __init__(self, connection):
        self.connection = connection
        self.headers = {'Content-type': 'application/json',
                        'Accept': 'application/json'}
        self.profiles_url = '/rest/profiles'
        self.account_client = account.AccountClient(connection)

    def _get(self, url, query_params=None, payload=None):
        self.account_client.login()
        r = self.connection.get(url, self.headers, query_params, payload)
        self.account_client.logout()
        return r

    def _post(self, url, payload=None, query_params=None):
        self.account_client.login()
        r = self.connection.post(url, payload, self.headers, query_params)
        self.account_client.logout()
        return r

    def _put(self, url, payload=None):
        self.account_client.login()
        r = self.connection.put(url, payload, self.headers)
        self.account_client.logout()
        return r

    def _delete(self, url):
        self.account_client.login()
        r = self.connection.delete(url, self.headers)
        self.account_client.logout()
        return r

    @pki.handle_exceptions()
    def list_profiles(self, start=None, size=None):
        """
        Fetches the list of profiles.
        The start and size arguments provide pagination support.
        Returns a ProfileDataInfoCollection object.
        """
        query_params = {
            'start': start,
            'size': size
        }
        r = self._get(self.profiles_url, query_params)
        return ProfileDataInfoCollection.from_json(r.json())

    @pki.handle_exceptions()
    def get_profile(self, profile_id):
        """
        Fetches information for the profile for the given profile id.
        Returns a ProfileData object.
        """
        if profile_id is None:
            raise ValueError("Profile ID must be specified.")
        url = self.profiles_url + '/' + str(profile_id)
        r = self._get(url)
        return Profile.from_json(r.json())

    def _modify_profile_state(self, profile_id, action):
        """
        Internal method used to modify the profile state.
        """
        if profile_id is None:
            raise ValueError("Profile ID must be specified.")
        if action is None:
            raise ValueError("A valid action(enable/disable) must be "
                             "specified.")

        url = self.profiles_url + '/' + str(profile_id)
        params = {'action': action}
        self._post(url, query_params=params)

    @pki.handle_exceptions()
    def enable_profile(self, profile_id):
        """
        Enables a profile.
        """
        return self._modify_profile_state(profile_id, 'enable')

    @pki.handle_exceptions()
    def disable_profile(self, profile_id):
        """
        Disables a profile.
        """
        return self._modify_profile_state(profile_id, 'disable')

    def _send_profile_create(self, profile_data):

        if profile_data is None:
            raise ValueError("No ProfileData specified")

        profile_object = json.dumps(profile_data, cls=encoder.CustomTypeEncoder,
                                    sort_keys=True)

        r = self._post(self.profiles_url, profile_object)

        return Profile.from_json(r.json())

    def _send_profile_modify(self, profile_data):
        if profile_data is None:
            raise ValueError("No ProfileData specified")
        if profile_data.profile_id is None:
            raise ValueError("Profile Id is not specified.")
        profile_object = json.dumps(profile_data, cls=encoder.CustomTypeEncoder,
                                    sort_keys=True)
        url = self.profiles_url + '/' + str(profile_data.profile_id)
        r = self._put(url, profile_object)

        return Profile.from_json(r.json())

    @pki.handle_exceptions()
    def create_profile(self, profile_data):
        """
        Create a new profile for the given Profile object.
        """
        return self._send_profile_create(profile_data)

    @pki.handle_exceptions()
    def modify_profile(self, profile_data):
        """
        Modify an existing profile with the given Profile object.
        """
        return self._send_profile_modify(profile_data)

    def create_profile_from_file(self, path_to_file):
        """
        Reads the file for the serialized Profile object.
        Performs the profile create operation.
        Currently supports only data format in json.
        """
        profile_data = Profile.get_profile_data_from_file(path_to_file)
        return self._send_profile_create(profile_data)

    def modify_profile_from_file(self, path_to_file):
        """
        Reads the file for the serialized Profile object.
        Performs the profile modify operation.
        Currently supports only data format in json.
        """
        profile_data = Profile.get_profile_data_from_file(path_to_file)
        return self._send_profile_modify(profile_data)

    @pki.handle_exceptions()
    def delete_profile(self, profile_id):
        """
        Delete a profile with the given Profile Id.
        """
        if profile_id is None:
            raise ValueError("Profile Id must be specified.")

        url = self.profiles_url + '/' + str(profile_id)
        r = self._delete(url)
        return r

    encoder.NOTYPES['Profile'] = Profile
    encoder.NOTYPES['ProfileInput'] = ProfileInput
    encoder.NOTYPES['ProfileOutput'] = ProfileOutput
    encoder.NOTYPES['ProfileAttribute'] = ProfileAttribute
    encoder.NOTYPES['Descriptor'] = Descriptor
    encoder.NOTYPES['PolicySetList'] = PolicySetList
    encoder.NOTYPES['PolicySet'] = PolicySet
    encoder.NOTYPES['ProfilePolicy'] = ProfilePolicy
    encoder.NOTYPES['PolicyDefault'] = PolicyDefault
    encoder.NOTYPES['PolicyConstraint'] = PolicyConstraint
    encoder.NOTYPES['ProfileParameter'] = ProfileParameter
    encoder.NOTYPES['PolicyConstraintValue'] = PolicyConstraintValue
    encoder.NOTYPES['Link'] = pki.Link


def main():
    # Initialize a PKIConnection object for the CA
    connection = client.PKIConnection('https', 'localhost', '8443', 'ca')

    # The pem file used for authentication. Created from a p12 file using the
    # command -
    # openssl pkcs12 -in <p12_file_path> -out /tmp/auth.pem -nodes
    connection.set_authentication_cert("/tmp/auth.pem")

    #Initialize the ProfileClient class
    profile_client = ProfileClient(connection)

    # Folder to store the files generated during test
    file_path = '/tmp/profile_client_test/'
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    #Fetching a list of profiles
    profile_data_infos = profile_client.list_profiles()
    print 'List of profiles:'
    print '-----------------'
    for profile_data_info in profile_data_infos:
        print '  Profile ID: ' + profile_data_info.profile_id
        print '  Profile Name: ' + profile_data_info.profile_name
        print '  Profile Description: ' + profile_data_info.profile_description
    print

    # Get a specific profile
    profile_data = profile_client.get_profile('caUserCert')
    print 'Profile Data for caUserCert:'
    print '----------------------------'
    print '  Profile ID: ' + profile_data.profile_id
    print '  Profile Name: ' + profile_data.name
    print '  Profile Description: ' + profile_data.description
    print '  Is profile enabled? ' + str(profile_data.enabled)
    print '  Is profile visible? ' + str(profile_data.visible)
    print

    # Disabling a profile
    print 'Disabling a profile:'
    print '--------------------'
    profile_client.disable_profile('caUserCert')
    profile = profile_client.get_profile('caUserCert')
    print '  Profile ID: ' + profile.profile_id
    print '  Is profile enabled? ' + str(profile.enabled)
    print

    # Disabling a profile
    print 'Enabling a profile:'
    print '-------------------'
    profile_client.enable_profile('caUserCert')
    profile = profile_client.get_profile('caUserCert')
    print '  Profile ID: ' + profile_data.profile_id
    print '  Is profile enabled? ' + str(profile.enabled)
    print
    #profile_client.delete_profile('MySampleProfile')
    # Create a new sample profile
    print 'Creating a new profile:'
    print '-----------------------'

    profile_data = Profile(name="My Sample User Cert Enrollment",
                           profile_id="MySampleProfile",
                           class_id="caEnrollImpl",
                           description="Example User Cert Enroll Impl",
                           enabled_by='admin', enabled=False, visible=False,
                           renewal=False, xml_output=False,
                           authorization_acl="")

    # Adding a profile input
    profile_input = ProfileInput("i1", "subjectNameInputImpl")
    profile_input.add_attribute(ProfileAttribute("sn_uid"))
    profile_input.add_attribute(ProfileAttribute("sn_e"))
    profile_input.add_attribute(ProfileAttribute("sn_c"))
    profile_input.add_attribute(ProfileAttribute("sn_ou"))
    profile_input.add_attribute(ProfileAttribute("sn_ou1"))
    profile_input.add_attribute(ProfileAttribute("sn_ou2"))
    profile_input.add_attribute(ProfileAttribute("sn_ou3"))
    profile_input.add_attribute(ProfileAttribute("sn_cn"))
    profile_input.add_attribute(ProfileAttribute("sn_o"))

    profile_data.add_input(profile_input)

    # Adding a profile output
    profile_output = ProfileOutput("o1", name="Certificate Output",
                                   class_id="certOutputImpl")
    profile_output.add_attribute(ProfileAttribute("pretty_cert"))
    profile_output.add_attribute(ProfileAttribute("b64_cert"))

    profile_data.add_output(profile_output)

    # Create a Policy set with a list of profile policies
    policy_list = []

    # Creating profile policy
    policy_default = PolicyDefault("Subject Name Default",
                                   "userSubjectNameDefaultImpl",
                                   "This default populates a User-Supplied "
                                   "Certificate Subject Name to the request.")

    attr_descriptor = Descriptor(syntax="string", description="Subject Name")
    policy_attribute = ProfileAttribute("name", descriptor=attr_descriptor)
    policy_default.add_attribute(policy_attribute)

    policy_constraint = PolicyConstraint("Subject Name Constraint",
                                         "This constraint accepts the subject "
                                         "name that matches UID=.*",
                                         "subjectNameConstraintImpl")
    constraint_descriptor = Descriptor(syntax="string",
                                       description="Subject Name Pattern")
    policy_constraint_value = PolicyConstraintValue("pattern",
                                                    "UID=.*",
                                                    constraint_descriptor)
    policy_constraint.add_constraint_value(policy_constraint_value)

    policy_list.append(ProfilePolicy("1", policy_default, policy_constraint))

    # Creating another profile policy
    # Defining the policy default
    policy_default = PolicyDefault("Validity Default", "validityDefaultImpl",
                                   "This default populates a Certificate "
                                   "Validity to the request. The default "
                                   "values are Range=180 in days")
    attr_descriptor = Descriptor(syntax="string", description="Not Before")
    policy_attribute = ProfileAttribute("notBefore", descriptor=attr_descriptor)
    policy_default.add_attribute(policy_attribute)

    attr_descriptor = Descriptor(syntax="string", description="Not After")
    policy_attribute = ProfileAttribute("notAfter", descriptor=attr_descriptor)
    policy_default.add_attribute(policy_attribute)

    profile_param = ProfileParameter("range", 180)
    profile_param2 = ProfileParameter("startTime", 0)
    policy_default.add_parameter(profile_param)
    policy_default.add_parameter(profile_param2)

    #Defining the policy constraint
    policy_constraint = PolicyConstraint("Validity Constraint",
                                         "This constraint rejects the validity "
                                         "that is not between 365 days.",
                                         "validityConstraintImpl")
    constraint_descriptor = Descriptor(syntax="integer",
                                       description="Validity Range (in days)",
                                       default_value=365)
    policy_constraint_value = PolicyConstraintValue("range", 365,
                                                    constraint_descriptor)
    policy_constraint.add_constraint_value(policy_constraint_value)

    constraint_descriptor = Descriptor(syntax="boolean", default_value=False,
                                       description="Check Not Before against"
                                                   " current time")
    policy_constraint_value = PolicyConstraintValue("notBeforeCheck", False,
                                                    constraint_descriptor)
    policy_constraint.add_constraint_value(policy_constraint_value)

    constraint_descriptor = Descriptor(syntax="boolean", default_value=False,
                                       description="Check Not After against"
                                                   " Not Before")
    policy_constraint_value = PolicyConstraintValue("notAfterCheck", False,
                                                    constraint_descriptor)
    policy_constraint.add_constraint_value(policy_constraint_value)

    policy_list.append(ProfilePolicy("2", policy_default, policy_constraint))

    policy_set = PolicySet("userCertSet", policy_list)

    profile_data.add_policy_set(policy_set)

    # Write the profile data object to a file for testing a file input
    with open(file_path+'/original.json', 'w') as output_file:
        output_file.write(json.dumps(profile_data,
                                     cls=encoder.CustomTypeEncoder,
                                     sort_keys=True, indent=4))
    # Create a new profile
    created_profile = profile_client.create_profile(profile_data)
    print created_profile
    print

    # Test creating a new profile with a duplicate profile id
    print "Create a profile with duplicate profile id."
    print "-------------------------------------------"

    try:
        profile_data = Profile(name="My Sample User Cert Enrollment",
                               profile_id="MySampleProfile",
                               class_id="caEnrollImpl",
                               description="Example User Cert Enroll Impl",
                               enabled_by='admin', enabled=False, visible=False,
                               renewal=False, xml_output=False,
                               authorization_acl="")
        profile_input = ProfileInput("i1", "subjectNameInputImpl")
        profile_input.add_attribute(ProfileAttribute("sn_uid"))
        profile_input.add_attribute(ProfileAttribute("sn_e"))
        profile_input.add_attribute(ProfileAttribute("sn_c"))
        profile_input.add_attribute(ProfileAttribute("sn_ou"))
        profile_input.add_attribute(ProfileAttribute("sn_ou1"))
        profile_input.add_attribute(ProfileAttribute("sn_ou2"))
        profile_input.add_attribute(ProfileAttribute("sn_ou3"))
        profile_input.add_attribute(ProfileAttribute("sn_cn"))
        profile_input.add_attribute(ProfileAttribute("sn_o"))

        profile_data.add_input(profile_input)
        profile_client.create_profile(profile_data)
    # pylint: disable=W0703
    except pki.BadRequestException as e:
        print 'MySampleProfile ' + str(e)
    print

    # Modify the above created profile
    print 'Modifying the profile MySampleProfile.'
    print '-----------------------------------'

    fetch = profile_client.get_profile('MySampleProfile')
    profile_input2 = ProfileInput("i2", "keyGenInputImpl")
    profile_input2.add_attribute(ProfileAttribute("cert_request_type"))
    profile_input2.add_attribute(ProfileAttribute("cert_request"))
    fetch.add_input(profile_input2)

    fetch.name += " (Modified)"
    modified_profile = profile_client.modify_profile(fetch)

    with open(file_path+'modified.json', 'w') as output_file:
        output_file.write(json.dumps(fetch, cls=encoder.CustomTypeEncoder,
                                     sort_keys=True, indent=4))

    print modified_profile
    print

    # Delete a profile
    print "Deleting the profile MySampleProfile."
    print "----------------------------------"
    profile_client.delete_profile('MySampleProfile')
    print "Deleted profile MySampleProfile."
    print

    # Testing deletion of a profile
    print 'Test profile deletion.'
    print '----------------------'
    try:
        profile_client.get_profile('MySampleProfile')
    # pylint: disable=W0703
    except pki.ProfileNotFoundException as e:
        print str(e)
    print

    # Creating a profile from file
    print 'Creating a profile using file input.'
    print '------------------------------------'
    original = profile_client.create_profile_from_file(
        file_path + 'original.json')
    print original
    print

    # Modifying a profile from file
    print 'Modifying a profile using file input.'
    print '------------------------------------'
    modified = profile_client.modify_profile_from_file(
        file_path + 'modified.json')
    print modified
    print

    # Test clean up
    profile_client.delete_profile('MySampleProfile')
    os.remove(file_path+'original.json')
    os.remove(file_path+'modified.json')
    os.removedirs(file_path)


if __name__ == "__main__":
    main()