-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathAuthorizationResolverUnitTests.cs
More file actions
1929 lines (1699 loc) · 106 KB
/
Copy pathAuthorizationResolverUnitTests.cs
File metadata and controls
1929 lines (1699 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Auth;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Service.Exceptions;
using Azure.DataApiBuilder.Service.Tests.Authentication.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace Azure.DataApiBuilder.Service.Tests.Authorization
{
[TestClass]
public class AuthorizationResolverUnitTests
{
private const string TEST_ENTITY = "SampleEntity";
private const string TEST_ROLE = "Writer";
private const EntityActionOperation TEST_OPERATION = EntityActionOperation.Create;
private const string TEST_AUTHENTICATION_TYPE = "TestAuth";
private const string TEST_CLAIMTYPE_NAME = "TestName";
#region Role Context Tests
/// <summary>
/// When the client role header is present, validates result when
/// Role is in ClaimsPrincipal.Roles -> VALID
/// Role is NOT in ClaimsPrincipal.Roles -> INVALID
/// </summary>
[DataTestMethod]
[DataRow("Reader", true, true)]
[DataRow("Reader", false, false)]
public void ValidRoleContext_Simple(string clientRoleHeaderValue, bool userIsInRole, bool expected)
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig();
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Mock<HttpContext> context = new();
context.SetupGet(x => x.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER]).Returns(clientRoleHeaderValue);
context.Setup(x => x.User.IsInRole(clientRoleHeaderValue)).Returns(userIsInRole);
context.Setup(x => x.User.Identity!.IsAuthenticated).Returns(true);
Assert.AreEqual(authZResolver.IsValidRoleContext(context.Object), expected);
}
[TestMethod("Role header has no value")]
public void RoleHeaderEmpty()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig();
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Mock<HttpContext> context = new();
context.SetupGet(x => x.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER]).Returns(StringValues.Empty);
bool expected = false;
Assert.AreEqual(authZResolver.IsValidRoleContext(context.Object), expected);
}
[TestMethod("Role header has multiple values")]
public void RoleHeaderDuplicated()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig();
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Mock<HttpContext> context = new();
StringValues multipleValuesForHeader = new(new string[] { "Reader", "Writer" });
context.SetupGet(x => x.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER]).Returns(multipleValuesForHeader);
context.Setup(x => x.User.IsInRole("Reader")).Returns(true);
bool expected = false;
Assert.AreEqual(authZResolver.IsValidRoleContext(context.Object), expected);
}
[TestMethod("Role header is missing")]
public void NoRoleHeader_RoleContextTest()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig();
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Mock<HttpContext> context = new();
context.SetupGet(x => x.Request.Headers[AuthorizationResolver.CLIENT_ROLE_HEADER]).Returns(StringValues.Empty);
bool expected = false;
Assert.AreEqual(authZResolver.IsValidRoleContext(context.Object), expected);
}
#endregion
#region Role and Operation on Entity Tests
/// <summary>
/// Tests the AreRoleAndOperationDefinedForEntity stage of authorization.
/// Request operation is defined for role -> VALID
/// Request operation not defined for role (role has 0 defined operations)
/// Ensures method short circuits in circumstances role is not defined -> INVALID
/// Request operation does not match an operation defined for role (role has >=1 defined operation) -> INVALID
/// </summary>
[DataTestMethod]
[DataRow("Writer", EntityActionOperation.Create, "Writer", EntityActionOperation.Create, true)]
[DataRow("Reader", EntityActionOperation.Create, "Reader", EntityActionOperation.None, false)]
[DataRow("Writer", EntityActionOperation.Create, "Writer", EntityActionOperation.Update, false)]
public void AreRoleAndOperationDefinedForEntityTest(
string configRole,
EntityActionOperation configOperation,
string roleName,
EntityActionOperation operation,
bool expected)
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: configRole,
operation: configOperation);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Mock Request Values
Assert.AreEqual(expected, authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY, roleName, operation));
}
/// <summary>
/// Test that wildcard operation are expanded to explicit operations.
/// Verifies that internal data structure are created correctly.
/// </summary>
[TestMethod("Wildcard operation is expanded to all valid operations")]
public void TestWildcardOperation()
{
List<string> expectedRoles = new() { AuthorizationHelpers.TEST_ROLE };
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.All);
// Override the permission operations to be a list of operations for wildcard
// instead of a list of objects created by readAction, updateAction
Entity entity = runtimeConfig.Entities[AuthorizationHelpers.TEST_ENTITY];
entity = entity with { Permissions = new[] { new EntityPermission(AuthorizationHelpers.TEST_ROLE, new EntityAction[] { new(EntityActionOperation.All, null, new(null, null)) }) } };
runtimeConfig = runtimeConfig with { Entities = new(new Dictionary<string, Entity> { { AuthorizationHelpers.TEST_ENTITY, entity } }) };
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// There should not be a wildcard operation in AuthorizationResolver.EntityPermissionsMap
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.All));
// The wildcard operation should be expanded to all the explicit operations.
foreach (EntityActionOperation operation in EntityAction.ValidPermissionOperations)
{
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation));
IEnumerable<string> actualRolesForCol1 = authZResolver.GetRolesForField(AuthorizationHelpers.TEST_ENTITY, "col1", operation);
CollectionAssert.AreEquivalent(expectedRoles, actualRolesForCol1.ToList());
IEnumerable<string> actualRolesForOperation = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
operation,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRoles, actualRolesForOperation.ToList());
}
// Validate that the authorization check fails because the operations are invalid.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY, TEST_ROLE, EntityActionOperation.Insert));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY, TEST_ROLE, EntityActionOperation.Upsert));
}
/// <summary>
/// Verify that the internal data structure is created correctly when we have
/// Two roles for the same entity with different permission.
/// readOnlyRole - Read permission only for col1 and no policy.
/// readAndUpdateRole - read and update permission for col1 and no policy.
/// </summary>
[TestMethod]
public void TestRoleAndOperationCombination()
{
const string READ_ONLY_ROLE = "readOnlyRole";
const string READ_AND_UPDATE_ROLE = "readAndUpdateRole";
EntityActionFields fieldsForRole = new(
Include: new HashSet<string> { "col1" },
Exclude: new());
EntityAction readAction = new(
Action: EntityActionOperation.Read,
Fields: fieldsForRole,
Policy: new(null, null));
EntityAction updateAction = new(
Action: EntityActionOperation.Update,
Fields: fieldsForRole,
Policy: new(null, null));
EntityPermission readOnlyPermission = new(
Role: READ_ONLY_ROLE,
Actions: new[] { readAction });
EntityPermission readAndUpdatePermission = new(
Role: READ_AND_UPDATE_ROLE,
Actions: new[] { readAction, updateAction });
EntityPermission[] permissions = new EntityPermission[] { readOnlyPermission, readAndUpdatePermission };
RuntimeConfig runtimeConfig = BuildTestRuntimeConfig(permissions, TEST_ENTITY);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Verify that read only role has permission for read and nothing else.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_ONLY_ROLE,
EntityActionOperation.Read));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_ONLY_ROLE,
EntityActionOperation.Update));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_ONLY_ROLE,
EntityActionOperation.Create));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_ONLY_ROLE,
EntityActionOperation.Delete));
// Verify that read only role has permission for read/update and nothing else.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_AND_UPDATE_ROLE,
EntityActionOperation.Read));
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_AND_UPDATE_ROLE,
EntityActionOperation.Update));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_AND_UPDATE_ROLE,
EntityActionOperation.Create));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
READ_AND_UPDATE_ROLE,
EntityActionOperation.Delete));
List<string> expectedRolesForRead = new() { READ_ONLY_ROLE, READ_AND_UPDATE_ROLE };
List<string> expectedRolesForUpdate = new() { READ_AND_UPDATE_ROLE };
IEnumerable<string> actualReadRolesForCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1",
EntityActionOperation.Read);
CollectionAssert.AreEquivalent(expectedRolesForRead, actualReadRolesForCol1.ToList());
IEnumerable<string> actualUpdateRolesForCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1",
EntityActionOperation.Update);
CollectionAssert.AreEquivalent(expectedRolesForUpdate, actualUpdateRolesForCol1.ToList());
IEnumerable<string> actualRolesForRead = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Read,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForRead, actualRolesForRead.ToList());
IEnumerable<string> actualRolesForUpdate = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Update,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForUpdate, actualRolesForUpdate.ToList());
}
/// <summary>
/// Test to validate that the permissions for the system role "authenticated" are derived the permissions of
/// the system role "anonymous" when authenticated role is not defined, but anonymous role is defined.
/// </summary>
[TestMethod]
public void TestAuthenticatedRoleWhenAnonymousRoleIsDefined()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationResolver.ROLE_ANONYMOUS,
operation: EntityActionOperation.Create);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
foreach (EntityActionOperation operation in EntityAction.ValidPermissionOperations)
{
if (operation is EntityActionOperation.Create)
{
// Create operation should be defined for anonymous role.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_ANONYMOUS,
operation));
// Create operation should be defined for authenticated role as well,
// because it is defined for anonymous role.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED,
operation));
}
else
{
// Check that no other operation is defined for the authenticated role to ensure
// the authenticated role's permissions match that of the anonymous role's permissions.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED,
operation));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_ANONYMOUS,
operation));
}
}
// With role inheritance, named roles inherit from authenticated (which inherited from anonymous).
// Assert that an arbitrary named role now effectively has the Create operation via inheritance.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE, EntityActionOperation.Create));
// Assert that the create operation has both anonymous, authenticated roles.
List<string> expectedRolesForCreate = new() { AuthorizationResolver.ROLE_AUTHENTICATED, AuthorizationResolver.ROLE_ANONYMOUS };
IEnumerable<string> actualRolesForCreate = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Create,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForCreate, actualRolesForCreate.ToList());
// Assert that the col1 field with create operation has both anonymous, authenticated roles.
List<string> expectedRolesForCreateCol1 = new() {
AuthorizationResolver.ROLE_ANONYMOUS,
AuthorizationResolver.ROLE_AUTHENTICATED };
IEnumerable<string> actualRolesForCreateCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1", EntityActionOperation.Create);
CollectionAssert.AreEquivalent(expectedRolesForCreateCol1, actualRolesForCreateCol1.ToList());
// Assert that the col1 field with read operation has no role.
List<string> expectedRolesForReadCol1 = new();
IEnumerable<string> actualRolesForReadCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1", EntityActionOperation.Read);
CollectionAssert.AreEquivalent(expectedRolesForReadCol1, actualRolesForReadCol1.ToList());
}
/// <summary>
/// Test to validate that the no permissions for authenticated role are derived when
/// both anonymous and authenticated role are not defined.
/// </summary>
[TestMethod]
public void TestAuthenticatedRoleWhenAnonymousRoleIsNotDefined()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Create operation should be defined for test role.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create));
// Create operation should not be defined for authenticated role,
// because neither authenticated nor anonymous role is defined.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED,
EntityActionOperation.Create));
// Assert that the Create operation has only test_role.
List<string> expectedRolesForCreate = new() { AuthorizationHelpers.TEST_ROLE };
IEnumerable<string> actualRolesForCreate = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Create,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForCreate, actualRolesForCreate.ToList());
// Since neither anonymous nor authenticated role is defined for the entity,
// Create operation would only have the test_role.
List<string> expectedRolesForCreateCol1 = new() { AuthorizationHelpers.TEST_ROLE };
IEnumerable<string> actualRolesForCreateCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1", EntityActionOperation.Create);
CollectionAssert.AreEquivalent(expectedRolesForCreateCol1, actualRolesForCreateCol1.ToList());
}
/// <summary>
/// Test to validate that when anonymous and authenticated role are both defined, then
/// the authenticated role does not derive permissions from anonymous role's permissions.
/// </summary>
[TestMethod]
public void TestAuthenticatedRoleWhenBothAnonymousAndAuthenticatedAreDefined()
{
EntityActionFields fieldsForRole = new(
Include: new HashSet<string> { "col1" },
Exclude: new());
EntityAction readAction = new(
Action: EntityActionOperation.Read,
Fields: fieldsForRole,
Policy: new());
EntityAction updateAction = new(
Action: EntityActionOperation.Update,
Fields: fieldsForRole,
Policy: new());
EntityPermission authenticatedPermission = new(
Role: AuthorizationResolver.ROLE_AUTHENTICATED,
Actions: new[] { readAction });
EntityPermission anonymousPermission = new(
Role: AuthorizationResolver.ROLE_ANONYMOUS,
Actions: new[] { readAction, updateAction });
EntityPermission[] permissions = new EntityPermission[] { authenticatedPermission, anonymousPermission };
const string entityName = TEST_ENTITY;
RuntimeConfig runtimeConfig = BuildTestRuntimeConfig(permissions, entityName);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Assert that for the role authenticated, only the Read operation is allowed.
// The Update operation is not allowed even though update is allowed for the role anonymous.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED, EntityActionOperation.Read));
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_ANONYMOUS, EntityActionOperation.Update));
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED, EntityActionOperation.Delete));
// Assert that the read operation has both anonymous and authenticated role.
List<string> expectedRolesForRead = new() {
AuthorizationResolver.ROLE_ANONYMOUS,
AuthorizationResolver.ROLE_AUTHENTICATED };
IEnumerable<string> actualRolesForRead = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Read,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForRead, actualRolesForRead.ToList());
// Assert that the update operation has only anonymous role.
List<string> expectedRolesForUpdate = new() { AuthorizationResolver.ROLE_ANONYMOUS };
IEnumerable<string> actualRolesForUpdate = IAuthorizationResolver.GetRolesForOperation(
AuthorizationHelpers.TEST_ENTITY,
EntityActionOperation.Update,
authZResolver.EntityPermissionsMap);
CollectionAssert.AreEquivalent(expectedRolesForUpdate, actualRolesForUpdate.ToList());
// Assert that the col1 field with Read operation has both anonymous and authenticated roles.
List<string> expectedRolesForReadCol1 = new() {
AuthorizationResolver.ROLE_ANONYMOUS,
AuthorizationResolver.ROLE_AUTHENTICATED };
IEnumerable<string> actualRolesForReadCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1", EntityActionOperation.Read);
CollectionAssert.AreEquivalent(expectedRolesForReadCol1, actualRolesForReadCol1.ToList());
// Assert that the col1 field with Update operation has only anonymous roles.
List<string> expectedRolesForUpdateCol1 = new() { AuthorizationResolver.ROLE_ANONYMOUS };
IEnumerable<string> actualRolesForUpdateCol1 = authZResolver.GetRolesForField(
AuthorizationHelpers.TEST_ENTITY,
"col1", EntityActionOperation.Update);
CollectionAssert.AreEquivalent(expectedRolesForUpdateCol1, actualRolesForUpdateCol1.ToList());
}
/// <summary>
/// Validates role inheritance for named roles: when a named role is not configured for an entity
/// but 'authenticated' is configured (or inherited from 'anonymous'), the named role inherits
/// the permissions of 'authenticated'.
/// Inheritance chain: named-role → authenticated → anonymous → none.
/// </summary>
[TestMethod]
public void TestNamedRoleInheritsFromAuthenticatedRole()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationResolver.ROLE_AUTHENTICATED,
operation: EntityActionOperation.Read);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Named role (TEST_ROLE = "Writer") is not configured but should inherit from 'authenticated'.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Read));
// Named role should NOT have operations that 'authenticated' does not have.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create));
}
/// <summary>
/// Validates that when neither 'anonymous' nor 'authenticated' is configured for an entity,
/// a named role that is also not configured inherits nothing (rule 5).
/// </summary>
[TestMethod]
public void TestNamedRoleInheritsNothingWhenNoSystemRolesDefined()
{
const string CONFIGURED_NAMED_ROLE = "admin";
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: CONFIGURED_NAMED_ROLE,
operation: EntityActionOperation.Create);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// The configured 'admin' role has Create permission.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
CONFIGURED_NAMED_ROLE,
EntityActionOperation.Create));
// TEST_ROLE ("Writer") is not configured and neither anonymous nor authenticated is configured,
// so it inherits nothing (rule 5).
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create));
}
/// <summary>
/// Validates that a named role inherits from 'authenticated', which in turn has already
/// inherited from 'anonymous' at setup time (when anonymous is configured but authenticated is not).
/// Inheritance chain: named-role → authenticated (inherited from anonymous).
/// </summary>
[TestMethod]
public void TestNamedRoleInheritsFromAnonymousViaAuthenticated()
{
// Only 'anonymous' is configured; 'authenticated' will inherit from it at setup time.
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationResolver.ROLE_ANONYMOUS,
operation: EntityActionOperation.Read);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Named role ("Writer") should inherit Read via: Writer → authenticated → anonymous.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Read));
// Named role should NOT have operations that anonymous does not have.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create));
}
/// <summary>
/// SECURITY: Validates that a named role that IS explicitly configured for an entity
/// does NOT inherit broader permissions from 'authenticated'. This prevents privilege
/// escalation when a config author intentionally restricts a named role's permissions.
/// Example: authenticated has CRUD, but 'restricted' is configured with only Read.
/// A request from 'restricted' for Create must be denied.
/// </summary>
[TestMethod]
public void TestExplicitlyConfiguredNamedRoleDoesNotInheritBroaderPermissions()
{
// 'authenticated' gets Read + Create; 'restricted' gets only Read.
EntityActionFields fieldsForRole = new(
Include: new HashSet<string> { "col1" },
Exclude: new());
EntityAction readAction = new(
Action: EntityActionOperation.Read,
Fields: fieldsForRole,
Policy: new(null, null));
EntityAction createAction = new(
Action: EntityActionOperation.Create,
Fields: fieldsForRole,
Policy: new(null, null));
EntityPermission authenticatedPermission = new(
Role: AuthorizationResolver.ROLE_AUTHENTICATED,
Actions: new[] { readAction, createAction });
EntityPermission restrictedPermission = new(
Role: "restricted",
Actions: new[] { readAction });
EntityPermission[] permissions = new[] { authenticatedPermission, restrictedPermission };
RuntimeConfig runtimeConfig = BuildTestRuntimeConfig(permissions, AuthorizationHelpers.TEST_ENTITY);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// 'restricted' is explicitly configured, so it should use its OWN permissions only.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
"restricted",
EntityActionOperation.Read),
"Explicitly configured 'restricted' role should have Read permission.");
// CRITICAL: 'restricted' must NOT inherit Create from 'authenticated'.
Assert.IsFalse(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
"restricted",
EntityActionOperation.Create),
"Explicitly configured 'restricted' role must NOT inherit Create from 'authenticated'.");
// Verify 'authenticated' still has Create (sanity check).
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationResolver.ROLE_AUTHENTICATED,
EntityActionOperation.Create),
"'authenticated' should retain its own Create permission.");
}
/// <summary>
/// Tests for IsRoleAllowedByDirective covering the full role inheritance chain at the
/// GraphQL @authorize directive gate.
/// Unconfigured named roles inherit: named-role inherits from 'authenticated'; 'authenticated'
/// inherits from 'anonymous'. Any unconfigured non-anonymous role is allowed when 'authenticated'
/// OR 'anonymous' is listed in the directive roles.
/// Explicitly configured named roles use strict matching only to prevent privilege escalation.
/// </summary>
[DataTestMethod]
[DataRow(null, "admin", false, DisplayName = "Null directive roles — deny all")]
[DataRow(new string[0], "admin", false, DisplayName = "Empty directive roles — deny all")]
[DataRow(new[] { "admin" }, "admin", true, DisplayName = "Explicit match — allowed")]
[DataRow(new[] { "admin" }, "other", false, DisplayName = "No match, no system roles — denied")]
[DataRow(new[] { "authenticated" }, "Writer", true, DisplayName = "Unconfigured named role inherits from authenticated")]
[DataRow(new[] { "authenticated" }, "anonymous", false, DisplayName = "anonymous does NOT inherit from authenticated")]
[DataRow(new[] { "anonymous" }, "authenticated", true, DisplayName = "authenticated inherits from anonymous")]
[DataRow(new[] { "anonymous" }, "Writer", true, DisplayName = "Unconfigured named role inherits from anonymous via authenticated")]
[DataRow(new[] { "anonymous" }, "anonymous", true, DisplayName = "anonymous explicit match when anonymous listed")]
[DataRow(new[] { "ANONYMOUS" }, "authenticated", true, DisplayName = "Case-insensitive: ANONYMOUS directive allows authenticated")]
[DataRow(new[] { "AUTHENTICATED" }, "Writer", true, DisplayName = "Case-insensitive: AUTHENTICATED directive allows unconfigured named role")]
public void TestIsRoleAllowedByDirective(string[]? directiveRoles, string clientRole, bool expected)
{
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(
AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationResolver.ROLE_ANONYMOUS,
operation: EntityActionOperation.Read));
bool actual = authZResolver.IsRoleAllowedByDirective(clientRole, directiveRoles);
Assert.AreEqual(expected, actual);
}
/// <summary>
/// Tests that explicitly configured named roles use strict directive matching.
/// A role that is explicitly configured for any entity (even with restricted permissions)
/// will NOT inherit from system roles at the @authorize directive level, preventing
/// unintended access to operations outside its configured permission scope.
/// </summary>
[DataTestMethod]
[DataRow(new[] { "authenticated" }, "Writer", false, DisplayName = "Configured role does NOT inherit from authenticated when not in directive")]
[DataRow(new[] { "anonymous" }, "Writer", false, DisplayName = "Configured role does NOT inherit from anonymous when not in directive")]
[DataRow(new[] { "Writer" }, "Writer", true, DisplayName = "Configured role passes when explicitly listed in directive")]
[DataRow(new[] { "anonymous", "authenticated" }, "Writer", false, DisplayName = "Configured role denied even when both system roles in directive")]
public void TestIsRoleAllowedByDirective_ExplicitlyConfiguredRoleUsesStrictMatching(
string[] directiveRoles, string clientRole, bool expected)
{
// Configure 'Writer' as an explicitly restricted role (read-only) on the test entity.
// Even though 'authenticated' or 'anonymous' may be in the directive, 'Writer' should
// not inherit because it is an explicitly configured role with its own permission scope.
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(
AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: "Writer",
operation: EntityActionOperation.Read));
bool actual = authZResolver.IsRoleAllowedByDirective(clientRole, directiveRoles);
Assert.AreEqual(expected, actual);
}
/// <summary>
/// Test to validate the AreRoleAndOperationDefinedForEntity method for the case insensitivity of roleName.
/// For eg. The role Writer is equivalent to wrIter, wRITer, WRITER etc.
/// </summary>
/// <param name="configRole">The role configured on the entity.</param>
/// <param name="operation">The operation configured for the configRole.</param>
/// <param name="roleNameToCheck">The roleName which is to be checked for the permission.</param>
[DataTestMethod]
[DataRow("Writer", EntityActionOperation.Create, "wRiTeR", DisplayName = "role wRiTeR checked against Writer")]
[DataRow("Reader", EntityActionOperation.Read, "READER", DisplayName = "role READER checked against Reader")]
[DataRow("Writer", EntityActionOperation.Create, "WrIter", DisplayName = "role WrIter checked against Writer")]
public void AreRoleAndOperationDefinedForEntityTestForDifferentlyCasedRole(
string configRole,
EntityActionOperation operation,
string roleNameToCheck
)
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: configRole,
operation: operation);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Assert that the roleName is case insensitive.
Assert.IsTrue(authZResolver.AreRoleAndOperationDefinedForEntity(AuthorizationHelpers.TEST_ENTITY, roleNameToCheck, operation));
}
#endregion
#region Column Tests
/// <summary>
/// Tests the authorization stage: Columns defined for operation
/// Columns are allowed for role
/// Columns are not allowed for role
/// Wildcard included and/or excluded columns handling
/// and assumes request validation has already occurred
/// </summary>
[TestMethod("Explicit include columns with no exclusion")]
public void ExplicitIncludeColumn()
{
HashSet<string> includedColumns = new() { "col1", "col2", "col3" };
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedCols: includedColumns
);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
includedColumns));
// Not allow column.
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
new List<string> { "col4" }));
// Mix of allow and not allow. Should result in not allow.
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
new List<string> { "col3", "col4" }));
// Column does not exist
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
new List<string> { "col5", "col6" }));
}
/// <summary>
/// Test to validate that for wildcard operation, the authorization stage for column check
/// would pass if the operation is one among create, read, update, delete and the columns are accessible.
/// Similarly if the column is in accessible, then we should not have access.
/// </summary>
[TestMethod("Explicit include and exclude columns")]
public void ExplicitIncludeAndExcludeColumns()
{
HashSet<string> includeColumns = new() { "col1", "col2" };
HashSet<string> excludeColumns = new() { "col3" };
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedCols: includeColumns,
excludedCols: excludeColumns
);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
includeColumns));
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
excludeColumns));
// Not exist column in the inclusion or exclusion list
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
new List<string> { "col4" }));
// Mix of allow and not allow. Should result in not allow.
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
EntityActionOperation.Create,
new List<string> { "col1", "col3" }));
}
/// <summary>
/// Exclusion has precedence over inclusion. So for this test case,
/// col1 will be excluded even if it is in the inclusion list.
/// </summary>
[TestMethod("Same column in exclusion and inclusion list")]
public void ColumnExclusionWithSameColumnInclusion()
{
HashSet<string> includedColumns = new() { "col1", "col2" };
HashSet<string> excludedColumns = new() { "col1", "col4" };
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedCols: includedColumns,
excludedCols: excludedColumns
);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Col2 should be included.
//
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
new List<string> { "col2" }));
// Col1 should NOT to included since it is in exclusion list.
//
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
new List<string> { "col1" }));
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
excludedColumns));
}
/// <summary>
/// Test that wildcard inclusion will include all the columns in the table.
/// </summary>
[TestMethod("Wildcard included columns")]
public void WildcardColumnInclusion()
{
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedCols: new HashSet<string> { AuthorizationResolver.WILDCARD }
);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
List<string> includedColumns = new() { "col1", "col2", "col3", "col4" };
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedColumns));
}
/// <summary>
/// Test that wildcard inclusion will include all column except column specify in exclusion.
/// Exclusion has priority over inclusion.
/// </summary>
[TestMethod("Wildcard include columns with some column exclusion")]
public void WildcardColumnInclusionWithExplicitExclusion()
{
List<string> includedColumns = new() { "col1", "col2" };
HashSet<string> excludedColumns = new() { "col3", "col4" };
RuntimeConfig runtimeConfig = AuthorizationHelpers.InitRuntimeConfig(
entityName: AuthorizationHelpers.TEST_ENTITY,
roleName: AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedCols: new HashSet<string> { AuthorizationResolver.WILDCARD },
excludedCols: excludedColumns
);
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
includedColumns));
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
excludedColumns));
}
/// <summary>
/// Reproduces the real-world Book entity scenario: a single role with MULTIPLE actions
/// (read with no field restriction, create/update excluding a column, delete with no
/// field restriction) all defined in one EntityPermission.Actions array - unlike
/// AuthorizationHelpers.InitRuntimeConfig which only ever builds a single action per role.
/// </summary>
[TestMethod("Multiple actions per role - column exclusion on create/update only")]
public void MultipleActionsPerRole_ColumnExclusionOnCreateAndUpdate()
{
EntityActionFields createUpdateFields = new(Exclude: new() { "col3" });
EntityAction readAction = new(Action: EntityActionOperation.Read, Fields: null, Policy: new(null, null));
EntityAction createAction = new(Action: EntityActionOperation.Create, Fields: createUpdateFields, Policy: new(null, null));
EntityAction updateAction = new(Action: EntityActionOperation.Update, Fields: createUpdateFields, Policy: new(null, null));
EntityAction deleteAction = new(Action: EntityActionOperation.Delete, Fields: null, Policy: new(null, null));
EntityPermission permissionForEntity = new(
Role: AuthorizationHelpers.TEST_ROLE,
Actions: new EntityAction[] { readAction, createAction, updateAction, deleteAction });
Entity sampleEntity = new(
Source: new EntitySource(AuthorizationHelpers.TEST_ENTITY, EntitySourceType.Table, null, null),
Fields: null,
Rest: new(Array.Empty<SupportedHttpVerb>()),
GraphQL: new(AuthorizationHelpers.TEST_ENTITY, AuthorizationHelpers.TEST_ENTITY),
Permissions: new EntityPermission[] { permissionForEntity },
Relationships: null,
Mappings: null);
RuntimeConfig runtimeConfig = new(
Schema: "UnitTestSchema",
DataSource: new DataSource(DatabaseType.MSSQL, "", new()),
Runtime: new(
Rest: new(),
GraphQL: new(),
Mcp: new(),
Host: new(
Cors: null,
Authentication: new("AppService", null))),
Entities: new(new Dictionary<string, Entity> { { AuthorizationHelpers.TEST_ENTITY, sampleEntity } }));
AuthorizationResolver authZResolver = AuthorizationHelpers.InitAuthorizationResolver(runtimeConfig);
// Read should allow all columns (no exclusion for read).
Assert.IsTrue(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Read,
new List<string> { "col1", "col3" }),
"Read should allow all columns since no fields are excluded for the read action.");
// Create should DENY col3 since it is excluded for create.
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
new List<string> { "col1", "col3" }),
"Create should deny col3 since it is excluded for the create action.");
// Update should DENY col3 since it is excluded for update.
Assert.IsFalse(authZResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Update,
new List<string> { "col1", "col3" }),
"Update should deny col3 since it is excluded for the update action.");
// Round-trip the config through JSON serialization/deserialization (as happens when DAB
// loads a real config file from disk) to rule out any bug specific to the JSON converters
// (e.g. shared/aliased Fields.Exclude HashSet instances across sibling actions).
string json = runtimeConfig.ToJson();
Assert.IsTrue(
RuntimeConfigLoader.TryParseConfig(json, out RuntimeConfig? roundTrippedConfig),
"Round-tripped config should parse successfully.");
AuthorizationResolver roundTrippedResolver = AuthorizationHelpers.InitAuthorizationResolver(roundTrippedConfig!);
Assert.IsTrue(roundTrippedResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Read,
new List<string> { "col1", "col3" }),
"After round-trip, read should still allow all columns.");
Assert.IsFalse(roundTrippedResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,
operation: EntityActionOperation.Create,
new List<string> { "col1", "col3" }),
"After round-trip, create should still deny excluded col3.");
Assert.IsFalse(roundTrippedResolver.AreColumnsAllowedForOperation(
AuthorizationHelpers.TEST_ENTITY,
AuthorizationHelpers.TEST_ROLE,