aboutsummaryrefslogtreecommitdiffstats
path: root/upstream/odl-aaa-moon/aaa/aaa-authn-api/src/main/docs/mapping.rst
blob: 3363550233c26f4172d16a657bf288a729bb96e1 (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
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
Operation Model
===============

The assertions from an IdP are stored in an associative array. A
sequence of rules are applied, the first rule which returns success is
considered a match. During the execution of each rule values from the
assertion can be tested and transformed with the results selectively
stored in variables local to the rule. If the rule succeeds an
associative array of mapped values is returned. The mapped values are
taken from the local variables set during the rule execution. The
definition of the rules and mapped results are expressed in JSON
notation.

A rule is somewhat akin to a function in a programming language. It
starts execution with a set of predefined local variables. It executes
statements which are grouped together in blocks. Execution continues
until an `exit`_ statement returning a success/fail result is
executed or until the last statement is reached which implies
success. The remaining statements in a block may be skipped via a
`continue`_ statement which tests a condition, this is equivalent to
an "if" control flow of logic in a programming language.

Rule execution continues until a rule returns success. Each rule has a
`mapping`_ associative array bound to it which is a template for the
transformed result. Upon success the `mapping`_ template for the
rule is loaded and the local variables from the successful rule are
used to populate the values in the `mapping`_ template yielding the
final mapped result.

If no rules returns success authentication fails.


Pseudo Code Illustrating Operational Model
------------------------------------------

::

    mapped = null
    foreach rule in rules {
        result = null
        initialize rule.variables with pre-defined values

        foreach block in rule.statement_blocks {
            for statement in block.statements {
                if statement.verb is exit {
                    result = exit.status
                    break
                }
                elif statement.verb is continue {
                    break
                }
            }
            if result {
                break
            }
        if result == null {
            result = success
        }
    if result == success {
        mapped = rule.mapping(rule.variables)
    }
    return mapped



Structure Of Rule Definitions
=============================

Rules are loaded by the rule processor via a JSON document called a
rule definition. A definition has an *optional* set of mapping
templates and a list of rules. Each rule has specifies a mapping
template and has a list of statement blocks. Each statement block has
a list of statements.

In pseudo-JSON (JSON does not have comments, the ... ellipsis is a
place holder):

::

    {
        "mappings": {
                        "template1": "{...}",
                        "template2": "{...}"
                    },
        "rules": [
                     {   # Rule 0. A rule has a mapping or a mapping name
                         # and a list of statement blocks

                         "mapping": {...},
                         # -OR-
                         "mapping_name": "template1",

                         "statement_blocks": [
                                                 [   # Block 0
                                                     [statement 0]
                                                     [statement 1]
                                                 ],
                                                 [   # Block 1
                                                     [statement 0]
                                                     [statement 1]
                                                 ],

                                              ]
                     },
                     {   # Rule 1 ...
                     }
                 ]

    }

Mapping
-------

A mapping template is used to produce the final associative array of
name/value pairs. The template is a JSON Object. The value in a
name/value pair can be a constant or a variable. If the template value
is a variable the value of the variable is retrieved from the set of
local variables bound to the rule thereby replacing it in the final
result.

For example given this mapping template and rule variables in JSON:

template:

::

    {
        "organization": "BigCorp.com",
        "user: "$subject",
        "roles": "$roles"
    }

local variables:

::

    {
        "subject": "Sally",
        "roles": ["user", "admin"]
    }

The final mapped results would be:

::

    {
        "organization": "BigCorp.com",
        "user: "Sally",
        "roles": ["user", "admin"]
    }


Each rule must bind a mapping template to the rule. The mapping
template may either be defined directly in the rule via the
``mapping`` key or referenced by name via the ``mapping_name`` key.

If the ``mapping_name`` is specified the mapping is looked up in a
table of mapping templates bound to the Rule Processor. Using the name
of a mapping template is useful when many rules generate the exact
same template values.

If both ``mapping`` and ``mapping_name`` are defined the locally bound
``mapping`` takes precedence.

Syntax
------

The logic for a rule consists of a sequence of statements grouped in
blocks. A statement is similar to a function call in a programming
language.

A statement is a list of values the first of which is a verb which
defines the operation the statement will perform. Think of the
`verbs`_ as function names or operators. Following the verb are
parameters which may be constants or variables. If the statement
assigns a value to a variable left hand side of the assignment (lhs)
is always the first parameter following the verb in the list of
statement values.

For example this statement in JSON:

::

    ["split", "$groups", "$assertion[Groups]", ":"]

will assign an array to the variable ``$groups``. It looks up the
string named ``Groups`` in the assertion which is a colon (:)
separated list of group names splitting that string on the colon
character.

Statements **must** be grouped together in blocks. Therefore a rule is
a sequence of blocks and block is a sequence of statements. The
purpose of blocks is allow for crude flow of control logic. For
example this JSON rule has 4 blocks.

::

    [
        [
            ["set", $user, ""],
            ["set", $roles, []]
        ],
        [
            ["in", "UserName", "$assertion"],
            ["continue", "if_not_success"],
            ["set", "$user", "$assertion[UserName"],
        ],
        [
            ["in", "subject", "$assertion"],
            ["continue", "if_not_success"],
            ["set", "$user", "$assertion[subject]"],
        ],
        [
            ["length", "$temp", "$user"],
            ["compare", "$temp", ">", 0],
            ["exit", "rule_fails", "if_not_success"]
            ["append" "$roles", "unprivileged"]
        ]
    ]

The rule will succeed if either ``UserName`` or ``subject`` is defined
in the assertion and if so the local variable ``$user`` will be set to
the value found in the assertion and the "unprivileged" role will be
appended to the roles array.

The first block performs initialization. The second block tests to see
if the assertion has the key ``UserName`` if not execution continues
at the next block otherwise the value of UserName in the assertion is
copied into the variable ``$user``. The third block performs a similar
operation looking for a ``subject`` in the assertion. The fourth block
checks to see if the ``$user`` variable is empty, if it is empty the
rule fails because it didn't find either a ``UserName`` nor a
``subject`` in the assertion. If ``$user`` is not empty the
"unprivileged" role is appended and the rule succeeds.

Data Types
----------

There are 7 supported types which equate to the types available in
JSON. At the time of this writing there are 2 implementations of this
Mapping specification, one in Python and one in Java. This table
illustrates how each data type is represented. The first two columns
are definitions from an abstract specification. The JSON column
enumerates the data type JSON supports.  The Mapping column lists the
7 enumeration names used by the Mapping implemenation in each
language. The following columns list the concrete data type used in
that language.

+-----------+------------+--------------------+---------------------+
|  JSON     |  Mapping   | Python             |       Java          |
+===========+============+====================+=====================+
|  object   |  MAP       | dict               | Map<String, Object> |
+-----------+------------+--------------------+---------------------+
|  array    |  ARRAY     | list               | List<Object>        |
+-----------+------------+--------------------+---------------------+
|  string   |  STRING    | unicode (Python 2) | String              |
|           |            +--------------------+                     |
|           |            | str (Python 3)     |                     |
+-----------+------------+--------------------+---------------------+
|           |  INTEGER   | int                | Long                |
|  number   +------------+--------------------+---------------------+
|           |  REAL      | float              | Double              |
+-----------+------------+--------------------+---------------------+
|  true     |            |                    |                     |
+-----------+  BOOLEAN   | bool               | Boolean             |
|  false    |            |                    |                     |
+-----------+------------+--------------------+---------------------+
|  null     |  NULL      | None               | null                |
+-----------+------------+--------------------+---------------------+


Rule Debugging and Documentation
--------------------------------

If the rule processor reports an error or if you're debugging your
rules by enabling DEBUG log tracing then you must be able to correlate
the reported statement to where it appears in your rule JSON source. A
message will always identify a statement by the rule number, block
number within that rule and the statement number within that
block. However once your rules become moderately complex it will
become increasingly difficult to identify a statement by counting
rules, blocks and statements.

A better approach is to tag rules and blocks with a name or other
identifying string. You can set the `Reserved Variables`_
``rule_name`` and ``block_name`` to a string of your choice. These
strings will be reported in all messages along with the rule, block
and statement numbers.

JSON does not permit comments, as such you cannot include explanatory
comments next to your rules, blocks and statements in the JSON
source. The ``rule_name`` and ``block_name`` can serve a similar
purpose. By putting assignments to these variables as the first
statement in a block you'll both document your rules and be able to
identify specific statements in log messages.

During rule execution the ``rule_name`` and ``block_name`` are
initialized to the empty string at the beginning of each rule and
block respectively.

The above example is augmented to include this information. The rule
name is set in the first statement in the first block.

::

    [
        [
            ["set", "$rule_name", "Must have UserName or subject"],
            ["set", "block_name", "Initialization"],
            ["set", $user, ""],
            ["set", $roles, []]
        ],
        [
            ["set", "block_name", "Test for UserName, set $user"],
            ["in", "UserName", "$assertion"],
            ["continue", "if_not_success"],
            ["set", "$user", "$assertion[UserName"],
        ],
        [
            ["set", "block_name", "Test for subject, set $user"],
            ["in", "subject", "$assertion"],
            ["continue", "if_not_success"],
            ["set", "$user", "$assertion[subject]"],
        ],
        [
            ["set", "block_name", "If not $user fail, else append unprivileged to roles"],
            ["length", "$temp", "$user"],
            ["compare", "$temp", ">", 0],
            ["exit", "rule_fails", "if_not_success"]
            ["append" "$roles", "unprivileged"]
        ]
    ]




Variables
---------


Variables always begin with a dollar sign ($) and are followed by an
identifier which is any alpha character followed by zero or more
alphanumeric or underscore characters. The variable may optionally be
delimited with braces ({}) to separate the variable from surrounding
text. Three types of variables are supported:

* scalar
* array (indexed by zero based integer)
* associative array (indexed by string)

Both arrays and associative arrays use square brackets ([]) to specify
a member of the array. Examples of variable usage:

::

    $name
    ${name}
    $groups[0]
    ${groups[0]}
    $properties[key]
    ${properties[key]}

An array or an associative array may be referenced by it's base name
(omitting the indexing brackets). For example the associative array
array named "properties" is referenced using it's base name
``$properties`` but if you want to access a member of the "properties"
associative array named "duration" you would do this ``$properties[duration]``

This is not a general purpose language with full expression
syntax. Only one level of variable lookup is supported. Therefore
compound references like this

::

    $properties[$groups[2]]

will not work.


Escaping
^^^^^^^^

If you need to include a dollar sign in a string (where it is
immediately followed by either an identifier or a brace and identifier)
and do not want to have it be interpreted as representing a variable
you must escape the dollar sign with a backslash, for example
"$amount" is interpreted as the variable ``amount`` but "\\$amount"
is interpreted as the string "$amount" .


Reserved Variables
------------------

A rule has the following reserved variables:

assertion
    The current assertion values from the federated IdP. It is a
    dictionary of key/value pairs.

regexp_array
    The regular expression groups from the last successful regexp match
    indexed by number. Group 0 is the entire match. Groups 1..n are
    the corresponding parenthesized group counting from the left. For
    example regexp_array[1] is the first group.

regexp_map
    The regular expression groups from the last successful regexp match
    indexed by group name.

rule_number
    The zero based index of the currently executing rule.

rule_name
    The name of the currently executing rule. If the rule name has not
    been set it will be the empty string.

block_number
    The zero based index of the currently executing block within the
    currently executing rule.

block_name
    The name of the currently executing block. If the block name has not
    been set it will be the empty string.


statement_number
    The zero based index of the currently executing statement within the
    currently executing block.


Examples
========

Split a fully qualified username into user and realm components
---------------------------------------------------------------

It's common for some IdP's to return a fully qualified username
(e.g. principal or subject). The fully qualified username is the
concatenation of the user name, separator and realm name. A common
separator is the @ character. In this example lets say the fully
qualified username is ``bob@example.com`` and you want to return the
user and realm as independent values in your mapped result. The
username appears in the assertion as the value ``Principal``.

Our strategy will be to use a regular expression identify the user and
realm components and then assign them to local variables which will
then populate the mapped result.

The mapping in JSON is:

::

    {
        "user": "$username",
        "realm": "$domain"
    }

The assertion in JSON is:

::

    {
        "Principal": "bob@example.com"
    }

Our rule is:

::

    [
        [
            ["in", "Principal", "assertion"],
            ["exit", "rule_fails", "if_not_success"],
            ["regexp", "$assertion[Principal]", (?P<username>\\w+)@(?P<domain>.+)"],
            ["set", "$username", "$regexp_map[username]"],
            ["set", "$domain", "$regexp_map[domain]"],
            ["exit, "rule_succeeds", "always"]
        ]
    ]

Rule explanation:

Block 0:

0. Test if the assertion contains a Principal value.
1. Abort the rule if the assertion does not contain a Principal
   value.
2. Apply a regular expression the the Principal value. Use named
   groupings for the username and domain components for clarity.
3. Assign the regexp group username to the $username local variable.
4. Assign the regexp group domain to the $domain local variable.
5. Exit the rule, apply the mapping, return the mapped values. Note, an
   explicit `exit`_ is not required if there are no further statements
   in the rule, as is the case here.

The mapped result in JSON is:

::

    {
        "user": "bob",
        "realm": "example.com"
    }

Build a set of roles based on group membership
----------------------------------------------

Often one wants to grant roles to a user based on their membership in
certain groups. In this example let's say the assertion contains a
``Groups`` value which is a colon separated list of group names. Our
strategy is to split the ``Groups`` assertion value into an array of
group names. Then we'll test if a specific group is in the groups
array, if it is we'll add a role. Finally if no roles have been mapped
we fail. Users in the group "student" will get the role "unprivileged"
and users in the group "helpdesk" will get the role "admin".

The mapping in JSON is:

::

    {
        "roles": "$roles",
    }

The assertion in JSON is:

::

    {
        "Groups": "student:helpdesk"
    }

Our rule is:

::

    [
        [
            ["in", "Groups", "assertion"],
            ["exit", "rule_fails", "if_not_success"],
            ["set", "$roles", []],
            ["split", "$groups", "$assertion[Groups]", ":"],
        ],
        [
            ["in", "student", "$groups"],
            ["continue", "if_not_success"],
            ["append", "$roles", "unprivileged"]
        ],
        [
            ["in", "helpdesk", "$groups"],
            ["continue", "if_not_success"],
            ["append", "$roles", "admin"]
        ],
        [
            ["unique", "$roles", "$roles"],
            ["length", "$temp", "roles"],
            ["compare", $temp", ">", 0],
            ["exit", "rule_fails", "if_not_success"]
        ]

    ]

Rule explanation:

Block 0

0. Test if the assertion contains a Groups value.
1. Abort the rule if the assertion does not contain a Groups
   value.
2. Initialize the $roles variable to an empty array.
3. Split the colon separated list of group names into an array of
   individual group names

Block 1

0. Test if "student" is in the $groups array
1. Exit the block if it's not.
2. Append "unprivileged" to the $roles array

Block 2

0. Test if "helpdesk" is in the $groups array
1. Exit the block if it's not.
2. Append "admin" to the $roles array

Block 3

0. Strip any duplicate roles that might have been appended to the
   $roles array to assure each role is unique.
1. Count how many members are in the $roles array, assign the
   length to the $temp variable.
2. Test to see if the $roles array had any members.
3. Fail if no roles had been assigned.

The mapped result in JSON is:

::

    {
        "roles": ["unprivileged", "admin"]
    }

However, suppose whatever is receiving your mapped results is not
expecting an array of roles. Instead it expects a comma separated list
in a string. To accomplish this add the following statement as the
last one in the final block:

::

            ["join", "$roles", "$roles", ","]

Then the mapped result will be:

::

    {
        "roles": "unprivileged,admin"]
    }




White list certain users and grant them specific roles
------------------------------------------------------

Suppose you have certain users you always want to unconditionally
accept and authorize with specific roles. For example if the user is
"head_of_IT" then assign her the "user" and "admin" roles. Otherwise
keep processing. The list of white listed users is hard-coded into the
rule.

The mapping in JSON is:

::

    {
        "user": $user,
        "roles": "$roles",
    }

The assertion in JSON is:

::

    {
        "UserName": "head_of_IT"
    }

Our rule in JSON is:

::

    [
        [
            ["in", "UserName", "assertion"],
            ["exit", "rule_fails", "if_not_success"],
            ["in", "$assertion[UserName]", ["head_of_IT", "head_of_Engineering"]],
            ["continue", "if_not_success"],
            ["set", "$user", "$assertion[UserName"]
            ["set", "$roles", ["user", "admin"]],
            ["exit", "rule_succeeds", "always"]
        ],
        [
            ...
        ]
    ]

Rule explanation:

Block 0

0. Test if the assertion contains a UserName value.
1. Abort the rule if the assertion does not contain a UserName
   value.
2. Test if the user is in the hardcoded list of white listed users.
3. If the user isn't in the white listed array then exit the block and
   continue execution at the next block.
4. Set the $user local variable to $assertion[UserName]
5. Set the $roles local variable to the hardcoded array containing
   "user" and "admin"
6. We're done, unconditionally exit and return the mapped result.

Block 1

0. Further processing

The mapped result in JSON is:

::

    {
        "user": "head_of_IT",
        "roles": ["users", "admin"]
    }


Black list certain users
------------------------

Suppose you have certain users you always want to unconditionally
deny access to by placing them in a black list. In this example the
user "BlackHat" will try to gain access. The black list includes the
users "BlackHat" and "Spook".

The mapping in JSON is:

::

    {
        "user": $user,
        "roles": "$roles",
    }

The assertion in JSON is:

::

    {
        "UserName": "BlackHat"
    }

Our rule in JSON is:

::

    [
        [
            ["in", "UserName", "assertion"],
            ["exit", "rule_fails", "if_not_success"],
            ["in", "$assertion[UserName]", ["BlackHat", "Spook"]],
            ["exit", "rule_fails", "if_success"]
        ],
        [
            ...
        ]
    ]

Rule explanation:

Block 0

0. Test if the assertion contains a UserName value.
1. Abort the rule if the assertion does not contain a UserName
   value.
2. Test if the user is in the hard-coded list of black listed users.
3. If the test succeeds then immediately abort and return failure.

Block 1

0. Further processing

The mapped result in JSON is:

::

    Null

Format Strings and/or Concatenate Strings
-----------------------------------------

You can replace variables in a format string using the `interpolate`_
verb. String concatenation is trivially placing two variables adjacent
to one another in a format string. Suppose you want to form an email
address from the username and domain in an assertion.

The mapping in JSON is:

::

    {
        "email": $email,
    }

The assertion in JSON is:

::

    {
        "UserName": "Bob",
        "Domain": "example.com"
    }

Our rule in JSON is:

::

    [
        [
            ["interpolate", "$email", "$assertion[UserName]@$assertion[Domain]"],
        ]
    ]

Rule explanation:

Block 0

0. Replace the variable $assertion[UserName] with it's value and
   replace the variable $assertion[Domain] with it's value.

The mapped result in JSON is:

::

    {
        "email": "Bob@example.com",
    }


Note, sometimes it's necessary to utilize braces to separate variables
from surrounding text by using the brace notation. This can also make
the format string more readable. Using braces to delimit variables the
above would be:

::

    [
        [
            ["interpolate", "$email", "${assertion[UserName]}@${assertion[Domain]}"],
        ]
    ]



Make associative array lookups case insensitive
-----------------------------------------------

Many systems treat field names as case insensitive. By default
associative array indexing is case sensitive. The solution is to lower
case all the keys in an associative array and then only use lower case
indices. Suppose you want the assertion associative array to be case
insensitive.

The mapping in JSON is:

::

    {
        "user": $user,
    }

The assertion in JSON is:

::

    {
        "UserName": "Bob"
    }

Our rule in JSON is:

::

    [
        [
            ["lower", "$assertion", "$assertion"],
            ["in", "username", "assertion"],
            ["exit", "rule_fails", "if_not_success"],
            ["set", "$user", "$assertion[username"]
        ]
    ]

Rule explanation:

Block 0

0. Lower case all the keys in the assertion associative array.
1. Test if the assertion contains a username value.
2. Abort the rule if the assertion does not contain a username
   value.
3. Assign the username value in the assertion to $user

The mapped result in JSON is:

::

    {
        "user": "Bob",
    }


Verbs
=====

The following verbs are supported:

* `set`_
* `length`_
* `interpolate`_
* `append`_
* `unique`_
* `regexp`_
* `regexp_replace`_
* `split`_
* `join`_
* `lower`_
* `upper`_
* `compare`_
* `in`_
* `not_in`_
* `exit`_
* `continue`_

Some verbs have a side effects. A verb may set a boolean success/fail
result which may then be tested with a subsequent verb. For example
the ``fail`` verb can be used to indicate the rule fails if a prior
result is either ``success`` or ``not_success``.  The ``regexp`` verb
which performs a regular expression search on a string stores the
regular expression sub-matches as a side effect in the variables
``$regexp_array`` and ``$regexp_map``.


Verb Definitions
================

set
---

``set $variable value``

$variable
    The variable being assigned (i.e. lhs)

value
    The value to assign to the variable (i.e. rhs). The value may be
    another variable or a constant.

**set** assigns a value to a variable, in other words it's an
assignment statement.

Examples:
^^^^^^^^^

Initialize a variable to an empty array.

::

    ["set", "$groups", []]

Initialize a variable to an empty associative array.

::

    ["set", "$groups", {}]

Assign a string.

::

    ["set", "$version", "1.2.3"]

Copy the ``UserName`` value from the assertion to a temporary variable.

::

    ["set", "$temp", "$assertion[UserName]"],


Get the 2nd item in an array (array indexing is zero based)

::

    ["set", "$group", "$groups[1]"]


Set the associative array entry "IdP" to "kdc.example.com".

::

    ["set", "$metadata[IdP]", "kdc.example.com""]

--------------------------------------------------------------------------------

length
------

``length $variable value``

$variable
    The variable which receives the length value

value
    The value whose length is to be determined. May be one of array,
    associative array, or string.

**length** computes the number of items in the value. How this is done
depends upon the type of value:

array
    The length is the number of items in the array.

associative array
    The length is the number of key/value pairs in the associative
    array.

string
    The length is the number of *characters* (not octets) in the
    string.

Examples:
^^^^^^^^^

Count how many items are in the ``$groups`` array and assign that
value to the ``$groups_length`` variable.

::

    ["length", "$groups_length", "$groups"]

Count how many key/value pairs are in the ``$assertion`` associative
array and assign that value to the ``$num_assertion_values`` variable.

::

    ["length", "$num_assertion_values", "$assertion"]

Count how many characters are in the assertion's UserName and assign
the value to ``$username_length``.

::

    ["length", "$user_name_length", "$assertion[UserName]"]


--------------------------------------------------------------------------------

interpolate
-----------

``interpolate $variable string``

$variable
    This variable is assigned the result of the interpolation.

string
    A string containing references to variables which will be replaced
    in the string.

**interpolate** replaces each occurrence of a variable in a string with
it's value. The result is assigned to $variable.

Examples:
^^^^^^^^^

Form an email address given the username and domain. If the username
is "jane" and the domain is "example.com" then $email will be
"jane@example.com"

::

    ["interpolate", "$email", "${username}@${domain}"]


--------------------------------------------------------------------------------


append
------

``append $variable value``

$variable
    This variable **must** be an array. It is modified in place by
    appending ``value`` to the end of the array.

value
    The value to append to the end of the array.

**append** adds a value to end of an array.

Examples:
^^^^^^^^^

Append the role "qa_test" to the roles list.

::

    ["append", "$roles", "qa_test"]


--------------------------------------------------------------------------------


unique
------

``unique $variable value``

$variable
    This variable is assigned the unique values in the ``value``
    array.

value
    An array of values. **must** be an array.

**unique** builds an array of unique values in ``value`` by stripping
out duplicates and assigns the array of unique values to
``$variable``. The order of items in the ``value`` array are
preserved.

Examples:
^^^^^^^^^

$one_of_a_kind will be assigned ["a", "b"]

::

    ["unique", "$one_of_a_kind", ["a", "b", "a"]]


--------------------------------------------------------------------------------

regexp
------

``regexp string pattern``

string
    The string the regular expression pattern is applied to.

pattern
    The regular expression pattern.

**regexp** performs a regular expression match against ``string``. The
regular expression pattern syntax is defined by the regular expression
implementation of the language this API is written in.

Pattern groups are a convenient way to select sub-matches. Pattern
groups may accessed by either group number or group name. After a
successful regular expression match the groups are stored in the
special variables ``$regexp_array`` and
``$regexp_map``.

``$regexp_array`` is used to access the groups by
numerical index. Groups are numbered by counting the left parenthesis
group delimiter starting at 1. Group 0 is the entire
match. ``$regexp_array`` is valid irregardless of whether you used
named groups or not.

``$regexp_map`` is used to access the groups by
name. ``$regexp_map`` is only valid if you used named groups in the
pattern.

Examples:
^^^^^^^^^

Many user names are of the form "user@domain", to split the username
from the domain and to be able to work with those values independently
use a regular expression and then assign the results to a variable. In
this example there are two regular expression groups, the first group
is the username and the second group is the domain. In the first
example we use named groups and then access the match information in
the special variable ``$regexp_map`` via the name of the group.

::

    ["regexp", "$assertion[UserName]", "(?P<username>\\w+)@(?P<domain>.+)"],
    ["continue", "if_not_success"],
    ["set", "$username", "$regexp_map[username]"],
    ["set", "$domain", "$regexp_map[domain]"],


This is exactly equivalent but uses numbered groups instead of named
groups. In this instance the group matches are stored in the special
variable ``$regexp_array`` and accessed by numerical index.

::

    ["regexp", "$assertion[UserName]", "(\\w+)@(.+)"],
    ["continue", "if_not_success"],
    ["set", "$username", "$regexp_array[1]"],
    ["set", "$domain", "$regexp_array[2]"],



--------------------------------------------------------------------------------

regexp_replace
--------------

``regexp_replace $variable string pattern replacement``

$variable
    The variable which receives result of the replacement.

string
    The string to perform the replacement on.

pattern
    The regular expression pattern.

replacement
    The replacement specification.

**regexp_replace** replaces each occurrence of ``pattern`` in
``$string`` with ``replacement``. See `regexp`_ for details of using
regular expressions.

Examples:
^^^^^^^^^

Convert hyphens in a name to underscores.

::

    ["regexp_replace", "$name", "$name", "-", "_"]


--------------------------------------------------------------------------------

split
-----

``split $variable string pattern``

$variable
    This variable is assigned an array containing the split items.

string
    The string to split into separate items.

pattern
    The regular expression pattern used to split the string.

**split** splits ``string`` into separate pieces and assigns the
result to ``$variable`` as an array of pieces. The split occurs
wherever the regular expression ``pattern`` occurs in ``string``. See
`regexp`_ for details of using regular expressions.

Examples:
^^^^^^^^^

Split a list of groups separated by a colon (:) into an array of
individual group names. If $assertion[Groups] contained the string
"user:admin" then $group_list will set to ["user", "admin"].

::

    ["split", "$group_list", "$assertion[Groups]", ":"]



--------------------------------------------------------------------------------

join
----

``join $variable array join_string``

$variable
    This variable is assigned the string result of the join operation.

array
    An array of string items to be joined together with
    ``$join_string``.

join_string
    The string inserted between each element in ``array``.

**join** accepts an array of strings and produces a single string
where each element in the array is separated by ``join_string``.

Examples:
^^^^^^^^^

Convert a list of group names into a single string where each group
name is separated by a colon (:). If the array ``$group_list`` is
["user", "admin"] and the ``join_string`` is ":" then the
``$group_string`` variable will be set to "user:admin".

::

    ["join", "$group_string", "$groups", ":"]


--------------------------------------------------------------------------------

lower
-----

``lower $variable value``

$variable
    This variable is assigned the result of the lower operation.

value
    The value to lower case, may be either a string, array, or
    associative array.

**lower** lower cases the input value. The input value may be one of
the following types:

string
    The string is lower cased.

array
    Each member of the array must be a string, the result is an array
    with the items replaced by their lower case value.

associative array
    Each key in the associative array is lower cased. The values
    associated with the key are **not** modified.

Examples:
^^^^^^^^^

Lookup ``UserName`` in the assertion and set the variable
``$username`` to it's lower case value.

::

    ["lower", "$username", "$assertion[UserName]"],

Set each member of the ``$groups`` array to it's lower case value. If
``$groups`` was ["User", "Admin"] then ``$groups`` will become
["user", "admin"].

::

    ["lower", "$groups", "$groups"],

To enable case insensitive lookup's in an associative array lower case
each key in the associative array. If ``$assertion`` was {"UserName":
"JoeUser"} then ``$assertion`` will become {"username": "JoeUser"}

::

    ["lower", "$assertion", $assertion"]

--------------------------------------------------------------------------------

upper
-----

``upper $variable value``

$variable
    This variable is assigned the result of the upper operation.

value
    The value to upper case, may be either a string, array, or
    associative array.

**upper** is exactly analogous to `lower`_ except the values are upper
cased, see `lower`_ for details.


--------------------------------------------------------------------------------

in
--

``in member collection``

member
    The value whose membership is being tested.

collection
    A collection of members. May be string, array or associative array.

**in** tests to see if ``member`` is a member of ``collection``. The
membership test depends on the type of collection, the following are
supported:

array
    If any item in the array is equal to ``member`` then the result is
    success.

associative array
    If the associative array contains a key equal to ``member`` then
    the result is success.

string
    If the string contains a sub-string equal to ``member`` then the
    result is success.

Examples:
^^^^^^^^^

Test to see if the assertion contains a UserName value.

::

    ["in", "UserName", "$assertion"]
    ["continue", "if_not_success"]

Test to see if a group is one of "user" or "admin".

::

    ["in", "$group", ["user", "admin"]]
    ["continue", "if_not_success"]

Test to see if the sub-string "BigCorp" is in
the assertion's ``Provider`` value.

::

    ["in", "BigCorp", "$assertion[Provider]"]
    ["continue", "if_not_success"]


--------------------------------------------------------------------------------

not_in
------

``in member collection``

member
    The value whose membership is being tested.

collection
    A collection of members. May be string, array or associative array.

**not_in** is exactly analogous to `in`_ except the sense of the test
is reversed. See `in`_ for details.

--------------------------------------------------------------------------------

compare
-------

``compare left operator right``

left
    The left hand value of the binary operator.

operator
    The binary operator used for comparing left to right.

right
    The right hand value of the binary operator.


**compare** compares the left value to the right value according the
operator and sets success if the comparison evaluates to True. The
following relational operators are supported.

+----------+-----------------------+
| Operator | Description           |
+==========+=======================+
| ==       | equal                 |
+----------+-----------------------+
| !=       | not equal             |
+----------+-----------------------+
| <        | less than             |
+----------+-----------------------+
| <=       | less than or equal    |
+----------+-----------------------+
| >        | greater than          |
+----------+-----------------------+
| >=       | greater than or equal |
+----------+-----------------------+


The left and right hand sides of the comparison operator *must* be
the same type, no type conversions are performed. Not all combinations
of operator and type are supported. The table below illustrates the
supported combinations. Essentially you can test for equality or
inequality on any type. But only strings and numbers support the
magnitude relational operators.


+----------+--------+---------+------+---------+-----+------+------+
| Operator | STRING | INTEGER | REAL | BOOLEAN | MAP | LIST | NULL |
+==========+========+=========+======+=========+=====+======+======+
| ==       |   X    |    X    |  X   |    X    |  X  |  X   |  X   |
+----------+--------+---------+------+---------+-----+------+------+
| !=       |   X    |    X    |  X   |    X    |  X  |  X   |  X   |
+----------+--------+---------+------+---------+-----+------+------+
| <        |   X    |    X    |  X   |         |     |      |      |
+----------+--------+---------+------+---------+-----+------+------+
| <=       |   X    |    X    |  X   |         |     |      |      |
+----------+--------+---------+------+---------+-----+------+------+
| >        |   X    |    X    |  X   |         |     |      |      |
+----------+--------+---------+------+---------+-----+------+------+
| >=       |   X    |    X    |  X   |         |     |      |      |
+----------+--------+---------+------+---------+-----+------+------+


Examples:
^^^^^^^^^

Test to see if the ``$groups`` array has at least 2 members

::

    ["length", "$group_length", "$groups"],
    ["compare", "$group_length", ">=", 2]


--------------------------------------------------------------------------------

exit
----

``exit status criteria``

status
    The result for the rule.

criteria
    The criteria upon which will cause the rule will be immediately
    exited with a failed status.

**exit** causes the rule being executed to immediately exit and a rule
result if the specified criteria is met. Statement verbs such as `in`_
or `compare`_ set the result status which may be tested with the
``success`` and ``not_success`` criteria.

The exit ``status`` may be one of:

rule_fails
    The rule has failed and no mapping will occur.

rule_succeeds
    The rule succeeded and the mapping will be applied.

The ``criteria`` may be one of:

if_success
    If current result status is success then exit with ``status``.

if_not_success
    If current result status is not success then exit with ``status``.

always
    Unconditionally exit with ``status``.

never
    Effectively a no-op. Useful for debugging.

Examples:
^^^^^^^^^

The rule requires ``UserName`` to be in the assertion.

::

    ["in", "UserName", "$assertion"]
    ["exit", "rule_fails", "if_not_success"]

--------------------------------------------------------------------------------


continue
--------

``continue criteria``

criteria
    The criteria which causes the remainder of the *block* to be
    skipped.

**continue** is used to control execution for statement blocks. It
mirrors in a crude way the `if` expression in a procedural
language. ``continue`` does *not* affect the success or failure of a
rule, rather it controls whether subsequent statements in a block are
executed or not. Control continues at the next statement block.

Statement verbs such as `in`_ or `compare`_ set the result status
which may be tested with the ``success`` and ``not_success`` criteria.

The criteria may be one of:

if_success
    If current result status is success then exit the statement
    block and continue execution at the next statement block.

if_not_success
    If current result status is not success then exit the statement
    block and continue execution at the next statement block.

always
    Immediately exit the statement block and continue execution at the
    next statement block.

never
    Effectively a no-op. Useful for debugging. Execution continues at
    the next statement.

Examples:
^^^^^^^^^

The following pseudo code:

::

    roles = [];
    if ("Groups" in assertion) {
        groups = assertion["Groups"].split(":");
        if ("qa_test" in groups) {
            roles.append("tester");
        }
    }

could be implemented this way:

::

    [
        ["set", "$roles", []],
        ["in", "Groups", "$assertion"],
        ["continue", "if_not_success"],
        ["split" "$groups", $assertion[Groups]", ":"],
        ["in", "qa_test", "$groups"],
        ["continue", "if_not_success"],
        ["append", "$roles", "tester"]
    ]